PeerTube/server/lib/webtorrentProcess.js

93 lines
2.3 KiB
JavaScript
Raw Normal View History

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