Greasy Fork is available in English.

解除B站区域限制

通过替换获取视频地址接口的方式, 实现解除B站区域限制; 只对HTML5播放器生效;

As of 07.04.2019. See ბოლო ვერსია.

  1. // ==UserScript==
  2. // @name 解除B站区域限制
  3. // @namespace http://tampermonkey.net/
  4. // @version 7.5.7
  5. // @description 通过替换获取视频地址接口的方式, 实现解除B站区域限制; 只对HTML5播放器生效;
  6. // @author ipcjs
  7. // @supportURL https://github.com/ipcjs/bilibili-helper/issues
  8. // @compatible chrome
  9. // @compatible firefox
  10. // @license MIT
  11. // @require https://static.hdslb.com/js/md5.js
  12. // @include *://www.bilibili.com/video/av*
  13. // @include *://www.bilibili.com/bangumi/play/ep*
  14. // @include *://www.bilibili.com/bangumi/play/ss*
  15. // @include *://m.bilibili.com/bangumi/play/ep*
  16. // @include *://m.bilibili.com/bangumi/play/ss*
  17. // @include *://bangumi.bilibili.com/anime/*
  18. // @include *://bangumi.bilibili.com/movie/*
  19. // @include *://www.bilibili.com/bangumi/media/md*
  20. // @include *://www.bilibili.com/blackboard/html5player.html*
  21. // @include *://link.acg.tv/forum.php*
  22. // @run-at document-start
  23. // @grant none
  24. // ==/UserScript==
  25.  
  26. 'use strict';
  27. const log = console.log.bind(console, 'injector:')
  28.  
  29. if (location.href.match('link.acg.tv/forum.php') != null) {
  30. if (location.href.match('access_key') != null && window.opener != null) {
  31. window.stop();
  32. document.children[0].innerHTML = '<title>BALH - 授权</title><meta charset="UTF-8" name="viewport" content="width=device-width">正在跳转……';
  33. window.opener.postMessage('balh-login-credentials: ' + location.href, '*');
  34. }
  35. return;
  36. }
  37.  
  38. function injector() {
  39. if (document.getElementById('balh-injector-source')) {
  40. log(`脚本已经注入过, 不需要执行`)
  41. return
  42. }
  43. // @require https://static.hdslb.com/js/md5.js
  44. GM_info.scriptMetaStr.replace(new RegExp('// @require\\s+https?:(//.*)'), (match, /*p1:*/url) => {
  45. log('@require:', url)
  46. let $script = document.createElement('script')
  47. $script.className = 'balh-injector-require'
  48. $script.setAttribute('type', 'text/javascript')
  49. $script.setAttribute('src', url)
  50. document.head.appendChild($script)
  51. return match
  52. })
  53. let $script = document.createElement('script')
  54. $script.id = 'balh-injector-source'
  55. $script.appendChild(document.createTextNode(`
  56. ;(function(GM_info){
  57. ${scriptSource.toString()}
  58. ${scriptSource.name}('${GM_info.scriptHandler}.${injector.name}')
  59. })(${JSON.stringify(GM_info)})
  60. `))
  61. document.head.appendChild($script)
  62. log('注入完成')
  63. }
  64.  
  65. if (!Object.getOwnPropertyDescriptor(window, 'XMLHttpRequest').writable) {
  66. log('XHR对象不可修改, 需要把脚本注入到页面中', GM_info.script.name, location.href, document.readyState)
  67. injector()
  68. return
  69. }
  70.  
  71. /** 脚本的主体部分, 在GM4中, 需要把这个函数转换成字符串, 注入到页面中, 故不要引用外部的变量 */
  72. function scriptSource(invokeBy) {
  73. 'use strict';
  74. let log = console.log.bind(console, 'injector:')
  75. if (document.getElementById('balh-injector-source') && invokeBy === GM_info.scriptHandler) {
  76. // 当前, 在Firefox+GM4中, 当返回缓存的页面时, 脚本会重新执行, 并且此时XMLHttpRequest是可修改的(为什么会这样?) + 页面中存在注入的代码
  77. // 导致scriptSource的invokeBy直接是GM4...
  78. log(`页面中存在注入的代码, invokeBy却等于${GM_info.scriptHandler}, 这种情况不合理, 终止脚本执行`)
  79. return
  80. }
  81. if (document.readyState === 'uninitialized') { // Firefox上, 对于ifame中执行的脚本, 会出现这样的状态且获取到的href为about:blank...
  82. log('invokeBy:', invokeBy, 'readState:', document.readyState, 'href:', location.href, '需要等待进入loading状态')
  83. setTimeout(() => scriptSource(invokeBy + '.timeout'), 0) // 这里会暴力执行多次, 直到状态不为uninitialized...
  84. return
  85. }
  86.  
  87. const r_text = {
  88. ok: { en: 'OK', zh_cn: '确定', },
  89. close: { en: 'Close', zh_cn: '关闭' },
  90. welcome_to_acfun: '<p><b>缺B乐 了解下?</b></p><br><p>PS: A站白屏/播放卡顿/被区域限制等问题,可以通过安装 <a href="https://github.com/esterTion/AcFun-HTML5-Player">AcFun HTML5 Player</a> 解决</p>',
  91. version_remind: ``,
  92. }
  93. const _t = (key) => {
  94. const text = r_text[key]
  95. const lang = 'zh_cn'
  96. return typeof text === 'string' ? text : text[lang]
  97. }
  98.  
  99. const r = {
  100. html: {},
  101. css: {
  102. 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;} ',
  103. },
  104. attr: {},
  105. url: {
  106. issue: 'https://github.com/ipcjs/bilibili-helper/issues',
  107. issue_new: 'https://github.com/ipcjs/bilibili-helper/issues/new',
  108. },
  109. script: {
  110. is_dev: GM_info.script.name.includes('.dev'),
  111. },
  112. const: {
  113. mode: {
  114. DEFAULT: 'default',// 默认模式, 自动判断使用何种模式, 推荐;
  115. REPLACE: 'replace', // 替换模式, 替换有区域限制的视频的接口的返回值;
  116. REDIRECT: 'redirect',// 重定向模式, 直接重定向所有番剧视频的接口到代理服务器; 所有番剧视频都通过代理服务器获取视频地址, 如果代理服务器不稳定, 可能加载不出视频;
  117. },
  118. server: {
  119. S0: 'https://biliplus.ipcjs.top',
  120. S1: 'https://www.biliplus.com',
  121. CUSTOM: '__custom__',
  122. defaultServer: function () {
  123. return this.S1
  124. },
  125. },
  126. TRUE: 'Y',
  127. FALSE: '',
  128. },
  129. baipiao: [
  130. { key: 'zomble_land_saga', match: () => (window.__INITIAL_STATE__ && window.__INITIAL_STATE__.epInfo && window.__INITIAL_STATE__.epInfo.ep_id) === 251255, link: 'http://www.acfun.cn/bangumi/ab5022161_31405_278830', message: r_text.welcome_to_acfun },
  131. { key: 'zomble_land_saga', match: () => (window.__INITIAL_STATE__ && window.__INITIAL_STATE__.mediaInfo && window.__INITIAL_STATE__.mediaInfo.media_id) === 140772, link: 'http://www.acfun.cn/bangumi/aa5022161', message: r_text.welcome_to_acfun },
  132. ]
  133. }
  134. const util_stringify = (item) => {
  135. if (typeof item === 'object') {
  136. try {
  137. return JSON.stringify(item)
  138. } catch (e) {
  139. console.debug(e)
  140. return item.toString()
  141. }
  142. } else {
  143. return item
  144. }
  145. }
  146. const util_arr_stringify = function (arr) {
  147. return arr.map(util_stringify).join(' ')
  148. }
  149.  
  150. const util_str_multiply = function (str, multiplier) {
  151. let result = ''
  152. for (let i = 0; i < multiplier; i++) {
  153. result += str
  154. }
  155. return result
  156. }
  157.  
  158. const util_log_hub = (function () {
  159. const tag = GM_info.script.name + '.msg'
  160.  
  161. // 计算"楼层", 若当前window就是顶层的window, 则floor为0, 以此类推
  162. function computefloor(w = window, floor = 0) {
  163. if (w === window.top) {
  164. return floor
  165. } else {
  166. return computefloor(w.parent, floor + 1)
  167. }
  168. }
  169.  
  170. let floor = computefloor()
  171. let msgList = []
  172. if (floor === 0) { // 只有顶层的Window才需要收集日志
  173. window.addEventListener('message', (event) => {
  174. if (event.data instanceof Array && event.data[0] === tag) {
  175. let [/*tag*/, fromFloor, msg] = event.data
  176. msgList.push(util_str_multiply(' ', fromFloor) + msg)
  177. }
  178. })
  179. }
  180. return {
  181. msg: function (msg) {
  182. window.top.postMessage([tag, floor, msg], '*')
  183. },
  184. getAllMsg: function () {
  185. return msgList.join('\n')
  186. }
  187. }
  188. }())
  189. const util_log_impl = function (type) {
  190. if (r.script.is_dev) {
  191. // 直接打印, 会显示行数
  192. return window.console[type].bind(window.console, type + ':');
  193. } else {
  194. // 将log收集到util_log_hub中, 显示的行数是错误的...
  195. return function (...args) {
  196. args.unshift(type + ':')
  197. window.console[type].apply(window.console, args)
  198. util_log_hub.msg(util_arr_stringify(args))
  199. }
  200. }
  201. }
  202. const util_log = util_log_impl('log')
  203. const util_debug = util_log_impl('debug')
  204. const util_error = util_log_impl('error')
  205. log = util_log
  206. log(`[${GM_info.script.name} v${GM_info.script.version} (${invokeBy})] run on: ${window.location.href}`);
  207.  
  208. const util_func_noop = function () { }
  209. const util_func_catched = function (func, onError) {
  210. let ret = function () {
  211. try {
  212. return func.apply(this, arguments)
  213. } catch (e) {
  214. if (onError) return onError(e) // onError可以处理报错时的返回值
  215. // 否则打印log, 并返回undefined
  216. util_error('Exception while run %o: %o\n%o', func, e, e.stack)
  217. return undefined
  218. }
  219. }
  220. // 函数的name属性是不可写+可配置的, 故需要如下代码实现类似这样的效果: ret.name = func.name
  221. // 在Edge上匿名函数的name的描述符会为undefined, 需要做特殊处理, fuck
  222. let funcNameDescriptor = Object.getOwnPropertyDescriptor(func, 'name') || {
  223. value: '',
  224. writable: false,
  225. configurable: true,
  226. }
  227. Object.defineProperty(ret, 'name', funcNameDescriptor)
  228. return ret
  229. }
  230.  
  231. const util_safe_get = (code) => {
  232. return eval(`
  233. (()=>{
  234. try{
  235. return ${code}
  236. }catch(e){
  237. console.warn(e.toString())
  238. return null
  239. }
  240. })()
  241. `)
  242. }
  243.  
  244. const util_ui_alert = function (message, resolve, reject) {
  245. setTimeout(() => {
  246. if (resolve) {
  247. if (window.confirm(message)) {
  248. resolve()
  249. } else {
  250. if (reject) {
  251. reject()
  252. }
  253. }
  254. } else {
  255. alert(message)
  256. }
  257. }, 500)
  258. }
  259.  
  260. const util_init = (function () {
  261. const RUN_AT = {
  262. DOM_LOADED: 0,
  263. DOM_LOADED_AFTER: 1,
  264. COMPLETE: 2,
  265. }
  266. const PRIORITY = {
  267. FIRST: 1e6,
  268. HIGH: 1e5,
  269. BEFORE: 1e3,
  270. DEFAULT: 0,
  271. AFTER: -1e3,
  272. LOW: -1e5,
  273. LAST: -1e6,
  274. }
  275. const callbacks = {
  276. [RUN_AT.DOM_LOADED]: [],
  277. [RUN_AT.DOM_LOADED_AFTER]: [],
  278. [RUN_AT.COMPLETE]: [],
  279. }
  280. const util_page_valid = () => true // 是否要运行
  281. const dclCreator = function (runAt) {
  282. let dcl = function () {
  283. util_init.atRun = runAt // 更新运行状态
  284. const valid = util_page_valid()
  285. // 优先级从大到小, index从小到大, 排序
  286. callbacks[runAt].sort((a, b) => b.priority - a.priority || a.index - b.index)
  287. .filter(item => valid || item.always)
  288. .forEach(item => item.func(valid))
  289. }
  290. return dcl
  291. }
  292.  
  293. if (window.document.readyState !== 'loading') {
  294. util_ui_alert(`${GM_info.script.name} 加载时机不对, 不能保证正常工作\n\n1. 点击'确定', 刷新页面/重载脚本\n2. 若依然出现该提示, 请尝试'硬性重新加载'(快捷键一般为ctrl+f5)\n3. 若还是出现该提示, 请尝试关闭再重新打开该页面\n4. 若反复出现该提示, 请尝试换个浏览器\n`, () => {
  295. location.reload(true)
  296. })
  297. // throw new Error('unit_init must run at loading, current is ' + document.readyState)
  298. }
  299.  
  300. window.document.addEventListener('DOMContentLoaded', dclCreator(RUN_AT.DOM_LOADED))
  301. window.addEventListener('DOMContentLoaded', dclCreator(RUN_AT.DOM_LOADED_AFTER))
  302. window.addEventListener('load', dclCreator(RUN_AT.COMPLETE))
  303.  
  304. const util_init = function (func, priority = PRIORITY.DEFAULT, runAt = RUN_AT.DOM_LOADED, always = false) {
  305. func = util_func_catched(func)
  306. if (util_init.atRun < runAt) { // 若还没运行到runAt指定的状态, 则放到队列里去
  307. callbacks[runAt].push({
  308. priority,
  309. index: callbacks[runAt].length, // 使用callback数组的长度, 作为添加元素的index属性
  310. func,
  311. always
  312. })
  313. } else { // 否则直接运行
  314. let valid = util_page_valid()
  315. setTimeout(() => (valid || always) && func(valid), 1)
  316. }
  317. return func
  318. }
  319. util_init.atRun = -1 // 用来表示当前运行到什么状态
  320. util_init.RUN_AT = RUN_AT
  321. util_init.PRIORITY = PRIORITY
  322. return util_init
  323. }())
  324. /** 通知模块 剽窃自 YAWF 用户脚本 硬广:https://tiansh.github.io/yawf/ */
  325. const util_notify = (function () {
  326. var avaliable = {};
  327. var shown = [];
  328. var use = {
  329. 'hasPermission': function () { return null; },
  330. 'requestPermission': function (callback) { return null; },
  331. 'hideNotification': function (notify) { return null; },
  332. 'showNotification': function (id, title, body, icon, delay, onclick) { return null; }
  333. };
  334.  
  335. // 检查一个微博是不是已经被显示过了,如果显示过了不重复显示
  336. var shownFeed = function (id) {
  337. return false;
  338. };
  339.  
  340. // webkitNotifications
  341. // Tab Notifier 扩展实现此接口,但显示的桌面提示最多只能显示前两行
  342. if (typeof webkitNotifications !== 'undefined') avaliable.webkit = {
  343. 'hasPermission': function () {
  344. return [true, null, false][webkitNotifications.checkPermission()];
  345. },
  346. 'requestPermission': function (callback) {
  347. return webkitNotifications.requestPermission(callback);
  348. },
  349. 'hideNotification': function (notify) {
  350. notify.cancel();
  351. afterHideNotification(notify);
  352. },
  353. 'showNotification': function (id, title, body, icon, delay, onclick) {
  354. if (shownFeed(id)) return null;
  355. var notify = webkitNotifications.createNotification(icon, title, body);
  356. if (delay && delay > 0) notify.addEventListener('display', function () {
  357. setTimeout(function () { hideNotification(notify); }, delay);
  358. });
  359. if (onclick) notify.addEventListener('click', function () {
  360. onclick.apply(this, arguments);
  361. hideNotification(notify);
  362. });
  363. notify.show();
  364. return notify;
  365. },
  366. };
  367.  
  368. // Notification
  369. // Firefox 22+
  370. // 显示4秒会自动关闭 https://bugzil.la/875114
  371. if (typeof Notification !== 'undefined') avaliable.standard = {
  372. 'hasPermission': function () {
  373. return {
  374. 'granted': true,
  375. 'denied': false,
  376. 'default': null,
  377. }[Notification.permission];
  378. },
  379. 'requestPermission': function (callback) {
  380. return Notification.requestPermission(callback);
  381. },
  382. 'hideNotification': function (notify) {
  383. notify.close();
  384. afterHideNotification(notify);
  385. },
  386. 'showNotification': function (id, title, body, icon, delay, onclick) {
  387. if (shownFeed(id)) return null;
  388. var notify = new Notification(title, { 'body': body, 'icon': icon, 'requireInteraction': !delay });
  389. if (delay && delay > 0) notify.addEventListener('show', function () {
  390. setTimeout(function () {
  391. hideNotification(notify);
  392. }, delay);
  393. });
  394. if (onclick) notify.addEventListener('click', function () {
  395. onclick.apply(this, arguments);
  396. hideNotification(notify);
  397. });
  398. return notify;
  399. },
  400. };
  401.  
  402. // 有哪些接口可用
  403. var avaliableNotification = function () {
  404. return Object.keys(avaliable);
  405. };
  406. // 选择用哪个接口
  407. var choseNotification = function (prefer) {
  408. return (use = prefer && avaliable[prefer] || avaliable.standard);
  409. };
  410. choseNotification();
  411. // 检查权限
  412. var hasPermission = function () {
  413. return use.hasPermission.apply(this, arguments);
  414. };
  415. // 请求权限
  416. var requestPermission = function () {
  417. return use.requestPermission.apply(this, arguments);
  418. };
  419. // 显示消息
  420. var showNotification = function (id, title, body, icon, delay, onclick) {
  421. var notify = use.showNotification.apply(this, arguments);
  422. shown.push(notify);
  423. return notify;
  424. };
  425. // 隐藏已经显示的消息
  426. var hideNotification = function (notify) {
  427. use.hideNotification.apply(this, arguments);
  428. return notify;
  429. };
  430. var afterHideNotification = function (notify) {
  431. shown = shown.filter(function (x) { return x !== notify; });
  432. };
  433.  
  434. document.addEventListener('unload', function () {
  435. shown.forEach(hideNotification);
  436. shown = [];
  437. });
  438. var showNotificationAnyway = function (id, title, body, icon, delay, onclick) {
  439. var that = this, thatArguments = arguments;
  440. switch (that.hasPermission()) {
  441. case null: // default
  442. that.requestPermission(function () {
  443. showNotificationAnyway.apply(that, thatArguments);
  444. });
  445. break;
  446. case true: // granted
  447. // 只有已获取了授权, 才能有返回值...
  448. return that.showNotification.apply(that, thatArguments);
  449. break;
  450. case false: // denied
  451. log('Notification permission: denied');
  452. break;
  453. }
  454. return null;
  455. }
  456.  
  457. return {
  458. 'avaliableNotification': avaliableNotification,
  459. 'choseNotification': choseNotification,
  460. 'hasPermission': hasPermission,
  461. 'requestPermission': requestPermission,
  462. 'showNotification': showNotification,
  463. 'hideNotification': hideNotification,
  464. show: function (body, onclick, delay = 3e3) {
  465. return this.showNotificationAnyway(Date.now(), GM_info.script.name, body, '//bangumi.bilibili.com/favicon.ico', delay, onclick)
  466. },
  467. showNotificationAnyway
  468. };
  469. }())
  470. const util_cookie = (function () {
  471. function getCookies() {
  472. var map = document.cookie.split('; ').reduce(function (obj, item) {
  473. var entry = item.split('=');
  474. obj[entry[0]] = entry[1];
  475. return obj;
  476. }, {});
  477. return map;
  478. }
  479.  
  480. function getCookie(key) {
  481. return getCookies()[key];
  482. }
  483.  
  484. /**
  485. * @param key key
  486. * @param value 为undefined时, 表示删除cookie
  487. * @param options 为undefined时, 表示过期时间为3年
  488. * 为''时, 表示Session cookie
  489. * 为数字时, 表示指定过期时间
  490. * 为{}时, 表示指定所有的属性
  491. * */
  492. function setCookie(key, value, options) {
  493. if (typeof options !== 'object') {
  494. options = {
  495. domain: '.bilibili.com',
  496. path: '/',
  497. 'max-age': value === undefined ? 0 : (options === undefined ? 94608000 : options)
  498. };
  499. }
  500. var c = Object.keys(options).reduce(function (str, key) {
  501. return str + '; ' + key + '=' + options[key];
  502. }, key + '=' + value);
  503. document.cookie = c;
  504. return c;
  505. }
  506.  
  507. return new Proxy({ set: setCookie, get: getCookie, all: getCookies }, {
  508. get: function (target, prop) {
  509. if (prop in target) return target[prop]
  510. return getCookie(prop)
  511. },
  512. set: function (target, prop, value) {
  513. setCookie(prop, value)
  514. return true
  515. }
  516. })
  517. }())
  518. const Promise = window.Promise // 在某些情况下, 页面中会修改window.Promise... 故我们要备份一下原始的Promise
  519. const util_promise_plus = (function () {
  520. /**
  521. * 模仿RxJava中的compose操作符
  522. * @param transformer 转换函数, 传入Promise, 返回Promise; 若为空, 则啥也不做
  523. */
  524. Promise.prototype.compose = function (transformer) {
  525. return transformer ? transformer(this) : this
  526. }
  527. }())
  528. const util_promise_timeout = function (timeout) {
  529. return new Promise((resolve, reject) => {
  530. setTimeout(resolve, timeout);
  531. })
  532. }
  533. // 直到满足condition()为止, 才执行promiseCreator(), 创建Promise
  534. // https://stackoverflow.com/questions/40328932/javascript-es6-promise-for-loop
  535. const util_promise_condition = function (condition, promiseCreator, retryCount = Number.MAX_VALUE, interval = 1) {
  536. const loop = (time) => {
  537. if (!condition()) {
  538. if (time < retryCount) {
  539. return util_promise_timeout(interval).then(loop.bind(null, time + 1))
  540. } else {
  541. return Promise.reject(`util_promise_condition timeout, condition: ${condition.toString()}`)
  542. }
  543. } else {
  544. return promiseCreator()
  545. }
  546. }
  547. return loop(0)
  548. }
  549.  
  550. const util_ajax = function (options) {
  551. const creator = () => new Promise(function (resolve, reject) {
  552. typeof options !== 'object' && (options = { url: options });
  553.  
  554. options.async === undefined && (options.async = true);
  555. options.xhrFields === undefined && (options.xhrFields = { withCredentials: true });
  556. options.success = function (data) {
  557. resolve(data);
  558. };
  559. options.error = function (err) {
  560. reject(err);
  561. };
  562. util_debug('ajax:', options.url)
  563. $.ajax(options);
  564. })
  565. return util_promise_condition(() => window.$, creator, 100, 100) // 重试 100 * 100 = 10s
  566. }
  567. /**
  568. * @param promiseCeator 创建Promise的函数
  569. * @param resultTranformer 用于变换result的函数, 返回新的result或Promise
  570. * @param errorTranformer 用于变换error的函数, 返回新的error或Promise, 返回的Promise可以做状态恢复...
  571. */
  572. const util_async_wrapper = function (promiseCeator, resultTranformer, errorTranformer) {
  573. return function (...args) {
  574. return new Promise((resolve, reject) => {
  575. // log(promiseCeator, ...args)
  576. promiseCeator(...args)
  577. .then(r => resultTranformer ? resultTranformer(r) : r)
  578. .then(r => resolve(r))
  579. .catch(e => {
  580. e = errorTranformer ? errorTranformer(e) : e
  581. if (!(e instanceof Promise)) {
  582. // 若返回值不是Promise, 则表示是一个error
  583. e = Promise.reject(e)
  584. }
  585. e.then(r => resolve(r)).catch(e => reject(e))
  586. })
  587. })
  588. }
  589. }
  590. /**
  591. * 创建元素的快捷方法:
  592. * 1. type, props, children
  593. * 2. type, props, innerHTML
  594. * 3. 'text', text
  595. * @param type string, 标签名; 特殊的, 若为text, 则表示创建文字, 对应的t为文字的内容
  596. * @param props object, 属性; 特殊的属性名有: className, 类名; style, 样式, 值为(样式名, 值)形式的object; event, 值为(事件名, 监听函数)形式的object;
  597. * @param children array, 子元素; 也可以直接是html文本;
  598. */
  599. const util_ui_element_creator = (type, props, children) => {
  600. let elem = null;
  601. if (type === "text") {
  602. return document.createTextNode(props);
  603. } else {
  604. elem = document.createElement(type);
  605. }
  606. for (let n in props) {
  607. if (n === "style") {
  608. for (let x in props.style) {
  609. elem.style[x] = props.style[x];
  610. }
  611. } else if (n === "className") {
  612. elem.className = props[n];
  613. } else if (n === "event") {
  614. for (let x in props.event) {
  615. elem.addEventListener(x, props.event[x]);
  616. }
  617. } else {
  618. elem.setAttribute(n, props[n]);
  619. }
  620. }
  621. if (children) {
  622. if (typeof children === 'string') {
  623. elem.innerHTML = children;
  624. } else {
  625. for (let i = 0; i < children.length; i++) {
  626. if (children[i] != null)
  627. elem.appendChild(children[i]);
  628. }
  629. }
  630. }
  631. return elem;
  632. }
  633. const _ = util_ui_element_creator
  634. const util_jsonp = function (url, callback) {
  635. return new Promise((resolve, reject) => {
  636. document.head.appendChild(_('script', {
  637. src: url,
  638. event: {
  639. load: function () {
  640. resolve()
  641. },
  642. error: function () {
  643. reject()
  644. }
  645. }
  646. }));
  647. })
  648. }
  649. const util_generate_sign = function (params, key) {
  650. var s_keys = [];
  651. for (var i in params) {
  652. s_keys.push(i);
  653. }
  654. s_keys.sort();
  655. var data = "";
  656. for (var i = 0; i < s_keys.length; i++) {
  657. // encodeURIComponent 返回的转义数字必须为大写( 如 %2F )
  658. data += (data ? "&" : "") + s_keys[i] + "=" + encodeURIComponent(params[s_keys[i]]);
  659. }
  660. return {
  661. "sign": hex_md5(data + key),
  662. "params": data
  663. };
  664. }
  665. const util_xml2obj = (xml) => {
  666. try {
  667. var obj = {}, text;
  668. var children = xml.children;
  669. if (children.length > 0) {
  670. for (var i = 0; i < children.length; i++) {
  671. var item = children.item(i);
  672. var nodeName = item.nodeName;
  673.  
  674. if (typeof (obj[nodeName]) == "undefined") { // 若是新的属性, 则往obj中添加
  675. obj[nodeName] = util_xml2obj(item);
  676. } else {
  677. if (typeof (obj[nodeName].push) == "undefined") { // 若老的属性没有push方法, 则把属性改成Array
  678. var old = obj[nodeName];
  679.  
  680. obj[nodeName] = [];
  681. obj[nodeName].push(old);
  682. }
  683. obj[nodeName].push(util_xml2obj(item));
  684. }
  685. }
  686. } else {
  687. text = xml.textContent;
  688. if (/^\d+(\.\d+)?$/.test(text)) {
  689. obj = Number(text);
  690. } else if (text === 'true' || text === 'false') {
  691. obj = Boolean(text);
  692. } else {
  693. obj = text;
  694. }
  695. }
  696. return obj;
  697. } catch (e) {
  698. util_error(e);
  699. }
  700. }
  701. const util_ui_popframe = function (iframeSrc) {
  702. if (!document.getElementById('balh-style-login')) {
  703. var style = document.createElement('style');
  704. style.id = 'balh-style-login';
  705. 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}';
  706. }
  707.  
  708. var div = document.createElement('div');
  709. div.id = 'GMBiliPlusLoginContainer';
  710. 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>';
  711. div.firstChild.addEventListener('click', function (e) {
  712. if (e.target === this || e.target.className === 'GMBiliPlusCloseBox') {
  713. if (!confirm('确认关闭?')) {
  714. return false;
  715. }
  716. div.firstChild.style.animationName = 'pop-iframe-out';
  717. setTimeout(function () {
  718. div.remove();
  719. }, 5e2);
  720. }
  721. });
  722. document.body.appendChild(div);
  723. }
  724.  
  725. /**
  726. * - param.content: 内容元素数组/HTML
  727. * - param.showConfirm: 是否显示确定按钮
  728. * - param.confirmBtn: 确定按钮的文字
  729. * - param.onConfirm: 确定回调
  730. * - param.onClose: 关闭回调
  731. */
  732. const util_ui_pop = function (param) {
  733. if (typeof param.content === 'string') {
  734. let template = _('template');
  735. template.innerHTML = param.content.trim()
  736. param.content = Array.from(template.content.childNodes)
  737. } else if (!(param.content instanceof Array)) {
  738. util_log(`param.content(${param.content}) 不是数组`)
  739. return;
  740. }
  741.  
  742. if (document.getElementById('AHP_Notice_style') == null) {
  743. let noticeWidth = Math.min(500, innerWidth - 40);
  744. document.head.appendChild(_('style', { id: 'AHP_Notice_style' }, [_('text', `#AHP_Notice{ line-height:normal;position:fixed;left:0;right:0;top:0;height:0;z-index:20000;transition:.5s;cursor:default;pointer-events:none } .AHP_down_banner{ margin:2px;padding:2px;color:#FFFFFF;font-size:13px;font-weight:bold;background-color:green } .AHP_down_btn{ margin:2px;padding:4px;color:#1E90FF;font-size:14px;font-weight:bold;border:#1E90FF 2px solid;display:inline-block;border-radius:5px } body.ABP-FullScreen{ overflow:hidden } @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)}} #AHP_Notice>div{ position:absolute;bottom:0;left:0;right:0;font-size:15px } #AHP_Notice>div>div{ border:1px #AAA solid;width:${noticeWidth}px;margin:0 auto;padding:20px 10px 5px;background:#EFEFF4;color:#000;border-radius:5px;box-shadow:0 0 5px -2px;pointer-events:auto;white-space:pre-wrap } #AHP_Notice>div>div *{ margin:5px 0; } #AHP_Notice input[type=text]{ border: none;border-bottom: 1px solid #AAA;width: 60%;background: transparent } #AHP_Notice input[type=text]:active{ border-bottom-color:#4285f4 } #AHP_Notice input[type=button] { border-radius: 2px; border: #adadad 1px solid; padding: 3px; margin: 0 5px; min-width:50px } #AHP_Notice input[type=button]:hover { background: #FFF; } #AHP_Notice input[type=button]:active { background: #CCC; } .noflash-alert{display:none}`)]));
  745. }
  746.  
  747. if (document.querySelector('#AHP_Notice') != null)
  748. document.querySelector('#AHP_Notice').remove();
  749.  
  750. let div = _('div', { id: 'AHP_Notice' });
  751. let childs = [];
  752. if (param.showConfirm || param.confirmBtn || param.onConfirm) {
  753. childs.push(_('input', { value: param.confirmBtn || _t('ok'), type: 'button', className: 'confirm', event: { click: param.onConfirm } }));
  754. }
  755. childs.push(_('input', {
  756. value: _t('close'), type: 'button', className: 'close', event: {
  757. click: function () {
  758. param.onClose && param.onClose();
  759. div.style.height = 0;
  760. setTimeout(function () { div.remove(); }, 500);
  761. }
  762. }
  763. }));
  764. div.appendChild(_('div', {}, [_('div', {},
  765. param.content.concat([_('hr'), _('div', { style: { textAlign: 'right' } }, childs)])
  766. )]));
  767. document.body.appendChild(div);
  768. div.style.height = div.firstChild.offsetHeight + 'px';
  769. }
  770.  
  771.  
  772. /**
  773. * MessageBox -> from base.core.js
  774. * MessageBox.show(referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback)
  775. * MessageBox.close()
  776. */
  777. const util_ui_msg = (function () {
  778. function MockMessageBox() {
  779. this.show = (...args) => util_log(MockMessageBox.name, 'show', args)
  780. this.close = (...args) => util_log(MockMessageBox.name, 'close', args)
  781. }
  782.  
  783. let popMessage = null
  784. let mockPopMessage = new MockMessageBox()
  785. let notifyPopMessage = {
  786. _current_notify: null,
  787. show: function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
  788. this.close()
  789. this._current_notify = util_notify.show(message, buttonTypeConfirmCallback, closeTime)
  790. },
  791. close: function () {
  792. if (this._current_notify) {
  793. util_notify.hideNotification(this._current_notify)
  794. this._current_notify = null
  795. }
  796. }
  797. }
  798. let alertPopMessage = {
  799. show: function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
  800. util_ui_alert(message, buttonTypeConfirmCallback)
  801. },
  802. close: util_func_noop
  803. }
  804.  
  805. util_init(() => {
  806. if (!popMessage && window.MessageBox) {
  807. popMessage = new window.MessageBox()
  808. let orignShow = popMessage.show
  809. popMessage.show = function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
  810. // 这个窗,有一定机率弹不出来。。。不知道为什么
  811. orignShow.call(this, referenceElement, message.replace('\n', '<br>'), closeTime, boxType, buttonTypeConfirmCallback)
  812. }
  813. popMessage.close = function () {
  814. // 若没调用过show, 就调用close, msgbox会为null, 导致报错
  815. this.msgbox != null && window.MessageBox.prototype.close.apply(this, arguments)
  816. }
  817. }
  818. }, util_init.PRIORITY.FIRST, util_init.RUN_AT.DOM_LOADED_AFTER)
  819.  
  820. return {
  821. _impl: function () {
  822. return popMessage || alertPopMessage
  823. },
  824. show: function (referenceElement, message, closeTime, boxType, buttonTypeConfirmCallback) {
  825. let pop = this._impl()
  826. return pop.show.apply(pop, arguments)
  827. },
  828. close: function () {
  829. let pop = this._impl()
  830. return pop.close.apply(pop, arguments)
  831. },
  832. setMsgBoxFixed: function (fixed) {
  833. if (popMessage) {
  834. popMessage.msgbox[0].style.position = fixed ? 'fixed' : ''
  835. } else {
  836. util_log(MockMessageBox.name, 'setMsgBoxFixed', fixed)
  837. }
  838. },
  839. showOnNetError: function (e) {
  840. if (e.readyState === 0) {
  841. this.show($('.balh_settings'), '哎呀,服务器连不上了,进入设置窗口,换个服务器试试?', 0, 'button', balh_ui_setting.show);
  842. }
  843. },
  844. showOnNetErrorInPromise: function () {
  845. return p => p
  846. .catch(e => {
  847. this.showOnNetError(e)
  848. return Promise.reject(e)
  849. })
  850. }
  851. }
  852. }())
  853. const util_ui_player_msg = function (message) {
  854. const msg = util_stringify(message)
  855. log('player msg:', msg)
  856. const $panel = document.querySelector('.bilibili-player-video-panel-text')
  857. if ($panel) {
  858. let stage = $panel.children.length + 1000 // 加1000和B站自己发送消息的stage区别开来
  859. $panel.appendChild(_('div', { className: 'bilibili-player-video-panel-row', stage: stage }, [_('text', `[${GM_info.script.name}] ${msg}`)]))
  860. }
  861. }
  862. const util_ui_copy = function (text, textarea) {
  863. textarea.value = text
  864. textarea.select()
  865. try {
  866. return document.execCommand('copy')
  867. } catch (e) {
  868. util_error('复制文本出错', e)
  869. }
  870. return false
  871. }
  872. const util_url_param = function (url, key) {
  873. return (url.match(new RegExp('[?|&]' + key + '=(\\w+)')) || ['', ''])[1];
  874. }
  875.  
  876. const util_page = {
  877. player: () => location.href.includes('www.bilibili.com/blackboard/html5player'),
  878. // 在av页面中的iframe标签形式的player
  879. player_in_av: util_func_catched(() => util_page.player() && window.top.location.href.includes('www.bilibili.com/video/av'), (e) => log(e), false),
  880. av: () => location.href.includes('www.bilibili.com/video/av'),
  881. av_new: function () { return this.av() && (window.__playinfo__ || window.__playinfo__origin) },
  882. bangumi: () => location.href.match(new RegExp('^https?://bangumi\\.bilibili\\.com/anime/\\d+/?$')),
  883. bangumi_md: () => location.href.includes('www.bilibili.com/bangumi/media/md'),
  884. // movie页面使用window.aid, 保存当前页面av号
  885. movie: () => location.href.includes('bangumi.bilibili.com/movie/'),
  886. // anime页面使用window.season_id, 保存当前页面season号
  887. anime: () => location.href.match(new RegExp('^https?://bangumi\\.bilibili\\.com/anime/\\d+/play.*')),
  888. anime_ep: () => location.href.includes('www.bilibili.com/bangumi/play/ep'),
  889. anime_ss: () => location.href.includes('www.bilibili.com/bangumi/play/ss'),
  890. anime_ep_m: () => location.href.includes('m.bilibili.com/bangumi/play/ep'),
  891. anime_ss_m: () => location.href.includes('m.bilibili.com/bangumi/play/ss'),
  892. new_bangumi: () => location.href.includes('www.bilibili.com/bangumi')
  893. }
  894.  
  895. const balh_config = (function () {
  896. const cookies = util_cookie.all() // 缓存的cookies
  897. return new Proxy({ /*保存config的对象*/ }, {
  898. get: function (target, prop) {
  899. if (prop === 'server') {
  900. const server_inner = balh_config.server_inner
  901. const server = server_inner === r.const.server.CUSTOM ? balh_config.server_custom : server_inner
  902. return server
  903. }
  904. if (prop in target) {
  905. return target[prop]
  906. } else { // 若target中不存在指定的属性, 则从缓存的cookies中读取, 并保存到target中
  907. let value = cookies['balh_' + prop]
  908. switch (prop) {
  909. case 'server_inner':
  910. value = value || r.const.server.defaultServer()
  911. // 迁移回biliplus, 只会执行一次
  912. if (util_page.new_bangumi() && !localStorage.balh_migrate_to_1) {
  913. localStorage.balh_migrate_to_1 = r.const.TRUE
  914. if (value.includes('biliplus.ipcjs.top')) {
  915. value = r.const.server.defaultServer()
  916. balh_config.server = value
  917. }
  918. }
  919. break
  920. case 'server_custom':
  921. value = value || ''
  922. break
  923. case 'mode':
  924. value = value || (balh_config.blocked_vip ? r.const.mode.REDIRECT : r.const.mode.DEFAULT)
  925. break
  926. case 'flv_prefer_ws':
  927. value = r.const.FALSE // 关闭该选项
  928. break
  929. default:
  930. // case 'blocked_vip':
  931. // case 'remove_pre_ad':
  932. break
  933. }
  934. target[prop] = value
  935. return value
  936. }
  937. },
  938. set: function (target, prop, value) {
  939. target[prop] = value // 更新值
  940. util_cookie['balh_' + prop] = value // 更新cookie中的值
  941. return true
  942. }
  943. })
  944. }())
  945.  
  946. const balh_api_plus_view = function (aid, update = true) {
  947. return util_ajax(`${balh_config.server}/api/view?id=${aid}&update=${update}`)
  948. }
  949. const balh_api_plus_season = function (season_id) {
  950. return util_ajax(`${balh_config.server}/api/bangumi?season=${season_id}`)
  951. }
  952. // https://www.biliplus.com/BPplayurl.php?otype=json&cid=30188339&module=bangumi&qn=16&src=vupload&vid=vupload_30188339
  953. // qn = 16, 能看
  954. const balh_api_plus_playurl = function (cid, qn = 16, bangumi = true) {
  955. return util_ajax(`${balh_config.server}/BPplayurl.php?otype=json&cid=${cid}${bangumi ? '&module=bangumi' : ''}&qn=${qn}&src=vupload&vid=vupload_${cid}`)
  956. }
  957. // https://www.biliplus.com/api/h5play.php?tid=33&cid=31166258&type=vupload&vid=vupload_31166258&bangumi=1
  958. 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}`)
  959. .then(text => (text.match(/srcUrl=\{"mp4":"(https?.*)"\};/) || ['', ''])[1]); // 提取mp4的url
  960.  
  961. const balh_is_close = false
  962.  
  963. const balh_version_remind = (function () {
  964. if (!util_page.new_bangumi()) return
  965.  
  966. util_init(() => {
  967. if ((localStorage.balh_version || '0') < GM_info.script.version) {
  968. localStorage.balh_version = GM_info.script.version
  969. let version_remind = _t('version_remind')
  970. if (version_remind) {
  971. util_ui_pop({ content: `<h3>${GM_info.script.name} v${GM_info.script.version} 更新日志</h3>${version_remind}` })
  972. }
  973. }
  974. })
  975. })()
  976.  
  977. const balh_feature_switch_to_old_player = (function () {
  978. if (util_page.av() && !localStorage.balh_disable_switch_to_old_player) {
  979. util_init(() => {
  980. let $switchToOldBtn = document.querySelector('#entryOld > .old-btn > a')
  981. if ($switchToOldBtn) {
  982. util_ui_pop({
  983. content: `${GM_info.script.name} 对新版播放器的支持还在测试阶段, 不稳定, 推荐切换回旧版`,
  984. confirmBtn: '切换回旧版',
  985. onConfirm: () => $switchToOldBtn.click(),
  986. onClose: () => localStorage.balh_disable_switch_to_old_player = r.const.TRUE,
  987. })
  988. }
  989. })
  990. }
  991. if (util_page.new_bangumi()) {
  992. if (util_cookie.stardustpgcv === '0606') {
  993. util_init(() => {
  994. let $panel = document.querySelector('.error-container > .server-error')
  995. if ($panel) {
  996. $panel.insertBefore(_('text', '临时切换到旧版番剧页面中...'), $panel.firstChild)
  997. util_cookie.stardustpgcv = '0'
  998. localStorage.balh_temp_switch_to_old_page = r.const.TRUE
  999. location.reload()
  1000. }
  1001. })
  1002. }
  1003. if (localStorage.balh_temp_switch_to_old_page) {
  1004. util_cookie.stardustpgcv = '0606'
  1005. delete localStorage.balh_temp_switch_to_old_page
  1006. }
  1007. }
  1008. })()
  1009. const balh_feature_area_limit_new = (function () {
  1010. if (balh_is_close) return
  1011.  
  1012. if (!(
  1013. (util_page.av() && balh_config.enable_in_av) || util_page.new_bangumi()
  1014. )) {
  1015. return
  1016. }
  1017. function replacePlayInfo() {
  1018. util_log("window.__playinfo__", window.__playinfo__)
  1019. window.__playinfo__origin = window.__playinfo__
  1020. let playinfo = undefined
  1021. // 将__playinfo__置空, 让播放器去重新加载它...
  1022. Object.defineProperty(window, '__playinfo__', {
  1023. configurable: true,
  1024. enumerable: true,
  1025. get: () => {
  1026. log('__playinfo__', 'get')
  1027. return playinfo
  1028. },
  1029. set: (value) => {
  1030. log('__playinfo__', 'set')
  1031. playinfo = value
  1032. },
  1033. })
  1034. }
  1035. // 新的av页面, __playinfo__直接放在head中, 这里可以直接读取到
  1036. if (window.__playinfo__) {
  1037. replacePlayInfo()
  1038. } else {
  1039. // 新的bangumi页面, __playinfo__放在body中, 这里不能直接读取, 需要等dom加载完成才能读取到
  1040. util_init(() => {
  1041. if (window.__playinfo__) {
  1042. replacePlayInfo()
  1043. }
  1044. }, util_init.PRIORITY.FIRST, util_init.RUN_AT.DOM_LOADED)
  1045. }
  1046. })()
  1047. const balh_feature_area_limit = (function () {
  1048. if (balh_is_close) return
  1049.  
  1050. function injectXHR() {
  1051. util_debug('XMLHttpRequest的描述符:', Object.getOwnPropertyDescriptor(window, 'XMLHttpRequest'))
  1052. let firstCreateXHR = true
  1053. window.XMLHttpRequest = new Proxy(window.XMLHttpRequest, {
  1054. construct: function (target, args) {
  1055. // 第一次创建XHR时, 打上断点...
  1056. if (firstCreateXHR && r.script.is_dev) {
  1057. firstCreateXHR = false
  1058. // debugger
  1059. }
  1060. let container = {} // 用来替换responseText等变量
  1061. return new Proxy(new target(...args), {
  1062. set: function (target, prop, value, receiver) {
  1063. if (prop === 'onreadystatechange') {
  1064. container.__onreadystatechange = value
  1065. let cb = value
  1066. value = function (event) {
  1067. if (target.readyState === 4) {
  1068. if (target.responseURL.includes('bangumi.bilibili.com/view/web_api/season/user/status')
  1069. || target.responseURL.includes('api.bilibili.com/pgc/view/web/season/user/status')) {
  1070. log('/season/user/status:', target.responseText)
  1071. let json = JSON.parse(target.responseText)
  1072. let rewriteResult = false
  1073. if (json.code === 0 && json.result) {
  1074. areaLimit(json.result.area_limit !== 0)
  1075. if (json.result.area_limit !== 0) {
  1076. json.result.area_limit = 0 // 取消区域限制
  1077. rewriteResult = true
  1078. }
  1079. if (balh_config.blocked_vip) {
  1080. json.result.pay = 1
  1081. rewriteResult = true
  1082. }
  1083. if (rewriteResult) {
  1084. container.responseText = JSON.stringify(json)
  1085. }
  1086. }
  1087. } else if (target.responseURL.includes('bangumi.bilibili.com/web_api/season_area')) {
  1088. log('/season_area', target.responseText)
  1089. let json = JSON.parse(target.responseText)
  1090. if (json.code === 0 && json.result) {
  1091. areaLimit(json.result.play === 0)
  1092. if (json.result.play === 0) {
  1093. json.result.play = 1
  1094. container.responseText = JSON.stringify(json)
  1095. }
  1096. }
  1097. } else if (target.responseURL.includes('api.bilibili.com/x/web-interface/nav')) {
  1098. let json = JSON.parse(target.responseText)
  1099. log('/x/web-interface/nav', (json.data && json.data.isLogin)
  1100. ? { uname: json.data.uname, isLogin: json.data.isLogin, level: json.data.level_info.current_level, vipType: json.data.vipType, vipStatus: json.data.vipStatus }
  1101. : target.responseText)
  1102. if (json.code === 0 && json.data && balh_config.blocked_vip) {
  1103. json.data.vipType = 2; // 类型, 年度大会员
  1104. json.data.vipStatus = 1; // 状态, 启用
  1105. container.responseText = JSON.stringify(json)
  1106. }
  1107. } else if (target.responseURL.includes('api.bilibili.com/x/player/playurl')) {
  1108. util_log('/x/player/playurl', 'origin', `block: ${container.__block_response}`, target.response)
  1109. // todo : 当前只实现了r.const.mode.REPLACE, 需要支持其他模式
  1110. // 2018-10-14: 等B站全面启用新版再说(;¬_¬)
  1111. }
  1112. if (container.__block_response) {
  1113. // 屏蔽并保存response
  1114. container.__response = target.response
  1115. return
  1116. }
  1117. }
  1118. // 这里的this是原始的xhr, 在container.responseText设置了值时需要替换成代理对象
  1119. cb.apply(container.responseText ? receiver : this, arguments)
  1120. }
  1121. }
  1122. target[prop] = value
  1123. return true
  1124. },
  1125. get: function (target, prop, receiver) {
  1126. if (prop in container) return container[prop]
  1127. let value = target[prop]
  1128. if (typeof value === 'function') {
  1129. let func = value
  1130. // open等方法, 必须在原始的xhr对象上才能调用...
  1131. value = function () {
  1132. if (prop === 'open') {
  1133. container.__method = arguments[0]
  1134. container.__url = arguments[1]
  1135. } else if (prop === 'send') {
  1136. let dispatchResultTransformerCreator = () => {
  1137. container.__block_response = true
  1138. let event = {} // 伪装的event
  1139. // debugger
  1140. return p => p
  1141. .then(r => {
  1142. container.readyState = 4
  1143. container.response = r
  1144. container.__onreadystatechange(event) // 直接调用会不会存在this指向错误的问题? => 目前没看到, 先这样(;¬_¬)
  1145. })
  1146. .catch(e => {
  1147. // 失败时, 让原始的response可以交付
  1148. container.__block_response = false
  1149. if (container.__response != null) {
  1150. container.readyState = 4
  1151. container.response = container.__response
  1152. container.__onreadystatechange(event) // 同上
  1153. }
  1154. })
  1155. }
  1156. if (container.__url.match(/^(https?:)?\/\/api\.bilibili\.com\/x\/player\/playurl.*$/) && balh_config.enable_in_av) {
  1157. log('/x/player/playurl')
  1158. // debugger
  1159. bilibiliApis._playurl.asyncAjax(container.__url)
  1160. .then(data => {
  1161. if (!data.code) {
  1162. data = {
  1163. code: 0,
  1164. data: data,
  1165. message: "0",
  1166. ttl: 1
  1167. }
  1168. }
  1169. util_log('/x/player/playurl', 'proxy', data)
  1170. return data
  1171. })
  1172. .compose(dispatchResultTransformerCreator())
  1173. }
  1174. }
  1175. return func.apply(target, arguments)
  1176. }
  1177. }
  1178. return value
  1179. }
  1180. })
  1181. }
  1182. })
  1183. }
  1184.  
  1185. function injectAjax() {
  1186. log('injectAjax at:', window.jQuery)
  1187. let originalAjax = $.ajax;
  1188. $.ajax = function (arg0, arg1) {
  1189. let param;
  1190. if (arg1 === undefined) {
  1191. param = arg0;
  1192. } else {
  1193. arg0 && (arg1.url = arg0);
  1194. param = arg1;
  1195. }
  1196. let oriSuccess = param.success;
  1197. let oriError = param.error;
  1198. let mySuccess, myError;
  1199. // 投递结果的transformer, 结果通过oriSuccess/Error投递
  1200. let dispatchResultTransformer = p => p
  1201. .then(r => oriSuccess(r))
  1202. .catch(e => oriError(e))
  1203. // 转换原始请求的结果的transformer
  1204. let oriResultTransformer
  1205. let oriResultTransformerWhenProxyError
  1206. let one_api;
  1207. // log(param)
  1208. if (param.url.match('/web_api/get_source')) {
  1209. one_api = bilibiliApis._get_source;
  1210. oriResultTransformer = p => p
  1211. .then(json => {
  1212. log(json);
  1213. if (json.code === -40301 // 区域限制
  1214. || json.result.payment && json.result.payment.price != 0 && balh_config.blocked_vip) { // 需要付费的视频, 此时B站返回的cid是错了, 故需要使用代理服务器的接口
  1215. areaLimit(true);
  1216. return one_api.asyncAjax(param.url)
  1217. .catch(e => json)// 新的请求报错, 也应该返回原来的数据
  1218. } else {
  1219. areaLimit(false);
  1220. if ((balh_config.blocked_vip || balh_config.remove_pre_ad) && json.code === 0 && json.result.pre_ad) {
  1221. json.result.pre_ad = 0; // 去除前置广告
  1222. }
  1223. return json;
  1224. }
  1225. })
  1226. } else if (param.url.match('/player/web_api/playurl') // 老的番剧页面playurl接口
  1227. || param.url.match('/player/web_api/v2/playurl') // 新的番剧页面playurl接口
  1228. || param.url.match(/^(https?:)?\/\/api\.bilibili\.com\/pgc\/player\/web\/playurl.*$/) // 新的番剧页面playurl接口
  1229. || (balh_config.enable_in_av && param.url.match('//interface.bilibili.com/v2/playurl')) // 普通的av页面playurl接口
  1230. ) {
  1231. // 新playrul:
  1232. // 1. 部分页面参数放在param.data中
  1233. // 2. 成功时, 返回的结果放到了result中: {"code":0,"message":"success","result":{}}
  1234. // 3. 失败时, 返回的结果没变
  1235. let isNewPlayurl
  1236. if (isNewPlayurl = param.url.includes('//api.bilibili.com/pgc/player/web/playurl')) {
  1237. if (param.data) {
  1238. param.url += `?${Object.keys(param.data).map(key => `${key}=${param.data[key]}`).join('&')}`
  1239. param.data = undefined
  1240. }
  1241. if (isBangumi(util_safe_get('window.__INITIAL_STATE__.mediaInfo.season_type || window.__INITIAL_STATE__.mediaInfo.ssType'))) {
  1242. log(`playurl add 'module=bangumi' param`)
  1243. param.url += `&module=bangumi`
  1244. }
  1245. }
  1246. one_api = bilibiliApis._playurl;
  1247. if (isNewPlayurl) {
  1248. oriResultTransformerWhenProxyError = p => p
  1249. .then(json => !json.code ? json.result : json)
  1250. }
  1251. oriResultTransformer = p => p
  1252. .then(json => {
  1253. log(json)
  1254. if (isNewPlayurl && !json.code) {
  1255. json = json.result
  1256. }
  1257. if (balh_config.blocked_vip || json.code || isAreaLimitForPlayUrl(json)) {
  1258. areaLimit(true)
  1259. return one_api.asyncAjax(param.url)
  1260. .catch(e => json)
  1261. } else {
  1262. areaLimit(false)
  1263. return json
  1264. }
  1265. })
  1266. const oriDispatchResultTransformer = dispatchResultTransformer
  1267. dispatchResultTransformer = p => p
  1268. .then(r => {
  1269. if (!r.code && !r.from && !r.result && !r.accept_description) {
  1270. util_log('playurl的result缺少必要的字段:', r)
  1271. r.from = 'local'
  1272. r.result = 'suee'
  1273. r.accept_description = ['未知 3P']
  1274. // r.timelength = r.durl.map(it => it.length).reduce((a, b) => a + b, 0)
  1275. if (r.durl && r.durl[0] && r.durl[0].url.includes('video-sg.biliplus.com')) {
  1276. const aid = window.__INITIAL_STATE__ && window.__INITIAL_STATE__.aid || window.__INITIAL_STATE__.epInfo && window.__INITIAL_STATE__.epInfo.aid || 'fuck'
  1277. util_ui_pop({
  1278. content: `原视频已被删除, 当前播放的是<a href="https://video-sg.biliplus.com/">转存服务器</a>中的视频, 速度较慢<br>被删的原因可能是:<br>1. 视频违规<br>2. 视频被归类到番剧页面 => 试下<a href="https://search.bilibili.com/bangumi?keyword=${aid}">搜索av${aid}</a>`
  1279. })
  1280. }
  1281. }
  1282. if (isNewPlayurl && !r.code) {
  1283. r = {
  1284. code: 0,
  1285. message: 'success',
  1286. result: r
  1287. }
  1288. }
  1289. return r
  1290. })
  1291. .compose(oriDispatchResultTransformer)
  1292. } else if (param.url.match('//interface.bilibili.com/player?')) {
  1293. if (balh_config.blocked_vip) {
  1294. mySuccess = function (data) {
  1295. try {
  1296. let xml = new window.DOMParser().parseFromString(`<userstatus>${data.replace(/\&/g, '&amp;')}</userstatus>`, 'text/xml');
  1297. let vipTag = xml.querySelector('vip');
  1298. if (vipTag) {
  1299. let vip = JSON.parse(vipTag.innerHTML);
  1300. vip.vipType = 2; // 类型, 年度大会员
  1301. vip.vipStatus = 1; // 状态, 启用
  1302. vipTag.innerHTML = JSON.stringify(vip);
  1303. data = xml.documentElement.innerHTML;
  1304. }
  1305. } catch (e) {
  1306. log('parse xml error: ', e);
  1307. }
  1308. oriSuccess(data);
  1309. };
  1310. }
  1311. } else if (param.url.match('//api.bilibili.com/x/ad/video?')) {
  1312. if (balh_config.remove_pre_ad) {
  1313. mySuccess = function (data) {
  1314. log('/ad/video', data)
  1315. if (data && data.code === 0 && data.data) {
  1316. data.data = [] // 移除广告接口返回的数据
  1317. }
  1318. oriSuccess(data)
  1319. }
  1320. }
  1321. }
  1322.  
  1323. if (one_api && oriResultTransformer) {
  1324. // 请求结果通过mySuccess/Error获取, 将其包装成Promise, 方便处理
  1325. let oriResultPromise = new Promise((resolve, reject) => {
  1326. mySuccess = resolve
  1327. myError = reject
  1328. })
  1329. if (needRedirect()) {
  1330. // 通过proxy, 执行请求
  1331. one_api.asyncAjax(param.url)
  1332. // proxy报错时, 返回原始请求的结果
  1333. .catch(e => oriResultPromise.compose(oriResultTransformerWhenProxyError))
  1334. .compose(dispatchResultTransformer)
  1335. } else {
  1336. oriResultPromise
  1337. .compose(oriResultTransformer)
  1338. .compose(dispatchResultTransformer)
  1339. }
  1340. }
  1341.  
  1342. // 若外部使用param.success处理结果, 则替换param.success
  1343. if (oriSuccess && mySuccess) {
  1344. param.success = mySuccess;
  1345. }
  1346. // 处理替换error
  1347. if (oriError && myError) {
  1348. param.error = myError;
  1349. }
  1350. // default
  1351. let xhr = originalAjax.apply(this, [param]);
  1352.  
  1353. // 若外部使用xhr.done()处理结果, 则替换xhr.done()
  1354. if (!oriSuccess && mySuccess) {
  1355. xhr.done(mySuccess);
  1356. xhr.done = function (success) {
  1357. oriSuccess = success; // 保存外部设置的success函数
  1358. return xhr;
  1359. };
  1360. }
  1361. // 处理替换error
  1362. if (!oriError && myError) {
  1363. xhr.fail(myError);
  1364. xhr.fail = function (error) {
  1365. oriError = error;
  1366. return xhr;
  1367. }
  1368. }
  1369. return xhr;
  1370. };
  1371. }
  1372.  
  1373. function injectFetch() {
  1374. window.fetch = util_async_wrapper(window.fetch,
  1375. resp => new Proxy(resp, {
  1376. get: function (target, prop, receiver) {
  1377. if (prop === 'json') {
  1378. return util_async_wrapper(target.json.bind(target),
  1379. oriResult => {
  1380. util_debug('injectFetch:', target.url)
  1381. if (target.url.includes('/player/web_api/v2/playurl/html5')) {
  1382. let cid = util_url_param(target.url, 'cid')
  1383. return balh_api_plus_playurl(cid)
  1384. .then(result => {
  1385. if (result.code) {
  1386. return Promise.reject('error: ' + JSON.stringify(result))
  1387. } else {
  1388. return balh_api_plus_playurl_for_mp4(cid)
  1389. .then(url => {
  1390. util_debug(`mp4地址, 移动版: ${url}, pc版: ${result.durl[0].url}`)
  1391. return {
  1392. "code": 0,
  1393. "cid": `http://comment.bilibili.com/${cid}.xml`,
  1394. "timelength": result.timelength,
  1395. "src": url || result.durl[0].url, // 只取第一个片段的url...
  1396. }
  1397. })
  1398. }
  1399. })
  1400. .catch(e => {
  1401. // 若拉取视频地址失败, 则返回原始的结果
  1402. log('fetch mp4 url failed', e)
  1403. return oriResult
  1404. })
  1405. }
  1406. return oriResult
  1407. },
  1408. error => error)
  1409. }
  1410. return target[prop]
  1411. }
  1412. }),
  1413. error => error)
  1414. }
  1415.  
  1416. function isAreaLimitSeason() {
  1417. return util_cookie['balh_season_' + getSeasonId()];
  1418. }
  1419.  
  1420. function needRedirect() {
  1421. return balh_config.mode === r.const.mode.REDIRECT || (balh_config.mode === r.const.mode.DEFAULT && isAreaLimitSeason())
  1422. }
  1423.  
  1424. function areaLimit(limit) {
  1425. balh_config.mode === r.const.mode.DEFAULT && setAreaLimitSeason(limit)
  1426. }
  1427.  
  1428. function setAreaLimitSeason(limit) {
  1429. var season_id = getSeasonId();
  1430. util_cookie.set('balh_season_' + season_id, limit ? '1' : undefined, ''); // 第三个参数为'', 表示时Session类型的cookie
  1431. log('setAreaLimitSeason', season_id, limit);
  1432. }
  1433. /** 使用该方法判断是否需要添加module=bangumi参数, 并不准确... */
  1434. function isBangumi(season_type) {
  1435. log(`season_type: ${season_type}`)
  1436. // 1是动画
  1437. // 5是电视剧
  1438. // 2是电影
  1439. return season_type != null // 有season_type, 就是bangumi?
  1440. }
  1441.  
  1442. function getSeasonId() {
  1443. var seasonId;
  1444. // 取anime页面的seasonId
  1445. try {
  1446. // 若w, 是其frame的window, 则有可能没有权限, 而抛异常
  1447. seasonId = window.season_id || window.top.season_id;
  1448. } catch (e) {
  1449. log(e);
  1450. }
  1451. if (!seasonId) {
  1452. try {
  1453. seasonId = (window.top.location.pathname.match(/\/anime\/(\d+)/) || ['', ''])[1];
  1454. } catch (e) {
  1455. log(e);
  1456. }
  1457. }
  1458.  
  1459. // 若没取到, 则取movie页面的seasonId, 以m开头
  1460. if (!seasonId) {
  1461. try {
  1462. seasonId = (window.top.location.pathname.match(/\/movie\/(\d+)/) || ['', ''])[1];
  1463. if (seasonId) {
  1464. seasonId = 'm' + seasonId;
  1465. }
  1466. } catch (e) {
  1467. log(e);
  1468. }
  1469. }
  1470.  
  1471. // 若没取到, 则去新的番剧播放页面的ep或ss
  1472. if (!seasonId) {
  1473. try {
  1474. seasonId = (window.top.location.pathname.match(/\/bangumi\/play\/((ep|ss)\d+)/) || ['', ''])[1];
  1475. } catch (e) {
  1476. log(e);
  1477. }
  1478. }
  1479. // 若没取到, 则去取av页面的av号
  1480. if (!seasonId) {
  1481. try {
  1482. seasonId = (window.top.location.pathname.match(/\/video\/(av\d+)/) || ['', ''])[1]
  1483. } catch (e) {
  1484. log(e);
  1485. }
  1486. }
  1487. // 最后, 若没取到, 则试图取出当前页面url中的aid
  1488. if (!seasonId) {
  1489. seasonId = util_url_param(window.location.href, 'aid');
  1490. if (seasonId) {
  1491. seasonId = 'aid' + seasonId;
  1492. }
  1493. }
  1494. return seasonId || '000';
  1495. }
  1496.  
  1497. function isAreaLimitForPlayUrl(json) {
  1498. return json.durl && json.durl.length === 1 && json.durl[0].length === 15126 && json.durl[0].size === 124627;
  1499. }
  1500.  
  1501. var bilibiliApis = (function () {
  1502. function AjaxException(message, code = 0/*用0表示未知错误*/) {
  1503. this.name = 'AjaxException'
  1504. this.message = message
  1505. this.code = code
  1506. }
  1507. AjaxException.prototype.toString = function () {
  1508. return `${this.name}: ${this.message}(${this.code})`
  1509. }
  1510. function BilibiliApi(props) {
  1511. Object.assign(this, props);
  1512. }
  1513.  
  1514. BilibiliApi.prototype.asyncAjaxByProxy = function (originUrl, success, error) {
  1515. var one_api = this;
  1516. $.ajax({
  1517. url: one_api.transToProxyUrl(originUrl),
  1518. async: true,
  1519. xhrFields: { withCredentials: true },
  1520. success: function (result) {
  1521. log('==>', result);
  1522. success(one_api.processProxySuccess(result));
  1523. // log('success', arguments, this);
  1524. },
  1525. error: function (e) {
  1526. log('error', arguments, this);
  1527. error(e);
  1528. }
  1529. });
  1530. };
  1531. BilibiliApi.prototype.asyncAjax = function (originUrl) {
  1532. return util_ajax(this.transToProxyUrl(originUrl))
  1533. .then(r => this.processProxySuccess(r))
  1534. .compose(util_ui_msg.showOnNetErrorInPromise()) // 出错时, 提示服务器连不上
  1535. }
  1536. var get_source_by_aid = new BilibiliApi({
  1537. transToProxyUrl: function (url) {
  1538. return balh_config.server + '/api/view?id=' + window.aid + '&update=true';
  1539. },
  1540. processProxySuccess: function (data) {
  1541. if (data && data.list && data.list[0] && data.movie) {
  1542. return {
  1543. code: 0,
  1544. message: 'success',
  1545. result: {
  1546. cid: data.list[0].cid,
  1547. formal_aid: data.aid,
  1548. movie_status: balh_config.blocked_vip ? 2 : data.movie.movie_status, // 2, 大概是免费的意思?
  1549. pay_begin_time: 1507708800,
  1550. pay_timestamp: 0,
  1551. pay_user_status: data.movie.pay_user.status, // 一般都是0
  1552. player: data.list[0].type, // 一般为movie
  1553. vid: data.list[0].vid,
  1554. vip: { // 2+1, 表示年度大会员; 0+0, 表示普通会员
  1555. vipType: balh_config.blocked_vip ? 2 : 0,
  1556. vipStatus: balh_config.blocked_vip ? 1 : 0,
  1557. }
  1558. }
  1559. };
  1560. } else {
  1561. return {
  1562. code: -404,
  1563. message: '不存在该剧集'
  1564. };
  1565. }
  1566. }
  1567. });
  1568. var get_source_by_season_id = new BilibiliApi({
  1569. transToProxyUrl: function (url) {
  1570. return balh_config.server + '/api/bangumi?season=' + window.season_id;
  1571. },
  1572. processProxySuccess: function (data) {
  1573. var found = null;
  1574. if (!data.code) {
  1575. for (var i = 0; i < data.result.episodes.length; i++) {
  1576. if (data.result.episodes[i].episode_id == window.episode_id) {
  1577. found = data.result.episodes[i];
  1578. }
  1579. }
  1580. } else {
  1581. util_ui_alert('代理服务器错误:' + JSON.stringify(data) + '\n点击刷新界面.', window.location.reload.bind(window.location));
  1582. }
  1583. var returnVal = found !== null
  1584. ? {
  1585. "code": 0,
  1586. "message": "success",
  1587. "result": {
  1588. "aid": found.av_id,
  1589. "cid": found.danmaku,
  1590. "episode_status": balh_config.blocked_vip ? 2 : found.episode_status,
  1591. "payment": { "price": "9876547210.33" },
  1592. "pay_user": {
  1593. "status": balh_config.blocked_vip ? 1 : 0 // 是否已经支付过
  1594. },
  1595. "player": "vupload",
  1596. "pre_ad": 0,
  1597. "season_status": balh_config.blocked_vip ? 2 : data.result.season_status
  1598. }
  1599. }
  1600. : { code: -404, message: '不存在该剧集' };
  1601. return returnVal;
  1602. }
  1603. });
  1604. var playurl_by_bilibili = new BilibiliApi({
  1605. dataType: 'xml',
  1606. transToProxyUrl: function (originUrl) {
  1607. const api_url = 'https://interface.bilibili.com/playurl?'
  1608. const bangumi_api_url = 'https://bangumi.bilibili.com/player/web_api/playurl?'
  1609. const SEC_NORMAL = '1c15888dc316e05a15fdd0a02ed6584f'
  1610. const SEC_BANGUMI = '9b288147e5474dd2aa67085f716c560d'
  1611.  
  1612. // 不设置module; 带module的接口都是有区域限制的...
  1613. let module = undefined /*util_url_param(originUrl, 'module')*/
  1614. // 不使用json; 让服务器直接返回json时, 获取的视频url不能直接播放...天知道为什么
  1615. let useJson = false
  1616. let paramDict = {
  1617. cid: util_url_param(originUrl, 'cid'),
  1618. quality: util_url_param(originUrl, 'quality'),
  1619. qn: util_url_param(originUrl, 'qn'), // 增加这个参数, 返回的清晰度更多
  1620. player: 1,
  1621. ts: Math.floor(Date.now() / 1000),
  1622. }
  1623. if (module) paramDict.module = module
  1624. if (useJson) paramDict.otype = 'json'
  1625. let { sign, params } = util_generate_sign(paramDict, module ? SEC_BANGUMI : SEC_NORMAL)
  1626. let url = module ? bangumi_api_url : api_url + params + '&sign=' + sign
  1627. return url
  1628. },
  1629. processProxySuccess: function (result, alertWhenError = true) {
  1630. // 将xml解析成json
  1631. let obj = util_xml2obj(result.documentElement)
  1632. if (!obj || obj.code) {
  1633. if (alertWhenError) {
  1634. util_ui_alert(`从B站接口获取视频地址失败\nresult: ${JSON.stringify(obj)}\n\n点击确定, 进入设置页面关闭'使用B站接口获取视频地址'功能`, balh_ui_setting.show)
  1635. } else {
  1636. return Promise.reject(`服务器错误: ${JSON.stringify(obj)}`)
  1637. }
  1638. } else {
  1639. obj.accept_quality && (obj.accept_quality = obj.accept_quality.split(',').map(n => +n))
  1640. if (!obj.durl.push) {
  1641. obj.durl = [obj.durl]
  1642. }
  1643. obj.durl.forEach((item) => {
  1644. if (item.backup_url === '') {
  1645. item.backup_url = undefined
  1646. } else if (item.backup_url && item.backup_url.url) {
  1647. item.backup_url = item.backup_url.url
  1648. }
  1649. })
  1650. }
  1651. log('xml2obj', result, '=>', obj)
  1652. return obj
  1653. },
  1654. _asyncAjax: function (originUrl) {
  1655. return util_ajax(this.transToProxyUrl(originUrl))
  1656. .then(r => this.processProxySuccess(r, false))
  1657. }
  1658. })
  1659. var playurl_by_proxy = new BilibiliApi({
  1660. _asyncAjax: function (originUrl, bangumi) {
  1661. return util_ajax(this.transToProxyUrl(originUrl, bangumi))
  1662. .then(r => this.processProxySuccess(r, false))
  1663. },
  1664. transToProxyUrl: function (url, bangumi) {
  1665. let params = url.split('?')[1];
  1666. if (bangumi === undefined) { // 自动判断
  1667. // av页面中的iframe标签形式的player, 不是番剧视频
  1668. bangumi = !util_page.player_in_av()
  1669. // url中存在season_type的情况
  1670. let season_type_param = util_url_param(url, 'season_type')
  1671. if (season_type_param && !isBangumi(+season_type_param)) {
  1672. bangumi = false
  1673. }
  1674. if (!bangumi) {
  1675. params = params.replace(/&?module=(\w+)/, '') // 移除可能存在的module参数
  1676. }
  1677. } else if (bangumi === true) { // 保证添加module=bangumi参数
  1678. params = params.replace(/&?module=(\w+)/, '')
  1679. params += '&module=bangumi'
  1680. } else if (bangumi === false) { // 移除可能存在的module参数
  1681. params = params.replace(/&?module=(\w+)/, '')
  1682. }
  1683. return `${balh_config.server}/BPplayurl.php?${params}`;
  1684. },
  1685. processProxySuccess: function (data, alertWhenError = true) {
  1686. // data有可能为null
  1687. if (data && data.code === -403) {
  1688. util_ui_alert(`突破黑洞失败\n当前代理服务器(${balh_config.server})依然有区域限制\n\n可以考虑进行如下尝试:\n1. 进行“帐号授权”\n2. 换个代理服务器\n\n点击确定, 打开设置页面`, balh_ui_setting.show)
  1689. } else if (data === null || data.code) {
  1690. util_error(data);
  1691. if (alertWhenError) {
  1692. util_ui_alert(`突破黑洞失败\n${JSON.stringify(data)}\n点击确定刷新界面`, window.location.reload.bind(window.location));
  1693. } else {
  1694. return Promise.reject(new AjaxException(`服务器错误: ${JSON.stringify(data)}`, data ? data.code : 0))
  1695. }
  1696. } else if (isAreaLimitForPlayUrl(data)) {
  1697. util_error('>>area limit');
  1698. util_ui_pop({
  1699. content: `突破黑洞失败\n需要登录\n点此确定进行登录`,
  1700. onConfirm: balh_feature_sign.showLogin
  1701. })
  1702. } else {
  1703. if (balh_config.flv_prefer_ws) {
  1704. data.durl.forEach(function (seg) {
  1705. var t, url, i;
  1706. if (!seg.url.includes('ws.acgvideo.com')) {
  1707. for (i in seg.backup_url) {
  1708. url = seg.backup_url[i];
  1709. if (url.includes('ws.acgvideo.com')) {
  1710. log('flv prefer use:', url);
  1711. t = seg.url;
  1712. seg.url = url;
  1713. url = t;
  1714. break;
  1715. }
  1716. }
  1717.  
  1718. }
  1719. });
  1720. }
  1721. }
  1722. return data;
  1723. }
  1724. })
  1725. const playurl = new BilibiliApi({
  1726. asyncAjax: function (originUrl) {
  1727. util_ui_player_msg('从代理服务器拉取视频地址中...')
  1728. return playurl_by_proxy._asyncAjax(originUrl) // 优先从代理服务器获取
  1729. .catch(e => {
  1730. if (e instanceof AjaxException) {
  1731. util_ui_player_msg(e)
  1732. if (e.code === 1) { // code: 1 表示非番剧视频, 不能使用番剧视频参数
  1733. util_ui_player_msg('尝试使用非番剧视频接口拉取视频地址...')
  1734. return playurl_by_proxy._asyncAjax(originUrl, false)
  1735. .catch(e2 => Promise.reject(e)) // 忽略e2, 返回原始错误e
  1736. } else if (e.code === 10004) { // code: 10004, 表示视频被隐藏, 一般添加module=bangumi参数可以拉取到视频
  1737. util_ui_player_msg('尝试使用番剧视频接口拉取视频地址...')
  1738. return playurl_by_proxy._asyncAjax(originUrl, true)
  1739. .catch(e2 => Promise.reject(e))
  1740. }
  1741. }
  1742. return Promise.reject(e)
  1743. })
  1744. // 报错时, 延时1秒再发送错误信息
  1745. .catch(e => util_promise_timeout(1000).then(r => Promise.reject(e)))
  1746. .catch(e => {
  1747. let msg
  1748. if (typeof e === 'object' && e.statusText == 'error') {
  1749. msg = '代理服务器临时不可用'
  1750. util_ui_player_msg(msg)
  1751. } else {
  1752. msg = util_stringify(e)
  1753. }
  1754. util_ui_pop({
  1755. content: `## 拉取视频地址失败\n原因: ${msg}\n\n可以考虑进行如下尝试:\n1. 多刷新几下页面\n2. 进入设置页面更换代理服务器\n3. 耐心等待代理服务器端修复问题`,
  1756. onConfirm: window.location.reload.bind(window.location),
  1757. confirmBtn: '刷新页面'
  1758. })
  1759. return Promise.reject(e)
  1760. })
  1761. }
  1762. })
  1763. return {
  1764. _get_source: util_page.movie() ? get_source_by_aid : get_source_by_season_id,
  1765. _playurl: playurl,
  1766. };
  1767. })();
  1768.  
  1769. if (util_page.anime_ep_m() || util_page.anime_ss_m()) {
  1770. // balh_api_plus_playurl_for_mp4返回的url能在移动设备上播放的前提是, 请求头不包含Referer...
  1771. // 故这里设置meta, 使页面不发送Referer
  1772. // 注意动态改变引用策略的方式并不是标准行为, 目前在Chrome上测试是有用的
  1773. document.head.appendChild(_('meta', { name: "referrer", content: "no-referrer" }))
  1774. injectFetch()
  1775. util_init(() => {
  1776. const $wrapper = document.querySelector('.player-wrapper')
  1777. new MutationObserver(function (mutations, observer) {
  1778. for (let mutation of mutations) {
  1779. if (mutation.type === 'childList') {
  1780. for (let node of mutation.addedNodes) {
  1781. if (node.tagName === 'DIV' && node.className.split(' ').includes('player-mask')) {
  1782. log('隐藏添加的mask')
  1783. node.style.display = 'none'
  1784. }
  1785. }
  1786. }
  1787. }
  1788. }).observe($wrapper, {
  1789. childList: true,
  1790. attributes: false,
  1791. });
  1792. })
  1793. }
  1794. injectXHR();
  1795. if (true) {
  1796. let jQuery = window.jQuery;
  1797. if (jQuery) { // 若已加载jQuery, 则注入
  1798. injectAjax()
  1799. }
  1800. // 需要监听jQuery变化, 因为有时会被设置多次...
  1801. Object.defineProperty(window, 'jQuery', {
  1802. configurable: true, enumerable: true, set: function (v) {
  1803. // debugger
  1804. log('set jQuery', jQuery, '->', v)
  1805. // 临时规避这个问题:https://github.com/ipcjs/bilibili-helper/issues/297
  1806. // 新的av页面中, 运行脚本的 injectXHR() 后, 页面会往该方法先后设置两个jQuery...原因未知
  1807. // 一个从jquery.min.js中设置, 一个从player.js中设置
  1808. // 并且点击/载入等事件会从两个jQuery中向下分发...导致很多功能失常
  1809. // 这里我们屏蔽掉jquery.min.js分发的一些事件, 避免一些问题
  1810. if (util_page.av_new() && balh_config.enable_in_av) {
  1811. try { // 获取调用栈的方法不是标准方法, 需要try-catch
  1812. const stack = (new Error()).stack.split('\n')
  1813. if (stack[stack.length - 1].includes('jquery')) { // 若从jquery.min.js中调用
  1814. log('set jQueury by jquery.min.js', v)
  1815. v.fn.balh_on = v.fn.on
  1816. v.fn.on = function (arg0, arg1) {
  1817. if (arg0 === 'click.reply' && arg1 === '.reply') {
  1818. // 屏蔽掉"回复"按钮的点击事件
  1819. log('block click.reply', arguments)
  1820. return
  1821. }
  1822. return v.fn.balh_on.apply(this, arguments)
  1823. }
  1824. }
  1825. // jQuery.fn.paging方法用于创建评论区的页标, 需要迁移到新的jQuery上
  1826. if (jQuery != null && jQuery.fn.paging != null
  1827. && v != null && v.fn.paging == null) {
  1828. log('迁移jQuery.fn.paging')
  1829. v.fn.paging = jQuery.fn.paging
  1830. }
  1831. } catch (e) {
  1832. util_error(e)
  1833. }
  1834. }
  1835.  
  1836. jQuery = v;
  1837. injectAjax();// 设置jQuery后, 立即注入
  1838. }, get: function () {
  1839. return jQuery;
  1840. }
  1841. });
  1842. }
  1843. }())
  1844. const balh_feature_remove_pre_ad = (function () {
  1845. if (util_page.player()) {
  1846. // 播放页面url中的pre_ad参数, 决定是否播放广告...
  1847. if (balh_config.remove_pre_ad && util_url_param(location.href, 'pre_ad') == 1) {
  1848. log('需要跳转到不含广告的url')
  1849. location.href = location.href.replace(/&?pre_ad=1/, '')
  1850. }
  1851. }
  1852. }())
  1853. const balh_feature_check_html5 = (function () {
  1854. function isHtml5Player() {
  1855. return localStorage.defaulth5 === '1'
  1856. }
  1857.  
  1858. function checkHtml5() {
  1859. var playerContent = document.querySelector('.player-content');
  1860. if (!localStorage.balh_h5_not_first && !isHtml5Player() && window.GrayManager && playerContent) {
  1861. new MutationObserver(function (mutations, observer) {
  1862. observer.disconnect();
  1863. localStorage.balh_h5_not_first = r.const.TRUE;
  1864. if (window.confirm(GM_info.script.name + '只在HTML5播放器下有效,是否切换到HTML5?')) {
  1865. window.GrayManager.clickMenu('change_h5');// change_flash, change_h5
  1866. }
  1867. }).observe(playerContent, {
  1868. childList: true, // 监听child的增减
  1869. attributes: false, // 监听属性的变化
  1870. });
  1871. }
  1872. }
  1873.  
  1874. util_init(() => {
  1875. // 除了播放器和番剧列表页面, 其他页面都需要检测html5
  1876. if (!(util_page.bangumi() || util_page.bangumi_md() || util_page.player())) {
  1877. checkHtml5()
  1878. }
  1879. })
  1880. return isHtml5Player
  1881. }())
  1882. const balh_feature_runPing = function () {
  1883. var pingOutput = document.getElementById('balh_server_ping');
  1884.  
  1885. var xhr = new XMLHttpRequest(), testUrl = [r.const.server.S0, r.const.server.S1],
  1886. testUrlIndex = 0, isReused = false, prevNow, outputArr = [];
  1887. if (balh_config.server_custom) {
  1888. testUrl.push(balh_config.server_custom)
  1889. }
  1890. pingOutput.textContent = '正在进行服务器测速…';
  1891. pingOutput.style.height = '100px';
  1892. xhr.open('GET', '', true);
  1893. xhr.onreadystatechange = function () {
  1894. this.readyState == 4 && pingResult();
  1895. };
  1896. var pingLoop = function () {
  1897. prevNow = performance.now();
  1898. xhr.open('GET', testUrl[testUrlIndex] + '/api/bangumi', true);
  1899. xhr.send();
  1900. };
  1901. var pingResult = function () {
  1902. var duration = (performance.now() - prevNow) | 0;
  1903. if (isReused)
  1904. outputArr.push('\t复用连接:' + duration + 'ms'), isReused = false, testUrlIndex++;
  1905. else
  1906. outputArr.push(testUrl[testUrlIndex] + ':'), outputArr.push('\t初次连接:' + duration + 'ms'), isReused = true;
  1907. pingOutput.textContent = outputArr.join('\n');
  1908. testUrlIndex < testUrl.length ? pingLoop() : pingOutput.appendChild(_('a', { href: 'javascript:', event: { click: balh_feature_runPing } }, [_('text', '\n再测一次?')]));
  1909. };
  1910. pingLoop();
  1911. }
  1912. const balh_feature_sign = (function () {
  1913. function isLogin() {
  1914. return localStorage.oauthTime !== undefined
  1915. }
  1916. function clearLoginFlag() {
  1917. delete localStorage.oauthTime
  1918. }
  1919.  
  1920. function updateLoginFlag(loadCallback) {
  1921. util_jsonp(balh_config.server + '/login?act=expiretime')
  1922. .then(() => loadCallback && loadCallback(true))
  1923. // .catch(() => loadCallback && loadCallback(false)) // 请求失败不需要回调
  1924. }
  1925. function isLoginBiliBili() {
  1926. return util_cookie['DedeUserID'] !== undefined
  1927. }
  1928. // 当前在如下情况才会弹一次登录提示框:
  1929. // 1. 第一次使用
  1930. // 2. 主站+服务器都退出登录后, 再重新登录主站
  1931. function checkLoginState() {
  1932. // 给一些状态,设置初始值
  1933. localStorage.balh_must_remind_login_v1 === undefined && (localStorage.balh_must_remind_login_v1 = r.const.TRUE)
  1934.  
  1935. if (isLoginBiliBili()) {
  1936. if (!localStorage.balh_old_isLoginBiliBili // 主站 不登录 => 登录
  1937. || localStorage.balh_pre_server !== balh_config.server // 代理服务器改变了
  1938. || localStorage.balh_must_remind_login_v1) { // 设置了"必须提醒"flag
  1939. clearLoginFlag()
  1940. updateLoginFlag(() => {
  1941. if (!isLogin()) {
  1942. localStorage.balh_must_remind_login_v1 = r.const.FALSE;
  1943. util_ui_pop({
  1944. content: [
  1945. _('text', `${GM_info.script.name}\n要不要考虑进行一下授权?\n\n授权后可以观看区域限定番剧的1080P\n(如果你是大会员或承包过这部番的话)\n\n你可以随时在设置中打开授权页面`)
  1946. ],
  1947. onConfirm: () => {
  1948. balh_feature_sign.showLogin();
  1949. document.querySelector('#AHP_Notice').remove()
  1950. }
  1951. })
  1952. }
  1953. })
  1954. } else if ((isLogin() && Date.now() - parseInt(localStorage.oauthTime) > 24 * 60 * 60 * 1000) // 已登录,每天为周期检测key有效期,过期前五天会自动续期
  1955. || localStorage.balh_must_updateLoginFlag) {// 某些情况下,必须更新一次
  1956. updateLoginFlag(() => localStorage.balh_must_updateLoginFlag = r.const.FALSE);
  1957. }
  1958. }
  1959. localStorage.balh_old_isLoginBiliBili = isLoginBiliBili() ? r.const.TRUE : r.const.FALSE
  1960. localStorage.balh_pre_server = balh_config.server
  1961. }
  1962.  
  1963. function showLogin() {
  1964. const balh_auth_window = window.open('about:blank');
  1965. balh_auth_window.document.title = 'BALH - 授权';
  1966. balh_auth_window.document.body.innerHTML = '<meta charset="UTF-8" name="viewport" content="width=device-width">正在获取授权,请稍候……';
  1967. window.balh_auth_window = balh_auth_window;
  1968. $.ajax('https://passport.bilibili.com/login/app/third?appkey=27eb53fc9058f8c3&api=http%3A%2F%2Flink.acg.tv%2Fforum.php&sign=67ec798004373253d60114caaad89a8c', {
  1969. xhrFields: { withCredentials: true },
  1970. type: 'GET',
  1971. dataType: 'json',
  1972. success: (data) => {
  1973. if (data.data.has_login) {
  1974. balh_auth_window.document.body.innerHTML = '<meta charset="UTF-8" name="viewport" content="width=device-width">正在跳转……';
  1975. balh_auth_window.location.href = data.data.confirm_uri;
  1976. } else {
  1977. balh_auth_window.close()
  1978. util_ui_alert('必须登录B站才能正常授权', () => {
  1979. location.href = 'https://passport.bilibili.com/login'
  1980. })
  1981. }
  1982. },
  1983. error: (e) => {
  1984. alert('error');
  1985. }
  1986. })
  1987. }
  1988.  
  1989. function showLoginByPassword() {
  1990. const loginUrl = balh_config.server + '/login'
  1991. util_ui_pop({
  1992. content: `B站当前关闭了第三方登录的接口<br>目前只能使用帐号密码的方式<a href="${loginUrl}">登录代理服务器</a><br><br>登录完成后, 请手动刷新当前页面`,
  1993. confirmBtn: '前往登录页面',
  1994. onConfirm: () => {
  1995. window.open(loginUrl)
  1996. }
  1997. })
  1998. }
  1999.  
  2000. function showLogout() {
  2001. util_ui_popframe(balh_config.server + '/login?act=logout')
  2002. }
  2003.  
  2004. // 监听登录message
  2005. window.addEventListener('message', function (e) {
  2006. if (typeof e.data !== 'string') return // 只处理e.data为string的情况
  2007. switch (e.data.split(':')[0]) {
  2008. case 'BiliPlus-Login-Success': {
  2009. //登入
  2010. localStorage.balh_must_updateLoginFlag = r.const.TRUE
  2011. Promise.resolve('start')
  2012. .then(() => util_jsonp(balh_config.server + '/login?act=getlevel'))
  2013. .then(() => location.reload())
  2014. .catch(() => location.reload())
  2015. break;
  2016. }
  2017. case 'BiliPlus-Logout-Success': {
  2018. //登出
  2019. clearLoginFlag()
  2020. location.reload()
  2021. break;
  2022. }
  2023. case 'balh-login-credentials': {
  2024. balh_auth_window.close();
  2025. let url = e.data.split(': ')[1];
  2026. util_ui_popframe(url.replace('http://link.acg.tv/forum.php', balh_config.server + '/login'));
  2027. break;
  2028. }
  2029. }
  2030. })
  2031.  
  2032.  
  2033. util_init(() => {
  2034. if (!(util_page.player() || util_page.av())) {
  2035. checkLoginState()
  2036. }
  2037. }, util_init.PRIORITY.DEFAULT, util_init.RUN_AT.DOM_LOADED_AFTER)
  2038. return {
  2039. showLogin,
  2040. showLogout,
  2041. isLogin,
  2042. isLoginBiliBili,
  2043. }
  2044. }())
  2045. const balh_feature_RedirectToBangumiOrInsertPlayer = (function () {
  2046. // 重定向到Bangumi页面, 或者在当前页面直接插入播放页面
  2047. function tryRedirectToBangumiOrInsertPlayer() {
  2048. let $errorPanel;
  2049. if (!($errorPanel = document.querySelector('.error-container > .error-panel'))) {
  2050. return;
  2051. }
  2052. let msg = document.createElement('a');
  2053. $errorPanel.insertBefore(msg, $errorPanel.firstChild);
  2054. msg.innerText = '获取番剧页Url中...';
  2055. let aid = location.pathname.replace(/.*av(\d+).*/, '$1'),
  2056. page = (location.pathname.match(/\/index_(\d+).html/) || ['', '1'])[1],
  2057. cid,
  2058. season_id,
  2059. episode_id;
  2060. let avData;
  2061. balh_api_plus_view(aid)
  2062. .then(function (data) {
  2063. avData = data;
  2064. if (data.code) {
  2065. return Promise.reject(JSON.stringify(data));
  2066. }
  2067. // 计算当前页面的cid
  2068. for (let i = 0; i < data.list.length; i++) {
  2069. if (data.list[i].page == page) {
  2070. cid = data.list[i].cid;
  2071. break;
  2072. }
  2073. }
  2074. if (!data.bangumi) {
  2075. generatePlayer(data, aid, page, cid)
  2076. // return Promise.reject('该AV号不属于任何番剧页');//No bangumi in api response
  2077. } else {
  2078. // 当前av属于番剧页面, 继续处理
  2079. season_id = data.bangumi.season_id;
  2080. return balh_api_plus_season(season_id);
  2081. }
  2082. })
  2083. .then(function (result) {
  2084. if (result === undefined) return // 上一个then不返回内容时, 不需要处理
  2085. if (result.code === 10) { // av属于番剧页面, 通过接口却未能找到番剧信息
  2086. let ep_id_newest = avData && avData.bangumi && avData.bangumi.newest_ep_id
  2087. if (ep_id_newest) {
  2088. episode_id = ep_id_newest // 此时, 若avData中有最新的ep_id, 则直接使用它
  2089. } else {
  2090. log(`av${aid}属于番剧${season_id}, 但却不能找到番剧页的信息, 试图直接创建播放器`)
  2091. generatePlayer(avData, aid, page, cid)
  2092. return
  2093. }
  2094. } else if (result.code) {
  2095. return Promise.reject(JSON.stringify(result))
  2096. } else {
  2097. let ep_id_by_cid, ep_id_by_aid_page, ep_id_by_aid,
  2098. episodes = result.result.episodes,
  2099. ep
  2100. // 为何要用三种不同方式匹配, 详见: https://greasyfork.org/zh-CN/forum/discussion/22379/x#Comment_34127
  2101. for (let i = 0; i < episodes.length; i++) {
  2102. ep = episodes[i]
  2103. if (ep.danmaku == cid) {
  2104. ep_id_by_cid = ep.episode_id
  2105. }
  2106. if (ep.av_id == aid && ep.page == page) {
  2107. ep_id_by_aid_page = ep.episode_id
  2108. }
  2109. if (ep.av_id == aid) {
  2110. ep_id_by_aid = ep.episode_id
  2111. }
  2112. }
  2113. episode_id = ep_id_by_cid || ep_id_by_aid_page || ep_id_by_aid
  2114. }
  2115. if (episode_id) {
  2116. let bangumi_url = `//www.bilibili.com/bangumi/play/ss${season_id}#${episode_id}`
  2117. log('Redirect', 'aid:', aid, 'page:', page, 'cid:', cid, '==>', bangumi_url, 'season_id:', season_id, 'ep_id:', episode_id)
  2118. msg.innerText = '即将跳转到:' + bangumi_url
  2119. location.href = bangumi_url
  2120. } else {
  2121. return Promise.reject('查询episode_id失败')
  2122. }
  2123. })
  2124. .catch(function (e) {
  2125. log('error:', arguments);
  2126. msg.innerText = 'error:' + e;
  2127. });
  2128. }
  2129.  
  2130. function generatePlayer(data, aid, page, cid) {
  2131. let generateSrc = function (aid, cid) {
  2132. return `//www.bilibili.com/blackboard/html5player.html?cid=${cid}&aid=${aid}&player_type=1`;
  2133. }
  2134. let generatePageList = function (pages) {
  2135. let $curPage = null;
  2136. function onPageBtnClick(e) {
  2137. e.target.className = 'curPage'
  2138. $curPage && ($curPage.className = '')
  2139.  
  2140. let index = e.target.attributes['data-index'].value;
  2141. iframe.src = generateSrc(aid, pages[index].cid);
  2142. }
  2143.  
  2144. return pages.map(function (item, index) {
  2145. let isCurPage = item.page == page
  2146. let $item = _('a', { 'data-index': index, className: isCurPage ? 'curPage' : '', event: { click: onPageBtnClick } }, [_('text', item.page + ': ' + item.part)])
  2147. if (isCurPage) $curPage = $item
  2148. return $item
  2149. });
  2150. }
  2151. // 当前av不属于番剧页面, 直接在当前页面插入一个播放器的iframe
  2152. let $pageBody = document.querySelector('.b-page-body');
  2153. if (!$pageBody) { // 若不存在, 则创建
  2154. $pageBody = _('div', { className: '.b-page-body' });
  2155. document.querySelector('.error-body').parentNode.appendChild($pageBody)
  2156. // 添加相关样式
  2157. document.head.appendChild(_('link', { type: 'text/css', rel: 'stylesheet', href: '//static.hdslb.com/css/core-v5/page-core.css' }))
  2158. }
  2159. let iframe = _('iframe', { className: 'player bilibiliHtml5Player', style: { position: 'relative' }, src: generateSrc(aid, cid) });
  2160.  
  2161. // 添加播放器
  2162. $pageBody.appendChild(_('div', { className: 'player-wrapper' }, [
  2163. _('div', { className: 'main-inner' }, [
  2164. _('div', { className: 'v-plist' }, [
  2165. _('div', { id: 'plist', className: 'plist-content open' }, generatePageList(data.list))
  2166. ])
  2167. ]),
  2168. _('div', { id: 'bofqi', className: 'scontent' }, [iframe])
  2169. ]));
  2170. // 添加评论区
  2171. $pageBody.appendChild(_('div', { className: 'main-inner' }, [
  2172. _('div', { className: 'common report-scroll-module report-wrap-module', id: 'common_report' }, [
  2173. _('div', { className: 'b-head' }, [
  2174. _('span', { className: 'b-head-t results' }),
  2175. _('span', { className: 'b-head-t' }, [_('text', '评论')]),
  2176. _('a', { className: 'del-log', href: `//www.bilibili.com/replydeletelog?aid=${aid}&title=${data.title}`, target: '_blank' }, [_('text', '查看删除日志')])
  2177. ]),
  2178. _('div', { className: 'comm', id: 'bbComment' }, [
  2179. _('div', { id: 'load_comment', className: 'comm_open_btn', onclick: "var fb = new bbFeedback('.comm', 'arc');fb.show(" + aid + ", 1);", style: { cursor: 'pointer' } })
  2180. ])
  2181. ])
  2182. ]));
  2183. // 添加包含bbFeedback的js
  2184. document.head.appendChild(_('script', { type: 'text/javascript', src: '//static.hdslb.com/js/core-v5/base.core.js' }))
  2185.  
  2186. document.title = data.title;
  2187. (document.querySelector('.error-body') || document.querySelector('.error-container')).remove(); // 移除错误信息面板
  2188. }
  2189.  
  2190. util_init(() => {
  2191. if (util_page.av()) {
  2192. tryRedirectToBangumiOrInsertPlayer()
  2193. }
  2194. })
  2195. return true // 随便返回一个值...
  2196. }())
  2197. const balh_feature_FillSeasonList = (function () {
  2198. function tryFillSeasonList() {
  2199. var error_container, season_id;
  2200. if (!(error_container = document.querySelector('div.error-container'))) {
  2201. return;
  2202. }
  2203. if (!(season_id = window.location.pathname.match(/^\/anime\/(\d+)\/?$/)[1])) {
  2204. return;
  2205. }
  2206.  
  2207. //尝试解决怪异模式渲染
  2208. /*
  2209. 会造成变量丢失,等待官方重写doctype
  2210. try{
  2211. window.stop();
  2212. var xhr = new XMLHttpRequest();
  2213. xhr.open('GET',location.href,false);
  2214. xhr.send();
  2215. document.head.appendChild(_('script',{},[_('text',
  2216. 'document.write(unescape("'+escape(xhr.response.replace(/<!DOCTYPE.+?>/,'<!DOCTYPE HTML>'))+'"));window.stop()'
  2217. )]));
  2218. }catch(e){util_error(e);}
  2219. */
  2220.  
  2221. var msg = _('a', { href: '//bangumi.bilibili.com/anime/' + season_id + '/play', style: { fontSize: '20px' } }, [_('text', `【${GM_info.script.name}】尝试获取视频列表中...`)]),
  2222. content = _('div');
  2223.  
  2224. error_container.insertBefore(content, error_container.firstChild);
  2225. content.appendChild(msg);
  2226. log('season>:', season_id);
  2227. balh_api_plus_season(season_id)
  2228. .then(function (data) {
  2229. log('season>then:', data);
  2230. if (data.code) {
  2231. return Promise.reject(data);
  2232. }
  2233.  
  2234. function generateEpisodeList(episodes) {
  2235. var childs = [];
  2236. episodes.reverse().forEach(function (i) {
  2237. childs.push(_('li', { className: 'v1-bangumi-list-part-child', 'data-episode-id': i.episode_id }, [_('a', { className: 'v1-complete-text', href: '//bangumi.bilibili.com/anime/' + season_id + '/play#' + i.episode_id, title: i.index + ' ' + i.index_title, target: '_blank', style: { height: '60px' } }, [
  2238. _('div', { className: 'img-wrp' }, [_('img', { src: i.cover, style: { opacity: 1 }, loaded: 'loaded', alt: i.index + ' ' + i.index_title })]),
  2239. _('div', { className: 'text-wrp' }, [
  2240. _('div', { className: 'text-wrp-num' }, [_('div', { className: 'text-wrp-num-content' }, [_('text', `第${i.index}话`)])]),
  2241. _('div', { className: 'text-wrp-title trunc' }, [_('text', i.index_title)])
  2242. ])
  2243. ])]));
  2244. });
  2245. return childs;
  2246. }
  2247.  
  2248. function generateSeasonList(seasons) {
  2249. function onSeasonClick(event) {
  2250. window.location.href = '//bangumi.bilibili.com/anime/' + event.target.attributes['data-season-id'].value;
  2251. }
  2252.  
  2253. return seasons.map(function (season) {
  2254. return _('li', { className: season.season_id == season_id ? 'cur' : '', 'data-season-id': season.season_id, event: { click: onSeasonClick } }, [_('text', season.title)]);
  2255. });
  2256. }
  2257.  
  2258. if (data.result) {
  2259. document.title = data.result.title;
  2260. document.head.appendChild(_('link', { href: 'https://s3.hdslb.com/bfs/static/anime/css/tag-index.css?v=110', rel: 'stylesheet' }));
  2261. document.head.appendChild(_('link', { href: 'https://s1.hdslb.com/bfs/static/anime/css/bangumi-index.css?v=110', rel: 'stylesheet' }));
  2262. document.body.insertBefore(_('div', { className: 'main-container-wrapper' }, [_('div', { className: 'main-container' }, [
  2263. _('div', { className: 'page-info-wrp' }, [_('div', { className: 'bangumi-info-wrapper' }, [
  2264. _('div', { className: 'bangumi-info-blurbg-wrapper' }, [_('div', { className: 'bangumi-info-blurbg blur', style: { backgroundImage: 'url(' + data.result.cover + ')' } })]),
  2265. _('div', { className: 'main-inner' }, [_('div', { className: 'info-content' }, [
  2266. _('div', { className: 'bangumi-preview' }, [_('img', { alt: data.result.title, src: data.result.cover })]),
  2267. _('div', { className: 'bangumi-info-r' }, [
  2268. _('div', { className: 'b-head' }, [_('h1', { className: 'info-title', 'data-seasonid': season_id, title: data.result.title }, [_('text', data.result.title)])]),
  2269. _('div', { className: 'info-count' }, [
  2270. _('span', { className: 'info-count-item info-count-item-play' }, [_('span', { className: 'info-label' }, [_('text', '总播放')]), _('em', {}, [_('text', data.result.play_count)])]),
  2271. _('span', { className: 'info-count-item info-count-item-fans' }, [_('span', { className: 'info-label' }, [_('text', '追番人数')]), _('em', {}, [_('text', data.result.favorites)])]),
  2272. _('span', { className: 'info-count-item info-count-item-review' }, [_('span', { className: 'info-label' }, [_('text', '弹幕总数')]), _('em', {}, [_('text', data.result.danmaku_count)])])
  2273. ]),
  2274. //_('div',{className:'info-row info-update'},[]),
  2275. //_('div',{className:'info-row info-cv'},[]),
  2276. _('div', { className: 'info-row info-desc-wrp' }, [
  2277. _('div', { className: 'info-row-label' }, [_('text', '简介:')]),
  2278. _('div', { className: 'info-desc' }, [_('text', data.result.evaluate)])
  2279. ]),
  2280. ])
  2281. ])])
  2282. ])]),
  2283. _('div', { className: 'main-inner' }, [_('div', { className: 'v1-bangumi-list-wrapper clearfix' }, [
  2284. _('div', { className: 'v1-bangumi-list-season-wrapper' }, [
  2285. _('div', { className: 'v1-bangumi-list-season-content slider-list-content' }, [
  2286. _('div', {}, [
  2287. _('ul', { className: 'v1-bangumi-list-season clearfix slider-list', 'data-current-season-id': season_id, style: { opacity: 1 } }, generateSeasonList(data.result.seasons))
  2288. ])
  2289. ])
  2290. ]),
  2291. _('div', { className: 'v1-bangumi-list-part-wrapper slider-part-wrapper' }, [_('div', { className: 'v1-bangumi-list-part clearfix', 'data-current-season-id': season_id, style: { display: 'block' } }, [
  2292. _('div', { className: 'complete-list', style: { display: 'block' } }, [_('div', { className: 'video-slider-list-wrapper' }, [_('div', { className: 'slider-part-wrapper' }, [_('ul', { className: 'slider-part clearfix hide', style: { display: 'block' } }, generateEpisodeList(data.result.episodes))])])])
  2293. ])])
  2294. ])])
  2295. ])]), msg.parentNode.parentNode);
  2296. msg.parentNode.parentNode.remove();
  2297. }
  2298. })
  2299. .catch(function (error) {
  2300. log('season>catch', error);
  2301. msg.innerText = 'error:' + JSON.stringify(error) + '\n点击跳转到播放界面 (不一定能够正常播放...)';
  2302. });
  2303. }
  2304.  
  2305. util_init(() => {
  2306. if (util_page.bangumi()) {
  2307. tryFillSeasonList()
  2308. }
  2309. })
  2310. return true
  2311. }())
  2312.  
  2313. const balh_ui_setting = (function () {
  2314. function addSettingsButton() {
  2315. var indexNav = document.getElementById('index_nav') || document.querySelector('.bangumi-nav-right') || document.querySelector('#fixnav_report'),
  2316. bottom = '110px',
  2317. size = '46px', settingBtnSvgContainer;
  2318. if (indexNav == null) {
  2319. // 信息页添加到按钮右侧
  2320. if (util_page.bangumi_md()) {
  2321. indexNav = document.querySelector('.media-info-btns');
  2322. indexNav.appendChild(_('style', {}, [_('text', `
  2323. #balh-settings-btn {
  2324. float: left;
  2325. margin: 3px 0 0 20px;
  2326. height: 44px;
  2327. width: 44px;
  2328. background: #FFF;
  2329. border-radius: 10px;
  2330. cursor: pointer;
  2331. }
  2332. #balh-settings-btn:hover {
  2333. background: #00a1d6;
  2334. border-color: #00a1d6;
  2335. }
  2336. #balh-settings-btn>:first-child {
  2337. text-align: center;
  2338. height: 100%;
  2339. }
  2340. #balh-settings-btn .icon-saturn {
  2341. width: 30px;
  2342. height: ${size};
  2343. fill: rgb(153,162,170);
  2344. }
  2345. #balh-settings-btn:hover .icon-saturn {
  2346. fill: white;
  2347. }
  2348. `)]))
  2349. settingBtnSvgContainer = indexNav.appendChild(_('div', { id: 'balh-settings-btn', title: GM_info.script.name + ' 设置', event: { click: showSettings } }, [_('div', {})])).firstChild;
  2350. }
  2351. } else {
  2352. // 视频页添加到回顶部下方
  2353. window.dispatchEvent(new Event('resize'));
  2354. indexNav.style.display = 'block';
  2355. indexNav.appendChild(_('style', {}, [_('text', `
  2356. #balh-settings-btn {
  2357. bottom: 110px;
  2358. border: 1px solid #e5e9ef;
  2359. border-radius: 4px;
  2360. background: #f6f9fa;
  2361. margin-top: 4px;
  2362. width: ${size};
  2363. height: ${size};
  2364. cursor: pointer;
  2365. }
  2366. #balh-settings-btn:hover {
  2367. background: #00a1d6;
  2368. border-color: #00a1d6;
  2369. }
  2370. #balh-settings-btn .btn-gotop {
  2371. text-align: center;
  2372. }
  2373. #balh-settings-btn .icon-saturn {
  2374. width: 30px;
  2375. height: ${size};
  2376. fill: rgb(153,162,170);
  2377. }
  2378. #balh-settings-btn:hover .icon-saturn {
  2379. fill: white;
  2380. }
  2381. `)]))
  2382. settingBtnSvgContainer = indexNav.appendChild(_('div', { id: 'balh-settings-btn', title: GM_info.script.name + ' 设置', event: { click: showSettings } }, [_('div', { className: 'btn-gotop' })])).firstChild;
  2383. }
  2384. settingBtnSvgContainer && (settingBtnSvgContainer.innerHTML = `<!-- https://www.flaticon.com/free-icon/saturn_53515 --><svg class="icon-saturn" viewBox="0 0 612.017 612.017"><path d="M596.275,15.708C561.978-18.59,478.268,5.149,380.364,68.696c-23.51-7.384-48.473-11.382-74.375-11.382c-137.118,0-248.679,111.562-248.679,248.679c0,25.902,3.998,50.865,11.382,74.375C5.145,478.253-18.575,561.981,15.724,596.279c34.318,34.318,118.084,10.655,216.045-52.949c23.453,7.365,48.378,11.344,74.241,11.344c137.137,0,248.679-111.562,248.679-248.68c0-25.862-3.979-50.769-11.324-74.24C606.931,133.793,630.574,50.026,596.275,15.708zM66.435,545.53c-18.345-18.345-7.919-61.845,23.338-117.147c22.266,39.177,54.824,71.716,94.02,93.943C128.337,553.717,84.837,563.933,66.435,545.53z M114.698,305.994c0-105.478,85.813-191.292,191.292-191.292c82.524,0,152.766,52.605,179.566,125.965c-29.918,41.816-68.214,87.057-113.015,131.839c-44.801,44.819-90.061,83.116-131.877,113.034C167.303,458.76,114.698,388.479,114.698,305.994z M305.99,497.286c-3.156,0-6.236-0.325-9.354-0.459c35.064-27.432,70.894-58.822,106.11-94.059c35.235-35.235,66.646-71.046,94.058-106.129c0.153,3.118,0.479,6.198,0.479,9.354C497.282,411.473,411.469,497.286,305.99,497.286z M428.379,89.777c55.303-31.238,98.803-41.683,117.147-23.338c18.402,18.383,8.187,61.902-23.204,117.377C500.095,144.62,467.574,112.043,428.379,89.777z"/></svg>`);
  2385. }
  2386.  
  2387. function _showSettings() {
  2388. document.body.appendChild(settingsDOM);
  2389. var form = settingsDOM.querySelector('form');
  2390. // elements包含index的属性, 和以name命名的属性, 其中以name命名的属性是不可枚举的, 只能通过这种方式获取出来
  2391. Object.getOwnPropertyNames(form.elements).forEach(function (name) {
  2392. if (name.startsWith('balh_')) {
  2393. var key = name.replace('balh_', '')
  2394. var ele = form.elements[name]
  2395. if (ele.type === 'checkbox') {
  2396. ele.checked = balh_config[key];
  2397. } else {
  2398. ele.value = balh_config[key];
  2399. }
  2400. }
  2401. })
  2402. document.body.style.overflow = 'hidden';
  2403. }
  2404.  
  2405. // 往顶层窗口发显示设置的请求
  2406. function showSettings() {
  2407. window.top.postMessage('balh-show-setting', '*')
  2408. }
  2409.  
  2410. // 只有顶层窗口才接收请求
  2411. if (window === window.top) {
  2412. window.addEventListener('message', (event) => {
  2413. if (event.data === 'balh-show-setting') {
  2414. _showSettings();
  2415. $('#upos-server')[0].value = balh_config.upos_server || '';
  2416. }
  2417. })
  2418. }
  2419.  
  2420. function onSignClick(event) {
  2421. settingsDOM.click();
  2422. switch (event.target.attributes['data-sign'].value) {
  2423. default:
  2424. case 'in':
  2425. balh_feature_sign.showLogin();
  2426. break;
  2427. case 'out':
  2428. balh_feature_sign.showLogout();
  2429. break;
  2430. }
  2431. }
  2432.  
  2433. function onSettingsFormChange(e) {
  2434. var name = e.target.name;
  2435. var value = e.target.type === 'checkbox' ? (e.target.checked ? r.const.TRUE : r.const.FALSE) : e.target.value.trim()
  2436. balh_config[name.replace('balh_', '')] = value
  2437. log(name, ' => ', value);
  2438. }
  2439.  
  2440. // 第一次点击时:
  2441. // 1. '复制日志&问题反馈' => '复制日志'
  2442. // 2. 显示'问题反馈'
  2443. // 3. 复制成功后请求跳转到GitHub
  2444. // 之后的点击, 只是正常的复制功能~~
  2445. function onCopyClick(event) {
  2446. let issueLink = document.getElementById('balh-issue-link')
  2447. let continueToIssue = issueLink.style.display === 'none'
  2448. if (continueToIssue) {
  2449. issueLink.style.display = 'inline'
  2450. let copyBtn = document.getElementById('balh-copy-log')
  2451. copyBtn.innerText = '复制日志'
  2452. }
  2453.  
  2454. let textarea = document.getElementById('balh-textarea-copy')
  2455. textarea.style.display = 'inline-block'
  2456. if (util_ui_copy(util_log_hub.getAllMsg(), textarea)) {
  2457. textarea.style.display = 'none'
  2458. util_ui_msg.show($(this),
  2459. continueToIssue ? '复制日志成功; 点击确定, 继续提交问题(需要GitHub帐号)\n请把日志粘贴到问题描述中' : '复制成功',
  2460. continueToIssue ? 0 : 3e3,
  2461. continueToIssue ? 'button' : undefined,
  2462. continueToIssue ? () => window.open(r.url.issue) : undefined)
  2463. } else {
  2464. util_ui_msg.show($(this), '复制失败, 请从下面的文本框手动复制', 5e3)
  2465. }
  2466. }
  2467.  
  2468. let printSystemInfoOk = false
  2469.  
  2470. // 鼠标移入设置底部的时候, 打印一些系统信息, 方便问题反馈
  2471. function onMouseEnterSettingBottom(event) {
  2472. if (!printSystemInfoOk) {
  2473. printSystemInfoOk = true
  2474. util_debug('userAgent', navigator.userAgent)
  2475. }
  2476. }
  2477.  
  2478. let customServerCheckText
  2479. var settingsDOM = _('div', { id: 'balh-settings', style: { position: 'fixed', top: 0, bottom: 0, left: 0, right: 0, background: 'rgba(0,0,0,.7)', animationName: 'balh-settings-bg', animationDuration: '.5s', zIndex: 10000, cursor: 'pointer' }, event: { click: function (e) { if (e.target === this) util_ui_msg.close(), document.body.style.overflow = '', this.remove(); } } }, [
  2480. _('style', {}, [_('text', r.css.settings)]),
  2481. _('div', { style: { position: 'absolute', background: '#FFF', borderRadius: '10px', padding: '20px', top: '50%', left: '50%', width: '600px', transform: 'translate(-50%,-50%)', cursor: 'default' } }, [
  2482. _('h1', {}, [_('text', `${GM_info.script.name} v${GM_info.script.version} 参数设置`)]),
  2483. _('br'),
  2484. _('form', { id: 'balh-settings-form', event: { change: onSettingsFormChange } }, [
  2485. _('text', '代理服务器:'), _('a', { href: 'javascript:', event: { click: balh_feature_runPing } }, [_('text', '测速')]), _('br'),
  2486. _('div', { style: { display: 'flex' } }, [
  2487. _('label', { style: { flex: 1 } }, [_('input', { type: 'radio', name: 'balh_server_inner', value: r.const.server.S0 }), _('text', '土豆服')]),
  2488. _('label', { style: { flex: 1 } }, [_('input', { type: 'radio', name: 'balh_server_inner', value: r.const.server.S1 }), _('text', 'BiliPlus')]),
  2489. _('label', { style: { flex: 2 } }, [
  2490. _('input', { type: 'radio', name: 'balh_server_inner', value: r.const.server.CUSTOM }), _('text', `自定义: `),
  2491. _('input', {
  2492. type: 'text', name: 'balh_server_custom', placeholder: '形如:https://hd.pilipili.com', event: {
  2493. input: (event) => {
  2494. customServerCheckText.innerText = /^https?:\/\/[\w.]+$/.test(event.target.value.trim()) ? '✔️' : '❌'
  2495. onSettingsFormChange(event)
  2496. }
  2497. }
  2498. }),
  2499. customServerCheckText = _('span'),
  2500. ]),
  2501. ]), _('br'),
  2502. _('div', { id: 'balh_server_ping', style: { whiteSpace: 'pre-wrap', overflow: 'auto' } }, []),
  2503. _('text', 'upos服务器:'), _('br'),
  2504. _('div', { title: '变更后 切换清晰度 或 刷新 生效' }, [
  2505. _('input', { style: { visibility: 'hidden' }, type: 'checkbox' }),
  2506. _('text', '替换upos视频服务器:'),
  2507. _('select', {
  2508. id: 'upos-server',
  2509. event: {
  2510. change: function () {
  2511. let server = this.value;
  2512. let message = $('#upos-server-message');
  2513. let clearMsg = function () { message.text('') }
  2514. message.text('保存中...')
  2515. $.ajax(balh_config.server + '/api/setUposServer?server=' + server, {
  2516. xhrFields: { withCredentials: true },
  2517. dataType: 'json',
  2518. success: function (json) {
  2519. if (json.code == 0) {
  2520. message.text('已保存');
  2521. setTimeout(clearMsg, 3e3);
  2522. balh_config.upos_server = server;
  2523. }
  2524. },
  2525. error: function () {
  2526. message.text('保存出错');
  2527. setTimeout(clearMsg, 3e3);
  2528. }
  2529. })
  2530. }
  2531. }
  2532. }, [
  2533. _('option', { value: "" }, [_('text', '不替换')]),
  2534. _('option', { value: "ks3" }, [_('text', 'ks3(金山)')]),
  2535. _('option', { value: "oss" }, [_('text', 'oss(阿里)')]),
  2536. _('option', { value: "kodo" }, [_('text', 'kodo(七牛)')]),
  2537. _('option', { value: "cos" }, [_('text', 'cos(腾讯)')]),
  2538. _('option', { value: "bos" }, [_('text', 'bos(百度)')])
  2539. ]),
  2540. _('span', { 'id': 'upos-server-message' })
  2541. ]), _('br'),
  2542. _('text', '脚本工作模式:'), _('br'),
  2543. _('div', { style: { display: 'flex' } }, [
  2544. _('label', { style: { flex: 1 } }, [_('input', { type: 'radio', name: 'balh_mode', value: r.const.mode.DEFAULT }), _('text', '默认:自动判断')]),
  2545. _('label', { style: { flex: 1 } }, [_('input', { type: 'radio', name: 'balh_mode', value: r.const.mode.REPLACE }), _('text', '替换:在需要时处理番剧')]),
  2546. _('label', { style: { flex: 1 } }, [_('input', { type: 'radio', name: 'balh_mode', value: r.const.mode.REDIRECT }), _('text', '重定向:完全代理所有番剧')])
  2547. ]), _('br'),
  2548. _('text', '其他:'), _('br'),
  2549. _('div', { style: { display: 'flex' } }, [
  2550. _('label', { style: { flex: 1 } }, [_('input', { type: 'checkbox', name: 'balh_blocked_vip' }), _('text', '被永封的大会员'), _('a', { href: 'https://github.com/ipcjs/bilibili-helper/blob/user.js/bilibili_bangumi_area_limit_hack.md#大会员账号被b站永封了', target: '_blank' }, [_('text', '(?)')])]),
  2551. _('label', { style: { flex: 1 } }, [_('input', { type: 'checkbox', name: 'balh_enable_in_av' }), _('text', '在AV页面启用'), _('a', { href: 'https://github.com/ipcjs/bilibili-helper/issues/172', target: '_blank' }, [_('text', '(?)')])]),
  2552. _('div', { style: { flex: 1, display: 'flex' } }, [
  2553. _('label', { style: { flex: 1 } }, [_('input', { type: 'checkbox', name: 'balh_remove_pre_ad' }), _('text', '去前置广告')]),
  2554. // _('label', { style: { flex: 1 } }, [_('input', { type: 'checkbox', name: 'balh_flv_prefer_ws' }), _('text', '优先使用ws')]),
  2555. ])
  2556. ]), _('br'),
  2557. _('a', { href: 'javascript:', 'data-sign': 'in', event: { click: onSignClick } }, [_('text', '帐号授权')]),
  2558. _('text', ' '),
  2559. _('a', { href: 'javascript:', 'data-sign': 'out', event: { click: onSignClick } }, [_('text', '取消授权')]),
  2560. _('text', '  '),
  2561. _('a', { href: 'javascript:', event: { click: function () { util_ui_msg.show($(this), '如果你的帐号进行了付费,不论是大会员还是承包,\n进行授权之后将可以在解除限制时正常享有这些权益\n\n你可以随时在这里授权或取消授权\n\n不进行授权不会影响脚本的正常使用,但可能会缺失1080P', 1e4); } } }, [_('text', '(这是什么?)')]),
  2562. _('br'), _('br'),
  2563. _('div', { style: { whiteSpace: 'pre-wrap' }, event: { mouseenter: onMouseEnterSettingBottom } }, [
  2564. _('a', { href: 'https://greasyfork.org/zh-CN/scripts/25718-%E8%A7%A3%E9%99%A4b%E7%AB%99%E5%8C%BA%E5%9F%9F%E9%99%90%E5%88%B6', target: '_blank' }, [_('text', '脚本主页')]),
  2565. _('text', ' '),
  2566. _('a', { href: 'https://github.com/ipcjs/bilibili-helper/blob/user.js/bilibili_bangumi_area_limit_hack.md', target: '_blank' }, [_('text', '帮助说明')]),
  2567. _('text', ' '),
  2568. _('a', { id: 'balh-copy-log', href: 'javascript:;', event: { click: onCopyClick } }, [_('text', '复制日志&问题反馈')]),
  2569. _('text', ' '),
  2570. _('a', { id: 'balh-issue-link', href: r.url.issue, target: '_blank', style: { display: 'none' } }, [_('text', '问题反馈')]),
  2571. _('text', '作者: ipcjs esterTion FlandreDaisuki 接口:BiliPlus')
  2572. ]),
  2573. _('textarea', { id: 'balh-textarea-copy', style: { display: 'none' } })
  2574. ])
  2575. ])
  2576. ]);
  2577.  
  2578. util_init(() => {
  2579. if (!(util_page.player() || (util_page.av() && !balh_config.enable_in_av))) {
  2580. if (!util_page.av()) { // av页面添加这个按钮不知道为啥页面会混乱...屏蔽掉(;¬_¬)
  2581. addSettingsButton()
  2582. }
  2583. }
  2584. }, util_init.PRIORITY.DEFAULT, util_init.RUN_AT.DOM_LOADED_AFTER)
  2585. return {
  2586. dom: settingsDOM,
  2587. show: showSettings,
  2588. }
  2589. }())
  2590.  
  2591. const balh_jump_to_baipiao = (function () {
  2592. function main() {
  2593. for (let bp of r.baipiao) {
  2594. const cookie_key = `balh_baipao_${bp.key}`
  2595. if (bp.match() && !util_cookie[cookie_key]) {
  2596. util_ui_pop({
  2597. content: [
  2598. _('text', '发现白嫖地址: '), _('a', { href: bp.link }, bp.link),
  2599. _('div', {}, bp.message),
  2600. ],
  2601. confirmBtn: '一键跳转',
  2602. onConfirm: () => { location.href = bp.link },
  2603. onClose: () => { util_cookie.set(cookie_key, r.const.TRUE, '') }
  2604. })
  2605. break
  2606. }
  2607. }
  2608. }
  2609. util_init(() => {
  2610. main()
  2611. }, util_init.PRIORITY.DEFAULT, util_init.RUN_AT.DOM_LOADED_AFTER)
  2612. }())
  2613.  
  2614. function main() {
  2615. util_log(
  2616. 'mode:', balh_config.mode,
  2617. 'blocked_vip:', balh_config.blocked_vip,
  2618. 'server:', balh_config.server,
  2619. 'upos_server:', balh_config.upos_server,
  2620. 'flv_prefer_ws:', balh_config.flv_prefer_ws,
  2621. 'remove_pre_ad:', balh_config.remove_pre_ad,
  2622. 'readyState:', document.readyState,
  2623. 'isLogin:', balh_feature_sign.isLogin(),
  2624. 'isLoginBiliBili:', balh_feature_sign.isLoginBiliBili()
  2625. )
  2626. // 暴露接口
  2627. window.bangumi_area_limit_hack = {
  2628. setCookie: util_cookie.set,
  2629. getCookie: util_cookie.get,
  2630. login: balh_feature_sign.showLogin,
  2631. logout: balh_feature_sign.showLogout,
  2632. getLog: util_log_hub.getAllMsg,
  2633. showSettings: balh_ui_setting.show,
  2634. _clear_local_value: function () {
  2635. delete localStorage.oauthTime
  2636. delete localStorage.balh_h5_not_first
  2637. delete localStorage.balh_old_isLoginBiliBili
  2638. delete localStorage.balh_must_remind_login_v1
  2639. delete localStorage.balh_must_updateLoginFlag
  2640. }
  2641. }
  2642. }
  2643.  
  2644. main();
  2645. }
  2646.  
  2647. scriptSource(GM_info.scriptHandler);