The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
fix(bili_pack): 修复字幕下载到无关视频的问题 (#1237)
XiaoYouChR8f8de490684a
diff --git a/dist/packs/bili_pack.zip b/dist/packs/bili_pack.zipindex 2cfeaa2f..14ac3654 100644Binary files a/dist/packs/bili_pack.zip and b/dist/packs/bili_pack.zip differdiff --git a/features/bili_pack/manifest.toml b/features/bili_pack/manifest.tomlindex f8e0453e..1bc35680 100644--- a/features/bili_pack/manifest.toml+++ b/features/bili_pack/manifest.toml@@ -2,5 +2,5 @@entry = "pack.py"class = "BilibiliPack"dependencies = ["http_pack", "ffmpeg_pack"]-version = "1.4.3"+version = "1.4.4"gdMinVersion = "4.6.0"diff --git a/features/bili_pack/stream.py b/features/bili_pack/stream.pyindex e392e770..40ffb045 100644--- a/features/bili_pack/stream.py+++ b/features/bili_pack/stream.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKINGfrom loguru import loggerfrom app.client import buildClient+from app.models.task import TaskErrorfrom .config import bilibiliConfigif TYPE_CHECKING:@@ -14,6 +15,27 @@ if TYPE_CHECKING:from .task import BiliPageALL_DASH_STREAMS = 4048+PLAYURL_API = "https://api.bilibili.com/x/player/wbi/playurl"+PLAYER_API = "https://api.bilibili.com/x/player/wbi/v2"+BUVID_API = "https://api.bilibili.com/x/frontend/finger/spi"+DEFAULT_REFERER = "https://www.bilibili.com"+++def extractHeader(headers: dict[str, str] | None, name: str, default: str = "") -> str:+ if not headers:+ return default+ target = name.lower()+ for k, v in headers.items():+ if k.lower() == target and v:+ return v+ return default+++def toSubtitleUrl(url: str) -> str:+ url = str(url or "").strip()+ if url.startswith("//"):+ return "https:" + url+ return urldef toStreamUrl(s: dict) -> str:@@ -118,6 +140,31 @@ def matchAudio(streams: list[dict], quality: int) -> dict:return pick(playable, key=lambda s: s["bandwidth"])+async def resolveSignParams(signParams: Callable[[dict], dict] | None = None) -> Callable[[dict], dict]:+ if signParams is not None:+ return signParams+ from .account import fetchWbiMixinKey, signWbiParams+ mixinKey = await fetchWbiMixinKey()+ return lambda params: signWbiParams(params, mixinKey)+++async def openPlayerClient(headers: dict[str, str] | None) -> tuple[wreq.Client, str]:+ cookie = extractHeader(headers, "cookie")+ referer = extractHeader(headers, "referer", DEFAULT_REFERER)+ reqHeaders = {"referer": referer}+ if cookie:+ reqHeaders["cookie"] = cookie+ client = buildClient(headers=reqHeaders)+ if cookie and "buvid3=" not in cookie.lower():+ buvid = await fetchBuvid(client)+ if buvid:+ cookie = f"{cookie}; buvid3={buvid}"+ reqHeaders["cookie"] = cookie+ client.close()+ client = buildClient(headers=reqHeaders)+ return client, cookie++async def fetchPlayurl(page: BiliPage,*,@@ -126,27 +173,17 @@ async def fetchPlayurl(signParams: Callable[[dict], dict] | None = None,audioQn: int,) -> tuple[list[int], list[str], int]:- if signParams is None:- from .account import fetchWbiMixinKey, signWbiParams- mixinKey = await fetchWbiMixinKey()- signParams = lambda params: signWbiParams(params, mixinKey)-- cookie = headers.get("cookie") or headers.get("Cookie") or ""- client = buildClient(headers={"cookie": cookie} if cookie else None)+ signParams = await resolveSignParams(signParams)+ client, cookie = await openPlayerClient(headers)try:- if cookie and "buvid3=" not in cookie.lower():- buvid = await fetchBuvid(client)- if buvid:- cookie = f"{cookie}; buvid3={buvid}"- page.headers["cookie"] = cookie- client.close()- client = buildClient(headers={"cookie": cookie})+ if cookie:+ page.headers["cookie"] = cookieplayParams = {"cid": page.cid, "qn": qn, "fnval": ALL_DASH_STREAMS, "fourk": 1}if page.bvid:playParams["bvid"] = page.bvidplayParams = signParams(playParams)- playApiUrl = f"https://api.bilibili.com/x/player/wbi/playurl?{urllib.parse.urlencode(playParams)}"+ playApiUrl = f"{PLAYURL_API}?{urllib.parse.urlencode(playParams)}"response = await client.get(playApiUrl)status = response.status.as_int()@@ -167,7 +204,13 @@ async def fetchPlayurl(acceptQuality = list(pageData.get("accept_quality") or [])parseDash(page, dash, qn=qn, acceptQuality=acceptQuality, audioQn=audioQn)if not page.subtitles:- page.subtitles = await fetchSubtitles(client, page)+ try:+ page.subtitles = await querySubtitles(+ client, cid=page.cid, aid=page.aid, bvid=page.bvid, signParams=signParams,+ )+ except Exception:+ logger.opt(exception=True).debug("Failed to fetch subtitles for cid={}", page.cid)+ page.subtitles = []return acceptQuality, list(pageData.get("accept_description") or []), qnfinally:client.close()@@ -175,7 +218,7 @@ async def fetchPlayurl(async def fetchBuvid(client: wreq.Client) -> str:try:- response = await client.get("https://api.bilibili.com/x/frontend/finger/spi")+ response = await client.get(BUVID_API)payload = await response.json()return str(((payload.get("data") or {}).get("b_3") or "")).strip()except Exception:@@ -183,25 +226,106 @@ async def fetchBuvid(client: wreq.Client) -> str:return ""-async def fetchSubtitles(client: wreq.Client, page: BiliPage) -> list[dict]:+async def querySubtitles(+ client: wreq.Client,+ *,+ cid: int,+ aid: int = 0,+ bvid: str = "",+ signParams: Callable[[dict], dict],+) -> list[dict]:+ params: dict = {"cid": cid}+ if aid > 0:+ params["aid"] = aid+ elif bvid:+ params["bvid"] = bvid+ params = signParams(params)+ url = f"{PLAYER_API}?{urllib.parse.urlencode(params)}"+ response = await client.get(url)try:- params: dict = {"cid": page.cid}- if page.bvid:- params["bvid"] = page.bvid- url = f"https://api.bilibili.com/x/player/v2?{urllib.parse.urlencode(params)}"- response = await client.get(url)+ if response.status.as_int() == 412:+ raise TaskError("Bilibili 拦截了字幕请求(412 风控),请稍后再试")response.raise_for_status()payload = await response.json()- rawList = ((payload.get("data") or {}).get("subtitle") or {}).get("subtitles") or []- return [- {- "lan": s["lan"],- "lan_doc": s.get("lan_doc", s["lan"]),- "subtitle_url": s.get("subtitle_url", ""),- "isAi": s.get("type", 0) == 1,- }- for s in rawList if s.get("lan") and s.get("subtitle_url")- ]- except Exception:- logger.opt(exception=True).debug("Failed to fetch subtitles for cid={}", page.cid)- return []+ finally:+ response.close()++ if payload.get("code") not in {None, 0}:+ raise ValueError(payload.get("message") or "获取 Bilibili 字幕列表失败")++ data = payload.get("data") or {}+ respCid = data.get("cid")+ if respCid and int(respCid) != cid:+ raise ValueError(f"字幕响应 cid 不匹配: 期望 {cid},实际 {respCid}")+ respAid = data.get("aid")+ if aid > 0 and respAid and int(respAid) != aid:+ raise ValueError(f"字幕响应 aid 不匹配: 期望 {aid},实际 {respAid}")+ respBvid = str(data.get("bvid") or "")+ if bvid and respBvid and respBvid != bvid:+ raise ValueError(f"字幕响应 bvid 不匹配: 期望 {bvid},实际 {respBvid}")++ rawList = (data.get("subtitle") or {}).get("subtitles") or []+ return [+ {+ "lan": s["lan"],+ "lan_doc": s.get("lan_doc", s["lan"]),+ "subtitle_url": toSubtitleUrl(s.get("subtitle_url", "")),+ "isAi": s.get("type", 0) == 1,+ }+ for s in rawList if s.get("lan") and s.get("subtitle_url")+ ]+++async def fetchSubtitles(+ cid: int,+ *,+ aid: int = 0,+ bvid: str = "",+ headers: dict[str, str] | None = None,+) -> list[dict]:+ signParams = await resolveSignParams()+ client, _ = await openPlayerClient(headers)+ try:+ return await querySubtitles(client, cid=cid, aid=aid, bvid=bvid, signParams=signParams)+ finally:+ client.close()+++def toSrtTime(seconds: float) -> str:+ totalMs = int(round(seconds * 1000))+ h, rem = divmod(totalMs // 1000, 3600)+ m, s = divmod(rem, 60)+ return f"{h:02d}:{m:02d}:{s:02d},{totalMs % 1000:03d}"+++def toSrt(body: list[dict]) -> str:+ lines: list[str] = []+ seq = 0+ for entry in body:+ content = str(entry.get("content", "")).strip()+ if not content:+ continue+ seq += 1+ lines.append(str(seq))+ lines.append(f"{toSrtTime(float(entry.get('from', 0)))} --> {toSrtTime(float(entry.get('to', 0)))}")+ lines.append(content)+ lines.append("")+ return "\n".join(lines)+++async def fetchSubtitleSrt(url: str, *, headers: dict[str, str] | None = None) -> str:+ url = toSubtitleUrl(url)+ if not url:+ return ""+ referer = extractHeader(headers, "referer", DEFAULT_REFERER)+ client = buildClient(headers={"referer": referer})+ try:+ response = await client.get(url)+ try:+ response.raise_for_status()+ payload = await response.json()+ finally:+ response.close()+ finally:+ client.close()+ return toSrt(payload.get("body") or [])diff --git a/features/bili_pack/task.py b/features/bili_pack/task.pyindex 45a11090..347225cb 100644--- a/features/bili_pack/task.py+++ b/features/bili_pack/task.py@@ -610,60 +610,33 @@ class BilibiliSubtitleStep(TaskStep):reportSpeed: Callable[[int], None],waitForSpeedLimit: Callable[[], Awaitable[None]],) -> None:- from app.client import buildClient+ from .stream import fetchSubtitleSrt, fetchSubtitlespage = pageByIndex(self.task, self.fileIndex)- pageHeaders = dict(page.headers) if page and page.headers else {}- referer = pageHeaders.get("referer") or "https://www.bilibili.com"- cookie = pageHeaders.get("cookie") or ""- listHeaders = {"referer": referer}- if cookie:- listHeaders["cookie"] = cookie-- if page and not page.subtitles:- from .stream import fetchSubtitles- subClient = buildClient(emulation=None, headers=listHeaders)- try:- page.subtitles = await fetchSubtitles(subClient, page)- finally:- subClient.close()- subtitle = next((s for s in (page.subtitles if page else []) if s["lan"] == self.language), None)- url = subtitle.get("subtitle_url", "") if subtitle else ""- if not url:+ if page is None:deletePlaceholder(Path(self.outputPath))return- if url.startswith("//"):- url = "https:" + url- def toSrtTime(seconds: float) -> str:- total_ms = int(round(seconds * 1000))- h, rem = divmod(total_ms // 1000, 3600)- m, s = divmod(rem, 60)- return f"{h:02d}:{m:02d}:{s:02d},{total_ms % 1000:03d}"-- client = buildClient(headers={"referer": referer})try:- response = await client.get(url)- response.raise_for_status()- payload = await response.json()+ if not page.subtitles:+ page.subtitles = await fetchSubtitles(+ page.cid, aid=page.aid, bvid=page.bvid, headers=page.headers,+ )+ subtitle = next((s for s in page.subtitles if s["lan"] == self.language), None)+ url = subtitle.get("subtitle_url", "") if subtitle else ""+ srt = await fetchSubtitleSrt(url, headers=page.headers) if url else ""+ except TaskError:+ raiseexcept Exception as e:raise TaskError("字幕下载失败") from e- finally:- client.close()-- lines: list[str] = []- seq = 0- for entry in payload.get("body") or []:- content = str(entry.get("content", "")).strip()- if not content:- continue- seq += 1- lines.append(str(seq))- lines.append(f"{toSrtTime(float(entry.get('from', 0)))} --> {toSrtTime(float(entry.get('to', 0)))}")- lines.append(content)- lines.append("")- if seq:- Path(self.outputPath).write_text("\n".join(lines), encoding="utf-8")++ if not srt:+ deletePlaceholder(Path(self.outputPath))+ return++ outputPath = Path(self.outputPath)+ outputPath.parent.mkdir(parents=True, exist_ok=True)+ outputPath.write_text(srt, encoding="utf-8")@dataclass(kw_only=True)diff --git a/tests/bili_pack/test_task.py b/tests/bili_pack/test_task.pyindex 019a0a19..4c668f01 100644--- a/tests/bili_pack/test_task.py+++ b/tests/bili_pack/test_task.py@@ -447,3 +447,120 @@ def test_bilibili_draft_card_danmaku_controls(qtbot, engine):finally:cfg.isCategoryEnabled.valueChanged.disconnect(card._refreshCategoryButton)++async def test_run_subtitle_side_file_and_errors(tmp_path: Path, startServer, monkeypatch):+ import json+ from urllib.parse import urlsplit+ from aiohttp import web+ import bili_pack.account as account+ import bili_pack.stream as stream+ from app.models.task import TaskError, TaskStatus+ from bili_pack.task import BiliPage, BilibiliSubtitleStep, BilibiliTask++ assert urlsplit(stream.PLAYER_API).path == "/x/player/wbi/v2"++ mode = "ok"+ wbiData = {+ "wbi_img": {+ "img_url": "https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png",+ "sub_url": "https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png",+ }+ }+ seenQueries: list[dict[str, str]] = []+ seenCookies: list[str] = []++ async def handler(request: web.Request) -> web.Response:+ if request.path.endswith("/nav"):+ return web.Response(text=json.dumps({"code": 0, "data": wbiData}), content_type="application/json")+ if request.path.endswith("/spi"):+ return web.Response(text=json.dumps({"code": 0, "data": {"b_3": "test-buvid3"}}), content_type="application/json")+ if request.path.endswith("/sub.json"):+ return web.Response(+ text=json.dumps({+ "body": [+ {"from": 1.25, "to": 3.5, "content": "第一句字幕"},+ {"from": 4.0, "to": 5.0, "content": " "},+ {"from": 6.0, "to": 8.125, "content": "第二句字幕"},+ ]+ }),+ content_type="application/json",+ )+ seenQueries.append(dict(request.query))+ seenCookies.append(request.headers.get("cookie", ""))+ if mode == "412":+ return web.Response(status=412, text="blocked")+ if mode == "mismatch":+ data = {+ "aid": 999999,+ "bvid": "BV1wrong",+ "cid": 888888,+ "subtitle": {"subtitles": [{"lan": "zh-CN", "lan_doc": "中文", "subtitle_url": f"{baseUrl}/sub.json"}]},+ }+ elif mode == "none":+ data = {"aid": 100, "bvid": "BV1ok", "cid": 200, "subtitle": {"subtitles": []}}+ else:+ data = {+ "aid": int(request.query.get("aid") or 100),+ "bvid": request.query.get("bvid") or "BV1ok",+ "cid": int(request.query["cid"]),+ "subtitle": {"subtitles": [{"lan": "zh-CN", "lan_doc": "中文", "subtitle_url": f"{baseUrl}/sub.json"}]},+ }+ return web.Response(text=json.dumps({"code": 0, "data": data}), content_type="application/json")++ baseUrl = (await startServer(handler)).rstrip("/")+ monkeypatch.setattr(account, "LOGIN_INFO_API", f"{baseUrl}/nav")+ monkeypatch.setattr(stream, "BUVID_API", f"{baseUrl}/spi")+ monkeypatch.setattr(stream, "PLAYER_API", f"{baseUrl}/player")++ def buildStep(name: str, *, aid: int = 100, headers: dict[str, str] | None = None) -> BilibiliSubtitleStep:+ task = BilibiliTask(+ name=f"{name}.mp4",+ url="https://www.bilibili.com/video/BV1ok",+ outputFolder=tmp_path,+ files=[BiliPage(index=0, relativePath="", cid=200, aid=aid, bvid="BV1ok", headers=headers or {}, _duration=10)],+ subtitleLanguages=["zh-CN"],+ _baseName=name,+ )+ task.update()+ step = next(s for s in task.steps if isinstance(s, BilibiliSubtitleStep))+ for s in task.steps:+ if s is not step:+ s.setStatus(TaskStatus.COMPLETED)+ Path(step.outputPath).write_text("", encoding="utf-8")+ return step++ # 1. 有 aid 时走 WBI + aid + cid 并补全 buvid3,写出合法 SRT+ step = buildStep("ok", aid=100, headers={"cookie": "SESSDATA=test"})+ await runStep(step)+ assert seenQueries[0]["aid"] == "100" and seenQueries[0]["cid"] == "200" and "bvid" not in seenQueries[0]+ assert seenQueries[0].get("wts") and len(seenQueries[0].get("w_rid", "")) == 32+ assert "buvid3=test-buvid3" in seenCookies[0]+ assert Path(step.outputPath).read_text(encoding="utf-8") == (+ "1\n00:00:01,250 --> 00:00:03,500\n第一句字幕\n\n2\n00:00:06,000 --> 00:00:08,125\n第二句字幕\n"+ )++ # 2. aid 为 0 时回退传 bvid + cid+ fallback = buildStep("fallback", aid=0)+ await runStep(fallback)+ assert seenQueries[1]["bvid"] == "BV1ok" and seenQueries[1]["cid"] == "200" and "aid" not in seenQueries[1]+ assert "第一句字幕" in Path(fallback.outputPath).read_text(encoding="utf-8")++ # 3. 串号响应拒绝落盘;412 抛 TaskError 且保留占位符;无字幕清理占位符+ mode = "mismatch"+ mismatched = buildStep("mismatch")+ with pytest.raises(TaskError, match="字幕下载失败"):+ await runStep(mismatched)+ assert Path(mismatched.outputPath).read_text(encoding="utf-8") == ""++ mode = "412"+ blocked = buildStep("blocked")+ with pytest.raises(TaskError, match="412"):+ await runStep(blocked)+ assert Path(blocked.outputPath).exists()++ mode = "none"+ missing = buildStep("missing")+ await runStep(missing)+ assert not Path(missing.outputPath).exists()++diff --git a/versions.json b/versions.jsonindex b833adbd..11bed574 100644--- a/versions.json+++ b/versions.json@@ -85,9 +85,9 @@},"packs": {"bili_pack": {- "version": "1.4.3",+ "version": "1.4.4","file": "bili_pack.zip",- "sha256": "01d88ccd82174606d518e753fa518f04cb9e5ac3e35db717e8e40bf24c093ccf",+ "sha256": "04bf91bb5789a7e8ec6912be71b8b19f699ecd6609ee79d5ab6215fe821ae6e9","gdMinVersion": "4.6.0"},"bittorrent_pack": {@@ -163,4 +163,4 @@"gdMinVersion": "4.5.0"}}-}\ No newline at end of file+}