Custom CDN URL

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

当前为 2023-08-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Custom CDN URL
  3. // @namespace https://greasyfork.org/en/scripts/473962-custom-cdn-url
  4. // @version 1.5.1
  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. if ( location.href.startsWith('https://www.bilibili.com/video/') || location.href.startsWith('https://www.bilibili.com/bangumi/play/') ) {
  14. const cdnDomains = [
  15. "upos-sz-mirrorhw.bilivideo.com",
  16. "upos-sz-mirrorcos.bilivideo.com",
  17. "upos-sz-mirrorali.bilivideo.com",
  18. "upos-sz-mirroralib.bilivideo.com"
  19. ];
  20.  
  21. function getRandomCdnDomain() {
  22. const randomIndex = Math.floor(Math.random() * cdnDomains.length);
  23. return cdnDomains[randomIndex];
  24. }
  25. function replaceP2PUrl(url) {
  26. try {
  27. const urlObj = new URL(url);
  28. const hostName = urlObj.hostname;
  29. if (urlObj.hostname.endsWith(".bilivideo.com") || urlObj.hostname.endsWith(".akamaized.net") || urlObj.hostname.endsWith(".szbdyd.com")) {
  30. urlObj.host = getRandomCdnDomain();
  31. urlObj.port = 443;
  32. // console.warn(`更换视频源: ${hostName} -> ${urlObj.host}`);
  33. return urlObj.toString();
  34. }
  35. return url;
  36. } catch(e) {
  37. return url;
  38. }
  39. }
  40.  
  41. function replaceP2PUrlDeep(obj) {
  42. for (const key in obj) {
  43. if ( key === 'baseUrl' ) {
  44. obj[key] = replaceP2PUrl(obj[key]);
  45. } else if (typeof obj[key] === 'array' || typeof obj[key] === 'object') {
  46. replaceP2PUrlDeep(obj[key]);
  47. }
  48. }
  49. }
  50. replaceP2PUrlDeep(unsafeWindow.__playinfo__);
  51.  
  52. (function (open) {
  53. unsafeWindow.XMLHttpRequest.prototype.open = function () {
  54. try {
  55. arguments[1] = replaceP2PUrl(arguments[1]);
  56. } finally {
  57. return open.apply(this, arguments);
  58. }
  59. }
  60. })(unsafeWindow.XMLHttpRequest.prototype.open);
  61. }