-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.version2.js
94 lines (75 loc) · 2.31 KB
/
server.version2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');
const MAX_TXT_URL = 'https://raw.githubusercontent.com/LovelyO0Sam/pgm-api/main/max.txt';
const MIN_TXT_URL = 'https://raw.githubusercontent.com/LovelyO0Sam/pgm-api/main/min.txt';
const ID_TXT_URL = 'https://raw.githubusercontent.com/LovelyO0Sam/pgm-api/main/id';
const MAX_TXT_PATH = path.join(__dirname, 'api-max.txt');
const MIN_TXT_PATH = path.join(__dirname, 'api-min.txt');
const ID_TXT_PATH = path.join(__dirname, 'api-id.txt');
const PORT = 443;
let maxLines = [];
let minLines = [];
let idLines = [];
fs.unlink(MAX_TXT_PATH, () => {});
fs.unlink(MIN_TXT_PATH, () => {});
fs.unlink(ID_TXT_PATH, () => {});
function downloadFiles() {
downloadTxtFile(MAX_TXT_URL, MAX_TXT_PATH, (lines) => {
maxLines = lines;
});
downloadTxtFile(MIN_TXT_URL, MIN_TXT_PATH, (lines) => {
minLines = lines;
});
downloadTxtFile(ID_TXT_URL, ID_TXT_PATH, (lines) => {
idLines = lines;
});
}
function downloadTxtFile(url, filePath, callback) {
const file = fs.createWriteStream(filePath);
const request = https.get(url, (res) => {
res.pipe(file);
file.on('finish', () => {
file.close(() => {
const lines = fs.readFileSync(filePath).toString().split('\n');
callback(lines);
});
});
}).on('error', (err) => {
console.error(err);
});
}
downloadFiles();
setInterval(downloadFiles, 24 * 60 * 60 * 1000);
const server = http.createServer((req, res) => {
const reqUrl = url.parse(req.url, true);
if (reqUrl.pathname !== '/api-min' && reqUrl.pathname !== '/api-max') {
res.statusCode = 404;
res.end();
return;
}
if (!reqUrl.query.id) {
res.statusCode = 404;
res.end();
return;
}
if (idLines.includes(reqUrl.query.id)) {
res.statusCode = 404;
res.end();
return;
}
let lines;
if (reqUrl.pathname === '/api-min') {
lines = minLines;
} else {
lines = maxLines;
}
const line = lines[Math.floor(Math.random() * lines.length)];
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(line);
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});