Peach: Local-first video metadata scraper and media manager.
fix(follow): 检查更新不再重探库里已补齐的 rule34video 与 kemono 条目
longmeidao543ee065f8a6
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 6b974adb9..37427ea2c 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -445,7 +445,8 @@ class _BaseConnector:#: 列表页一次请求给一整页,详情页是每条一次——它是唯一会让请求数随条目数增长#: 的路径,所以必须有额度,不能由页面长度决定。DEFAULT_ENRICH_BUDGET = 0- #: 第二阶段成功之后,ledger 行上哪一处会有值。空串 = 没有第二阶段。+ #: 详情页问过之后,ledger 行上哪一处会有值。空串 = 不打详情页。第二阶段补细节+ #: (`DEFAULT_ENRICH_BUDGET`)与列表阶段的逐条探测(`DEFAULT_MAX_PROBES`)都按它跳过。#: 调用方拿它算「这条不必再问详情」,判据本身登记在 `follow_store`。#: **不能一律用 `published_at`**:rule34xxx 的上传时间来自列表的 `change`,#: 第一次落库就有值,拿它当判据会让详情失败的行永远补不回来。@@ -562,17 +563,26 @@ class _BaseConnector:raise FollowSourceError(f"{self.provider} 拒绝访问(HTTP {response.status}):需要有效凭据,""或站点已加机器人验证")- if response.status == 429:- headers = {key.lower(): value for key, value in response.headers.items()}- try:- retry_after = float(headers.get("retry-after", ""))- except ValueError:- retry_after = None- raise FollowSourceRateLimited(- f"{self.provider} 返回 HTTP 429:请求过于频繁,稍后再试", retry_after)+ self._raise_if_rate_limited(response)if response.status != 200:raise FollowSourceError(f"{self.provider} 返回 HTTP {response.status}")+ def _raise_if_rate_limited(self, response: HttpResponse) -> None:+ """HTTP 429 抛 `FollowSourceRateLimited`。++ 逐条探测详情页时也要过这一关:探测吞掉失败是为了不因一条取不到就丢更新,+ 被限流却不同,接着探剩下的只会让整站被封得更久,要让检查停下、整站冷却。+ """+ if response.status != 429:+ return+ headers = {key.lower(): value for key, value in response.headers.items()}+ try:+ retry_after = float(headers.get("retry-after", ""))+ except ValueError:+ retry_after = None+ raise FollowSourceRateLimited(+ f"{self.provider} 返回 HTTP 429:请求过于频繁,稍后再试", retry_after)+#: 上游限流页的固定句式(2026-08-29 实测 rule34.xxx):HTTP 200 + 文本正文#: "You currently have a limit of 60 requests every 60 second(s)"。不识别的话# 会被报成「请求失败/不是合法 JSON」,用户看不出是被限流了。@@ -785,6 +795,7 @@ class KemonoConnector(_BaseConnector):#: 增长的路径:一个从不贴附件、只发网盘链接的作者会让每一帖都触发一次。上限用完#: 之后剩下的判不出来的帖子一律保留——宁可多留卡片,不能因为额度用完就删更新。DEFAULT_MAX_PROBES = 12+ ENRICHED_MARK = "kept"#: 列表接口一页的条数,2026-08-27 实测为 50(`?o=50` 拿到的是第 51 条起)。PAGE_SIZE = 50@@ -879,6 +890,9 @@ class KemonoConnector(_BaseConnector):if not self.within_history(self._candidate(post, service, user)):continueverdict = self._delivers_resource(post)+ if verdict is None and str(post.get("id") or "") in self.enrich_skip:+ # 库里已有的帖子当初判过保留,再探一次只会得到同一个答案。+ verdict = Trueif verdict is None and probed < self.max_probes:# 列表接口判不出来才去抓详情。这是唯一一处「一帖一请求」,# 所以只在拿不准时用,并且有上限。@@ -926,7 +940,8 @@ class KemonoConnector(_BaseConnector):"""抓详情页再判一次。**抓不到就当它是 release。**这一步是兜底,不是判据来源:网络抖一下就删掉用户的一份更新,是拿一次失败的- 请求换一次不可见的数据丢失。宁可多留一张卡片。+ 请求换一次不可见的数据丢失。宁可多留一张卡片。被限流例外:照样抛出,让这次+ 检查停下、整站冷却。"""post_id = str(post.get("id") or "")if not post_id:@@ -934,9 +949,12 @@ class KemonoConnector(_BaseConnector):url = f"https://{self.host}/api/v1/{service}/user/{user}/post/{post_id}"try:response = self._get(url)+ self._raise_if_rate_limited(response)if response.status >= 400:return Truepayload = self.parse_json(response)+ except FollowSourceRateLimited:+ raiseexcept (FollowSourceError, OSError, httpx.HTTPError):return Trueif not isinstance(payload, dict):@@ -1126,6 +1144,10 @@ class Rule34VideoConnector(_BaseConnector):r"\((?:va|audio|audio/sfx|sfx|sound|voice|music)\)\s*$", re.IGNORECASE)MAX_COLLECTION_MODELS = 3DEFAULT_MAX_PROBES = 24+ ENRICHED_MARK = "tag_types"+ #: 列表卡片给的、详情页会改写的 metadata 键。库里已补齐的行跳过探测时去掉它们,+ #: 免得列表的「预览片」「相对时间」并进去盖掉详情页取到的值。+ _LIST_ONLY_EXTRA = ("media_kind", "published_precision")@classmethoddef visual_model_count(cls, models) -> int:@@ -1197,7 +1219,13 @@ class Rule34VideoConnector(_BaseConnector):if not self.within_history(candidate):continueenriched = candidate- if probed < self.max_probes and candidate.url:+ if str(candidate.external_id) in self.enrich_skip:+ # 库里这条的详情已经取到过:不再打详情页,只让列表权威的几列照常更新。+ # 合辑在落库前就挡掉了,库里有的都不是合辑。+ enriched = replace(candidate, partial=True, extra={+ key: value for key, value in candidate.extra.items()+ if key not in self._LIST_ONLY_EXTRA})+ elif probed < self.max_probes and candidate.url:probed += 1enriched = self._probe_detail(candidate)visual = int(enriched.extra.get("visual_model_count") or 0)@@ -1247,16 +1275,22 @@ class Rule34VideoConnector(_BaseConnector):Rule34Video 的列表页只有预览片和相对时间,详情页才同时给 JSON-LD 正片、内容标签、分类与署名作者。探测有每页 24 条上限,不会无界放大请求。+ 失败时的列表候选标成 `partial`:库里已有的正片、封面与日期不被列表值盖掉,+ 判据仍不成立,下次检查再补。被限流照样抛出,让检查停下、整站冷却。"""+ listed = replace(candidate, partial=True)try:response = self._get(candidate.url or "", headers={"Accept": "text/html"})+ self._raise_if_rate_limited(response)if response.status != 200:- return candidate+ return listeddetail = self._detail(response.body)+ except FollowSourceRateLimited:+ raiseexcept (FollowSourceError, OSError, httpx.HTTPError, ValueError):- return candidate+ return listedif not detail:- return candidate+ return listedextra = {**dict(candidate.extra), **detail["extra"]}return replace(candidate,diff --git a/src/peach/follow_store.py b/src/peach/follow_store.pyindex 2f3b089d9..1f82ef1fd 100644--- a/src/peach/follow_store.py+++ b/src/peach/follow_store.py@@ -188,11 +188,16 @@ _PARTIAL_UPDATE = (" last_seen_at=excluded.last_seen_at")-#: 「第二阶段已经补齐过这一行」在 ledger 上怎么看出来。键就是连接器声明的+#: 「详情页已经问过这一行」在 ledger 上怎么看出来。键就是连接器声明的#: `ENRICHED_MARK`,值是判据。写死成一张表而不是拼 SQL:判据是封闭词表,#: 由 `tests/test_follow_sources.py` 反过来核对每个连接器声明的键都在这里。_ENRICHED_PREDICATES = {"published_at": "published_at IS NOT NULL AND published_at<>''",+ # rule34video:标签、分类与署名只有详情页给,有 `tag_types` 就是详情页取到过。+ "tag_types": "json_extract(metadata_json,'$.tag_types') IS NOT NULL",+ # kemono 系:详情页只用来判「这一帖交付了资源没有」,没有要补的列。判过保留的帖子+ # 才会落库,所以行在 ledger 里本身就是判定结果,库里有的帖子不必再探。+ "kept": "1",# rule34xxx:分类只有帖子页给,时长只有原文件头给,两样都有才算补齐。只看分类的话,# 时长功能上线前补过分类的行、文件头那次没读到的行,常规检查永远不会再问。"tag_types_duration": (diff --git a/tests/test_follow_check.py b/tests/test_follow_check.pyindex 6a7598b09..97986d77e 100644--- a/tests/test_follow_check.py+++ b/tests/test_follow_check.py@@ -184,8 +184,8 @@ class PlanCheckTests(_CheckCase):planned = plan_check(self.store, _Credentials())self.assertEqual(planned[0]["enrich_skip"], frozenset({"1"}))- def test_a_source_without_a_second_phase_never_computes_a_skip_set(self):- """kemono 的探测是收录判定,在列表阶段做;那里没有可跳过的第二阶段。"""+ def test_kemono_skips_probing_every_post_it_already_kept(self):+ """kemono 的探测是收录判定:库里有的帖子当初判过保留,不必再探。"""source_id = self._register(provider="kemono", ref="fanbox/1",url="https://kemono.cr/fanbox/user/1")self.store.record(source_id, _fetch(@@ -193,6 +193,17 @@ class PlanCheckTests(_CheckCase):FollowCandidate(provider="kemono", external_id="1", title="a",published_at="2026-08-26T15:21:00Z"),)),moment=MOMENT)+ self.assertEqual(plan_check(self.store, _Credentials())[0]["enrich_skip"],+ frozenset({"1"}))++ def test_a_source_that_never_opens_detail_pages_never_computes_a_skip_set(self):+ source_id = self._register(provider="subscribestar", ref="creator",+ url="https://subscribestar.adult/creator")+ self.store.record(source_id, _fetch(+ provider="subscribestar", ref="creator", candidates=(+ FollowCandidate(provider="subscribestar", external_id="1", title="a",+ published_at="2026-08-26T15:21:00Z"),)),+ moment=MOMENT)self.assertEqual(plan_check(self.store, _Credentials())[0]["enrich_skip"],frozenset())diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex cb866135e..49d1bb6f6 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -808,6 +808,40 @@ class KemonoConnectorTests(unittest.TestCase):self.assertIn("888", [c.external_id for c in result.candidates])self.assertEqual(result.probed, 1)+ def test_a_post_already_in_the_ledger_is_not_probed_again(self):+ """库里有的帖子当初判过保留;每次检查都再探一遍,请求数就跟着库存涨。"""+ posts = json.loads(KEMONO_POSTS)+ posts.append({"id": "888", "title": "March pack", "published": "2026-03-01T00:00:00",+ "file": {}, "attachments": [], "substring": "Here you go"})++ def route(request):+ if "/post/" in request.url:+ raise AssertionError(f"未预期的详情请求:{request.url}")+ return HttpResponse(200, {}, json.dumps(posts).encode())++ result = KemonoConnector(transport=_routed(route), enrich_skip={"888"}).fetch("fanbox/1")+ self.assertIn("888", [c.external_id for c in result.candidates])+ self.assertEqual(result.probed, 0)++ def test_a_rate_limited_probe_stops_the_check(self):+ """探测被 429 挡回来时不能当成「保留」接着探下一帖,要让这次检查停下。"""+ posts = json.loads(KEMONO_POSTS)+ posts.extend({"id": str(ident), "title": f"pack {ident}",+ "published": "2026-03-01T00:00:00", "file": {}, "attachments": [],+ "substring": "Here"} for ident in (801, 802, 803))+ probes = []++ def route(request):+ if "/post/" in request.url:+ probes.append(request.url)+ return HttpResponse(429, {"Retry-After": "90"}, b"")+ return HttpResponse(200, {}, json.dumps(posts).encode())++ with self.assertRaises(FollowSourceRateLimited) as raised:+ KemonoConnector(transport=_routed(route)).fetch("fanbox/1")+ self.assertEqual(raised.exception.retry_after, 90.0)+ self.assertEqual(len(probes), 1)+def test_a_post_with_no_resource_at_all_is_dropped(self):"""公告、感谢这类帖子既没有附件也没有网盘链接,抓了详情之后确认丢掉。"""posts = json.loads(KEMONO_POSTS)@@ -1049,6 +1083,56 @@ class Rule34VideoConnectorTests(unittest.TestCase):self.assertEqual(first.extra["model_count"], 6)self.assertEqual(first.extra["visual_model_count"], 1)+ def test_a_video_already_detailed_in_the_ledger_is_not_probed_again(self):+ """库里补齐过的条目不再打详情页,额度全留给新条目。++ 跳过的候选是 `partial`:落库时详情给的正片、封面、日期不被列表值盖掉;+ 列表那份「预览片」「相对时间」也不带进 metadata。+ """+ seen = []++ def transport(request, timeout, max_bytes):+ seen.append(request.url)+ body = (RULE34VIDEO_HTML if "/models/" in request.url+ else RULE34VIDEO_DETAIL_HTML)+ return HttpResponse(200, {}, body)++ result = Rule34VideoConnector(transport=transport, enrich_skip={"4542721"}).fetch(+ "lazyprocrastinator")+ known, fresh = result.candidates+ details = [url for url in seen if "/video/" in url]+ self.assertEqual(result.probed, 1)+ self.assertEqual(len(details), 1)+ self.assertNotIn("/video/4542721/", details[0])+ self.assertTrue(known.partial)+ self.assertNotIn("media_kind", known.extra)+ self.assertNotIn("published_precision", known.extra)+ self.assertFalse(fresh.partial)++ def test_a_failed_probe_does_not_overwrite_the_details_already_recorded(self):+ def transport(request, timeout, max_bytes):+ if "/models/" in request.url:+ return HttpResponse(200, {}, RULE34VIDEO_HTML)+ return HttpResponse(404, {}, b"")++ result = Rule34VideoConnector(transport=transport).fetch("lazyprocrastinator")+ self.assertTrue(all(candidate.partial for candidate in result.candidates))++ def test_a_rate_limited_probe_stops_the_check(self):+ """详情页被 429 挡回来,接着探剩下的只会让整站被封得更久。"""+ probes = []++ def transport(request, timeout, max_bytes):+ if "/models/" in request.url:+ return HttpResponse(200, {}, RULE34VIDEO_HTML)+ probes.append(request.url)+ return HttpResponse(429, {"Retry-After": "120"}, b"")++ with self.assertRaises(FollowSourceRateLimited) as raised:+ Rule34VideoConnector(transport=transport).fetch("lazyprocrastinator")+ self.assertEqual(raised.exception.retry_after, 120.0)+ self.assertEqual(len(probes), 1)+class PagingBackTests(unittest.TestCase):"""各站往回翻的地址形状。都是 2026-08-27 实测过的端点。"""@@ -2133,17 +2217,18 @@ class EnrichPhaseTests(unittest.TestCase):from peach.follow_store import _ENRICHED_PREDICATESfor provider, factory in sorted(follow_sources.CONNECTORS.items()):mark = factory.ENRICHED_MARK+ probes = factory.DEFAULT_ENRICH_BUDGET or getattr(factory, "DEFAULT_MAX_PROBES", 0)with self.subTest(provider=provider):- self.assertEqual(bool(mark), bool(factory.DEFAULT_ENRICH_BUDGET),- "有额度就得有判据,有判据就得有额度")+ self.assertEqual(bool(mark), bool(probes),+ "打详情页就得有判据,有判据就得打详情页")if mark:self.assertIn(mark, _ENRICHED_PREDICATES)def test_the_mark_of_an_unknown_provider_is_empty_not_an_error(self):self.assertEqual(follow_sources.enrichment_mark("nope"), "")self.assertEqual(follow_sources.enrichment_mark(""), "")- self.assertEqual(follow_sources.enrichment_mark("kemono"), "",- "kemono 的探测是收录判定,在列表阶段做,不是第二阶段")+ self.assertEqual(follow_sources.enrichment_mark("kemono"), "kept",+ "kemono 的探测是收录判定,库里有的帖子就是判过保留的")self.assertEqual(follow_sources.enrichment_mark("rule34xxx"), "tag_types_duration")def test_rule34xxx_is_not_marked_by_a_time_the_list_already_gave(self):diff --git a/tests/test_follow_store.py b/tests/test_follow_store.pyindex 5515b989f..7a7c9768d 100644--- a/tests/test_follow_store.py+++ b/tests/test_follow_store.py@@ -1342,6 +1342,45 @@ class EnrichedMarkTests(_StoreCase):"SELECT external_id, duration FROM follow_item WHERE source_id=?", (source_id,)))self.assertEqual(durations, {"empty": 10.0, "known": 30.0})+ def test_a_rule34video_row_stays_detailed_when_the_list_sees_it_again(self):+ """补齐过的 rule34video 行再被列表看到时不打详情页,详情给的值都要留住。"""+ source_id = self._source(provider="rule34video", ref="artist")+ self.store.record(source_id, _fetch([+ FollowCandidate(provider="rule34video", external_id="1", title="a",+ media_url="https://rule34video.com/get_file/1_720p.mp4/",+ published_at="2026-08-18T00:00:00Z",+ extra={"media_kind": "video", "published_precision": "exact",+ "tag_types": {"3D": "metadata"}}),+ FollowCandidate(provider="rule34video", external_id="2", title="b",+ media_url="https://rule34video.com/get_file/2_preview.mp4/",+ partial=True, extra={"media_kind": "preview_clip"}),+ ], provider="rule34video", ref="artist"), moment=MOMENT)+ self.assertEqual(self.store.enriched_external_ids(source_id, "tag_types"),+ frozenset({"1"}))+ self.store.record(source_id, _fetch([+ FollowCandidate(provider="rule34video", external_id="1", title="a",+ media_url="https://rule34video.com/get_file/1_preview.mp4/",+ published_at="2026-08-10T00:00:00Z", partial=True,+ extra={"added_text": "2 months ago"}),+ ], provider="rule34video", ref="artist"), moment=MOMENT + timedelta(minutes=1))+ media_url, published_at, metadata = self.connection.execute(+ "SELECT media_url, published_at, metadata_json FROM follow_item"+ " WHERE source_id=? AND external_id='1'", (source_id,)).fetchone()+ self.assertEqual(media_url, "https://rule34video.com/get_file/1_720p.mp4/")+ self.assertEqual(published_at, "2026-08-18T00:00:00Z")+ self.assertEqual(json.loads(metadata)["media_kind"], "video")+ self.assertEqual(self.store.enriched_external_ids(source_id, "tag_types"),+ frozenset({"1"}))++ def test_every_kemono_row_in_the_ledger_counts_as_judged(self):+ source_id = self._source(provider="kemono", ref="fanbox/1")+ self.store.record(source_id, _fetch([+ FollowCandidate(provider="kemono", external_id="10", title="a"),+ FollowCandidate(provider="kemono", external_id="11", title="b", partial=True),+ ], provider="kemono", ref="fanbox/1"), moment=MOMENT)+ self.assertEqual(self.store.enriched_external_ids(source_id, "kept"),+ frozenset({"10", "11"}))+def test_an_unregistered_mark_is_refused_not_silently_matched(self):source_id = self._source()with self.assertRaises(ValueError):