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