-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
413 lines (383 loc) · 11.3 KB
/
index.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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
var express = require('express');
var webtorrent = require('webtorrent');
var bodyParser = require('body-parser');
var parseTorrent = require('parse-torrent');
var path = require('path');
var http = require('http');
var fs = require('fs');
var multipart = require('connect-multiparty');
var app = express();
var ffmpeg = require('fluent-ffmpeg');
var port = 9111;
var client = new webtorrent();
// Allow Cross-Origin requests
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
var getLargestFile = function (torrent) {
var file;
for(i = 0; i < torrent.files.length; i++) {
if (!file || file.length < torrent.files[i].length) {
file = torrent.files[i];
}
}
return file;
};
var getVideoParams = function (quality) {
var params;
for(i = 0; i < videoPresets.length; i++) {
if (videoPresets[i].quality == quality) {
params = videoPresets[i];
}
}
return params;
};
var buildMagnetURI = function(infoHash) {
return 'magnet:?xt=urn:btih:' + infoHash + '&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969';
};
var myParseTorrent = function(uri, callback) {
if(typeof uri == 'string' && (uri.substring(0, 7) == 'http://' || uri.substring(0, 8) == 'https://')) {
parseTorrent.remote(uri, function(err, data) {
if(err) { callback(false); }
callback(data.infoHash.toLowerCase());
});
} else {
var parsed = parseTorrent(uri);
callback(parsed.infoHash.toLowerCase());
}
};
var removeTorrent = function(ih) {
var m = buildMagnetURI(ih);
client.remove(m);
delete store.uris[ih];
delete store.torrents[ih];
delete store.lastAccess[ih];
};
var time = function() {
return Math.floor(new Date() / 1000);
};
var videoPresets = [
{
quality: '720p',
video: {
codec: 'libvpx',
bitrate: '4096k'
},
audio: {
codec: 'libvorbis',
bitrate: '256k'
},
picture: {
resolution: '1280x?'
}
},
{
quality: '480p',
video: {
codec: 'libvpx',
bitrate: '3072k'
},
audio: {
codec: 'libvorbis',
bitrate: '192k'
},
picture: {
resolution: '854x?'
}
},
{
quality: '360p',
video: {
codec: 'libvpx',
bitrate: '2048k'
},
audio: {
codec: 'libvorbis',
bitrate: '128k'
},
picture: {
resolution: '640x?'
}
},
{
quality: '240p',
video: {
codec: 'libvpx',
bitrate: '1024k'
},
audio: {
codec: 'libvorbis',
bitrate: '96k'
},
picture: {
resolution: '426x?'
}
},
{
quality: '144p',
video: {
codec: 'libvpx',
bitrate: '512k'
},
audio: {
codec: 'libvorbis',
bitrate: '64k'
},
picture: {
resolution: '256x?'
}
}
];
var store = {};
store.uris = {};
store.lastAccess = {};
store.torrents = {};
setInterval(function() {
var _time = time();
Object.keys(store.lastAccess).forEach(function(key) {
var accessTime = store.lastAccess[key];
var delay = 60 * 30;
if(_time - accessTime > delay) {
console.log('Autoremoving ' + key + ' after ' + delay + ' seconds!');
removeTorrent(key);
}
});
}, 1000);
app.post('/api/parse-torrent', function(req, res) {
if(typeof req.body.uri == 'undefined' || req.body.uri == '') {
res.status(500).send('Missing URI parameter!'); return;
}
myParseTorrent(req.body.uri, function(infoHash) {
if(!infoHash) {
return res.status(500).send('Error. ');
}
res.status(200).send({ infoHash: infoHash });
});
});
app.get('/api/video-presets', function(req, res) {
var presets = [];
videoPresets.forEach(function(preset) {
presets.push(preset.quality);
});
res.status(200).send(presets);
});
app.get('/api/torrent/:infoHash/keep-alive', function(req, res) {
if(typeof req.params.infoHash == 'undefined' || req.params.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.params.infoHash;
if(typeof store.torrents[infoHash] == 'undefined') {
res.status(404).send('Torrent not found!');
return;
}
var _time = time();
store.lastAccess[infoHash] = _time;
res.status(200).send(_time.toString());
});
app.post('/api/upload-torrent', multipart(), function (req, res) {
var file = req.files && req.files.file;
if(!file) {
res.status(500).send('Missing file parameter!'); return;
}
myParseTorrent(fs.readFileSync(file.path), function(infoHash) {
if(!infoHash) {
return res.status(500).send('Error. ');
}
res.status(200).send({ infoHash: infoHash });
});
});
app.post('/api/add-torrent', function(req, res) {
if(typeof req.body.infoHash == 'undefined' || req.body.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.body.infoHash;
var uri = buildMagnetURI(infoHash);
if(typeof store.torrents[infoHash] != 'undefined') {
res.status(200).send('Added torrent!');
store.lastAccess[infoHash] = time();
return;
}
try {
store.torrents[infoHash] = client.add(uri, function (torrent) {
store.uris[infoHash] = uri;
store.lastAccess[infoHash] = time();
res.status(200).send('Added torrent!');
});
} catch (err) {
res.status(500).send('Error: ' + err.toString());
}
});
app.get('/api/torrent/:infoHash/files', function(req, res) {
if(typeof req.params.infoHash == 'undefined' || req.params.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.params.infoHash;
var uri = buildMagnetURI(infoHash);
if(typeof store.torrents[infoHash] == 'undefined') {
res.status(404).send('Torrent not found!');
return;
}
try {
var torrent = client.get(uri);
var files = [];
for(i = 0; i < torrent.files.length; i++) {
var file = torrent.files[i];
files.push({
index: i,
name: file.name,
size: file.length
});
}
res.status(200).send({ title: torrent.name, files: files });
} catch (err) {
res.status(500).send('Error: ' + err.toString());
}
});
app.get('/api/torrent/:infoHash/download/:index', function(req, res) {
if(typeof req.params.infoHash == 'undefined' || req.params.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.params.infoHash;
var index = req.params.index;
var uri = buildMagnetURI(infoHash);
if(typeof store.torrents[infoHash] == 'undefined') {
res.status(404).send('Torrent not found!');
return;
}
try {
var torrent = client.get(uri);
if(typeof torrent.files[index] == 'undefined') {
res.status(404).send('File not found!');
return;
}
var file = torrent.files[index];
var total = file.length;
if(typeof req.headers.range != 'undefined') {
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total - 1;
var chunksize = (end - start) + 1;
} else {
var start = 0; var end = total; var chunksize = total;
}
var stream = file.createReadStream({start: start, end: end});
res.writeHead(206, {
'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Disposition': 'attachment; filename="' + file.name + '"',
'Content-Type': 'application/octet-stream'
});
stream.pipe(res);
} catch (err) {
res.status(500).send('Error: ' + err.toString());
}
});
app.get('/api/torrent/:infoHash/stream/:index/metadata.json', function(req, res) {
if(typeof req.params.infoHash == 'undefined' || req.params.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.params.infoHash;
var index = req.params.index;
var quality = req.params.quality;
var uri = buildMagnetURI(infoHash);
if(typeof store.torrents[infoHash] == 'undefined') {
res.status(404).send('Torrent not found!');
return;
}
try {
var torrent = client.get(uri);
if(typeof torrent.files[index] == 'undefined') {
res.status(404).send('File not found!');
return;
}
var command = ffmpeg('http://localhost:' + port + '/api/torrent/' + infoHash + '/download/' + index)
.ffprobe(0, function(err, data) {
res.send(data);
});
} catch (err) {
res.status(500).send('Error: ' + err.toString());
}
});
app.get('/api/torrent/:infoHash/stream/:index/:quality.webm', function(req, res) {
if(typeof req.params.infoHash == 'undefined' || req.params.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.params.infoHash;
var index = req.params.index;
var quality = req.params.quality;
var uri = buildMagnetURI(infoHash);
if(typeof store.torrents[infoHash] == 'undefined') {
res.status(404).send('Torrent not found!');
return;
}
var params = getVideoParams(quality);
if(!params) {
res.status(404).send('Video quality not available!');
return;
}
var start = false;
if(typeof req.query.start != 'undefined' && req.query.start != null) {
start = parseFloat(req.query.start);
}
try {
var torrent = client.get(uri);
if(typeof torrent.files[index] == 'undefined') {
res.status(404).send('File not found!');
return;
}
res.contentType('webm');
var command = ffmpeg('http://localhost:' + port + '/api/torrent/' + infoHash + '/download/' + index)
.format('webm')
.size(params.picture.resolution)
.videoCodec(params.video.codec)
.videoBitrate(params.video.bitrate)
.audioCodec(params.audio.codec)
.audioBitrate(params.audio.bitrate)
.audioChannels(2)
.on('end', function() {
console.log('file has been converted succesfully');
})
.outputOptions([
'-deadline realtime',
'-error-resilient 1'
])
.on('error', function(err) {
console.log('an error happened: ' + err.message);
});
if(start) {
command.seekInput(start);
}
command.pipe(res, { end: true });
} catch (err) {
res.status(500).send('Error: ' + err.toString());
}
});
app.post('/api/torrent/:infoHash/delete', function(req, res) {
if(typeof req.params.infoHash == 'undefined' || req.params.infoHash == '') {
res.status(500).send('Missing infoHash parameter!'); return;
}
var infoHash = req.params.infoHash;
if(typeof store.torrents[infoHash] == 'undefined') {
res.status(404).send('Torrent not found!');
return;
}
try {
removeTorrent(infoHash);
res.status(200).send('Removed torrent. ');
} catch (err) {
res.status(500).send('Error: ' + err.toString());
}
});
var server = http.createServer(app);
server.listen(port, function() {
console.log('Listening on http://127.0.0.1:' + port);
});