// ==UserScript== // @name 育才视频破解-9班特制-自用 // @namespace yucai9ban.local // @version 2.0.0 // @description B站视频批量下载(合集 / 分P / UP主全部视频、音视频、XML或ASS弹幕字幕)+ VIP视频解析二合一,液态玻璃界面。 // @match *://*/* // @require https://cdn.jsdelivr.net/npm/@ffmpeg/ffmpeg@0.11.6/dist/ffmpeg.min.js // @grant GM_xmlhttpRequest // @grant GM_download // @grant GM_addStyle // @grant unsafeWindow // @connect api.bilibili.com // @connect comment.bilibili.com // @connect www.bilibili.com // @connect *.bilivideo.com // @connect bilivideo.com // @connect *.bilivideo.cn // @connect bilivideo.cn // @connect *.jsdelivr.net // @connect registry.npmmirror.com // @connect unpkg.com // @run-at document-idle // @license MIT // ==/UserScript== (function () { 'use strict'; /* 仅 B 站视频 / 列表页启用下载面板,其余页面只保留解析工具 */ const YC9_IS_BILI_TARGET = /^https?:\/\/(www\.|m\.)?bilibili\.com\/(video|list)\//.test( location.href ); /* * ========================================================= * 常量 * ========================================================= */ const PANEL_ID = 'tm-bili-downloader'; const BILI_BLUE = '#00AEEC'; const FALLBACK_LOGO = 'https://i0.hdslb.com/bfs/static/jinkela/long/images/512.png'; const FFMPEG_CORE_VERSION = '@ffmpeg/core-st@0.11.1'; const FFMPEG_CORE_FILES = { js: 'ffmpeg-core.js', wasm: 'ffmpeg-core.wasm', worker: 'ffmpeg-core.worker.js', }; // 按国内可达速度排序;某镜像超时/停滞时自动切换下一个 const FFMPEG_CORE_MIRRORS = [ 'https://registry.npmmirror.com/@ffmpeg/core-st/0.11.1/files/dist/', 'https://cdn.jsdelivr.net/npm/@ffmpeg/core-st@0.11.1/dist/', 'https://fastly.jsdelivr.net/npm/@ffmpeg/core-st@0.11.1/dist/', 'https://gcore.jsdelivr.net/npm/@ffmpeg/core-st@0.11.1/dist/', 'https://unpkg.com/@ffmpeg/core-st@0.11.1/dist/', ]; const QUALITY_FALLBACK = [ { qn: 127, label: '8K 超高清' }, { qn: 126, label: '杜比视界' }, { qn: 125, label: 'HDR 真彩' }, { qn: 120, label: '4K 超清' }, { qn: 116, label: '1080P 60帧' }, { qn: 112, label: '1080P 高码率' }, { qn: 80, label: '1080P 高清' }, { qn: 74, label: '720P 60帧' }, { qn: 64, label: '720P 高清' }, { qn: 32, label: '480P 清晰' }, { qn: 16, label: '360P 流畅' }, ]; const CODECS = { auto: { ids: [12, 7, 13], label: '自动(优先 H.265)', }, avc: { ids: [7], label: 'AVC / H.264', }, hevc: { ids: [12], label: 'HEVC / H.265', }, av1: { ids: [13], label: 'AV1', }, }; const state = { href: location.href, videoData: null, items: [], collectionTitle: '', hasCollection: false, formats: [], selectedKeys: new Set(), lastCheckedKey: '', search: '', busy: false, initSeq: 0, scrollCurrentPending: false, listMode: false, listUid: '', listTotal: 0, listLoadedCount: 0, listCursor: null, listCollectionTitle: '', listRawItems: [], listMaxCount: 0, listDateStart: '', listDateEnd: '', listLoading: false, }; const $ = ( selector, root = document ) => root.querySelector( selector ); const $$ = ( selector, root = document ) => [ ...root.querySelectorAll( selector ), ]; const sleep = ms => new Promise( resolve => setTimeout( resolve, ms ) ); function unsafeWindowSafe() { try { return typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; } catch { return window; } } function sanitize(name) { return ( String( name || 'bilibili_video' ) .replace( /[\\/:*?"<>|\u0000-\u001f]+/g, '_' ) .replace( /\s+/g, ' ' ) .replace( /[. ]+$/g, '' ) .trim() .slice( 0, 180 ) || 'bilibili_video' ); } function escapeHtml(text) { return String( text ).replace( /[&<>'"]/g, c => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"', })[c] ); } function pad( n, width = 2 ) { return String( n ).padStart( width, '0' ); } function formatBytes(bytes) { if ( !Number.isFinite( bytes ) || bytes <= 0 ) { return '未知'; } const units = [ 'B', 'KB', 'MB', 'GB', ]; let n = bytes; let i = 0; while ( n >= 1024 && i < units.length - 1 ) { n /= 1024; i += 1; } return `${n.toFixed( i >= 2 ? 2 : 1 )} ${units[i]}`; } function setStatus( text, type = '' ) { const el = $( `#${PANEL_ID} .tm-status` ); if (!el) { return; } el.textContent = text; el.dataset.type = type; } function setProgress( value, text = '' ) { const p = Math.max( 0, Math.min( 100, Number( value ) || 0 ) ); const fill = $( `#${PANEL_ID} .tm-progress-fill` ); const label = $( `#${PANEL_ID} .tm-progress-text` ); if ( fill ) { fill.style.width = `${p}%`; } if ( label ) { label.textContent = text || `${p.toFixed( 0 )}%`; } } function setBusy(busy) { state.busy = busy; $$( `#${PANEL_ID} button, #${PANEL_ID} input` ).forEach( el => { if ( el.classList.contains( 'tm-min-btn' ) ) { return; } el.disabled = busy; } ); updateSelectAllState(); } /* * ========================================================= * Logo * ========================================================= */ function findOfficialLogo() { const selectors = [ '#biliMainHeader .mini-header__logo', '.bili-header .mini-header__logo', '.left-entry__title .mini-header__logo', '.mini-header__logo', '.zhuzhan-icon', ]; for ( const selector of selectors ) { const element = document.querySelector( selector ); if ( !element || element.closest( `#${PANEL_ID}` ) ) { continue; } if ( element.tagName ?.toLowerCase() === 'svg' ) { return element; } const svg = element.querySelector ?.( 'svg' ); if ( svg ) { return svg; } } return null; } function mountOfficialLogo() { const host = $( `#${PANEL_ID} .tm-logo-host` ); if ( !host ) { return false; } const official = findOfficialLogo(); if ( official ) { const clone = official.cloneNode( true ); clone.removeAttribute( 'id' ); clone.removeAttribute( 'style' ); clone.classList.add( 'tm-bili-official-svg' ); clone.setAttribute( 'aria-hidden', 'true' ); host.innerHTML = ''; host.appendChild( clone ); host.classList.add( 'is-svg' ); return true; } host.innerHTML = ` `; host.classList.remove( 'is-svg' ); return false; } function startLogoWatcher() { let attempts = 0; const timer = setInterval( () => { attempts += 1; if ( mountOfficialLogo() || attempts >= 30 ) { clearInterval( timer ); } }, 500 ); } /* * ========================================================= * API * ========================================================= */ function getCurrentBvid() { const match = location.pathname.match( /\/video\/(BV[0-9A-Za-z]+)/i ); if ( match ) { return match[1]; } const urlBvid = new URL( location.href ).searchParams.get( 'bvid' ); if ( urlBvid ) { return urlBvid; } const initial = unsafeWindowSafe() ?.__INITIAL_STATE__; return ( initial ?.videoData ?.bvid || initial ?.bvid || '' ); } /* * ========================================================= * 列表页 (/list/uid) 批量加载 * ========================================================= */ function isListPage() { return /^\/list\/\d+/.test( location.pathname ); } function getListUid() { const match = location.pathname.match( /\/list\/(\d+)/ ); if (match) { return match[1]; } const initial = unsafeWindowSafe() ?.__INITIAL_STATE__; return ( initial?.upInfo?.mid || initial?.mediaListInfo?.mid || '' ); } function getListInitialState() { const initial = unsafeWindowSafe() ?.__INITIAL_STATE__; if (!initial) { return null; } return { uid: String( initial.upInfo?.mid || initial.mediaListInfo ?.mid || getListUid() ), total: Number( initial.listTotal || initial.mediaListInfo ?.media_count || 0 ), pn: Number( initial.pn || 1 ), cursor: initial.cursor || null, resourceList: Array.isArray( initial.resourceList ) ? initial.resourceList : [], }; } function normalizeListPages( pages ) { if ( !Array.isArray( pages ) ) { return []; } return pages .filter( page => page && (page.cid || page.id) ) .map( ( page, index ) => ({ cid: page.cid || page.id, page: page.page || page.p || index + 1, part: page.part || page.title || `P${index + 1}`, duration: page.duration || 0, }) ); } function resourceItemToEpisode( item ) { const bvid = item.bvid || item.bv_id; const title = item.title || bvid; let pages = normalizeListPages( item.pages ); if ( !pages.length ) { pages = [ { cid: item.cid || 0, page: 1, part: title, duration: item.duration || 0, }, ]; } return { bvid, title, pubtime: item.pubtime || item.ctime || 0, isSeason: false, parts: pages, }; } function buildListTree( resourceList ) { return resourceList .filter( item => item && (item.bvid || item.bv_id) ) .map( resourceItemToEpisode ); } async function fetchMediaListPage( bizId, cursor ) { const url = new URL( 'https://api.bilibili.com/x/v2/medialist/resource/list' ); url.searchParams.set( 'out_referer', '' ); url.searchParams.set( 'mobi_app', 'web' ); url.searchParams.set( 'type', '1' ); url.searchParams.set( 'biz_id', bizId ); url.searchParams.set( 'ps', '20' ); url.searchParams.set( 'desc', 'false' ); url.searchParams.set( 'sort_field', '1' ); url.searchParams.set( 'tid', '0' ); url.searchParams.set( 'bvid', cursor?.bvid || '' ); url.searchParams.set( 'oid', cursor?.oid || '' ); url.searchParams.set( 'otype', '2' ); url.searchParams.set( 'with_current', 'false' ); url.searchParams.set( 'direction', 'true' ); url.searchParams.set( 'preview', '0' ); url.searchParams.set( 'use_pn', 'false' ); url.searchParams.set( 'pn', '1' ); url.searchParams.set( 'web_location', '333.1245' ); return apiJson( url.toString() ); } function updateListBatchUI() { const panel = document.getElementById( PANEL_ID ); if (!panel) { return; } panel.classList.toggle( 'tm-list-mode', state.listMode ); const countEl = $( `#${PANEL_ID} .tm-list-batch-count` ); const loadBtn = $( `#${PANEL_ID} .tm-list-load-btn` ); if ( countEl ) { countEl.textContent = state.listMode ? `已加载 ${state.listLoadedCount} / ${state.listTotal}` : ''; } if ( loadBtn ) { loadBtn.disabled = state.listLoading || state.busy; loadBtn.textContent = state.listLoading ? '加载中…' : '加载/刷新列表'; } } async function enrichInitialPubtimes( resourceList ) { const needFetch = resourceList.filter( item => item && !(item.pubtime || item.ctime) ); if ( !needFetch.length ) { return; } const results = await Promise.all( needFetch.map( async item => { try { const data = await fetchView( item.bvid ); item.pubtime = Number( data?.pubdate || 0 ); } catch (err) { console.warn( '[BiliDL] fetch pubdate failed:', item.bvid, err ); } return item; } ) ); const map = new Map( results.map( item => [ item.bvid, item, ] ) ); resourceList.forEach( item => { if ( map.has( item.bvid ) ) { const fetched = map.get( item.bvid ); item.pubtime = fetched.pubtime; } } ); } async function loadListItems( options = {} ) { const bizId = state.listUid; if ( !bizId ) { throw new Error( '未识别到列表用户 UID' ); } const maxCount = Number( options.maxCount ) || 0; const dateStart = options.dateStart; const dateEnd = options.dateEnd; const fetchMore = Boolean( options.fetchMore ); const startTs = dateStart ? new Date( `${dateStart}T00:00:00` ).getTime() / 1000 : 0; const endTs = dateEnd ? new Date( `${dateEnd}T23:59:59` ).getTime() / 1000 : Infinity; state.listLoading = true; updateListBatchUI(); try { const initial = getListInitialState(); let resourceList = initial?.resourceList ? initial.resourceList.map( item => ({ ...item, }) ) : []; if ( (dateStart || dateEnd) && resourceList.length ) { setStatus( '正在补齐前 20 个视频的发布时间…' ); await enrichInitialPubtimes( resourceList ); } resourceList = resourceList.filter( item => { const pubtime = item.pubtime || 0; if ( pubtime && pubtime < startTs ) { return false; } if ( pubtime && pubtime > endTs ) { return false; } return true; } ); const seen = new Set( resourceList.map( item => item.bvid ) ); let cursor = state.listCursor; let hasMore = fetchMore && state.listTotal > resourceList.length; let pageCount = 0; while ( hasMore ) { if ( maxCount > 0 && seen.size >= maxCount ) { break; } if ( pageCount > 200 ) { break; } setStatus( `正在加载列表第 ${pageCount + 1} 页…` ); const data = await fetchMediaListPage( bizId, cursor ); const list = Array.isArray( data?.media_list ) ? data.media_list : []; hasMore = Boolean( data?.has_more ) && list.length > 0; if ( !list.length ) { break; } for ( const item of list ) { const pubtime = item.pubtime || 0; if ( pubtime && pubtime < startTs ) { hasMore = false; break; } if ( pubtime && pubtime > endTs ) { continue; } const bvid = item.bv_id; if ( !bvid || seen.has( bvid ) ) { continue; } seen.add( bvid ); resourceList.push( item ); if ( maxCount > 0 && seen.size >= maxCount ) { hasMore = false; break; } } const first = list[0]; cursor = first ? { bvid: first.bv_id, oid: String( first.id ), } : null; pageCount += 1; await sleep( 120 ); } state.listRawItems = resourceList; state.listLoadedCount = resourceList.length; state.listCursor = cursor; const tree = buildListTree( resourceList ); state.items = buildFlatItems( tree, state.listCollectionTitle ); state.hasCollection = state.items.length > 1; state.collectionTitle = state.hasCollection ? sanitize( state.listCollectionTitle ) : ''; state.selectedKeys = new Set( state.items.map( item => item.key ) ); state.search = ''; const searchInput = $( `#${PANEL_ID} .tm-search` ); if ( searchInput ) { searchInput.value = ''; } renderItems(); updateListBatchUI(); setStatus( `列表加载完成 · ${state.listLoadedCount} 个视频`, 'ok' ); } finally { state.listLoading = false; updateListBatchUI(); } } async function initListPage() { const initial = getListInitialState(); const uid = initial?.uid || getListUid(); if ( !uid ) { throw new Error( '当前列表页未识别到用户 UID' ); } const sameList = state.listMode && state.listUid === uid && state.listRawItems.length > 0; state.listMode = true; state.listUid = uid; state.listTotal = initial?.total || initial ?.resourceList ?.length || 0; state.listCollectionTitle = initial?.resourceList?.[0] ?.upper?.name || unsafeWindowSafe() ?.__INITIAL_STATE__ ?.upInfo ?.name || 'UP主全部视频'; const currentBvid = getCurrentBvid(); const currentItem = initial?.resourceList?.find( item => item.bvid === currentBvid ); state.listCursor = currentItem ? { bvid: currentItem.bvid, oid: String( currentItem.oid ), } : initial?.resourceList?.[0] ? { bvid: initial .resourceList[0] .bvid, oid: String( initial .resourceList[0] .oid ), } : null; if ( sameList ) { state.scrollCurrentPending = true; renderItems(); return { currentBvid, videoData: unsafeWindowSafe() ?.__INITIAL_STATE__ ?.videoData, tree: buildListTree( state.listRawItems ), }; } await loadListItems({ maxCount: 0, dateStart: '', dateEnd: '', fetchMore: false, }); return { currentBvid, videoData: unsafeWindowSafe() ?.__INITIAL_STATE__ ?.videoData, tree: buildListTree( state.listRawItems ), }; } async function apiJson(url) { const res = await fetch( url, { credentials: 'include', referrer: location.href, referrerPolicy: 'strict-origin-when-cross-origin', headers: { Accept: 'application/json, text/plain, */*', }, } ); if ( !res.ok ) { throw new Error( `API HTTP ${res.status}` ); } const json = await res.json(); if ( json.code !== 0 ) { throw new Error( json.message || `API code ${json.code}` ); } return json.data; } async function fetchView( bvid ) { const url = new URL( 'https://api.bilibili.com/x/web-interface/view' ); url.searchParams.set( 'bvid', bvid ); return apiJson( url.toString() ); } async function fetchPagelist( bvid ) { const url = new URL( 'https://api.bilibili.com/x/player/pagelist' ); url.searchParams.set( 'bvid', bvid ); url.searchParams.set( 'jsonp', 'jsonp' ); const data = await apiJson( url.toString() ); return Array.isArray( data ) ? data : []; } function getFreshInitialVideoData( currentBvid ) { const videoData = unsafeWindowSafe() ?.__INITIAL_STATE__ ?.videoData; if ( !videoData ) { return null; } if ( videoData.bvid && currentBvid && videoData.bvid !== currentBvid ) { return null; } return videoData; } /* * ========================================================= * 合集 / 分P * ========================================================= */ function extractSeasonEpisodes( videoData ) { const episodes = []; const sections = videoData ?.ugc_season ?.sections; if ( !Array.isArray( sections ) ) { return episodes; } for ( const section of sections ) { if ( !Array.isArray( section ?.episodes ) ) { continue; } for ( const ep of section.episodes ) { if ( !ep?.bvid ) { continue; } episodes.push({ bvid: ep.bvid, title: ep.title || ep.arc ?.title || ep.bvid, cid: ep.cid || 0, isSeason: true, }); } } return episodes; } async function fetchSeasonArchivesFallback( videoData ) { const seasonId = videoData ?.ugc_season ?.id; const mid = videoData ?.owner ?.mid; if ( !seasonId || !mid ) { return []; } const archives = []; let pageNum = 1; let total = Infinity; while ( archives.length < total ) { const url = new URL( 'https://api.bilibili.com/x/polymer/web-space/seasons_archives_list' ); url.searchParams.set( 'mid', String( mid ) ); url.searchParams.set( 'season_id', String( seasonId ) ); url.searchParams.set( 'page_num', String( pageNum ) ); url.searchParams.set( 'page_size', '100' ); const data = await apiJson( url.toString() ); const list = Array.isArray( data ?.archives ) ? data.archives : []; total = Number( data ?.page ?.total ?? list.length ); for ( const item of list ) { if ( !item?.bvid ) { continue; } archives.push({ bvid: item.bvid, title: item.title || item.bvid, cid: item.cid || 0, isSeason: true, }); } if ( !list.length || archives.length >= total ) { break; } pageNum += 1; if ( pageNum > 100 ) { break; } } return [ ...new Map( archives.map( item => [ item.bvid, item, ] ) ).values(), ]; } function buildFlatItems( tree, collectionTitle ) { const flat = []; tree.forEach( ( episode, episodeIndex ) => { episode.parts.forEach( ( part, partIndex ) => { flat.push({ key: `${episode.bvid}:${part.cid}`, bvid: episode.bvid, cid: part.cid, page: part.page || partIndex + 1, pages: episode.parts.length, duration: part.duration || 0, part: sanitize( part.part || `P${partIndex + 1}` ), videoTitle: sanitize( episode.title || episode.bvid ), collectionTitle: sanitize( collectionTitle || '' ), collectionIndex: episodeIndex + 1, collectionCount: tree.length, isSeason: episode.isSeason, }); } ); } ); return flat; } async function parseResourcesFast() { const currentBvid = getCurrentBvid(); if ( !currentBvid ) { throw new Error( '当前页面没有识别到 BV 号' ); } setStatus( '正在读取合集信息…' ); let videoData = getFreshInitialVideoData( currentBvid ); if ( !videoData ) { videoData = await fetchView( currentBvid ); } state.videoData = videoData; let rawEpisodes = extractSeasonEpisodes( videoData ); if ( !rawEpisodes.length && videoData ?.ugc_season ?.id ) { try { rawEpisodes = await fetchSeasonArchivesFallback( videoData ); } catch (err) { console.warn( '[BiliDL] season fallback failed:', err ); } } if ( !rawEpisodes.length ) { rawEpisodes = [ { bvid: currentBvid, title: videoData ?.title || currentBvid, cid: videoData ?.cid || 0, isSeason: false, }, ]; } rawEpisodes = [ ...new Map( rawEpisodes.map( episode => [ episode.bvid, episode, ] ) ).values(), ]; setStatus( `正在并发解析 ${rawEpisodes.length} 个视频的分P…` ); const tree = await Promise.all( rawEpisodes.map( async episode => { let pages = []; if ( episode.bvid === currentBvid && Array.isArray( videoData ?.pages ) && videoData .pages .length ) { pages = videoData.pages; } else { try { pages = await fetchPagelist( episode.bvid ); } catch (err) { console.warn( `[BiliDL] pagelist failed: ${episode.bvid}`, err ); } } if ( !pages.length ) { pages = [ { cid: episode.cid || ( episode.bvid === currentBvid ? videoData ?.cid : 0 ), page: 1, part: episode.title, }, ]; } return { bvid: episode.bvid, title: episode.title, isSeason: episode.isSeason, parts: pages .filter( page => page ?.cid ) .map( ( page, index ) => ({ cid: page.cid, page: page.page || index + 1, part: page.part || `P${index + 1}`, }) ), }; } ) ); const collectionTitle = videoData ?.ugc_season ?.title || videoData ?.ugc_season ?.name || videoData ?.title || '合集'; state.items = buildFlatItems( tree, collectionTitle ); state.hasCollection = Boolean( videoData ?.ugc_season ?.id ) || rawEpisodes.length > 1; state.collectionTitle = state.hasCollection ? sanitize( collectionTitle ) : ''; /* * 默认只勾选当前视频 / 当前分P。 */ state.selectedKeys.clear(); const currentItem = getCurrentItem(); if ( currentItem ) { state.selectedKeys.add( currentItem.key ); } state.search = ''; state.scrollCurrentPending = true; const searchInput = $( `#${PANEL_ID} .tm-search` ); if ( searchInput ) { searchInput.value = ''; } const searchWrap = $( `#${PANEL_ID} .tm-search-wrap` ); if ( searchWrap ) { searchWrap.classList.remove( 'open' ); } return { currentBvid, videoData, tree, }; } /* * ========================================================= * 当前视频 * ========================================================= */ function getCurrentItem() { const currentBvid = getCurrentBvid(); if ( !currentBvid ) { return null; } const sameVideo = state.items.filter( item => item.bvid === currentBvid ); if ( !sameVideo.length ) { return null; } const pParam = Number( new URL( location.href ).searchParams.get( 'p' ) || 0 ); if ( pParam > 0 ) { const byPage = sameVideo.find( item => Number( item.page ) === pParam ); if ( byPage ) { return byPage; } } const currentCid = Number( state.videoData ?.cid || 0 ); if ( currentCid ) { const byCid = sameVideo.find( item => Number( item.cid ) === currentCid ); if ( byCid ) { return byCid; } } return sameVideo[0]; } function flashCurrentRow( row ) { if ( !row ) { return; } row.classList.remove( 'tm-current-flash' ); void row.offsetWidth; row.classList.add( 'tm-current-flash' ); setTimeout( () => { row.classList.remove( 'tm-current-flash' ); }, 1400 ); } function scrollCurrentItemToTop() { if ( !state.scrollCurrentPending || state.search ) { return; } const panel = document.getElementById( PANEL_ID ); const list = $( `#${PANEL_ID} .tm-items` ); if ( !panel || !list ) { return; } if ( panel.classList.contains( 'minimized' ) ) { return; } if ( list.offsetParent === null || list.clientHeight <= 0 ) { return; } const currentRow = list.querySelector( '.tm-item[data-current="1"]' ); if ( !currentRow ) { return; } requestAnimationFrame( () => { if ( panel.classList.contains( 'minimized' ) || list.offsetParent === null || list.clientHeight <= 0 ) { return; } list.scrollTop = Math.max( 0, currentRow.offsetTop ); state.scrollCurrentPending = false; requestAnimationFrame( () => { flashCurrentRow( currentRow ); } ); } ); } /* * ========================================================= * 播放信息 * ========================================================= */ async function fetchPlayData( item, qn ) { const url = new URL( 'https://api.bilibili.com/x/player/playurl' ); url.searchParams.set( 'bvid', item.bvid ); url.searchParams.set( 'cid', String( item.cid ) ); url.searchParams.set( 'qn', String( qn ) ); url.searchParams.set( 'fnver', '0' ); url.searchParams.set( 'fnval', '4048' ); url.searchParams.set( 'fourk', '1' ); url.searchParams.set( 'otype', 'json' ); return apiJson( url.toString() ); } /* * 尝试获取已经包含音视频的 durl。 * * 能拿到完整单文件时优先直接下载, * 不进入 FFmpeg。 */ async function fetchDirectPlayData( item, qn ) { const url = new URL( 'https://api.bilibili.com/x/player/playurl' ); url.searchParams.set( 'bvid', item.bvid ); url.searchParams.set( 'cid', String( item.cid ) ); url.searchParams.set( 'qn', String( qn ) ); url.searchParams.set( 'fnver', '0' ); url.searchParams.set( 'fnval', '0' ); url.searchParams.set( 'fourk', '0' ); url.searchParams.set( 'otype', 'json' ); return apiJson( url.toString() ); } function normalizeFormats( data ) { const map = new Map(); for ( const format of data ?.support_formats || [] ) { const qn = Number( format .quality ); if ( !qn ) { continue; } map.set( qn, { qn, label: format .new_description || format .display_desc || format .superscript || format .format || `画质 ${qn}`, } ); } for ( const quality of data ?.accept_quality || [] ) { const qn = Number( quality ); if ( !qn || map.has( qn ) ) { continue; } map.set( qn, { qn, label: QUALITY_FALLBACK.find( item => item.qn === qn ) ?.label || `画质 ${qn}`, } ); } return [ ...map.values(), ].sort( ( a, b ) => b.qn - a.qn ); } function codecName( codecid ) { const id = Number( codecid ); if ( id === 7 ) { return 'H.264'; } if ( id === 12 ) { return 'H.265'; } if ( id === 13 ) { return 'AV1'; } return `codec ${id}`; } function frameRateName( stream ) { const value = String( stream ?.frameRate || stream ?.frame_rate || '' ).trim(); if ( !value ) { return ''; } if ( /^\d+(?:\.\d+)?$/.test( value ) ) { return `${Math.round( Number( value ) )}fps`; } return value .toLowerCase() .includes( 'fps' ) ? value : `${value}fps`; } function streamUrls( stream ) { const urls = []; const add = value => { if ( !value ) { return; } if ( Array.isArray( value ) ) { value.forEach( add ); return; } const url = String( value ).replace( /^http:/, 'https:' ); if ( url && !urls.includes( url ) ) { urls.push( url ); } }; add( stream ?.baseUrl ); add( stream ?.base_url ); add( stream ?.url ); add( stream ?.backupUrl ); add( stream ?.backup_url ); return urls; } function getActualSupportedQns( data ) { const qns = new Set(); for ( const video of data ?.dash ?.video || [] ) { const qn = Number( video.id ); if ( qn ) { qns.add( qn ); } } if ( !qns.size ) { for ( const format of data ?.support_formats || [] ) { const qn = Number( format.quality ); if ( qn ) { qns.add( qn ); } } } return [ ...qns, ].sort( ( a, b ) => b - a ); } function resolveTargetQn( data, requestedQn ) { const supported = getActualSupportedQns( data ); if ( !supported.length ) { return Number( data?.quality || 0 ); } for ( const qn of supported ) { if ( qn <= requestedQn ) { return qn; } } return supported[ supported.length - 1 ]; } function pickExactVideo( data, requestedQn, codecPref ) { const targetQn = resolveTargetQn( data, requestedQn ); if ( !targetQn ) { throw new Error( '当前视频没有可用的视频流。' ); } const videos = Array.isArray( data ?.dash ?.video ) ? data .dash .video : []; const exact = videos.filter( video => Number( video.id ) === targetQn ); if ( !exact.length ) { throw new Error( '当前视频没有所选画质的视频流。' ); } const codecIds = CODECS[ codecPref ]?.ids || CODECS .auto .ids; for ( const codecId of codecIds ) { const candidates = exact .filter( video => Number( video .codecid ) === codecId ) .sort( ( a, b ) => ( b.bandwidth || 0 ) - ( a.bandwidth || 0 ) ); if ( candidates.length ) { return candidates[0]; } } throw new Error( `当前画质没有 ${CODECS[ codecPref ]?.label || codecPref } 编码的视频流。` ); } function pickAudio( data ) { const list = []; if ( Array.isArray( data ?.dash ?.audio ) ) { list.push( ...data .dash .audio ); } if ( Array.isArray( data ?.dash ?.dolby ?.audio ) ) { list.push( ...data .dash .dolby .audio ); } if ( data ?.dash ?.flac ?.audio ) { list.push( data .dash .flac .audio ); } if ( !list.length ) { return null; } return list.sort( ( a, b ) => ( b.bandwidth || 0 ) - ( a.bandwidth || 0 ) )[0]; } /* * ========================================================= * 下载网络数据 * ========================================================= */ function requestArrayBufferUrl( url, onProgress ) { return new Promise( ( resolve, reject ) => { GM_xmlhttpRequest({ method: 'GET', url, responseType: 'arraybuffer', timeout: 120000, headers: { Referer: 'https://www.bilibili.com/', Origin: 'https://www.bilibili.com', }, onprogress: event => { if ( typeof onProgress === 'function' ) { onProgress( event.loaded || 0, event.total || 0 ); } }, onload: response => { if ( response.status >= 200 && response.status < 300 && response.response ) { resolve( response.response ); } else { reject( new Error( `HTTP ${response.status}` ) ); } }, onerror: () => { logError( 'net', `媒体流请求失败:${url}` ); reject( new Error( '媒体网络请求失败' ) ); }, ontimeout: () => { logError( 'net', `媒体流请求超时:${url}` ); reject( new Error( '媒体网络请求超时' ) ); }, }); } ); } function requestTextUrl( url ) { return new Promise( ( resolve, reject ) => { GM_xmlhttpRequest({ method: 'GET', url, responseType: 'text', timeout: 120000, headers: { Referer: 'https://www.bilibili.com/', Origin: 'https://www.bilibili.com', }, onload: response => { const text = typeof response .responseText === 'string' ? response .responseText : String( response .response || '' ); if ( response.status >= 200 && response.status < 300 ) { resolve( text ); } else { reject( new Error( `HTTP ${response.status}` ) ); } }, onerror: () => { logError( 'api', `接口请求失败:${url}` ); reject( new Error( '文本网络请求失败' ) ); }, ontimeout: () => { logError( 'api', `接口请求超时:${url}` ); reject( new Error( '文本网络请求超时' ) ); }, }); } ); } async function requestStreamBuffer( stream, onProgress ) { const urls = streamUrls( stream ); if ( !urls.length ) { throw new Error( '媒体直链为空' ); } let lastError = null; for ( let i = 0; i < urls.length; i += 1 ) { try { return await requestArrayBufferUrl( urls[i], onProgress ); } catch (err) { lastError = err; console.warn( `[BiliDL] CDN ${i + 1}/${urls.length} failed:`, urls[i], err ); } } throw new Error( `所有媒体CDN均下载失败:${lastError ?.message || lastError || '未知错误' }` ); } function requestDirectFile( url, filename, onProgress ) { return new Promise( ( resolve, reject ) => { try { GM_download({ url, name: filename, saveAs: false, headers: { Referer: 'https://www.bilibili.com/', }, onprogress: event => { if ( typeof onProgress === 'function' ) { onProgress( event.loaded || 0, event.total || 0 ); } }, onload: () => resolve(), onerror: error => reject( new Error( `直链下载失败:${error ?.error || error ?.message || '未知错误' }` ) ), ontimeout: () => reject( new Error( '直链下载超时' ) ), }); } catch (err) { reject( err ); } } ); } function directEntryUrls( entry ) { const urls = []; const add = value => { if ( !value ) { return; } if ( Array.isArray( value ) ) { value.forEach( add ); return; } const url = String( value ).replace( /^http:/, 'https:' ); if ( url && !urls.includes( url ) ) { urls.push( url ); } }; add( entry ?.url ); add( entry ?.backup_url ); add( entry ?.backupUrl ); return urls; } function directFileExtension( data, entry ) { const format = String( data ?.format || '' ).toLowerCase(); const url = String( entry ?.url || '' ).toLowerCase(); if ( format.includes( 'flv' ) || /\.flv(?:\?|$)/.test( url ) ) { return 'flv'; } return 'mp4'; } async function downloadDirectEntry( entry, filename, onProgress ) { const urls = directEntryUrls( entry ); if ( !urls.length ) { throw new Error( '直链地址为空' ); } let lastError = null; for ( let i = 0; i < urls.length; i += 1 ) { try { await requestDirectFile( urls[i], filename, onProgress ); return; } catch (err) { lastError = err; console.warn( `[BiliDL] direct CDN ${i + 1}/${urls.length} failed:`, urls[i], err ); } } throw new Error( `所有直链均下载失败:${lastError ?.message || lastError || '未知错误' }` ); } /* * 页面 frame 可能被沙箱化(缺 allow-downloads), * a[download] 会被 Chrome 静默拦截,因此保存分三层: * 1) 大文件:点击下载时预弹“另存为”拿到 FileHandle,流式写盘(零拷贝); * 2) 小文件:Blob → data: URL → GM_download(扩展下载通道,不受沙箱限制); * 3) 兜底:a[download](非沙箱环境仍可用)。 */ const SAVE_DATA_URL_LIMIT = 256 * 1024 * 1024; function blobToDataURL( blob ) { return new Promise( (resolve, reject) => { const fr = new FileReader(); fr.onload = () => resolve( String(fr.result) ); fr.onerror = () => reject( fr.error || new Error( 'FileReader 转换失败' ) ); fr.readAsDataURL( blob ); } ); } function gmDownloadUrl( url, name ) { return new Promise( (resolve, reject) => { GM_download({ url: url, name: name, onload: () => resolve(), onerror: (e) => reject( new Error( `GM_download 失败:${ e?.error || 'unknown' }${ e?.details ? `(${e.details})` : '' }` ) ), ontimeout: () => reject( new Error( 'GM_download 超时' ) ), }); } ); } function saveBlobViaAnchor( blob, filename ) { const url = URL.createObjectURL( blob ); const a = document.createElement( 'a' ); a.href = url; a.download = filename; a.rel = 'noopener'; document.body.appendChild( a ); a.click(); a.remove(); logInfo( 'app', `a[download] 已触发:${filename},若浏览器没有弹出下载说明页面环境拦截了页面下载(沙箱)` ); setTimeout( () => URL.revokeObjectURL( url ), 60000 ); } async function saveBlob( blob, filename, saveTarget = null ) { // 1) 大文件:写入用户预选的位置 if ( saveTarget && saveTarget.fileHandle ) { try { const writable = await saveTarget.fileHandle.createWritable(); await writable.write( blob ); await writable.close(); logInfo( 'app', `已写入预选位置:${filename}(${formatBytes( blob.size )},file-picker 通道)` ); return; } catch (e) { logWarn( 'app', `file-picker 写入失败,转下一通道:${ e && e.message }` ); } } // 2) 小文件:data: URL → 扩展下载通道 if ( blob.size <= SAVE_DATA_URL_LIMIT ) { try { const dataUrl = await blobToDataURL( blob ); await gmDownloadUrl( dataUrl, filename ); logInfo( 'app', `已通过扩展通道保存:${filename}(${formatBytes( blob.size )},gm-data 通道)` ); return; } catch (e) { logWarn( 'app', `扩展通道保存失败,转 a[download] 兜底:${ e && e.message }` ); } } else { logWarn( 'app', `文件 ${formatBytes( blob.size )} 超过 data 通道阈值且没有预选保存位置,仅剩 a[download] 可用` ); } // 3) 兜底:页面 a[download] saveBlobViaAnchor( blob, filename ); } /* * ========================================================= * FFmpeg * ========================================================= */ /* * ========================================================= * 日志 * ========================================================= */ const LOG_CATEGORIES = { api: '解析', net: '下载', ffmpeg: 'FFmpeg', app: '脚本', }; const LOG_BUFFER = []; const LOG_BUFFER_MAX = 1000; const LOG_STATE = { echo: false, filter: 'all', open: false, stickBottom: true, }; let logOverlayEl = null; function logInfo(cat, msg) { pushLog(cat, 'info', msg); } function logWarn(cat, msg) { pushLog(cat, 'warn', msg); } function logError(cat, msg) { pushLog(cat, 'error', msg); } function pushLog(cat, level, msg) { const entry = { ts: Date.now(), cat: cat, level: level, msg: String(msg), }; LOG_BUFFER.push(entry); if (LOG_BUFFER.length > LOG_BUFFER_MAX) { LOG_BUFFER.splice( 0, LOG_BUFFER.length - LOG_BUFFER_MAX ); } if (LOG_STATE.echo) { const tag = `[BiliDL][${LOG_CATEGORIES[cat] || cat}]`; if (level === 'error') console.error(tag, msg); else if (level === 'warn') console.warn(tag, msg); else console.log(tag, msg); } if (LOG_STATE.open && logOverlayEl) { if (matchesLogFilter(entry)) { appendLogEntry(entry); } } } function matchesLogFilter(entry) { return ( LOG_STATE.filter === 'all' || LOG_STATE.filter === entry.cat ); } function formatLogTime(ts) { const d = new Date(ts); const p = (n, w = 2) => String(n).padStart(w, '0'); return `${p(d.getHours())}:${p( d.getMinutes() )}:${p(d.getSeconds())}.${p( d.getMilliseconds(), 3 )}`; } function formatLogLine(entry) { return `[${formatLogTime( entry.ts )}][${LOG_CATEGORIES[entry.cat] || entry.cat}][${entry.level}] ${ entry.msg }`; } function buildLogText() { return LOG_BUFFER.map(formatLogLine).join( '\n' ); } function ensureLogOverlay() { if (logOverlayEl) return logOverlayEl; const root = document.createElement( 'div' ); root.id = `${PANEL_ID}-log`; root.innerHTML = `
运行日志
`; document.body.appendChild(root); const catsBox = root.querySelector( '.tm-log-cats' ); const chips = [ ['all', '全部'], ...Object.entries(LOG_CATEGORIES), ]; chips.forEach(([key, label]) => { const chip = document.createElement('button'); chip.type = 'button'; chip.className = 'tm-log-chip'; chip.dataset.cat = key; chip.textContent = label; if (key === LOG_STATE.filter) { chip.classList.add('active'); } chip.addEventListener('click', () => { LOG_STATE.filter = key; catsBox .querySelectorAll('.tm-log-chip') .forEach(el => { el.classList.toggle( 'active', el.dataset.cat === key ); }); renderLogList(); }); catsBox.appendChild(chip); }); root .querySelector('.tm-log-echo-box') .addEventListener('change', event => { LOG_STATE.echo = event.target.checked; logInfo( 'app', `控制台回显已${ LOG_STATE.echo ? '开启' : '关闭' }` ); }); root .querySelectorAll('.tm-log-btn') .forEach(btn => { btn.addEventListener( 'click', event => { handleLogAction( event.currentTarget .dataset.act ); } ); }); const list = root.querySelector( '.tm-log-list' ); list.addEventListener('scroll', () => { LOG_STATE.stickBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 24; }); logOverlayEl = root; renderLogList(); return root; } function appendLogEntry(entry) { if (!logOverlayEl) return; const list = logOverlayEl.querySelector( '.tm-log-list' ); const line = document.createElement('div'); line.className = `tm-log-line tm-log-${entry.level}`; line.textContent = formatLogLine(entry); const stick = LOG_STATE.stickBottom; list.appendChild(line); while (list.childElementCount > 600) { list.removeChild(list.firstChild); } if (stick) { list.scrollTop = list.scrollHeight; } } function renderLogList() { if (!logOverlayEl) return; const list = logOverlayEl.querySelector( '.tm-log-list' ); list.textContent = ''; LOG_BUFFER.filter(matchesLogFilter).forEach( appendLogEntry ); list.scrollTop = list.scrollHeight; } function toggleLogOverlay(force) { const next = typeof force === 'boolean' ? force : !LOG_STATE.open; if (next) { ensureLogOverlay(); logOverlayEl.style.display = 'flex'; LOG_STATE.open = true; renderLogList(); } else if (logOverlayEl) { logOverlayEl.style.display = 'none'; LOG_STATE.open = false; } } function handleLogAction(act) { if (act === 'close') { toggleLogOverlay(false); return; } if (act === 'clear') { LOG_BUFFER.length = 0; renderLogList(); logInfo('app', '日志已清空'); return; } if (act === 'copy') { copyLogToClipboard(); return; } if (act === 'export') { const stamp = new Date() .toISOString() .replace(/[:T]/g, '-') .slice(0, 19); saveBlob( new Blob([buildLogText()], { type: 'text/plain;charset=utf-8', }), `育才9班下载日志-${stamp}.txt` ); logInfo('app', '日志已导出为文本文件'); } } function copyLogToClipboard() { const text = buildLogText(); const done = () => { logInfo('app', '日志已复制到剪贴板'); }; const fallback = () => { const ta = document.createElement('textarea'); ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); try { document.execCommand('copy'); done(); } catch (e) { logError( 'app', `复制失败:${e && e.message}` ); } ta.remove(); }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard .writeText(text) .then(done) .catch(fallback); } else { fallback(); } } /* * ========================================================= * FFmpeg 核心缓存与多镜像下载 * ========================================================= */ const CORE_CACHE_DB_NAME = 'mt-bili-downloader'; const CORE_CACHE_STORE = 'ffmpeg-core'; // 固定包版本的已知字节数,用于识别截断/损坏的下载 const FFMPEG_CORE_SIZES = { 'ffmpeg-core.js': 86313, 'ffmpeg-core.wasm': 24383038, 'ffmpeg-core.worker.js': 0, }; let ffmpegCorePromise = null; function openCoreCacheDB() { return new Promise( (resolve, reject) => { const req = indexedDB.open( CORE_CACHE_DB_NAME, 1 ); req.onupgradeneeded = () => { if ( !req.result.objectStoreNames.contains( CORE_CACHE_STORE ) ) { req.result.createObjectStore( CORE_CACHE_STORE ); } }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); } ); } async function readCoreCache( key, expectedSize ) { // 缓存读失败一律视为未命中,静默降级为重新下载 try { const db = await openCoreCacheDB(); const rec = await new Promise( (resolve, reject) => { const req = db .transaction( CORE_CACHE_STORE, 'readonly' ) .objectStore( CORE_CACHE_STORE ) .get(key); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); } ); if ( rec && rec.blob instanceof Blob && rec.blob.size === rec.size && (!expectedSize || rec.blob.size === expectedSize) ) { return rec.blob; } return null; } catch (e) { return null; } } function writeCoreCache( key, blob ) { openCoreCacheDB() .then( (db) => new Promise( (resolve, reject) => { const tx = db.transaction( CORE_CACHE_STORE, 'readwrite' ); tx.objectStore( CORE_CACHE_STORE ).put( { name: key, size: blob.size, blob: blob, ts: Date.now(), }, key ); tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); } ) ) .catch( () => {} ); } function requestCoreBuffer( url, options ) { return new Promise( (resolve, reject) => { const timeout = options.timeout; const stall = options.stall; const onProgress = options.onProgress; let settled = false; let request = null; let watchdog = null; let lastProgressAt = Date.now(); const finish = ( ok, value ) => { if (settled) return; settled = true; if (watchdog) clearInterval( watchdog ); if (request) { try { request.abort(); } catch (e) { // 已结束的请求 abort 无意义 } } if (ok) resolve(value); else reject(value); }; // 停滞看门狗:长时间无进度数据视为该镜像不可用(0 字节文件禁用) if (stall > 0) { watchdog = setInterval(() => { if ( Date.now() - lastProgressAt > stall ) { finish( false, new Error( '下载停滞' ) ); } }, 2000); } request = GM_xmlhttpRequest( { method: 'GET', url: url, responseType: 'arraybuffer', timeout: timeout, onprogress: ( event ) => { lastProgressAt = Date.now(); if (onProgress) onProgress( event.loaded || 0, event.total || 0 ); }, onload: ( response ) => { if ( response.status >= 200 && response.status < 300 && response.response ) { finish( true, response.response ); } else { finish( false, new Error( `HTTP ${response.status}` ) ); } }, onerror: () => finish( false, new Error( '网络请求失败' ) ), ontimeout: () => finish( false, new Error( '网络请求超时' ) ), } ); } ); } async function fetchCoreFile( filename, onProgress ) { const isWasm = filename === FFMPEG_CORE_FILES.wasm; const expectedSize = FFMPEG_CORE_SIZES[ filename ]; let lastError = null; for (const mirror of FFMPEG_CORE_MIRRORS) { try { const buf = await requestCoreBuffer( mirror + filename, { timeout: isWasm ? 120000 : 10000, stall: isWasm ? 20000 : 0, onProgress, } ); if ( expectedSize && buf.byteLength !== expectedSize ) { throw new Error( '文件大小不符' ); } logInfo( 'net', `FFmpeg核心 ${filename} 下载成功:${buf.byteLength} 字节 ← ${mirror}` ); return buf; } catch (e) { logWarn( 'net', `FFmpeg核心 ${filename} 镜像失败:${mirror}(${ e && e.message })` ); lastError = e; } } logError( 'net', `FFmpeg核心 ${filename} 所有镜像均不可用:${ lastError && lastError.message }` ); throw new Error( `FFmpeg 核心下载失败(所有镜像均不可用):${ lastError && lastError.message }` ); } async function loadFFmpegCore() { const prefix = FFMPEG_CORE_VERSION + ':'; const names = [ FFMPEG_CORE_FILES.js, FFMPEG_CORE_FILES.wasm, FFMPEG_CORE_FILES.worker, ]; const blobs = {}; for (const name of names) { blobs[name] = await readCoreCache( prefix + name, FFMPEG_CORE_SIZES[name] ); if (blobs[name]) { logInfo( 'net', `FFmpeg核心 ${name} 命中本地缓存` ); } } for (const name of names) { if (blobs[name]) continue; const isWasm = name === FFMPEG_CORE_FILES.wasm; if (isWasm) setStatus( '正在下载 FFmpeg 核心…' ); const buf = await fetchCoreFile( name, isWasm ? (loaded, total) => setStatus( `正在下载 FFmpeg 核心(${formatBytes( loaded )} / ${formatBytes( total )})…` ) : null ); const blob = new Blob( [buf] ); blobs[name] = blob; writeCoreCache( prefix + name, blob ); } return { corePath: URL.createObjectURL( blobs[FFMPEG_CORE_FILES.js] ), wasmPath: URL.createObjectURL( blobs[ FFMPEG_CORE_FILES.wasm ] ), workerPath: URL.createObjectURL( blobs[ FFMPEG_CORE_FILES .worker ] ), }; } function getFFmpegCoreUrls() { if (!ffmpegCorePromise) { ffmpegCorePromise = loadFFmpegCore(); // 失败后清空,允许下次下载时重试 ffmpegCorePromise.catch( () => { ffmpegCorePromise = null; } ); } return ffmpegCorePromise; } async function muxAndSave( videoBuf, audioBuf, outputName, saveTarget = null ) { if ( typeof FFmpeg === 'undefined' || !FFmpeg.createFFmpeg ) { logError( 'ffmpeg', 'FFmpeg.wasm 没有加载成功(@require 未注入)' ); throw new Error( 'FFmpeg.wasm 没有加载成功' ); } setStatus( '正在加载 FFmpeg…' ); logInfo( 'ffmpeg', `准备合流:${outputName}(视频 ${formatBytes( videoBuf.byteLength )}${audioBuf ? `,音频 ${formatBytes(audioBuf.byteLength)}` : ',无音轨'})` ); const urls = await getFFmpegCoreUrls(); logInfo( 'ffmpeg', 'FFmpeg核心已就绪,开始装载 wasm' ); const ffmpeg = FFmpeg.createFFmpeg({ log: false, mainName: 'main', // 捕获 FFmpeg 内部 stderr/stdout,关键错误会进日志面板 logger: ({ type, message }) => { if ( type === 'fferr' && message && !/^\s*(frame|size|fps)=/.test( message ) ) { logWarn( 'ffmpeg', message ); } else if ( type === 'ffout' && message ) { logInfo( 'ffmpeg', message ); } }, corePath: urls.corePath, wasmPath: urls.wasmPath, workerPath: urls.workerPath, }); await ffmpeg.load(); const token = `${Date.now()}_${Math.random() .toString(36) .slice(2)}`; const vin = `video_${token}.mp4`; const ain = `audio_${token}.m4a`; const out = `output_${token}.mp4`; try { ffmpeg.FS( 'writeFile', vin, new Uint8Array( videoBuf ) ); if ( audioBuf ) { ffmpeg.FS( 'writeFile', ain, new Uint8Array( audioBuf ) ); } setStatus( '正在无损合流音视频…' ); setProgress( 96, '合流中…' ); try { if ( audioBuf ) { await ffmpeg.run( '-nostdin', '-y', '-i', vin, '-i', ain, '-map', '0:v:0', '-map', '1:a:0', '-c', 'copy', '-movflags', '+faststart', '-shortest', out ); } else { await ffmpeg.run( '-nostdin', '-y', '-i', vin, '-c', 'copy', '-movflags', '+faststart', out ); } } catch (err) { const message = String( err ?.message ?? err ); logError( 'ffmpeg', `ffmpeg.run 抛出异常:${message}` ); if ( !/\bexit\(0\)\b/i.test( message ) ) { throw err; } } const bytes = ffmpeg.FS( 'readFile', out ); if ( !( bytes instanceof Uint8Array ) || !bytes.byteLength ) { logError( 'ffmpeg', `合流输出为空:${out}` ); throw new Error( 'FFmpeg输出MP4为空' ); } logInfo( 'ffmpeg', `合流输出 ${bytes.byteLength} 字节` ); setStatus( '正在保存到本地…' ); /* * Blob 构造时会对 bytes 做内部快照, * 直接吃 FS 读出的 Uint8Array 即可, * 不再需要 slice 的整份拷贝。 */ await saveBlob( new Blob( [ bytes, ], { type: 'video/mp4', } ), `${outputName}.mp4`, saveTarget && saveTarget.dirHandle ? { fileHandle: await uniqueSaveFileHandle( saveTarget.dirHandle, `${outputName}.mp4` ), } : saveTarget ); } finally { for ( const path of [ vin, ain, out, ] ) { try { ffmpeg.FS( 'unlink', path ); } catch { } } try { ffmpeg.exit(); } catch { } } } /* * ========================================================= * 自定义下拉框 * ========================================================= */ function dropdownArrowHtml() { return ` `; } function getDropdownRoot( name ) { return $( `#${PANEL_ID} .tm-dropdown[data-name="${name}"]` ); } function getDropdownValue( name ) { return ( getDropdownRoot( name ) ?.dataset ?.value || '' ); } function closeDropdowns( except = null ) { $$( `#${PANEL_ID} .tm-dropdown.open` ).forEach( root => { if ( root !== except ) { root.classList.remove( 'open' ); } } ); } function setDropdownValue( root, value, label = null ) { if ( !root ) { return; } const stringValue = String( value ?? '' ); root.dataset.value = stringValue; const options = $$( '.tm-select-option', root ); let selectedLabel = label; options.forEach( option => { const selected = option.dataset .value === stringValue; option.classList.toggle( 'selected', selected ); option.setAttribute( 'aria-selected', selected ? 'true' : 'false' ); if ( selected && selectedLabel == null ) { selectedLabel = option .querySelector( '.tm-option-text' ) ?.textContent ?.trim() || option .textContent .trim(); } } ); const labelEl = $( '.tm-select-label', root ); if ( labelEl ) { labelEl.textContent = selectedLabel || '请选择'; } } function setDropdownOptions( name, options, preferredValue = '' ) { const root = getDropdownRoot( name ); if ( !root ) { return; } const menu = $( '.tm-select-menu', root ); if ( !menu ) { return; } const normalized = ( options || [] ).map( option => ({ value: String( option.value ), label: String( option.label ), }) ); menu.innerHTML = normalized .map( option => ` ` ) .join( '' ); if ( !normalized.length ) { root.dataset.value = ''; const labelEl = $( '.tm-select-label', root ); if ( labelEl ) { labelEl.textContent = '无可用选项'; } return; } const preferred = String( preferredValue ?? '' ); const selected = normalized.find( option => option.value === preferred ) || normalized[0]; setDropdownValue( root, selected.value, selected.label ); } function initStaticDropdowns() { setDropdownOptions( 'codec', [ { value: 'auto', label: '自动(优先 H.265)', }, { value: 'avc', label: 'AVC / H.264', }, { value: 'hevc', label: 'HEVC / H.265', }, { value: 'av1', label: 'AV1', }, ], 'auto' ); setDropdownOptions( 'subtitle', [ { value: 'xml', label: 'XML 原始弹幕', }, { value: 'ass', label: 'ASS 播放器字幕', }, ], 'xml' ); } /* * ========================================================= * UI 数据 * ========================================================= */ function getSelectedQn() { return Number( getDropdownValue( 'quality' ) || 0 ); } function getSelectedCodec() { return ( getDropdownValue( 'codec' ) || 'auto' ); } function getSelectedSubtitleFormat() { return ( getDropdownValue( 'subtitle' ) || 'xml' ); } function getVisibleItems() { const keyword = state.search .trim() .toLowerCase(); if ( !keyword ) { return state.items; } return state.items.filter( item => { const text = [ item.videoTitle, item.part, `P${item.page}`, item.page, item.collectionIndex, ] .join( ' ' ) .toLowerCase(); return text.includes( keyword ); } ); } function selectedItems() { return state.items.filter( item => state.selectedKeys.has( item.key ) ); } function itemLabel( item ) { if ( item.pages > 1 ) { return `${item.videoTitle} / P${item.page} ${item.part}`; } return item.videoTitle; } function itemIndexText( item, visibleIndex ) { if ( state.hasCollection ) { if ( item.pages > 1 ) { return `${pad( item.collectionIndex, 2 )}-${pad( item.page, 2 )}`; } return pad( item.collectionIndex, 2 ); } if ( item.pages > 1 ) { return `P${pad( item.page, 2 )}`; } return pad( visibleIndex + 1, 2 ); } function buildBaseName( item, qualityLabel, stream ) { const fps = frameRateName( stream ); const codec = codecName( stream ?.codecid ); const suffix = [ qualityLabel, fps, codec, ] .filter( Boolean ) .join( ' - ' ); if ( state.hasCollection && item.isSeason ) { const part = item.pages > 1 ? ` - P${pad( item.page )} ${item.part}` : ''; return sanitize( `[${pad( item.collectionIndex )}] ${item.videoTitle}${part} - ${suffix}` ); } const part = item.pages > 1 ? ` - P${pad( item.page )} ${item.part}` : ''; return sanitize( `${item.videoTitle}${part} - ${suffix}` ); } function buildPlainBaseName( item ) { if ( state.hasCollection && item.isSeason ) { const part = item.pages > 1 ? ` - P${pad( item.page )} ${item.part}` : ''; return sanitize( `[${pad( item.collectionIndex )}] ${item.videoTitle}${part}` ); } const part = item.pages > 1 ? ` - P${pad( item.page )} ${item.part}` : ''; return sanitize( `${item.videoTitle}${part}` ); } function audioCodecName( stream ) { const codec = String( stream ?.codecs || stream ?.codec || '' ).toLowerCase(); if ( codec.includes( 'flac' ) ) { return 'FLAC'; } if ( codec.includes( 'ec-3' ) || codec.includes( 'eac3' ) ) { return 'E-AC-3'; } if ( codec.includes( 'ac-3' ) || codec.includes( 'ac3' ) ) { return 'AC-3'; } if ( codec.includes( 'opus' ) ) { return 'Opus'; } if ( codec.includes( 'mp4a' ) || codec.includes( 'aac' ) ) { return 'AAC'; } return codec ? codec.toUpperCase() : '音频'; } function audioFileExtension( stream ) { const mime = String( stream ?.mimeType || stream ?.mime_type || '' ).toLowerCase(); if ( mime.includes( 'webm' ) ) { return 'webm'; } if ( mime.includes( 'ogg' ) ) { return 'ogg'; } return 'm4a'; } function buildAudioBaseName( item, stream ) { const codec = audioCodecName( stream ); const bandwidth = Number( stream ?.bandwidth || 0 ); const bitrate = bandwidth > 0 ? `${Math.round( bandwidth / 1000 )}kbps` : ''; const suffix = [ '音频', bitrate, codec, ] .filter( Boolean ) .join( ' - ' ); if ( state.hasCollection && item.isSeason ) { const part = item.pages > 1 ? ` - P${pad( item.page )} ${item.part}` : ''; return sanitize( `[${pad( item.collectionIndex )}] ${item.videoTitle}${part} - ${suffix}` ); } const part = item.pages > 1 ? ` - P${pad( item.page )} ${item.part}` : ''; return sanitize( `${item.videoTitle}${part} - ${suffix}` ); } async function probeFormats( item ) { if ( !item ) { state.formats = []; renderFormats(); return; } try { setStatus( '正在读取可用清晰度…' ); const data = await fetchPlayData( item, 127 ); state.formats = normalizeFormats( data ); renderFormats(); } catch (err) { console.warn( '[BiliDL] quality probe failed:', err ); state.formats = []; renderFormats(); } } function renderFormats() { const previous = Number( getDropdownValue( 'quality' ) || 0 ); const formats = QUALITY_FALLBACK; const preferred = formats.some( item => item.qn === previous ) ? previous : 80; setDropdownOptions( 'quality', formats.map( item => ({ value: item.qn, label: item.label, }) ), preferred ); } /* * ========================================================= * 列表 * ========================================================= */ function updateSelectAllState() { const checkbox = $( `#${PANEL_ID} .tm-select-all` ); if ( !checkbox ) { return; } const visibleItems = getVisibleItems(); if ( !visibleItems.length ) { checkbox.checked = false; checkbox.indeterminate = false; checkbox.disabled = true; return; } const selectedCount = visibleItems.filter( item => state.selectedKeys.has( item.key ) ).length; checkbox.checked = selectedCount === visibleItems.length; checkbox.indeterminate = selectedCount > 0 && selectedCount < visibleItems.length; checkbox.disabled = state.busy; } function updateSelectedCount() { const el = $( `#${PANEL_ID} .tm-selected-count` ); if ( el ) { el.textContent = `已选 ${state.selectedKeys.size}`; } updateSelectAllState(); } function toggleRangeSelection( startKey, endKey, select ) { const visibleItems = getVisibleItems(); const start = visibleItems.findIndex( item => item.key === startKey ); const end = visibleItems.findIndex( item => item.key === endKey ); if ( start < 0 || end < 0 ) { return; } const lo = Math.min( start, end ); const hi = Math.max( start, end ); for ( let i = lo; i <= hi; i += 1 ) { const key = visibleItems[i].key; if ( select ) { state.selectedKeys.add( key ); } else { state.selectedKeys.delete( key ); } } } function renderItems() { const list = $( `#${PANEL_ID} .tm-items` ); const hint = $( `#${PANEL_ID} .tm-items-hint` ); if ( !list ) { return; } const items = getVisibleItems(); const currentItem = getCurrentItem(); const currentKey = currentItem ?.key || ''; list.innerHTML = ''; if ( !items.length ) { list.innerHTML = '
没有匹配的视频
'; if ( hint ) { hint.textContent = '0 项'; } updateSelectedCount(); return; } items.forEach( ( item, index ) => { const row = document.createElement( 'div' ); row.className = 'tm-item'; if ( item.key === currentKey ) { row.dataset.current = '1'; } row.innerHTML = ` ${escapeHtml( itemIndexText( item, index ) )} ${escapeHtml( itemLabel( item ) )} `; list.appendChild( row ); } ); if ( hint ) { hint.textContent = state.search ? `${items.length}/${state.items.length} 项` : `${state.items.length} 项`; } updateSelectedCount(); scrollCurrentItemToTop(); } function findItem( key ) { return ( state.items.find( item => item.key === key ) || null ); } /* * ========================================================= * 直链优先 * ========================================================= */ async function tryDirectMuxedDownload( item, index, total, requestedQn, codecPref, qualityLabel ) { /* * durl 无法精确控制 HEVC / AV1。 * 用户明确选这两种编码时直接走 DASH。 */ if ( codecPref === 'hevc' || codecPref === 'av1' ) { return false; } let data; try { data = await fetchDirectPlayData( item, requestedQn ); } catch { return false; } /* * 直链(durl)端点经常返回低于实际可用的清晰度 * (例如 DASH 能给 1080P,durl 却只返回 720P)。 * 只有返回画质与目标档位完全一致时才接受直链, * 否则交给 DASH 流程,避免偷偷降档。 * 批量下载的自动适配已由 resolveTargetQn 在调用前完成。 */ const actualQn = Number( data ?.quality || 0 ); if ( !actualQn || actualQn !== Number( requestedQn ) ) { return false; } const durl = Array.isArray( data ?.durl ) ? data.durl : []; /* * 多段 durl 最后仍然需要合并, * 这种情况继续交给 DASH。 */ if ( durl.length !== 1 ) { return false; } const directCodecId = Number( data ?.video_codecid || 0 ); if ( codecPref === 'avc' && directCodecId && directCodecId !== 7 ) { return false; } const entry = durl[0]; const extension = directFileExtension( data, entry ); const directQualityLabel = QUALITY_FALLBACK.find( q => q.qn === actualQn )?.label || qualityLabel; const pseudoStream = { codecid: directCodecId || 7, }; const outputName = buildBaseName( item, directQualityLabel, pseudoStream ); setStatus( `[${index}/${total}] 直链下载 ${directQualityLabel} · 无需合流` ); await downloadDirectEntry( entry, `${outputName}.${extension}`, ( loaded, totalBytes ) => { const taskProgress = totalBytes > 0 ? loaded / totalBytes : 0; const global = ( ( index - 1 ) + Math.min( taskProgress, 0.995 ) ) / total * 100; setProgress( global, `[${index}/${total}] ${formatBytes( loaded )}${totalBytes > 0 ? ` / ${formatBytes( totalBytes )}` : '' }` ); } ); setProgress( index / total * 100, `[${index}/${total}] 完成` ); return true; } /* * ========================================================= * 视频 * ========================================================= */ async function downloadOne( item, index, total, options = {} ) { const requestedQn = Number( options .requestedQn ?? getSelectedQn() ); const codecPref = options .codecPref || getSelectedCodec(); const qualityLabel = options .qualityLabel || getDropdownRoot( 'quality' ) ?.querySelector( '.tm-select-label' ) ?.textContent ?.trim() || String( requestedQn ); if ( !requestedQn ) { throw new Error( '请选择清晰度' ); } setStatus( `[${index}/${total}] 正在解析:${itemLabel( item )}` ); setProgress( ( index - 1 ) / total * 100, `[${index}/${total}] 解析` ); const probeData = options.playData || await fetchPlayData( item, 127 ); const targetQn = resolveTargetQn( probeData, requestedQn ); if ( !targetQn ) { throw new Error( '当前视频没有可用的清晰度。' ); } const actualQualityLabel = QUALITY_FALLBACK.find( q => q.qn === targetQn )?.label || qualityLabel; /* * 所有画质都先试一次完整直链。 * * 能得到单文件且画质不高于目标档位, * 就不加载 FFmpeg。 */ const directDone = await tryDirectMuxedDownload( item, index, total, targetQn, codecPref, actualQualityLabel ); if ( directDone ) { if ( options.saveTarget ) { logInfo( 'app', '直链通道已保存,预选的保存位置未使用' ); } return; } const data = probeData; if ( !data ?.dash ) { throw new Error( '当前视频没有可用的 DASH 视频流。' ); } const video = pickExactVideo( data, requestedQn, codecPref ); const audio = pickAudio( data ); const fps = frameRateName( video ); const codec = codecName( video .codecid ); const outputName = buildBaseName( item, actualQualityLabel, video ); setStatus( `[${index}/${total}] DASH 下载 ${actualQualityLabel}${fps ? ` · ${fps}` : '' } · ${codec}` ); let videoLoaded = 0; let audioLoaded = 0; let videoTotal = 0; let audioTotal = 0; const updateProgress = () => { const loaded = videoLoaded + audioLoaded; const all = videoTotal + audioTotal; const taskProgress = all > 0 ? loaded / all : 0; const global = ( ( index - 1 ) + Math.min( taskProgress, 0.94 ) ) / total * 100; setProgress( global, `[${index}/${total}] ${formatBytes( loaded )}${all > 0 ? ` / ${formatBytes( all )}` : '' }` ); }; const videoPromise = requestStreamBuffer( video, ( loaded, totalBytes ) => { videoLoaded = loaded; videoTotal = totalBytes || videoTotal; updateProgress(); } ); const audioPromise = audio ? requestStreamBuffer( audio, ( loaded, totalBytes ) => { audioLoaded = loaded; audioTotal = totalBytes || audioTotal; updateProgress(); } ) : Promise.resolve( null ); const [ videoBuf, audioBuf, ] = await Promise.all( [ videoPromise, audioPromise, ] ); setStatus( `[${index}/${total}] 下载完成,正在无损合流…` ); await muxAndSave( videoBuf, audioBuf, outputName, options.saveTarget || null ); setProgress( index / total * 100, `[${index}/${total}] 完成` ); } /* * ========================================================= * 音频 * ========================================================= */ async function downloadAudioOne( item, index, total ) { setStatus( `[${index}/${total}] 正在解析音频:${itemLabel( item )}` ); setProgress( ( index - 1 ) / total * 100, `[${index}/${total}] 解析音频` ); const data = await fetchPlayData( item, 80 ); if ( !data ?.dash ) { throw new Error( '当前视频没有DASH音频流。' ); } const audio = pickAudio( data ); if ( !audio ) { throw new Error( '当前视频没有可下载的音频流。' ); } const codec = audioCodecName( audio ); const bandwidth = Number( audio .bandwidth || 0 ); const bitrate = bandwidth > 0 ? `${Math.round( bandwidth / 1000 )}kbps` : ''; setStatus( `[${index}/${total}] 下载音频${bitrate ? ` · ${bitrate}` : '' } · ${codec}` ); const audioBuf = await requestStreamBuffer( audio, ( loaded, totalBytes ) => { const progress = totalBytes > 0 ? loaded / totalBytes : 0; const global = ( ( index - 1 ) + Math.min( progress, 0.99 ) ) / total * 100; setProgress( global, `[${index}/${total}] ${formatBytes( loaded )}${totalBytes > 0 ? ` / ${formatBytes( totalBytes )}` : '' }` ); } ); const extension = audioFileExtension( audio ); const mime = audio .mimeType || audio .mime_type || ( extension === 'webm' ? 'audio/webm' : 'audio/mp4' ); const outputName = buildAudioBaseName( item, audio ); saveBlob( new Blob( [ audioBuf, ], { type: mime, } ), `${outputName}.${extension}` ); setProgress( index / total * 100, `[${index}/${total}] 音频完成` ); } /* * ========================================================= * 弹幕 XML / ASS * ========================================================= */ async function fetchDanmakuXml( item ) { if ( !item ?.cid ) { throw new Error( '当前条目没有 CID,无法读取弹幕。' ); } const xml = await requestTextUrl( `https://comment.bilibili.com/${encodeURIComponent( String( item.cid ) )}.xml` ); if ( !xml ) { throw new Error( '没有读取到弹幕 XML。' ); } return xml; } function assTime( seconds ) { const value = Math.max( 0, Number( seconds ) || 0 ); const h = Math.floor( value / 3600 ); const m = Math.floor( ( value % 3600 ) / 60 ); const s = Math.floor( value % 60 ); const cs = Math.floor( ( value - Math.floor( value ) ) * 100 ); return `${h}:${pad( m )}:${pad( s )}.${pad( cs )}`; } function assColor( decimalColor ) { const value = Math.max( 0, Math.min( 0xffffff, Number( decimalColor ) || 0xffffff ) ); const r = ( value >> 16 ) & 0xff; const g = ( value >> 8 ) & 0xff; const b = value & 0xff; return `&H00${b .toString(16) .padStart( 2, '0' )}${g .toString(16) .padStart( 2, '0' )}${r .toString(16) .padStart( 2, '0' )}&`; } function assEscapeText( text ) { return String( text || '' ) .replace( /\\/g, '\\\\' ) .replace( /\{/g, '\\{' ) .replace( /\}/g, '\\}' ) .replace( /\r?\n/g, '\\N' ); } function estimateDanmakuWidth( text, fontSize ) { let units = 0; for ( const char of String( text || '' ) ) { units += /[\u0000-\u00ff]/.test( char ) ? 0.56 : 1; } return Math.max( fontSize * 2, units * fontSize * 0.98 ); } function convertDanmakuXmlToAss( xml, title ) { const doc = new DOMParser() .parseFromString( xml, 'application/xml' ); if ( doc.querySelector( 'parsererror' ) ) { throw new Error( '弹幕 XML 解析失败。' ); } const entries = [ ...doc.querySelectorAll( 'd[p]' ), ] .map( node => { const p = String( node.getAttribute( 'p' ) || '' ).split( ',' ); return { time: Number( p[0] ) || 0, mode: Number( p[1] ) || 1, size: Number( p[2] ) || 25, color: Number( p[3] ) || 0xffffff, text: node.textContent || '', }; } ) .filter( item => item.text && item.mode !== 8 ) .sort( ( a, b ) => a.time - b.time ); const width = 1920; const height = 1080; const scrollDuration = 8; const fixedDuration = 4; const laneHeight = 54; const scrollFree = Array( 17 ).fill( 0 ); const topFree = Array( 7 ).fill( 0 ); const bottomFree = Array( 7 ).fill( 0 ); const pickLane = ( lanes, start ) => { const free = lanes.findIndex( time => time <= start ); if ( free >= 0 ) { return free; } let best = 0; for ( let i = 1; i < lanes.length; i += 1 ) { if ( lanes[i] < lanes[best] ) { best = i; } } return best; }; const events = []; for ( const entry of entries ) { const start = entry.time; let end = start + scrollDuration; const fontSize = Math.max( 24, Math.min( 64, Math.round( entry.size * 1.75 ) ) ); let tag = ''; if ( entry.mode === 4 ) { const lane = pickLane( bottomFree, start ); bottomFree[ lane ] = start + fixedDuration; end = start + fixedDuration; tag = `\\an2\\pos(${width / 2},${height - 48 - lane * laneHeight})`; } else if ( entry.mode === 5 ) { const lane = pickLane( topFree, start ); topFree[ lane ] = start + fixedDuration; end = start + fixedDuration; tag = `\\an8\\pos(${width / 2},${48 + lane * laneHeight})`; } else if ( entry.mode === 7 ) { end = start + fixedDuration; tag = `\\an5\\pos(${width / 2},${height / 2})`; } else { const lane = pickLane( scrollFree, start ); scrollFree[ lane ] = start + scrollDuration * 0.82; const y = 48 + lane * laneHeight; const textWidth = Math.ceil( estimateDanmakuWidth( entry.text, fontSize ) ); if ( entry.mode === 6 ) { tag = `\\move(${-textWidth - 30},${y},${width + 30},${y})`; } else { tag = `\\move(${width + 30},${y},${-textWidth - 30},${y})`; } } events.push( `Dialogue: 0,${assTime( start )},${assTime( end )},Danmaku,,0,0,0,,{${tag}\\fs${fontSize}\\c${assColor( entry.color )}}${assEscapeText( entry.text )}` ); } return [ '[Script Info]', `Title: ${String( title || 'Bilibili Danmaku' ).replace( /[\r\n]+/g, ' ' )}`, 'ScriptType: v4.00+', 'WrapStyle: 2', 'ScaledBorderAndShadow: yes', `PlayResX: ${width}`, `PlayResY: ${height}`, '', '[V4+ Styles]', 'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding', 'Style: Danmaku,Microsoft YaHei,48,&H00FFFFFF,&H00FFFFFF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,2,0,7,20,20,20,1', '', '[Events]', 'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text', ...events, '', ].join( '\n' ); } async function downloadSubtitleOne( item, index, total, format ) { setStatus( `[${index}/${total}] 正在读取 ${format.toUpperCase()} 弹幕:${itemLabel( item )}` ); setProgress( ( index - 1 ) / total * 100, `[${index}/${total}] 弹幕` ); const xml = await fetchDanmakuXml( item ); const baseName = buildPlainBaseName( item ); if ( format === 'ass' ) { const ass = convertDanmakuXmlToAss( xml, itemLabel( item ) ); saveBlob( new Blob( [ '\ufeff', ass, ], { type: 'text/x-ssa;charset=utf-8', } ), `${baseName}.ass` ); } else { saveBlob( new Blob( [ xml, ], { type: 'application/xml;charset=utf-8', } ), `${baseName}.xml` ); } setProgress( index / total * 100, `[${index}/${total}] 弹幕完成` ); } /* * ========================================================= * Logo 极速下载 * ========================================================= */ function quickQualityLabel( qn, data ) { return ( normalizeFormats( data ).find( item => item.qn === Number( qn ) )?.label || QUALITY_FALLBACK.find( item => item.qn === Number( qn ) )?.label || `画质 ${qn}` ); } function pickQuickQn( data ) { /* * 上限为 1080P60。 */ const maxQn = 116; const available = [ ...new Set( ( data ?.dash ?.video || [] ) .map( stream => Number( stream ?.id || 0 ) ) .filter( qn => qn > 0 && qn <= maxQn ) ), ].sort( ( a, b ) => b - a ); if ( available.length ) { return available[0]; } const actual = Number( data ?.quality || 0 ); if ( actual > 0 && actual <= maxQn ) { return actual; } throw new Error( '没有找到不高于 1080P60 的可下载视频流。' ); } let quickToastTimer = null; function showQuickToast( text, type = '', duration = 0 ) { const panel = document.getElementById( PANEL_ID ); if ( !panel ) { return; } let toast = document.getElementById( `${PANEL_ID}-quick-toast` ); if ( !toast ) { toast = document.createElement( 'div' ); toast.id = `${PANEL_ID}-quick-toast`; document.body.appendChild( toast ); } const rect = panel.getBoundingClientRect(); toast.style.left = `${Math.max( 8, Math.min( rect.left, window.innerWidth - 338 ) )}px`; toast.style.top = `${Math.min( window.innerHeight - 60, rect.bottom + 8 )}px`; toast.textContent = text; toast.dataset.type = type; toast.classList.add( 'show' ); if ( quickToastTimer ) { clearTimeout( quickToastTimer ); quickToastTimer = null; } if ( duration > 0 ) { quickToastTimer = setTimeout( () => { toast.classList.remove( 'show' ); }, duration ); } } async function startQuickCurrent() { if ( state.busy ) { showQuickToast( '已有下载任务正在进行,请勿重复点击。', 'warn', 2200 ); return; } const item = getCurrentItem() || state.items[0]; if ( !item ) { showQuickToast( '视频仍在解析,请稍后再点 Logo。', 'error', 2500 ); return; } setBusy( true ); const panel = document.getElementById( PANEL_ID ); panel ?.classList .add( 'quick-busy' ); showQuickToast( '已开始解析下载,请勿重复点击…', 'loading' ); try { const data = await fetchPlayData( item, 116 ); if ( !data ?.dash ) { throw new Error( '当前视频没有 DASH 视频流。' ); } const requestedQn = pickQuickQn( data ); const qualityLabel = quickQualityLabel( requestedQn, data ); showQuickToast( `正在下载 ${qualityLabel},请勿重复点击。`, 'loading' ); await downloadOne( item, 1, 1, { requestedQn, codecPref: 'auto', qualityLabel, playData: data, } ); setStatus( `下载完成:${qualityLabel} · ${itemLabel( item )}`, 'ok' ); setProgress( 100, '完成' ); showQuickToast( `${qualityLabel} 下载完成。`, 'ok', 2800 ); } catch (err) { console.error( '[BiliDL] quick download failed:', err ); logError( 'app', `极速下载失败:${err?.message || err}` ); setStatus( `极速下载失败:${err ?.message || err }`, 'error' ); showQuickToast( `下载失败:${err ?.message || err }`, 'error', 3500 ); } finally { panel ?.classList .remove( 'quick-busy' ); setBusy( false ); } } /* * ========================================================= * 下载入口 * ========================================================= */ /* * 大文件(估算超过 data 通道阈值)必须在点击下载的手势内 * 预弹系统保存对话框拿到 FileSystemHandle, * 合流完成后再弹会因用户激活过期被浏览器拒绝。 */ // DASH 各档位合并码率粗估(Mbps,含音轨),仅用于大小分流判断 const QN_BITRATE_MBPS = { 127: 52, 126: 48, 125: 42, 120: 32, 116: 9, 112: 7, 80: 5, 74: 4, 64: 3, 32: 1.5, 16: 0.8, }; function estimateDashBytes( item, requestedQn ) { const duration = Number( item?.duration || 0 ); if ( !duration ) { return 0; } const mbps = QN_BITRATE_MBPS[ Number( requestedQn ) ] || 5; return Math.round( (mbps * 1000000 / 8) * duration * 1.15 ); } function supportsFsPicker() { return ( typeof window .showSaveFilePicker === 'function' && typeof window .showDirectoryPicker === 'function' ); } async function pickLargeSaveFile( suggestedName ) { if ( !supportsFsPicker() ) { logWarn( 'app', '当前浏览器不支持文件系统访问 API,大文件将退回页面下载通道' ); return null; } const types = [ { description: 'MP4 视频', accept: { 'video/mp4': [ '.mp4', ], }, }, ]; try { let handle = null; try { handle = await window.showSaveFilePicker( { suggestedName, types, } ); } catch (e) { if ( e?.name === 'AbortError' ) { throw e; } // 建议文件名不合法等情形,去掉建议名重试 handle = await window.showSaveFilePicker( { types, } ); } logInfo( 'app', '已为本次下载选定保存位置(file-picker)' ); return { fileHandle: handle, }; } catch (e) { if ( e?.name === 'AbortError' ) { throw new Error( '已取消保存位置选择' ); } logWarn( 'app', `另存为对话框不可用:${ e && e.message }` ); return null; } } async function pickLargeSaveDir() { if ( !supportsFsPicker() ) { logWarn( 'app', '当前浏览器不支持文件系统访问 API,大文件将退回页面下载通道' ); return null; } try { const handle = await window.showDirectoryPicker( { mode: 'readwrite', } ); logInfo( 'app', '已为本次批量下载选定保存文件夹(file-picker)' ); return { dirHandle: handle, }; } catch (e) { if ( e?.name === 'AbortError' ) { throw new Error( '已取消保存位置选择' ); } logWarn( 'app', `文件夹选择对话框不可用:${ e && e.message }` ); return null; } } async function uniqueSaveFileHandle( dirHandle, name ) { const dot = name.lastIndexOf( '.' ); const base = dot > 0 ? name.slice( 0, dot ) : name; const ext = dot > 0 ? name.slice( dot ) : ''; let candidate = name; for ( let i = 0; i < 100; i += 1 ) { const exists = await dirHandle .getFileHandle( candidate ) .then( () => true, () => false ); if ( !exists ) { return dirHandle.getFileHandle( candidate, { create: true, } ); } candidate = `${base}(${i + 1})${ext}`; } return dirHandle.getFileHandle( name, { create: true, } ); } async function startSingle( item ) { if ( state.busy || !item ) { return; } /* * 大文件必须在点击手势内预弹“另存为”, * 拿到保存位置后再进入下载流程。 */ let saveTarget = null; const estBytes = estimateDashBytes( item, getSelectedQn() ); logInfo( 'app', `保存方式预判:估算 ${formatBytes( estBytes )}(时长 ${ Number(item?.duration) || 0 }s · qn${getSelectedQn()})` ); if ( estBytes > SAVE_DATA_URL_LIMIT ) { saveTarget = await pickLargeSaveFile( `${itemLabel( item )}.mp4` ); } setBusy( true ); try { await downloadOne( item, 1, 1, { saveTarget, } ); setStatus( `下载完成:${itemLabel( item )}`, 'ok' ); setProgress( 100, '完成' ); } catch (err) { console.error( '[BiliDL] single download failed:', err ); logError( 'app', `单个下载失败:${err?.message || err}` ); setStatus( `失败:${err ?.message || err }`, 'error' ); } finally { setBusy( false ); } } async function startSelected() { if ( state.busy ) { return; } const items = selectedItems(); if ( !items.length ) { throw new Error( '请先勾选要批量下载的视频。' ); } /* * 大文件必须在点击手势内预弹一次“选择文件夹”, * 批量内所有大文件都写入该文件夹。 */ let saveTarget = null; const estimates = items.map( it => estimateDashBytes( it, getSelectedQn() ) ); const largeCount = estimates.filter( v => v > SAVE_DATA_URL_LIMIT ).length; logInfo( 'app', `批量保存方式预判:最大估算 ${formatBytes( Math.max( ...estimates, 0 ) )},大文件 ${largeCount}/${items.length}` ); if ( largeCount > 0 ) { saveTarget = await pickLargeSaveDir(); } setBusy( true ); let completed = 0; try { for ( let i = 0; i < items.length; i += 1 ) { await downloadOne( items[i], i + 1, items.length, { saveTarget, } ); completed += 1; if ( i < items.length - 1 ) { await sleep( 250 ); } } setStatus( `全部完成:${completed}/${items.length}`, 'ok' ); setProgress( 100, `完成 ${completed}/${items.length}` ); } catch (err) { console.error( '[BiliDL]', err ); logError( 'app', `批量下载失败:${err?.message || err}` ); setStatus( `失败:${err ?.message || err }`, 'error' ); } finally { setBusy( false ); } } async function startSelectedAudio() { if ( state.busy ) { return; } const items = selectedItems(); if ( !items.length ) { throw new Error( '请先勾选要下载音频的视频。' ); } setBusy( true ); let completed = 0; try { for ( let i = 0; i < items.length; i += 1 ) { await downloadAudioOne( items[i], i + 1, items.length ); completed += 1; if ( i < items.length - 1 ) { await sleep( 250 ); } } setStatus( `音频全部完成:${completed}/${items.length}`, 'ok' ); setProgress( 100, `音频完成 ${completed}/${items.length}` ); } catch (err) { console.error( '[BiliDL] audio download failed:', err ); logError( 'app', `音频下载失败:${err?.message || err}` ); setStatus( `音频下载失败:${err ?.message || err }`, 'error' ); } finally { setBusy( false ); } } async function startSelectedSubtitles() { if ( state.busy ) { return; } const items = selectedItems(); if ( !items.length ) { throw new Error( '请先勾选要下载弹幕字幕的视频。' ); } const format = getSelectedSubtitleFormat(); setBusy( true ); let completed = 0; try { for ( let i = 0; i < items.length; i += 1 ) { await downloadSubtitleOne( items[i], i + 1, items.length, format ); completed += 1; if ( i < items.length - 1 ) { await sleep( 120 ); } } setStatus( `${format.toUpperCase()} 弹幕全部完成:${completed}/${items.length}`, 'ok' ); setProgress( 100, `弹幕 ${completed}/${items.length}` ); } catch (err) { console.error( '[BiliDL] subtitle download failed:', err ); logError( 'app', `弹幕字幕下载失败:${err?.message || err}` ); setStatus( `弹幕下载失败:${err ?.message || err }`, 'error' ); } finally { setBusy( false ); } } /* * ========================================================= * 拖拽 / 最小化 * ========================================================= */ function pinPanelToCurrentScreenPosition( panel ) { const rect = panel.getBoundingClientRect(); panel.style.left = `${rect.left}px`; panel.style.top = `${rect.top}px`; panel.style.right = 'auto'; } function bindDragAndMin(panel) { const header = $(`#${PANEL_ID} .tm-head`); const minBtn = $(`#${PANEL_ID} .tm-min-btn`); const logBtn = $(`#${PANEL_ID} .tm-log-btn`); let dragging = false; let dragMoved = false; let startX = 0; let startY = 0; let startLeft = 0; let startTop = 0; logBtn.addEventListener('click', event => { event.stopPropagation(); toggleLogOverlay(); }); minBtn.addEventListener('click', event => { event.stopPropagation(); pinPanelToCurrentScreenPosition(panel); const minimized = panel.classList.toggle('minimized'); minBtn.textContent = minimized ? '+' : '−'; minBtn.title = minimized ? '展开' : '最小化'; closeDropdowns(); if (!minimized) { requestAnimationFrame(() => { requestAnimationFrame(() => { scrollCurrentItemToTop(); }); }); } }); header.addEventListener('mousedown', event => { if (event.button !== 0 || event.target.closest('button')) { return; } const rect = panel.getBoundingClientRect(); panel.style.left = `${rect.left}px`; panel.style.top = `${rect.top}px`; panel.style.right = 'auto'; dragging = true; dragMoved = false; startX = event.clientX; startY = event.clientY; startLeft = rect.left; startTop = rect.top; header.classList.add('dragging'); event.preventDefault(); }); document.addEventListener('mousemove', event => { if (!dragging) { return; } if (Math.abs(event.clientX - startX) > 3 || Math.abs(event.clientY - startY) > 3) { dragMoved = true; } const maxLeft = Math.max(0, window.innerWidth - panel.offsetWidth); const maxTop = Math.max(0, window.innerHeight - panel.offsetHeight); const left = Math.max(0, Math.min(maxLeft, startLeft + event.clientX - startX)); const top = Math.max(0, Math.min(maxTop, startTop + event.clientY - startY)); panel.style.left = `${left}px`; panel.style.top = `${top}px`; }); document.addEventListener('mouseup', () => { if (!dragging) { return; } dragging = false; header.classList.remove('dragging'); if (dragMoved) { panel.dataset.justDragged = '1'; setTimeout(() => { delete panel.dataset.justDragged; }, 0); } }); } /* * ========================================================= * Panel * ========================================================= */ function createPanel() { if (!YC9_IS_BILI_TARGET) { return null; } let panel = document.getElementById( PANEL_ID ); if ( panel ) { return panel; } panel = document.createElement( 'section' ); panel.id = PANEL_ID; /* * 默认最小化。 */ panel.classList.add( 'minimized' ); panel.innerHTML = `
育才9班自用破解
0 项
UP主全部视频
已选 0 点标题可直接下载
正在解析视频…
等待
`; document.body.appendChild( panel ); bindDragAndMin( panel ); initStaticDropdowns(); mountOfficialLogo(); startLogoWatcher(); panel.addEventListener( 'input', event => { if ( !event.target.matches( '.tm-search' ) ) { return; } state.search = event.target.value || ''; renderItems(); } ); panel.addEventListener( 'change', event => { if ( event.target.matches( '.tm-select-all' ) ) { const visibleItems = getVisibleItems(); if ( event.target.checked ) { for ( const item of visibleItems ) { state.selectedKeys.add( item.key ); } } else { for ( const item of visibleItems ) { state.selectedKeys.delete( item.key ); } } renderItems(); return; } if ( event.target.matches( '.tm-item-check' ) ) { const key = event.target .dataset .key; if ( !key ) { return; } if ( event.target.checked ) { state.selectedKeys.add( key ); } else { state.selectedKeys.delete( key ); } updateSelectedCount(); } } ); panel.addEventListener( 'click', async event => { /* * Shift + 点击选框: * 与上一次点击的选框之间连续选中/取消选中。 */ const itemCheck = event.target.closest( '.tm-item-check' ); if ( itemCheck ) { const key = itemCheck.dataset.key; if ( !key ) { return; } if ( event.shiftKey && state.lastCheckedKey && state.lastCheckedKey !== key ) { event.preventDefault(); const wasSelected = state.selectedKeys.has( key ); toggleRangeSelection( state.lastCheckedKey, key, !wasSelected ); state.lastCheckedKey = key; renderItems(); return; } state.lastCheckedKey = key; /* * 普通点击仍走 change 事件处理。 */ } /* * 自定义下拉框。 */ const option = event.target.closest( '.tm-select-option' ); if ( option ) { const root = option.closest( '.tm-dropdown' ); setDropdownValue( root, option .dataset .value, option .querySelector( '.tm-option-text' ) ?.textContent ?.trim() ); root.classList.remove( 'open' ); return; } const trigger = event.target.closest( '.tm-select-trigger' ); if ( trigger ) { const root = trigger.closest( '.tm-dropdown' ); const opening = !root.classList.contains( 'open' ); closeDropdowns( root ); root.classList.toggle( 'open', opening ); return; } /* * Logo: * 单击下载; * 拖动以后不触发。 */ const logo = event.target.closest( '.tm-logo-host' ); if ( logo ) { if ( panel.dataset.justDragged === '1' ) { return; } await startQuickCurrent(); return; } /* * 标题下载逻辑保持不变。 */ const title = event.target.closest( '.tm-item-title' ); if ( title ) { await startSingle( findItem( title .dataset .key ) ); return; } const button = event.target.closest( 'button[data-action]' ); if ( !button ) { return; } try { if ( button .dataset .action === 'toggle-search' ) { const wrap = button.closest( '.tm-search-wrap' ); const input = wrap ?.querySelector( '.tm-search' ); if ( !wrap || !input ) { return; } const opened = wrap.classList.toggle( 'open' ); button.classList.toggle( 'active', opened ); if ( opened ) { requestAnimationFrame( () => { input.focus(); input.select(); } ); } else { input.blur(); if ( input.value || state.search ) { input.value = ''; state.search = ''; renderItems(); } } return; } if ( button .dataset .action === 'download' ) { await startSelected(); return; } if ( button .dataset .action === 'download-audio' ) { await startSelectedAudio(); return; } if ( button .dataset .action === 'download-subtitle' ) { await startSelectedSubtitles(); return; } if ( button .dataset .action === 'load-list' ) { const limitInput = $( `#${PANEL_ID} .tm-list-limit` ); const startInput = $( `#${PANEL_ID} .tm-list-date-start` ); const endInput = $( `#${PANEL_ID} .tm-list-date-end` ); await loadListItems({ maxCount: limitInput ?.value || 0, dateStart: startInput ?.value || '', dateEnd: endInput ?.value || '', fetchMore: true, }); setStatus( `列表已刷新 · ${state.listLoadedCount} 个视频`, 'ok' ); return; } } catch (err) { console.error( '[BiliDL]', err ); setStatus( `失败:${err ?.message || err }`, 'error' ); } } ); panel.addEventListener( 'contextmenu', event => { const title = event.target.closest( '.tm-item-title' ); if ( !title ) { return; } const item = findItem( title.dataset.key ); if ( !item ) { return; } event.preventDefault(); const url = `https://www.bilibili.com/video/${item.bvid}${item.page > 1 ? `?p=${item.page}` : ''}`; window.open( url, '_blank' ); } ); document.addEventListener( 'click', event => { if ( !event.target.closest( `#${PANEL_ID} .tm-dropdown` ) ) { closeDropdowns(); } } ); document.addEventListener( 'keydown', event => { if ( event.key === 'Escape' ) { closeDropdowns(); } } ); return panel; } /* * ========================================================= * 初始化 * ========================================================= */ async function initPage( force = false ) { if (!YC9_IS_BILI_TARGET) { return; } if ( state.busy && !force ) { return; } const seq = ++state.initSeq; state.listMode = isListPage(); logInfo( 'app', `脚本初始化:v${ typeof GM_info !== 'undefined' ? GM_info?.script ?.version || '未知' : '未知' },页面 ${location.pathname}` ); createPanel(); mountOfficialLogo(); setStatus( '正在加载视频列表…' ); setProgress( 0, '加载中' ); const result = isListPage() ? await initListPage() : await parseResourcesFast(); if ( seq !== state.initSeq ) { return; } updateListBatchUI(); /* * 不在初始化时自动调用 probeFormats, * 避免每次打开/切换页面都请求 playurl API 产生解析记录, * 实际下载时由下载流程自行调用 fetchPlayData。 */ state.formats = []; renderFormats(); const videoCount = new Set( state.items.map( item => item.bvid ) ).size; const description = state.listMode ? `${state.listLoadedCount} / ${state.listTotal} 个视频` : state.hasCollection ? `${videoCount} 个视频 · ${state.items.length} 个条目` : state.items.length > 1 ? `${state.items.length} 个分P` : '单视频'; setStatus( `列表加载完成 · ${description} · 待解析`, 'ok' ); setProgress( 0, '待解析' ); renderItems(); return result; } /* * ========================================================= * SPA * ========================================================= */ async function refreshForUrlChange() { /* * 如果此时正在下载, * 等当前任务结束后再解析新页面。 */ while ( state.busy ) { await sleep( 300 ); } await initPage(); } function installSpaWatcher() { if (!YC9_IS_BILI_TARGET) { return; } const fire = () => window.dispatchEvent( new Event( 'tm-bili-urlchange' ) ); for ( const name of [ 'pushState', 'replaceState', ] ) { const original = history[name]; history[name] = function ( ...args ) { const result = original.apply( this, args ); fire(); return result; }; } window.addEventListener( 'popstate', fire ); window.addEventListener( 'tm-bili-urlchange', () => { setTimeout( () => { if ( location.href === state.href ) { return; } state.href = location.href; refreshForUrlChange() .catch( err => { setStatus( `自动刷新失败:${err ?.message || err }`, 'error' ); } ); }, 300 ); } ); setInterval( () => { if ( location.href === state.href ) { return; } state.href = location.href; refreshForUrlChange() .catch( err => { setStatus( `自动刷新失败:${err ?.message || err }`, 'error' ); } ); }, 1000 ); } /* * ========================================================= * CSS * ========================================================= */ GM_addStyle(` #${PANEL_ID} { --bili-blue: ${BILI_BLUE}; --bili-blue-soft: rgba( 0, 174, 236, .09 ); --bili-blue-selected: rgba( 0, 174, 236, .13 ); --text: #18191c; --muted: #9499a0; --border: #e3e5e7; /* * 所有可见控件统一圆角。 */ --radius: 12px; position: fixed; left: calc( 50% + 10px ); right: auto; top: 72px; width: 430px; max-height: calc( 100vh - 92px ); z-index: 2147483646; box-sizing: border-box; /* * 自定义下拉菜单需要溢出窗口。 */ overflow: visible; color: var( --text ); background: rgba( 255, 255, 255, .985 ); border: 1px solid rgba( 0, 0, 0, .07 ); border-radius: var( --radius ); box-shadow: 0 12px 36px rgba( 0, 0, 0, .14 ); backdrop-filter: blur( 18px ); -webkit-backdrop-filter: blur( 18px ); font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; transition: width .18s ease, box-shadow .18s ease; } #${PANEL_ID} * { box-sizing: border-box; } #${PANEL_ID} button, #${PANEL_ID} input { font: inherit; } /* * ===================================================== * Header * ===================================================== */ #${PANEL_ID} .tm-head { height: 76px; padding: 0 13px 0 17px; display: flex; align-items: center; justify-content: space-between; gap: 16px; cursor: grab; user-select: none; background: rgba( 255, 255, 255, .985 ); border-radius: var( --radius ) var( --radius ) 0 0; border-bottom: 1px solid #f0f1f2; } #${PANEL_ID} .tm-head.dragging { cursor: grabbing; } #${PANEL_ID} .tm-brand { position: relative; width: 230px; height: 76px; flex: 0 0 230px; } #${PANEL_ID} .tm-brand-line { position: absolute; left: 0; top: 50%; width: 100%; height: 30px; transform: translateY( -50% ); display: flex; align-items: center; gap: 11px; } /* * Logo: * 不再有任何 hover / focus 蓝色高亮。 */ #${PANEL_ID} .tm-logo-host { width: 78px; height: 30px; flex: 0 0 78px; display: flex; align-items: center; justify-content: flex-start; overflow: hidden; color: var( --bili-blue ); cursor: pointer; background: transparent !important; border: none; border-radius: 0; outline: none !important; box-shadow: none !important; transition: opacity .15s ease; } #${PANEL_ID} .tm-logo-host:hover, #${PANEL_ID} .tm-logo-host:focus, #${PANEL_ID} .tm-logo-host:focus-visible, #${PANEL_ID} .tm-logo-host:active { background: transparent !important; outline: none !important; box-shadow: none !important; } #${PANEL_ID} .tm-head.dragging .tm-logo-host { cursor: grabbing; } #${PANEL_ID} .quick-busy .tm-logo-host, #${PANEL_ID}.quick-busy .tm-logo-host { opacity: .48; cursor: wait; } #${PANEL_ID} .tm-logo-host.is-svg .tm-bili-official-svg { display: block !important; width: 78px !important; height: 30px !important; max-width: 78px !important; max-height: 30px !important; margin: 0 !important; padding: 0 !important; flex: none !important; color: var( --bili-blue ) !important; } #${PANEL_ID} .tm-logo-host.is-svg .tm-bili-official-svg path, #${PANEL_ID} .tm-logo-host.is-svg .tm-bili-official-svg use, #${PANEL_ID} .tm-logo-host.is-svg .tm-bili-official-svg polygon { fill: var( --bili-blue ) !important; color: var( --bili-blue ) !important; } #${PANEL_ID} .tm-bili-fallback-logo { display: block; width: 29px; height: 29px; object-fit: contain; } #${PANEL_ID} .tm-brand-divider { width: 1px; height: 19px; flex: 0 0 1px; margin: 0 1px; background: var( --border ); } #${PANEL_ID} .tm-brand-name { flex: 0 0 auto; color: var( --text ); font-size: 18px; line-height: 30px; font-weight: 700; letter-spacing: -.25px; white-space: nowrap; } #${PANEL_ID} .tm-head-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 4px; } #${PANEL_ID} .tm-icon-btn { width: 36px; height: 36px; flex: 0 0 36px; padding: 0; display: grid; place-items: center; border: 1px solid var( --border ); border-radius: var( --radius ); color: #61666d; background: #fff; outline: none; font-size: 20px; line-height: 1; cursor: pointer; transition: border-color .15s ease, color .15s ease, background .15s ease, transform .1s ease; } #${PANEL_ID} .tm-icon-btn:hover:not(:disabled) { color: var( --bili-blue ); border-color: rgba( 0, 174, 236, .44 ); background: var( --bili-blue-soft ); } #${PANEL_ID} .tm-icon-btn:active:not(:disabled) { transform: scale( .95 ); } /* * ===================================================== * 最小化 * ===================================================== */ #${PANEL_ID}.minimized { width: 150px; box-shadow: 0 9px 30px rgba( 0, 0, 0, .13 ); } #${PANEL_ID}.minimized .tm-body { display: none; } #${PANEL_ID}.minimized .tm-head { height: 70px; padding: 0 12px 0 14px; gap: 5px; border-radius: var( --radius ); border-bottom-color: transparent; } #${PANEL_ID}.minimized .tm-brand { width: 78px; height: 70px; flex: 0 0 78px; } #${PANEL_ID}.minimized .tm-brand-line { width: 78px; } #${PANEL_ID}.minimized .tm-brand-divider, #${PANEL_ID}.minimized .tm-brand-name { display: none; } #${PANEL_ID}.minimized .tm-icon-btn { width: 34px; height: 34px; flex-basis: 34px; } #${PANEL_ID}.minimized .tm-log-btn { display: none; } /* * ===================================================== * Body * ===================================================== */ #${PANEL_ID} .tm-body { padding: 12px 15px 14px; display: flex; flex-direction: column; gap: 9px; max-height: calc( 100vh - 178px ); background: rgba( 255, 255, 255, .985 ); border-radius: 0 0 var( --radius ) var( --radius ); } #${PANEL_ID} .tm-row { display: grid; grid-template-columns: 88px 1fr; align-items: center; gap: 9px; } #${PANEL_ID} .tm-row label { color: #61666d; font-size: 14px; } /* * ===================================================== * 自定义下拉 * ===================================================== */ #${PANEL_ID} .tm-dropdown { position: relative; min-width: 0; } #${PANEL_ID} .tm-select-trigger { width: 100%; height: 42px; padding: 0 13px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border: 1px solid var( --border ); border-radius: var( --radius ); color: var( --text ); background: #fff; outline: none; cursor: pointer; text-align: left; transition: border-color .15s ease, box-shadow .15s ease, background .15s ease; } #${PANEL_ID} .tm-select-trigger:hover:not(:disabled) { border-color: #c9ccd0; } #${PANEL_ID} .tm-select-label { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } /* * 箭头永远固定朝下。 * 打开和关闭均不旋转、不移动。 */ #${PANEL_ID} .tm-select-arrow { width: 18px; height: 18px; flex: 0 0 18px; display: grid; place-items: center; color: #61666d; transform: none !important; } #${PANEL_ID} .tm-select-arrow svg { width: 16px; height: 16px; display: block; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } #${PANEL_ID} .tm-dropdown.open .tm-select-trigger { border-color: var( --bili-blue ); box-shadow: 0 0 0 3px var( --bili-blue-soft ); } #${PANEL_ID} .tm-dropdown.open .tm-select-arrow { color: #61666d; transform: none !important; } /* * 菜单本体有内边距, * 每个选项之间也有 6px 真正空隙。 */ #${PANEL_ID} .tm-select-menu { position: absolute; left: 0; right: 0; top: calc( 100% + 7px ); z-index: 60; max-height: 255px; padding: 7px; display: flex; flex-direction: column; gap: 6px; overflow-x: hidden; overflow-y: auto; opacity: 0; visibility: hidden; transform: translateY( -4px ); border: 1px solid var( --border ); border-radius: var( --radius ); background: #fff; box-shadow: 0 12px 30px rgba( 0, 0, 0, .15 ); transition: opacity .12s ease, transform .12s ease, visibility .12s ease; } #${PANEL_ID} .tm-dropdown.open .tm-select-menu { opacity: 1; visibility: visible; transform: translateY( 0 ); } #${PANEL_ID} .tm-select-option { width: 100%; min-height: 40px; flex: 0 0 auto; padding: 0 12px; display: flex; align-items: center; justify-content: space-between; gap: 10px; border: 0; border-radius: var( --radius ); color: var( --text ); background: transparent; outline: none; cursor: pointer; text-align: left; transition: color .14s ease, background-color .14s ease; } #${PANEL_ID} .tm-select-option:hover:not(:disabled) { color: #008fc4; background: var( --bili-blue-soft ); } #${PANEL_ID} .tm-select-option.selected { color: #008fc4; font-weight: 600; background: var( --bili-blue-selected ); } #${PANEL_ID} .tm-option-text { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #${PANEL_ID} .tm-option-check { flex: 0 0 auto; opacity: 0; color: var( --bili-blue ); font-size: 18px; font-weight: 800; } #${PANEL_ID} .tm-select-option.selected .tm-option-check { opacity: 1; } /* * ===================================================== * 列表顶部 * ===================================================== */ #${PANEL_ID} .tm-list-head { min-height: 32px; display: flex; align-items: center; justify-content: space-between; gap: 10px; } #${PANEL_ID} .tm-list-batch { display: none; flex-direction: column; gap: 8px; padding: 10px; margin: 0 -4px 4px; border-radius: var( --radius ); background: #f6f7f8; } #${PANEL_ID}.tm-list-mode .tm-list-batch { display: flex; } #${PANEL_ID} .tm-list-batch-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; } #${PANEL_ID} .tm-list-batch-title { color: var( --text ); font-weight: 600; font-size: 13px; } #${PANEL_ID} .tm-list-batch-count { color: var( --muted ); font-size: 11px; } #${PANEL_ID} .tm-list-batch input { min-width: 0; height: 32px; padding: 0 8px; border: 1px solid var( --border ); border-radius: var( --radius ); color: var( --text ); background: #fff; outline: none; font-size: 12px; } #${PANEL_ID} .tm-list-batch input:focus { border-color: var( --bili-blue ); box-shadow: 0 0 0 3px var( --bili-blue-soft ); } #${PANEL_ID} .tm-list-limit { flex: 0 0 72px; } #${PANEL_ID} .tm-list-date-start, #${PANEL_ID} .tm-list-date-end { flex: 1 1 0; min-width: 0; } #${PANEL_ID} .tm-list-load-btn { flex: 0 0 auto; height: 32px; padding: 0 12px; border: 0; border-radius: var( --radius ); color: #fff; background: var( --bili-blue ); font-weight: 600; font-size: 12px; cursor: pointer; transition: filter .15s ease, transform .1s ease; } #${PANEL_ID} .tm-list-load-btn:hover:not(:disabled) { filter: brightness( 1.05 ); } #${PANEL_ID} .tm-list-load-btn:disabled { opacity: .55; cursor: not-allowed; } #${PANEL_ID} .tm-list-tools { min-width: 0; display: flex; align-items: center; justify-content: flex-end; gap: 7px; } #${PANEL_ID} .tm-search-wrap { min-width: 0; display: flex; align-items: center; justify-content: flex-end; gap: 7px; } #${PANEL_ID} .tm-search { width: 0; min-width: 0; height: 36px; padding: 0; opacity: 0; pointer-events: none; border: 1px solid transparent; border-radius: var( --radius ); color: var( --text ); background: #fff; outline: none; transition: width .18s ease, padding .18s ease, opacity .12s ease, border-color .12s ease, box-shadow .15s ease; } #${PANEL_ID} .tm-search-wrap.open .tm-search { width: 180px; padding: 0 10px; opacity: 1; pointer-events: auto; border-color: var( --border ); } #${PANEL_ID} .tm-search:focus { border-color: var( --bili-blue ); box-shadow: 0 0 0 3px var( --bili-blue-soft ); } #${PANEL_ID} .tm-search-toggle { width: 36px; height: 36px; flex: 0 0 36px; padding: 0; display: grid; place-items: center; border: 1px solid var( --border ); border-radius: var( --radius ); color: #61666d; background: #fff; outline: none; cursor: pointer; } #${PANEL_ID} .tm-search-toggle:hover:not(:disabled), #${PANEL_ID} .tm-search-toggle.active { color: var( --bili-blue ); border-color: rgba( 0, 174, 236, .44 ); background: var( --bili-blue-soft ); } #${PANEL_ID} .tm-search-toggle svg { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; } #${PANEL_ID} .tm-select-all-wrap { display: inline-flex; align-items: center; gap: 7px; color: #61666d; font-weight: 500; cursor: pointer; user-select: none; } #${PANEL_ID} input[type="checkbox"] { width: 18px; height: 18px; margin: 0; accent-color: var( --bili-blue ); cursor: pointer; } #${PANEL_ID} .tm-items-hint { color: var( --muted ); font-size: 11px; } /* * ===================================================== * 视频列表 * ===================================================== */ #${PANEL_ID} .tm-items { position: relative; min-height: 0; max-height: 320px; overflow: auto; border: 1px solid var( --border ); border-radius: var( --radius ); background: #f7f8f9; scroll-behavior: auto; } #${PANEL_ID} .tm-items::-webkit-scrollbar, #${PANEL_ID} .tm-select-menu::-webkit-scrollbar { width: 6px; } #${PANEL_ID} .tm-items::-webkit-scrollbar-thumb, #${PANEL_ID} .tm-select-menu::-webkit-scrollbar-thumb { border-radius: 999px; background: #d3d6d9; } #${PANEL_ID} .tm-item { min-height: 46px; padding: 6px 10px; display: grid; grid-template-columns: 20px max-content minmax( 0, 1fr ); align-items: center; column-gap: 7px; background: transparent; transition: background-color .2s ease; } #${PANEL_ID} .tm-item + .tm-item { border-top: 1px solid #e9eaec; } #${PANEL_ID} .tm-item:hover { background: #fff; } #${PANEL_ID} .tm-item-index { color: var( --muted ); white-space: nowrap; font-variant-numeric: tabular-nums; transition: color .2s ease; } #${PANEL_ID} .tm-item-title { min-width: 0; padding: 6px 7px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; border-radius: var( --radius ); color: var( --text ); cursor: pointer; transition: color .2s ease, background-color .2s ease; } #${PANEL_ID} .tm-item-title:hover, #${PANEL_ID} .tm-item.tm-current-flash .tm-item-title { color: var( --bili-blue ); background: var( --bili-blue-soft ); } #${PANEL_ID} .tm-item.tm-current-flash .tm-item-index { color: var( --bili-blue ); } #${PANEL_ID} .tm-empty { padding: 20px; color: var( --muted ); text-align: center; } #${PANEL_ID} .tm-summary { display: flex; align-items: center; justify-content: space-between; color: var( --muted ); font-size: 11px; } /* * ===================================================== * 下载 * ===================================================== */ #${PANEL_ID} .tm-download-actions, #${PANEL_ID} .tm-subtitle-actions { display: grid; grid-template-columns: minmax( 0, 1fr ) minmax( 0, 1fr ); gap: 8px; } #${PANEL_ID} .tm-subtitle-actions { grid-template-columns: 166px minmax( 0, 1fr ); } #${PANEL_ID} .tm-download { width: 100%; min-height: 42px; padding: 0 10px; border: 0; border-radius: var( --radius ); color: #fff; background: linear-gradient( 135deg, #00aeec 0%, #22bce9 100% ); font-weight: 700; cursor: pointer; box-shadow: 0 5px 15px rgba( 0, 174, 236, .18 ); transition: filter .15s ease, transform .1s ease, box-shadow .15s ease; } #${PANEL_ID} .tm-download:hover:not(:disabled) { filter: brightness( 1.055 ); box-shadow: 0 6px 18px rgba( 0, 174, 236, .26 ); } #${PANEL_ID} .tm-download:active:not(:disabled) { transform: scale( .985 ); } #${PANEL_ID} button:disabled, #${PANEL_ID} input:disabled { opacity: .52; cursor: not-allowed; } /* * ===================================================== * 状态 / 进度 * ===================================================== */ #${PANEL_ID} .tm-status-card { padding: 9px 10px 7px; border-radius: var( --radius ); background: #f6f7f8; } #${PANEL_ID} .tm-status-line { min-width: 0; display: flex; align-items: center; justify-content: space-between; gap: 8px; } #${PANEL_ID} .tm-status { min-width: 0; flex: 1 1 auto; overflow: hidden; color: #61666d; white-space: nowrap; text-overflow: ellipsis; } #${PANEL_ID} .tm-status[data-type="ok"] { color: #008fc4; } #${PANEL_ID} .tm-status[data-type="error"] { color: #d64242; } #${PANEL_ID} .tm-progress-text { flex: 0 0 auto; max-width: 150px; overflow: hidden; color: var( --muted ); font-size: 10.5px; white-space: nowrap; text-overflow: ellipsis; text-align: right; } #${PANEL_ID} .tm-progress-track { height: 3px; margin-top: 6px; overflow: hidden; border-radius: 999px; background: var( --border ); } #${PANEL_ID} .tm-progress-fill { width: 0; height: 100%; border-radius: 999px; background: var( --bili-blue ); transition: width .18s ease; } /* * ===================================================== * Logo 下载提示 * ===================================================== */ #${PANEL_ID}-quick-toast { position: fixed; z-index: 2147483647; max-width: 330px; padding: 10px 13px; opacity: 0; visibility: hidden; transform: translateY( -5px ); border: 1px solid rgba( 0, 174, 236, .22 ); border-radius: 12px; color: #0078a8; background: rgba( 255, 255, 255, .985 ); box-shadow: 0 10px 28px rgba( 0, 0, 0, .16 ); font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; transition: opacity .14s ease, transform .14s ease, visibility .14s ease; pointer-events: none; } #${PANEL_ID}-quick-toast.show { opacity: 1; visibility: visible; transform: translateY( 0 ); } #${PANEL_ID}-quick-toast[data-type="error"] { color: #d64242; border-color: rgba( 214, 66, 66, .22 ); } #${PANEL_ID}-quick-toast[data-type="ok"] { color: #008fc4; } #${PANEL_ID}-quick-toast[data-type="warn"] { color: #a66a00; border-color: rgba( 166, 106, 0, .20 ); } @media ( max-width: 900px ) { #${PANEL_ID} { left: 8px; right: auto; top: 62px; width: min( 430px, calc( 100vw - 16px ) ); } #${PANEL_ID}.minimized { width: min( 150px, calc( 100vw - 16px ) ); } } /* 运行日志面板(挂在 body 下,独立于主面板) */ #${PANEL_ID}-log { position: fixed; right: 20px; bottom: 20px; width: min(680px, calc(100vw - 40px)); height: min(460px, calc(100vh - 120px)); display: none; flex-direction: column; background: #ffffff; border: 1px solid #d0d7e2; border-radius: 10px; box-shadow: 0 12px 40px rgba(15, 30, 60, 0.25); z-index: 999999; } #${PANEL_ID}-log .tm-log-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 8px 10px; border-bottom: 1px solid #e3e8ef; } #${PANEL_ID}-log .tm-log-title { font-size: 13px; font-weight: 700; } #${PANEL_ID}-log .tm-log-cats { display: flex; gap: 4px; } #${PANEL_ID}-log .tm-log-chip { padding: 3px 10px; font-size: 12px; border: 1px solid #d0d7e2; border-radius: 999px; background: #f5f7fa; cursor: pointer; } #${PANEL_ID}-log .tm-log-chip.active { background: ${BILI_BLUE}; border-color: ${BILI_BLUE}; color: #fff; } #${PANEL_ID}-log .tm-log-echo { display: flex; align-items: center; gap: 4px; font-size: 12px; color: #4a5568; cursor: pointer; user-select: none; } #${PANEL_ID}-log .tm-log-actions { display: flex; gap: 6px; margin-left: auto; } #${PANEL_ID}-log .tm-log-btn { padding: 3px 10px; font-size: 12px; border: 1px solid #d0d7e2; border-radius: 6px; background: #fff; cursor: pointer; } #${PANEL_ID}-log .tm-log-btn:hover { background: #eef2f7; } #${PANEL_ID}-log .tm-log-list { flex: 1 1 auto; overflow: auto; background: #14161a; color: #d6deeb; font-family: Consolas, Menlo, monospace; font-size: 12px; line-height: 1.55; padding: 8px 10px; white-space: pre-wrap; word-break: break-all; } #${PANEL_ID}-log .tm-log-line.tm-log-warn { color: #f6c177; } #${PANEL_ID}-log .tm-log-line.tm-log-error { color: #ff6b6b; } `); /* * ========================================================= * 全屏隐藏 UI(避免遮挡播放画面) * ========================================================= */ GM_addStyle(` html.tm-dl-fs #${PANEL_ID}, html.tm-dl-fs #${PANEL_ID}-quick-toast, html.tm-dl-fs #yc9-dock, html.tm-dl-fs #yc9-orb { display: none !important; } `); let fsVideoEl = null; let fsVideoOversized = false; function isNativeFullscreen() { try { return !!( document.fullscreenElement || document.webkitFullscreenElement ); } catch (err) { return false; } } function isBiliScreenModeFull() { try { const el = document.querySelector( '.bpx-player-container' ); const mode = el?.getAttribute('data-screen'); return ( mode === 'full' || mode === 'web' ); } catch (err) { return false; } } function refreshFullscreenUi() { try { if ( fsVideoOversized && fsVideoEl && !fsVideoEl.isConnected ) { fsVideoOversized = false; } const fullscreen = isNativeFullscreen() || fsVideoOversized || isBiliScreenModeFull(); document.documentElement.classList.toggle( 'tm-dl-fs', fullscreen ); } catch (err) { /* 静默失败,不影响主流程 */ } } function watchVideoResizeForWebFullscreen() { if ( typeof ResizeObserver === 'undefined' ) { return; } let attempts = 0; const timer = setInterval(() => { attempts++; const video = document.querySelector( 'video' ); if (!video) { if (attempts >= 60) { clearInterval(timer); } return; } clearInterval(timer); try { fsVideoEl = video; const observer = new ResizeObserver(() => { fsVideoOversized = video.clientWidth === window.innerWidth && video.clientHeight >= window.innerHeight * 0.9; refreshFullscreenUi(); }); observer.observe(video); } catch (err) { /* ignore */ } }, 500); } function installFullscreenWatcher() { if (!YC9_IS_BILI_TARGET) { return; } document.addEventListener( 'fullscreenchange', refreshFullscreenUi ); document.addEventListener( 'webkitfullscreenchange', refreshFullscreenUi ); /* * 每 500ms 兜底轮询一次, * 覆盖 B 站网页全屏(data-screen="web"/"full")、 * 浏览器原生全屏,以及旧版播放器无标记的情况。 */ setInterval( refreshFullscreenUi, 500 ); watchVideoResizeForWebFullscreen(); } /* * ========================================================= * 液态玻璃主题 * ========================================================= */ GM_addStyle(` #${PANEL_ID} { --text: #f1f6ff; --muted: rgba(236, 243, 255, .56); --border: rgba(255, 255, 255, .16); --radius: 16px; --yc9-face: linear-gradient(158deg, rgba(255,255,255,.18) 0%, rgba(255,255,255,.06) 100%); border-radius: 26px !important; border: 1px solid rgba(255, 255, 255, .22) !important; background: radial-gradient(125% 85% at 6% -8%, rgba(255,255,255,.34) 0%, rgba(255,255,255,0) 54%), radial-gradient(115% 95% at 103% 108%, rgba(0,174,236,.30) 0%, rgba(0,0,0,0) 62%), linear-gradient(158deg, rgba(44,48,64,.62) 0%, rgba(12,14,20,.60) 100%) !important; backdrop-filter: blur(30px) saturate(180%) !important; -webkit-backdrop-filter: blur(30px) saturate(180%) !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.55), inset 0 0 0 1px rgba(255,255,255,.05), inset 0 -30px 56px -32px rgba(255,255,255,.22), 0 30px 72px rgba(0,0,0,.46), 0 4px 14px rgba(0,0,0,.28) !important; } #${PANEL_ID} .tm-head { background: transparent !important; border-bottom: 1px solid rgba(255,255,255,.10) !important; border-radius: 26px 26px 0 0 !important; } #${PANEL_ID} .tm-head:hover { background: rgba(255,255,255,.04) !important; } #${PANEL_ID} .tm-body { background: transparent !important; border-radius: 0 0 26px 26px !important; } #${PANEL_ID} .tm-brand-name { color: #ffffff !important; font-weight: 600 !important; letter-spacing: .2px !important; text-shadow: 0 1px 2px rgba(0,0,0,.35); } #${PANEL_ID} .tm-brand-divider { background: rgba(255,255,255,.18) !important; } #${PANEL_ID} .tm-row label, #${PANEL_ID} .tm-select-all-wrap, #${PANEL_ID} .tm-select-trigger, #${PANEL_ID} .tm-item-title, #${PANEL_ID} .tm-status { color: rgba(240, 246, 255, .80) !important; } #${PANEL_ID} .tm-item-title:hover, #${PANEL_ID} .tm-item-title:focus, #${PANEL_ID} .tm-item-title:active { color: #7fe0ff !important; } #${PANEL_ID} .tm-item-index { color: rgba(236, 243, 255, .42) !important; } /* 玻璃质感控件 */ #${PANEL_ID} .tm-select-trigger, #${PANEL_ID} .tm-search, #${PANEL_ID} .tm-search-toggle, #${PANEL_ID} .tm-icon-btn, #${PANEL_ID} .tm-list-batch input, #${PANEL_ID} .tm-list-load-btn { background: var(--yc9-face) !important; border: 1px solid rgba(255, 255, 255, .18) !important; color: #f1f6ff !important; border-radius: 14px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.32), 0 2px 8px rgba(0,0,0,.16) !important; backdrop-filter: blur(10px) saturate(160%); -webkit-backdrop-filter: blur(10px) saturate(160%); } #${PANEL_ID} .tm-search-toggle:hover:not(:disabled), #${PANEL_ID} .tm-search-toggle.active, #${PANEL_ID} .tm-select-trigger:hover, #${PANEL_ID} .tm-icon-btn:hover:not(:disabled) { background: rgba(255,255,255,.22) !important; border-color: rgba(255, 255, 255, .34) !important; color: #ffffff !important; } #${PANEL_ID} .tm-search-toggle { border-radius: 50% !important; } /* 自定义复选框:玻璃质感 */ #${PANEL_ID} input[type="checkbox"] { appearance: none !important; -webkit-appearance: none !important; width: 18px !important; height: 18px !important; flex: 0 0 18px; border-radius: 6px !important; border: 1px solid rgba(255, 255, 255, .34) !important; background: rgba(255, 255, 255, .10) !important; box-shadow: inset 0 1px 0 rgba(255, 255, 255, .30) !important; transition: background .15s ease, border-color .15s ease, box-shadow .15s ease; } #${PANEL_ID} input[type="checkbox"]:checked { border-color: rgba(255, 255, 255, .55) !important; background-color: #17a9e0 !important; background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M3.4 8.4l3.1 3.2 6.2-7' fill='none' stroke='%23ffffff' stroke-width='2.4' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") !important; background-repeat: no-repeat !important; background-position: center !important; background-size: 13px 13px !important; box-shadow: inset 0 1px 0 rgba(255, 255, 255, .65), 0 3px 10px rgba(0, 174, 236, .45) !important; } #${PANEL_ID} input::placeholder { color: rgba(236, 243, 255, .42) !important; } /* 列表 */ #${PANEL_ID} .tm-items { background: rgba(255, 255, 255, .05) !important; border: 1px solid rgba(255, 255, 255, .12) !important; border-radius: 16px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.14), inset 0 -18px 36px -26px rgba(0,0,0,.55) !important; backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); } #${PANEL_ID} .tm-item { border-color: rgba(255, 255, 255, .08) !important; } #${PANEL_ID} .tm-item:hover { background: rgba(255, 255, 255, .10) !important; } #${PANEL_ID} .tm-item[data-current="1"] { background: rgba(0, 174, 236, .20) !important; } #${PANEL_ID} .tm-empty { color: rgba(236, 243, 255, .45) !important; } /* 下拉菜单 */ #${PANEL_ID} .tm-select-menu { background: linear-gradient(160deg, rgba(46,51,68,.90) 0%, rgba(16,19,27,.92) 100%) !important; border: 1px solid rgba(255, 255, 255, .20) !important; border-radius: 18px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.30), 0 24px 50px rgba(0,0,0,.50) !important; backdrop-filter: blur(28px) saturate(180%) !important; -webkit-backdrop-filter: blur(28px) saturate(180%) !important; color: #eef4ff !important; } #${PANEL_ID} .tm-select-option { color: rgba(240, 246, 255, .84) !important; border-radius: 12px !important; } #${PANEL_ID} .tm-select-option:hover { background: rgba(255, 255, 255, .12) !important; } #${PANEL_ID} .tm-select-option.selected { background: rgba(0, 174, 236, .26) !important; color: #ffffff !important; } #${PANEL_ID} .tm-option-check { color: #7fe0ff !important; } #${PANEL_ID} .tm-list-batch { background: rgba(255, 255, 255, .06) !important; border: 1px solid rgba(255, 255, 255, .12) !important; border-radius: 16px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.14) !important; } #${PANEL_ID} .tm-list-batch-title { color: rgba(240, 246, 255, .82) !important; } #${PANEL_ID} .tm-list-batch-count { color: rgba(236, 243, 255, .55) !important; } #${PANEL_ID} .tm-list-load-btn:hover:not(:disabled) { background: rgba(255, 255, 255, .22) !important; border-color: rgba(255, 255, 255, .34) !important; } /* 状态 / 进度 */ #${PANEL_ID} .tm-status-card { background: rgba(255, 255, 255, .07) !important; border: 1px solid rgba(255, 255, 255, .10) !important; border-radius: 16px !important; box-shadow: inset 0 1px 0 rgba(255, 255, 255, .18) !important; } #${PANEL_ID} .tm-status[data-type="ok"] { color: #6fe4ff !important; } #${PANEL_ID} .tm-status[data-type="error"] { color: #ff9b9b !important; } #${PANEL_ID} .tm-progress-track { height: 4px !important; background: rgba(255, 255, 255, .14) !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.10) !important; } #${PANEL_ID} .tm-progress-fill { background: linear-gradient(90deg, #6fe4ff 0%, #00aeec 100%) !important; box-shadow: 0 0 10px rgba(111, 228, 255, .65) !important; } #${PANEL_ID} .tm-summary { color: rgba(236, 243, 255, .55) !important; } /* 下载按钮:玻璃高光 */ #${PANEL_ID} .tm-download { border-radius: 14px !important; background: linear-gradient(135deg, #35c8f5 0%, #0a9fe2 100%) !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.50), inset 0 -10px 20px -14px rgba(0,0,0,.45), 0 10px 24px rgba(0, 174, 236, .32) !important; color: #ffffff !important; } #${PANEL_ID} .tm-download:hover:not(:disabled) { filter: brightness(1.06) !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.60), 0 14px 30px rgba(0, 174, 236, .42) !important; } /* 滚动条 */ #${PANEL_ID} .tm-items::-webkit-scrollbar-thumb, #${PANEL_ID} .tm-select-menu::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, .22) !important; } /* 最小化状态 */ #${PANEL_ID}.minimized { border-radius: 999px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.55), inset 0 0 0 1px rgba(255,255,255,.05), 0 22px 50px rgba(0,0,0,.42) !important; } #${PANEL_ID}.minimized .tm-head { border-radius: 999px !important; border-bottom-color: transparent !important; } /* 运行日志 */ #${PANEL_ID}-log { background: linear-gradient(160deg, rgba(42,47,63,.88) 0%, rgba(13,16,23,.90) 100%) !important; border: 1px solid rgba(255, 255, 255, .18) !important; border-radius: 22px !important; color: #eef4ff !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.40), 0 24px 56px rgba(0,0,0,.48) !important; backdrop-filter: blur(26px) saturate(180%) !important; -webkit-backdrop-filter: blur(26px) saturate(180%) !important; } #${PANEL_ID}-log .tm-log-head { border-bottom: 1px solid rgba(255, 255, 255, .12) !important; } #${PANEL_ID}-log .tm-log-chip { background: rgba(255, 255, 255, .08) !important; border: 1px solid rgba(255, 255, 255, .16) !important; color: rgba(240, 246, 255, .82) !important; } #${PANEL_ID}-log .tm-log-list { background: rgba(0, 0, 0, .18) !important; color: rgba(236, 243, 255, .82) !important; } #${PANEL_ID}-log .tm-log-btn, #${PANEL_ID}-log .tm-log-action { background: rgba(255, 255, 255, .10) !important; border: 1px solid rgba(255, 255, 255, .18) !important; color: rgba(240, 246, 255, .86) !important; border-radius: 10px !important; } /* 轻提示 */ #${PANEL_ID}-quick-toast { background: linear-gradient(160deg, rgba(44,49,66,.94) 0%, rgba(14,17,24,.96) 100%) !important; border: 1px solid rgba(255, 255, 255, .20) !important; color: #d9f4ff !important; border-radius: 14px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,.35), 0 18px 40px rgba(0,0,0,.45) !important; backdrop-filter: blur(22px) saturate(180%) !important; -webkit-backdrop-filter: blur(22px) saturate(180%) !important; } #${PANEL_ID}-quick-toast[data-type="error"] { color: #ff9b9b !important; } #${PANEL_ID}-quick-toast[data-type="ok"] { color: #6fe4ff !important; } #${PANEL_ID}-quick-toast[data-type="warn"] { color: #ffd08a !important; } `); createPanel(); installSpaWatcher(); installFullscreenWatcher(); initPage() .catch( err => { console.error( '[BiliDL] init failed:', err ); setStatus( `初始化失败:${err ?.message || err }`, 'error' ); } ); })(); /* * ========================================================= * 育才9班自用破解 · VIP 解析 / 直链下载 * 开源许可:MIT * ========================================================= */ (function () { 'use strict'; const DOCK_ID = 'yc9-dock'; const ORB_ID = 'yc9-orb'; const parserList = [ { name: '虾米解析', url: 'https://jx.yparse.com/index.php?url=' }, { name: '云解析1', url: 'https://jx.xmflv.cc/?url=' }, { name: '云解析2', url: 'https://jx.playerjy.com/?url=' }, { name: '高清解析', url: 'https://www.8090g.cn/jiexi/?url=' }, { name: '备用解析', url: 'https://www.ckplayer.vip/jiexi/?url=' }, { name: 'ckplayer', url: 'https://www.ckp23lay37uter.vip/jiexi/?url=' }, { name: 'M3U8解析', url: 'https://jx.m3uqae8.tv/jiexi/?url=' }, { name: '夜幕', url: 'https://www.ye34wdmu.xyz/?url=' }, { name: '8090解析', url: 'https://www.8y0liu90g.cn/jiexi/?url=' }, { name: '云解析', url: 'https://ypatr4erse.ik9.cc/index.php?url=' }, { name: 'JY解析', url: 'https://jx.we-vip.com/?url=' }, { name: 'YT', url: 'https://jx.yanw2qagtu.top/?url=' }, { name: '⑸号解析', url: 'https://www.809opl0g.cn/jiexi/?url=' }, { name: 'M1907解析', url: 'https://im19cds07.top/?jx=' }, { name: '咸鱼解析', url: 'https://jx.xyfzaslv.cc/?url=' }, { name: '极速解析', url: 'https://jx.2sklj0.cn/player/?url=' }, { name: 'qianqi', url: 'https://api.qi32weanqi.net/vip/?url=' }, { name: 'M1907', url: 'https://z1.im19awqz07.top/?jx=' }, { name: 'yparse', url: 'https://jx.yparswr456se.com/index.php?url=' }, { name: '云解析', url: 'https://yparawedse.i67k9.cc/index.php?url=' }, { name: 'Player-JY', url: 'https://jx.plavdfe3yerjy.com/?url=' }, { name: '虾米', url: 'https://jx.xmflw345v.com/?url=' }, { name: '全能vip②', url: 'https://www.8090.la/8090/?url=' }, { name: 'BL', url: 'https://svip.bljiex.com/?v=' }, { name: 'play', url: 'https://www.playm56yt3u8.cn/jiexi.php?url=' }, { name: '⑤号接口', url: 'https://jx.m3uwrtv8.tv/jiexi/?url=' }, { name: '8090解析', url: 'https://www.8090g.cn/jiexi/?url=' }, { name: 'yparse', url: 'https://jx.yparred45rse.com/index.php?url=' }, { name: '综合/B站', url: 'https://jx.jsonplayer.com/player/?url=' }, { name: 'Mao解析', url: 'https://www.mtosz.com/m3u8.php?url=' }, { name: '风影阁', url: 'https://movie.heheda.top/?v=' }, { name: 'M1907', url: 'https://z1.im1w3erdx907.top/?&jx=' }, { name: '猪蹄', url: 'https://jx.iztyy.com/Bei/?url=' }, { name: 'BL智能解析', url: 'https://svip.blji23weex.cc/?v=' }, ]; const SITES = [ { key: 'iqiyi', label: '爱奇艺', url: 'https://www.iqiyi.com' }, { key: 'tencent', label: '腾讯', url: 'https://v.qq.com' }, { key: 'yinghua', label: '樱花', url: 'http://www.yinghuadm.co/' }, { key: 'bilibili', label: 'B站', url: 'https://www.bilibili.com' }, { key: 'gold', label: '金牌影院', url: 'https://www.ksnnhbj.com/' }, ]; /* ---------------- 样式 ---------------- */ GM_addStyle(` #${DOCK_ID}, #${ORB_ID} { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; box-sizing: border-box; } #${DOCK_ID} *, #${ORB_ID} * { box-sizing: border-box; } #${DOCK_ID} { position: fixed; right: 16px; bottom: 16px; width: 386px; max-width: calc(100vw - 24px); z-index: 2147483000; padding: 0; border-radius: 26px; overflow: hidden; color: #f1f6ff; border: 1px solid rgba(255, 255, 255, .22); background: radial-gradient(125% 85% at 8% -10%, rgba(255,255,255,.34) 0%, rgba(255,255,255,0) 54%), radial-gradient(115% 95% at 104% 108%, rgba(255,120,170,.22) 0%, rgba(0,0,0,0) 62%), linear-gradient(158deg, rgba(46,50,66,.62) 0%, rgba(12,14,20,.60) 100%); backdrop-filter: blur(30px) saturate(180%); -webkit-backdrop-filter: blur(30px) saturate(180%); box-shadow: inset 0 1px 0 rgba(255,255,255,.55), inset 0 0 0 1px rgba(255,255,255,.05), inset 0 -30px 56px -32px rgba(255,255,255,.22), 0 30px 72px rgba(0,0,0,.46), 0 4px 14px rgba(0,0,0,.28); transition: opacity .2s ease, transform .2s ease; } #${DOCK_ID}.yc9-hide { opacity: 0; transform: translateY(12px) scale(.96); pointer-events: none; } /* 头部 */ #${DOCK_ID} .yc9-head { height: 52px; padding: 0 10px 0 16px; display: flex; align-items: center; justify-content: space-between; gap: 8px; cursor: grab; user-select: none; border-bottom: 1px solid rgba(255, 255, 255, .10); } #${DOCK_ID} .yc9-head.yc9-dragging { cursor: grabbing; } #${DOCK_ID} .yc9-brand { display: flex; align-items: center; gap: 9px; min-width: 0; } #${DOCK_ID} .yc9-dot { width: 10px; height: 10px; flex: 0 0 10px; border-radius: 50%; background: radial-gradient(circle at 32% 28%, #ffffff, #4fd2ff 42%, #0a8fc4 100%); box-shadow: 0 0 10px rgba(79, 210, 255, .8), inset 0 1px 0 rgba(255,255,255,.8); } #${DOCK_ID} .yc9-title { font-size: 14px; font-weight: 600; letter-spacing: .2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-shadow: 0 1px 2px rgba(0,0,0,.35); } #${DOCK_ID} .yc9-head-btns { display: flex; align-items: center; gap: 5px; flex: 0 0 auto; } #${DOCK_ID} .yc9-hbtn { height: 28px; min-width: 28px; padding: 0 9px; display: grid; place-items: center; border-radius: 11px; border: 1px solid rgba(255, 255, 255, .18); background: linear-gradient(158deg, rgba(255,255,255,.18) 0%, rgba(255,255,255,.06) 100%); color: rgba(240, 246, 255, .88); font-size: 12px; line-height: 1; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255,255,255,.32); transition: background .15s ease, color .15s ease, border-color .15s ease; } #${DOCK_ID} .yc9-hbtn:hover { background: rgba(255, 255, 255, .22); border-color: rgba(255, 255, 255, .34); color: #ffffff; } #${DOCK_ID} .yc9-hbtn.yc9-close:hover { background: rgba(255, 106, 120, .30); border-color: rgba(255, 140, 150, .48); color: #ffffff; } /* 主体 */ #${DOCK_ID} .yc9-body { padding: 13px 14px 12px; display: flex; flex-direction: column; gap: 9px; } #${DOCK_ID}.yc9-min .yc9-body, #${DOCK_ID}.yc9-min .yc9-foot { display: none; } #${DOCK_ID}.yc9-min { width: auto; min-width: 236px; border-radius: 999px; } #${DOCK_ID}.yc9-min .yc9-head { border-bottom-color: transparent; border-radius: 999px; } #${DOCK_ID} .yc9-sec-title { display: flex; align-items: center; gap: 7px; margin-bottom: 7px; font-size: 12px; font-weight: 600; letter-spacing: .4px; color: rgba(240, 246, 255, .92); } #${DOCK_ID} .yc9-sec-title::before { content: ''; width: 3px; height: 12px; border-radius: 999px; background: linear-gradient(180deg, #7fe0ff, #0a9fe2); box-shadow: 0 0 8px rgba(79, 210, 255, .7); } #${DOCK_ID} .yc9-sec-title.yc9-pink::before { background: linear-gradient(180deg, #ffb3c7, #ff5f7e); box-shadow: 0 0 8px rgba(255, 95, 126, .7); } #${DOCK_ID} .yc9-row { display: flex; gap: 6px; margin-bottom: 7px; } #${DOCK_ID} .yc9-input { flex: 1 1 auto; min-width: 0; height: 32px; padding: 0 11px; border-radius: 13px; border: 1px solid rgba(255, 255, 255, .18); background: linear-gradient(158deg, rgba(255,255,255,.18) 0%, rgba(255,255,255,.06) 100%); color: #f1f6ff; font-size: 12px; outline: none; box-shadow: inset 0 1px 0 rgba(255,255,255,.30), 0 2px 8px rgba(0,0,0,.16); backdrop-filter: blur(10px) saturate(160%); -webkit-backdrop-filter: blur(10px) saturate(160%); transition: border-color .15s ease, background .15s ease; appearance: none; -webkit-appearance: none; } #${DOCK_ID} .yc9-input:focus { border-color: rgba(127, 224, 255, .62); background: rgba(255, 255, 255, .22); } #${DOCK_ID} .yc9-input::placeholder { color: rgba(236, 243, 255, .42); } #${DOCK_ID} select.yc9-input { padding-right: 26px; background-image: linear-gradient(45deg, transparent 50%, rgba(240,246,255,.75) 50%), linear-gradient(135deg, rgba(240,246,255,.75) 50%, transparent 50%); background-position: calc(100% - 15px) 14px, calc(100% - 10px) 14px; background-size: 5px 5px, 5px 5px; background-repeat: no-repeat; cursor: pointer; } #${DOCK_ID} select.yc9-input option { background: #1b1f2b; color: #f1f6ff; } #${DOCK_ID} .yc9-btn { flex: 0 0 auto; height: 32px; padding: 0 12px; border-radius: 13px; border: 1px solid rgba(255, 255, 255, .18); background: linear-gradient(158deg, rgba(255,255,255,.18) 0%, rgba(255,255,255,.06) 100%); color: rgba(240, 246, 255, .9); font-size: 12px; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255,255,255,.30); transition: background .15s ease, color .15s ease, transform .1s ease; } #${DOCK_ID} .yc9-btn:hover { background: rgba(255, 255, 255, .22); color: #ffffff; } #${DOCK_ID} .yc9-btn:active { transform: scale(.97); } #${DOCK_ID} .yc9-btn.yc9-wide { flex: 1 1 auto; height: 36px; font-size: 13px; font-weight: 600; color: #ffffff; } #${DOCK_ID} .yc9-btn.yc9-red { background: linear-gradient(135deg, #ff7a90 0%, #f03e60 100%); border-color: rgba(255, 255, 255, .26); box-shadow: inset 0 1px 0 rgba(255,255,255,.50), inset 0 -10px 20px -14px rgba(0,0,0,.45), 0 10px 24px rgba(240, 62, 96, .34); } #${DOCK_ID} .yc9-btn.yc9-green { background: linear-gradient(135deg, #5ee6a8 0%, #10b981 100%); border-color: rgba(255, 255, 255, .26); box-shadow: inset 0 1px 0 rgba(255,255,255,.50), inset 0 -10px 20px -14px rgba(0,0,0,.45), 0 10px 24px rgba(16, 185, 129, .34); } #${DOCK_ID} .yc9-btn.yc9-red:hover, #${DOCK_ID} .yc9-btn.yc9-green:hover { filter: brightness(1.06); color: #ffffff; } #${DOCK_ID} .yc9-chips { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; margin-bottom: 8px; } #${DOCK_ID} .yc9-chip { height: 30px; padding: 0 2px; font-size: 11px; letter-spacing: 0; border-radius: 12px; border: 1px solid rgba(255, 255, 255, .16); background: linear-gradient(158deg, rgba(255,255,255,.14) 0%, rgba(255,255,255,.05) 100%); color: rgba(240, 246, 255, .86); cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; box-shadow: inset 0 1px 0 rgba(255,255,255,.28); transition: background .15s ease, color .15s ease, border-color .15s ease; } #${DOCK_ID} .yc9-chip:hover { background: rgba(255, 255, 255, .20); border-color: rgba(255, 255, 255, .30); color: #ffffff; } #${DOCK_ID} .yc9-hr { height: 1px; margin: 4px 0 2px; background: linear-gradient( 90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,.20) 22%, rgba(255,255,255,.20) 78%, rgba(255,255,255,0) 100% ); } #${DOCK_ID} .yc9-status { min-height: 20px; padding: 4px 10px; border-radius: 12px; background: rgba(255, 255, 255, .07); border: 1px solid rgba(255, 255, 255, .10); box-shadow: inset 0 1px 0 rgba(255,255,255,.16); font-size: 11.5px; line-height: 18px; color: rgba(236, 243, 255, .70); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } #${DOCK_ID} .yc9-status[data-type="ok"] { color: #6fe4ff; } #${DOCK_ID} .yc9-status[data-type="error"] { color: #ff9b9b; } #${DOCK_ID} .yc9-status[data-type="warn"] { color: #ffd08a; } #${DOCK_ID} .yc9-foot { padding: 0 14px 11px; font-size: 10.5px; letter-spacing: .3px; color: rgba(236, 243, 255, .40); text-align: right; } /* 关闭后的小球启动器 */ #${ORB_ID} { position: fixed; right: 18px; bottom: 18px; width: 54px; height: 54px; z-index: 2147483001; display: none; place-items: center; border-radius: 50%; cursor: pointer; color: #f1f6ff; font-size: 15px; font-weight: 700; border: 1px solid rgba(255, 255, 255, .30); background: radial-gradient(90% 80% at 30% 20%, rgba(255,255,255,.55) 0%, rgba(255,255,255,0) 58%), linear-gradient(158deg, rgba(60,66,86,.72) 0%, rgba(14,17,24,.72) 100%); backdrop-filter: blur(24px) saturate(180%); -webkit-backdrop-filter: blur(24px) saturate(180%); box-shadow: inset 0 1px 0 rgba(255,255,255,.60), inset 0 -12px 22px -14px rgba(255,255,255,.30), 0 18px 40px rgba(0,0,0,.45); transition: transform .18s ease; } #${ORB_ID}:hover { transform: translateY(-2px) scale(1.04); } `); /* ---------------- 界面 ---------------- */ function buildDock() { const existed = document.getElementById(DOCK_ID); if (existed) { return existed; } const dock = document.createElement('div'); dock.id = DOCK_ID; dock.innerHTML = `
育才9班自用破解
VIP 视频解析
${SITES.map( site => `` ).join('')}
B 站 1080P 下载
就绪
开源许可:MIT
`; document.body.appendChild(dock); makeDraggable(dock); bindEvents(dock); return dock; } function buildOrb() { let orb = document.getElementById(ORB_ID); if (orb) { return orb; } orb = document.createElement('div'); orb.id = ORB_ID; orb.textContent = '9'; orb.title = '打开育才9班自用破解'; document.body.appendChild(orb); orb.addEventListener('click', () => { const dock = buildDock(); orb.style.display = 'none'; dock.style.display = ''; dock.classList.remove('yc9-hide'); const minBtn = dock.querySelector('.yc9-hbtn[data-act="min"]'); if (minBtn && !dock.classList.contains('yc9-min')) { minBtn.textContent = '−'; } }); return orb; } function makeDraggable(el) { const bar = el.querySelector('.yc9-head'); let ox = 0; let oy = 0; let dragging = false; bar.addEventListener('mousedown', event => { if (event.button !== 0 || event.target.closest('button')) { return; } const rect = el.getBoundingClientRect(); ox = event.clientX - rect.left; oy = event.clientY - rect.top; dragging = true; el.style.left = `${rect.left}px`; el.style.top = `${rect.top}px`; el.style.right = 'auto'; el.style.bottom = 'auto'; bar.classList.add('yc9-dragging'); event.preventDefault(); }); document.addEventListener('mousemove', event => { if (!dragging) { return; } const maxLeft = Math.max(0, window.innerWidth - el.offsetWidth); const maxTop = Math.max(0, window.innerHeight - el.offsetHeight); el.style.left = `${Math.max(0, Math.min(maxLeft, event.clientX - ox))}px`; el.style.top = `${Math.max(0, Math.min(maxTop, event.clientY - oy))}px`; }); document.addEventListener('mouseup', () => { if (!dragging) { return; } dragging = false; bar.classList.remove('yc9-dragging'); }); } /* ---------------- 请求 / 下载 ---------------- */ function httpGet(url, headers = {}) { if (typeof GM_xmlhttpRequest === 'function') { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url, headers, timeout: 20000, onload: res => resolve(res.responseText || ''), onerror: () => reject(new Error('网络请求失败')), ontimeout: () => reject(new Error('请求超时')), }); }); } return fetch(url, { headers, credentials: 'include' }).then(res => res.text() ); } function saveFile(url, name, referer) { return new Promise(resolve => { if (typeof GM_download === 'function') { try { GM_download({ url, name, headers: referer ? { Referer: referer } : {}, onload: () => resolve(true), onerror: () => resolve(false), ontimeout: () => resolve(false), }); return; } catch (err) { /* 回退到标签页下载 */ } } try { const a = document.createElement('a'); a.href = url; a.download = name; a.target = '_blank'; a.rel = 'noreferrer'; document.body.appendChild(a); a.click(); a.remove(); resolve(true); } catch (err) { resolve(false); } }); } async function parseBilibili(url) { const html = await httpGet(url, { Referer: 'https://www.bilibili.com/', }); const match = html.match( /window\.__INITIAL_STATE__=(.*?)(?:\}\;|\);\(function\(\))/ ); if (!match) { return []; } const data = JSON.parse(match[1]); const videos = []; const qn = '112'; if (url.includes('/bangumi/play/ep')) { const ep = data.epInfo; videos.push({ title: ep.share_copy, url: `https://api.bilibili.com/x/player/playurl?cid=${ep.cid}&avid=${ep.aid}&qn=${qn}`, }); } else if (url.includes('/video/BV')) { const vd = data.videoData; const aid = vd.aid; for (const p of vd.pages) { const title = vd.pages.length > 1 ? p.part : vd.title; videos.push({ title, url: `https://api.bilibili.com/x/player/playurl?cid=${p.cid}&avid=${aid}&qn=${qn}`, }); } } return videos; } async function downloadVideo(info, onStatus) { try { const raw = await httpGet(info.url, { Referer: 'https://www.bilibili.com/', }); const d = JSON.parse(raw); if (d.code !== 0) { onStatus(`接口返回错误:${d.message || d.code}`); return false; } const playUrl = d?.data?.durl?.[0]?.url; if (!playUrl) { onStatus('未获取到视频直链'); return false; } const name = String(info.title || 'bilibili_video').replace(/[\\/:*?"<>|]/g, '') + '.mp4'; return await saveFile(playUrl, name, 'https://www.bilibili.com/'); } catch (err) { onStatus(`下载失败:${err?.message || err}`); return false; } } /* ---------------- 事件 ---------------- */ function bindEvents(dock) { const $ = selector => dock.querySelector(selector); const statusEl = $('#yc9-status'); function setStatus(text, type = '') { if (!statusEl) { return; } statusEl.textContent = text; statusEl.dataset.type = type; } // 头部按钮 dock.querySelectorAll('.yc9-hbtn').forEach(btn => { btn.addEventListener('click', event => { event.stopPropagation(); const act = btn.dataset.act; if (act === 'min') { const min = dock.classList.toggle('yc9-min'); btn.textContent = min ? '+' : '−'; btn.title = min ? '展开' : '收起'; return; } if (act === 'close') { dock.classList.add('yc9-hide'); setTimeout(() => { dock.style.display = 'none'; buildOrb().style.display = 'grid'; }, 200); return; } if (act === 'panel') { const panel = document.getElementById('tm-bili-downloader'); const minBtn = panel?.querySelector('.tm-min-btn'); if (!panel || !minBtn) { setStatus('当前页不是 B 站视频页,下载面板不可用', 'warn'); return; } minBtn.click(); /* 展开主面板时顺手把解析工具收起,避免两个窗口叠在一起 */ if (!panel.classList.contains('minimized')) { const minBtnSelf = dock.querySelector('.yc9-hbtn[data-act="min"]'); if (minBtnSelf && !dock.classList.contains('yc9-min')) { minBtnSelf.click(); } } if (panel.classList.contains('minimized')) { setStatus('已收起 B 站下载面板', ''); } else { setStatus('已展开 B 站下载面板', 'ok'); } } }); }); // 清空 $('#yc9-vip-clear').addEventListener('click', () => { $('#yc9-vip-url').value = ''; setStatus('已清空', ''); }); $('#yc9-bili-clear').addEventListener('click', () => { $('#yc9-bili-url').value = ''; setStatus('已清空', ''); }); // 站点跳转 dock.querySelectorAll('.yc9-chip').forEach(chip => { chip.addEventListener('click', () => { const site = SITES.find(item => item.key === chip.dataset.site); if (site) { window.open(site.url, '_blank'); } }); }); $('#yc9-bili-home').addEventListener('click', () => { window.open('https://www.bilibili.com', '_blank'); }); // VIP 解析 $('#yc9-play').addEventListener('click', () => { let url = $('#yc9-vip-url').value.trim(); if (!url) { setStatus('请输入视频链接', 'error'); return; } if (!url.startsWith('http')) { url = `https://${url}`; } const index = Number($('#yc9-parser').value) || 0; const parserUrl = parserList[index]?.url; if (!parserUrl) { setStatus('解析接口不可用', 'error'); return; } window.open(parserUrl + encodeURIComponent(url), '_blank'); setStatus(`已提交给「${parserList[index].name}」解析`, 'ok'); }); // B 站下载 $('#yc9-start').addEventListener('click', async () => { const url = $('#yc9-bili-url').value.trim(); if (!url) { setStatus('请输入 B 站链接', 'error'); return; } setStatus('正在解析…', ''); try { const list = await parseBilibili(url); if (!list.length) { setStatus('解析失败,请检查链接', 'error'); return; } setStatus(`准备下载 ${list.length} 个视频`, ''); setStatus('开始下载,请留意浏览器下载提示', 'ok'); for (let i = 0; i < list.length; i++) { const ok = await downloadVideo(list[i], text => setStatus(text, 'error')); setStatus( ok ? `已完成 ${i + 1}/${list.length}` : `${i + 1}/${list.length} 失败`, ok ? 'ok' : 'error' ); } setStatus('全部下载完成', 'ok'); } catch (err) { setStatus(`解析出错:${err?.message || err}`, 'error'); } }); } /* ---------------- 启动 ---------------- */ function boot() { const dock = buildDock(); /* 窄屏时靠左下,避免和 B 站下载面板重叠 */ if (window.innerWidth < 1500) { dock.style.right = 'auto'; dock.style.left = '16px'; } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot, { once: true }); } else { boot(); } })();