Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(follow): rule34video 多清晰度,档数由来源决定

longmeidaoaf6c7a454fa0
diff --git a/src/peach/api.py b/src/peach/api.py
index 6dec81b9d..6fc17c740 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -684,15 +684,45 @@ def create_app(
response.headers["Cache-Control"] = f"private, max-age={AVATAR_CACHE_SECONDS}"
return response
+ @app.api_route("/follow-qualities", methods=["GET"])
+ def follow_qualities(id: int, args: dict[str, str] = Depends(require_auth)):
+ """这条关注视频有哪些清晰度可选。
+
+ 单独一个端点而不是塞进 /api/follow:解析要抓一次来源详情页,列表一次几百条,
+ 逐条解析等于几百个外部请求。这里只在用户展开某个条目、播放器要画菜单时问一次,
+ 解析结果本身在 resolver 里有缓存。
+
+ 只有 rule34video 给多档(video_url 加 video_alt_url{,2,3});其余来源返回空表,
+ 播放器据此只显示「原画」。取不到不是错误——签名 URL 会过期、来源也可能改版,
+ 那时照常播默认档就行。
+ """
+ with database.read_connection() as connection:
+ item = FollowStore(lambda: connection).item(id)
+ if item is None:
+ return JSONResponse({"error": "no such follow item"}, status_code=404)
+ try:
+ resolved = follow_media_resolver.resolve(item)
+ except FollowMediaUnavailable:
+ return {"qualities": []}
+ # 档位数量不写死:正则匹配 video_url 与任意编号的 video_alt_urlN,
+ # 站点给几档就是几档(实测同一作者下有 4 档也有 5 档的条目)。
+ # 2160 按站点自己的写法叫 4K,不叫 2160p。
+ return {"qualities": [
+ {"height": height, "label": "4K" if height >= 2160 else f"{height}p"}
+ for height, _ in resolved.qualities if height
+ ]}
+
@app.api_route("/follow-stream", methods=["GET", "HEAD"])
- def follow_stream(request: Request, id: int, media: int | None = None, args: dict[str, str] = Depends(require_auth)):
+ def follow_stream(request: Request, id: int, media: int | None = None,
+ quality: int | None = None,
+ args: dict[str, str] = Depends(require_auth)):
"""Play a remote follow candidate through Peach without exposing its upstream URL."""
with database.read_connection() as connection:
item = FollowStore(lambda: connection).item(id)
if item is None:
return JSONResponse({"error": "no such follow item"}, status_code=404)
try:
- target = follow_media_resolver.resolve(item, media)
+ target = follow_media_resolver.resolve(item, media, quality)
headers = {
"User-Agent": "Peach/0.2",
"Accept": request.headers.get("accept", "*/*"),
diff --git a/src/peach/follow_stream.py b/src/peach/follow_stream.py
index 3c6a657b8..6e481f00f 100644
--- a/src/peach/follow_stream.py
+++ b/src/peach/follow_stream.py
@@ -29,13 +29,37 @@ class ResolvedFollowMedia:
url: str
referer: str | None = None
headers: Mapping[str, str] | None = None
+ #: (高度, URL) 从高到低。只有 rule34video 给多档;其余来源留空,
+ #: 播放器据此只显示「原画」。
+ qualities: tuple[tuple[int, str], ...] = ()
#: 媒体代理允许的主机,投影自 follow_providers;不在表里的 provider 一律拒绝。
_PROVIDER_HOSTS = follow_providers.hosts()
-_VIDEO_URL_RE = re.compile(r"\bvideo_url\s*:\s*'([^']+)'", re.IGNORECASE)
+#: rule34video 把每一档清晰度写成独立字段:`video_url` 是最低档,
+#: `video_alt_url`、`video_alt_url2`、`video_alt_url3` 依次更高。
+#: 2026-08-31 实测 video/4564733 给出 360 / 480p / 720p / 1080p 四档;
+#: 只解析 `video_url` 的话永远播最低那一档。
+_VIDEO_URL_RE = re.compile(r"\bvideo(?:_alt)?_url\d*\s*:\s*'([^']+)'", re.IGNORECASE)
+#: 从文件名尾部读分辨率:`4564733_1080p.mp4` → 1080,`4564733_360.mp4` → 360。
+_VIDEO_HEIGHT_RE = re.compile(r"_(\d{3,4})p?\.mp4", re.IGNORECASE)
+def _video_height(url: str) -> int:
+ matched = _VIDEO_HEIGHT_RE.search(urllib.parse.urlsplit(url).path)
+ return int(matched.group(1)) if matched else 0
+
+
+def _pick_quality(resolved: ResolvedFollowMedia, height: int | None) -> ResolvedFollowMedia:
+ """按高度挑一档。要的那档不在就保持原样(默认是最高档)。"""
+ if not height or not resolved.qualities:
+ return resolved
+ for level, url in resolved.qualities:
+ if level == height:
+ return ResolvedFollowMedia(url, resolved.referer, resolved.headers,
+ resolved.qualities)
+ return resolved
+
def _allowed(provider: str, url: str) -> bool:
try:
parsed = urllib.parse.urlsplit(url)
@@ -65,7 +89,11 @@ class FollowMediaResolver:
self._credential_loader = loader
return self
- def resolve(self, item: FollowItemRow, media_index: int | None = None) -> ResolvedFollowMedia:
+ def resolve(self, item: FollowItemRow, media_index: int | None = None,
+ height: int | None = None) -> ResolvedFollowMedia:
+ """解析可播地址。`height` 指定清晰度,只有 rule34video 有多档可选;
+ 要的那档不存在就退回默认(最高档),不报错——签名 URL 会过期,
+ 为一次选档失败中断播放不值得。"""
if item.metadata.get("media_needs_credential"):
raise FollowMediaUnavailable("媒体需要来源登录会话")
media_items = item.metadata.get("media_items")
@@ -112,7 +140,7 @@ class FollowMediaResolver:
with self._lock:
cached = self._cache.get(item.id)
if cached and cached[0] > time.monotonic():
- return cached[1]
+ return _pick_quality(cached[1], height)
if not item.url or not _allowed(item.provider, item.url):
raise FollowMediaUnavailable("Rule34Video 详情地址不可用")
response = self.transport(
@@ -123,13 +151,20 @@ class FollowMediaResolver:
if response.status != 200 or len(response.body) > self.max_bytes:
raise FollowMediaUnavailable("Rule34Video 详情页未取得")
text = response.body.decode("utf-8", errors="replace")
- matched = _VIDEO_URL_RE.search(text)
- if not matched:
+ found: list[str] = []
+ for matched in _VIDEO_URL_RE.finditer(text):
+ candidate = html.unescape(matched.group(1)).replace("\\/", "/")
+ if candidate not in found and _allowed(item.provider, candidate):
+ found.append(candidate)
+ if not found:
raise FollowMediaUnavailable("Rule34Video 正片地址未取得")
- target = html.unescape(matched.group(1)).replace("\\/", "/")
- if not _allowed(item.provider, target):
- raise FollowMediaUnavailable("Rule34Video 返回了不受信任的媒体地址")
- resolved = ResolvedFollowMedia(target, item.url)
+ # 高清优先:默认播最高一档,其余作为可选清晰度交给播放器。认不出分辨率的
+ # 排在最后但不丢——签名 URL 每次都变,丢了就没有回退。
+ ordered = sorted(found, key=_video_height, reverse=True)
+ resolved = ResolvedFollowMedia(
+ ordered[0], item.url,
+ qualities=tuple((_video_height(url), url) for url in ordered))
+ resolved = _pick_quality(resolved, height)
with self._lock:
self._cache[item.id] = (time.monotonic() + self.ttl, resolved)
return resolved
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 8dc0f2580..ba0efd8c7 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -791,6 +791,58 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(head.content, b"")
self.assertEqual(head.headers["content-length"], "10")
+ async def test_follow_qualities_lists_every_tier_the_source_offers(self):
+ """档位数量由来源决定,不由我们写死。
+
+ 取证时那条给四档,实测线上另有五档(多一个 2160)的条目——所以解析用的是
+ `video_alt_url` 加任意编号,而不是固定认三个 alt 字段。这里就用五档兜住:
+ 少认一档等于用户白白播低清。2160 按站点自己的写法叫 4K,不叫 2160p。
+ """
+ connection = sqlite3.connect(self.db)
+ connection.executescript((ROOT / "migrations" / "0018_online_follow.sql").read_text(
+ encoding="utf-8"))
+ connection.execute(
+ "INSERT INTO follow_source(id,provider,ref,label,url,semantics,created_at,updated_at)"
+ " VALUES(2,'rule34video','r34/1','Creator','https://rule34video.com/u','work','x','x')"
+ )
+ connection.execute(
+ "INSERT INTO follow_item(id,source_id,external_id,title,url,media_url,release_key,"
+ "first_seen_at,last_seen_at) VALUES(9,2,'9','Remote',"
+ "'https://rule34video.com/video/9/x/','https://rule34video.com/get_file/9.mp4/',"
+ "'remote','x','x')"
+ )
+ connection.commit()
+ connection.close()
+
+ page = ("<script>"
+ "video_url: 'https://rule34video.com/get_file/9_360.mp4/?v=t0';"
+ "video_alt_url: 'https://rule34video.com/get_file/9_480p.mp4/?v=t1';"
+ "video_alt_url2: 'https://rule34video.com/get_file/9_720p.mp4/?v=t2';"
+ "video_alt_url3: 'https://rule34video.com/get_file/9_1080p.mp4/?v=t3';"
+ "video_alt_url4: 'https://rule34video.com/get_file/9_2160p.mp4/?v=t4';"
+ "</script>").encode("utf-8")
+
+ def upstream(request):
+ return httpx.Response(200, stream=httpx.ByteStream(page), request=request,
+ headers={"content-type": "text/html"})
+
+ original = self.app.state.http_transport.client
+ fake = httpx.Client(transport=httpx.MockTransport(upstream), follow_redirects=True)
+ self.app.state.http_transport.client = fake
+ try:
+ response = await self.client.get("/follow-qualities?id=9&t=secret")
+ finally:
+ self.app.state.http_transport.client = original
+ fake.close()
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["qualities"], [
+ {"height": 2160, "label": "4K"},
+ {"height": 1080, "label": "1080p"},
+ {"height": 720, "label": "720p"},
+ {"height": 480, "label": "480p"},
+ {"height": 360, "label": "360p"},
+ ])
+
async def test_follow_stream_proxies_range_without_exposing_the_upstream_url(self):
connection = sqlite3.connect(self.db)
connection.executescript((ROOT / "migrations" / "0018_online_follow.sql").read_text(
diff --git a/tests/test_follow_stream.py b/tests/test_follow_stream.py
index eb58bdf2c..d0fc4fb84 100644
--- a/tests/test_follow_stream.py
+++ b/tests/test_follow_stream.py
@@ -94,3 +94,62 @@ class FollowMediaResolverTests(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+
+
+class Rule34VideoQualityTests(unittest.TestCase):
+ """rule34video 把每档清晰度写成独立字段,只解析 video_url 会永远播最低那档。
+
+ 2026-08-31 实测 video/4564733 的页面给出四档:
+
+ video_url -> 4564733_360.mp4
+ video_alt_url -> 4564733_480p.mp4
+ video_alt_url2 -> 4564733_720p.mp4
+ video_alt_url3 -> 4564733_1080p.mp4
+ """
+
+ PAGE = (b"<script>"
+ b"video_url: 'https://rule34video.com/get_file/51/a/1/1_360.mp4/?v-acctoken=t0';"
+ b"video_alt_url: 'https://rule34video.com/get_file/51/a/1/1_480p.mp4/?v-acctoken=t1';"
+ b"video_alt_url2: 'https://rule34video.com/get_file/51/a/1/1_720p.mp4/?v-acctoken=t2';"
+ b"video_alt_url3: 'https://rule34video.com/get_file/51/a/1/1_1080p.mp4/?v-acctoken=t3';"
+ b"</script>")
+
+ def _resolver(self, body=None):
+ def transport(request, timeout, max_bytes):
+ return HttpResponse(200, {}, self.PAGE if body is None else body)
+ return FollowMediaResolver(transport)
+
+ def _item(self):
+ return SimpleNamespace(
+ id=11, provider="rule34video",
+ url="https://rule34video.com/video/11/x/",
+ media_url="https://rule34video.com/get_file/1.mp4/",
+ metadata={},
+ )
+
+ def test_every_quality_is_parsed_and_the_highest_plays_by_default(self):
+ resolved = self._resolver().resolve(self._item())
+ self.assertEqual([height for height, _ in resolved.qualities],
+ [1080, 720, 480, 360])
+ self.assertIn("1_1080p.mp4", resolved.url,
+ "默认应当是最高一档,旧实现固定播 360")
+
+ def test_a_requested_height_is_honoured(self):
+ resolved = self._resolver().resolve(self._item(), None, 480)
+ self.assertIn("1_480p.mp4", resolved.url)
+
+ def test_an_unavailable_height_falls_back_instead_of_failing(self):
+ """签名 URL 会过期、来源也会改版;选档失败不该中断播放。"""
+ resolved = self._resolver().resolve(self._item(), None, 4320)
+ self.assertIn("1_1080p.mp4", resolved.url)
+
+ def test_other_providers_report_no_quality_choices(self):
+ item = SimpleNamespace(
+ id=12, provider="pawchive",
+ url="https://pawchive.pw/x",
+ media_url="https://pawchive.pw/data/a/b/c.mp4",
+ metadata={},
+ )
+ resolved = self._resolver(body=b"").resolve(item)
+ self.assertEqual(resolved.qualities, (),
+ "只有 rule34video 给多档,其余来源只显示原画")
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index ff09aa58d..1df1a29cc 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -1613,7 +1613,12 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("if(followVideo){")
self.assertPageContains("const followPlayer=mountDetailPlayer(item,followVideo,false,{")
self.assertPageContains("source:{src,type:selectedMedia?.media_type||item.media_type||'video/mp4'}")
- self.assertPageContains("function mountPlayerQualityControl(player,video,fallbackHeight=0)")
+ # 第四个参数是来源自己给的清晰度表:rule34video 把每档写成独立 mp4 字段,
+ # videojs 的 qualityLevels 只认 HLS/DASH 的自适应轨道,看不到它们。
+ self.assertPageContains(
+ "function mountPlayerQualityControl(player,video,fallbackHeight=0,sourceQualities=null)")
+ self.assertPageContains("qualities:followQualities",
+ "关注详情要把查到的档位传给播放器")
self.assertPageContains('aria-label="播放器设置"')
self.assertPageContains("data-player-quality-badge")
self.assertPageContains("currentTimeDisplay:true,timeDivider:true")
diff --git a/web/app.js b/web/app.js
index 8272016d0..61642d6c4 100644
--- a/web/app.js
+++ b/web/app.js
@@ -478,7 +478,10 @@ function mountPlayerAmbient(video){
document.addEventListener('peachambientchange',onChange);video.addEventListener('play',schedule);schedule();
return()=>{stopped=true;document.removeEventListener('peachambientchange',onChange);video.removeEventListener('play',schedule);clear()};
}
-function mountPlayerQualityControl(player,video,fallbackHeight=0){
+/* `sourceQualities` 是来源自己给的清晰度表([{height,label}],从高到低)。
+ rule34video 把每档写成独立字段,videojs 的 qualityLevels 看不到它们——那套只认
+ HLS/DASH 的自适应轨道,而这里是四个各自独立的 mp4。所以由调用方查好再传进来。 */
+function mountPlayerQualityControl(player,video,fallbackHeight=0,sourceQualities=null){
const controlBar=player.getChild('controlBar')?.el();
if(!controlBar||controlBar.querySelector('[data-player-quality]'))return;
const root=document.createElement('div');
@@ -503,12 +506,15 @@ function mountPlayerQualityControl(player,video,fallbackHeight=0){
}
return result;
}
+ if(sourceQualities?.length){
+ return sourceQualities.map(q=>({key:`h${q.height}`,label:q.label||`${q.height}p`,pixels:q.height}));
+ }
const pixels=resolution(video.videoWidth,video.videoHeight)||Number(fallbackHeight)||0;
return [{key:'original',label:pixels?`${pixels}p`:'原画',pixels}];
};
const qualityRows=()=>{
const options=rows();
- if(!levels?.length)selected='original';
+ if(!levels?.length&&!sourceQualities?.length)selected='original';
const active=options.find(option=>option.key===selected)||options[0];
const activePixels=active.pixels||Math.max(0,...options.map(option=>option.pixels||0));
badge.textContent=activePixels>=2160?'4K':activePixels>=720?'HD':'';badge.hidden=!badge.textContent;
@@ -540,6 +546,19 @@ function mountPlayerQualityControl(player,video,fallbackHeight=0){
menu.querySelectorAll('[data-player-quality-option]').forEach(button=>button.onclick=()=>{
selected=button.dataset.playerQualityOption;
if(levels?.length)for(let index=0;index<levels.length;index++)levels[index].enabled=selected==='auto'||selected===String(index);
+ /* 来源档位是四个各自独立的 mp4,不是同一条流的多个轨道,所以只能换 src。
+ 记住当前进度和播放状态再换:换源会重新加载,不接回去就等于从头开始。 */
+ if(sourceQualities?.length&&selected.startsWith('h')){
+ const height=selected.slice(1);
+ const at=player.currentTime()||0,wasPlaying=!player.paused();
+ const next=new URL(player.currentSrc()||video.src,location.origin);
+ next.searchParams.set('quality',height);
+ player.src({src:next.pathname+next.search,type:'video/mp4'});
+ player.one('loadedmetadata',()=>{
+ if(at>0)player.currentTime(at);
+ if(wasPlaying)player.play().catch(()=>{});
+ });
+ }
showMain();
});
};
@@ -743,7 +762,7 @@ function mountDetailPlayer(it,video,autoplay,options={}){
});
});
detailPlayer.ready(()=>{
- enforceDuration();mountPlayerQualityControl(detailPlayer,video,it.height);
+ enforceDuration();mountPlayerQualityControl(detailPlayer,video,it.height,options.qualities);
mountPlayerSeekPreview(detailPlayer,it,{thumbnail:!options.source});
mountPlayerCenterControls(detailPlayer);
if(statsButton)statsButton.hidden=false
@@ -2564,9 +2583,17 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=fals
});
const followVideo=$('#stage').querySelector('.followdetailmedia>video');
if(followVideo){
+ /* 清晰度单独问一次:解析要抓来源详情页,列表一次几百条不可能逐条解析,
+ 所以只在用户真的展开某个条目时问。取不到就当只有原画,不挡播放。 */
+ let followQualities=null;
+ try{
+ const answer=await api(`/follow-qualities?id=${encodeURIComponent(item.id)}`);
+ followQualities=answer?.qualities?.length?answer.qualities:null;
+ }catch(_e){}
const followPlayer=mountDetailPlayer(item,followVideo,false,{
source:{src,type:selectedMedia?.media_type||item.media_type||'video/mp4'},
- checkSourceStatus:false
+ checkSourceStatus:false,
+ qualities:followQualities
});
const stopFollowAmbient=mountPlayerAmbient(followVideo);
followPlayer?.one?.('dispose',stopFollowAmbient);