forked from ipcjs/bilibili-helper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbilibili_bangumi_area_limit_hack.user.js
2126 lines (2035 loc) · 106 KB
/
bilibili_bangumi_area_limit_hack.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 解除B站区域限制
// @namespace http://tampermonkey.net/
// @version 6.8.5
// @description 通过替换获取视频地址接口的方式, 实现解除B站区域限制; 只对HTML5播放器生效; 只支持番剧视频;
// @author ipcjs
// @supportURL https://github.com/ipcjs/bilibili-helper/issues
// @compatible chrome
// @compatible firefox
// @license MIT
// @require https://static.hdslb.com/js/md5.js
// @include *://www.bilibili.com/video/av*
// @include *://www.bilibili.com/bangumi/play/ep*
// @include *://www.bilibili.com/bangumi/play/ss*
// @include *://m.bilibili.com/bangumi/play/ep*
// @include *://m.bilibili.com/bangumi/play/ss*
// @include *://bangumi.bilibili.com/anime/*
// @include *://bangumi.bilibili.com/movie/*
// @include *://www.bilibili.com/bangumi/media/md*
// @include *://www.bilibili.com/blackboard/html5player.html*
// @run-at document-start
// @grant none
// ==/UserScript==
'use strict';
const log = console.log.bind(console, 'injector:')
function injector() {
if (document.getElementById('balh-injector-source')) {
log(`脚本已经注入过, 不需要执行`)
return
}
// @require https://static.hdslb.com/js/md5.js
GM_info.scriptMetaStr.replace(new RegExp('// @require\\s+https?:(//.*)'), (match, /*p1:*/url) => {
log('@require:', url)
let $script = document.createElement('script')
$script.className = 'balh-injector-require'
$script.setAttribute('type', 'text/javascript')
$script.setAttribute('src', url)
document.head.appendChild($script)
return match
})
let $script = document.createElement('script')
$script.id = 'balh-injector-source'
$script.appendChild(document.createTextNode(`
;(function(GM_info){
${scriptSource.toString()}
${scriptSource.name}('${GM_info.scriptHandler}.${injector.name}')
})(${JSON.stringify(GM_info)})
`))
document.head.appendChild($script)
log('注入完成')
}
if (!Object.getOwnPropertyDescriptor(window, 'XMLHttpRequest').writable) {
log('XHR对象不可修改, 需要把脚本注入到页面中', GM_info.script.name, location.href, document.readyState)
injector()
return
}
/** 脚本的主体部分, 在GM4中, 需要把这个函数转换成字符串, 注入到页面中, 故不要引用外部的变量 */
function scriptSource(invokeBy) {
'use strict';
let log = console.log.bind(console, 'injector:')
if (document.getElementById('balh-injector-source') && invokeBy === GM_info.scriptHandler) {
// 当前, 在Firefox+GM4中, 当返回缓存的页面时, 脚本会重新执行, 并且此时XMLHttpRequest是可修改的(为什么会这样?) + 页面中存在注入的代码
// 导致scriptSource的invokeBy直接是GM4...
log(`页面中存在注入的代码, 但invokeBy却等于${GM_info.scriptHandler}, 这种情况不合理, 终止脚本执行`)
return
}
if (document.readyState === 'uninitialized') { // Firefox上, 对于ifame中执行的脚本, 会出现这样的状态且获取到的href为about:blank...
log('invokeBy:', invokeBy, 'readState:', document.readyState, 'href:', location.href, '需要等待进入loading状态')
setTimeout(() => scriptSource(invokeBy + '.timeout'), 0) // 这里会暴力执行多次, 直到状态不为uninitialized...
return
}
const r = {
text: {
ok: { en: 'OK', zh_cn: '确定', },
},
html: {},
css: {
settings: '#balh-settings {font-size: 12px;color: #6d757a;} #balh-settings h1 {color: #161a1e} #balh-settings a {color: #00a1d6;} #balh-settings a:hover {color: #f25d8e} #balh-settings input {margin-left: 3px;margin-right: 3px;} @keyframes balh-settings-bg { from {background: rgba(0, 0, 0, 0)} to {background: rgba(0, 0, 0, .7)} } #balh-settings label {width: 100%;display: inline-block;cursor: pointer} #balh-settings label:after {content: "";width: 0;height: 1px;background: #4285f4;transition: width .3s;display: block} #balh-settings label:hover:after {width: 100%} form {margin: 0} #balh-settings input[type="radio"] {-webkit-appearance: radio;-moz-appearance: radio;appearance: radio;} #balh-settings input[type="checkbox"] {-webkit-appearance: checkbox;-moz-appearance: checkbox;appearance: checkbox;} ',
},
attr: {},
url: {
issue: 'https://github.com/ipcjs/bilibili-helper/issues',
issue_new: 'https://github.com/ipcjs/bilibili-helper/issues/new',
},
script: {
is_dev: GM_info.script.name.includes('.dev'),
},
const: {
mode: {
DEFAULT: 'default',// 默认模式, 自动判断使用何种模式, 推荐;
REPLACE: 'replace', // 替换模式, 替换有区域限制的视频的接口的返回值;
REDIRECT: 'redirect',// 重定向模式, 直接重定向所有番剧视频的接口到代理服务器; 所有番剧视频都通过代理服务器获取视频地址, 如果代理服务器不稳定, 可能加载不出视频;
},
server: {
S0: 'https://biliplus.ipcjs.win',
S1: 'https://www.biliplus.com',
defaultServer: function () {
return this.S1
},
},
TRUE: 'Y',
FALSE: '',
}
}
const util_stringify = (item) => {
if (typeof item === 'object') {
try {
return JSON.stringify(item)
} catch (e) {
console.debug(e)
return item.toString()
}
} else {
return item
}
}
const util_arr_stringify = function (arr) {
return arr.map(util_stringify).join(' ')
}
const util_str_multiply = function (str, multiplier) {
let result = ''
for (let i = 0; i < multiplier; i++) {
result += str
}
return result
}
const util_log_hub = (function () {
const tag = GM_info.script.name + '.msg'
// 计算"楼层", 若当前window就是顶层的window, 则floor为0, 以此类推
function computefloor(w = window, floor = 0) {
if (w === window.top) {
return floor
} else {
return computefloor(w.parent, floor + 1)
}
}
let floor = computefloor()
let msgList = []
if (floor === 0) { // 只有顶层的Window才需要收集日志
window.addEventListener('message', (event) => {
if (event.data instanceof Array && event.data[0] === tag) {
let [/*tag*/, fromFloor, msg] = event.data
msgList.push(util_str_multiply(' ', fromFloor) + msg)
}
})
}
return {
msg: function (msg) {
window.top.postMessage([tag, floor, msg], '*')
},
getAllMsg: function () {
return msgList.join('\n')
}
}
}())
const util_log_impl = function (type) {
if (r.script.is_dev) {
// 直接打印, 会显示行数
return window.console[type].bind(window.console, type + ':');
} else {
// 将log收集到util_log_hub中, 显示的行数是错误的...
return function (...args) {
args.unshift(type + ':')
window.console[type].apply(window.console, args)
util_log_hub.msg(util_arr_stringify(args))
}
}
}
const util_log = util_log_impl('log')
const util_debug = util_log_impl('debug')
const util_error = util_log_impl('error')
log = util_log
log(`[${GM_info.script.name} v${GM_info.script.version} (${invokeBy})] run on: ${window.location.href}`);
const util_func_noop = function () { }
const util_func_catched = function (func, onError) {
let ret = function () {
try {
return func.apply(this, arguments)
} catch (e) {
if (onError) return onError(e) // onError可以处理报错时的返回值
// 否则打印log, 并返回undefined
util_error('Exception while run %o: %o\n%o', func, e, e.stack)
return undefined
}
}
// 函数的name属性是不可写+可配置的, 故需要如下代码实现类似这样的效果: ret.name = func.name
// 在Edge上匿名函数的name的描述符会为undefined, 需要做特殊处理, fuck
let funcNameDescriptor = Object.getOwnPropertyDescriptor(func, 'name') || {
value: '',
writable: false,
configurable: true,
}
Object.defineProperty(ret, 'name', funcNameDescriptor)
return ret
}
const util_init = (function () {
const RUN_AT = {
DOM_LOADED: 0,
DOM_LOADED_AFTER: 1,
COMPLETE: 2,
}
const PRIORITY = {
FIRST: 1e6,
HIGH: 1e5,
BEFORE: 1e3,
DEFAULT: 0,
AFTER: -1e3,
LOW: -1e5,
LAST: -1e6,
}
const callbacks = {
[RUN_AT.DOM_LOADED]: [],
[RUN_AT.DOM_LOADED_AFTER]: [],
[RUN_AT.COMPLETE]: [],
}
const util_page_valid = () => true // 是否要运行
const dclCreator = function (runAt) {
let dcl = function () {
util_init.atRun = runAt // 更新运行状态
const valid = util_page_valid()
// 优先级从大到小, index从小到大, 排序
callbacks[runAt].sort((a, b) => b.priority - a.priority || a.index - b.index)
.filter(item => valid || item.always)
.forEach(item => item.func(valid))
}
return dcl
}
if (window.document.readyState !== 'loading') {
throw new Error('unit_init must run at loading, current is ' + document.readyState)
}
window.document.addEventListener('DOMContentLoaded', dclCreator(RUN_AT.DOM_LOADED))
window.addEventListener('DOMContentLoaded', dclCreator(RUN_AT.DOM_LOADED_AFTER))
window.addEventListener('load', dclCreator(RUN_AT.COMPLETE))
const util_init = function (func, priority = PRIORITY.DEFAULT, runAt = RUN_AT.DOM_LOADED, always = false) {
func = util_func_catched(func)
if (util_init.atRun < runAt) { // 若还没运行到runAt指定的状态, 则放到队列里去
callbacks[runAt].push({
priority,
index: callbacks[runAt].length, // 使用callback数组的长度, 作为添加元素的index属性
func,
always
})
} else { // 否则直接运行
let valid = util_page_valid()
setTimeout(() => (valid || always) && func(valid), 1)
}
return func
}
util_init.atRun = -1 // 用来表示当前运行到什么状态
util_init.RUN_AT = RUN_AT
util_init.PRIORITY = PRIORITY
return util_init
}())
/** 通知模块 剽窃自 YAWF 用户脚本 硬广:https://tiansh.github.io/yawf/ */
const util_notify = (function () {
var avaliable = {};
var shown = [];
var use = {
'hasPermission': function () { return null; },
'requestPermission': function (callback) { return null; },
'hideNotification': function (notify) { return null; },
'showNotification': function (id, title, body, icon, delay, onclick) { return null; }
};
// 检查一个微博是不是已经被显示过了,如果显示过了不重复显示
var shownFeed = function (id) {
return false;
};
// webkitNotifications
// Tab Notifier 扩展实现此接口,但显示的桌面提示最多只能显示前两行
if (typeof webkitNotifications !== 'undefined') avaliable.webkit = {
'hasPermission': function () {
return [true, null, false][webkitNotifications.checkPermission()];
},
'requestPermission': function (callback) {
return webkitNotifications.requestPermission(callback);
},
'hideNotification': function (notify) {
notify.cancel();
afterHideNotification(notify);
},
'showNotification': function (id, title, body, icon, delay, onclick) {
if (shownFeed(id)) return null;
var notify = webkitNotifications.createNotification(icon, title, body);
if (delay && delay > 0) notify.addEventListener('display', function () {
setTimeout(function () { hideNotification(notify); }, delay);
});
if (onclick) notify.addEventListener('click', function () {
onclick.apply(this, arguments);
hideNotification(notify);
});
notify.show();
return notify;
},
};
// Notification
// Firefox 22+
// 显示4秒会自动关闭 https://bugzil.la/875114
if (typeof Notification !== 'undefined') avaliable.standard = {
'hasPermission': function () {
return {
'granted': true,
'denied': false,
'default': null,
}[Notification.permission];
},
'requestPermission': function (callback) {
return Notification.requestPermission(callback);
},
'hideNotification': function (notify) {
notify.close();
afterHideNotification(notify);
},
'showNotification': function (id, title, body, icon, delay, onclick) {
if (shownFeed(id)) return null;
var notify = new Notification(title, { 'body': body, 'icon': icon, 'requireInteraction': !delay });
if (delay && delay > 0) notify.addEventListener('show', function () {
setTimeout(function () {
hideNotification(notify);
}, delay);
});
if (onclick) notify.addEventListener('click', function () {
onclick.apply(this, arguments);
hideNotification(notify);
});
return notify;
},
};
// 有哪些接口可用
var avaliableNotification = function () {
return Object.keys(avaliable);
};
// 选择用哪个接口
var choseNotification = function (prefer) {
return (use = prefer && avaliable[prefer] || avaliable.standard);
};
choseNotification();
// 检查权限
var hasPermission = function () {
return use.hasPermission.apply(this, arguments);
};
// 请求权限
var requestPermission = function () {
return use.requestPermission.apply(this, arguments);
};
// 显示消息
var showNotification = function (id, title, body, icon, delay, onclick) {
var notify = use.showNotification.apply(this, arguments);
shown.push(notify);
return notify;
};
// 隐藏已经显示的消息
var hideNotification = function (notify) {
use.hideNotification.apply(this, arguments);
return notify;
};
var afterHideNotification = function (notify) {
shown = shown.filter(function (x) { return x !== notify; });
};
document.addEventListener('unload', function () {
shown.forEach(hideNotification);
shown = [];
});
var showNotificationAnyway = function (id, title, body, icon, delay, onclick) {
var that = this, thatArguments = arguments;
switch (that.hasPermission()) {
case null: // default
that.requestPermission(function () {
showNotificationAnyway.apply(that, thatArguments);
});
break;
case true: // granted
// 只有已获取了授权, 才能有返回值...
return that.showNotification.apply(that, thatArguments);
break;
case false: // denied
log('Notification permission: denied');
break;
}
return null;
}
return {
'avaliableNotification': avaliableNotification,
'choseNotification': choseNotification,
'hasPermission': hasPermission,
'requestPermission': requestPermission,
'showNotification': showNotification,
'hideNotification': hideNotification,
show: function (body, onclick, delay = 3e3) {
return this.showNotificationAnyway(Date.now(), GM_info.script.name, body, '//bangumi.bilibili.com/favicon.ico', delay, onclick)
},
showNotificationAnyway
};
}())
const util_cookie = (function () {
function getCookies() {
var map = document.cookie.split('; ').reduce(function (obj, item) {
var entry = item.split('=');
obj[entry[0]] = entry[1];
return obj;
}, {});
return map;
}
function getCookie(key) {
return getCookies()[key];
}
/**
* @param key key
* @param value 为undefined时, 表示删除cookie
* @param options 为undefined时, 表示过期时间为3年
* 为''时, 表示Session cookie
* 为数字时, 表示指定过期时间
* 为{}时, 表示指定所有的属性
* */
function setCookie(key, value, options) {
if (typeof options !== 'object') {
options = {
domain: '.bilibili.com',
path: '/',
'max-age': value === undefined ? 0 : (options === undefined ? 94608000 : options)
};
}
var c = Object.keys(options).reduce(function (str, key) {
return str + '; ' + key + '=' + options[key];
}, key + '=' + value);
document.cookie = c;
return c;
}
return new Proxy({ set: setCookie, get: getCookie, all: getCookies }, {
get: function (target, prop) {
if (prop in target) return target[prop]
return getCookie(prop)
},
set: function (target, prop, value) {
setCookie(prop, value)
return true
}
})
}())
const Promise = window.Promise // 在某些情况下, 页面中会修改window.Promise... 故我们要备份一下原始的Promise
const util_promise_plus = (function () {
/**
* 模仿RxJava中的compose操作符
* @param transformer 转换函数, 传入Promise, 返回Promise; 若为空, 则啥也不做
*/
Promise.prototype.compose = function (transformer) {
return transformer ? transformer(this) : this
}
}())
const util_ajax = function (options) {
return new Promise(function (resolve, reject) {
typeof options !== 'object' && (options = { url: options });
options.async === undefined && (options.async = true);
options.xhrFields === undefined && (options.xhrFields = { withCredentials: true });
options.success = function (data) {
resolve(data);
};
options.error = function (err) {
reject(err);
};
util_debug('ajax:', options.url)
$.ajax(options);
});
}
/**
* @param promiseCeator 创建Promise的函数
* @param resultTranformer 用于变换result的函数, 返回新的result或Promise
* @param errorTranformer 用于变换error的函数, 返回新的error或Promise, 返回的Promise可以做状态恢复...
*/
const util_async_wrapper = function (promiseCeator, resultTranformer, errorTranformer) {
return function (...args) {
return new Promise((resolve, reject) => {
// log(promiseCeator, ...args)
promiseCeator(...args)
.then(r => resultTranformer ? resultTranformer(r) : r)
.then(r => resolve(r))
.catch(e => {
e = errorTranformer ? errorTranformer(e) : e
if (!(e instanceof Promise)) {
// 若返回值不是Promise, 则表示是一个error
e = Promise.reject(e)
}
e.then(r => resolve(r)).catch(e => reject(e))
})
})
}
}
/**
* 创建元素的快捷方法
* @param type string, 标签名; 特殊的, 若为text, 则表示创建文字, 对应的t为文字的内容
* @param props object, 属性; 特殊的属性名有: className, 类名; style, 样式, 值为(样式名, 值)形式的object; event, 值为(事件名, 监听函数)形式的object;
* @param children array, 子元素;
*/
const util_ui_element_creator = (type, props, children) => {
let elem = null;
if (type === "text") {
return document.createTextNode(props);
} else {
elem = document.createElement(type);
}
for (let n in props) {
if (n === "style") {
for (let x in props.style) {
elem.style[x] = props.style[x];
}
} else if (n === "className") {
elem.className = props[n];
} else if (n === "event") {
for (let x in props.event) {
elem.addEventListener(x, props.event[x]);
}
} else {
elem.setAttribute(n, props[n]);
}
}
if (children) {
for (let i = 0; i < children.length; i++) {
if (children[i] != null)
elem.appendChild(children[i]);
}
}
return elem;
}
const _ = util_ui_element_creator
const util_jsonp = function (url, callback) {
return new Promise((resolve, reject) => {
document.head.appendChild(_('script', {
src: url,
event: {
load: function () {
resolve()
},
error: function () {
reject()
}
}
}));
})
}
const util_generate_sign = function (params, key) {
var s_keys = [];
for (var i in params) {
s_keys.push(i);
}
s_keys.sort();
var data = "";
for (var i = 0; i < s_keys.length; i++) {
// encodeURIComponent 返回的转义数字必须为大写( 如 %2F )
data += (data ? "&" : "") + s_keys[i] + "=" + encodeURIComponent(params[s_keys[i]]);
}
return {
"sign": hex_md5(data + key),
"params": data
};
}
const util_xml2obj = (xml) => {
try {
var obj = {}, text;
var children = xml.children;
if (children.length > 0) {
for (var i = 0; i < children.length; i++) {
var item = children.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") { // 若是新的属性, 则往obj中添加
obj[nodeName] = util_xml2obj(item);
} else {
if (typeof (obj[nodeName].push) == "undefined") { // 若老的属性没有push方法, 则把属性改成Array
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(util_xml2obj(item));
}
}
} else {
text = xml.textContent;
if (/^\d+(\.\d+)?$/.test(text)) {
obj = Number(text);
} else if (text === 'true' || text === 'false') {
obj = Boolean(text);
} else {
obj = text;
}
}
return obj;
} catch (e) {
util_error(e);
}
}
const util_ui_popframe = function (iframeSrc) {
if (!document.getElementById('balh-style-login')) {
var style = document.createElement('style');
style.id = 'balh-style-login';
document.head.appendChild(style).innerHTML = '@keyframes pop-iframe-in{0%{opacity:0;transform:scale(.7);}100%{opacity:1;transform:scale(1)}}@keyframes pop-iframe-out{0%{opacity:1;transform:scale(1);}100%{opacity:0;transform:scale(.7)}}.GMBiliPlusCloseBox{position:absolute;top:5%;right:8%;font-size:40px;color:#FFF}';
}
var div = document.createElement('div');
div.id = 'GMBiliPlusLoginContainer';
div.innerHTML = '<div style="position:fixed;top:0;left:0;z-index:10000;width:100%;height:100%;background:rgba(0,0,0,.5);animation-fill-mode:forwards;animation-name:pop-iframe-in;animation-duration:.5s;cursor:pointer"><iframe src="' + iframeSrc + '" style="background:#e4e7ee;position:absolute;top:10%;left:10%;width:80%;height:80%"></iframe><div class="GMBiliPlusCloseBox">×</div></div>';
div.firstChild.addEventListener('click', function (e) {
if (e.target === this || e.target.className === 'GMBiliPlusCloseBox') {
if (!confirm('确认关闭?')) {
return false;
}
div.firstChild.style.animationName = 'pop-iframe-out';
setTimeout(function () {
div.remove();
}, 5e2);
}
});
document.body.appendChild(div);
}
const util_ui_alert = function (message, callback) {
setTimeout(() => {
if (callback) {
if (window.confirm(message)) {
callback()
}
} else {
alert(message)
}
}, 500)
}
/**
* MessageBox -> from base.core.js
* MessageBox.show(referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback)
* MessageBox.close()
*/
const util_ui_msg = (function () {
function MockMessageBox() {
this.show = (...args) => util_log(MockMessageBox.name, 'show', args)
this.close = (...args) => util_log(MockMessageBox.name, 'close', args)
}
let popMessage = null
let mockPopMessage = new MockMessageBox()
let notifyPopMessage = {
_current_notify: null,
show: function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
this.close()
this._current_notify = util_notify.show(message, buttonTypeConfirmCallback, closeTime)
},
close: function () {
if (this._current_notify) {
util_notify.hideNotification(this._current_notify)
this._current_notify = null
}
}
}
let alertPopMessage = {
show: function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
util_ui_alert(message, buttonTypeConfirmCallback)
},
close: util_func_noop
}
util_init(() => {
if (!popMessage && window.MessageBox) {
popMessage = new window.MessageBox()
let orignShow = popMessage.show
popMessage.show = function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
// 这个窗,有一定机率弹不出来。。。不知道为什么
orignShow.call(this, referenceElement, message.replace('\n', '<br>'), closeTime, boxType, buttonTypeConfirmCallback)
}
popMessage.close = function () {
// 若没调用过show, 就调用close, msgbox会为null, 导致报错
this.msgbox != null && window.MessageBox.prototype.close.apply(this, arguments)
}
}
}, util_init.PRIORITY.FIRST, util_init.RUN_AT.DOM_LOADED_AFTER)
return {
_impl: function () {
return popMessage || alertPopMessage
},
show: function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
let pop = this._impl()
return pop.show.apply(pop, arguments)
},
close: function () {
let pop = this._impl()
return pop.close.apply(pop, arguments)
},
setMsgBoxFixed: function (fixed) {
if (popMessage) {
popMessage.msgbox[0].style.position = fixed ? 'fixed' : ''
} else {
util_log(MockMessageBox.name, 'setMsgBoxFixed', fixed)
}
},
showOnNetError: function (e) {
if (e.readyState === 0) {
this.show($('.balh_settings'), '哎呀,服务器连不上了,进入设置窗口,换个服务器试试?', 0, 'button', balh_ui_setting.show);
}
},
showOnNetErrorInPromise: function () {
return p => p
.catch(e => {
this.showOnNetError(e)
return Promise.reject(e)
})
}
}
}())
const util_ui_player_msg = function (message) {
const msg = util_stringify(message)
log('player msg:', msg)
const $panel = document.querySelector('.bilibili-player-video-panel-text')
if ($panel) {
let stage = $panel.children.length + 1000 // 加1000和B站自己发送消息的stage区别开来
$panel.appendChild(_('div', { className: 'bilibili-player-video-panel-row', stage: stage }, [_('text', `[${GM_info.script.name}] ${msg}`)]))
}
}
const util_ui_copy = function (text, textarea) {
textarea.value = text
textarea.select()
try {
return document.execCommand('copy')
} catch (e) {
util_error('复制文本出错', e)
}
return false
}
const util_url_param = function (url, key) {
return (url.match(new RegExp('[?|&]' + key + '=(\\w+)')) || ['', ''])[1];
}
const util_page = {
player: () => location.href.includes('www.bilibili.com/blackboard/html5player'),
// 在av页面中的iframe标签形式的player
player_in_av: util_func_catched(() => util_page.player() && window.top.location.href.includes('www.bilibili.com/video/av'), (e) => log(e), false),
av: () => location.href.includes('www.bilibili.com/video/av'),
bangumi: () => location.href.match(new RegExp('^https?://bangumi\\.bilibili\\.com/anime/\\d+/?$')),
bangumi_md: () => location.href.includes('www.bilibili.com/bangumi/media/md'),
// movie页面使用window.aid, 保存当前页面av号
movie: () => location.href.includes('bangumi.bilibili.com/movie/'),
// anime页面使用window.season_id, 保存当前页面season号
anime: () => location.href.match(new RegExp('^https?://bangumi\\.bilibili\\.com/anime/\\d+/play.*')),
anime_ep: () => location.href.includes('www.bilibili.com/bangumi/play/ep'),
anime_ss: () => location.href.includes('www.bilibili.com/bangumi/play/ss'),
anime_ep_m: () => location.href.includes('m.bilibili.com/bangumi/play/ep'),
anime_ss_m: () => location.href.includes('m.bilibili.com/bangumi/play/ss'),
}
const balh_config = (function () {
const cookies = util_cookie.all() // 缓存的cookies
return new Proxy({ /*保存config的对象*/ }, {
get: function (target, prop) {
if (prop in target) {
return target[prop]
} else { // 若target中不存在指定的属性, 则从缓存的cookies中读取, 并保存到target中
let value = cookies['balh_' + prop]
switch (prop) {
case 'server':
value = value || r.const.server.defaultServer()
// 从tk域名迁移到新的默认域名
if (value.includes('biliplus.ipcjsdev.tk')) {
value = r.const.server.defaultServer()
balh_config.server = value
}
break
case 'mode':
value = value || (balh_config.blocked_vip ? r.const.mode.REDIRECT : r.const.mode.DEFAULT)
break
default:
// case 'blocked_vip':
// case 'flv_prefer_ws':
// case 'remove_pre_ad':
break
}
target[prop] = value
return value
}
},
set: function (target, prop, value) {
target[prop] = value // 更新值
util_cookie['balh_' + prop] = value // 更新cookie中的值
return true
}
})
}())
const balh_api_plus_view = function (aid, update = true) {
return util_ajax(`${balh_config.server}/api/view?id=${aid}&update=${update}`)
}
const balh_api_plus_season = function (season_id) {
return util_ajax(`${balh_config.server}/api/bangumi?season=${season_id}`)
}
// https://www.biliplus.com/BPplayurl.php?otype=json&cid=30188339&module=bangumi&qn=16&src=vupload&vid=vupload_30188339
// qn = 16, 能看
const balh_api_plus_playurl = function (cid, qn = 16, bangumi = true) {
return util_ajax(`${balh_config.server}/BPplayurl.php?otype=json&cid=${cid}${bangumi ? '&module=bangumi' : ''}&qn=${qn}&src=vupload&vid=vupload_${cid}`)
}
// https://www.biliplus.com/api/h5play.php?tid=33&cid=31166258&type=vupload&vid=vupload_31166258&bangumi=1
const balh_api_plus_playurl_for_mp4 = (cid, bangumi = true) => util_ajax(`${balh_config.server}/api/h5play.php?tid=33&cid=${cid}&type=vupload&vid=vupload_${cid}&bangumi=${bangumi ? 1 : 0}`)
.then(text => (text.match(/srcUrl=\{"mp4":"(https?.*)"\};/) || ['', ''])[1]); // 提取mp4的url
const balh_feature_area_limit = (function () {
function injectXHR() {
util_debug('XMLHttpRequest的描述符:', Object.getOwnPropertyDescriptor(window, 'XMLHttpRequest'))
let firstCreateXHR = true
window.XMLHttpRequest = new Proxy(window.XMLHttpRequest, {
construct: function (target, args) {
// 第一次创建XHR时, 打上断点...
if (firstCreateXHR && r.script.is_dev) {
firstCreateXHR = false
// debugger
}
let container = {} // 用来替换responseText等变量
return new Proxy(new target(...args), {
set: function (target, prop, value, receiver) {
if (prop === 'onreadystatechange') {
let cb = value
value = function () {
if (target.readyState === 4) {
if (target.responseURL.includes('bangumi.bilibili.com/view/web_api/season/user/status')) {
log('/season/user/status:', target.responseText)
let json = JSON.parse(target.responseText)
let rewriteResult = false
if (json.code === 0 && json.result) {
areaLimit(json.result.area_limit !== 0)
if (json.result.area_limit !== 0) {
json.result.area_limit = 0 // 取消区域限制
rewriteResult = true
}
if (balh_config.blocked_vip) {
json.result.pay = 1
rewriteResult = true
}
if (rewriteResult) {
container.responseText = JSON.stringify(json)
}
}
} else if (target.responseURL.includes('bangumi.bilibili.com/web_api/season_area')) {
log('/season_area', target.responseText)
let json = JSON.parse(target.responseText)
if (json.code === 0 && json.result) {
areaLimit(json.result.play === 0)
if (json.result.play === 0) {
json.result.play = 1
container.responseText = JSON.stringify(json)
}
}
} else if (target.responseURL.includes('api.bilibili.com/x/web-interface/nav')) {
let json = JSON.parse(target.responseText)
log('/x/web-interface/nav', (json.data && json.data.isLogin)
? { uname: json.data.uname, isLogin: json.data.isLogin, level: json.data.level_info.current_level, vipType: json.data.vipType, vipStatus: json.data.vipStatus }
: target.responseText)
if (json.code === 0 && json.data && balh_config.blocked_vip) {
json.data.vipType = 2; // 类型, 年度大会员
json.data.vipStatus = 1; // 状态, 启用
container.responseText = JSON.stringify(json)
}
}
}
// 这里的this是原始的xhr, 在container.responseText设置了值时需要替换成代理对象
cb.apply(container.responseText ? receiver : this, arguments)
}
}
target[prop] = value
return true
},
get: function (target, prop, receiver) {
if (prop in container) return container[prop]
let value = target[prop]
if (typeof value === 'function') {
let func = value
// open等方法, 必须在原始的xhr对象上才能调用...
value = function () {
return func.apply(target, arguments)
}
}
return value
}
})
}
})
}
function injectAjax() {
let originalAjax = $.ajax;
$.ajax = function (arg0, arg1) {
// log(arguments);
let param;
if (arg1 === undefined) {
param = arg0;
} else {
arg0 && (arg1.url = arg0);
param = arg1;
}
let oriSuccess = param.success;
let oriError = param.error;
let mySuccess, myError;
// 投递结果的transformer, 结果通过oriSuccess/Error投递
const dispatchResultTransformer = p => p
.then(r => oriSuccess(r))
.catch(e => oriError(e))
// 转换原始请求的结果的transformer
let oriResultTransformer
let one_api;
if (param.url.match('/web_api/get_source')) {
one_api = bilibiliApis._get_source;
oriResultTransformer = p => p
.then(json => {
log(json);
if (json.code === -40301 // 区域限制
|| json.result.payment && json.result.payment.price != 0 && balh_config.blocked_vip) { // 需要付费的视频, 此时B站返回的cid是错了, 故需要使用代理服务器的接口
areaLimit(true);
return one_api.asyncAjax(param.url)
.catch(e => json)// 新的请求报错, 也应该返回原来的数据
} else {
areaLimit(false);
if ((balh_config.blocked_vip || balh_config.remove_pre_ad) && json.code === 0 && json.result.pre_ad) {
json.result.pre_ad = 0; // 去除前置广告
}
return json;
}
})
} else if (param.url.match('/player/web_api/playurl') // 老的番剧页面playurl接口
|| param.url.match('/player/web_api/v2/playurl') // 新的番剧页面playurl接口
|| (balh_config.enable_in_av && param.url.match('//interface.bilibili.com/v2/playurl')) // 普通的av页面playurl接口
) {
one_api = bilibiliApis._playurl;
oriResultTransformer = p => p
.then(json => {
log(json)
if (balh_config.blocked_vip || json.code || isAreaLimitForPlayUrl(json)) {
areaLimit(true)
return one_api.asyncAjax(param.url)
.catch(e => json)
} else {
areaLimit(false)
return json
}
})
} else if (param.url.match('//interface.bilibili.com/player?')) {
if (balh_config.blocked_vip) {
mySuccess = function (data) {
try {
let xml = new window.DOMParser().parseFromString(`<userstatus>${data.replace(/\&/g, '&')}</userstatus>`, 'text/xml');
let vipTag = xml.querySelector('vip');
if (vipTag) {
let vip = JSON.parse(vipTag.innerHTML);
vip.vipType = 2; // 类型, 年度大会员
vip.vipStatus = 1; // 状态, 启用
vipTag.innerHTML = JSON.stringify(vip);
data = xml.documentElement.innerHTML;
}
} catch (e) {
log('parse xml error: ', e);
}
oriSuccess(data);
};
}
} else if (param.url.match('//api.bilibili.com/x/ad/video?')) {
if (balh_config.remove_pre_ad) {
mySuccess = function (data) {
log('/ad/video', data)
if (data && data.code === 0 && data.data) {
data.data = [] // 移除广告接口返回的数据
}
oriSuccess(data)
}
}
}
if (one_api && oriResultTransformer) {
if (needRedirect()) {
// 清除原始请求的回调
mySuccess = util_func_noop
myError = util_func_noop
// 通过proxy, 执行请求
one_api.asyncAjax(param.url)
.compose(dispatchResultTransformer)
} else {