-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhr_hook.js
1669 lines (1558 loc) · 77.1 KB
/
xhr_hook.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
(function () {
'use strict'
if (XMLHttpRequest.prototype.pakku_open) return;
let console = {};
(() => {
Object.keys(window.console).forEach(functionName => {
if (typeof window.console[functionName] == "function") {
console[functionName] = window.console[functionName]
}
})
console.log('disable sentry')
})();
let setting = {}
postExtension("getSetting").then(function (result) {
setting = result.setting
})
//postHook Listener
window.addEventListener("message", function (event) {
if (event.source !== window || !event.data || !event.data.type) return;
switch (event.data.type) {
case "replaceLoadPage": {
console.log('replaceLoadPage')
buildLoadPage(event.data.youtube)
break
}
case "pakku_ajax_response": {
callbacks[event.data.arg](event.data.resp);
delete callbacks[event.data.arg]
break
}
case "load_danmaku": {
window.top.closure.loadDanmu(event.data.ldanmu)
break
}
case "load_comment_art": {
loadNicoCommentArt(event.data.ldanmu)
break
}
}
}, false);
async function postExtension(messageType, data = null, hasCallback = true) {
let timeStamp = new Date().getTime();
if (!data) data = {}
data.type = messageType
data.timeStamp = timeStamp
data.source = 'DFex'
data.hasCallback = hasCallback
window.postMessage(data, "*");
if (hasCallback) {
return await new Promise((resolve) => {
let handle = (event) => {
if (event.source === window && event.data && event.data.type === messageType + '_response' && event.data.timeStamp === timeStamp) {
window.removeEventListener('message', handle)
resolve(event.data.content)
}
}
window.addEventListener("message", handle, false);
})
}
}
let callbacksAfterDanmakuRequest = [biliEvolvedPlugin,];
let callbacks = {};
let loadedSegmentList = [];
let currentCid = null;
(function pakkuXhrHook() {
async function hasLoadDanmu() {
await new Promise((resolve) => setTimeout(resolve, 1));
if (window.top.closure && window.top.closure.loadDanmu) {
return true
}
}
// https://github.com/xmcp/pakku.js/blob/master/pakkujs/assets/xhr_hook.js
XMLHttpRequest.prototype.pakku_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
this.pakku_url = url;
return this.pakku_open(method, url, async === undefined ? true : async, user, password);
};
XMLHttpRequest.prototype.pakku_addEventListener = XMLHttpRequest.prototype.addEventListener;
XMLHttpRequest.prototype.addEventListener = function (name, callback) {
if (name === "load" || name === 'readystatechange' || name === 'loadend') {
this.pakku_load_callback = this.pakku_load_callback || [];
this.pakku_load_callback.push(callback);
}
return this.pakku_addEventListener(name, callback);
};
XMLHttpRequest.prototype.pakku_send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = (function () {
function uint8array_to_arraybuffer(array) {
// https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
}
function str_to_arraybuffer(str) {
// https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
let buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
let bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function byte_object_to_arraybuffer(obj) {
let ks = Object.keys(obj);
let buf = new ArrayBuffer(ks.length);
let bufView = new Uint8Array(buf);
ks.forEach(function (i) {
bufView[i] = obj[i];
});
return buf;
}
async function send_msg_proxy(arg, callback, type = "pakku_ajax_request") {
callbacks[arg] = callback;
window.postMessage({
type: type, arg: arg, loadDanmu: await hasLoadDanmu()
}, "*");
}
return function (arg) {
let that = this
function callback(resp) {
if (!resp || !resp.data) return that.pakku_send(arg);
Object.defineProperty(that, "response", {
writable: true
});
Object.defineProperty(that, "responseText", {
writable: true
});
Object.defineProperty(that, "readyState", {
writable: true
});
Object.defineProperty(that, "status", {
writable: true
});
Object.defineProperty(that, "statusText", {
writable: true
});
Object.defineProperty(that, "responseURL", {
writable: true
});
if (that.responseType === 'arraybuffer') {
if (resp.data instanceof Uint8Array) that.response = uint8array_to_arraybuffer(resp.data); else if (resp.data instanceof Object) // uint8arr object representation {0: ord, 1: ord, ...}
that.response = byte_object_to_arraybuffer(resp.data); else // maybe str
that.response = str_to_arraybuffer(resp.data);
that.responseURL = 'file:'
} else {
that.response = that.responseText = resp.data;
}
// console.log(resp.data)
that.readyState = 4;
that.status = 200;
that.statusText = "Pakku OK";
that.responseURL = that.pakku_url
console.log("pakku ajax: got tampered response for", that.pakku_url);
that.pakku_load_callback = that.pakku_load_callback || [];
if (that.onreadystatechange) that.pakku_load_callback.push(that.onreadystatechange);
if (that.onload) that.pakku_load_callback.push(that.onload);
if (that.onloadend) that.pakku_load_callback.push(that.onloadend);
if (that.pakku_load_callback.length > 0) {
for (let i = 0; i < that.pakku_load_callback.length; i++) that.pakku_load_callback[i].bind(that)();
}
}
if (this.pakku_url.indexOf('seg.so') !== -1 && this.pakku_url.indexOf('segment_index') !== -1 && this.pakku_url.indexOf('data.bilibili.com') === -1) {
while (callbacksAfterDanmakuRequest.length !== 0) {
let callback = callbacksAfterDanmakuRequest.pop()
callback()
}
// || this.pakku_url.indexOf('web-interface/view') !== -1) {
// injectUI()
let link = document.createElement("a");
link.href = this.pakku_url;
this.pakku_url = link.href;
let that = this;
let cid = /oid=(\d+)/.exec(that.pakku_url)[1]
console.log(currentCid, '/', cid)
if (cid !== currentCid) {
currentCid = cid
console.log('cid changed,clear')
clearNicoComment()
loadedSegmentList = []
}
if (this.pakku_load_callback || this.onreadystatechange !== null) {
send_msg_proxy(that.pakku_url, callback);
} else {
console.log("pakku ajax: ignoring request as no onload callback found", this.pakku_url);
return that.pakku_send(arg);
}
} else if (youtubeManager.loadComment && this.pakku_url.indexOf("x/v2/reply") !== -1) {
youtubeManager.loadComment(this.pakku_url).then(callback).catch((e) => {
console.log(e, e.stack)
return this.pakku_send(arg)
})
} else {
let cacheUrlList = [{
type: 'season', pattern: 'season?ep_id'
}, {
type: 'view', pattern: 'view?aid='
}]
let url = this.pakku_url
for (let cache of cacheUrlList) {
if (url.indexOf(cache.pattern) !== -1) {
this.addEventListener('readystatechange', function (s) {
if (4 === s.target.readyState) {
window.postMessage({
type: 'cacheUrl', url: url, urlType: cache.type, data: s.target.response,
}, "*");
}
})
}
}
return this.pakku_send(arg)
}
};
})();
return true
})();
(function closureExpose() {
function hookAttr(obj, property) {
obj["_" + property] = obj[property]
Object.defineProperty(obj, property, {
set: function (value) {
debugger; // trigger the debugger when the value is set
this["_" + property] = value;
}, get: function () {
return this["_" + property];
}
});
}
let danmakuPlayerCallback = function () {
window.top.closure.loadDanmu = function (ldanmu) {
console.log('loadDanmu', ldanmu)
let temp = []
for (let danmu of ldanmu) {
let obj = {
attr: 0,
color: danmu.color,
date: danmu.ctime,
mode: danmu.mode,
size: danmu.fontsize,
stime: danmu.progress,
text: danmu.content,
uhash: danmu.midHash,
weight: danmu.weight ? danmu.weight : 8,
dmid: danmu.id.toString(),
}
// hookAttr(obj, "attr")
temp.push(obj)
}
ldanmu = temp
if (window.top.closure.danmakuPlayer.dmListStore && window.top.closure.danmakuPlayer.dmListStore.appendDm) {
window.top.closure.danmakuPlayer.dmListStore.appendDm(ldanmu)
window.top.closure.danmakuPlayer.dmListStore.refresh()
} else {
//add at 2022.12.16
window.top.closure.danmakuPlayer.danmaku.addList(ldanmu)
}
if (window.top.closure.danmakuScroll) {
window.top.closure.danmakuScroll.toinit()
}
};
setInterval(async function () {
if (window.top.player && currentCid) {
let currentTime = window.top.player.getCurrentTime()
let segmentIndex = Math.ceil((currentTime) / 360)
if (segmentIndex !== 0 && !loadedSegmentList.includes(segmentIndex)) {
loadedSegmentList.push(segmentIndex)
console.log('postExtension("actualSegment")')
await postExtension("actualSegment", {'segmentIndex': segmentIndex})
}
if (currentTime + 30 > segmentIndex * 360 && !loadedSegmentList.includes(segmentIndex + 1)) {
loadedSegmentList.push(segmentIndex + 1)
console.log('postExtension("actualSegment")')
await postExtension("actualSegment", {'segmentIndex': segmentIndex + 1})
}
}
}, 1000)
}
let injectList = [{
type: 'webpack',
keyword: 'initDanmaku()',
target: 'danmakuPlayer',
replaceList: [[',this.initDanmaku()', ',this.initDanmaku(),$inject,console.log(this)']],
callback: danmakuPlayerCallback
}, {
type: 'webpack',
keyword: 'firstPb',
target: 'danmakuPlayer',
replaceList: [['this.allDM=', '\nwindow.top.closure.danmakuPlayer=this.player,console.log(this),this.allDM=']],
callback: function () {
window.top.closure.loadDanmu = function (ldanmu) {
console.log('loadDanmu', ldanmu)
window.top.closure.danmakuPlayer.danmaku.loadPb.appendDm(ldanmu)
if (window.top.closure.danmakuScroll) {
window.top.closure.danmakuScroll.toinit()
}
}
}
}, {
type: 'webpack',
keyword: '弹幕列表',
target: 'danmakuScroll',
replaceList: [['this.danmaku.style.display="block",', 'this.danmaku.style.display = "block",$inject,']]
}]
let coreInjector = {
type: 'core',
target: 'danmakuPlayer',
replaceList: [[',t.prototype.loadDmPb=function(e,t){var r=this;', ',t.prototype.loadDmPb=function(e,t){var r=this;$inject;'],],
callback: danmakuPlayerCallback
}
function doReplace(injectedFunction, injector, injectIndex) {
let injected = false
for (let r of injector.replaceList) {
if (typeof r === 'string') {
throw injector
}
let [src, dst] = r
if (dst.includes("$inject")) {
dst = dst.replace("$inject", `window.top.closure.setValue("${injector.target}",this,${injectIndex})`)
}
if (injectedFunction.indexOf(src) === -1) {
console.log('inject for', src, 'not found')
} else {
injected = true
console.log('replace ', src)
injectedFunction = injectedFunction.replace(src, dst)
}
}
if (injected) {
if (injector.callback) {
if (injector.target) {
if (!window.top.closure['_' + injector.target]) {
window.top.closure['_' + injector.target] = {}
}
window.top.closure['_' + injector.target][injectIndex] = injector.callback
} else {
injector.callback()
}
}
return injectedFunction
} else return null;
}
(function initClosure() {
if (!window.top.closure) {
window.top.closure = {}
for (let injector of injectList) {
if (injector.target) {
window.top.closure[injector.target] = null
}
}
for (let key of Object.keys(window.top.closure)) {
Object.defineProperty(window.top.closure, key, {
set: function (value) {
let callback = window.top.closure['_' + key]
window.top.closure['_' + key] = value
if (callback) {
callback()
}
}, get: function () {
return window.top.closure['_' + key]
}
})
}
window.closure.setValue = function (name, value, injectIndex) {
if (window.top.closure['_' + name][injectIndex]) {
window.top.closure['_' + name][injectIndex]()
}
window.top.closure['_' + name] = value
}
}
})();
(function injectCore() {
function redefine() {
window._customElements = window.customElements
Object.defineProperty(window, 'customElements', {
get: function () {
let stack = new Error().stack
if (stack.includes('static/player/main/core.')) {
console.log("disable customElements for core", stack)
return null
} else {
return window._customElements
}
}
})
}
function main() {
// 创建 MutationObserver 对象
let handle = mutations => {
// 遍历每一个 DOM 变化
mutations.forEach(mutation => {
// 遍历每一个新添加到页面的节点
mutation.addedNodes.forEach(node => {
// 判断节点是否为 <script> 元素
if (node.tagName === 'SCRIPT' && node.src.includes('static/player/main/core.')) {
//为了在页面元素的script执行前覆盖,使用同步逻辑
const xhr = new XMLHttpRequest();
xhr.open("get", node.src, false);
xhr.send()
let content = xhr.responseText
content = doReplace(content, coreInjector, -1)
console.log('replace core', node)
window.top.eval(content)
redefine()
observer.disconnect()
// 在这里添加你的代码来阻止该脚本被执行
// node.remove(); // 删除该 <script> 元素
}
});
});
}
const observer = new MutationObserver(handle);
// 配置 MutationObserver 监听 DOM 的变化
observer.observe(document.documentElement, {
childList: true, subtree: true
});
}
main()
})();
(function injectWebpack() {
function inject(widgetsJsonp, widgetsJsonpString) {
widgetsJsonp.pakku_push = widgetsJsonp.push
widgetsJsonp.push = function (obj) {
widgetsJsonp.pakku_push(obj)
for (let prop in obj[1]) {
let injectedFunction = obj[1][prop].toString()
try {
let injectIndex = -1
let injected = false
for (let injector of injectList) {
if (injector.type !== 'webpack') continue
injectIndex += 1
if (obj[1][prop].toString().indexOf(injector.keyword) !== -1) {
console.log(prop, obj[1], injector.keyword)
injectedFunction = doReplace(injectedFunction, injector, injectIndex)
injected = true
}
}
if (injected && injectedFunction) {
try {
window.top.eval(`window.top.${widgetsJsonpString}[window.top.${widgetsJsonpString}.length-1][1][${prop}]=` + injectedFunction)
} catch (e) {
console.log(e)
console.log(e.stack)
}
}
} catch (e) {
console.log(e, window.top, window)
}
}
}
}
function hookFunction(target, functionName, newFunction) {
let __pakku_origin__ = target[functionName]
target[functionName] = function () {
newFunction.apply(target, arguments)
__pakku_origin__.apply(target, arguments)
}
}
function main() {
if (window.location.href.indexOf('https://www.bilibili.com/bangumi') === -1 && window.location.href.indexOf('https://www.bilibili.com/video') === -1) {
return;
}
try {
if (window.top.closure && window.top.closure.danmakuPlayer) return;
} catch (e) {
console.log(e)
return;
}
let widgetsJsonpString = null
let widgetsJsonp
for (let webpack of ['nanoWidgetsJsonp', 'videoWidgetsJsonP']) {
if (window.top[webpack]) {
widgetsJsonpString = webpack
widgetsJsonp = window.top[webpack]
}
}
if (!widgetsJsonpString) {
for (let webpack of ['nanoWidgetsJsonp', 'videoWidgetsJsonP']) {
Object.defineProperty(window.top, webpack, {
set: function (value) {
window.top['_' + webpack] = value
if (!window.top['_' + webpack].pakku_push) {
inject(value, webpack)
console.log('webpack set, do inject', value)
}
}, get: function () {
return window.top['_' + webpack]
}
})
}
return;
} else {
console.log('closureExpose: hook webpack', (widgetsJsonp.length), widgetsJsonp)
inject(widgetsJsonp, widgetsJsonpString)
}
}
main()
})();
})();
async function parse(url, json = false) {
let res = await postExtension('parse', {url: url})
console.log(res)
if (json) {
return JSON.parse(res)
} else {
return res
}
}
async function biliEvolvedPlugin() {
function copySidebar() {
let translateX = setting.hideSidebar ? '-90' : '-50'
let sideBarHtml = `<style type="text/css">
.be-settings {
line-height: normal;
font-size: 12px;
--panel-height: calc(100vh - 120px);
}
.be-settings > .sidebar {
position: fixed;
top: 50%;
z-index: 1002;
transform: translateX(calc(${translateX}% * var(--direction))) translateY(-50%);
}
body:not(.settings-panel-dock-right) .be-settings {
--direction: 1;
}
.be-settings > .sidebar > * {
transition: transform 0.3s ease-out, opacity 0.3s ease-out;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
width: 26px;
height: 26px;
padding: 8px;
box-sizing: content-box;
background-color: rgba(255, 255, 255, 0.6666666667);
border-radius: 50%;
position: relative;
}
.be-settings > .sidebar > *:not(:last-child) {
margin-bottom: 26px;
}
.be-settings > .sidebar > *::after {
content: "";
width: 140%;
height: 140%;
position: absolute;
top: -20%;
left: -20%;
background: transparent;
}
.be-settings > .sidebar > * .be-icon {
font-size: 26px;
color: #888;
fill: #888;
transition: fill 0.3s ease-out;
}
.be-settings > .sidebar > *:hover {
transform: translateX(calc(60% * var(--direction))) scale(1.1);
background-color: #fff;
}
.be-settings > .sidebar > *:hover .be-icon {
color: #222;
fill: #222;
}
.be-settings > .sidebar > *.open {
transform: translateX(calc(100% * var(--direction))) scale(1.5);
opacity: 0;
}
body:not(.settings-panel-dock-right) .be-settings > .sidebar {
left: 0;
}
body:not(.settings-panel-dock-right) .settings-panel-popup .settings-panel-content .sidebar {
border-right: 1px solid rgba(136, 136, 136, 0.1333333333);
}
body.settings-panel-dock-right {
--direction: -1;
}
body.settings-panel-dock-right .be-settings > .sidebar {
right: 0;
}
body.settings-panel-dock-right .settings-panel-popup .settings-panel-content .sidebar {
order: 1;
border-left: 1px solid rgba(136, 136, 136, 0.1333333333);
}
</style>
<div class="be-settings">
<div class="sidebar">
</div>
</div>
`
document.body.insertAdjacentHTML('beforeend', sideBarHtml)
let sideBar = document.body.querySelector('[class="sidebar"]')
if (!setting.hideSidebar) {
let html = `
<div title="完全收起侧边栏" id="dfex-hide-sidebar"><i class="be-icon" style="--size:26px;">
<div class="custom-icon">
<svg fill="#000000" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M8.70710678,12 L19.5,12 C19.7761424,12 20,12.2238576 20,12.5 C20,12.7761424 19.7761424,13 19.5,13 L8.70710678,13 L11.8535534,16.1464466 C12.0488155,16.3417088 12.0488155,16.6582912 11.8535534,16.8535534 C11.6582912,17.0488155 11.3417088,17.0488155 11.1464466,16.8535534 L7.14644661,12.8535534 C6.95118446,12.6582912 6.95118446,12.3417088 7.14644661,12.1464466 L11.1464466,8.14644661 C11.3417088,7.95118446 11.6582912,7.95118446 11.8535534,8.14644661 C12.0488155,8.34170876 12.0488155,8.65829124 11.8535534,8.85355339 L8.70710678,12 L8.70710678,12 Z M4,5.5 C4,5.22385763 4.22385763,5 4.5,5 C4.77614237,5 5,5.22385763 5,5.5 L5,19.5 C5,19.7761424 4.77614237,20 4.5,20 C4.22385763,20 4,19.7761424 4,19.5 L4,5.5 Z"/>
</svg>
</div>
</i></div>
`
sideBar.insertAdjacentHTML('beforeend', html)
let hideButton = sideBar.querySelector('[id="dfex-hide-sidebar"]')
hideButton.addEventListener("click", function () {
hideButton.title = '已收起'
postExtension("editSetting", {'key': 'hideSidebar', 'value': true})
})
sideBar.appendChild(hideButton)
}
return sideBar
}
function popupWindow() {
let html = `
<div id="dfex-window">
<style type="text/css">
#dfex-window {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 320px;
height: 200px;
background-color: white;
box-shadow: rgb(51, 51, 51) 0px 0px 10px 0px;
z-index: 99999;
}
#dfex-close {
position: absolute;
right: 2px;
top: 2px;
background-color: transparent;
border: none;
outline: none;
cursor: pointer;
}
#dfex-center {
position: absolute;
left: 10px;
top: 10px;
width: 90%;
height: 90%;
}
</style>
<div id="dfex-center">
</div>
<button id="dfex-close">
<svg width="20px" height="20px" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#000000" d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"/></svg>
</button>
</div>
`
document.body.insertAdjacentHTML('beforeend', html)
let window = document.querySelector('[id="dfex-window"]')
window.querySelector('[id="dfex-close"]').addEventListener('click', function () {
document.body.removeChild(window)
})
window.center = window.querySelector('[id="dfex-center"]')
document.body.appendChild(window);
return window
};
async function main() {
let i = 0, sideBar
if (document.querySelector('[id="custom-navbar-style"]') || document.querySelector('[id="auto-hide-sidebar"]')) {
while (!sideBar && i < 25) {
i += 1
sideBar = document.querySelector("body > div.be-settings > div.sidebar")
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
if (!sideBar) {
sideBar = copySidebar()
}
console.log('sideBar', sideBar)
let htmlText = `
<div title="加载本地弹幕" class="dfex-upload"><i class="be-icon" style="--size:26px;">
<div class="custom-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1920 1920">
<path d="m1838.86 1451.576 81.14 81.37-361.566 361.566H361.566L0 1532.946l81.255-81.37 327.891 328.007h1101.708l328.006-328.007ZM962.333 25l500.285 500.285-81.14 81.37-361.795-361.681v1187.559H904.869V244.973L543.188 606.655l-81.14-81.37L962.333 25Z"
fill-rule="evenodd"/>
</svg>
</div>
</i></div>
<div title="绑定外站视频" class="dfex-bind"><i class="be-icon" style="--size:26px;">
<div class="custom-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1920 1920">
<path d="M1866.003 351.563 1565.128 50.575c-69.46-67.652-180.932-67.426-248.923.565L906.23 461.116c-68.33 68.443-68.33 179.69.113 248.132l31.623 31.624 79.737-79.963-31.624-31.51c-24.282-24.396-24.282-64.038 0-88.433l409.977-409.977c24.508-24.395 64.828-24.17 89.675 0l299.859 299.972c24.734 25.186 24.847 65.619.564 90.014l-409.976 409.977c-24.508 24.282-64.15 24.282-88.546 0l-110.795-110.909 159.473-159.36-79.85-79.85-435.614 435.502-109.779-109.779c-32.866-33.656-76.8-52.292-123.67-52.63-43.596 1.694-92.273 18.296-126.156 52.178L51.377 1316.081c-68.442 68.442-68.442 179.69 0 248.132l301.553 301.553c34.108 34.108 79.059 51.275 124.01 51.275 44.95 0 89.9-17.167 124.122-51.275l409.976-409.977c33.77-33.882 52.405-78.607 52.066-126.042-.226-46.984-18.974-90.918-52.066-123.219l-30.494-30.494-79.85 79.85 30.946 30.945c11.86 11.633 18.41 27.106 18.523 43.595.113 16.942-6.664 33.092-18.974 45.516l-409.977 409.976c-23.492 23.492-64.94 23.492-88.433 0l-301.553-301.553c-11.746-11.746-18.183-27.444-18.183-44.273 0-16.715 6.437-32.414 18.183-44.16l409.977-409.976c12.197-12.31 28.235-19.087 45.063-19.087h.452c16.49.113 31.962 6.663 43.934 19.087l110.344 110.23-162.184 162.297 79.85 79.85 438.324-438.438 110.796 110.908c34.334 34.221 79.171 51.275 124.122 51.275 44.95 0 89.901-17.054 124.122-51.275l409.977-409.977c67.877-67.99 67.99-179.463 0-249.26"
fill-rule="evenodd"/>
</svg>
</div>
</i></div>
`
sideBar.insertAdjacentHTML('beforeend', htmlText);
return sideBar
}
let sideBar = await main();
(function uploadButton() {
let button = sideBar.querySelector('[class="dfex-upload"]')
function handle() {
let html = `<label for="dfex-upload-input">请选择XML弹幕文件:</label><input type="file" accept="application/xml" id="dfex-upload-input">
<p id="dfex-upload-result"></p>`
let popup = popupWindow()
popup.center.innerHTML = html
let input = popup.center.querySelector('[id="dfex-upload-input"]')
input.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = async (event) => {
let ldanmu = (await postExtension('parseXmlContent', {
'content': event.target.result
})).ldanmu
popup.center.querySelector('[id="dfex-upload-result"]').textContent = '\n' + `从文件中读取到${ldanmu.length}条弹幕\n`
};
reader.readAsText(file);
});
function loadFileDanmaku(reload = false) {
const file = input.files[0];
const reader = new FileReader();
reader.onload = async (event) => {
let ldanmu = (await postExtension('parseXmlContent', {
'content': event.target.result
})).ldanmu
if (reload) {
window.top.closure.danmakuPlayer.dmListStore.allDm = []
}
window.top.closure.loadDanmu(ldanmu)
popup.center.querySelector('[id="dfex-upload-result"]').textContent = '\n' + `从文件中读取到${ldanmu.length}条弹幕\n` + `总弹幕数:${window.top.closure.danmakuPlayer.dmListStore.allDm.length}`
};
reader.readAsText(file);
}
let bottomHtml = `
<style>#dfex-upload-reload {
position: absolute;
right: 8px;
bottom: 8px;
outline: none;
cursor: pointer;
}</style>
<input type="button" value="重载" id="dfex-upload-reload" title="清空现有弹幕后加载"/>
<style>#dfex-upload-append {
position: absolute;
right: 40px;
bottom: 8px;
outline: none;
cursor: pointer;
}</style>
<input type="button" value="追加" id="dfex-upload-append" title="同现有弹幕一起加载"/>
`
popup.insertAdjacentHTML('beforeend', bottomHtml)
popup.querySelector('[id="dfex-upload-reload"]').addEventListener('click', () => {
loadFileDanmaku(true)
})
popup.querySelector('[id="dfex-upload-append"]').addEventListener('click', () => {
loadFileDanmaku(false)
})
}
button.addEventListener('click', handle)
sideBar.appendChild(button)
})();
(function bindButton() {
let button = sideBar.querySelector('[class="dfex-bind"]')
async function handle() {
let lastDesc = (await postExtension("queryDesc")).lastDesc
let bindDict = {}
let html = `<style>
#dfex-bind-input, #dfex-bind-confirm, #dfex-bind-error, #dfex-bind-result {
margin-top: 10px;
margin-bottom: 10px;
float: left;
margin-right: 10px;
}</style>
<p>请输入需要绑定的网址:</p>
<input type="url" id="dfex-bind-input" style="width: 80%">
<input type="button" id="dfex-bind-confirm" value="确定"/>
<p id="dfex-bind-error" style="width: 80%"> </p>
<div id="dfex-bind-result"></div>`
let popup = popupWindow()
let bottomHtml = `
<style>#dfex-bind-submit {
position: absolute;
right: 8px;
bottom: 8px;
/*border: none;*/
outline: none;
cursor: pointer;
display: none;
}</style>
<input type="button" value="提交" id="dfex-bind-submit"/>
`
if (lastDesc[3].youtube) {
bottomHtml += `
<style>
#dfex-bind-youtube-chat {
position: absolute;
right: 40px;
bottom: 8px;
outline: none;
cursor: pointer;
}</style>
<input type="button" id="dfex-bind-youtube-chat" value="油管回放弹幕" title="加载直播弹幕"/>
`
}
popup.insertAdjacentHTML('beforeend', bottomHtml)
popup.center.innerHTML = html
let input = popup.center.querySelector('input[id="dfex-bind-input"]')
let confirm = popup.center.querySelector('input[id="dfex-bind-confirm"]')
let submit = popup.querySelector('input[id="dfex-bind-submit"]')
let result = popup.center.querySelector('div[id="dfex-bind-result"]')
let error = popup.center.querySelector('p[id="dfex-bind-error"]')
confirm.addEventListener('click', async function () {
error.textContent = ''
let bindResult = await postExtension('parseBindInfo', {content: input.value})
let keys = Object.keys(bindResult)
confirm.value = '继续'
if (keys.length === 0) {
error.textContent = "错误: 未识别到匹配的网址"
} else {
for (let key of keys) {
bindDict[key] = bindResult[key]
}
input.value = ''
let resultText = ''
for (let key of Object.keys(bindDict)) {
resultText += `<p>${key}: ${bindDict[key]}</p>`
}
result.innerHTML = resultText
submit.style.display = "block"
}
})
submit.addEventListener('click', async function () {
postExtension('bindVideo', {'bindDict': bindDict})
result.innerHTML = '<p>已提交</p>'
if (bindDict.youtube) {
buildLoadPage(bindDict.youtube)
}
})
let youtubeChat = popup.querySelector('input[id="dfex-bind-youtube-chat"]')
if (youtubeChat) {
youtubeChat.addEventListener("click", async function () {
input.value = "https://www.youtube.com/watch?v=" + lastDesc[3].youtube + "&live=1"
confirm.click()
})
}
}
button.addEventListener('click', handle)
sideBar.appendChild(button)
})();
}
let [loadNicoCommentArt, clearNicoComment] = (function loadNicoCommentArt() {
function buildCanvas() {
// Get a reference to the existing element in the document
let existingElement = document.querySelector('video');
let html = `
<style>
#nico-canvas,
#nico-container
{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: 100%;
width: 100%;
object-fit: contain;
pointer-events: none;
z-index: 999;
}
</style>
<div id="nico-container">
<canvas id="nico-canvas" width="1920" height="1080""></canvas>
</div>
`
existingElement.parentElement.insertAdjacentHTML('beforeend', html);
return existingElement.parentElement.querySelector("#nico-canvas")
}
async function initScript() {
if (scriptInited) {
return
} else {
scriptInited = true
}
let result = await parse("extension::plugin/niconicomments.min.js")
let script = document.createElement('script');
script.textContent = result
document.body.appendChild(script)
}
let scriptInited = false
let niconiComments
let canvasElem
let interval
return [async function (comments) {
if (!niconiComments) {
canvasElem = buildCanvas()
console.log('buildNicoCanvas', canvasElem)
await initScript()
niconiComments = new NiconiComments(canvasElem, [], {
mode: 'default'
});
interval = setInterval(() => {
niconiComments.drawCanvas(Math.floor(window.player.getCurrentTime() * 100))
}, 10);
}
niconiComments.addComments(...comments)
console.log('addCommentArt', niconiComments, comments)
}, function () {
if (canvasElem) {
canvasElem.parentElement.removeChild(canvasElem)
clearInterval(interval)
niconiComments = undefined
interval = undefined
canvasElem = undefined
}
}];
})();
let youtubeManager = {
youtubeId: null,
created: false,
isEnd: false,
context: null,
ytcfg: null,
showed: false,
lastHref: window.location.href,
loadComment: null,
commentList: [],
init: true
}
let buildLoadPage = function (youtubeId) {
async function sleep(seconds) {
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
let createElement = function (sHtml) {
// 创建一个可复用的包装元素
let recycled = document.createElement('div'), // 创建标签简易匹配