3 const WebTorrent = require('webtorrent')
4 const ipc = require('node-ipc')
6 function webtorrent (args) {
7 if (args.length !== 3) {
8 throw new Error('Wrong arguments number: ' + args.length + '/3')
13 const nodeKey = 'webtorrentnode' + port
14 const processKey = 'webtorrentprocess' + port
16 ipc.config.silent = true
17 ipc.config.id = processKey
19 if (host === 'client' && port === '1') global.WEBTORRENT_ANNOUNCE = []
20 else global.WEBTORRENT_ANNOUNCE = 'ws://' + host + ':' + port + '/tracker/socket'
21 const wt = new WebTorrent({ dht: false })
23 function seed (data) {
24 const args = data.args
25 const path = args.path
28 wt.seed(path, { announceList: '' }, function (torrent) {
30 magnetUri: torrent.magnetURI
33 ipc.of[nodeKey].emit(nodeKey + '.seedDone.' + _id, to_send)
38 const args = data.args
39 const magnetUri = args.magnetUri
42 wt.add(magnetUri, function (torrent) {
47 torrent.files.forEach(function (file) {
48 to_send.files.push({ path: file.path })
51 ipc.of[nodeKey].emit(nodeKey + '.addDone.' + _id, to_send)
55 function remove (data) {
56 const args = data.args
57 const magnetUri = args.magnetUri
61 wt.remove(magnetUri, callback)
63 console.log('Cannot remove the torrent from WebTorrent.')
67 function callback () {
69 ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, to_send)
73 console.log('Configuration: ' + host + ':' + port)
74 console.log('Connecting to IPC...')
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)
81 ipc.of[nodeKey].emit(processKey + '.ready')
85 process.on('uncaughtException', function (e) {
86 ipc.of[nodeKey].emit(processKey + '.exception', { exception: e.toString() })
90 // ---------------------------------------------------------------------------
92 module.exports = webtorrent