// ==UserScript==
// @name 育才视频破解-9班特制-自用
// @namespace yucai9ban.local
// @version 2.1.0
// @description 三合一:B站批量下载(合集/分P/UP主全部视频、音视频、弹幕字幕)+ 全网VIP视频解析 + 页面内播放控制(0.1–16倍变速/画中画/截图/全屏/镜像/进度记忆),液态玻璃界面。
// @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 GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @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 =
window.top === window.self &&
/^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();
});
/* 其它面板展开时自动收起本面板,避免窗口堆叠 */
document.addEventListener('yc9:expand', event => {
if (event.detail?.id === 'dl') {
return;
}
if (!panel.classList.contains('minimized')) {
panel.classList.add('minimized');
minBtn.textContent = '+';
minBtn.title = '展开';
}
});
minBtn.addEventListener('click', event => {
event.stopPropagation();
pinPanelToCurrentScreenPosition(panel);
const minimized = panel.classList.toggle('minimized');
if (!minimized) {
document.dispatchEvent(
new CustomEvent('yc9:expand', {
detail: { id: 'dl' },
})
);
}
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 = `
已选 0
点标题可直接下载
开源许可 MIT
`;
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;
}
`);
/*
* =========================================================
* 布局重排:右上角停靠、双列参数、许可页脚
* =========================================================
*/
GM_addStyle(`
#${PANEL_ID} {
left: auto !important;
right: 20px !important;
top: 84px !important;
width: 392px !important;
max-height: calc(100vh - 104px) !important;
}
#${PANEL_ID} .tm-head {
height: 60px !important;
padding: 0 12px 0 14px !important;
gap: 10px !important;
}
#${PANEL_ID} .tm-brand {
width: 200px !important;
height: 60px !important;
flex: 0 0 200px !important;
}
#${PANEL_ID} .tm-brand-line {
height: 26px !important;
gap: 9px !important;
}
#${PANEL_ID} .tm-logo-host {
width: 62px !important;
height: 26px !important;
flex: 0 0 62px !important;
}
#${PANEL_ID} .tm-bili-fallback-logo {
width: 25px !important;
height: 25px !important;
}
#${PANEL_ID} .tm-brand-divider {
height: 15px !important;
}
#${PANEL_ID} .tm-brand-name {
font-size: 14px !important;
line-height: 26px !important;
letter-spacing: .1px !important;
}
#${PANEL_ID} .tm-icon-btn {
width: 32px !important;
height: 32px !important;
flex: 0 0 32px !important;
border-radius: 11px !important;
font-size: 17px !important;
}
#${PANEL_ID} .tm-body {
padding: 12px 14px 12px !important;
gap: 10px !important;
max-height: calc(100vh - 148px) !important;
}
/* 清晰度 + 编码:并排双列 */
#${PANEL_ID} .tm-pair {
display: grid !important;
grid-template-columns: 1fr 1fr !important;
gap: 9px !important;
}
#${PANEL_ID} .tm-pair .tm-row {
display: flex !important;
flex-direction: column !important;
align-items: stretch !important;
gap: 5px !important;
}
#${PANEL_ID} .tm-pair .tm-row label {
font-size: 10.5px !important;
letter-spacing: .4px !important;
color: rgba(236, 243, 255, .48) !important;
}
#${PANEL_ID} .tm-pair .tm-select-trigger {
height: 38px !important;
padding: 0 11px !important;
font-size: 12px !important;
border-radius: 12px !important;
}
#${PANEL_ID} .tm-pair .tm-select-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#${PANEL_ID} .tm-items {
max-height: 268px !important;
border-radius: 14px !important;
}
#${PANEL_ID} .tm-item {
min-height: 42px !important;
}
#${PANEL_ID} .tm-download-actions {
grid-template-columns: 1.35fr 1fr !important;
}
#${PANEL_ID} .tm-download-actions .tm-download {
min-height: 38px !important;
font-size: 12.5px !important;
}
#${PANEL_ID} .tm-subtitle-actions {
grid-template-columns: 1fr 1.2fr !important;
}
#${PANEL_ID} .tm-license {
margin-top: 2px;
font-size: 10px;
letter-spacing: .6px;
text-align: center;
color: rgba(236, 243, 255, .30);
user-select: none;
}
#${PANEL_ID}.minimized {
right: 20px !important;
width: 132px !important;
}
#${PANEL_ID}.minimized .tm-head {
height: 56px !important;
padding: 0 10px 0 12px !important;
gap: 4px !important;
}
#${PANEL_ID}.minimized .tm-brand {
width: 62px !important;
height: 56px !important;
flex: 0 0 62px !important;
}
#${PANEL_ID}.minimized .tm-brand-line {
width: 62px !important;
}
#${PANEL_ID}.minimized .tm-icon-btn {
width: 30px !important;
height: 30px !important;
flex-basis: 30px !important;
}
@media (max-height: 820px) {
#${PANEL_ID} .tm-items {
max-height: 210px !important;
}
}
@media (max-height: 700px) {
#${PANEL_ID} .tm-items {
max-height: 150px !important;
}
#${PANEL_ID} .tm-body {
gap: 8px !important;
}
#${PANEL_ID} .tm-license {
display: none !important;
}
}
@media (max-width: 1080px) {
#${PANEL_ID} {
left: 12px !important;
right: auto !important;
top: 72px !important;
width: min(392px, calc(100vw - 24px)) !important;
}
#${PANEL_ID}.minimized {
left: 12px !important;
right: auto !important;
}
}
`);
/* 窗口尺寸变化时,把拖到屏幕外的面板拉回来 */
window.addEventListener('resize', () => {
const panel = document.getElementById(PANEL_ID);
if (!panel || !panel.style.left) {
return;
}
const rect = panel.getBoundingClientRect();
const maxLeft = Math.max(0, window.innerWidth - panel.offsetWidth);
const maxTop = Math.max(0, window.innerHeight - panel.offsetHeight);
panel.style.left = `${Math.min(Math.max(0, rect.left), maxLeft)}px`;
panel.style.top = `${Math.min(Math.max(0, rect.top), maxTop)}px`;
panel.style.right = 'auto';
});
createPanel();
installSpaWatcher();
installFullscreenWatcher();
initPage()
.catch(
err => {
console.error(
'[BiliDL] init failed:',
err
);
setStatus(
`初始化失败:${err
?.message ||
err
}`,
'error'
);
}
);
})();
/*
* =========================================================
* 育才9班自用破解 · VIP 解析 / 直链下载
* 开源许可:MIT
* =========================================================
*/
(function () {
'use strict';
if (window.top !== window.self) {
return;
}
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: auto;
left: 16px;
bottom: 16px;
width: 352px;
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: 46px;
padding: 0 9px 0 14px;
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: 11px 13px 10px;
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: 220px;
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 = `
VIP 视频解析
${SITES.map(
site =>
``
).join('')}
B 站 1080P 下载
就绪
`;
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 ? '展开' : '收起';
if (!min) {
document.dispatchEvent(
new CustomEvent('yc9:expand', {
detail: { id: 'vip' },
})
);
}
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();
/* 其它面板展开时自动收起,避免窗口堆叠 */
document.addEventListener('yc9:expand', event => {
if (event.detail?.id === 'vip') {
return;
}
if (!dock.classList.contains('yc9-min')) {
const btn = dock.querySelector('.yc9-hbtn[data-act="min"]');
dock.classList.add('yc9-min');
if (btn) {
btn.textContent = '+';
btn.title = '展开';
}
}
});
/* 窗口缩放后把拖出视口的窗口拉回来 */
window.addEventListener('resize', () => {
if (!dock.style.left) {
return;
}
const rect = dock.getBoundingClientRect();
const maxLeft = Math.max(0, window.innerWidth - dock.offsetWidth);
const maxTop = Math.max(0, window.innerHeight - dock.offsetHeight);
dock.style.left = `${Math.min(Math.max(0, rect.left), maxLeft)}px`;
dock.style.top = `${Math.min(Math.max(0, rect.top), maxTop)}px`;
dock.style.right = 'auto';
dock.style.bottom = 'auto';
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot, { once: true });
} else {
boot();
}
})();
/*
* =========================================================
* 育才9班自用破解 · 播放控制面板
* 开源许可:MIT
* =========================================================
*/
(function () {
'use strict';
if (window.top !== window.self) {
return;
}
const PFX = 'vp2.';
const NAME = '播放控制';
/* ---------------------------------------------------------- 存储 */
const hasGM =
typeof GM_getValue === 'function' && typeof GM_setValue === 'function';
const store = {
get(key, fallback) {
try {
if (hasGM) {
const v = GM_getValue(PFX + key);
return v === undefined || v === null ? fallback : v;
}
const raw = localStorage.getItem(PFX + key);
return raw === null ? fallback : JSON.parse(raw);
} catch (err) {
return fallback;
}
},
set(key, value) {
try {
if (hasGM) {
GM_setValue(PFX + key, value);
} else {
localStorage.setItem(PFX + key, JSON.stringify(value));
}
} catch (err) {
/* 忽略 */
}
},
};
/* ---------------------------------------------------------- 站点 */
const SITES = [
{ id: 'bilibili', label: '哔哩哔哩', re: /(^|\.)bilibili\.com$/i },
{ id: 'iqiyi', label: '爱奇艺', re: /(^|\.)(iqiyi|iq)\.com$/i },
{ id: 'tencent', label: '腾讯视频', re: /(^|\.)qq\.com$/i },
{ id: 'youku', label: '优酷', re: /(^|\.)youku\.com$/i },
{ id: 'youtube', label: 'YouTube', re: /(^|\.)youtube\.com$/i },
];
const site = (function () {
const h = location.hostname;
for (const item of SITES) {
if (item.re.test(h)) {
return item;
}
}
return {
id: 'page',
label: location.hostname.replace(/^www\./, '') || '本地页面',
};
})();
const CLEAN = {
bilibili: [
'.ad-report',
'.video-card-ad-small',
'.slide-ad-exp',
'.bili-guide',
'.pop-live-small-mode',
'.bpx-player-row-dm-wrap > .bpx-player-ad',
'.fixed-sdanav',
],
iqiyi: ['.qy-player-ad', '[class*="qy-player-ad"]', '.qy-player-guide', '.iqp-ad'],
tencent: ['.txp_ad', '.txp_adv', '.mod_ad', '[class*="player-ad"]'],
youku: ['.youku-ad', '.h5-ext-layer', '[class*="ad-banner"]'],
youtube: ['#masthead-ad', 'ytd-display-ad-renderer', '#player-ads'],
};
const PRESETS = [0.5, 1, 1.5, 2, 3];
/* ---------------------------------------------------------- 状态 */
const S = {
speed: 1,
tone: store.get('tone', 'auto'),
collapsed: store.get('collapsed', true),
hidden: false,
drawer: false,
sw: {
resume: store.get('sw.resume', true),
clean: store.get('sw.clean', false),
keys: store.get('sw.keys', true),
remember: store.get('sw.remember', false),
},
pos: store.get('pos', null),
};
const posFromStore = !!(S.pos && typeof S.pos.x === 'number');
let video = null;
let pendingResume = null;
let cleanStyle = null;
let restoreFS = null;
let restoreMirror = null;
let saveTimer = 0;
let toastTimer = 0;
let lastStat = '';
let mounted = false;
let userMoved = !!store.get('moved', false);
/* ---------------------------------------------------------- 工具 */
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
function fmtTime(t) {
if (!isFinite(t) || t < 0) {
return '--:--';
}
const total = Math.floor(t);
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
const mm = (m < 10 ? '0' : '') + m;
const ss = (s < 10 ? '0' : '') + s;
return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
}
function fmtSpeed(v) {
return (v >= 10 ? v.toFixed(1) : v.toFixed(2).replace(/(\.\d)0$/, '$1')) + '×';
}
/* ---------------------------------------------------------- 样式 */
const CSS = String.raw`
:host {
all: initial;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
.vp-dock {
position: fixed;
pointer-events: auto;
left: 0;
top: 0;
width: var(--vp-w, 300px);
transform: translate3d(var(--vp-x, 0px), var(--vp-y, 0px), 0);
z-index: 2147483000;
font-family: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", system-ui,
-apple-system, "Segoe UI", sans-serif;
font-size: 12.5px;
line-height: 1.45;
color: #f2f5fa;
-webkit-font-smoothing: antialiased;
contain: layout style;
}
.vp-dock.is-collapsed {
width: auto;
}
.vp-dock.is-hidden {
display: none !important;
}
/* ---------- 卡片 ---------- */
.vp-card {
position: relative;
border-radius: 22px;
max-height: calc(100vh - 32px);
overflow-x: hidden;
overflow-y: auto;
isolation: isolate;
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.22) transparent;
color: var(--fg);
background:
radial-gradient(120% 80% at 12% -10%, rgba(255, 255, 255, 0.26), rgba(255, 255, 255, 0) 54%),
radial-gradient(100% 90% at 102% 112%, rgba(255, 176, 87, 0.22), rgba(0, 0, 0, 0) 62%),
linear-gradient(160deg, rgba(48, 44, 38, 0.66), rgba(11, 12, 15, 0.64));
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.55),
inset 0 0 0 1px rgba(255, 255, 255, 0.05),
inset 0 -26px 46px -30px rgba(255, 255, 255, 0.18),
0 26px 60px rgba(0, 0, 0, 0.46),
0 2px 8px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(30px) saturate(175%);
-webkit-backdrop-filter: blur(30px) saturate(175%);
animation: vp-in 200ms ease-out both;
}
.vp-card {
--fg: #f2f5fa;
--fg2: rgba(242, 245, 250, 0.66);
--fg3: rgba(242, 245, 250, 0.42);
--line: rgba(255, 255, 255, 0.14);
--plate: rgba(255, 255, 255, 0.06);
--plate2: rgba(255, 255, 255, 0.12);
--accent: #ffb057;
--accent2: #ff7a59;
--ink: #2a1705;
}
.vp-card::-webkit-scrollbar {
width: 6px;
}
.vp-card::-webkit-scrollbar-thumb {
border-radius: 99px;
background: rgba(255, 255, 255, 0.2);
}
.vp-card[data-tone="light"] {
--fg: #141a22;
--fg2: rgba(20, 26, 34, 0.68);
--fg3: rgba(20, 26, 34, 0.46);
--line: rgba(20, 26, 34, 0.14);
--plate: rgba(20, 26, 34, 0.05);
--plate2: rgba(20, 26, 34, 0.1);
--accent: #b4661b;
--accent2: #c25a2a;
--ink: #ffffff;
background:
linear-gradient(168deg, rgba(255, 255, 255, 0.95), rgba(250, 251, 253, 0.9) 48%, rgba(255, 255, 255, 0.94)),
rgba(255, 255, 255, 0.62);
border-color: rgba(255, 255, 255, 0.98);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 1),
inset 0 0 0 1px rgba(255, 255, 255, 0.6),
0 22px 50px -22px rgba(15, 23, 42, 0.38);
}
.vp-card[data-tone="light"] .vp-sw,
.vp-card[data-tone="light"] .vp-bar,
.vp-card[data-tone="light"] .vp-tool {
background: rgba(20, 26, 34, 0.04);
}
.vp-card[data-tone="light"] .vp-tool:hover,
.vp-card[data-tone="light"] .vp-sw:hover {
background: rgba(20, 26, 34, 0.08);
}
.vp-card[data-tone="light"] .vp-bar {
background: rgba(20, 26, 34, 0.1);
}
.vp-card[data-tone="light"] .vp-tone button.is-on,
.vp-card[data-tone="light"] .vp-presets {
background: rgba(20, 26, 34, 0.06);
}
.vp-card[data-tone="light"] .vp-tone button.is-on {
background: rgba(20, 26, 34, 0.1);
}
@keyframes vp-in {
from {
opacity: 0;
transform: translateY(8px) scale(0.985);
}
to {
opacity: 1;
transform: none;
}
}
.vp-sheen {
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
z-index: 1;
background:
radial-gradient(120% 44% at 50% -12%, rgba(255, 255, 255, 0.22), transparent 62%),
linear-gradient(100deg, rgba(255, 255, 255, 0.06), transparent 34%, transparent 68%, rgba(255, 255, 255, 0.05));
}
/* ---------- 头部 ---------- */
.vp-head {
position: relative;
z-index: 5;
display: flex;
align-items: center;
gap: 8px;
height: 42px;
padding: 0 8px 0 12px;
cursor: grab;
user-select: none;
touch-action: none;
}
.vp-head.is-drag {
cursor: grabbing;
}
.vp-tile {
flex: 0 0 auto;
width: 21px;
height: 21px;
display: grid;
place-items: center;
border-radius: 7px;
color: var(--accent);
background: var(--plate);
border: 1px solid var(--line);
}
.vp-tile svg {
width: 11px;
height: 11px;
fill: currentColor;
}
.vp-name {
flex: 1 1 auto;
min-width: 0;
font-size: 12px;
font-weight: 600;
letter-spacing: 0.3px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.vp-mini {
display: flex;
gap: 1px;
flex: 0 0 auto;
}
.vp-iconbtn {
width: 24px;
height: 24px;
display: grid;
place-items: center;
padding: 0;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--fg3);
font: inherit;
font-size: 12px;
line-height: 1;
cursor: pointer;
transition: background 140ms ease, color 140ms ease;
}
.vp-iconbtn:hover {
background: var(--plate);
color: var(--fg);
}
.vp-iconbtn:active {
opacity: 0.65;
}
/* ---------- 速度 ---------- */
.vp-speed {
position: relative;
z-index: 5;
padding: 0 14px;
}
.vp-readout {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 10px;
}
.vp-value {
display: flex;
align-items: baseline;
gap: 1px;
color: var(--fg);
font-variant-numeric: tabular-nums;
}
.vp-value b {
font-size: 26px;
font-weight: 700;
letter-spacing: -0.6px;
line-height: 1;
}
.vp-value b.is-hot {
color: var(--accent);
text-shadow: 0 0 16px rgba(255, 176, 87, 0.45);
}
.vp-value i {
font-style: normal;
font-size: 11px;
color: var(--fg3);
}
.vp-hint {
font-size: 10.5px;
color: var(--fg3);
text-align: right;
white-space: nowrap;
}
.vp-range {
display: block;
width: 100%;
height: 20px;
margin: 7px 0 0;
background: transparent;
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
.vp-range::-webkit-slider-runnable-track {
height: 6px;
border-radius: 99px;
background: linear-gradient(
90deg,
var(--accent) 0%,
var(--accent2) var(--vp-fill, 42%),
rgba(255, 255, 255, 0.14) var(--vp-fill, 42%),
rgba(255, 255, 255, 0.14) 100%
);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.35);
}
.vp-range::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
margin-top: -5px;
border: none;
border-radius: 50%;
background: radial-gradient(circle at 34% 28%, #ffffff, #ffe6c9 58%, #ffb057);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(255, 255, 255, 0.55);
transition: box-shadow 140ms ease, transform 140ms ease;
}
.vp-range:hover::-webkit-slider-thumb {
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.45), 0 0 0 6px rgba(255, 176, 87, 0.16);
}
.vp-range:active::-webkit-slider-thumb {
transform: scale(1.06);
}
.vp-range::-moz-range-track {
height: 6px;
border-radius: 99px;
background: rgba(255, 255, 255, 0.14);
}
.vp-range::-moz-range-progress {
height: 6px;
border-radius: 99px;
background: var(--accent);
}
.vp-range::-moz-range-thumb {
width: 15px;
height: 15px;
border: none;
border-radius: 50%;
background: #fbfdff;
}
/* ---------- 预设档 ---------- */
.vp-presets {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 2px;
margin-top: 3px;
padding: 3px;
border-radius: 12px;
border: 1px solid var(--line);
background: var(--plate);
}
.vp-preset {
height: 26px;
padding: 0;
border: 0;
border-radius: 9px;
background: transparent;
color: var(--fg2);
font: inherit;
font-size: 11px;
font-variant-numeric: tabular-nums;
cursor: pointer;
transition: background 140ms ease, color 140ms ease;
}
.vp-preset:hover {
background: var(--plate2);
color: var(--fg);
}
.vp-preset.is-on {
color: var(--ink);
font-weight: 700;
background: linear-gradient(180deg, var(--accent), var(--accent2));
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.5), 0 4px 10px rgba(255, 122, 89, 0.28);
}
/* ---------- 工具 ---------- */
.vp-tools {
position: relative;
z-index: 5;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
padding: 10px 14px 0;
}
.vp-tool {
height: 38px;
display: grid;
place-items: center;
padding: 0;
border-radius: 13px;
border: 1px solid var(--line);
background: var(--plate);
color: var(--fg2);
font: inherit;
font-size: 10px;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.22);
transition: background 140ms ease, color 140ms ease, border-color 140ms ease;
}
.vp-tool svg {
width: 16px;
height: 16px;
fill: none;
stroke: currentColor;
stroke-width: 1.6;
stroke-linecap: round;
stroke-linejoin: round;
}
.vp-tool:hover {
background: var(--plate2);
color: var(--fg);
}
.vp-tool:active {
opacity: 0.7;
}
.vp-tool.is-on {
color: var(--accent);
border-color: rgba(255, 176, 87, 0.45);
background: rgba(255, 176, 87, 0.13);
}
/* ---------- 更多 ---------- */
.vp-more {
position: relative;
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
width: calc(100% - 28px);
height: 30px;
margin: 8px 14px 0;
padding: 0 2px;
border: 0;
background: transparent;
color: var(--fg3);
font: inherit;
font-size: 10.5px;
cursor: pointer;
transition: color 140ms ease;
}
.vp-more:hover {
color: var(--fg2);
}
.vp-more .vp-caret {
font-size: 9px;
transition: transform 180ms ease;
}
.vp-more.is-open .vp-caret {
transform: rotate(180deg);
}
.vp-drawer {
display: none;
flex-direction: column;
gap: 8px;
padding: 0 14px 2px;
}
.vp-drawer.is-open {
display: flex;
animation: vp-fade 160ms ease-out both;
}
@keyframes vp-fade {
from {
opacity: 0;
transform: translateY(-4px);
}
to {
opacity: 1;
transform: none;
}
}
.vp-duo {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.vp-duo .vp-tool {
height: 34px;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.vp-duo .vp-tool svg {
width: 14px;
height: 14px;
}
.vp-duo .vp-tool span {
font-size: 10.5px;
letter-spacing: 0.2px;
}
.vp-tone {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2px;
padding: 3px;
border-radius: 12px;
border: 1px solid var(--line);
background: var(--plate);
}
.vp-tone button {
height: 26px;
padding: 0;
border: 0;
border-radius: 9px;
background: transparent;
color: var(--fg2);
font: inherit;
font-size: 10.5px;
cursor: pointer;
transition: background 140ms ease, color 140ms ease;
}
.vp-tone button:hover {
color: var(--fg);
}
.vp-tone button.is-on {
color: var(--fg);
background: var(--plate2);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3);
}
.vp-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.vp-sw {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.03);
color: var(--fg);
font: inherit;
text-align: left;
cursor: pointer;
transition: background 140ms ease;
}
.vp-sw:hover {
background: var(--plate);
}
.vp-sw .vp-txt {
flex: 1 1 auto;
min-width: 0;
display: flex;
flex-direction: column;
}
.vp-sw b {
font-size: 11.5px;
font-weight: 500;
}
.vp-sw i {
font-style: normal;
font-size: 10px;
color: var(--fg3);
}
.vp-toggle {
flex: 0 0 auto;
width: 28px;
height: 16px;
border-radius: 99px;
background: rgba(255, 255, 255, 0.18);
position: relative;
transition: background 180ms ease;
}
.vp-toggle::after {
content: "";
position: absolute;
top: 2px;
left: 2px;
width: 12px;
height: 12px;
border-radius: 50%;
background: #fff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35);
transition: transform 180ms ease;
}
.vp-sw[data-on="1"] .vp-toggle {
background: linear-gradient(180deg, var(--accent), var(--accent2));
}
.vp-sw[data-on="1"] .vp-toggle::after {
transform: translateX(12px);
}
/* ---------- 底栏 ---------- */
.vp-foot {
position: relative;
z-index: 5;
padding: 10px 14px 11px;
}
.vp-bar {
height: 3px;
margin-bottom: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.12);
}
.vp-bar i {
display: block;
width: 0;
height: 100%;
border-radius: 99px;
background: linear-gradient(90deg, var(--accent), var(--accent2));
transition: width 220ms linear;
}
.vp-stat {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
font-size: 10px;
color: var(--fg3);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.vp-dot {
flex: 0 0 auto;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--accent);
}
.vp-dot.is-idle {
background: var(--fg3);
}
/* ---------- 提示 ---------- */
.vp-toast {
position: absolute;
left: 12px;
right: 12px;
bottom: 12px;
z-index: 20;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-radius: 12px;
font-size: 11px;
color: var(--fg);
background: rgba(20, 18, 16, 0.96);
border: 1px solid rgba(255, 176, 87, 0.34);
box-shadow: 0 14px 30px -16px rgba(0, 0, 0, 0.85);
opacity: 0;
transform: translateY(6px);
pointer-events: none;
transition: opacity 160ms ease, transform 160ms ease;
}
.vp-toast.is-show {
opacity: 1;
transform: none;
pointer-events: auto;
}
.vp-card[data-tone="light"] .vp-toast {
background: rgba(253, 252, 250, 0.98);
border-color: rgba(180, 102, 27, 0.3);
color: var(--fg);
}
.vp-toast span {
flex: 1 1 auto;
min-width: 0;
}
.vp-toast button {
flex: 0 0 auto;
height: 22px;
padding: 0 9px;
border: 0;
border-radius: 8px;
background: var(--accent);
color: var(--ink);
font: inherit;
font-size: 10.5px;
font-weight: 600;
cursor: pointer;
}
/* ---------- 收起后的窄条 ---------- */
.vp-strip {
display: none;
align-items: center;
gap: 7px;
height: 38px;
padding: 0 11px 0 5px;
border-radius: 99px;
border: 1px solid rgba(255, 255, 255, 0.22);
background:
linear-gradient(160deg, rgba(255, 255, 255, 0.16), rgba(255, 255, 255, 0.05)),
rgba(16, 16, 18, 0.68);
backdrop-filter: blur(20px) saturate(170%);
-webkit-backdrop-filter: blur(20px) saturate(170%);
box-shadow: 0 12px 28px -14px rgba(0, 0, 0, 0.72), inset 0 1px 0 rgba(255, 255, 255, 0.24);
cursor: pointer;
user-select: none;
touch-action: none;
}
.vp-strip:hover {
transform: translateY(-1px);
}
.vp-strip .vp-tile {
width: 26px;
height: 26px;
border-radius: 50%;
}
.vp-strip b {
font-size: 11.5px;
font-weight: 700;
color: #ffb057;
font-variant-numeric: tabular-nums;
}
.vp-strip i {
font-style: normal;
font-size: 10px;
color: rgba(242, 245, 250, 0.5);
font-variant-numeric: tabular-nums;
}
.vp-strip .vp-chev {
font-size: 11px;
color: rgba(242, 245, 250, 0.42);
}
.vp-dock.is-collapsed .vp-card {
display: none;
}
.vp-dock.is-collapsed .vp-strip {
display: flex;
}
@media (max-width: 560px) {
.vp-dock {
width: var(--vp-w, 280px);
}
}
@media (prefers-reduced-motion: reduce) {
.vp-card,
.vp-drawer.is-open {
animation: none;
}
}
`;
/* ---------------------------------------------------------- 图标 */
const ICONS = {
pip: '',
shot:
'',
full:
'',
mute:
'',
loop:
'',
mirror:
'',
};
const MARK = '';
const toolHTML = (key, icon, label) =>
``;
const duoHTML = (key, icon, label) =>
``;
/* ---------------------------------------------------------- 骨架 */
const host = document.createElement('div');
host.id = 'yc9-vplay';
[
['position', 'fixed'],
['left', '0'],
['top', '0'],
['width', '0'],
['height', '0'],
['display', 'block'],
['z-index', '2147483000'],
['pointer-events', 'none'],
].forEach(([k, v]) => host.style.setProperty(k, v, 'important'));
const root = host.attachShadow({ mode: 'open' });
const styleTag = document.createElement('style');
styleTag.textContent = CSS;
root.appendChild(styleTag);
const wrap = document.createElement('div');
wrap.className = 'vp-dock';
wrap.innerHTML = `
${toolHTML('pip', 'pip', '画中画')}
${toolHTML('shot', 'shot', '截图')}
${toolHTML('full', 'full', '全屏')}
${toolHTML('mute', 'mute', '静音')}
${duoHTML('loop', 'loop', '循环播放')}
${duoHTML('mirror', 'mirror', '画面镜像')}
`;
root.appendChild(wrap);
const $ = sel => wrap.querySelector(sel);
const el = {
dock: wrap,
card: $('.vp-card'),
head: $('.vp-head'),
range: $('.vp-range'),
value: $('.vp-value b'),
hint: $('.vp-hint'),
presets: $('.vp-presets'),
tools: $('.vp-tools'),
more: $('.vp-more'),
drawer: $('.vp-drawer'),
tone: $('.vp-tone'),
stat: $('.vp-stat-txt'),
dot: $('.vp-dot'),
bar: $('.vp-bar i'),
toast: $('.vp-toast'),
toastMsg: $('.vp-toast span'),
strip: $('.vp-strip'),
stripSpeed: $('.vp-strip b'),
stripTime: $('.vp-strip i'),
};
/* 让交互只作用于面板本身,不触发站点快捷键 */
['click', 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'dblclick', 'wheel'].forEach(ev =>
host.addEventListener(
ev,
e => {
if (ev !== 'wheel' || e.target.closest('.vp-range')) {
e.stopPropagation();
}
},
{ passive: true }
)
);
/* ---------------------------------------------------------- 外观 */
function resolvedTone() {
if (S.tone === 'light' || S.tone === 'dark') {
return S.tone;
}
try {
const bg = getComputedStyle(document.body || document.documentElement).backgroundColor;
const m = /rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/.exec(bg);
if (m) {
const alpha = m[4] === undefined ? 1 : parseFloat(m[4]);
if (alpha > 0.2) {
const lum = (0.299 * +m[1] + 0.587 * +m[2] + 0.114 * +m[3]) / 255;
return lum > 0.6 ? 'light' : 'dark';
}
}
} catch (err) {
/* 忽略 */
}
return 'dark';
}
function applyTone() {
const tone = resolvedTone();
el.card.setAttribute('data-tone', tone);
wrap.setAttribute('data-tone', tone);
el.tone.querySelectorAll('button').forEach(btn => {
btn.classList.toggle('is-on', btn.dataset.toneSet === S.tone);
});
}
/* ---------------------------------------------------------- 提示 */
function hideToast() {
el.toast.classList.remove('is-show');
}
function toast(msg, opt = {}) {
el.toastMsg.textContent = msg;
const old = el.toast.querySelector('button');
if (old) {
old.remove();
}
if (opt.action) {
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = opt.action.label;
btn.addEventListener('click', () => {
opt.action.fn();
hideToast();
});
el.toast.appendChild(btn);
}
el.toast.classList.add('is-show');
clearTimeout(toastTimer);
toastTimer = setTimeout(hideToast, opt.timeout || 2400);
}
/* ---------------------------------------------------------- 停靠 */
function measure() {
const r = el.dock.getBoundingClientRect();
return { w: r.width || 300, h: r.height || 260 };
}
function place(x, y) {
const m = measure();
const maxX = Math.max(8, window.innerWidth - m.w - 8);
const maxY = Math.max(8, window.innerHeight - m.h - 8);
S.pos = {
x: Math.round(clamp(x, 8, maxX)),
y: Math.round(clamp(y, 8, maxY)),
};
wrap.style.setProperty('--vp-x', `${S.pos.x}px`);
wrap.style.setProperty('--vp-y', `${S.pos.y}px`);
}
function rectOf(selector) {
const node = document.querySelector(selector);
if (!node) {
return null;
}
const r = node.getBoundingClientRect();
return r.width && r.height ? r : null;
}
function hits(a, b) {
return !!b && a.left < b.right - 4 && a.right > b.left + 4 && a.top < b.bottom - 4 && a.bottom > b.top + 4;
}
/* 默认停靠底部居中;若与其它窗口相撞,自动换到不重叠的位置 */
function dockToCenterBottom() {
const m = measure();
const bottom = window.innerHeight - m.h - 18;
const center = (window.innerWidth - m.w) / 2;
const others = [
rectOf('#tm-bili-downloader'),
rectOf('#yc9-dock'),
].filter(Boolean);
const tried = [
[center, bottom],
[window.innerWidth - m.w - 18, bottom],
[18, bottom],
[center, 90],
];
let chosen = tried[0];
for (const [x, y] of tried) {
const box = {
left: x,
top: y,
right: x + m.w,
bottom: y + m.h,
};
if (!others.some(other => hits(box, other))) {
chosen = [x, y];
break;
}
}
place(chosen[0], chosen[1]);
}
/* 被别的窗口压住时自动挪到空位(用户手动拖过就不再干预) */
function avoidWalls() {
if (userMoved || !S.pos) {
return;
}
const m = measure();
const self = {
left: S.pos.x,
top: S.pos.y,
right: S.pos.x + m.w,
bottom: S.pos.y + m.h,
};
const others = [rectOf('#tm-bili-downloader'), rectOf('#yc9-dock')].filter(Boolean);
if (others.some(other => hits(self, other))) {
dockToCenterBottom();
}
}
/* 对方展开有自己的排版节奏,延后两次再判重叠更稳 */
function scheduleAvoid() {
setTimeout(avoidWalls, 90);
setTimeout(avoidWalls, 320);
}
/* 尺寸变化时按最近的边锚定,避免面板"跳走"或被挤到屏幕外 */
function placeKeeping(prev) {
const m = measure();
const centerX = prev.left + prev.width / 2;
const nearRight = prev.right > window.innerWidth - 140;
const nearLeft = prev.left < 140;
const nearBottom = prev.top + prev.height / 2 > window.innerHeight / 2;
let x = centerX - m.w / 2;
if (nearRight) {
x = prev.right - m.w;
} else if (nearLeft) {
x = prev.left;
}
place(x, nearBottom ? prev.bottom - m.h : prev.top);
}
function dragify() {
let start = null;
const onDown = e => {
if (e.button !== 0) {
return;
}
if (e.target.closest('button') || e.target.closest('.vp-range')) {
return;
}
if (!e.target.closest('.vp-head') && !e.target.closest('.vp-strip')) {
return;
}
const base = S.pos || { x: 0, y: 0 };
start = { px: e.clientX, py: e.clientY, x: base.x, y: base.y };
el.head.classList.add('is-drag');
host.style.setProperty('z-index', String(2147483200), 'important');
try {
e.target.setPointerCapture(e.pointerId);
} catch (err) {
/* 忽略 */
}
e.preventDefault();
};
const onMove = e => {
if (!start) {
return;
}
place(start.x + (e.clientX - start.px), start.y + (e.clientY - start.py));
};
const onUp = () => {
if (!start) {
return;
}
start = null;
el.head.classList.remove('is-drag');
host.style.setProperty('z-index', '2147483000', 'important');
userMoved = true;
store.set('moved', true);
store.set('pos', S.pos);
};
wrap.addEventListener('pointerdown', onDown);
wrap.addEventListener('pointermove', onMove);
wrap.addEventListener('pointerup', onUp);
wrap.addEventListener('pointercancel', onUp);
}
/* ---------------------------------------------------------- 播放器 */
function pickVideo() {
const list = document.querySelectorAll('video');
let best = null;
let area = -1;
for (const node of list) {
const r = node.getBoundingClientRect();
const a = Math.max(0, r.width) * Math.max(0, r.height);
if (a > area) {
area = a;
best = node;
}
}
return best && area > 0 ? best : list[0] || null;
}
function bindVideo(node) {
if (!node || node === video) {
return;
}
if (video) {
video.removeEventListener('loadedmetadata', onMeta);
video.removeEventListener('ratechange', onRate);
video.removeEventListener('timeupdate', onTick);
}
video = node;
video.addEventListener('loadedmetadata', onMeta);
video.addEventListener('ratechange', onRate);
video.addEventListener('timeupdate', onTick);
if (S.sw.remember && S.speed !== 1) {
try {
video.playbackRate = S.speed;
} catch (err) {
/* 忽略 */
}
}
onMeta();
updateStat();
}
const progKey = () => location.origin + location.pathname;
function onMeta() {
if (!video) {
return;
}
updateStat();
if (!S.sw.resume) {
return;
}
const rec = store.get(`prog.${progKey()}`, null);
if (!rec || !rec.t) {
return;
}
const d = video.duration;
if (!isFinite(d) || d < 60) {
return;
}
if (rec.t < 15 || d - rec.t < 30) {
return;
}
if (Date.now() - (rec.ts || 0) > 30 * 24 * 3600 * 1000) {
return;
}
pendingResume = rec.t;
toast(`上次看到 ${fmtTime(rec.t)}`, {
action: {
label: '接着看',
fn() {
try {
video.currentTime = pendingResume;
} catch (err) {
/* 忽略 */
}
pendingResume = null;
toast(`已跳到 ${fmtTime(video.currentTime)}`);
},
},
timeout: 9000,
});
}
function onRate() {
if (!video || !S.sw.remember) {
return;
}
if (Math.abs(video.playbackRate - S.speed) > 0.01) {
try {
video.playbackRate = S.speed;
} catch (err) {
/* 忽略 */
}
}
}
function onTick() {
updateStat();
if (!S.sw.resume) {
return;
}
const now = Date.now();
if (now - saveTimer < 5000) {
return;
}
saveTimer = now;
if (!video || video.paused) {
return;
}
store.set(`prog.${progKey()}`, {
t: Math.round(video.currentTime),
d: Math.round(video.duration || 0),
ts: now,
});
}
function updateStat() {
if (!el.stat) {
return;
}
let text = '';
let ratio = 0;
let timeText = '--:--';
if (!video) {
text = `${site.label} · 未找到播放器`;
el.dot.classList.add('is-idle');
} else {
const w = video.videoWidth || 0;
const h = video.videoHeight || 0;
const cur = video.currentTime || 0;
const dur = video.duration || 0;
timeText = fmtTime(cur);
if (isFinite(dur) && dur > 0) {
ratio = clamp((cur / dur) * 100, 0, 100);
}
text = `${w && h ? `${w}×${h}` : site.label} · ${fmtTime(cur)} / ${fmtTime(dur)}`;
el.dot.classList.toggle('is-idle', video.paused);
}
el.hint.textContent = video ? (video.paused ? '已暂停' : '正在播放') : '未找到播放器';
if (text !== lastStat) {
lastStat = text;
el.stat.textContent = text;
}
el.bar.style.width = `${ratio}%`;
el.stripTime.textContent = timeText;
}
/* ---------------------------------------------------------- 倍速 */
const sliderToSpeed = t => 0.1 * Math.pow(160, t);
const speedToSlider = v => Math.log(clamp(v, 0.1, 16) / 0.1) / Math.log(160);
function paintSpeed() {
const t = speedToSlider(S.speed);
el.range.value = String(Math.round(t * 1000));
el.range.style.setProperty('--vp-fill', `${(t * 100).toFixed(1)}%`);
el.value.textContent = fmtSpeed(S.speed).replace('×', '') + '×';
el.stripSpeed.textContent = fmtSpeed(S.speed);
el.presets.querySelectorAll('.vp-preset').forEach(btn => {
btn.classList.toggle(
'is-on',
Math.abs(parseFloat(btn.dataset.speed) - S.speed) < 0.005
);
});
}
function setSpeed(v, quiet) {
const next = Math.round(clamp(v, 0.1, 16) * 100) / 100;
S.speed = next;
if (video) {
try {
video.playbackRate = next;
} catch (err) {
/* 忽略 */
}
}
paintSpeed();
el.value.classList.add('is-hot');
setTimeout(() => el.value.classList.remove('is-hot'), 280);
if (!quiet && S.sw.remember) {
store.set('speed', next);
}
}
function stepSpeed(dir) {
let v = S.speed;
if (dir > 0) {
v = v < 3.99 ? v + 0.25 : v * 1.5;
} else {
v = v <= 4.01 ? v - 0.25 : v / 1.5;
}
setSpeed(v);
toast(fmtSpeed(S.speed), { timeout: 1000 });
}
/* ---------------------------------------------------------- 动作 */
function needVideo() {
bindVideo(pickVideo());
if (!video) {
toast('这个页面没有播放器');
return null;
}
return video;
}
function setAct(key, on) {
const btn = wrap.querySelector(`[data-act="${key}"]`);
if (btn) {
btn.classList.toggle('is-on', !!on);
}
}
function togglePip() {
const v = needVideo();
if (!v) {
return;
}
try {
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
setAct('pip', false);
return;
}
const p = v.requestPictureInPicture();
if (p && p.then) {
p.then(() => setAct('pip', true)).catch(() => toast('这个浏览器不支持画中画'));
}
} catch (err) {
toast('这个浏览器不支持画中画');
}
}
function shoot() {
const v = needVideo();
if (!v) {
return;
}
const w = v.videoWidth;
const h = v.videoHeight;
if (!w || !h) {
toast('画面还没加载完');
return;
}
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
try {
canvas.getContext('2d').drawImage(v, 0, 0, w, h);
} catch (err) {
toast('画面受跨域限制,取不到');
return;
}
try {
canvas.toBlob(blob => {
if (!blob) {
toast('截图失败');
return;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${site.id}-${fmtTime(v.currentTime).replace(/:/g, '')}.png`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 5000);
toast(`已保存 ${w}×${h}`);
}, 'image/png');
} catch (err) {
toast('画面受跨域限制,存不下来');
}
}
function toggleFull() {
const v = needVideo();
if (!v) {
return;
}
if (restoreFS) {
restoreFS();
restoreFS = null;
setAct('full', false);
host.style.setProperty('z-index', '2147483000', 'important');
return;
}
const st = v.style;
const prev = {};
['position', 'inset', 'left', 'top', 'width', 'height', 'maxWidth', 'maxHeight', 'objectFit', 'background', 'zIndex', 'transform', 'margin'].forEach(
k => {
prev[k] = st[k];
}
);
st.position = 'fixed';
st.inset = '0px';
st.left = '0px';
st.top = '0px';
st.width = '100vw';
st.height = '100vh';
st.maxWidth = 'none';
st.maxHeight = 'none';
st.objectFit = 'contain';
st.background = '#000';
st.zIndex = '2147483100';
st.margin = '0';
if (restoreMirror) {
st.transform = 'scaleX(-1)';
}
/* 面板压在视频之上,保证按钮仍可点击 */
host.style.setProperty('z-index', '2147483300', 'important');
restoreFS = () => {
Object.keys(prev).forEach(k => {
st[k] = prev[k];
});
};
setAct('full', true);
}
function toggleMute() {
const v = needVideo();
if (!v) {
return;
}
v.muted = !v.muted;
setAct('mute', v.muted);
toast(v.muted ? '已静音' : '已开启声音', { timeout: 1000 });
}
function toggleLoop() {
const v = needVideo();
if (!v) {
return;
}
v.loop = !v.loop;
setAct('loop', v.loop);
toast(v.loop ? '循环播放' : '取消循环', { timeout: 1000 });
}
function toggleMirror() {
const v = needVideo();
if (!v) {
return;
}
if (restoreMirror) {
restoreMirror();
restoreMirror = null;
setAct('mirror', false);
return;
}
const st = v.style;
const prev = st.transform;
st.transform = 'scaleX(-1)';
restoreMirror = () => {
st.transform = prev;
};
setAct('mirror', true);
}
/* ---------------------------------------------------------- 净化 */
function applyClean(on) {
S.sw.clean = on;
store.set('sw.clean', on);
if (!cleanStyle) {
cleanStyle = document.createElement('style');
cleanStyle.id = 'yc9-clean';
document.head.appendChild(cleanStyle);
}
const sel = (CLEAN[site.id] || []).slice();
cleanStyle.textContent =
on && sel.length ? `${sel.join(',\n')}{display:none !important;}` : '';
}
/* ---------------------------------------------------------- 键盘 */
function isEditable(t) {
if (!t) {
return false;
}
const tag = (t.tagName || '').toLowerCase();
return tag === 'input' || tag === 'textarea' || tag === 'select' || t.isContentEditable;
}
function onKey(e) {
if (!S.sw.keys) {
return;
}
if (e.ctrlKey || e.altKey || e.metaKey || !e.shiftKey) {
return;
}
if (isEditable(e.target)) {
return;
}
let handled = true;
switch (e.code) {
case 'Comma':
stepSpeed(-1);
break;
case 'Period':
stepSpeed(1);
break;
case 'KeyD':
shoot();
break;
case 'KeyP':
togglePip();
break;
case 'KeyF':
toggleFull();
break;
case 'KeyH':
setHidden(!S.hidden);
break;
default:
handled = false;
}
if (handled) {
e.preventDefault();
e.stopPropagation();
}
}
/* ---------------------------------------------------------- 显隐 */
function setHidden(hidden) {
if (hidden && !S.hidden) {
toast('已隐藏,Shift+H 恢复', { timeout: 1500 });
S.hidden = true;
setTimeout(() => {
if (S.hidden) {
wrap.classList.add('is-hidden');
}
}, 700);
return;
}
S.hidden = hidden;
wrap.classList.toggle('is-hidden', hidden);
}
function setCollapsed(collapsed) {
if (S.collapsed === collapsed) {
return;
}
const before = el.dock.getBoundingClientRect();
S.collapsed = collapsed;
wrap.classList.toggle('is-collapsed', collapsed);
store.set('collapsed', collapsed);
placeKeeping(before);
store.set('pos', S.pos);
if (!collapsed) {
document.dispatchEvent(
new CustomEvent('yc9:expand', { detail: { id: 'vp' } })
);
}
}
function setDrawer(open) {
const before = el.dock.getBoundingClientRect();
S.drawer = open;
el.drawer.classList.toggle('is-open', open);
el.more.classList.toggle('is-open', open);
el.more.setAttribute('aria-expanded', open ? 'true' : 'false');
placeKeeping(before);
store.set('pos', S.pos);
}
/* ---------------------------------------------------------- 事件 */
wrap.addEventListener('click', e => {
const btn = e.target.closest('button');
if (!btn) {
if (e.target.closest('.vp-strip')) {
setCollapsed(false);
}
return;
}
const act = btn.dataset.act;
if (act) {
if (act === 'more') {
setDrawer(!S.drawer);
} else if (act === 'collapse') {
setCollapsed(true);
} else if (act === 'hide') {
setHidden(true);
} else if (act === 'pip') {
togglePip();
} else if (act === 'shot') {
shoot();
} else if (act === 'full') {
toggleFull();
} else if (act === 'mute') {
toggleMute();
} else if (act === 'loop') {
toggleLoop();
} else if (act === 'mirror') {
toggleMirror();
}
return;
}
if (btn.dataset.speed) {
setSpeed(parseFloat(btn.dataset.speed));
return;
}
if (btn.dataset.toneSet) {
S.tone = btn.dataset.toneSet;
store.set('tone', S.tone);
applyTone();
return;
}
const sw = btn.dataset.sw;
if (sw) {
const on = btn.dataset.on !== '1';
btn.dataset.on = on ? '1' : '0';
S.sw[sw] = on;
store.set(`sw.${sw}`, on);
if (sw === 'clean') {
applyClean(on);
}
if (sw === 'resume' && !on) {
pendingResume = null;
}
if (sw === 'remember') {
if (on) {
store.set('speed', S.speed);
} else {
S.speed = 1;
if (video) {
video.playbackRate = 1;
}
paintSpeed();
}
}
toast(
`${on ? '已开启 ' : '已关闭 '}${btn.querySelector('b').textContent}`,
{ timeout: 1200 }
);
}
});
el.range.addEventListener('input', () => {
setSpeed(sliderToSpeed(parseInt(el.range.value, 10) / 1000), true);
});
el.range.addEventListener('change', () => {
if (S.sw.remember) {
store.set('speed', S.speed);
}
});
el.range.addEventListener(
'wheel',
e => {
e.preventDefault();
stepSpeed(e.deltaY < 0 ? 1 : -1);
},
{ passive: false }
);
window.addEventListener('keydown', onKey, true);
/* 其它面板展开时自动收起 */
document.addEventListener('yc9:expand', event => {
if (event.detail?.id === 'vp') {
return;
}
if (!S.collapsed) {
setCollapsed(true);
}
scheduleAvoid();
});
/* 窗口缩放:宽度自适应 + 位置夹取(不跳位、不出屏) */
window.addEventListener('resize', () => {
const width = window.innerWidth < 560 ? Math.min(280, window.innerWidth - 24) : 300;
wrap.style.setProperty('--vp-w', `${width}px`);
if (S.pos) {
place(S.pos.x, S.pos.y);
}
scheduleAvoid();
});
/* ---------------------------------------------------------- 启动 */
function mount() {
if (mounted) {
return;
}
mounted = true;
(document.body || document.documentElement).appendChild(host);
wrap.style.setProperty(
'--vp-w',
`${window.innerWidth < 560 ? Math.min(280, window.innerWidth - 24) : 300}px`
);
dragify();
applyTone();
const saved = store.get('speed', 1);
if (S.sw.remember && typeof saved === 'number') {
S.speed = clamp(saved, 0.1, 16);
}
paintSpeed();
applyClean(!!S.sw.clean);
wrap.classList.toggle('is-collapsed', !!S.collapsed);
if (posFromStore) {
place(S.pos.x, S.pos.y);
} else {
dockToCenterBottom();
}
bindVideo(pickVideo());
requestAnimationFrame(() => {
if (!posFromStore) {
dockToCenterBottom();
}
updateStat();
});
if (typeof GM_registerMenuCommand === 'function') {
try {
GM_registerMenuCommand('播放面板:显示 / 隐藏', () => setHidden(!S.hidden));
GM_registerMenuCommand('播放面板:展开 / 收起', () => setCollapsed(!S.collapsed));
GM_registerMenuCommand('播放面板:归位', () => {
S.pos = null;
userMoved = false;
store.set('pos', null);
store.set('moved', false);
dockToCenterBottom();
});
} catch (err) {
/* 忽略 */
}
}
}
/* 有视频才出现:避免在普通网页上多出一块面板 */
let tries = 0;
const timer = setInterval(() => {
tries += 1;
if (!mounted) {
if (pickVideo()) {
mount();
} else if (tries > 120) {
clearInterval(timer);
}
return;
}
if (!host.isConnected) {
(document.body || document.documentElement).appendChild(host);
}
const v = pickVideo();
if (v && v !== video) {
bindVideo(v);
}
if (!v && video) {
video = null;
updateStat();
}
}, 1500);
if (document.readyState === 'loading') {
document.addEventListener(
'DOMContentLoaded',
() => {
if (pickVideo()) {
mount();
}
},
{ once: true }
);
} else if (pickVideo()) {
mount();
}
})();