-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
145 lines (133 loc) · 5.53 KB
/
Copy pathserver.js
File metadata and controls
145 lines (133 loc) · 5.53 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
const http = require('http');
const fs = require('fs');
const path = require('path');
const CONFIG_DIR = '/config';
const VERSION_PATH = path.join(__dirname, 'VERSION');
const STATIC_DIR = __dirname;
const PORT = 80;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
};
http.createServer((req, res) => {
// ── POST /api/save/:type ────────────────────────────────
if (req.method === 'POST' && req.url.startsWith('/api/save/')) {
const type = req.url.split('/').pop();
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
if (!['config', 'history', 'bookmark'].includes(type)) {
throw new Error('Invalid type');
}
const data = JSON.parse(body);
const filePath = path.join(CONFIG_DIR, `${type}.json`);
if (!fs.existsSync(CONFIG_DIR)) fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end('{"ok":true}');
} catch (e) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message }));
}
});
return;
}
// ── GET /api/version ─────────────────────────────────────
if (req.method === 'GET' && req.url === '/api/version') {
const version = fs.existsSync(VERSION_PATH)
? fs.readFileSync(VERSION_PATH, 'utf8').trim()
: 'unknown';
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ version }));
return;
}
// ── GET /config/ ──────────────────────────────
if (req.method === 'GET' && req.url.startsWith('/config/')) {
const filename = req.url.split('/').pop();
const filePath = path.join(CONFIG_DIR, filename);
if (fs.existsSync(filePath)) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(fs.readFileSync(filePath));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
if (filename === 'history.json' || filename === 'bookmark.json') {
res.end('[]');
} else {
res.end('{}');
}
}
return;
}
// ── POST /api/torrent-proxy ──────────────────────────────
if (req.method === 'POST' && req.url === '/api/torrent-proxy') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const payload = JSON.parse(body);
const targetUrl = payload.url;
if (!targetUrl) throw new Error('Missing target URL');
const urlObj = new URL(targetUrl);
const isHttps = urlObj.protocol === 'https:';
const lib = isHttps ? require('https') : require('http');
const options = {
hostname: urlObj.hostname,
port: urlObj.port || (isHttps ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: payload.method || 'POST',
headers: {
'Content-Type': payload.contentType || 'application/json',
...(payload.headers || {})
}
};
const proxyBody = typeof payload.body === 'string' ? payload.body : '';
if (proxyBody) options.headers['Content-Length'] = Buffer.byteLength(proxyBody);
const proxyReq = lib.request(options, (proxyRes) => {
let responseBody = '';
proxyRes.on('data', chunk => responseBody += chunk);
proxyRes.on('end', () => {
const setCookies = proxyRes.headers['set-cookie'];
const xTransmission = proxyRes.headers['x-transmission-session-id'];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: proxyRes.statusCode,
headers: {
...(setCookies ? { 'x-proxy-set-cookie': JSON.stringify(setCookies) } : {}),
...(xTransmission ? { 'x-transmission-session-id': xTransmission } : {})
},
body: responseBody
}));
});
});
proxyReq.on('error', (err) => {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
});
if (proxyBody) proxyReq.write(proxyBody);
proxyReq.end();
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: e.message }));
}
});
return;
}
// ── Static files ─────────────────────────────────────────
let urlPath = req.url.split('?')[0]; // strip query string
if (urlPath === '/') urlPath = '/index.html';
const filePath = path.join(STATIC_DIR, urlPath);
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
res.end(fs.readFileSync(filePath));
} else {
res.writeHead(404);
res.end('Not found');
}
}).listen(PORT, () => console.log(`Tracker Tools running on port ${PORT}`));