-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
706 lines (596 loc) · 20.7 KB
/
app.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
var YTS = require('yts.to');
var http = require('http');
var https = require('https');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var yts = new YTS('https://yts.ph/api/v2/');
var optimist = require('optimist')
var rc = require('rc')
var clivas = require('clivas')
var numeral = require('numeral')
var os = require('os')
var address = require('network-address')
var proc = require('child_process')
var peerflix = require('peerflix')
var keypress = require('keypress')
var openUrl = require('open')
var inquirer = require('inquirer')
var parsetorrent = require('parse-torrent')
var path = require('path')
const PirateBay = require('thepiratebay')
var moviesAvailable;
var searchWords;
const commandLineArgs = require('command-line-args')
/**const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
**/
prompt.start();
const optionDefinitions = [
{ name: 'magnet', alias: 'v', type: Boolean }
]
const options = commandLineArgs(optionDefinitions)
console.log(JSON.stringify(options));
var prMagnet = [
{
name: 'magnet',
warning: 'Enter Magnet: '
},
];
var prMovieName = [
{
name: 'movieName',
validator: /^[ A-Za-z0-9_@./#&+-]*$/,
warning: 'Enter the name of the film to find.'
},
];
var prChooseFilm = [
{
name: 'chooseFilm',
validator: /^[0-99]+$/,
warning: 'Enter the number of the film'
},
];
setTimeout(function(){ console.log('\033[2J');},500);
setTimeout(promptMovieName, 1000);
function promptMovieName() {
if(options.magnet){
prompt.get(prMagnet, function (err, result) {
if (err) { return onErr(err); }
filename = result.magnet;
//console.log(' Film: ' + nameFormated);
parsetorrent.remote(filename, function (err, parsedtorrent) {
if (err) {
console.error(err.message)
process.exit(1)
}
ontorrent(parsedtorrent)
})
});
function onErr(err) {
console.log(err);
return 1;
}
}else{
prompt.get(prMovieName, function (err, result) {
if (err) { return onErr(err); }
searchWords = result.movieName;
//console.log(' Film: ' + nameFormated);
searchPirateBay(searchWords);
});
function onErr(err) {
console.log(err);
return 1;
}
}
}
function searchPirateBay(tvShowName){
// do the GET request
PirateBay.search(tvShowName, {
category: 'all'
})
.then(results => parsePirateBay(results))
.catch(err => searchFilm(tvShowName))
}
function parsePirateBay(results){
if(results.length == 0){
var nameFormated = searchWords.replace(' ','&')
searchFilm(nameFormated)
}else{
//console.log(results)
var index = 0;
moviesAvailable = results;
moviesAvailable.forEach(function(movie){
//console.log(movie);
index ++;
console.log(index+" ::: "+movie.name);
});
console.log("0 <<< Back");
prompt.get(prChooseFilm, function (err, result) {
if (err) { return onErr(err); }
if(result.chooseFilm == 0){
promptMovieName();
}else{
console.log('Choose film to play in VLC: ' + result.chooseFilm);
playPirateBay(moviesAvailable[result.chooseFilm-1]);
}
});
}
}
function playPirateBay(movie){
console.log(movie);
//'magnet:?xt=urn:btih:'+movie.torrents[0].hash
filename = movie.magnetLink;
argv.vlc = true
parsetorrent.remote(filename, function (err, parsedtorrent) {
if (err) {
console.error(err.message)
process.exit(1)
}
ontorrent(parsedtorrent)
})
}
function searchFilm(movieName){
yts.findMovie(movieName, {with_rt_ratings: true}).then( function(movies) {
// console.log(movies);
if(movies.data != null ){
var index = 0;
moviesAvailable = movies.data.movies;
moviesAvailable.forEach(function(movie){
//console.log(movie);
index ++;
console.log(index+" ::: "+movie.title_long);
});
console.log("0 <<< Back");
prompt.get(prChooseFilm, function (err, result) {
if (err) { return onErr(err); }
if(result.chooseFilm == 0){
promptMovieName();
}else{
console.log('Choose film to play in VLC: ' + result.chooseFilm);
playMovie(moviesAvailable[result.chooseFilm-1]);
}
});
function onErr(err) {
console.log("XXXXXX::"+err);
return 1;
}
}else{
console.error("Movie not found. Try again.");
promptMovieName();
}
});
}
var filename ="";
function playMovie(movie){
//'magnet:?xt=urn:btih:'+movie.torrents[0].hash
filename = "magnet:?xt=urn:btih:"+movie.torrents[0].hash
argv.vlc = true
parsetorrent.remote(filename, function (err, parsedtorrent) {
if (err) {
console.error(err.message)
process.exit(1)
}
ontorrent(parsedtorrent)
})
}
process.title = 'peerflix'
var argv = rc('peerflix', {}, optimist
.usage('Usage: $0 magnet-link-or-torrent [options]')
.alias('c', 'connections').describe('c', 'max connected peers').default('c', os.cpus().length > 1 ? 100 : 30)
.alias('p', 'port').describe('p', 'change the http port').default('p', 8888)
.alias('i', 'index').describe('i', 'changed streamed file (index)')
.alias('l', 'list').describe('l', 'list available files with corresponding index').boolean('l')
.alias('t', 'subtitles').describe('t', 'load subtitles file')
.alias('q', 'quiet').describe('q', 'be quiet').boolean('v')
.alias('v', 'vlc').describe('v', 'autoplay in vlc*').boolean('v')
.alias('s', 'airplay').describe('s', 'autoplay via AirPlay').boolean('a')
.alias('m', 'mplayer').describe('m', 'autoplay in mplayer*').boolean('m')
.alias('g', 'smplayer').describe('g', 'autoplay in smplayer*').boolean('g')
.describe('mpchc', 'autoplay in MPC-HC player*').boolean('boolean')
.describe('potplayer', 'autoplay in Potplayer*').boolean('boolean')
.alias('k', 'mpv').describe('k', 'autoplay in mpv*').boolean('k')
.alias('o', 'omx').describe('o', 'autoplay in omx**').boolean('o')
.alias('w', 'webplay').describe('w', 'autoplay in webplay').boolean('w')
.alias('j', 'jack').describe('j', 'autoplay in omx** using the audio jack').boolean('j')
.alias('f', 'path').describe('f', 'change buffer file path')
.alias('b', 'blocklist').describe('b', 'use the specified blocklist')
.alias('n', 'no-quit').describe('n', 'do not quit peerflix on vlc exit').boolean('n')
.alias('a', 'all').describe('a', 'select all files in the torrent').boolean('a')
.alias('r', 'remove').describe('r', 'remove files on exit').boolean('r')
.alias('h', 'hostname').describe('h', 'host name or IP to bind the server to')
.alias('e', 'peer').describe('e', 'add peer by ip:port')
.alias('x', 'peer-port').describe('x', 'set peer listening port')
.alias('d', 'not-on-top').describe('d', 'do not float video on top').boolean('d')
.describe('on-downloaded', 'script to call when file is 100% downloaded')
.describe('on-listening', 'script to call when server goes live')
.describe('version', 'prints current version').boolean('boolean')
.argv)
if (argv.version) {
console.error(require('./package').version)
process.exit(0)
}
var onTop = !argv.d
var VLC_ARGS = '-q' + (onTop ? ' --video-on-top' : '') + ' --play-and-exit'
var OMX_EXEC = argv.jack ? 'omxplayer -r -o local ' : 'omxplayer -r -o hdmi '
var MPLAYER_EXEC = 'mplayer ' + (onTop ? '-ontop' : '') + ' -really-quiet -noidx -loop 0 '
var SMPLAYER_EXEC = 'smplayer ' + (onTop ? '-ontop' : '')
var MPV_EXEC = 'mpv ' + (onTop ? '--ontop' : '') + ' --really-quiet --loop=no '
var MPC_HC_ARGS = '/play'
var POTPLAYER_ARGS = ''
var enc = function (s) {
return /\s/.test(s) ? JSON.stringify(s) : s
}
if (argv.t) {
VLC_ARGS += ' --sub-file=' + (process.platform === 'win32') ? argv.t : enc(argv.t)
OMX_EXEC += ' --subtitles ' + enc(argv.t)
MPLAYER_EXEC += ' -sub ' + enc(argv.t)
SMPLAYER_EXEC += ' -sub ' + enc(argv.t)
MPV_EXEC += ' --sub-file=' + enc(argv.t)
POTPLAYER_ARGS += ' ' + enc(argv.t)
}
if (argv._.length > 1) {
var _args = argv._
_args.shift()
var playerArgs = _args.join(' ')
VLC_ARGS += ' ' + playerArgs
OMX_EXEC += ' ' + playerArgs
MPLAYER_EXEC += ' ' + playerArgs
SMPLAYER_EXEC += ' ' + playerArgs
MPV_EXEC += ' ' + playerArgs
MPC_HC_ARGS += ' ' + playerArgs
POTPLAYER_ARGS += ' ' + playerArgs
}
var ontorrent = function (torrent) {
if (argv['peer-port']) argv.peerPort = Number(argv['peer-port'])
var engine = peerflix(torrent, argv)
var hotswaps = 0
var verified = 0
var invalid = 0
var downloadedPercentage = 0
engine.on('verify', function () {
verified++
downloadedPercentage = Math.floor(verified / engine.torrent.pieces.length * 100)
})
engine.on('invalid-piece', function () {
invalid++
})
var bytes = function (num) {
return numeral(num).format('0.0b')
}
if (argv.list) {
var interactive = process.stdout.isTTY && process.stdin.isTTY && !!process.stdin.setRawMode
var onready = function () {
if (interactive) {
inquirer.prompt([{
type: 'list',
name: 'file',
message: 'Choose one file',
choices: engine.files.map(function (file, i) {
return {
name: file.name + ' : ' + bytes(file.length),
value: i
} })}], function (answers) {
argv.index = answers.file
delete argv.list
ontorrent(torrent)
})
} else {
engine.files.forEach(function (file, i, files) {
clivas.line('{3+bold:' + i + '} : {magenta:' + file.name + '} : {blue:' + bytes(file.length) + '}')
})
process.exit(0)
}
}
if (engine.torrent) onready()
else engine.on('ready', onready)
return
}
engine.on('hotswap', function () {
hotswaps++
})
var started = Date.now()
var wires = engine.swarm.wires
var swarm = engine.swarm
var active = function (wire) {
return !wire.peerChoking
}
var peers = [].concat(argv.peer || [])
peers.forEach(function (peer) {
engine.connect(peer)
})
if (argv['on-downloaded']) {
var downloaded = false
engine.on('uninterested', function () {
if (!downloaded) proc.exec(argv['on-downloaded'])
downloaded = true
})
}
engine.server.on('listening', function () {
var host = argv.hostname || address()
var href = 'http://' + host + ':' + engine.server.address().port + '/'
var localHref = 'http://localhost:' + engine.server.address().port + '/'
var filename = engine.server.index.name.split('/').pop().replace(/\{|\}/g, '')
var filelength = engine.server.index.length
var player = null
var paused = false
var timePaused = 0
var pausedAt = null
if (argv.all) {
filename = engine.torrent.name
filelength = engine.torrent.length
href += '.m3u'
localHref += '.m3u'
}
var registry, key
if (argv.vlc && process.platform === 'win32') {
player = 'vlc'
registry = require('windows-no-runnable').registry
if (process.arch === 'x64') {
try {
key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
if (!key['InstallDir']) {
throw new Error('no install dir')
}
} catch (e) {
try {
key = registry('HKLM/Software/VideoLAN/VLC')
} catch (err) {}
}
} else {
try {
key = registry('HKLM/Software/VideoLAN/VLC')
} catch (err) {
try {
key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
} catch (e) {}
}
}
if (key) {
var vlcPath = key['InstallDir'].value + path.sep + 'vlc'
VLC_ARGS = VLC_ARGS.split(' ')
VLC_ARGS.unshift(localHref)
proc.execFile(vlcPath, VLC_ARGS)
}
} else if (argv.mpchc && process.platform === 'win32') {
player = 'mph-hc'
registry = require('windows-no-runnable').registry
key = registry('HKCU/Software/MPC-HC/MPC-HC')
var exePath = key['ExePath']
proc.exec('"' + exePath + '" "' + localHref + '" ' + MPC_HC_ARGS)
} else if (argv.potplayer && process.platform === 'win32') {
player = 'potplayer'
registry = require('windows-no-runnable').registry
if (process.arch === 'x64') {
key = registry('HKCU/Software/DAUM/PotPlayer64')
}
if (!key || !key['ProgramPath']) {
key = registry('HKCU/Software/DAUM/PotPlayer')
}
if (key['ProgramPath']) {
var potplayerPath = key['ProgramPath'].value
proc.exec('"' + potplayerPath + '" "' + localHref + '" ' + POTPLAYER_ARGS)
}
} else {
if (argv.vlc) {
player = 'vlc'
var root = '/Applications/VLC.app/Contents/MacOS/VLC'
var home = (process.env.HOME || '') + root
var vlc = proc.exec('vlc ' + VLC_ARGS + ' ' + localHref + ' || ' + root + ' ' + VLC_ARGS + ' ' + localHref + ' || ' + home + ' ' + VLC_ARGS + ' ' + localHref, function (error, stdout, stderror) {
if (error) {
process.exit(0)
}
})
vlc.on('exit', function () {
if (!argv.n && argv.quit !== false) process.exit(0)
})
}
}
if (argv.omx) {
player = 'omx'
var omx = proc.exec(OMX_EXEC + ' ' + localHref)
omx.on('exit', function () {
if (!argv.n && argv.quit !== false) process.exit(0)
})
}
if (argv.mplayer) {
player = 'mplayer'
var mplayer = proc.exec(MPLAYER_EXEC + ' ' + localHref)
mplayer.on('exit', function () {
if (!argv.n && argv.quit !== false) process.exit(0)
})
}
if (argv.smplayer) {
player = 'smplayer'
var smplayer = proc.exec(SMPLAYER_EXEC + ' ' + localHref)
smplayer.on('exit', function () {
if (!argv.n && argv.quit !== false) process.exit(0)
})
}
if (argv.mpv) {
player = 'mpv'
var mpv = proc.exec(MPV_EXEC + ' ' + localHref)
mpv.on('exit', function () {
if (!argv.n && argv.quit !== false) process.exit(0)
})
}
if (argv.webplay) {
player = 'webplay'
openUrl('https://85d514b3e548d934d8ff7c45a54732e65a3162fe.htmlb.in/#' + localHref)
}
if (argv.airplay) {
var list = require('airplayer')()
list.once('update', function (player) {
list.destroy()
player.play(href)
})
}
if (argv['on-listening']) proc.exec(argv['on-listening'] + ' ' + href)
if (argv.quiet) return console.log('server is listening on ' + href)
process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing
var interactive = !player && process.stdin.isTTY && !!process.stdin.setRawMode
if (interactive) {
keypress(process.stdin)
process.stdin.on('keypress', function (ch, key) {
if (!key) return
if (key.name === 'c' && key.ctrl === true) return process.kill(process.pid, 'SIGINT')
if (key.name === 'l' && key.ctrl === true) {
var command = 'xdg-open'
if (process.platform === 'win32') { command = 'explorer' }
if (process.platform === 'darwin') { command = 'open' }
return proc.exec(command + ' ' + engine.path)
}
if (key.name !== 'space') return
if (player) return
if (paused === false) {
if (!argv.all) {
engine.server.index.deselect()
} else {
engine.files.forEach(function (file) {
file.deselect()
})
}
paused = true
pausedAt = Date.now()
draw()
return
}
if (!argv.all) {
engine.server.index.select()
} else {
engine.files.forEach(function (file) {
file.select()
})
}
paused = false
timePaused += Date.now() - pausedAt
draw()
})
process.stdin.setRawMode(true)
}
var draw = function () {
var unchoked = engine.swarm.wires.filter(active)
var timeCurrentPause = 0
if (paused === true) {
timeCurrentPause = Date.now() - pausedAt
}
var runtime = Math.floor((Date.now() - started - timePaused - timeCurrentPause) / 1000)
var linesremaining = clivas.height
var peerslisted = 0
clivas.clear()
if (argv.airplay) clivas.line('{green:streaming to} {bold:apple-tv} {green:using airplay}')
else clivas.line('{green:open} {bold:' + (player || 'vlc') + '} {green:and enter} {bold:' + href + '} {green:as the network address}')
clivas.line('')
clivas.line('{yellow:info} {green:streaming} {bold:' + filename + ' (' + bytes(filelength) + ')} {green:-} {bold:' + bytes(swarm.downloadSpeed()) + '/s} {green:from} {bold:' + unchoked.length + '/' + wires.length + '} {green:peers} ')
clivas.line('{yellow:info} {green:path} {cyan:' + engine.path + '}')
clivas.line('{yellow:info} {green:downloaded} {bold:' + bytes(swarm.downloaded) + '} (' + downloadedPercentage + '%) {green:and uploaded }{bold:' + bytes(swarm.uploaded) + '} {green:in }{bold:' + runtime + 's} {green:with} {bold:' + hotswaps + '} {green:hotswaps} ')
clivas.line('{yellow:info} {green:verified} {bold:' + verified + '} {green:pieces and received} {bold:' + invalid + '} {green:invalid pieces}')
clivas.line('{yellow:info} {green:peer queue size is} {bold:' + swarm.queued + '}')
clivas.line('{80:}')
if (interactive) {
var openLoc = ' or CTRL+L to open download location}'
if (paused) clivas.line('{yellow:PAUSED} {green:Press SPACE to continue download' + openLoc)
else clivas.line('{50+green:Press SPACE to pause download' + openLoc)
}
clivas.line('')
linesremaining -= 9
wires.every(function (wire) {
var tags = []
if (wire.peerChoking) tags.push('choked')
clivas.line('{25+magenta:' + wire.peerAddress + '} {10:' + bytes(wire.downloaded) + '} {10 + cyan:' + bytes(wire.downloadSpeed()) + '/s} {15 + grey:' + tags.join(', ') + '} ')
peerslisted++
return linesremaining - peerslisted > 4
})
linesremaining -= peerslisted
if (wires.length > peerslisted) {
clivas.line('{80:}')
clivas.line('... and ' + (wires.length - peerslisted) + ' more ')
}
clivas.line('{80:}')
clivas.flush()
}
setInterval(draw, 500)
draw()
})
engine.server.once('error', function () {
engine.server.listen(0, argv.hostname)
})
var onmagnet = function () {
clivas.clear()
clivas.line('{green:fetching torrent metadata from} {bold:' + engine.swarm.wires.length + '} {green:peers}')
}
if (typeof torrent === 'string' && torrent.indexOf('magnet:') === 0 && !argv.quiet) {
onmagnet()
engine.swarm.on('wire', onmagnet)
}
engine.on('ready', function () {
engine.swarm.removeListener('wire', onmagnet)
if (!argv.all) return
engine.files.forEach(function (file) {
file.select()
})
})
var onexit = function () {
// we're doing some heavy lifting so it can take some time to exit... let's
// better output a status message so the user knows we're working on it :)
clivas.line('')
clivas.line('{yellow:info} {green:peerflix is exiting...}')
}
if (argv.remove) {
var remove = function () {
onexit()
engine.remove(function () {
process.exit()
})
}
process.on('SIGINT', remove)
process.on('SIGTERM', remove)
} else {
process.on('SIGINT', function () {
onexit()
process.exit()
})
}
}