Make BiliBili Great Again

useful tweaks for bilibili.com

< Feedback on Make BiliBili Great Again

Review: OK - script works, but has bugs

§
Posted: 2024.06.19.

用ChatGPT生成了一个,替换p2p cdn部分。


// 去 P2P CDN
Object.defineProperty(unsafeWindow, 'PCDNLoader', { value: class { }, enumerable: false, writable: false });
Object.defineProperty(unsafeWindow, 'BPP2PSDK', { value: class { on() { } }, enumerable: false, writable: false });
Object.defineProperty(unsafeWindow, 'SeederSDK', { value: class { }, enumerable: false, writable: false });

if (location.href.startsWith('https://www.bilibili.com/video/') || location.href.startsWith('https://www.bilibili.com/bangumi/play/')) {
let cdnDomain;

function replaceP2PUrl(url) {
cdnDomain ||= document.head.innerHTML.match(/up[\w-]+\.bilivideo\.com/)?.[0];

try {
const urlObj = new URL(url);
const hostName = urlObj.hostname;
const port = urlObj.port;

// 如果是 P2P CDN 域名,替换为传统 CDN 域名并使用443端口
if (urlObj.hostname.endsWith(".mcdn.bilivideo.cn") || urlObj.hostname.endsWith(".szbdyd.com")) {
if (port && !['80', '443'].includes(port)) {
urlObj.port = '443'; // 强制使用443端口
console.warn(`更换视频源端口: ${port} -> ${urlObj.port}`);
}
urlObj.hostname = cdnDomain || 'upos-hz-mirrorakam.akamaized.net'; // 替换为传统 CDN 域名
console.warn(`更换视频源: ${hostName} -> ${urlObj.hostname}`);
return urlObj.toString();
}

return url;
} catch (e) {
console.error('URL 替换错误:', e);
return url;
}
}

function replaceP2PUrlDeep(obj) {
for (const key in obj) {
if (typeof obj[key] === 'string') {
obj[key] = replaceP2PUrl(obj[key]);
} else if (typeof obj[key] === 'object') {
replaceP2PUrlDeep(obj[key]);
}
}
}

// 替换初始播放信息中的 P2P URL
replaceP2PUrlDeep(unsafeWindow.__playinfo__);

// 拦截 XMLHttpRequest,替换 P2P URL
(function (open) {
unsafeWindow.XMLHttpRequest.prototype.open = function () {
try {
arguments[1] = replaceP2PUrl(arguments[1]);
} finally {
return open.apply(this, arguments);
}
}
})(unsafeWindow.XMLHttpRequest.prototype.open);

// 拦截 fetch 请求,替换 P2P URL
const originalFetch = unsafeWindow.fetch;
unsafeWindow.fetch = function() {
arguments[0] = replaceP2PUrl(arguments[0]);
return originalFetch.apply(this, arguments);
};
}

Post reply

Sign in to post a reply.