-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
executable file
·92 lines (76 loc) · 2.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const argv = require('yargs').argv
const fs = require('fs')
const os = require('os')
const path = require('path')
let help = `Webtorrent Web UI
-h displays this message
-t sets the torrent folder - default ~/.torrent_folder
-d sets the download folder - default ~/Downloads
-v gives a console status msg/sec - default disabled
-l sets the host to listen to - default 127.0.0.1
-p sets the port to listen to - default 9081
-a sets the DHT listen UDP port - default 7000
-o sets the Torrent listen TCP port - default 7000`
function die (msg, code) {
console.log(msg)
process.exit(code)
}
module.exports = function start (hybrid) {
if (hybrid) {
help = help + '\r\nThis hybrid version runs webtorrent-hybrid'
}
if (argv.h || argv.help) { return die(help, 0) }
let tFolder = argv.t || (os.homedir() + '/.torrent_folder/')
let dlFolder = argv.d || (os.homedir() + '/Downloads/')
const host = !argv.l ? ['127.0.0.1'] : typeof argv.l === 'string' ? [argv.l] : argv.l
const port = argv.p ? parseInt(argv.p) : 9081
const verb = !!argv.v
const dhtPort = argv.a ? parseInt(argv.a) : 7000
const torrentPort = argv.o ? parseInt(argv.o) : 7000
// Check input
tFolder = tFolder.endsWith('/') ? tFolder : tFolder + '/'
dlFolder = dlFolder.endsWith('/') ? dlFolder : dlFolder + '/'
if (!fs.existsSync(tFolder)) {
try {
fs.mkdirSync(tFolder)
} catch (e) { die("Can't create torrent folder", 1) }
}
if (!fs.existsSync(dlFolder)) {
try {
fs.mkdirSync(dlFolder)
} catch (e) { die("Can't create download folder", 1) }
}
const bodyParser = require('body-parser')
const ecstatic = require('ecstatic')
const express = require('express')
const app = express()
const parser = require('./lib/parser')
const HandlerWebtorrent = require('./lib/handlerWebtorrent')
let handler
app.all('*', (req, res, next) => {
if (host.includes(req.hostname)) {
next()
} else {
res.writeHead(403, { 'Connection': 'close' })
res.end()
}
})
app.get(/files/, ecstatic({
root: dlFolder,
baseDir: '/files',
showdir: true
}))
app.get(/\//, express.static(path.join(__dirname, '/static')))
var jsonParser = bodyParser.json()
app.post('/rpc/', jsonParser, (req, res, next) => {
res.json(parser(req.body, handler))
})
app.listen(port, host, (err) => {
if (err) die(err, 1)
console.log(`Starting at ${host.map(t => '\r\n http://' + t + ':' + port)}`)
handler = new HandlerWebtorrent(tFolder, dlFolder, verb, hybrid, dhtPort, torrentPort)
})
process.on('SIGTERM', function () {
handler.destroy(() => process.exit(0))
})
}