Skip to content

The only downloader you need. 下载器的集大成者。

feat(bili): 支持 b23.tv 短链解析 #1025

XiaoYouChR87b5b1e1357e
diff --git a/features/bili_pack/pack.py b/features/bili_pack/pack.py
index a17370f2..3243fee3 100644
--- a/features/bili_pack/pack.py
+++ b/features/bili_pack/pack.py
@@ -3,6 +3,8 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
+from wreq.redirect import Policy
+
from app.client import buildClient
from app.i18n import N
from app.models.pack import FeaturePack, PackServices, TaskParser
@@ -10,7 +12,7 @@ from app.models.task import Task, TaskOptions
from app.platform.filesystem import toSafeFilename
from .account import BilibiliAccount
from .config import bilibiliConfig
-from .parse import BiliUrl, buildFavoritePages, buildPages, matchFavoriteVideo, parseBiliUrl, toHttps
+from .parse import BiliUrl, buildFavoritePages, buildPages, matchFavoriteVideo, matchShortUrl, parseBiliUrl, toHttps
from .stream import buildSize, fetchPlayurl, toStreamUrl
from .task import BiliPage, BilibiliTask
@@ -28,11 +30,13 @@ class BilibiliParser(TaskParser):
def match(self, options: TaskOptions) -> bool:
hostname = (urlparse(options.url).hostname or "").lower()
- return hostname == "bilibili.com" or hostname.endswith(".bilibili.com")
+ return hostname == "bilibili.com" or hostname.endswith(".bilibili.com") or matchShortUrl(options.url)
def matchPassive(self, options: TaskOptions) -> bool:
if not self.match(options):
return False
+ if matchShortUrl(options.url):
+ return bool(urlparse(options.url).path.strip("/"))
try:
biliUrl = parseBiliUrl(options.url)
except ValueError:
@@ -46,26 +50,16 @@ class BilibiliParser(TaskParser):
await self.pack.account.fetchWbiKeys()
- parsed = urlparse(url)
- referer = parsed._replace(netloc="www.bilibili.com").geturl() if (
- (parsed.hostname or "").lower() != "bilibili.com"
- ) else url
-
apiHeaders = {}
cookie = self.pack.account.cookie
if cookie:
apiHeaders["cookie"] = cookie
- downloadHeaders = {
- **dict(options.headers),
- "referer": referer,
- }
- if cookie:
- downloadHeaders["cookie"] = cookie
-
client = buildClient(emulation=None, headers=apiHeaders)
try:
+ if matchShortUrl(url):
+ url = await fetchRedirectUrl(client, url)
biliUrl = parseBiliUrl(url)
if biliUrl.favoriteId:
parsedPages, title, coverUrl = await fetchFavorite(client, biliUrl.favoriteId)
@@ -77,6 +71,17 @@ class BilibiliParser(TaskParser):
if not parsedPages:
raise ValueError("未获取到视频分P信息")
+ parsed = urlparse(url)
+ referer = parsed._replace(netloc="www.bilibili.com").geturl() if (
+ (parsed.hostname or "").lower() != "bilibili.com"
+ ) else url
+ downloadHeaders = {
+ **dict(options.headers),
+ "referer": referer,
+ }
+ if cookie:
+ downloadHeaders["cookie"] = cookie
+
requestedQuality = bilibiliConfig.defaultQuality.value
requestedAudioQuality = bilibiliConfig.defaultAudioQuality.value
baseName = toSafeFilename(title, fallback="bilibili_video")
@@ -137,6 +142,17 @@ class BilibiliParser(TaskParser):
client.close()
+async def fetchRedirectUrl(client: wreq.Client, url: str) -> str:
+ response = await client.get(url, redirect=Policy.none())
+ try:
+ location = bytes(response.headers.get("location") or b"").decode()
+ finally:
+ response.close()
+ if not location:
+ raise ValueError("不是有效的 Bilibili 视频链接")
+ return urlparse(location)._replace(query="", fragment="").geturl()
+
+
async def fetchFavorite(client: wreq.Client, favoriteId: int) -> tuple[list[BiliPage], str, str]:
medias: list[dict[str, Any]] = []
info: dict[str, Any] = {}
@@ -196,7 +212,7 @@ async def fetchView(client: wreq.Client, biliUrl: BiliUrl) -> dict[str, Any]:
raise ValueError("未获取到合集信息")
viewApiUrl = (
- f"https://api.bilibili.com/x/web-interface/view?avid={videoId[2:]}"
+ f"https://api.bilibili.com/x/web-interface/view?aid={videoId[2:]}"
if videoId.startswith("av")
else f"https://api.bilibili.com/x/web-interface/view?bvid={videoId}"
)
diff --git a/features/bili_pack/parse.py b/features/bili_pack/parse.py
index 2b4f9c62..adbe9a1e 100644
--- a/features/bili_pack/parse.py
+++ b/features/bili_pack/parse.py
@@ -16,6 +16,11 @@ class BiliUrl:
selectedPages: list[int] | None = None
+def matchShortUrl(url: str) -> bool:
+ hostname = (urlparse(url).hostname or "").lower()
+ return hostname == "b23.tv" or hostname.endswith(".b23.tv")
+
+
def parseBiliUrl(url: str) -> BiliUrl:
parsed = urlparse(url)
videoIdMatch = re.match(r"/video/(BV[a-zA-Z0-9]+|av\d+)", parsed.path)
diff --git a/tests/bili_pack/test_task_parser.py b/tests/bili_pack/test_task_parser.py
index f38b577e..8bbb7d53 100644
--- a/tests/bili_pack/test_task_parser.py
+++ b/tests/bili_pack/test_task_parser.py
@@ -314,3 +314,42 @@ async def test_probe_size_unknown_without_content_range(startServer):
assert await probeSize(url, {}) == 0
+def test_match_short_link():
+ from app.models.task import TaskOptions
+ from bili_pack.pack import BilibiliParser
+
+ parser = BilibiliParser()
+ assert parser.match(TaskOptions(url="https://b23.tv/eRp4567"))
+ assert parser.matchPassive(TaskOptions(url="https://b23.tv/eRp4567"))
+ assert parser.match(TaskOptions(url="https://b23.tv/"))
+ assert not parser.matchPassive(TaskOptions(url="https://b23.tv/"))
+
+
+async def test_fetch_redirect_strips_query_and_fragment(startServer):
+ from aiohttp import web
+ from app.client import buildClient
+ from bili_pack.pack import fetchRedirectUrl
+
+ async def handler(request):
+ if request.query.get("code") == "valid":
+ return web.Response(
+ status=302,
+ headers={
+ "Location": "https://www.bilibili.com/video/BV1eugW6DEYT/?buvid=1&p=1&share_source=COPY#reply",
+ },
+ )
+ return web.Response(status=200, body=b"not found")
+
+ baseUrl = await startServer(handler)
+ client = buildClient()
+ try:
+ resolved = await fetchRedirectUrl(client, f"{baseUrl}?code=valid")
+ assert resolved == "https://www.bilibili.com/video/BV1eugW6DEYT/"
+
+ with pytest.raises(ValueError, match="不是有效的 Bilibili 视频链接"):
+ await fetchRedirectUrl(client, f"{baseUrl}?code=invalid")
+ finally:
+ client.close()
+
+
+