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
|
import EventEmitter from 'events'
import { PassThrough } from 'streamx'
import { BlobWriteStream } from 'fast-blob-stream'
import streamToBuffer from 'stream-with-known-length-to-buffer'
import queueMicrotask from 'queue-microtask'
import rangeParser from 'range-parser'
import mime from 'mime'
import eos from 'end-of-stream'
import FileStream from './file-stream.js'
export default class File extends EventEmitter {
constructor (torrent, file) {
super()
this._torrent = torrent
this._destroyed = false
this._fileStreams = new Set()
this.name = file.name
this.path = file.path
this.length = file.length
this.offset = file.offset
this.done = false
const start = file.offset
const end = start + file.length - 1
this._startPiece = start / this._torrent.pieceLength | 0
this._endPiece = end / this._torrent.pieceLength | 0
if (this.length === 0) {
this.done = true
this.emit('done')
}
this._server = torrent.client._server
}
get downloaded () {
if (this._destroyed || !this._torrent.bitfield) return 0
const { pieces, bitfield, pieceLength, lastPieceLength } = this._torrent
const { _startPiece: start, _endPiece: end } = this
const getPieceLength = (pieceIndex) => (
pieceIndex === pieces.length - 1 ? lastPieceLength : pieceLength
)
const getPieceDownloaded = (pieceIndex) => {
const len = pieceIndex === pieces.length - 1 ? lastPieceLength : pieceLength
if (bitfield.get(pieceIndex)) {
// verified data
return len
} else {
// "in progress" data
return len - pieces[pieceIndex].missing
}
}
let downloaded = 0
for (let index = start; index <= end; index += 1) {
const pieceDownloaded = getPieceDownloaded(index)
downloaded += pieceDownloaded
if (index === start) {
// First piece may have an offset, e.g. irrelevant bytes from the end of
// the previous file
const irrelevantFirstPieceBytes = this.offset % pieceLength
downloaded -= Math.min(irrelevantFirstPieceBytes, pieceDownloaded)
}
if (index === end) {
// Last piece may have an offset, e.g. irrelevant bytes from the start
// of the next file
const irrelevantLastPieceBytes = getPieceLength(end) - (this.offset + this.length) % pieceLength
downloaded -= Math.min(irrelevantLastPieceBytes, pieceDownloaded)
}
}
return downloaded
}
get progress () {
return this.length ? this.downloaded / this.length : 0
}
select (priority) {
if (this.length === 0) return
this._torrent.select(this._startPiece, this._endPiece, priority)
}
deselect () {
if (this.length === 0) return
this._torrent.deselect(this._startPiece, this._endPiece, false)
}
createReadStream (opts) {
if (this.length === 0) {
const empty = new PassThrough()
queueMicrotask(() => {
empty.end()
})
return empty
}
const fileStream = new FileStream(this, opts)
this._fileStreams.add(fileStream)
fileStream.once('close', () => {
this._fileStreams.delete(fileStream)
})
return fileStream
}
getBuffer (cb) {
streamToBuffer(this.createReadStream(), this.length, cb)
}
getBlob (cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
const writeStream = new BlobWriteStream(blob => {
cb(null, blob)
}, { mimeType: this._getMimeType() })
this.createReadStream().pipe(writeStream)
}
getBlobURL (cb) {
this.getBlob((_err, blob) => {
cb(null, URL.createObjectURL(blob))
})
}
_serve (req) {
const res = {
status: 200,
headers: {
// Support range-requests
'Accept-Ranges': 'bytes',
'Content-Type': mime.getType(this.name),
'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
Expires: '0'
},
body: req.method === 'HEAD' ? '' : 'STREAM'
}
// force the browser to download the file if if it's opened in a new tab
if (req.destination === 'document') {
res.headers['Content-Type'] = 'application/octet-stream'
res.headers['Content-Disposition'] = 'attachment'
res.body = 'DOWNLOAD'
}
// `rangeParser` returns an array of ranges, or an error code (number) if
// there was an error parsing the range.
let range = rangeParser(this.length, req.headers.range || '')
if (range.constructor === Array) {
res.status = 206 // indicates that range-request was understood
// no support for multi-range request, just use the first range
range = range[0]
res.headers['Content-Range'] = `bytes ${range.start}-${range.end}/${this.length}`
res.headers['Content-Length'] = `${range.end - range.start + 1}`
} else {
res.headers['Content-Length'] = this.length
}
const stream = req.method === 'GET' && this.createReadStream(range)
let pipe = null
if (stream) {
this.emit('stream', { stream, req, file: this }, piped => {
pipe = piped
// piped stream might not close the original filestream on close/error, this is agressive but necessary
eos(piped, () => {
if (piped) piped.destroy()
stream.destroy()
})
})
}
return [res, pipe || stream, pipe && stream]
}
getStreamURL () {
if (!this._server) throw new Error('No server created')
const url = `${this._server.pathname}/${this._torrent.infoHash}/${encodeURI(this.path)}`
return url
}
streamTo (elem) {
elem.src = this.getStreamURL()
return elem
}
includes (piece) {
return this._startPiece <= piece && this._endPiece >= piece
}
_destroy () {
this._destroyed = true
this._torrent = null
for (const fileStream of this._fileStreams) {
fileStream.destroy()
}
this._fileStreams.clear()
}
}
|