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