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
|
module.exports = Torrent
var bncode = require('bncode')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var magnet = require('magnet-uri')
var Swarm = require('bittorrent-swarm')
var METADATA_BLOCK_SIZE = 16 * 1024
var WIRE_TIMEOUT = 10000
inherits(Torrent, EventEmitter)
function Torrent (uri, opts) {
if (!(this instanceof Torrent)) return new Torrent(uri, opts)
EventEmitter.call(this)
var info = this._parseMagnetUri(uri)
if (!info.infoHash)
throw new Error('invalid torrent uri')
this.infoHash = info.infoHash
this.title = info.title
this.metadata = null
this.swarm = new Swarm(this.infoHash, opts.peerId, { dht: true })
if (opts.port) {
this.swarm.listen(opts.port, function (port) {
this.emit('listening', port)
}.bind(this))
}
this.swarm.on('error', function (err) {
console.error(err.message)
})
this.swarm.on('wire', function (wire) {
// Send KEEP-ALIVE (every 60s) so peers will not disconnect the wire
wire.setKeepAlive(true)
// If peer supports DHT, send PORT message to report what port our DHT node
// is listening on
if (wire.peerExtensions.dht) {
console.log('peer supports DHT')
// TODO: DHT doesn't support listening yet
// wire.port(dht.port)
}
// When peer sends PORT, add them to the routing table
wire.on('port', function (port) {
console.log('received PORT: ', port)
// TODO: DHT doesn't have a routing table yet
// dht.add(wire.remoteAddress, port)
})
// Timeout for wire requests to this peer
wire.setTimeout(WIRE_TIMEOUT)
// Support extended messages:
// - ut_metadata (metadata fetching, trackerless torrents)
if (wire.peerExtensions.extended) {
console.log('Wire ' + wire.remoteAddress + ' supports extended messages', wire.peerExtensions)
wire.extended(0, {
m: {
ut_metadata: 1
}
// TODO - this should be set once we have metadata
// metadata_size: xx
})
}
wire.on('extended', function (ext, buf) {
var dict
console.log('Received extended message ' + ext + ' from ' + wire.remoteAddress)
if (ext === 0) { // handshake
try {
console.log('decoding ' + buf.toString())
dict = bncode.decode(buf.toString())
console.log('got extended handshake: ' + JSON.stringify(dict))
} catch (e) {
console.error('Error decoding extended message: ' + e.message)
}
if (dict.m.ut_metadata && dict.metadata_size) {
var metadataSize = dict.metadata_size
var numPieces = Math.ceil(metadataSize / METADATA_BLOCK_SIZE)
console.log('metadata size: ' + metadataSize)
console.log(numPieces + ' pieces')
wire.metadata = new Buffer(metadataSize)
// request all pieces
for (var piece = 0; piece < numPieces; piece++) {
wire.extended(dict.m.ut_metadata, {
msg_type: 0,
piece: piece
})
}
}
} else if (ext === 1) { // ut_metadata
// 0 - request
// 1 - data
// 2 - reject
var str
var dataIndex
var data
try {
str = buf.toString()
console.log('decoding ' + str)
dataIndex = str.indexOf('ee') + 2
var msg = str.substring(0, dataIndex)
console.log('using ' + msg)
dict = bncode.decode(msg)
data = buf.slice(dataIndex)
console.log('got metadata: ' + JSON.stringify(dict))
console.log('got metadata data: ' + data.length + ' bytes')
} catch (e) {
console.error('Error decoding extended message: ' + e.message)
}
// {'msg_type': 1, 'piece': 0, 'total_size': 3425}
if (dict.msg_type === 1) { // data
console.log('total_size: ' + dict.total_size)
data.copy(wire.metadata, dict.piece * METADATA_BLOCK_SIZE)
console.log('METADATA')
console.log(wire.metadata.toString())
this.metadata = {
'announce-list': [],
info: bncode.decode(wire.metadata),
// info_hash:
}
console.log(this.metadata)
this.emit('metadata', this.metadata)
}
}
}.bind(this))
}.bind(this))
}
Torrent.prototype.downloadMetadata = function () {
if (!this.metadata)
return
var errorHandler = function (err) {
console.error('error' + err.toString())
}
chrome.fileSystem.chooseEntry({
type: 'saveFile',
suggestedName: this.title + '.torrent'
}, function (fileEntry) {
if (!fileEntry)
return
fileEntry.createWriter(function (writer) {
writer.onerror = errorHandler
writer.onwriteend = function (e) {
console.log('write complete')
}
var metadata = new Buffer(bncode.encode(this.metadata))
writer.write(new Blob([metadata]), { type: 'application/x-bittorrent' })
}.bind(this), errorHandler)
}.bind(this))
}
Object.defineProperty(Torrent.prototype, 'numPeers', {
get: function () {
return this.swarm.wires.length
}
})
/**
* Add a peer to the swarm
* @param {string} addr
*/
Torrent.prototype.addPeer = function (addr) {
this.swarm.add(addr)
}
//
// HELPER METHODS
//
/**
* Given a magnet URI, return infoHash and title
* @param {string} uri
* @return {Object}
*/
Torrent.prototype._parseMagnetUri = function (uri) {
var parsed = magnet(uri)
return {
title: parsed.dn, // displayName
infoHash: parsed.xt && parsed.xt.split('urn:btih:')[1]
}
}
|