当前位置:   article > 正文

Tampermonkeych插件看B站无地区限制,加速arxiv下载论文速度_balh授权

balh授权

相关问题:

Tampermonkeych插件看B站无地区限制,加速arxiv下载论文速度

pycharm备份还原 在Pycharm中使用GitHub

python&anaconda环境备份(package备份)

谷歌浏览器书签及插件备份

git错误上传大文件&版本回退

windows使用bash指令


 

arxiv 中国的官方镜像 http://cn.arxiv.org,通过使用 chrome 插件Tampermonkeych将 arxiv 的重定向到镜像网站链接,点击一篇文章的arxiv链接后就可以自动到cn.arxiv.org,速度很快。

方法

  1. 安装chrome 浏览器。
  2. 安装tempermonkey插件,crx4chrome上tampermonkey插件的下载链接
  3. 添加 arxiv 重定向脚本。
  4. 脚本代码并保存
    1. // ==UserScript==
    2. // @name Redirect arxiv.org to CN.arxiv.org/pdf
    3. // @namespace uso2usom
    4. // @description On any web page it will check if the clicked links goes to arxiv.org. If so, the link will be rewritten to point to cn.arxiv.org
    5. // @include http://*.*
    6. // @include https://*.*
    7. // @version 1.2
    8. // @grant none
    9. // ==/UserScript==
    10. // This is a slightly brute force solution, but there is no other way to do it using only a userscript.
    11. // Release Notes
    12. // version 1.2
    13. // Focus on pdf link only!
    14. // Add '.pdf' link automatically. Convenient for saving as pdf.
    15. // version 1.1
    16. // Redirect arxiv.org to CN.arxiv.org
    17. document.body.addEventListener('mousedown', function(e){
    18. var targ = e.target || e.srcElement;
    19. if ( targ && targ.href && targ.href.match(/https?:\/\/arxiv.org\/pdf/) ) {
    20. targ.href = targ.href.replace(/https?:\/\/arxiv\.org/, 'http://cn.arxiv.org');
    21. }
    22. if ( targ && targ.href && targ.href.match(/http?:\/\/arxiv.org\/pdf/) ) {
    23. targ.href = targ.href.replace(/http?:\/\/arxiv\.org/, 'http://cn.arxiv.org');
    24. }
    25. if ( targ && targ.href && targ.href.match(/https?:\/\/arxiv.org\/abs/) ) {
    26. targ.href = targ.href.replace(/https?:\/\/arxiv\.org\/abs/, 'http://cn.arxiv.org/pdf');
    27. }
    28. if ( targ && targ.href && targ.href.match(/http?:\/\/arxiv.org\/abs/) ) {
    29. targ.href = targ.href.replace(/http?:\/\/arxiv\.org\/abs/, 'http://cn.arxiv.org/pdf');
    30. }
    31. if (targ && targ.href && targ.href.match(/http?:\/\/cn.arxiv.org\/pdf/) && !targ.href.match(/\.pdf/) )
    32. {
    33. targ.href = targ.href + '.pdf';
    34. }
    35. });

     

 

B站加速 

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/290107
推荐阅读
相关标签
  

闽ICP备14008679号