-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
270 lines (236 loc) · 7.13 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
module.exports = Client
var debug = require('debug')('bittorrent-client')
var DHT = require('bittorrent-dht/client')
var EventEmitter = require('events').EventEmitter
var extend = require('extend.js')
var hat = require('hat')
var inherits = require('inherits')
var magnet = require('magnet-uri')
var once = require('once')
var parallel = require('run-parallel')
var parseTorrent = require('parse-torrent')
var portfinder = require('portfinder')
var speedometer = require('speedometer')
var Storage = require('./lib/storage')
var Torrent = require('./lib/torrent')
portfinder.basePort = Math.floor(Math.random() * 64000) + 1025 // pick port >1024
inherits(Client, EventEmitter)
/**
* Create a new `bittorrent-client` instance. Available options described in the README.
* @param {Object} opts
*/
function Client (opts) {
var self = this
if (!(self instanceof Client)) return new Client(opts)
EventEmitter.call(self)
// default options
opts = extend({
dht: true,
trackers: true
}, opts)
// TODO: these ids should be consistent between restarts!
self.peerId = opts.peerId || new Buffer('-WW0001-' + hat(48), 'utf8')
self.nodeId = opts.nodeId || new Buffer(hat(160), 'hex')
// TODO: DHT port should be consistent between restarts
self.dhtPort = opts.dhtPort
self.torrentPort = opts.torrentPort
self.trackersEnabled = opts.trackers
self.ready = false
self.torrents = []
self.blocklist = opts.blocklist || []
self.downloadSpeed = speedometer()
self.uploadSpeed = speedometer()
var tasks = []
if (!self.torrentPort) {
// TODO: move portfinder stuff into bittorrent-swarm, like how
// it works with bittorrent-dht
tasks.push(function (cb) {
portfinder.getPort(function (err, port) {
self.torrentPort = port
cb(err)
})
})
}
if (opts.dht) {
tasks.push(function (cb) {
self.dht = new DHT(extend({ nodeId: self.nodeId }, opts.dht))
self.dht.on('peer', self._onDHTPeer.bind(self))
self.dht.on('listening', function (port) {
self.dhtPort = port
})
self.dht.on('ready', function () {
cb()
})
self.dht.listen(self.dhtPort)
})
}
parallel(tasks, function (err) {
if (err) return self.emit('error', err)
self.ready = true
self.emit('ready')
})
}
Client.Storage = Storage
/**
* Aggregate seed ratio for all torrents in the client.
* @type {number}
*/
Object.defineProperty(Client.prototype, 'ratio', {
get: function () {
var self = this
var uploaded = self.torrents.reduce(function (total, torrent) {
return total + torrent.uploaded
}, 0)
var downloaded = self.torrents.reduce(function (total, torrent) {
return total + torrent.downloaded
}, 0)
if (downloaded === 0) return 0
return uploaded / downloaded
}
})
/**
* Return the torrent with the given `torrentId`. Easier than searching through the
* `client.torrents` array by hand for the torrent you want.
* @param {string|Buffer} torrentId
* @return {Torrent}
*/
Client.prototype.get = function (torrentId) {
var self = this
var infoHash = Client.toInfoHash(torrentId)
for (var i = 0, len = self.torrents.length; i < len; i++) {
var torrent = self.torrents[i]
if (torrent.infoHash === infoHash) {
return torrent
}
}
return null
}
/**
* Add a new torrent to the client. `torrentId` can be a magnet uri (utf8 string),
* torrent file (buffer), or info hash (hex string or buffer).
*
* @param {string|Buffer|Object} torrentId magnet uri, torrent file, info hash, or parsed torrent
* @param {Object} opts optional torrent-specific options
* @param {function=} cb called when the torrent is ready and has metadata
*/
Client.prototype.add = function (torrentId, opts, cb) {
var self = this
if (!self.ready) return self.once('ready', self.add.bind(self, torrentId, opts, cb))
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (typeof cb !== 'function') cb = function () {}
cb = once(cb)
var torrent = new Torrent(torrentId, extend({
blocklist: self.blocklist,
dht: !!self.dht,
dhtPort: self.dhtPort,
peerId: self.peerId,
torrentPort: self.torrentPort,
trackers: self.trackersEnabled
}, opts))
self.torrents.push(torrent)
torrent.swarm.on('download', function (downloaded) {
self.downloadSpeed(downloaded)
})
torrent.swarm.on('upload', function (uploaded) {
self.uploadSpeed(uploaded)
})
process.nextTick(function () {
self.emit('addTorrent', torrent)
})
torrent.on('listening', function (port) {
debug('Swarm listening on port ' + port)
self.emit('listening', torrent)
// TODO: Add the torrent to the public DHT so peers know to find us
})
torrent.on('error', function (err) {
cb(err)
self.emit('error', err)
})
torrent.on('metadata', function () {
// Call callback and emit 'torrent' when a torrent is ready to be used
cb(null, torrent)
self.emit('torrent', torrent)
})
if (self.dht) {
self.dht.lookup(torrent.infoHash, function (err) {
self.dht.announce(torrent.infoHash, self.torrentPort, function () {
torrent.emit('announce')
})
})
}
}
/**
* Remove a torrent from the client. Destroy all connections to peers and delete all
* saved file data. Optional callback is called when file data has been removed.
* @param {string|Buffer} torrentId
* @param {function} cb
*/
Client.prototype.remove = function (torrentId, cb) {
var self = this
var torrent = self.get(torrentId)
if (!torrent) {
throw new Error('No torrent with id ' + torrentId)
}
self.torrents.splice(self.torrents.indexOf(torrent), 1)
torrent.destroy(cb)
}
/**
* Destroy the client, including all torrents and connections to peers.
* @param {function} cb
*/
Client.prototype.destroy = function (cb) {
var self = this
if (self.dht) {
self.dht.destroy()
}
var tasks = self.torrents.map(function (torrent) {
return function (cb) {
self.remove(torrent.infoHash, cb)
}
})
parallel(tasks, cb)
}
Client.prototype._onDHTPeer = function (addr, infoHash) {
var self = this
var torrent = self.get(infoHash)
torrent.addPeer(addr)
}
//
// HELPER METHODS
//
/**
* Given a magnet uri, torrent file, info hash, or parsed torrent, return a hex string info hash
* @param {string|Buffer} torrentId magnet uri, torrent file, or infohash
* @return {string} info hash (hex string)
*/
Client.toInfoHash = function (torrentId) {
if (typeof torrentId === 'string') {
if (!/^magnet:/.test(torrentId) && torrentId.length === 40 || torrentId.length === 32) {
// info hash (hex/base-32 string)
torrentId = 'magnet:?xt=urn:btih:' + torrentId
}
// magnet uri
var info = magnet(torrentId)
return info && info.infoHash
} else if (Buffer.isBuffer(torrentId)) {
if (torrentId.length === 20) {
// info hash (buffer)
return torrentId.toString('hex')
} else {
// torrent file
try {
return parseTorrent(torrentId).infoHash
} catch (err) {
return null
}
}
} else if (torrentId && torrentId.infoHash) {
// parsed torrent (from parse-torrent module)
return torrentId.infoHash
} else {
return null
}
}