87 lines
2.7 KiB
JavaScript
87 lines
2.7 KiB
JavaScript
const http = require('http');
|
|
const https = require('https');
|
|
const url = require('url');
|
|
|
|
const PORT = 3000;
|
|
const MAX_RETRIES = 3;
|
|
const INITIAL_TIMEOUT = 3000; // 初始超时时间设置为3秒
|
|
const BACKOFF_FACTOR = 2; // 指数退避因子
|
|
|
|
const server = http.createServer((req, res) => {
|
|
const reqUrl = url.parse(req.url, true);
|
|
const id = reqUrl.pathname.split('/').pop();
|
|
|
|
// 检查 ID 是否存在且格式正确
|
|
if (!id || isNaN(id)) {
|
|
res.writeHead(400, { 'Content-Type': 'text/plain' });
|
|
res.end('Invalid ID');
|
|
return;
|
|
}
|
|
|
|
const targetUrl = `https://xxxclub.to/torrents/details/${id}`;
|
|
console.log(`Target URL: ${targetUrl}`);
|
|
|
|
let responseSent = false;
|
|
|
|
const makeRequest = (retryCount = 0, timeout = INITIAL_TIMEOUT) => {
|
|
if (responseSent) return;
|
|
|
|
const options = url.parse(targetUrl);
|
|
options.method = 'GET';
|
|
options.timeout = timeout;
|
|
|
|
const proxyReq = https.request(options, (proxyRes) => {
|
|
let data = '';
|
|
|
|
proxyRes.on('data', (chunk) => {
|
|
data += chunk;
|
|
});
|
|
|
|
proxyRes.on('end', () => {
|
|
if (!responseSent) {
|
|
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
|
res.end(data);
|
|
responseSent = true;
|
|
}
|
|
});
|
|
});
|
|
|
|
proxyReq.on('timeout', () => {
|
|
console.error('Request timed out.');
|
|
proxyReq.abort();
|
|
|
|
if (retryCount < MAX_RETRIES) {
|
|
const newTimeout = timeout * BACKOFF_FACTOR;
|
|
console.log(`Retrying... (${retryCount + 1}/${MAX_RETRIES}) with timeout ${newTimeout}ms`);
|
|
makeRequest(retryCount + 1, newTimeout);
|
|
} else if (!responseSent) {
|
|
res.writeHead(504, { 'Content-Type': 'text/plain' });
|
|
res.end('Request timed out.');
|
|
responseSent = true;
|
|
}
|
|
});
|
|
|
|
proxyReq.on('error', (e) => {
|
|
console.error(`Problem with request: ${e.message}`);
|
|
|
|
if (retryCount < MAX_RETRIES) {
|
|
const newTimeout = timeout * BACKOFF_FACTOR;
|
|
console.log(`Retrying... (${retryCount + 1}/${MAX_RETRIES}) with timeout ${newTimeout}ms`);
|
|
makeRequest(retryCount + 1, newTimeout);
|
|
} else if (!responseSent) {
|
|
res.writeHead(500, { 'Content-Type': 'text/plain' });
|
|
res.end('Error occurred while fetching the data.');
|
|
responseSent = true;
|
|
}
|
|
});
|
|
|
|
proxyReq.end();
|
|
};
|
|
|
|
makeRequest();
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Proxy server is running on http://localhost:${PORT}`);
|
|
});
|