解除B站区域限制

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

Ekde 2018/11/24. Vidu La ĝisdata versio.

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