Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(follow): 角标数与点开所见一致,在线资产就地播放

longmeidao1f52c4103ede
diff --git a/scripts/backfill_rule34_tag_types.py b/scripts/backfill_rule34_tag_types.py
new file mode 100644
index 000000000..862d9d9cf
--- /dev/null
+++ b/scripts/backfill_rule34_tag_types.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+r"""给已入库的 rule34.xxx 追更条目补上标签类型。
+
+rule34.xxx 的 posts DAPI 只回一串扁平标签,类型(general/artist/character/
+copyright/metadata)只在帖子页的 `#tag-sidebar` 上。连接器早就会读它,但那是
+后加的:2152 条里只有 40 条带 `tag_types`,其余 2112 条一条类型也没有。
+
+这直接造成两个可见后果:
+
+- 卡片上没有标签。`_item_tags` 只放行**明确标为 general** 的标签,没有类型就
+ 一个都不放行——而详情页用的是 `_item_all_tags`,所以「点进去里面是有的」。
+- 详情标签全是中性色。按类型着色和按 rule34 分类排序都要有类型才成立。
+
+常规「检查更新」只看第一页,补不到历史条目,所以要这一趟。抓取逻辑不重写,
+直接复用连接器的 `_detail_tag_types`:判据只能有一处。
+
+默认 dry-run。`--apply` 必须同时给 `--backup`,与本仓库其它真实写入脚本一致。
+可反复运行:已经有类型的条目直接跳过,中断后接着跑就是。
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import sqlite3
+import sys
+import time
+from pathlib import Path
+
+from peach.config import DATABASE_PATH, GENERATED_DIR
+from peach.follow_sources import FollowSourceError, build_connector
+from peach.review_csv import write_rows
+
+FIELDS = ("item_id", "external_id", "url", "result", "tag_types", "note")
+
+#: 同一主机的最小请求间隔。rule34.xxx 公布的口径是每 60 秒 60 次;留一倍余量。
+DEFAULT_DELAY = 1.5
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="补齐 rule34.xxx 追更条目的标签类型")
+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)
+ parser.add_argument("--out", type=Path,
+ default=GENERATED_DIR / "rule34-tag-type-backfill.csv")
+ parser.add_argument("--limit", type=int, default=0, help="只处理前 N 条,0 为全部")
+ parser.add_argument("--delay", type=float, default=DEFAULT_DELAY)
+ parser.add_argument("--apply", action="store_true", help="真正写入账本")
+ parser.add_argument("--backup", type=Path, help="写入前的账本备份路径;--apply 必须给")
+ return parser
+
+
+def pending_rows(connection: sqlite3.Connection, limit: int) -> list[dict]:
+ """待补条目:rule34xxx 来源、metadata 里还没有 tag_types 的。
+
+ 判据落在解析后的 JSON 上而不是 `LIKE '%tag_types%'`:空字典也算没有类型,
+ 而它在字符串里是命中的。
+ """
+ rows = []
+ query = (
+ "SELECT i.id, i.external_id, i.url, i.metadata_json FROM follow_item i"
+ " JOIN follow_source s ON s.id=i.source_id"
+ " WHERE s.provider='rule34xxx' ORDER BY i.id"
+ )
+ for row in connection.execute(query):
+ try:
+ metadata = json.loads(row["metadata_json"] or "{}")
+ except ValueError:
+ metadata = {}
+ if isinstance(metadata.get("tag_types"), dict) and metadata["tag_types"]:
+ continue
+ rows.append({"id": row["id"], "external_id": str(row["external_id"] or ""),
+ "url": row["url"], "metadata": metadata})
+ if limit and len(rows) >= limit:
+ break
+ return rows
+
+
+def merge_tag_types(metadata: dict, tag_types: dict[str, str]) -> str:
+ merged = dict(metadata)
+ merged["tag_types"] = dict(tag_types)
+ return json.dumps(merged, ensure_ascii=False)
+
+
+def run(args: argparse.Namespace) -> int:
+ if args.apply and not args.backup:
+ print("--apply 必须同时给 --backup", file=sys.stderr)
+ return 2
+ database = args.db.resolve()
+ with sqlite3.connect(database.as_uri() + "?mode=ro", uri=True) as reader:
+ reader.row_factory = sqlite3.Row
+ rows = pending_rows(reader, args.limit)
+ total = reader.execute(
+ "SELECT COUNT(*) FROM follow_item i JOIN follow_source s ON s.id=i.source_id"
+ " WHERE s.provider='rule34xxx'").fetchone()[0]
+ print(f"rule34xxx 共 {total} 条,待补 {len(rows)} 条", flush=True)
+ if not rows:
+ return 0
+
+ writer: sqlite3.Connection | None = None
+ before = after = 0
+ if args.apply:
+ # 备份先做,批量写入才敢分批落。整轮跑完再一次性写,中断一次就等于白跑
+ # 五十分钟——而这一趟本来就是可反复运行的。
+ shutil.copy2(database, args.backup)
+ print(f"备份:{args.backup}", flush=True)
+ writer = sqlite3.connect(database)
+ before = writer.execute("SELECT COUNT(*) FROM follow_item").fetchone()[0]
+
+ connector = build_connector("rule34xxx")
+ log: list[dict] = []
+ pending_updates: list[tuple[str, int]] = []
+ written = 0
+ fetched = 0
+
+ def flush() -> None:
+ nonlocal written
+ if writer is None or not pending_updates:
+ return
+ writer.executemany("UPDATE follow_item SET metadata_json=? WHERE id=?",
+ pending_updates)
+ writer.commit()
+ written += len(pending_updates)
+ pending_updates.clear()
+
+ for index, row in enumerate(rows, 1):
+ post_id = row["external_id"]
+ if not post_id.isdigit():
+ log.append({"item_id": row["id"], "external_id": post_id, "url": row["url"],
+ "result": "跳过", "tag_types": "", "note": "external_id 不是帖子号"})
+ continue
+ try:
+ tag_types = connector._detail_tag_types(post_id)
+ except (FollowSourceError, OSError) as error:
+ log.append({"item_id": row["id"], "external_id": post_id, "url": row["url"],
+ "result": "未取得", "tag_types": "",
+ "note": f"{type(error).__name__}: {error}"[:120]})
+ time.sleep(args.delay)
+ continue
+ time.sleep(args.delay)
+ if not tag_types:
+ # 取不到不等于这条没有类型:留待下一轮,不写空字典冒充已补。
+ log.append({"item_id": row["id"], "external_id": post_id, "url": row["url"],
+ "result": "未取得", "tag_types": "", "note": "帖子页没有解析出类型"})
+ continue
+ fetched += 1
+ row["merged"] = merge_tag_types(row["metadata"], tag_types)
+ pending_updates.append((row["merged"], row["id"]))
+ log.append({"item_id": row["id"], "external_id": post_id, "url": row["url"],
+ "result": "取得", "tag_types": json.dumps(tag_types, ensure_ascii=False),
+ "note": ""})
+ if index % 50 == 0:
+ flush()
+ print(f"{index}/{len(rows)}:已取得 {fetched},已写入 {written}", flush=True)
+ write_rows(args.out, FIELDS, log, atomic=True)
+
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ write_rows(args.out, FIELDS, log, atomic=True)
+ print(f"取得 {fetched} 条 → {args.out}", flush=True)
+
+ if writer is None:
+ print(f"dry-run:可写入 {fetched} 条;加 --apply --backup 才真正写入")
+ return 0
+ flush()
+ after = writer.execute("SELECT COUNT(*) FROM follow_item").fetchone()[0]
+ typed = writer.execute(
+ "SELECT COUNT(*) FROM follow_item i JOIN follow_source s ON s.id=i.source_id"
+ " WHERE s.provider='rule34xxx' AND i.metadata_json LIKE '%tag_types%'"
+ ).fetchone()[0]
+ writer.close()
+ # 条数必须不变:这一趟只补 metadata,不新增也不删除条目。
+ print(f"已更新 {written} 条;follow_item {before} → {after};"
+ f"rule34xxx 带类型 {typed}/{total}")
+ return 0 if before == after else 1
+
+
+def main(argv: list[str] | None = None) -> int:
+ return run(build_parser().parse_args(argv))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/peach/api.py b/src/peach/api.py
index e645b21a4..ba3d73849 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -136,6 +136,28 @@ def _offline_response(exc: MediaOffline) -> JSONResponse:
#: (封面重生成写的是新文件),所以一年也不嫌长。
#: 不加 immutable——那会让浏览器连刷新都不再回源,真要换图就只能干等过期。
MEDIA_CACHE_SECONDS = 365 * 24 * 3600
+
+#: 文件名里不能出现的字符,按 Windows 的最严口径取——落盘的那台多半是它。
+_UNSAFE_FILENAME = re.compile('[\\/:*?"<>|]+|[\x00-\x1f]+')
+
+
+def _attachment_disposition(title: str, url: str) -> str:
+ """按条目标题构造下载文件名,扩展名沿用上游地址的后缀。
+
+ 不回传上游地址:主机名和签名同样是不该外露的东西,和 `/follow-stream`
+ 整体的边界一致。`filename*` 用 RFC 5987 编码,标题里的中文和日文才落得下来。
+ """
+ stem = _UNSAFE_FILENAME.sub(" ", str(title or "")).strip() or "peach-media"
+ stem = " ".join(stem.split())[:120]
+ suffix = Path(urlsplit(str(url or "")).path).suffix.lower()
+ if not re.fullmatch(r"\.[a-z0-9]{2,5}", suffix):
+ suffix = ".mp4"
+ name = f"{stem}{suffix}"
+ # 标题整条都是中日文时,ascii 回退会只剩空格和标点,浏览器落下来是个没名字的
+ # 文件。回退名必须自己站得住,不能是「把非 ASCII 删掉之后剩下的」。
+ ascii_stem = "".join(ch for ch in stem if ch.isascii() and (ch.isalnum() or ch in " -_[]().")).strip()
+ ascii_name = f"{ascii_stem}{suffix}" if ascii_stem else f"peach-media{suffix}"
+ return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(name)}"
#: 头像单独短一档:id 不变但人会换头像,作者换得还挺勤。
AVATAR_CACHE_SECONDS = 30 * 24 * 3600
@@ -714,7 +736,7 @@ def create_app(
@app.api_route("/follow-stream", methods=["GET", "HEAD"])
def follow_stream(request: Request, id: int, media: int | None = None,
- quality: int | None = None,
+ quality: int | None = None, download: int = 0,
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:
@@ -751,6 +773,11 @@ def create_app(
if value:
forwarded[name] = value
forwarded["cache-control"] = "no-store"
+ # 下载是显式动作,不是播放的副作用:只有带 `download=1` 才让浏览器落盘。
+ # 文件名从条目标题来,不回传上游地址——上游主机名同样是不该外露的东西。
+ if download:
+ forwarded["content-disposition"] = _attachment_disposition(
+ item.title, target.url)
if request.method == "HEAD":
status = upstream.status_code
upstream.close()
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index 6bd460af2..35793317e 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import html
import json
import re
+import time
import urllib.parse
from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta, timezone
@@ -1166,9 +1167,21 @@ class Rule34PahealConnector(_BaseConnector):
return SourceFetch(candidates=tuple(candidates), probed=len(candidates),
raw_body=response.body, **common)
+ #: 详情页取不到就重试的状态码。列表页一页 24 条,每条都要单独打一次详情页,
+ #: 上游按频率挡回来是常态;一次挡回来就当「这条没有上传时间」,得到的是一条
+ #: 看似完整、时间却是抓取时刻的记录——比报错更难发现。
+ _DETAIL_RETRY_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
+ #: 与外网退避规则同一套节奏。
+ _DETAIL_RETRY_DELAYS = (1.0, 2.0, 4.0)
+
def _detail(self, post_id: str) -> dict[str, object]:
url = f"https://rule34.paheal.net/post/view/{post_id}"
response = self._get(url, headers={"Accept": "text/html"})
+ for delay in self._DETAIL_RETRY_DELAYS:
+ if response.status not in self._DETAIL_RETRY_STATUSES:
+ break
+ time.sleep(delay)
+ response = self._get(url, headers={"Accept": "text/html"})
if response.status != 200:
return {}
soup = BeautifulSoup(response.body, "html.parser")
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index b708c36db..b80b55ba7 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -237,9 +237,16 @@ class FollowStore:
"first_seen_at,last_seen_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
" ON CONFLICT(source_id,external_id) DO UPDATE SET"
" title=excluded.title, url=excluded.url, media_url=excluded.media_url,"
- " thumb_url=excluded.thumb_url, published_at=excluded.published_at,"
- " published_precision=excluded.published_precision,"
- " version=excluded.version, duration=excluded.duration,"
+ # 详情页取不到不等于这条没有发布时间。paheal 每个候选都要单独打一次
+ # 详情页,被限流时 `_detail` 返回 {},这里若直接覆盖,就会把上一轮
+ # 已经取到的上传时间和时长抹成 NULL——实测 168 条里 7 条正是这样,
+ # 而 `COALESCE(published_at, first_seen_at)` 会让界面改显示抓取时刻。
+ " thumb_url=excluded.thumb_url,"
+ " published_at=COALESCE(excluded.published_at, follow_item.published_at),"
+ " published_precision=CASE WHEN excluded.published_at IS NOT NULL"
+ " THEN excluded.published_precision ELSE follow_item.published_precision END,"
+ " version=excluded.version,"
+ " duration=COALESCE(excluded.duration, follow_item.duration),"
" release_key=excluded.release_key, variant_kind=excluded.variant_kind,"
" variant_label=excluded.variant_label, group_hint=excluded.group_hint,"
" metadata_json=excluded.metadata_json, last_seen_at=excluded.last_seen_at",
diff --git a/src/peach/follow_variants.py b/src/peach/follow_variants.py
index 6f0aef14e..e2de5bfda 100644
--- a/src/peach/follow_variants.py
+++ b/src/peach/follow_variants.py
@@ -46,6 +46,10 @@ _ALT_MARKERS: tuple[tuple[str, str], ...] = (
(r"no[\s\-]?sound|muted?|silent", "no sound"),
(r"with[\s\-]?sound|sound[\s\-]?version|w/[\s\-]?sound|audio", "sound"),
(r"(\d{3,4})p", "{0}p"),
+ # 分辨率常写成不带 `p` 的裸数字:`2B Camp [4K]` 与 `2B Camp [1080]` 是同一部片的
+ # 两个版本,而 `[1080]` 此前留在 release_key 里,两张卡永远合不到一起。只认已知
+ # 分辨率档位,不认任意三四位数——那可能是年份或作品序号。
+ (r"(480|720|1080|1440|2160|4320)", "{0}p"),
(r"([248])k(?![a-z])", "{0}K"),
(r"(\d{2,3})[\s\-]?fps", "{0}fps"),
(r"alt(?:ernat(?:e|ive))?(?:[\s\-]?(?:version|ver|angle|ending))?", "alt"),
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index cd21d9f34..3360ee7c4 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -886,6 +886,14 @@ def q_item(contract: WebContract, aid):
if not r:
return {"error": "not found"}
d = dict(r)
+ # 在线资产的 `path` 是来源作品页,不是可播地址;能播的那条代理在
+ # `/follow-stream?id=<follow_item>`。保存时写的是 `follow_item.asset_id`,
+ # 反查一次就能让馆藏详情自己播,不必先跳回关注页。
+ if d.get("location") == "online":
+ row = c.execute(
+ "SELECT id FROM follow_item WHERE asset_id=? ORDER BY id LIMIT 1", (aid,),
+ ).fetchone()
+ d["follow_item_id"] = int(row[0]) if row else None
legacy_rows = list(c.execute(
"SELECT t.tag,t.source FROM asset_tag t WHERE t.asset_id=? AND "
+ tag_not_hidden("t.asset_id", "peach_normalize(t.tag)")
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index d25953f17..477c4569a 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -950,6 +950,48 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.headers["content-range"], "bytes 2-5/10")
self.assertNotIn("img.kemono.cr", response.text)
+ async def test_follow_stream_only_offers_a_download_when_asked(self):
+ """下载是显式动作,不是播放的副作用。
+
+ 文件名从条目标题来,不回传上游地址——上游主机名和签名同样不该外露,
+ 这和 `/follow-stream` 整体的边界是同一条。
+ """
+ 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(1,'kemono','fanbox/1','Creator','https://kemono.cr/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(8,1,'8','2B Camp [4K]','https://kemono.cr/p/8',"
+ "'https://img.kemono.cr/data/8.webm','remote','x','x')"
+ )
+ connection.commit()
+ connection.close()
+
+ def upstream(request):
+ return httpx.Response(
+ 200, stream=httpx.ByteStream(b"0123456789"), request=request,
+ headers={"content-type": "video/webm", "content-length": "10"},
+ )
+
+ 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:
+ played = await self.client.get("/follow-stream?id=8&t=secret")
+ saved = await self.client.get("/follow-stream?id=8&t=secret&download=1")
+ finally:
+ self.app.state.http_transport.client = original
+ fake.close()
+ self.assertNotIn("content-disposition", played.headers)
+ disposition = saved.headers["content-disposition"]
+ self.assertIn("attachment;", disposition)
+ self.assertIn("2B Camp [4K].webm", disposition)
+ self.assertNotIn("img.kemono.cr", disposition)
+
async def test_follow_cover_serves_cached_frame_and_falls_back_to_source_thumb(self):
connection = sqlite3.connect(self.db)
connection.executescript((ROOT / "migrations" / "0018_online_follow.sql").read_text(
diff --git a/tests/test_follow_store.py b/tests/test_follow_store.py
index 19098904e..bfc08340c 100644
--- a/tests/test_follow_store.py
+++ b/tests/test_follow_store.py
@@ -129,6 +129,39 @@ class RecordTests(_StoreCase):
self.assertEqual(refreshed.first_seen_at, item.first_seen_at)
self.assertNotEqual(refreshed.last_seen_at, item.last_seen_at)
+ def test_a_failed_detail_never_erases_a_known_upload_time(self):
+ """paheal 每个候选都要单独打一次详情页,被限流时 `_detail` 返回 {}。
+
+ 此前 upsert 无条件覆盖,于是上一轮已经取到的上传时间和时长被抹成 NULL,
+ 而 `COALESCE(published_at, first_seen_at)` 会让界面改显示抓取时刻——
+ 看着是条完整记录,时间却是错的。实测 168 条 paheal 里 7 条正是这样。
+ """
+ source_id = self._source()
+ self.store.record(source_id, _fetch([_candidate(
+ "1", "A", published_at="2026-08-18T09:03:30Z", duration=44.7)]), moment=MOMENT)
+ first = self.store.items()[0]
+ self.assertEqual(first.published_at, "2026-08-18T09:03:30Z")
+
+ later = MOMENT + timedelta(hours=1)
+ self.store.record(source_id, _fetch([_candidate("1", "A")], raw=b"<html>2</html>"),
+ moment=later)
+ again = self.store.items()[0]
+ self.assertEqual(again.published_at, "2026-08-18T09:03:30Z")
+ self.assertEqual(again.duration, 44.7)
+ self.assertEqual(again.published_precision, "exact")
+
+ def test_a_later_fetch_with_a_real_time_still_wins(self):
+ """保守只针对「取不到」;来源真的给了新时间就要覆盖,不能变成只写一次。"""
+ source_id = self._source()
+ self.store.record(source_id, _fetch([_candidate("1", "A")]), moment=MOMENT)
+ self.assertIsNone(self.store.items()[0].published_at)
+ self.store.record(source_id, _fetch([_candidate(
+ "1", "A", published_at="2026-08-18T09:03:30Z")], raw=b"<html>2</html>"),
+ moment=MOMENT + timedelta(hours=1))
+ item = self.store.items()[0]
+ self.assertEqual(item.published_at, "2026-08-18T09:03:30Z")
+ self.assertEqual(item.published_precision, "exact")
+
def test_not_modified_records_the_check_without_touching_items(self):
source_id = self._source()
self.store.record(source_id, _fetch([_candidate("1", "A")]), moment=MOMENT)
diff --git a/tests/test_follow_variants.py b/tests/test_follow_variants.py
index 4adff9644..3b661b975 100644
--- a/tests/test_follow_variants.py
+++ b/tests/test_follow_variants.py
@@ -128,6 +128,24 @@ class ClassifyTests(unittest.TestCase):
self.assertEqual(normalize_handle("Lazy_Procrast!"), "lazyprocrast")
+ def test_resolution_written_without_the_p_is_still_a_version(self):
+ """`2B Camp [4K]` 与 `2B Camp [1080]` 是同一部片的两个版本。
+
+ `[1080]` 此前留在 release_key 里(`2b camp 1080`),两张卡永远合不到一起,
+ 而 `[4K]` 那张的角标写着「2 个版本」,数的是 `[4K]` + `[WIP]`。
+ 只认已知分辨率档位:任意三四位数可能是年份或作品序号。
+ """
+ self.assertEqual(classify("2B Camp [4K]").release_key,
+ classify("2B Camp [1080]").release_key)
+ self.assertEqual(classify("2B Camp [1080]").variant_label, "1080p")
+ self.assertEqual(classify("Yuffie Photoshoot Part 3 [1080]").release_key,
+ classify("Yuffie Photoshoot Part 3 [4K]").release_key)
+ # 不是分辨率的数字照旧留在键里。
+ self.assertEqual(classify("Sayuri - Cowgirl 2").release_key, "sayuri cowgirl 2")
+ self.assertEqual(classify("Scene [2023]").release_key, "scene 2023")
+ self.assertEqual(classify("Part [1200]").release_key, "part 1200")
+
+
class GroupDuplicatesTests(unittest.TestCase):
def test_cross_site_duplicates_fold_onto_one_primary(self):
video = _Item("4542713", "rule34video", "fiona paizuri", "main", "2026-08-18")
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index fd8a60596..ece9670d3 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -1923,11 +1923,12 @@ class FollowWebSourceTests(unittest.TestCase):
同一份数据两种口径,两个视频的组会显示成「1 个版本」。现在共用一个表达式,
只有量词不同。
"""
- self.assertPageContains(
- "`${group.variants.length+1} ${group.is_release?'条动态':'个版本'}`")
+ self.assertPageContains("`${count} ${group.is_release?'条动态':'个版本'}`")
self.assertPageLacks(
"`${group.variants.length} 个版本`",
"版本数必须含主条目,否则两个视频显示成 1 个版本")
+ # 计数来源换成了「点开真能看到的那一组」,量词的分工不变。
+ self.assertPageContains("const count=(openable||followOpenableItems(group)).length;")
def test_cross_site_duplicates_are_shown_as_another_source(self):
self.assertPageContains("另见 ")
@@ -2124,6 +2125,31 @@ class FollowWebSourceTests(unittest.TestCase):
# 来源没记类型的排最后、保持中性色:不按词形猜类型是关注标签的既有门槛。
self.assertPageContains(".followdetailtags .r34-unknown{--r34-tag:var(--muted)}")
+ def test_version_badge_counts_what_opening_the_card_actually_shows(self):
+ """角标数和点开后能看到的条数必须来自同一个集合。
+
+ 实测两处对不上:paheal 一组 9 条里有 1 张图,卡上写「9 个版本」、播放角标
+ 写「8 个视频」;`2B Camp [4K]` 卡上写「2 个版本」,同组另一条不是可播视频,
+ `collection` 因此为 null,点开只有 1 条。
+ """
+ self.assertPageContains("function followOpenableItems(group)")
+ self.assertPageContains("if(followMediaView==='videos')return followVideoItems(group);")
+ self.assertPageContains("const count=(openable||followOpenableItems(group)).length;")
+ self.assertPageContains("if(count>1)badges.push(")
+ self.assertPageLacks("${group.variants.length+1} ${group.is_release?'条动态':'个版本'}")
+
+ def test_wip_badge_describes_this_item_not_its_siblings(self):
+ """`2B Camp [4K]` 判的是 alt,只因为同组还有一条 `[WIP]` 就挂上 WIP。
+
+ `has_wip` 是组属性(`any(item.variant_kind == "wip" for item in self.variants)`),
+ 角标却贴在主条目标题旁边,读起来就是「这一条是半成品」。
+ """
+ self.assertPageContains(
+ "if(group.primary.variant_kind==='wip')badges.push('<span class=\"fbadge wip\">WIP</span>');")
+ self.assertPageContains(
+ "else if(group.has_wip)badges.push('<span class=\"fbadge wip partial\">含 WIP</span>');")
+ self.assertPageContains(".fbadge.wip.partial{border-color:var(--border-15);color:var(--muted)}")
+
def test_follow_bulk_actions_are_buttons_not_inline_links(self):
"""批量标记已看/全部忽略是 2292 条级别的操作,不能长得像行内文字链接。
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 5f0d82b0c..7eef78867 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -75,6 +75,21 @@ class OperationalScriptTests(unittest.TestCase):
self.assertNotIn("Featured Actress", category_map,
"来源营销分类不是内容标签,不能因为官方给了就直接入库")
+ def test_rule34_tag_type_backfill_reuses_the_connector_and_is_resumable(self):
+ """rule34xxx 的标签类型只在帖子页上,2152 条里当时只有 40 条带着它。
+
+ 常规检查只看第一页,补不到历史条目。抓取判据不重写,直接复用连接器的
+ `_detail_tag_types`;备份先做、分批提交,中断一次不至于白跑五十分钟。
+ """
+ source = (ROOT / "scripts" / "backfill_rule34_tag_types.py").read_text(encoding="utf-8")
+ self.assertIn("connector._detail_tag_types(post_id)", source)
+ self.assertIn('if args.apply and not args.backup:', source)
+ self.assertIn("shutil.copy2(database, args.backup)", source)
+ self.assertIn("writer.commit()", source)
+ # 取不到不等于这条没有类型:不写空字典冒充已补,下一轮还要再问。
+ self.assertIn('if not tag_types:', source)
+ self.assertIn('return 0 if before == after else 1', source)
+
def test_test_entrypoint_enforces_worktree_source_and_unittest(self):
windows = (ROOT / "scripts" / "test.ps1").read_text(encoding="utf-8")
self.assertIn("rev-parse --git-common-dir", windows)
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 7dc32391e..59a55739c 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -394,6 +394,27 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("const returnSurfaceReady=hasReturnSurface();")
self.assertPageLacks("const returnSurfaceReady=$('#grid').children.length>0")
+ def test_a_saved_online_asset_plays_where_it_is(self):
+ """保存过的在线资产此前在馆藏详情里只给一道闸:「媒体与原始页面在关注详情中查看」。
+
+ `path` 是来源作品页不假,但能播的那条代理一直都在
+ (`/follow-stream?id=<follow_item>`),保存时写的就是 `follow_item.asset_id`。
+ 反查不到关注条目时才拦下来,并说清是什么拦的。
+ """
+ self.assertPageContains("function followStreamSource(it)")
+ self.assertPageContains(
+ "return it.location==='online'&&it.follow_item_id")
+ self.assertPageContains("const proxied=followStreamSource(it);")
+ self.assertPageContains("const onlineGated=online&&!it.follow_item_id;")
+ self.assertPageLacks("这条内容从关注候选保存;媒体与原始页面在关注详情中查看。")
+
+ def test_follow_detail_has_an_explicit_download(self):
+ """下载到本地是显式动作,此前根本没有入口。用 `<a download>` 让浏览器落盘。"""
+ self.assertPageContains('class="fdownload"')
+ self.assertPageContains("download=1")
+ self.assertPageContains('<symbol id="i-download"')
+ self.assertPageContains(".fb .fdownload{box-sizing:border-box;width:44px;height:42px;")
+
def test_detail_like_reason_is_an_icon_disclosure_without_idle_explanation(self):
self.assertPageContains('id="preferenceToggle" aria-label="喜爱理由"')
self.assertPageContains('id="preferencePanel" hidden')
diff --git a/web/app.css b/web/app.css
index 9de36f3ac..6c04c9952 100644
--- a/web/app.css
+++ b/web/app.css
@@ -1401,7 +1401,11 @@ body.index-open #tiers,body.index-open #tagbar{display:none}
.fb button{width:44px;height:42px;padding:0;border:0;border-right:1px solid var(--border-10);background:transparent;border-radius:0;
cursor:pointer;display:grid;place-items:center;color:var(--muted);transition:transform .14s ease,color .14s ease,background .14s ease}
.fb button svg{width:21px;height:21px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
-.fb button:last-child{border-right:0}.fb button:hover{transform:none;background:rgba(255,255,255,.12)}
+.fb button:last-child,.fb .fdownload:last-child{border-right:0}.fb button:hover{transform:none;background:rgba(255,255,255,.12)}
+/* 下载是 `<a download>`,不是按钮:让浏览器自己落盘,不经过 JS。几何与同排按钮一致。 */
+.fb .fdownload{box-sizing:border-box;width:44px;height:42px;display:grid;place-items:center;border-right:1px solid var(--border-10);color:var(--ink-2)}
+.fb .fdownload:hover{background:rgba(255,255,255,.12);color:var(--ink)}
+.fb .fdownload svg{width:21px;height:21px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.fb .like:hover,.fb .like[aria-pressed="true"]{color:var(--tungsten);background:var(--tungsten-soft)}
.fb .reason:hover,.fb .reason[aria-expanded="true"],.fb .reason[data-has-reason="true"]{color:#FF669D;background:color-mix(in srgb,#FF669D 12%,transparent)}
.fb .dislike:hover,.fb .dislike[aria-pressed="true"]{color:var(--drop);background:color-mix(in srgb,var(--drop) 12%,transparent)}
@@ -1924,6 +1928,8 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
.followitem .meta .s{min-height:21px}.fbadges{display:flex;flex-wrap:nowrap;gap:5px;min-width:0;overflow:hidden}
.fbadge{padding:2px 8px;border:1px solid var(--border-15);border-radius:var(--badge-radius);font-size:var(--fs-xs);color:var(--ink-2)}
.fbadge.wip{border-color:var(--meter);color:var(--meter)}
+/* 「含 WIP」说的是同组里还有一条半成品,这一条本身不是;配色要弱于 WIP 本体。 */
+.fbadge.wip.partial{border-color:var(--border-15);color:var(--muted)}
.fbadge.ver{border-color:var(--tungsten);color:var(--tungsten)}
.fbadge.dup{border-style:dashed}
.fnote{font-size:var(--fs-xs);color:var(--muted)}
diff --git a/web/app.js b/web/app.js
index 3c1478744..35b9b558e 100644
--- a/web/app.js
+++ b/web/app.js
@@ -412,7 +412,16 @@ function detailStreamUrl(id){
function directDetailSource(it){
return {src:detailStreamUrl(it.id),type:String(it.name||'').toLowerCase().endsWith('.webm')?'video/webm':'video/mp4'};
}
+/* 在线资产的 `path` 是来源作品页,不是可播地址。能播的那条代理在
+ `/follow-stream?id=<follow_item>`,保存时写了 `follow_item.asset_id`,
+ `/api/item` 反查后回传 `follow_item_id`。 */
+function followStreamSource(it){
+ return it.location==='online'&&it.follow_item_id
+ ?{src:`/follow-stream?id=${it.follow_item_id}`,type:'video/mp4'}:null;
+}
async function detailStreamSource(it){
+ const proxied=followStreamSource(it);
+ if(proxied)return proxied;
const direct=directDetailSource(it);
if(!['115','pikpak'].includes(it.location))return direct;
try{
@@ -2819,14 +2828,26 @@ function followDetailTags(item){
return [...tags].sort((a,b)=>rank(a)-rank(b)||tagLabel(a).localeCompare(tagLabel(b)));
}
-function followBadges(group){
+/* 角标上的数和点开后真能看到的条数必须来自同一个集合。
+ 实测两处对不上:paheal 一组 9 条里有 1 张图,卡上写「9 个版本」、播放角标写
+ 「8 个视频」,点开也是 8 条;`2B Camp [4K]` 更极端——卡上写「2 个版本」,同组
+ 另一条不是可播视频,`collection` 因此整个为 null,点开只有 1 条。 */
+function followOpenableItems(group){
+ if(followMediaView==='videos')return followVideoItems(group);
+ return followCollectionItems(group)
+ .filter(item=>followItemMediaKinds(item).has('image'));
+}
+function followBadges(group,openable=null){
const badges=[];
- if(group.has_wip)badges.push('<span class="fbadge wip">WIP</span>');
+ const count=(openable||followOpenableItems(group)).length;
+ /* WIP 说的是这一条,不是这一组。`2B Camp [4K]` 判的是 alt,只因为同组还有一条
+ `[WIP]` 就在它头上挂 WIP,读起来就成了「这一条是半成品」。同组有 WIP 仍然要
+ 说,但要说成「含」。 */
+ if(group.primary.variant_kind==='wip')badges.push('<span class="fbadge wip">WIP</span>');
+ else if(group.has_wip)badges.push('<span class="fbadge wip partial">含 WIP</span>');
if(group.primary.version)badges.push(`<span class="fbadge ver">${esc(group.primary.version)}</span>`);
- if(group.variants.length)badges.push(`<span class="fbadge">${
- // 两个分支都含主条目:以前 release 记 +1、work 不记,同一份数据两种口径,
- // 两个视频的组会显示成「1 个版本」。
- `${group.variants.length+1} ${group.is_release?'条动态':'个版本'}`}</span>`);
+ if(count>1)badges.push(`<span class="fbadge">${
+ `${count} ${group.is_release?'条动态':'个版本'}`}</span>`);
if(group.duplicates.length)badges.push(`<span class="fbadge dup">另见 ${
esc([...new Set(group.duplicates.map(d=>d.provider_label))].join('、'))}</span>`);
return badges.join('');
@@ -3057,7 +3078,9 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=fals
<button class="later" data-follow-detail-save aria-label="${item.status==='saved'?'已保存':'保存到账本'}" title="${item.status==='saved'?'已保存':'保存到账本'}"${item.status==='saved'?' disabled':''}>${item.status==='saved'?icon('check'):icon('bookmark-plus')}</button>
<button class="seen" data-follow-detail-status="seen" aria-label="标记已看" title="标记已看" aria-pressed="${item.status==='seen'}">${icon('eye')}</button>
<button class="dislike" data-follow-detail-status="ignored" aria-label="忽略" title="忽略" aria-pressed="${item.status==='ignored'}">${icon('eye-off')}</button>
- ${item.status==='seen'||item.status==='ignored'?`<button data-follow-detail-status="new" aria-label="恢复未看" title="恢复未看">${icon('rotate-ccw')}</button>`:''}</div>
+ ${item.status==='seen'||item.status==='ignored'?`<button data-follow-detail-status="new" aria-label="恢复未看" title="恢复未看">${icon('rotate-ccw')}</button>`:''}
+ ${src?`<a class="fdownload" href="${esc(src)}${src.includes('?')?'&':'?'}download=1" download
+ aria-label="下载到本地" title="下载到本地">${icon('download')}</a>`:''}</div>
<span class="fstate" aria-live="polite"></span>
</div></div></div>`;
$('#stage').classList.toggle('ambient-on',selectedKind==='video'&&appSettings.ambientMode);
@@ -5650,6 +5673,8 @@ async function openItem(id,push=true,queueContext=null,anchor=null){
const gated=it.cost==='metered';
const offline=sourceOffline(it.location);
const online=it.location==='online';
+ /* 保存过的在线资产照常播;只有反查不到关注条目时才拦下来说明原因。 */
+ const onlineGated=online&&!it.follow_item_id;
const who=it.creator||it.code||it.studio||'未归属';
const refs=it.entity_refs||{},studioRef=(refs.studio||[])[0];
// 共演作品的女优逐行列出,每行带自己的头像;标签只写在第一行,其余留空保持对齐。
@@ -5717,10 +5742,10 @@ async function openItem(id,push=true,queueContext=null,anchor=null){
<button class="chip" id="offlineRetry" type="button">重新检测</button></div>
<video id="vid" class="video-js vjs-big-play-centered" controls playsinline preload="none"
hidden style="display:none"></video>`
- :online?`<div class="gate" id="onlineGate" role="status">
+ :onlineGated?`<div class="gate" id="onlineGate" role="status">
${srcBadge(it.location,it.cost,'srcbig')}
<b style="font-size:14px">在线资产</b>
- <span style="font-size:12px;color:var(--muted)">这条内容从关注候选保存;媒体与原始页面在关注详情中查看。</span>
+ <span style="font-size:12px;color:var(--muted)">这条没有对应的关注条目,媒体地址无从解析。</span>
<button class="chip" id="openSavedFollow" type="button">打开已保存关注</button></div>
<video id="vid" class="video-js vjs-big-play-centered" controls playsinline preload="none"
hidden style="display:none"></video>`
diff --git a/web/index.html b/web/index.html
index 4950f355e..d514c026b 100644
--- a/web/index.html
+++ b/web/index.html
@@ -85,6 +85,7 @@
<symbol id="i-chevron-down" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6" /></symbol>
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5" /></symbol>
<symbol id="i-upload" viewBox="0 0 24 24"><path d="M12 3v12" /><path d="m17 8-5-5-5 5" /><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /></symbol>
+ <symbol id="i-download" viewBox="0 0 24 24"><path d="M12 15V3" /><path d="m7 10 5 5 5-5" /><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /></symbol>
<symbol id="i-database" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="9" ry="3" /><path d="M3 5V19A9 3 0 0 0 21 19V5" /><path d="M3 12A9 3 0 0 0 21 12" /></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" /></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" /><path d="M12 6v6l4 2" /></symbol>