// ==UserScript== // @name 百度网盘高清播放(个人版) // @namespace http://tampermonkey.net/ // @version 1.0.1 // @description 仅个人使用:替换播放器,获取更高清晰度 m3u8 流(v1.0.1 修复原播放器残留导致的双声音、暂停后仍有声音问题) // @author You // @match https://pan.baidu.com/play/video* // @match https://pan.baidu.com/pfile/video* // @require https://unpkg.com/artplayer@5.4.0/dist/artplayer.js // @require https://unpkg.com/hls.js@1.7.3/dist/hls.min.js // @grant unsafeWindow // @grant GM_getValue // @grant GM_setValue // @run-at document-idle // ==/UserScript== /* global Artplayer, Hls */ (function () { 'use strict'; /* ========================================================== * 常量与全局状态 * 说明:GM_getValue / GM_setValue 按规格书保留授权, * 但本版本不做设置持久化(规格第七节),因此暂不使用。 * ========================================================== */ const TAG = '[BDHQ]'; const MAX_WAIT = 30000; // 各类等待的最长时间(毫秒) const INTERVAL = 500; // 轮询间隔(毫秒) const state = { videoInfo: null, // 当前视频信息(来自 Pinia) vipLevel: 0, // 如实读取的会员等级:0 普通 / 1 VIP / 2 SVIP qualities: [], // 当前可用清晰度列表 currentQuality: null, // 当前播放的清晰度项 art: null, // ArtPlayer 实例 hls: null, // 当前 hls.js 实例 observer: null, // MutationObserver(路由 / 原播放器重建监控) lastHref: location.href, initializing: false, // 防止初始化流程重入 networkRetry: 0 // hls 致命网络错误计数(用于升级恢复策略) }; // 防止同一页面重复注入执行 if (unsafeWindow.__BDHQ_BOOTED__) { console.warn(TAG, '检测到脚本已在运行,跳过重复初始化'); return; } unsafeWindow.__BDHQ_BOOTED__ = true; /* ========================================================== * 3.1 页面就绪检测模块 * ========================================================== */ function waitFor(conditionFn, callback, maxWait = MAX_WAIT, interval = INTERVAL, onTimeout) { const start = Date.now(); const timer = setInterval(() => { let ok = false; try { ok = !!conditionFn(); } catch (e) { ok = false; } if (ok) { clearInterval(timer); callback(); } else if (Date.now() - start > maxWait) { clearInterval(timer); console.error(TAG, '等待超时'); if (typeof onTimeout === 'function') onTimeout(); } }, interval); } // 读取页面侧 Vue 应用实例。 // 优先通过 unsafeWindow.document 访问,确保能读到页面 JS 挂在 DOM 上的 __vue_app__。 function getVueApp() { try { const doc = unsafeWindow.document || document; const el = doc.querySelector('#app'); if (el && el.__vue_app__) return el.__vue_app__; } catch (e) { /* 继续尝试沙箱 document */ } const el = document.querySelector('#app'); return el && el.__vue_app__ ? el.__vue_app__ : null; } /* ========================================================== * 3.2 数据提取模块 * ========================================================== */ // 3.2.1 从 Pinia 拿视频信息 function getVideoInfo() { try { const vueApp = getVueApp(); if (!vueApp) { console.error(TAG, '未找到 Vue 应用实例(#app.__vue_app__ 不可访问)'); return null; } const pinia = vueApp.config.globalProperties.$pinia; if (!pinia) { console.error(TAG, '未找到 Pinia 实例($pinia 不存在)'); return null; } const videoinfo = pinia.state.value.videoinfo?.videoinfo; if (!videoinfo) { console.error(TAG, 'Pinia 中没有 videoinfo 数据(页面可能尚未渲染完成)'); return null; } return { fs_id: videoinfo.fs_id, path: videoinfo.path, resolution: videoinfo.resolution, // 形如 "width:1920,height:1080" thumbs: videoinfo.thumbs, // 封面图集合 server_filename: videoinfo.server_filename }; } catch (e) { console.error(TAG, '提取视频信息失败:', e); return null; } } // 3.2.2 获取 jsToken(每次调用都取最新值,应对短时效,规格 5.1) function getJsToken() { try { if (unsafeWindow.jsToken) return unsafeWindow.jsToken; if (unsafeWindow.yunData && unsafeWindow.yunData.jsToken) return unsafeWindow.yunData.jsToken; } catch (e) { console.error(TAG, '读取 jsToken 异常:', e); } return ''; } // 3.2.3 获取会员状态(如实返回,绝不伪造) function getVipLevel() { try { if (unsafeWindow.yunData && !unsafeWindow.yunData.neglect) { if (unsafeWindow.yunData.ISSVIP === 1) return 2; if (unsafeWindow.yunData.ISVIP === 1) return 1; return 0; } if (unsafeWindow.locals) { if (typeof unsafeWindow.locals.get === 'function') { if (unsafeWindow.locals.get('is_svip') === 1) return 2; if (unsafeWindow.locals.get('is_vip') === 1) return 1; } else { if (unsafeWindow.locals.is_svip === 1) return 2; if (unsafeWindow.locals.is_vip === 1) return 1; } } } catch (e) { /* 读取失败按普通用户处理 */ } return 0; } /* ========================================================== * 3.3 streaming URL 构造模块 * ========================================================== */ // 统一构造 /api/streaming 请求 URL(同域请求,直接 fetch,规格 5.6)。 // 修正:URLSearchParams.toString() 会自动对参数值做一次 URL 编码, // 因此这里传入原始 path。规格书示例中手动 encodeURIComponent 后再交给 // URLSearchParams 会造成双重编码,服务端将解析出错误路径。 function buildStreamingUrl(type, path, vipLevel, adToken) { const params = new URLSearchParams({ type: type, path: path, vip: vipLevel, jsToken: getJsToken() }); let url = '/api/streaming?' + params.toString(); if (adToken) url += '&adToken=' + encodeURIComponent(adToken); return url; } // 3.3.1 清晰度列表生成 // 修正:规格书签名 buildQualityList(resolution, adToken, vipLevel) 内部 // 引用了未传入的 path,这里补充 path 参数,保证代码可直接运行。 function buildQualityList(resolution, path, adToken, vipLevel) { const qualities = []; let width = 0, height = 0; if (resolution) { const match = String(resolution).match(/width:(\d+),height:(\d+)/); if (match) { width = parseInt(match[1], 10); height = parseInt(match[2], 10); } } const pixelCount = width * height; if (!pixelCount) console.warn(TAG, '未能解析源视频分辨率,将只提供 480P/360P'); // 非 SVIP 请求 1080 时服务端可能拒绝或自动降级,故不展示 const templates = [ { key: 1080, label: '超清 1080P', minPixels: 921600 }, { key: 720, label: '高清 720P', minPixels: 409920 }, { key: 480, label: '流畅 480P', minPixels: 0 }, { key: 360, label: '省流 360P', minPixels: 0 } ]; for (const t of templates) { if (pixelCount >= t.minPixels || t.minPixels === 0) { if (t.key === 1080 && vipLevel < 2) continue; qualities.push({ html: t.label, url: buildStreamingUrl('M3U8_AUTO_' + t.key, path, vipLevel, adToken), type: 'hls', key: t.key }); } } return qualities; } // 带 jsToken 刷新的 fetch:网络异常或 401/403 时自动重试一次(规格 5.1) async function fetchWithTokenRetry(makeUrl) { let resp; try { resp = await fetch(makeUrl(), { credentials: 'same-origin' }); } catch (e) { console.warn(TAG, '请求失败,重新读取 jsToken 后重试一次:', e); resp = await fetch(makeUrl(), { credentials: 'same-origin' }); } if (resp.status === 401 || resp.status === 403) { console.warn(TAG, '收到 HTTP ' + resp.status + '(jsToken 可能已过期),重试一次'); resp = await fetch(makeUrl(), { credentials: 'same-origin' }); } return resp; } // 3.3.2 adToken 获取(关键步骤) async function getAdToken(path, vipLevel) { if (vipLevel >= 2) return ''; // SVIP 不需要 adToken const makeUrl = () => buildStreamingUrl('M3U8_AUTO_480', path, vipLevel, ''); try { const resp = await fetchWithTokenRetry(makeUrl); const text = await resp.text(); let data; try { data = JSON.parse(text); } catch (e) { // 返回的不是 JSON(例如直接是 m3u8 正文),说明无需 adToken return ''; } if (data.errno === 133 && data.adToken) { console.log(TAG, '获取到 adToken'); return data.adToken; } if (typeof data.errno === 'number' && data.errno !== 0) { console.warn(TAG, 'streaming 接口返回 errno=' + data.errno + ',可能权限不足或凭证失效'); } } catch (e) { console.error(TAG, '获取 adToken 失败:', e); } return ''; } /* ========================================================== * 3.4 DOM 替换模块 * ========================================================== */ function findOriginalPlayer() { return document.getElementById('video-wrap') || document.querySelector('.vp-video__player') || document.querySelector('.video-content'); } // 3.4.1 等待原播放器出现 function waitForPlayerDOM(callback, onTimeout) { waitFor(() => findOriginalPlayer(), callback, MAX_WAIT, INTERVAL, onTimeout); } // 3.4.2 替换播放器 function replacePlayer(posterUrl) { const oldPlayer = findOriginalPlayer(); if (!oldPlayer) { console.error(TAG, '找不到原播放器'); return null; } // 已替换过则直接复用容器 const existing = document.getElementById('bdhq-player'); if (existing) return existing; const container = document.createElement('div'); container.id = 'bdhq-player'; container.style.cssText = 'width:100%; height:100%; background:#000;'; // [修复1] 替换前停止并移除页面上所有已存在的