1
0
Fork 0
peertube/server/lib/webtorrentProcess.js

93 lines
2.2 KiB
JavaScript
Raw Normal View History

'use strict'
2016-02-06 10:22:39 -05:00
2016-02-07 07:12:32 -05:00
var WebTorrent = require('webtorrent')
var ipc = require('node-ipc')
2016-02-06 10:22:39 -05:00
2016-02-07 07:12:32 -05:00
function webtorrent (args) {
if (args.length !== 3) {
throw new Error('Wrong arguments number: ' + args.length + '/3')
}
2016-02-06 10:22:39 -05:00
var host = args[1]
var port = args[2]
var nodeKey = 'webtorrentnode' + port
var processKey = 'webtorrentprocess' + port
2016-02-06 10:22:39 -05:00
ipc.config.silent = true
ipc.config.id = processKey
2016-02-06 10:22:39 -05:00
if (host === 'client' && port === '1') global.WEBTORRENT_ANNOUNCE = []
else global.WEBTORRENT_ANNOUNCE = 'ws://' + host + ':' + port + '/tracker/socket'
var wt = new WebTorrent({ dht: false })
2016-02-06 10:22:39 -05:00
function seed (data) {
var args = data.args
var path = args.path
var _id = data._id
2016-02-06 10:22:39 -05:00
wt.seed(path, { announceList: '' }, function (torrent) {
var to_send = {
magnetUri: torrent.magnetURI
}
2016-02-06 10:22:39 -05:00
ipc.of[nodeKey].emit(nodeKey + '.seedDone.' + _id, to_send)
})
}
2016-02-06 10:22:39 -05:00
function add (data) {
var args = data.args
var magnetUri = args.magnetUri
var _id = data._id
2016-02-06 10:22:39 -05:00
wt.add(magnetUri, function (torrent) {
var to_send = {
files: []
}
2016-02-06 10:22:39 -05:00
torrent.files.forEach(function (file) {
to_send.files.push({ path: file.path })
2016-02-06 10:22:39 -05:00
})
ipc.of[nodeKey].emit(nodeKey + '.addDone.' + _id, to_send)
})
}
2016-02-06 10:22:39 -05:00
function remove (data) {
var args = data.args
var magnetUri = args.magnetUri
var _id = data._id
2016-02-06 10:22:39 -05:00
try {
wt.remove(magnetUri, callback)
} catch (err) {
console.log('Cannot remove the torrent from WebTorrent.')
return callback(null)
}
function callback () {
var to_send = {}
ipc.of[nodeKey].emit(nodeKey + '.removeDone.' + _id, to_send)
2016-02-06 10:22:39 -05:00
}
}
2016-02-06 10:22:39 -05:00
console.log('Configuration: ' + host + ':' + port)
console.log('Connecting to IPC...')
2016-02-06 10:22:39 -05:00
ipc.connectTo(nodeKey, function () {
ipc.of[nodeKey].on(processKey + '.seed', seed)
ipc.of[nodeKey].on(processKey + '.add', add)
ipc.of[nodeKey].on(processKey + '.remove', remove)
2016-02-06 10:22:39 -05:00
ipc.of[nodeKey].emit(processKey + '.ready')
console.log('Ready.')
})
2016-02-06 10:22:39 -05:00
process.on('uncaughtException', function (e) {
ipc.of[nodeKey].emit(processKey + '.exception', { exception: e })
})
}
2016-02-06 10:22:39 -05:00
// ---------------------------------------------------------------------------
2016-02-06 10:22:39 -05:00
module.exports = webtorrent