-
Notifications
You must be signed in to change notification settings - Fork 36
/
background.ts
1381 lines (1253 loc) · 44.6 KB
/
background.ts
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const Log = console
class ExtendableError extends Error {
constructor(message?: string) {
super(message)
this.name = new.target.name
}
}
class AssertionError extends ExtendableError {
constructor(message = 'assertion failed') { super(message) }
}
function assert(condition: any, message?: string) {
if (!condition) throw new AssertionError(message)
}
function abortError() {
return new DOMException("The operation was aborted. ", "AbortError")
}
class LocalizedError extends ExtendableError {
constructor(msg: string, ...substitutions: any[]) {
super(browser.i18n.getMessage(msg, substitutions.map(v => `${v}`)))
}
private _tagLocalizedError: never
}
class CriticalSection {
private promise: Promise<any> = Promise.resolve()
sync<T>(fn: () => T | PromiseLike<T>) { // fair, non-recursive
const result = this.promise.then(fn)
this.promise = result.then(() => { }, () => { })
return result
}
}
class Timer {
private id?: number
constructor(public onTimer: () => any, public defaultInterval = 0,
public allowParallel = false) { }
start(interval = this.defaultInterval) {
this.stop()
const id: number = setInterval(
() => { if (this.id === id) this.dispatch() }, interval)
this.id = id
}
startOnce(interval = this.defaultInterval) {
this.stop()
const id: number = setTimeout(() => {
if (this.id !== id) return
this.id = undefined
this.dispatch()
}, interval)
this.id = id
}
stop() {
if (this.id === undefined) return
clearInterval(this.id) // clearTimeout, clearInterval are interchangeable
this.id = undefined
}
get isStarted() { return this.id !== undefined }
private parallelCount = 0
private async dispatch() {
if (!this.allowParallel && this.parallelCount) return
this.parallelCount++
try { await this.onTimer() } finally { this.parallelCount-- }
}
}
const browserDownloadCrashErrors = new WeakSet<Error>()
const browserDownloadMap = new Map<number, Deferred<void>>()
function resolveBrowserDownload(id: number, error?: Error) {
const deferred = browserDownloadMap.get(id)
if (!deferred) return
!error ? deferred.resolve() : deferred.reject(error)
browserDownloadMap.delete(id)
}
browser.downloads.onChanged.addListener(({ id, state, error }) => {
if (state && state.current === 'complete') resolveBrowserDownload(id)
if (error && error.current) {
const result = new LocalizedError('browserDownloadError', error.current)
if (error.current === 'CRASH') browserDownloadCrashErrors.add(result)
resolveBrowserDownload(id, result)
}
})
browser.downloads.onErased.addListener(id => {
resolveBrowserDownload(id, new LocalizedError('browserDownloadErased'))
})
function waitForBrowserDownload(id: number) {
const deferred = new Deferred<void>()
browserDownloadMap.set(id, deferred)
return deferred.promise
}
class NotFoundError extends ExtendableError {
constructor(message = 'not found') { super(message) }
}
class WritableFile {
private mutableFile?: IDBMutableFile
private handle?: IDBFileHandle
readonly initialization: Promise<void>
constructor(private readonly storage: SimpleStorage,
private readonly filename: string, mode: 'create' | 'open' | 'opencreate') {
this.initialization = (async () => {
if (mode === 'open' || mode === 'opencreate')
this.mutableFile = await storage.get(filename)
if (!this.mutableFile) {
if (mode === 'open') throw new NotFoundError()
this.mutableFile = await storage.transaction(function* (_, db) {
return yield db.createMutableFile(filename,
'application/octet-stream')
}, 'nolock')
await storage.set(filename, this.mutableFile)
}
})()
}
async destroy() { await this.storage.delete(this.filename) }
disabled = 0
private async lock<T>(fn: () => T | Promise<T>, location?: number) {
if (!this.mutableFile) await this.initialization
if (this.disabled > 0) throw abortError()
if (!this.handle || !this.handle.active)
this.handle = this.mutableFile!.open('readwrite')
return fn()
}
write(data: string | ArrayBuffer, location: number): Promise<void> {
return this.lock(() => {
this.handle!.location = location
return SimpleStorage.request(this.handle!.write(data))
})
}
read(size: number, location: number): Promise<ArrayBuffer> {
return this.lock(() => {
this.handle!.location = location
return SimpleStorage.request(this.handle!.readAsArrayBuffer(size))
})
}
truncate(start?: number): Promise<void> {
return this.lock(() => SimpleStorage.request(this.handle!.truncate(start)))
}
flush(): Promise<void> {
return this.lock(() => SimpleStorage.request(this.handle!.flush()))
}
async getBlob<T>(callback: (blob: Blob) => T): Promise<T> {
if (!this.mutableFile) await this.initialization
const that = this
return this.storage.transaction(function* (): any {
return callback(yield that.mutableFile!.getFile())
}, 'nolock')
}
}
let taskStorage: SimpleStorage
let fileStorageV0: SimpleStorage
let fileStorageV1: SimpleStorage
class TaskPersistentData extends TaskOptions {
state: DownloadState = 'paused'
error?: string = undefined
totalSize?: number = undefined
constructor(source: Partial<TaskPersistentData>) {
super({})
Object.assign(this, source)
}
}
class Task extends TaskPersistentData {
readonly id: number
private readonly criticalSection = new CriticalSection()
private file?: WritableFile
private currentMaxThreads = 1
private currentMaxRetries = 0
private startTime?: number
private startSize = 0
currentSize = 0
private firstChunk?: Chunk
private lastChunk?: Chunk
threads = new Map<number, Thread>()
fileAccessId?: number
private isRangeSupported = true
private isSavingDownload = false
private isPreallocating = false
get totalSize() { return this.lastChunk ? this.lastChunk.initPosition : undefined }
set totalSize(v) { } // used in base class
private static nextId = 1
static readonly list: Task[] = []
static get(id: number) { return this.list.find(v => v.id === id) }
static newTaskAtTop = false
constructor(options: Partial<TaskPersistentData>, loadId?: number) {
super(options)
this.state = 'paused'
this.id = loadId !== undefined ? loadId : Task.nextId++
assert(!Task.get(this.id))
if (Task.newTaskAtTop)
Task.list.unshift(this)
else
Task.list.push(this)
if (Task.nextId <= this.id) Task.nextId = this.id + 1
broadcastRemote.update([[this.id, {
url: this.url, filename: this.filename, referrer: this.referrer,
state: this.state
}]])
const taskOrder = Task.list.map(v => v.id)
void Settings.set({ taskOrder })
broadcastRemote.setTaskOrder(taskOrder)
void updateBadge()
void this.criticalSection.sync(async () => {
const keys = { maxThreads: 1, minChunkSize: 1, maxRetries: 1 }
for (const key of Object.keys(keys) as (keyof typeof keys)[])
if (this[key] === undefined)
this[key] = await Settings.get(key)
if (options.state !== 'completed') {
if (loadId === undefined) {
this.file = new WritableFile(fileStorageV1, `${this.id}`, 'create')
} else {
const params: [SimpleStorage, 'open' | 'create'][] = [
[fileStorageV1, 'open'], [fileStorageV0, 'open'],
[fileStorageV1, 'create']
]
for (const param of params) {
try {
this.file = new WritableFile(param[0], `${this.id}`, param[1])
await this.file.initialization // check error
break // finish if there is no error
} catch { }
}
}
if (loadId === undefined) {
await fileStorageV0.delete(this.snapshotName)
await fileStorageV1.delete(this.snapshotName)
}
}
if (options.totalSize !== undefined) {
if (options.state === 'saving' || options.state === 'completed') {
this.firstChunk = new Chunk(this, 0, undefined, undefined)
this.lastChunk = new Chunk(this, options.totalSize,
this.firstChunk, undefined)
this.currentSize = this.firstChunk.currentSize = options.totalSize
} else if (options.state &&
DownloadState.canWriteChunks(options.state)) {
await this.readChunks(options.totalSize)
}
}
if (options.state === 'completed' || options.state === 'failed') {
this.setState(options.state, true)
} else if (options.state && DownloadState.isProgressing(options.state))
this.start()
if (loadId === undefined) void this.persist()
})
}
private async persist() {
const data = new TaskPersistentData({})
for (const key of Object.keys(data) as (keyof TaskPersistentData)[])
data[key] = this[key]
await taskStorage.set(this.id, data)
}
private get isWriteChunksDisabled() {
return this.totalSize === undefined || this.isPreallocating ||
!DownloadState.canWriteChunks(this.state)
}
async writeChunks() {
if (this.isWriteChunksDisabled) return
await this.criticalSection.sync(async () => {
if (this.isWriteChunksDisabled) return
const data: number[] = [0]
for (const chunk of this.getChunks())
if (chunk.currentSize)
data.push(chunk.initPosition, chunk.currentSize)
data[0] = data.length - 1
await this.file!.write(
Float64Array.from(data).buffer as ArrayBuffer, this.totalSize!)
})
}
async readChunks(totalSize: number) {
try {
const nBytes = Float64Array.BYTES_PER_ELEMENT
const size = new Float64Array(await this.file!
.read(nBytes, totalSize))[0]
if (!size /* 0 | undefined */) return
const data = Array.from(new Float64Array(await this.file!
.read(nBytes * size, totalSize + nBytes)))
if (data.length !== size) return
let chunk: Chunk | undefined = undefined
let firstChunk: Chunk | undefined = undefined
let currentSize = 0
for (let i = 0; i < data.length; i += 2) {
chunk = new Chunk(this, data[i], chunk, undefined)
if (!firstChunk) firstChunk = chunk
chunk.currentSize = data[i + 1]
currentSize += chunk.currentSize
}
this.firstChunk = firstChunk
this.lastChunk = new Chunk(this, totalSize, chunk, undefined)
this.currentSize = currentSize
} catch (error) { Log.warn('Task.readChunks failed', this.id, error) }
}
private setState(state: DownloadState, disableBadgeColor = false) {
let canceled = false
const isProgressing = DownloadState.isProgressing(state)
if (DownloadState.isProgressing(this.state) !== isProgressing) {
this.startTime =
DownloadState.isProgressing(state) ? performance.now() : undefined
this.startSize = this.currentSize
this.isPreallocating = false
if (!isProgressing) {
for (const thread of [...this.threads.values()]) thread.remove()
if (this.firstChunk && state !== 'completed' &&
(!this.lastChunk || !this.isRangeSupported)) {
this.currentSize -= this.firstChunk.currentSize
this.firstChunk = undefined
this.lastChunk = undefined
canceled = true
}
}
}
this.state = state
broadcastRemote.update([[this.id, {
state: this.state, error: this.error || '',
fileAccessId: this.fileAccessId, canceled,
}]])
void updateBadge(disableBadgeColor ? undefined : this.state)
void this.persist()
void this.writeChunks()
}
start() {
void this.criticalSection.sync(() => {
if (!DownloadState.canStart(this.state)) return
this.error = undefined
this.currentMaxThreads = this.maxThreads!
this.currentMaxRetries = this.maxRetries!
this.setState('downloading')
if (!writeChunksTimer.isStarted) {
Log.log('writeChunksTimer.start')
writeChunksTimer.start()
}
this.adjustThreads()
})
}
setDetail(thread: Thread, filename: string, totalSize: number | undefined,
acceptRanges: boolean) {
return this.criticalSection.sync(async () => {
if (!this.firstChunk || this.firstChunk.thread !== thread) return
assert(!this.firstChunk.next)
if (!this.filename) this.filename = filename
if (totalSize !== undefined) {
this.lastChunk = new Chunk(this, totalSize, this.firstChunk, undefined)
if (this.firstChunk.remainingSize <= 0) thread.remove()
}
this.isRangeSupported = acceptRanges && totalSize !== undefined
broadcastRemote.update([[this.id, {
filename: this.filename, totalSize: this.totalSize,
pauseIsStop: !this.isRangeSupported,
isPreallocating: this.isPreallocating,
}]])
void this.persist()
if (this.isRangeSupported && totalSize && totalSize > 16) {
try {
broadcastRemote.update(
[[this.id, { isPreallocating: this.isPreallocating = true }]])
const byte = new Uint8Array([1]).buffer as ArrayBuffer
const interval = 64 * 1024 ** 2
for (let i = 0; i < totalSize; i += interval)
await this.file!.write(byte, i)
await this.file!.write(byte, totalSize - 1)
await this.file!.flush()
} catch (error) {
this.lastChunk = undefined
throw error
} finally {
if (this.startTime !== undefined) {
this.startTime = performance.now()
this.startSize = this.currentSize
}
broadcastRemote.update(
[[this.id, { isPreallocating: this.isPreallocating = false }]])
}
}
this.adjustThreads()
})
}
private adjustThreads() {
if (this.state !== 'downloading') return
if (!this.firstChunk) {
assert(this.threads.size === 0)
new Thread(this.firstChunk = new Chunk(this, 0, undefined, undefined))
} else {
if (this.currentMaxThreads > this.threads.size)
this.addThreads()
if (!this.threads.size) this.saveDownload()
}
broadcastRemote.update([[this.id, { threadCount: this.threads.size }]])
}
private *getChunks() { // [firstChunk, lastChunk)
if (!this.firstChunk || !this.lastChunk) return
for (let chunk = this.firstChunk!; chunk.next; chunk = chunk.next)
yield chunk
}
private addThreads() {
if (!this.isRangeSupported) return
let quota = this.currentMaxThreads - this.threads.size
if (quota <= 0) return
assert(this.lastChunk)
// first fill all the gaps
const gaps = [] as { size: number, chunk: Chunk }[]
for (const chunk of this.getChunks())
if (!chunk.thread && chunk.remainingSize)
gaps.push({ size: chunk.remainingSize, chunk })
for (let i = 0; i < gaps.length && quota; i++)
new Thread(gaps[i].chunk), quota--
if (quota <= 0) return
// then divide existing threads
const divisibles = [...this.threads.values()].map(({ chunk }) =>
({ size: chunk.remainingSize, chunk, count: 0 })).filter(v => v.size)
if (!divisibles.length) return
divisibles.sort((v0, v1) => v1.size - v0.size)
const totalSize = divisibles.map(v => v.size).reduce((v0, v1) => v0 + v1)
// (quota + gaps.length) is the number of the divided spaces
// try to evenly distribute totalSize
const invertSpaceSize = (quota + divisibles.length) / totalSize
for (const divisible of divisibles) {
divisible.count = Math.floor(divisible.size * invertSpaceSize - 1)
quota -= divisible.count
}
// adjust the floored numbers to keep the sum.
for (let i = divisibles.length; i-- > 0 && quota > 0;)
++divisibles[i].count, --quota
for (const divisible of divisibles) {
// avoid too small chunks
let spaceSize
do {
spaceSize = Math.floor(divisible.size / (divisible.count + 1))
if (spaceSize > 0 && spaceSize >= this.minChunkSize! * 1024) break
divisible.count--
} while (divisible.count > 0)
let chunk0 = divisible.chunk, chunk1 = chunk0.next!
let position = divisible.chunk.currentPosition
for (let i = 0; i < divisible.count; i++) {
position += spaceSize
new Thread(chunk0 = new Chunk(this, position, chunk0, chunk1))
}
}
}
pause() {
if (!DownloadState.canPause(this.state)) return
if (this.file) this.file.disabled++
void this.criticalSection.sync(() => {
if (this.file) this.file.disabled--
if (!DownloadState.canPause(this.state)) return
this.setState('paused')
})
}
private saveDownload() {
assert(this.state === 'downloading')
assert(this.totalSize === undefined || this.currentSize === this.totalSize)
this.setState('saving')
const chunks = [...this.getChunks()]
void this.doSaveDownload(chunks)
}
private get snapshotName() { return `${this.id}-snapshot` }
private async doSaveDownload(chunks: Chunk[]) {
if (this.isSavingDownload) return
this.isSavingDownload = true
const blobUrl = new class {
value?: string
open(blob: Blob | File) {
this.close()
this.value = URL.createObjectURL(blob)
}
close() {
if (!this.value) return
URL.revokeObjectURL(this.value)
this.value = undefined
}
}
const filename = (this.filename || '').replace(/[\\/]+/g, '_')
.replace(/</g, '(').replace(/>/g, ')').replace(/"/g, "'")
.replace(/[\x00-\x1f\x7f-\x9f:*?|]+/g, ' ')
.replace(/^[\s\u180e.]+|[\s\u180e.]+$/g, '') || undefined
try {
for (const lastTrial of [false, true]) {
const snapshot = await fileStorageV1.get(this.snapshotName)
if (snapshot) {
blobUrl.open(snapshot)
} else {
if (this.totalSize !== undefined)
await this.file!.truncate(this.totalSize)
await this.file!.getBlob(v => blobUrl.open(v))
}
const saveId = (snapshot || !await Settings.get(
'skipFirstSavingAttempt')) ? await browser.downloads.download({
url: blobUrl.value!, filename,
saveAs: {
systemDefault: undefined,
downloadFolder: false,
alwaysAsk: true,
}[await Settings.get('saveFileTo')],
}) : NaN
try {
if (!Number.isFinite(saveId)) {
const error = new Error('Saving attempt is skipped')
browserDownloadCrashErrors.add(error)
throw error
}
await waitForBrowserDownload(saveId)
} catch (error) {
if (snapshot || lastTrial ||
!browserDownloadCrashErrors.has(error)) throw error
blobUrl.close()
if (Number.isFinite(saveId))
await removeBrowserDownload(saveId)
await fileStorageV1.initialization /* prevent async */
await this.file!.getBlob(blob =>
fileStorageV1.set(this.snapshotName, blob))
continue
}
this.fileAccessId = saveId
this.complete()
break
}
} catch (error) {
this.fail(error && !(error instanceof LocalizedError) &&
error.message.includes('Download canceled') ?
new LocalizedError('browserDownloadErased') : error)
} finally {
blobUrl.close()
this.isSavingDownload = false
}
}
complete() {
this.criticalSection.sync(() => {
this.setState('completed')
void this.cleanupFileStorage()
})
}
async cleanupFileStorage() {
if (this.file) void this.file.destroy()
delete this.file
void fileStorageV0.delete(this.snapshotName)
void fileStorageV1.delete(this.snapshotName)
}
remove() {
if (this.file) this.file.disabled++
this.criticalSection.sync(() => {
if (this.file) this.file.disabled--
for (const thread of [...this.threads.values()]) thread.remove()
Task.list.splice(Task.list.indexOf(this), 1)
void this.cleanupFileStorage()
void taskStorage.delete(this.id)
if (this.fileAccessId !== undefined)
void removeBrowserDownload(this.fileAccessId)
broadcastRemote.notifyRemove(this.id)
void updateBadge()
})
}
write(thread: Thread, data: ArrayBuffer) {
return this.criticalSection.sync(async () => {
if (!thread.exists) return
const { chunk } = thread
let adjust = false, remove = false
while (data.byteLength > chunk.remainingSize &&
chunk.next!.next && !chunk.next!.currentSize) {
const nextThread = chunk.next!.thread
if (nextThread) { nextThread.remove(); adjust = true }
chunk.next = chunk.next!.next
chunk.next!.prev = chunk
}
const addedSize = Math.min(data.byteLength, chunk.remainingSize)
if (addedSize === chunk.remainingSize) { remove = adjust = true }
if (chunk.remainingSize > 0) {
try {
await this.file!.write(data, chunk.currentPosition)
} catch (error) {
if (error && error.name === 'AbortError') return
return this.setFailure(error)
}
chunk.currentSize += addedSize
this.currentSize += addedSize
}
if (remove) thread.remove()
if (adjust) this.adjustThreads()
})
}
finishThread(thread: Thread, error: Error | undefined) {
// should be called by thread itself
void this.criticalSection.sync(() => {
if (!thread.exists) return
// after locked, all the writes have completed.
if (!error && this.totalSize !== undefined &&
thread.chunk.remainingSize > 0) {
// this happens after setDetail, in the thread's fetch
assert(Number.isFinite(thread.chunk.totalSize))
error = new LocalizedError('threadStopped')
}
thread.remove()
if (error && error.name !== 'AbortError') {
const localizedError = error instanceof LocalizedError ? error :
(error.name === 'TypeError' &&
error.message.startsWith('NetworkError')) ?
new LocalizedError('networkError') :
new LocalizedError('unknownError', [`${error}`])
Log.warn('thread failed', thread.chunk.initPosition,
thread.chunk.currentPosition, localizedError.message)
if (!this.isRangeSupported || this.totalSize === undefined)
return this.setFailure(localizedError)
if (this.currentMaxRetries <= 0) {
this.currentMaxThreads = Math.min(
this.currentMaxThreads, this.threads.size)
if (!this.currentMaxThreads)
return this.setFailure(localizedError)
} else --this.currentMaxRetries
}
this.adjustThreads()
})
}
private setFailure(error: LocalizedError) {
if (!DownloadState.isProgressing(this.state)) return
Log.error('task failed', this.id, error.message)
this.error = error.message
this.setState('failed')
}
fail(error: LocalizedError) {
void this.criticalSection.sync(async () => this.setFailure(error))
}
getAllUpdateData(): TaskUpdateData {
return {
state: this.state,
url: this.url,
referrer: this.referrer,
error: this.error,
filename: this.filename,
totalSize: this.totalSize,
currentSize: this.currentSize,
threadCount: this.threads.size,
averageSpeed: this.averageSpeed,
chunks: [...this.getChunks()].reduce((v0, v1) =>
Object.assign(v0, v1.updateData), {} as { [id: number]: number }),
fileAccessId: this.fileAccessId,
pauseIsStop: !this.isRangeSupported,
isPreallocating: this.isPreallocating,
}
}
get averageSpeed() {
return this.startTime === undefined ? undefined : (
(this.currentSize - this.startSize) /
((performance.now() - this.startTime) / 1000))
}
}
const writeChunksTimer = new Timer(async () => {
const tasks = Task.list.filter(t => t.state === 'downloading')
if (!tasks.length) {
Log.log('writeChunksTimer.stop')
writeChunksTimer.stop()
return
}
await Promise.all(tasks.map(task => task.writeChunks().catch(() => { })))
}, 1000)
class Chunk {
thread?: Thread
currentSize = 0
get currentPosition() { return this.initPosition + this.currentSize }
get totalSize() {
return this.next ? this.next.initPosition - this.initPosition : Infinity
}
get remainingSize() { return this.totalSize - this.currentSize }
get updateData() { return { [this.initPosition]: this.currentSize } }
constructor(readonly task: Task, readonly initPosition: number,
public prev: Chunk | undefined, public next: Chunk | undefined) {
assert(!prev && initPosition === 0
|| prev && initPosition >= prev.currentPosition)
assert(!next || next && initPosition <= next.initPosition)
if (this.next) this.next.prev = this
if (this.prev) this.prev.next = this
}
}
const extensionHeader = 'x-multithreaded-download-manager-' +
[...window.crypto.getRandomValues(new Uint8Array(12)) as Uint8Array].map(
v => 'abcdefghijklmnopqrstuvwxyz'[v % 26]).join('')
interface ThreadInfo {
taskId: number
initPosition: number
threadId: number
}
class Thread {
static nextId = 0
readonly id = Thread.nextId++
readonly initPosition: number
private readonly controller = new AbortController()
private preventAbort = false
constructor(readonly chunk: Chunk) {
this.initPosition = this.chunk.currentPosition
assert(!this.task.threads.has(this.initPosition))
assert(!chunk.thread)
Log.log('thread created', this.initPosition)
chunk.thread = this
this.task.threads.set(this.initPosition, this)
const minErrorDelayPromise = new Promise(resolve =>
setTimeout(resolve, 1000))
void this.init().catch(error =>
minErrorDelayPromise.then(() => this.task.finishThread(this, error)))
}
get task() { return this.chunk.task }
private async init() {
const headers = new Headers(this.initPosition > 0 ? {
Range: `bytes=${this.initPosition}-`,
} : {})
headers.append(extensionHeader, JSON.stringify({
taskId: this.task.id,
initPosition: this.initPosition,
threadId: this.id,
} as ThreadInfo))
const response = await fetch(this.task.url, {
credentials: "include",
signal: this.controller.signal,
headers,
})
if (this.controller.signal.aborted) throw abortError()
if (!response.ok) {
throw new LocalizedError('unsuccessfulResponse',
response.status, response.statusText)
}
await response.arrayBuffer() // empty, only for catching error
this.task.finishThread(this, undefined)
}
get exists() { return this.chunk.thread === this }
remove() {
if (!this.exists) return
Log.log('thread removed', this.initPosition)
this.chunk.thread = undefined
this.task.threads.delete(this.initPosition)
if (!this.preventAbort) this.controller.abort()
broadcastRemote.update([[this.task.id, {
chunks: this.chunk.updateData,
currentSize: this.task.currentSize,
}]])
}
async setupFilter({ requestId, url, statusCode, responseHeaders }: {
requestId: string,
url: string,
responseHeaders?: browser.webRequest.HttpHeaders,
statusCode: number,
}) {
this.preventAbort = true
if (!this.chunk.next) {
const headers = new Map(responseHeaders!.map(({ name, value })
: [string, string] => [name.toLowerCase(), value || '']))
let totalSize: number | undefined = Number(
headers.get('content-length') || NaN)
const acceptRanges = (headers.get('accept-ranges') || '')
.toLowerCase() === 'bytes'
const siteResult = await callSiteHandler(url)
if (siteResult) {
if (!Number.isInteger(totalSize) &&
siteResult.totalSize !== undefined)
totalSize = siteResult.totalSize
}
if (!Number.isInteger(totalSize)) {
totalSize = undefined
Log.warn(browser.i18n.getMessage(
'rangesNotSupported', ['Content-Length']))
}
if (!acceptRanges)
Log.warn(browser.i18n.getMessage(
'rangesNotSupported', ['Accept-Ranges']))
try {
await this.task.setDetail(this, await getSuggestedFilename(
url, headers.get('content-disposition') || ''),
totalSize, acceptRanges)
} catch (error) {
if (!(error && error.name === 'AbortError')) throw error
}
}
const filter = browser.webRequest.filterResponseData(requestId)
const buffers: ArrayBuffer[] = []
let lastCommitTime = performance.now()
const commit = () => {
const data = new Uint8Array(buffers.reduce((s, v) => s + v.byteLength, 0))
buffers.reduce((s, v) =>
(data.set(new Uint8Array(v), s), s + v.byteLength), 0)
void this.task.write(this, data.buffer as ArrayBuffer)
buffers.length = 0
lastCommitTime = performance.now()
}
const stop = () => { commit(); filter.close() }
filter.onstart = () => { if (!this.exists) filter.close() }
filter.ondata = ({ data }) => {
if (!this.exists) { stop(); return }
buffers.push(data)
if (performance.now() - lastCommitTime > 300) commit()
}
filter.onstop = stop; filter.onerror = stop
}
}
const downloadRequestMap = new Map<string, Thread>()
const downloadRequestFilter = {
urls: ['<all_urls>'] as ['<all_urls>'],
types: ['xmlhttprequest'] as ['xmlhttprequest'],
}
browser.webRequest.onBeforeSendHeaders.addListener(({ requestId, requestHeaders }) => {
if (!requestHeaders!.some(h => h.name.toLowerCase() === extensionHeader)) return {}
const headers = new Map(requestHeaders!.map(h =>
[h.name.toLowerCase(), h.value] as [string, string]))
let thread: Thread
try {
const infoStr = headers.get(extensionHeader) as string
const info = JSON.parse(infoStr) as ThreadInfo
const task = Task.get(info.taskId)
thread = task!.threads.get(info.initPosition)!
if (!thread || !thread.exists || thread.id != info.threadId) return {}
} catch { return {} }
downloadRequestMap.set(requestId, thread)
const newHeaders = requestHeaders!.filter(v =>
![extensionHeader, 'accept-encoding', 'origin', 'referer'].includes(
v.name.toLowerCase()))
if (thread.task.referrer)
newHeaders.push({ name: 'Referer', value: thread.task.referrer })
return { requestHeaders: newHeaders }
}, downloadRequestFilter, ['requestHeaders', 'blocking'])
browser.webRequest.onHeadersReceived.addListener(details => {
const { requestId, statusCode } = details
const thread = downloadRequestMap.get(requestId)
if (!thread) return {}
if (!(statusCode >= 200 && statusCode < 300)) return {}
downloadRequestMap.delete(requestId)
return thread.setupFilter(details).then(() => ({}))
}, downloadRequestFilter, ['blocking', 'responseHeaders'])
browser.webRequest.onErrorOccurred.addListener(({ requestId }) => {
downloadRequestMap.delete(requestId)
}, downloadRequestFilter)
browser.webRequest.onResponseStarted.addListener(({ requestId }) => {
downloadRequestMap.delete(requestId)
}, downloadRequestFilter)
function parseRFC5987(value: string) {
try {
const parts = value.split('\'')
if (parts.length !== 3) return undefined
if (['utf-8', 'utf8'].includes(parts[0].toLowerCase()))
return decodeURIComponent(parts[2])
const arr = (parts[2].match(/%[0-9a-fA-F]{2}|./g) || [])
.map(v => v.length === 3 ? parseInt(v.slice(1), 16) : v.charCodeAt(0))
.filter(v => v <= 255)
return (new TextDecoder(parts[0])).decode(Uint8Array.from(arr))
} catch { return undefined }
}
function getLegacyFilenameEncoding(settings: Settings) {
return settings.legacyFilenameEncoding || document.characterSet || 'UTF-8'
}
function parseURLEncodedFilename(s: string, settings: Settings) {
if (settings.legacyFilenameDetectURLEncoded) {
try {
const decoded = decodeURIComponent(s)
if (decoded !== s) return decoded
} catch (err) { }
}
if (settings.legacyFilenameDetectNonStandardURLEncoded) {
try {
const seq = unescape(s)
if (seq !== s) {
const arr = [...seq].map(v => v.charCodeAt(0)).filter(v => v <= 255)
const encoding = getLegacyFilenameEncoding(settings)
return new TextDecoder(encoding).decode(Uint8Array.from(arr))
}
} catch (err) { }
}
return undefined
}
function parseLegacyFilename(value: string, settings: Settings) {
const decoded = parseURLEncodedFilename(value, settings)
if (decoded) return decoded
if (settings.legacyFilenameDetectUTF8) try {
return decodeURIComponent(escape(value))
} catch { }
try {
const encoding = getLegacyFilenameEncoding(settings)
const arr = [...value].map(v => v.charCodeAt(0)).filter(v => v <= 255)
return (new TextDecoder(encoding)).decode(Uint8Array.from(arr))
} catch { return undefined }
}
function getSuggestedFilename(url: string, contentDisposition: string,
settings?: Settings): string | Promise<string> {
if (!settings)
return Settings.load([
'legacyFilenameEncoding', 'legacyFilenameDetectUTF8',
'legacyFilenameDetectURLEncoded',
'legacyFilenameDetectNonStandardURLEncoded',
]).then(v => getSuggestedFilename(url, contentDisposition, v))
const regex = /^\s*filename(\*?)\s*=\s*("[^"]+"?|[^\s;]+)(;?)/i
let filename = ''
for (let match: string[] | null,
s = contentDisposition.replace(/^\s*[-\w]+\s*(?:;|$)/, '');
match = regex.exec(s); s = s.replace(regex, '')) {
if (!filename || match[1]) {
let value = match[2].trim()
if (value.startsWith('"')) {
value = value.slice(1)
if (value.endsWith('"')) value = value.slice(0, -1)
}
filename = (match[1] ? parseRFC5987(value) :
parseLegacyFilename(value, settings)) || value
if (match[1]) break // star
}
if (!match[3]) break // semicolon
}
if (filename) return filename
filename = getSuggestedFilenameFromURL(url)
return parseURLEncodedFilename(filename, settings) || filename
}
if (!browser.contextMenus)
browser.contextMenus = { create() { }, remove() { } } as any
async function migrateLegacyPersistentSimpleStorage(databaseName: string) {