]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - lib/webtorrentProcess.js
Require on the top of the files
[github/Chocobozzz/PeerTube.git] / lib / webtorrentProcess.js
CommitLineData
9f10b292 1'use strict'
c5a8be2b 2
9f10b292
C
3function webtorrent (args) {
4 var WebTorrent = require('webtorrent')
5 var ipc = require('node-ipc')
c5a8be2b 6
9f10b292
C
7 if (args.length !== 3) {
8 console.log('Wrong arguments number: ' + args.length + '/3')
9 process.exit(-1)
10 }
c5a8be2b 11
9f10b292
C
12 var host = args[1]
13 var port = args[2]
14 var nodeKey = 'webtorrentnode' + port
15 var processKey = 'webtorrentprocess' + port
c5a8be2b 16
9f10b292
C
17 ipc.config.silent = true
18 ipc.config.id = processKey
c5a8be2b 19
9f10b292
C
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 })
c5a8be2b 23
9f10b292
C
24 function seed (data) {
25 var args = data.args
26 var path = args.path
27 var _id = data._id
c5a8be2b 28
9f10b292
C
29 wt.seed(path, { announceList: '' }, function (torrent) {
30 var to_send = {
31 magnetUri: torrent.magnetURI
32 }
c5a8be2b 33
9f10b292
C
34 ipc.of[nodeKey].emit(nodeKey + '.seedDone.' + _id, to_send)
35 })
36 }
c5a8be2b 37
9f10b292
C
38 function add (data) {
39 var args = data.args
40 var magnetUri = args.magnetUri
41 var _id = data._id
c5a8be2b 42
9f10b292
C
43 wt.add(magnetUri, function (torrent) {
44 var to_send = {
45 files: []
46 }
c5a8be2b 47
9f10b292
C
48 torrent.files.forEach(function (file) {
49 to_send.files.push({ path: file.path })
c5a8be2b 50 })
c5a8be2b 51
9f10b292
C
52 ipc.of[nodeKey].emit(nodeKey + '.addDone.' + _id, to_send)
53 })
54 }
c5a8be2b 55
9f10b292
C
56 function remove (data) {
57 var args = data.args
58 var magnetUri = args.magnetUri
59 var _id = data._id
c5a8be2b 60
9f10b292
C
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)
c5a8be2b 71 }
9f10b292 72 }
c5a8be2b 73
9f10b292
C
74 console.log('Configuration: ' + host + ':' + port)
75 console.log('Connecting to IPC...')
c5a8be2b 76
9f10b292
C
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)
c5a8be2b 81
9f10b292
C
82 ipc.of[nodeKey].emit(processKey + '.ready')
83 console.log('Ready.')
84 })
c5a8be2b 85
9f10b292
C
86 process.on('uncaughtException', function (e) {
87 ipc.of[nodeKey].emit(processKey + '.exception', { exception: e })
88 })
89}
c5a8be2b 90
9f10b292 91// ---------------------------------------------------------------------------
c5a8be2b 92
9f10b292 93module.exports = webtorrent