Custom CDN URL

自定义cdn,国内/国外可以换成合适的cdn

  1. // ==UserScript==
  2. // @name Custom CDN URL
  3. // @namespace https://greasyfork.org/en/scripts/473962-custom-cdn-url
  4. // @version 1.5.2
  5. // @description 自定义cdn,国内/国外可以换成合适的cdn
  6. // @author freenzoo
  7. // @match https://*.bilibili.com/*
  8. // @run-at document-body
  9. // @grant unsafeWindow
  10. // @grant GM_addStyle
  11. // @license MIT
  12. // ==/UserScript==
  13. // 判断是否在指定的网址范围内
  14. function isSupportedURL(url) {
  15. return url.startsWith('https://www.bilibili.com/video/') ||
  16. url.startsWith('https://www.bilibili.com/bangumi/play/') ||
  17. url.startsWith('https://www.bilibili.com/blackboard/');
  18. }
  19.  
  20. // 获取随机的 CDN 域名
  21. const cdnDomains = [
  22. "upos-sz-mirrorhw.bilivideo.com",
  23. "upos-sz-mirrorcos.bilivideo.com",
  24. "upos-sz-mirrorali.bilivideo.com",
  25. "upos-sz-mirroralib.bilivideo.com"
  26. ];
  27.  
  28. const getRandomCdnDomain = () => {
  29. return cdnDomains[Math.floor(Math.random() * cdnDomains.length)];
  30. };
  31.  
  32. // 替换 P2P URL
  33. const replaceP2PUrl = url => {
  34. try {
  35. const urlObj = new URL(url);
  36. const hostName = urlObj.hostname;
  37. const supportedDomainsRegex = /\.bilivideo\.com$|\.akamaized\.net$|\.szbdyd\.com$/;
  38. if (supportedDomainsRegex.test(hostName)) {
  39. urlObj.host = getRandomCdnDomain();
  40. urlObj.port = 443;
  41. // console.warn(`更换视频源: ${hostName} -> ${urlObj.host}`);
  42. return urlObj.toString();
  43. }
  44. return url;
  45. } catch(e) {
  46. return url;
  47. }
  48. };
  49.  
  50.  
  51. // 递归替换对象中的 URL
  52. const replaceP2PUrlDeep = obj => {
  53. for (const key in obj) {
  54. if (key === 'baseUrl' || key === 'base_url') {
  55. obj[key] = replaceP2PUrl(obj[key]);
  56. } else if (typeof obj[key] === 'array' || typeof obj[key] === 'object') {
  57. replaceP2PUrlDeep(obj[key]);
  58. }
  59. }
  60. }
  61.  
  62. // 在合适的 URL 范围内进行操作
  63. if (isSupportedURL(location.href)) {
  64. replaceP2PUrlDeep(unsafeWindow.__playinfo__);
  65. (function (open) {
  66. unsafeWindow.XMLHttpRequest.prototype.open = function () {
  67. try {
  68. arguments[1] = replaceP2PUrl(arguments[1]);
  69. } finally {
  70. return open.apply(this, arguments);
  71. }
  72. }
  73. })(unsafeWindow.XMLHttpRequest.prototype.open);
  74. }