forked from webtorrent/webtorrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
219 lines (188 loc) · 5.88 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// TODO: move vlc/airplay/etc. functionality from cmd.js to the module
module.exports = WebTorrent
var Client = require('bittorrent-client')
var concat = require('concat-stream')
var debug = require('debug')('webtorrent')
var extend = require('extend.js')
var fs = require('fs')
var FSStorage = require('./lib/fs-storage')
var http = require('http')
var inherits = require('inherits')
var mime = require('mime')
var parallel = require('run-parallel')
var parseTorrent = require('parse-torrent')
var pump = require('pump')
var rangeParser = require('range-parser')
var url = require('url')
inherits(WebTorrent, Client)
function WebTorrent (opts) {
var self = this
opts = opts || {}
debug('new webtorrent')
if (opts.blocklist) opts.blocklist = parseBlocklist(opts.blocklist)
Client.call(self, opts)
self.listening = false
if (opts.list) return
if (opts.port !== false) {
// start http server
self.server = http.createServer()
self.server.on('connection', function (socket) {
socket.setTimeout(36000000)
})
self.server.on('request', self._onRequest.bind(self))
self.server.listen(opts.port)
self.server.once('listening', function () {
self.listening = true
self.emit('listening')
})
}
self.on('torrent', self._onTorrent.bind(self))
}
/**
* Add a new torrent to the client. `torrentId` can be one of:
*
* - magnet uri (utf8 string)
* - torrent file (buffer)
* - info hash (hex string or buffer)
* - parsed torrent (from parse-torrent module)
* - http/https url to a .torrent file (string)
* - filesystem path to a .torrent file (string)
*
* @override
* @param {string|Buffer|Object} torrentId torrent (choose from above list)
* @param {Object} opts optional torrent-specific options
* @param {function=} ontorrent called when the torrent is ready (has metadata)
*/
WebTorrent.prototype.add = function (torrentId, opts, ontorrent) {
var self = this
if (typeof opts === 'function') {
ontorrent = opts
opts = {}
}
debug('add %s', torrentId)
opts = extend({
storage: FSStorage
}, opts)
// TODO: fix this to work with multiple torrents
self.index = opts.index
// Called once we have a torrentId that bittorrent-client can handle
function onTorrentId (torrentId) {
var torrent = Client.prototype.add.call(self, torrentId, opts, ontorrent)
process.nextTick(function () {
self.emit('add', torrent)
})
}
var parsed = parseTorrent(torrentId)
if (parsed && parsed.infoHash) {
// magnet uri, info hash, torrent file, or parsed torrent can be handled by bittorrent-client
process.nextTick(function () {
onTorrentId(parsed)
})
} else if (/^https?:/.test(torrentId)) {
// http or https url to torrent file
http.get(torrentId, function (res) {
res.pipe(concat(function (torrent) {
onTorrentId(torrent)
}))
}).on('error', function (err) {
self.emit('error', new Error('Error downloading torrent. ' + err.message))
})
} else {
// assume it's a filesystem path
fs.readFile(torrentId, function (err, torrent) {
if (err) {
self.emit('error', new Error('Invalid torrent. Need magnet uri, info hash, ' +
'torrent file, http url, or filesystem path.'))
} else {
onTorrentId(torrent)
}
})
}
return self
}
/**
* Destroy the client, including all torrents and connections to peers.
*
* @override
* @param {function} cb
*/
WebTorrent.prototype.destroy = function (cb) {
var self = this
debug('destroy')
var tasks = [
Client.prototype.destroy.bind(self)
]
if (self.server) {
tasks.push(function (cb) {
try {
self.server.close(cb)
} catch (err) {
// ignore error, server was already closed or not listening
cb(null)
}
})
}
parallel(tasks, cb)
return self
}
WebTorrent.prototype._onTorrent = function (torrent) {
var self = this
debug('on torrent')
// if no index specified, use largest file
if (typeof torrent.index !== 'number') {
var largestFile = torrent.files.reduce(function (a, b) {
return a.length > b.length ? a : b
})
torrent.index = torrent.files.indexOf(largestFile)
}
torrent.files[torrent.index].select()
// TODO: this won't work with multiple torrents
self.index = torrent.index
self.torrent = torrent
}
WebTorrent.prototype._onRequest = function (req, res) {
var self = this
debug('onRequest')
var u = url.parse(req.url)
if (u.pathname === '/favicon.ico') return res.end()
if (u.pathname === '/') u.pathname = '/' + self.index
var i = Number(u.pathname.slice(1))
if (isNaN(i) || i >= self.torrent.files.length) {
res.statusCode = 404
return res.end()
}
if (self.torrent) onTorrent(self.torrent)
else self.once('torrent', onTorrent)
function onTorrent (torrent) {
var file = torrent.files[i]
res.setHeader('Accept-Ranges', 'bytes')
res.setHeader('Content-Type', mime.lookup(file.name))
res.statusCode = 206
var range
if (req.headers.range) {
// no support for multi-range reqs
range = rangeParser(file.length, req.headers.range)[0]
debug('range %s', JSON.stringify(range))
res.setHeader(
'Content-Range',
'bytes ' + range.start + '-' + range.end + '/' + file.length
)
res.setHeader('Content-Length', range.end - range.start + 1)
} else {
res.setHeader('Content-Length', file.length)
}
if (req.method === 'HEAD') res.end()
pump(file.createReadStream(range), res)
}
}
// TODO: support gzipped files
var blocklistRe = /^\s*[^#].*?\s*:\s*([a-f0-9.:]+?)\s*-\s*([a-f0-9.:]+?)\s*$/
function parseBlocklist (filename) {
var blocklistData = fs.readFileSync(filename, 'utf8')
var blocklist = []
blocklistData.split('\n').forEach(function (line) {
var match = blocklistRe.exec(line)
if (match) blocklist.push({ start: match[1], end: match[2] })
})
return blocklist
}