forked from webtorrent/parse-torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
275 lines (232 loc) · 8.78 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
271
272
273
274
275
/*! parse-torrent. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */
/* global Blob */
const bencode = require('bencode')
const blobToBuffer = require('blob-to-buffer')
const fs = require('fs') // browser exclude
const get = require('simple-get')
const magnet = require('magnet-uri')
const path = require('path')
const sha1 = require('simple-sha1')
const sha256 = require('simple-sha256')
const queueMicrotask = require('queue-microtask')
module.exports = parseTorrent
module.exports.remote = parseTorrentRemote
module.exports.toMagnetURI = magnet.encode
module.exports.toTorrentFile = encodeTorrentFile
/**
* Parse a torrent identifier (magnet uri, .torrent file, info hash)
* @param {string|Buffer|Object} torrentId
* @return {Object} parsed torrent object
*/
function parseTorrent (torrentId) {
if (typeof torrentId === 'string' && /^(stream-)?magnet:/.test(torrentId)) {
// if magnet uri (string)
const torrentObj = magnet(torrentId)
// infoHash won't be defined if a non-bittorrent magnet is passed
if (!torrentObj.infoHash && !torrentObj.infoHashV2) {
throw new Error('Invalid torrent identifier')
}
return torrentObj
} else if (typeof torrentId === 'string' && (/^[a-f0-9]{40}$/i.test(torrentId) || /^[a-z2-7]{32}$/i.test(torrentId))) {
// if v1 info hash (hex/base-32 string)
return magnet(`magnet:?xt=urn:btih:${torrentId}`)
} else if (typeof torrentId === 'string' && /^1220(.{64})/.test(torrentId)) {
// if v2 info hash (base-32 string)
return magnet(`magnet:?xt=urn:btmh:${torrentId}`)
} else if (Buffer.isBuffer(torrentId) && torrentId.length === 20) {
// if v1 info hash (buffer)
return magnet(`magnet:?xt=urn:btih:${torrentId.toString('hex')}`)
} else if (Buffer.isBuffer(torrentId)) {
// if .torrent file (buffer)
return decodeTorrentFile(torrentId) // might throw
} else if (torrentId && (torrentId.infoHash || torrentId.infoHashV2)) {
// if parsed torrent (from `parse-torrent` or `magnet-uri`)
if (torrentId.infoHash) torrentId.infoHash = torrentId.infoHash.toLowerCase()
if (torrentId.infoHashV2) torrentId.infoHashV2 = torrentId.infoHashV2.toLowerCase()
if (!torrentId.announce) torrentId.announce = []
if (typeof torrentId.announce === 'string') {
torrentId.announce = [torrentId.announce]
}
if (!torrentId.urlList) torrentId.urlList = []
return torrentId
} else {
throw new Error('Invalid torrent identifier')
}
}
function parseTorrentRemote (torrentId, opts, cb) {
if (typeof opts === 'function') return parseTorrentRemote(torrentId, {}, opts)
if (typeof cb !== 'function') throw new Error('second argument must be a Function')
let parsedTorrent
try {
parsedTorrent = parseTorrent(torrentId)
} catch (err) {
// If torrent fails to parse, it could be a Blob, http/https URL or
// filesystem path, so don't consider it an error yet.
}
if (parsedTorrent && (parsedTorrent.infoHash || parsedTorrent.infoHashV2)) {
queueMicrotask(() => {
cb(null, parsedTorrent)
})
} else if (isBlob(torrentId)) {
blobToBuffer(torrentId, (err, torrentBuf) => {
if (err) return cb(new Error(`Error converting Blob: ${err.message}`))
parseOrThrow(torrentBuf)
})
} else if (typeof get === 'function' && /^https?:/.test(torrentId)) {
// http, or https url to torrent file
opts = Object.assign({
url: torrentId,
timeout: 30 * 1000,
headers: { 'user-agent': 'WebTorrent (https://webtorrent.io)' }
}, opts)
get.concat(opts, (err, res, torrentBuf) => {
if (err) return cb(new Error(`Error downloading torrent: ${err.message}`))
parseOrThrow(torrentBuf)
})
} else if (typeof fs.readFile === 'function' && typeof torrentId === 'string') {
// assume it's a filesystem path
fs.readFile(torrentId, (err, torrentBuf) => {
if (err) return cb(new Error('Invalid torrent identifier'))
parseOrThrow(torrentBuf)
})
} else {
queueMicrotask(() => {
cb(new Error('Invalid torrent identifier'))
})
}
function parseOrThrow (torrentBuf) {
try {
parsedTorrent = parseTorrent(torrentBuf)
} catch (err) {
return cb(err)
}
if (parsedTorrent && (parsedTorrent.infoHash || parsedTorrent.infoHashV2)) cb(null, parsedTorrent)
else cb(new Error('Invalid torrent identifier'))
}
}
/**
* Parse a torrent. Throws an exception if the torrent is missing required fields.
* @param {Buffer|Object} torrent
* @return {Object} parsed torrent
*/
function decodeTorrentFile (torrent) {
if (Buffer.isBuffer(torrent)) {
torrent = bencode.decode(torrent)
}
// sanity check
ensure(torrent.info, 'info')
ensure(torrent.info['name.utf-8'] || torrent.info.name, 'info.name')
ensure(torrent.info['piece length'], 'info[\'piece length\']')
ensure(torrent.info.pieces, 'info.pieces')
if (torrent.info.files) {
torrent.info.files.forEach(file => {
ensure(typeof file.length === 'number', 'info.files[0].length')
ensure(file['path.utf-8'] || file.path, 'info.files[0].path')
})
} else {
ensure(typeof torrent.info.length === 'number', 'info.length')
}
const result = {
info: torrent.info,
infoBuffer: bencode.encode(torrent.info),
name: (torrent.info['name.utf-8'] || torrent.info.name).toString(),
announce: []
}
result.infoHash = sha1.sync(result.infoBuffer)
result.infoHashBuffer = Buffer.from(result.infoHash, 'hex')
result.infoHashV2 = sha256.sync(result.infoBuffer)
if (torrent.info.private !== undefined) result.private = !!torrent.info.private
if (torrent['creation date']) result.created = new Date(torrent['creation date'] * 1000)
if (torrent['created by']) result.createdBy = torrent['created by'].toString()
if (Buffer.isBuffer(torrent.comment)) result.comment = torrent.comment.toString()
// announce and announce-list will be missing if metadata fetched via ut_metadata
if (Array.isArray(torrent['announce-list']) && torrent['announce-list'].length > 0) {
torrent['announce-list'].forEach(urls => {
urls.forEach(url => {
result.announce.push(url.toString())
})
})
} else if (torrent.announce) {
result.announce.push(torrent.announce.toString())
}
// handle url-list (BEP19 / web seeding)
if (Buffer.isBuffer(torrent['url-list'])) {
// some clients set url-list to empty string
torrent['url-list'] = torrent['url-list'].length > 0
? [torrent['url-list']]
: []
}
result.urlList = (torrent['url-list'] || []).map(url => url.toString())
// remove duplicates by converting to Set and back
result.announce = Array.from(new Set(result.announce))
result.urlList = Array.from(new Set(result.urlList))
const files = torrent.info.files || [torrent.info]
result.files = files.map((file, i) => {
const parts = [].concat(result.name, file['path.utf-8'] || file.path || []).map(p => p.toString())
return {
path: path.join.apply(null, [path.sep].concat(parts)).slice(1),
name: parts[parts.length - 1],
length: file.length,
offset: files.slice(0, i).reduce(sumLength, 0)
}
})
result.length = files.reduce(sumLength, 0)
const lastFile = result.files[result.files.length - 1]
result.pieceLength = torrent.info['piece length']
result.lastPieceLength = ((lastFile.offset + lastFile.length) % result.pieceLength) || result.pieceLength
result.pieces = splitPieces(torrent.info.pieces)
return result
}
/**
* Convert a parsed torrent object back into a .torrent file buffer.
* @param {Object} parsed parsed torrent
* @return {Buffer}
*/
function encodeTorrentFile (parsed) {
const torrent = {
info: parsed.info
}
torrent['announce-list'] = (parsed.announce || []).map(url => {
if (!torrent.announce) torrent.announce = url
url = Buffer.from(url, 'utf8')
return [url]
})
torrent['url-list'] = parsed.urlList || []
if (parsed.private !== undefined) {
torrent.private = Number(parsed.private)
}
if (parsed.created) {
torrent['creation date'] = (parsed.created.getTime() / 1000) | 0
}
if (parsed.createdBy) {
torrent['created by'] = parsed.createdBy
}
if (parsed.comment) {
torrent.comment = parsed.comment
}
return bencode.encode(torrent)
}
/**
* Check if `obj` is a W3C `Blob` or `File` object
* @param {*} obj
* @return {boolean}
*/
function isBlob (obj) {
return typeof Blob !== 'undefined' && obj instanceof Blob
}
function sumLength (sum, file) {
return sum + file.length
}
function splitPieces (buf) {
const pieces = []
for (let i = 0; i < buf.length; i += 20) {
pieces.push(buf.slice(i, i + 20).toString('hex'))
}
return pieces
}
function ensure (bool, fieldName) {
if (!bool) throw new Error(`Torrent is missing required field: ${fieldName}`)
}
// Workaround Browserify v13 bug
// https://github.com/substack/node-browserify/issues/1483
;(() => { Buffer.alloc(0) })()