]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - lib/webtorrentProcess.js
Remove useless anonymous functions of files
[github/Chocobozzz/PeerTube.git] / lib / webtorrentProcess.js
1 'use strict'
2
3 function webtorrent (args) {
4 var WebTorrent = require('webtorrent')
5 var ipc = require('node-ipc')
6
7 if (args.length !== 3) {
8 console.log('Wrong arguments number: ' + args.length + '/3')
9 process.exit(-1)
10 }
11
12 var host = args[1]
13 var port = args[2]
14 var nodeKey = 'webtorrentnode' + port
15 var processKey = 'webtorrentprocess' + port
16
17 ipc.config.silent = true
18 ipc.config.id = processKey
19
20 if (host === 'client' && port === '1') global.WEBTORRENT_ANNOUNCE = []
21 else global.WEBTORRENT_ANNOUNCE = 'ws://' + host + ':' + port + '/tracker/socket'
22 var wt = new WebTorrent({ dht: false })
23
24 function seed (data) {
25 var args = data.args
26 var path = args.path
27 var _id = data._id
28
29 wt.seed(path, { announceList: '' }, function (torrent) {
30 var to_send = {
31 magnetUri: torrent.magnetURI
32 }
33
34 ipc.of[nodeKey].emit(nodeKey + '.seedDone.' + _id, to_send)
35 })
36 }
37
38 function add (data) {
39 var args = data.args
40 var magnetUri = args.magnetUri
41 var _id = data._id
42
43 wt.add(magnetUri, function (torrent) {
44 var to_send = {
45 files: []
46 }
47
48 torrent.files.forEach(function (file) {
49 to_send.files.push({ path: file.path })
50 })
51
52 ipc.of[nodeKey].emit(nodeKey + '.addDone.' + _id, to_send)
53 })
54 }
55
56 function remove (data) {
57 var args = data.args
58 var magnetUri = args.magnetUri
59 var _id = data._id
60
61 try {
62 wt.remove(magnetUri, callback)
63 } catch (err) {
64 console.log('Cannot remove the torrent from WebTorrent.')
65 return callback(null)
66 }
67
68 function callback () {
69 var to_send = {}
70 ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, to_send)
71 }
72 }
73
74 console.log('Configuration: ' + host + ':' + port)
75 console.log('Connecting to IPC...')
76
77 ipc.connectTo(nodeKey, function () {
78 ipc.of[nodeKey].on(processKey + '.seed', seed)
79 ipc.of[nodeKey].on(processKey + '.add', add)
80 ipc.of[nodeKey].on(processKey + '.remove', remove)
81
82 ipc.of[nodeKey].emit(processKey + '.ready')
83 console.log('Ready.')
84 })
85
86 process.on('uncaughtException', function (e) {
87 ipc.of[nodeKey].emit(processKey + '.exception', { exception: e })
88 })
89 }
90
91 // ---------------------------------------------------------------------------
92
93 module.exports = webtorrent