forked from liqi0816/bilitwin
-
Notifications
You must be signed in to change notification settings - Fork 57
/
biliTwin.user.js
12114 lines (10621 loc) · 456 KB
/
biliTwin.user.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
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
// ==UserScript==
// @name bilibili merged flv+mp4+ass+enhance
// @namespace http://qli5.tk/
// @homepageURL https://github.com/Xmader/bilitwin/
// @supportURL https://github.com/Xmader/bilitwin/issues
// @description bilibili/哔哩哔哩:超清FLV下载,FLV合并,原生MP4下载,弹幕ASS下载,CC字幕转码ASS下载,AAC音频下载,MKV打包,播放体验增强,原生appsecret,不借助其他网站
// @match *://www.bilibili.com/video/av*
// @match *://www.bilibili.com/video/bv*
// @match *://www.bilibili.com/video/BV*
// @match *://bangumi.bilibili.com/anime/*/play*
// @match *://www.bilibili.com/bangumi/play/ep*
// @match *://www.bilibili.com/bangumi/play/ss*
// @match *://www.bilibili.com/bangumi/media/md*
// @match *://www.biligame.com/detail/*
// @match *://vc.bilibili.com/video/*
// @match *://www.bilibili.com/watchlater/
// @version 1.24.1
// @author qli5
// @copyright qli5, 2014+, 田生, grepmusic, zheng qian, ryiwamoto, xmader
// @license Mozilla Public License 2.0; http://www.mozilla.org/MPL/2.0/
// @grant unsafeWindow
// @grant GM.registerMenuCommand
// @run-at document-start
// ==/UserScript==
/***
*
* @author qli5 <goodlq11[at](163|gmail).com>
*
* BiliTwin consists of two parts - BiliMonkey and BiliPolyfill.
* They are bundled because I am too lazy to write two user interfaces.
*
* So what is the difference between BiliMonkey and BiliPolyfill?
*
* BiliMonkey deals with network. It is a (naIve) Service Worker.
* This is also why it uses IndexedDB instead of localStorage.
* BiliPolyfill deals with experience. It is more a "user script".
* Everything it can do can be done by hand.
*
* BiliPolyfill will be pointless in the long run - I believe bilibili
* will finally provide these functions themselves.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an “as is” basis,
* without warranty of any kind, either expressed, implied, or statutory,
* including, without limitation, warranties that the Covered Software
* is free of defects, merchantable, fit for a particular purpose or
* non-infringing. The entire risk as to the quality and performance of
* the Covered Software is with You. Should any Covered Software prove
* defective in any respect, You (not any Contributor) assume the cost
* of any necessary servicing, repair, or correction. This disclaimer
* of warranty constitutes an essential part of this License. No use of
* any Covered Software is authorized under this License except under
* this disclaimer.
*
* Under no circumstances and under no legal theory, whether tort
* (including negligence), contract, or otherwise, shall any Contributor,
* or anyone who distributes Covered Software as permitted above, be
* liable to You for any direct, indirect, special, incidental, or
* consequential damages of any character including, without limitation,
* damages for lost profits, loss of goodwill, work stoppage, computer
* failure or malfunction, or any and all other commercial damages or
* losses, even if such party shall have been informed of the possibility
* of such damages. This limitation of liability shall not apply to
* liability for death or personal injury resulting from such party’s
* negligence to the extent applicable law prohibits such limitation.
* Some jurisdictions do not allow the exclusion or limitation of
* incidental or consequential damages, so this exclusion and limitation
* may not apply to You.
*/
/***
* This is a bundled code. While it is not uglified, it may still be too
* complex for reviewing. Please refer to
* https://github.com/Xmader/bilitwin/
* for source code.
*/
var window = typeof unsafeWindow !== "undefined" && unsafeWindow || self
var top = window.top // workaround
/***
* Copyright (C) 2018 Qli5. All Rights Reserved.
*
* @author qli5 <goodlq11[at](163|gmail).com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Basically a Promise that exposes its resolve and reject callbacks
*/
class AsyncContainer {
/***
* The thing is, if we cannot cancel a promise, we should at least be able to
* explicitly mark a promise as garbage collectible.
*
* Yes, this is something like cancelable Promise. But I insist they are different.
*/
constructor(callback) {
// 1. primary promise
this.primaryPromise = new Promise((s, j) => {
this.resolve = arg => { s(arg); return arg; };
this.reject = arg => { j(arg); return arg; };
});
// 2. hang promise
this.hangReturn = Symbol();
this.hangPromise = new Promise(s => this.hang = () => s(this.hangReturn));
this.destroiedThen = this.hangPromise.then.bind(this.hangPromise);
this.primaryPromise.then(() => this.state = 'fulfilled');
this.primaryPromise.catch(() => this.state = 'rejected');
this.hangPromise.then(() => this.state = 'hanged');
// 4. race
this.promise = Promise
.race([this.primaryPromise, this.hangPromise])
.then(s => s == this.hangReturn ? new Promise(() => { }) : s);
// 5. inherit
this.then = this.promise.then.bind(this.promise);
this.catch = this.promise.catch.bind(this.promise);
this.finally = this.promise.finally.bind(this.promise);
// 6. optional callback
if (typeof callback == 'function') callback(this.resolve, this.reject);
}
/***
* Memory leak notice:
*
* The V8 implementation of Promise requires
* 1. the resolve handler of a Promise
* 2. the reject handler of a Promise
* 3. !! the Promise object itself !!
* to be garbage collectible to correctly free Promise runtime contextes
*
* This piece of code will work
* void (async () => {
* const buf = new Uint8Array(1024 * 1024 * 1024);
* for (let i = 0; i < buf.length; i++) buf[i] = i;
* await new Promise(() => { });
* return buf;
* })();
* if (typeof gc == 'function') gc();
*
* This piece of code will cause a Promise context mem leak
* const deadPromise = new Promise(() => { });
* void (async () => {
* const buf = new Uint8Array(1024 * 1024 * 1024);
* for (let i = 0; i < buf.length; i++) buf[i] = i;
* await deadPromise;
* return buf;
* })();
* if (typeof gc == 'function') gc();
*
* In other words, do NOT directly inherit from promise. You will need to
* dereference it on destroying.
*/
destroy() {
this.hang();
this.resolve = () => { };
this.reject = this.resolve;
this.hang = this.resolve;
this.primaryPromise = null;
this.hangPromise = null;
this.promise = null;
this.then = this.resolve;
this.catch = this.resolve;
this.finally = this.resolve;
this.destroiedThen = f => f();
/***
* For ease of debug, do not dereference hangReturn
*
* If run from console, mysteriously this tiny symbol will help correct gc
* before a console.clear
*/
//this.hangReturn = null;
}
static _UNIT_TEST() {
const containers = [];
async function foo() {
const buf = new Uint8Array(600 * 1024 * 1024);
for (let i = 0; i < buf.length; i++) buf[i] = i;
const ac = new AsyncContainer();
ac.destroiedThen(() => console.log('asyncContainer destroied'));
containers.push(ac);
await ac;
return buf;
}
const foos = [foo(), foo(), foo()];
containers.forEach(e => e.destroy());
console.warn('Check your RAM usage. I allocated 1.8GB in three dead-end promises.');
return [foos, containers];
}
}
/***
* Copyright (C) 2018 Qli5. All Rights Reserved.
*
* @author qli5 <goodlq11[at](163|gmail).com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Provides common util for all bilibili user scripts
*/
class BiliUserJS {
static async getPlayerWin() {
if (location.href.includes('/watchlater/#/list')) {
await new Promise(resolve => {
window.addEventListener('hashchange', () => resolve(location.href), { once: true });
});
}
if (!document.getElementById('bilibili-player')) {
if (document.querySelector("video")) {
top.location.reload(); // 刷新
} else {
await new Promise(resolve => {
const observer = new MutationObserver(() => {
if (document.getElementById('bilibili-player')) {
resolve(document.getElementById('bilibili-player'));
observer.disconnect();
}
});
observer.observe(document, { childList: true, subtree: true });
});
}
}
if (document.getElementById('bilibiliPlayer')) {
return window;
}
else {
return new Promise(resolve => {
const observer = new MutationObserver(() => {
if (document.getElementById('bilibiliPlayer')) {
observer.disconnect();
resolve(window);
}
});
observer.observe(document.getElementById('bilibili-player'), { childList: true });
});
}
}
static tryGetPlayerWinSync() {
if (document.getElementById('bilibiliPlayer')) {
return window;
}
else if (document.querySelector('#bofqi > object')) {
throw 'Need H5 Player';
}
}
static getCidRefreshPromise(playerWin) {
/***********
* !!!Race condition!!!
* We must finish everything within one microtask queue!
*
* bilibili script:
* videoElement.remove() -> setTimeout(0) -> [[microtask]] -> load playurl
* \- synchronous macrotask -/ || \- synchronous
* ||
* the only position to inject monkey.sniffDefaultFormat
*/
const cidRefresh = new AsyncContainer();
// 1. no active video element in document => cid refresh
const observer = new MutationObserver(() => {
if (!playerWin.document.getElementsByTagName('video')[0]) {
observer.disconnect();
cidRefresh.resolve();
}
});
observer.observe(playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
// 2. playerWin unload => cid refresh
playerWin.addEventListener('unload', () => Promise.resolve().then(() => cidRefresh.resolve()));
return cidRefresh;
}
static async domContentLoadedThen(func) {
if (document.readyState == 'loading') {
return new Promise(resolve => {
document.addEventListener('DOMContentLoaded', () => resolve(func()), { once: true });
})
}
else {
return func();
}
}
}
/**
* Copyright (C) 2018 Xmader.
* @author Xmader
*/
/**
* @template T
* @param {Promise<T>} promise
* @param {number} ms
* @returns {Promise< T | null >}
*/
const setTimeoutDo = (promise, ms) => {
/** @type {Promise<null>} */
const t = new Promise((resolve) => {
setTimeout(() => resolve(null), ms);
});
return Promise.race([promise, t])
};
/***
* Copyright (C) 2018 Qli5. All Rights Reserved.
*
* @author qli5 <goodlq11[at](163|gmail).com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* A promisified indexedDB with large file(>100MB) support
*/
class CacheDB {
constructor(dbName = 'biliMonkey', osName = 'flv', keyPath = 'name', maxItemSize = 100 * 1024 * 1024) {
// Neither Chrome or Firefox can handle item size > 100M
this.dbName = dbName;
this.osName = osName;
this.keyPath = keyPath;
this.maxItemSize = maxItemSize;
this.db = null;
}
async getDB() {
if (this.db) return this.db;
this.db = await new Promise((resolve, reject) => {
const openRequest = indexedDB.open(this.dbName);
openRequest.onupgradeneeded = e => {
const db = e.target.result;
if (!db.objectStoreNames.contains(this.osName)) {
db.createObjectStore(this.osName, { keyPath: this.keyPath });
}
};
openRequest.onsuccess = e => {
return resolve(e.target.result);
};
openRequest.onerror = reject;
});
return this.db;
}
async addData(item, name = item.name, data = item.data || item) {
if (!data instanceof Blob) throw 'CacheDB: data must be a Blob';
const itemChunks = [];
const numChunks = Math.ceil(data.size / this.maxItemSize);
for (let i = 0; i < numChunks; i++) {
itemChunks.push({
name: `${name}/part_${i}`,
numChunks,
data: data.slice(i * this.maxItemSize, (i + 1) * this.maxItemSize)
});
}
const reqCascade = new Promise(async (resolve, reject) => {
const db = await this.getDB();
const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
const onsuccess = e => {
const chunk = itemChunks.pop();
if (!chunk) return resolve(e);
const req = objectStore.add(chunk);
req.onerror = reject;
req.onsuccess = onsuccess;
};
onsuccess();
});
return reqCascade;
}
async putData(item, name = item.name, data = item.data || item) {
if (!data instanceof Blob) throw 'CacheDB: data must be a Blob';
const itemChunks = [];
const numChunks = Math.ceil(data.size / this.maxItemSize);
for (let i = 0; i < numChunks; i++) {
itemChunks.push({
name: `${name}/part_${i}`,
numChunks,
data: data.slice(i * this.maxItemSize, (i + 1) * this.maxItemSize)
});
}
const reqCascade = new Promise(async (resolve, reject) => {
const db = await this.getDB();
const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
const onsuccess = e => {
const chunk = itemChunks.pop();
if (!chunk) return resolve(e);
const req = objectStore.put(chunk);
req.onerror = reject;
req.onsuccess = onsuccess;
};
onsuccess();
});
return reqCascade;
}
async getData(name) {
const reqCascade = new Promise(async (resolve, reject) => {
const dataChunks = [];
const db = await this.getDB(); // 浏览器默认在隐私浏览模式中禁用 IndexedDB ,这一步会超时
const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
const probe = objectStore.get(`${name}/part_0`);
probe.onerror = reject;
probe.onsuccess = e => {
// 1. Probe fails => key does not exist
if (!probe.result) return resolve(null);
// 2. How many chunks to retrieve?
const { numChunks } = probe.result;
// 3. Cascade on the remaining chunks
const onsuccess = e => {
dataChunks.push(e.target.result.data);
if (dataChunks.length == numChunks) return resolve(dataChunks);
const req = objectStore.get(`${name}/part_${dataChunks.length}`);
req.onerror = reject;
req.onsuccess = onsuccess;
};
onsuccess(e);
};
});
// 浏览器默认在隐私浏览模式中禁用 IndexedDB ,添加超时
const dataChunks = await setTimeoutDo(reqCascade, 5 * 1000);
return dataChunks ? { name, data: new Blob(dataChunks) } : null;
}
async deleteData(name) {
const reqCascade = new Promise(async (resolve, reject) => {
let currentChunkNum = 0;
const db = await this.getDB();
const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
const probe = objectStore.get(`${name}/part_0`);
probe.onerror = reject;
probe.onsuccess = e => {
// 1. Probe fails => key does not exist
if (!probe.result) return resolve(null);
// 2. How many chunks to delete?
const { numChunks } = probe.result;
// 3. Cascade on the remaining chunks
const onsuccess = e => {
const req = objectStore.delete(`${name}/part_${currentChunkNum}`);
req.onerror = reject;
req.onsuccess = onsuccess;
currentChunkNum++;
if (currentChunkNum == numChunks) return resolve(e);
};
onsuccess();
};
});
return reqCascade;
}
async deleteEntireDB() {
const req = indexedDB.deleteDatabase(this.dbName);
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(this.db = null);
req.onerror = reject;
});
}
static async _UNIT_TEST() {
let db = new CacheDB();
console.warn('Storing 201MB...');
console.log(await db.putData(new Blob([new ArrayBuffer(201 * 1024 * 1024)]), 'test'));
console.warn('Deleting 201MB...');
console.log(await db.deleteData('test'));
}
}
/***
* Copyright (C) 2018 Qli5. All Rights Reserved.
*
* @author qli5 <goodlq11[at](163|gmail).com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* A more powerful fetch with
* 1. onprogress handler
* 2. partial response getter
*/
class DetailedFetchBlob {
constructor(input, init = {}, onprogress = init.onprogress, onabort = init.onabort, onerror = init.onerror, fetch = init.fetch || top.fetch) {
// Fire in the Fox fix
if (this.firefoxConstructor(input, init, onprogress, onabort, onerror)) return;
// Now I know why standardizing cancelable Promise is that difficult
// PLEASE refactor me!
this.onprogress = onprogress;
this.onabort = onabort;
this.onerror = onerror;
this.abort = null;
this.loaded = init.cacheLoaded || 0;
this.total = init.cacheLoaded || 0;
this.lengthComputable = false;
this.buffer = [];
this.blob = null;
this.reader = null;
this.blobPromise = fetch(input, init).then(/** @param {Response} res */ res => {
if (this.reader == 'abort') return res.body.getReader().cancel().then(() => null);
if (!res.ok) throw `HTTP Error ${res.status}: ${res.statusText}`;
this.lengthComputable = res.headers.has('Content-Length');
this.total += parseInt(res.headers.get('Content-Length')) || Infinity;
if (this.lengthComputable) {
this.reader = res.body.getReader();
return this.blob = this.consume();
}
else {
if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
return this.blob = res.blob();
}
});
this.blobPromise.then(() => this.abort = () => { });
this.blobPromise.catch(e => this.onerror({ target: this, type: e }));
this.promise = Promise.race([
this.blobPromise,
new Promise(resolve => this.abort = () => {
this.onabort({ target: this, type: 'abort' });
resolve('abort');
this.buffer = [];
this.blob = null;
if (this.reader) this.reader.cancel();
else this.reader = 'abort';
})
]).then(s => s == 'abort' ? new Promise(() => { }) : s);
this.then = this.promise.then.bind(this.promise);
this.catch = this.promise.catch.bind(this.promise);
}
getPartialBlob() {
return new Blob(this.buffer);
}
async getBlob() {
return this.promise;
}
async pump() {
while (true) {
let { done, value } = await this.reader.read();
if (done) return this.loaded;
this.loaded += value.byteLength;
this.buffer.push(new Blob([value]));
if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
}
}
async consume() {
await this.pump();
this.blob = new Blob(this.buffer);
this.buffer = null;
return this.blob;
}
firefoxConstructor(input, init = {}, onprogress = init.onprogress, onabort = init.onabort, onerror = init.onerror) {
if (!top.navigator.userAgent.includes('Firefox')) return false;
const firefoxVersionM = top.navigator.userAgent.match(/Firefox\/(\d+)/);
const firefoxVersion = firefoxVersionM && +firefoxVersionM[1];
if (firefoxVersion >= 65) {
// xhr.responseType "moz-chunked-arraybuffer" is deprecated since Firefox 68
// but res.body is implemented since Firefox 65
return false
}
this.onprogress = onprogress;
this.onabort = onabort;
this.onerror = onerror;
this.abort = null;
this.loaded = init.cacheLoaded || 0;
this.total = init.cacheLoaded || 0;
this.lengthComputable = false;
this.buffer = [];
this.blob = null;
this.reader = undefined;
this.blobPromise = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.responseType = 'moz-chunked-arraybuffer';
xhr.onload = () => { resolve(this.blob = new Blob(this.buffer)); this.buffer = null; };
let cacheLoaded = this.loaded;
xhr.onprogress = e => {
this.loaded = e.loaded + cacheLoaded;
this.total = e.total + cacheLoaded;
this.lengthComputable = e.lengthComputable;
this.buffer.push(new Blob([xhr.response]));
if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
};
xhr.onabort = e => this.onabort({ target: this, type: 'abort' });
xhr.onerror = e => { this.onerror({ target: this, type: e.type }); reject(e); };
this.abort = xhr.abort.bind(xhr);
xhr.open(init.method || 'get', input);
if (init.headers) {
Object.entries(init.headers).forEach(([header, value]) => {
xhr.setRequestHeader(header, value);
});
}
xhr.send();
});
this.promise = this.blobPromise;
this.then = this.promise.then.bind(this.promise);
this.catch = this.promise.catch.bind(this.promise);
return true;
}
}
/***
* Copyright (C) 2018 Qli5. All Rights Reserved.
*
* @author qli5 <goodlq11[at](163|gmail).com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* A simple emulation of pthread_mutex
*/
class Mutex {
constructor() {
this.queueTail = Promise.resolve();
this.resolveHead = null;
}
/**
* await mutex.lock = pthread_mutex_lock
* @returns a promise to be resolved when the mutex is available
*/
async lock() {
let myResolve;
let _queueTail = this.queueTail;
this.queueTail = new Promise(resolve => myResolve = resolve);
await _queueTail;
this.resolveHead = myResolve;
return;
}
/**
* mutex.unlock = pthread_mutex_unlock
*/
unlock() {
this.resolveHead();
return;
}
/**
* lock, ret = await async, unlock, return ret
* @param {(Function|Promise)} promise async thing to wait for
*/
async lockAndAwait(promise) {
await this.lock();
let ret;
try {
if (typeof promise == 'function') promise = promise();
ret = await promise;
}
finally {
this.unlock();
}
return ret;
}
static _UNIT_TEST() {
let m = new Mutex();
function sleep(time) {
return new Promise(r => setTimeout(r, time));
}
m.lockAndAwait(() => {
console.warn('Check message timestamps.');
console.warn('Bad:');
console.warn('1 1 1 1 1:5s');
console.warn(' 1 1 1 1 1:10s');
console.warn('Good:');
console.warn('1 1 1 1 1:5s');
console.warn(' 1 1 1 1 1:10s');
});
m.lockAndAwait(async () => {
await sleep(1000);
await sleep(1000);
await sleep(1000);
await sleep(1000);
await sleep(1000);
});
m.lockAndAwait(async () => console.log('5s!'));
m.lockAndAwait(async () => {
await sleep(1000);
await sleep(1000);
await sleep(1000);
await sleep(1000);
await sleep(1000);
});
m.lockAndAwait(async () => console.log('10s!'));
}
}
/**
* @typedef DanmakuColor
* @property {number} r
* @property {number} g
* @property {number} b
*/
/**
* @typedef Danmaku
* @property {string} text
* @property {number} time
* @property {string} mode
* @property {number} size
* @property {DanmakuColor} color
* @property {boolean} bottom
* @property {string=} sender
*/
const parser = {};
/**
* @param {Danmaku} danmaku
* @returns {boolean}
*/
const danmakuFilter = danmaku => {
if (!danmaku) return false;
if (!danmaku.text) return false;
if (!danmaku.mode) return false;
if (!danmaku.size) return false;
if (danmaku.time < 0 || danmaku.time >= 360000) return false;
return true;
};
const parseRgb256IntegerColor = color => {
const rgb = parseInt(color, 10);
const r = (rgb >>> 4) & 0xff;
const g = (rgb >>> 2) & 0xff;
const b = (rgb >>> 0) & 0xff;
return { r, g, b };
};
const parseNiconicoColor = mail => {
const colorTable = {
red: { r: 255, g: 0, b: 0 },
pink: { r: 255, g: 128, b: 128 },
orange: { r: 255, g: 184, b: 0 },
yellow: { r: 255, g: 255, b: 0 },
green: { r: 0, g: 255, b: 0 },
cyan: { r: 0, g: 255, b: 255 },
blue: { r: 0, g: 0, b: 255 },
purple: { r: 184, g: 0, b: 255 },
black: { r: 0, g: 0, b: 0 },
};
const defaultColor = { r: 255, g: 255, b: 255 };
const line = mail.toLowerCase().split(/\s+/);
const color = Object.keys(colorTable).find(color => line.includes(color));
return color ? colorTable[color] : defaultColor;
};
const parseNiconicoMode = mail => {
const line = mail.toLowerCase().split(/\s+/);
if (line.includes('ue')) return 'TOP';
if (line.includes('shita')) return 'BOTTOM';
return 'RTL';
};
const parseNiconicoSize = mail => {
const line = mail.toLowerCase().split(/\s+/);
if (line.includes('big')) return 36;
if (line.includes('small')) return 16;
return 25;
};
/**
* @param {string|ArrayBuffer} content
* @return {{ cid: number, danmaku: Array<Danmaku> }}
*/
parser.bilibili = function (content) {
const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
const clean = text.replace(/(?:[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g, '').replace(/.*?\?>/,"");
const data = (new DOMParser()).parseFromString(clean, 'text/xml');
const cid = +data.querySelector('chatid,oid').textContent;
/** @type {Array<Danmaku>} */
const danmaku = Array.from(data.querySelectorAll('d')).map(d => {
const p = d.getAttribute('p');
const [time, mode, size, color, create, bottom, sender, id] = p.split(',');
return {
text: d.textContent,
time: +time,
// We do not support ltr mode
mode: [null, 'RTL', 'RTL', 'RTL', 'BOTTOM', 'TOP'][+mode],
size: +size,
color: parseRgb256IntegerColor(color),
bottom: bottom > 0,
sender,
};
}).filter(danmakuFilter);
return { cid, danmaku };
};
/**
* @param {string|ArrayBuffer} content
* @return {{ cid: number, danmaku: Array<Danmaku> }}
*/
parser.acfun = function (content) {
const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
const data = JSON.parse(text);
const list = data.reduce((x, y) => x.concat(y), []);
const danmaku = list.map(line => {
const [time, color, mode, size, sender, create, uuid] = line.c.split(','), text = line.m;
return {
text,
time: +time,
color: parseRgb256IntegerColor(+color),
mode: [null, 'RTL', null, null, 'BOTTOM', 'TOP'][mode],
size: +size,
bottom: false,
uuid,
};
}).filter(danmakuFilter);
return { danmaku };
};
/**
* @param {string|ArrayBuffer} content
* @return {{ cid: number, danmaku: Array<Danmaku> }}
*/
parser.niconico = function (content) {
const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
const data = JSON.parse(text);
const list = data.map(item => item.chat).filter(x => x);
const { thread } = list.find(comment => comment.thread);
const danmaku = list.map(comment => {
if (!comment.content || !(comment.vpos >= 0) || !comment.no) return null;
const { vpos, mail = '', content, no } = comment;
return {
text: content,
time: vpos / 100,
color: parseNiconicoColor(mail),
mode: parseNiconicoMode(mail),
size: parseNiconicoSize(mail),
bottom: false,
id: no,
};
}).filter(danmakuFilter);
return { thread, danmaku };
};
const font = {};
// Meansure using canvas
font.textByCanvas = function () {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
return function (fontname, text, fontsize) {
context.font = `bold ${fontsize}px ${fontname}`;
return Math.ceil(context.measureText(text).width);
};
};
// Meansure using <div>
font.textByDom = function () {
const container = document.createElement('div');
container.setAttribute('style', 'all: initial !important');
const content = document.createElement('div');
content.setAttribute('style', [
'top: -10000px', 'left: -10000px',
'width: auto', 'height: auto', 'position: absolute',
].map(item => item + ' !important;').join(' '));
const active = () => { document.body.parentNode.appendChild(content); };
if (!document.body) document.addEventListener('DOMContentLoaded', active);
else active();
return (fontname, text, fontsize) => {
content.textContent = text;
content.style.font = `bold ${fontsize}px ${fontname}`;
return content.clientWidth;
};
};
font.text = (function () {
// https://bugzilla.mozilla.org/show_bug.cgi?id=561361
if (/linux/i.test(navigator.platform)) {
return font.textByDom();
} else {
return font.textByCanvas();
}
}());
font.valid = (function () {
const cache = new Map();
const textWidth = font.text;
// Use following texts for checking
const sampleText = [
'The quick brown fox jumps over the lazy dog',
'7531902468', ',.!-', ',。:!',
'天地玄黄', '則近道矣',
'あいうえお', 'アイウエオガパ', 'アイウエオガパ',
].join('');
// Some given font family is avaliable iff we can meansure different width compared to other fonts
const sampleFont = [
'monospace', 'sans-serif', 'sans',
'Symbol', 'Arial', 'Comic Sans MS', 'Fixed', 'Terminal',
'Times', 'Times New Roman',
'SimSum', 'Microsoft YaHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei',
'Pmingliu', 'Microsoft JhengHei', 'PingFang TC', 'Heiti TC',
'MS Gothic', 'Meiryo', 'Hiragino Kaku Gothic Pro', 'Hiragino Mincho Pro',
];
const diffFont = function (base, test) {
const baseSize = textWidth(base, sampleText, 72);
const testSize = textWidth(test + ',' + base, sampleText, 72);
return baseSize !== testSize;
};
const validFont = function (test) {
if (cache.has(test)) return cache.get(test);
const result = sampleFont.some(base => diffFont(base, test));
cache.set(test, result);
return result;
};
return validFont;
}());
const rtlCanvas = function (options) {
const {
resolutionX: wc, // width of canvas
resolutionY: hc, // height of canvas
bottomReserved: b, // reserved bottom height for subtitle
rtlDuration: u, // duration appeared on screen
maxDelay: maxr, // max allowed delay
} = options;
// Initial canvas border
let used = [
// p: top
// m: bottom
// tf: time completely enter screen
// td: time completely leave screen
// b: allow conflict with subtitle
// add a fake danmaku for describe top of screen
{ p: -Infinity, m: 0, tf: Infinity, td: Infinity, b: false },
// add a fake danmaku for describe bottom of screen
{ p: hc, m: Infinity, tf: Infinity, td: Infinity, b: false },
// add a fake danmaku for placeholder of subtitle
{ p: hc - b, m: hc, tf: Infinity, td: Infinity, b: true },
];
// Find out some position is available
const available = (hv, t0s, t0l, b) => {
const suggestion = [];
// Upper edge of candidate position should always be bottom of other danmaku (or top of screen)
used.forEach(i => {
if (i.m + hv >= hc) return;
const p = i.m;
const m = p + hv;
let tas = t0s;
let tal = t0l;
// and left border should be right edge of others
used.forEach(j => {
if (j.p >= m) return;
if (j.m <= p) return;
if (j.b && b) return;
tas = Math.max(tas, j.tf);
tal = Math.max(tal, j.td);
});
const r = Math.max(tas - t0s, tal - t0l);
if (r > maxr) return;
// save a candidate position
suggestion.push({ p, r });
});
// sorted by its vertical position
suggestion.sort((x, y) => x.p - y.p);
let mr = maxr;
// the bottom and later choice should be ignored
const filtered = suggestion.filter(i => {
if (i.r >= mr) return false;
mr = i.r;
return true;
});