Peach: Local-first video metadata scraper and media manager.
fix(follow): filter F95 replies without resources
longmeidao90515574060f
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 6b7af2dd5..195f0ed2f 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -844,6 +844,7 @@ class F95ZoneConnector(_BaseConnector):#: latest_data.php 按分类分库,线程不在哪个分类里事先不知道,只能逐个试。CATEGORIES = ("games", "animations", "comics", "assets", "mods")_MASKED_PATH_RE = re.compile(r"^/masked/", re.IGNORECASE)+ _ATTACHMENT_PATH_RE = re.compile(r"^/attachments/\d+/?$", re.IGNORECASE)def fetch(self, ref: str, *, etag: str | None = None,last_modified: str | None = None, page: int = 0) -> SourceFetch:@@ -862,11 +863,13 @@ class F95ZoneConnector(_BaseConnector):self._check_status(response)soup = BeautifulSoup(response.body, "html.parser")title = self._thread_title(soup)- candidates = tuple(self._replies(soup, thread, title or f"thread {thread}"))- if not candidates:+ candidates, parsed, skipped = self._replies(+ soup, thread, title or f"thread {thread}")+ if not parsed:raise FollowSourceError("f95zone 线程页没有解析出任何回复:可能需要登录,或页面结构已变")- return SourceFetch(candidates=candidates, raw_body=response.body, **common)+ return SourceFetch(candidates=candidates, skipped=skipped,+ raw_body=response.body, **common)@staticmethoddef _thread_title(soup) -> str | None:@@ -884,11 +887,15 @@ class F95ZoneConnector(_BaseConnector):def _replies(self, soup, thread: str, thread_title: str):posts = soup.select('article[data-content^="post-"]')+ candidates: list[FollowCandidate] = []+ parsed = 0+ skipped = 0for article in posts[-self.max_items:]:content = str(article.get("data-content") or "")post_id = content.removeprefix("post-")if not post_id.isdigit():continue+ parsed += 1time_node = article.select_one("time")body = article.select_one(".bbWrapper")# XenForo 把被引用的楼层原样嵌在正文里。不剥掉的话,摘要会变成@@ -902,20 +909,58 @@ class F95ZoneConnector(_BaseConnector):if str(node.get("href", "")).startswith("http")]media_links, needs_credential = self._media_links(links)- yield FollowCandidate(+ attachment_urls = self._attachment_urls(body)+ if not media_links and not attachment_urls:+ skipped += 1+ continue+ direct_attachment = next((url for url in attachment_urls+ if urllib.parse.urlsplit(url).hostname+ == "attachments.f95zone.to"), None)+ candidates.append(FollowCandidate(provider=self.provider,external_id=post_id,title=thread_title,url=f"https://f95zone.to/threads/{thread}/post-{post_id}",media_url=media_links[0] if media_links else None,+ thumb_url=direct_attachment,published_at=_iso_from_text(time_node.get("datetime"))if time_node is not None else None,author=_plain_text(str(article.get("data-author") or "")) or None,summary=_plain_text(body.get_text(" ")) if body else None,extra={"thread_id": thread, "link_count": len(media_links),"links": media_links[:8],+ "attachment_count": len(attachment_urls),+ "attachments": attachment_urls[:8],"media_needs_credential": needs_credential},- )+ ))+ return tuple(candidates), parsed, skipped++ @classmethod+ def _attachment_urls(cls, body) -> list[str]:+ """只认回复正文内的 F95 附件,避免把头像或签名图算成发布内容。"""+ if body is None:+ return []+ direct: list[str] = []+ pages: list[str] = []+ for node in body.select("[data-src], a[href]"):+ for attribute in ("data-src", "href"):+ value = str(node.get(attribute) or "").strip()+ if not value.startswith("https://"):+ continue+ try:+ parsed = urllib.parse.urlsplit(value)+ except ValueError:+ continue+ host = (parsed.hostname or "").casefold()+ if host == "attachments.f95zone.to":+ if value not in direct:+ direct.append(value)+ elif (host == "f95zone.to" or host.endswith(".f95zone.to")) \+ and cls._ATTACHMENT_PATH_RE.match(parsed.path):+ if value not in pages:+ pages.append(value)+ # 同一附件通常同时有直链和详情页;优先保留可直接预览的直链,避免重复计数。+ return direct or pagesdef _media_links(self, links: list[str]) -> tuple[list[str], bool]:"""只保留文件分发链接,并用本机 F95 会话解开 masked URL。"""diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex c091b9374..cdf6d4f2a 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -131,9 +131,27 @@ def _thumb_url(item) -> str | None:return None+def _f95_has_resource(media_url: str | None, metadata: dict) -> bool:+ if media_url:+ return True+ links = metadata.get("links")+ if isinstance(links, list) and resource_links(+ "\n".join(str(value) for value in links)):+ return True+ try:+ return int(metadata.get("attachment_count") or 0) > 0+ except (TypeError, ValueError):+ return False++def _excluded_item(item) -> bool:- return (item.provider == "rule34video"- and item.external_id in RULE34VIDEO_EXCLUDED_IDS)+ if (item.provider == "rule34video"+ and item.external_id in RULE34VIDEO_EXCLUDED_IDS):+ return True+ # 旧版曾把没有附件、也没有文件站外链的纯讨论回复写进候选。读取时隐藏,+ # 不改 ledger;有效的历史条目在下一次检查后会补上资源证据并重新出现。+ return (item.provider == "f95zone"+ and not _f95_has_resource(item.media_url, item.metadata))def _item_payload(item) -> dict:@@ -507,6 +525,21 @@ def q_follow(contract, args) -> dict:).fetchall()for status, count in excluded_counts:counts[status] = max(0, int(counts.get(status, 0)) - int(count))+ f95_excluded_counts: dict[str, int] = {}+ for row in connection.execute(+ "SELECT i.status,i.media_url,i.metadata_json FROM follow_item i"+ " JOIN follow_source s ON s.id=i.source_id"+ " WHERE s.enabled=1 AND s.provider='f95zone'").fetchall():+ try:+ metadata = json.loads(row["metadata_json"] or "{}")+ except (TypeError, ValueError):+ metadata = {}+ if not _f95_has_resource(+ row["media_url"], metadata if isinstance(metadata, dict) else {}):+ status = str(row["status"])+ f95_excluded_counts[status] = f95_excluded_counts.get(status, 0) + 1+ for status, count in f95_excluded_counts.items():+ counts[status] = max(0, int(counts.get(status, 0)) - count)suggestions = _suggestions(contract, sources)return {"ok": True,diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex 3a0084d8f..776eadebf 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -93,6 +93,16 @@ Lazy Procrastinator Collection [2026-06-28] [LazyProcrastinator/LazyProcrast]</hClick to expand...</blockquote>Genre spoilers first page have futa spoiler.</div></article>+<article data-content="post-21400001" data-author="LazyProcrastinator">+ <time datetime="2026-08-23T09:00:00+0100">Aug 23, 2026</time>+ <div class="bbWrapper">Preview attached+ <div data-lb-id="attachment6372325"+ data-src="https://attachments.f95zone.to/2026/08/6372325_preview.png">+ <img data-src="https://attachments.f95zone.to/2026/08/6372325_preview.png">+ </div>+ <a href="https://f95zone.to/attachments/6372325/">View attachment</a>+ </div>+</article></body></html>"""FANBOX_JSON = json.dumps({"body": {"posts": [@@ -533,7 +543,8 @@ class F95ZoneConnectorTests(unittest.TestCase):self.assertEqual(seen[0].url, "https://f95zone.to/threads/50685/latest")self.assertEqual(result.semantics, "release")self.assertEqual([c.external_id for c in result.candidates],- ["21383374", "21394555"])+ ["21383374", "21400001"])+ self.assertEqual(result.skipped, 1)self.assertEqual(result.candidates[0].author, "Jkhomie1198")self.assertEqual(result.candidates[0].published_at, "2026-08-21T04:14:09Z")@@ -544,13 +555,22 @@ class F95ZoneConnectorTests(unittest.TestCase):self.assertNotIn("F95zone", title)self.assertIn("[2026-06-28]", title)- def test_quoted_posts_are_stripped_from_the_reply_body(self):+ def test_quoted_links_and_discussion_only_replies_are_skipped(self):# 引用块里的链接是被引用那层发的。不剥掉会把追更信号指向错误的楼层。result = F95ZoneConnector(transport=_transport(body=F95_HTML)).fetch("50685")- second = result.candidates[1]- self.assertEqual(second.summary, "Genre spoilers first page have futa spoiler.")- self.assertIsNone(second.media_url)- self.assertEqual(second.extra["link_count"], 0)+ self.assertNotIn("21394555", [row.external_id for row in result.candidates])+ self.assertEqual(result.skipped, 1)++ def test_reply_with_an_attachment_is_kept_and_gets_a_thumbnail(self):+ result = F95ZoneConnector(transport=_transport(body=F95_HTML)).fetch("50685")+ candidate = result.candidates[1]+ self.assertEqual(candidate.external_id, "21400001")+ self.assertEqual(candidate.thumb_url,+ "https://attachments.f95zone.to/2026/08/6372325_preview.png")+ self.assertEqual(candidate.extra["attachment_count"], 1)+ self.assertEqual(candidate.extra["attachments"], [+ "https://attachments.f95zone.to/2026/08/6372325_preview.png",+ ])def test_media_is_flagged_as_needing_a_login_session(self):# 发现不需要 cookie,取附件需要。下载动作必须先看这个标志。@@ -580,9 +600,20 @@ class F95ZoneConnectorTests(unittest.TestCase):b"https://example.com/creator",)result = F95ZoneConnector(transport=_transport(body=body)).fetch("50685")- self.assertIsNone(result.candidates[0].media_url)- self.assertEqual(result.candidates[0].extra["link_count"], 0)- self.assertFalse(result.candidates[0].extra["media_needs_credential"])+ self.assertEqual([row.external_id for row in result.candidates], ["21400001"])+ self.assertEqual(result.skipped, 2)++ def test_a_valid_page_with_only_discussion_returns_an_empty_fetch(self):+ body = F95_HTML.replace(+ b"https://f95zone.to/masked/gofile.io/50685/abc",+ b"https://example.com/creator",+ ).replace(+ b'<article data-content="post-21400001"',+ b'<article data-content="comment-21400001"',+ )+ result = F95ZoneConnector(transport=_transport(body=body)).fetch("50685")+ self.assertEqual(result.candidates, ())+ self.assertEqual(result.skipped, 2)def test_only_absolute_links_count_as_media(self):result = F95ZoneConnector(transport=_transport(body=F95_HTML)).fetch("50685")diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex f0129bfec..db7661292 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -190,6 +190,24 @@ class FollowContractTests(unittest.TestCase):])self.assertNotIn("media_url", item)+ def test_f95_discussion_without_attachments_or_file_links_is_hidden(self):+ self._seed(candidates=(+ FollowCandidate(+ provider="f95zone", external_id="discussion", title="Thread",+ url="https://f95zone.to/threads/50685/post-discussion",+ summary="Thanks for sharing"),+ FollowCandidate(+ provider="f95zone", external_id="attachment", title="Thread",+ url="https://f95zone.to/threads/50685/post-attachment",+ thumb_url="https://attachments.f95zone.to/preview.png",+ extra={"attachment_count": 1,+ "attachments": ["https://attachments.f95zone.to/preview.png"]}),+ ), provider="f95zone", ref="50685", semantics="release")+ payload = self._get()+ items = [group["primary"] for group in payload["groups"]]+ self.assertEqual([item["external_id"] for item in items], ["attachment"])+ self.assertEqual(payload["counts"]["new"], 1)+def test_old_archive_images_get_a_thumbnail_without_rewriting_the_ledger(self):self._seed(candidates=(FollowCandidate(provider="kemono", external_id="1", title="Image release",@@ -569,11 +587,16 @@ class FollowContractTests(unittest.TestCase):url="https://f95zone.to/threads/50685/post-21383374",published_at="2026-08-21T04:14:09Z", author="Jkhomie1198",summary="New batch up Gofile",- extra={"media_needs_credential": True}),+ media_url="https://f95zone.to/masked/gofile.io/50685/abc",+ extra={"links": [+ "https://f95zone.to/masked/gofile.io/50685/abc"],+ "media_needs_credential": True}),FollowCandidate(provider="f95zone", external_id="21394555",title="Lazy Procrastinator Collection [2026-06-28]",url="https://f95zone.to/threads/50685/post-21394555",- published_at="2026-08-22T18:09:23Z"),+ published_at="2026-08-22T18:09:23Z",+ thumb_url="https://attachments.f95zone.to/preview.png",+ extra={"attachment_count": 1}),))group = self._get()["groups"][0]self.assertTrue(group["is_release"])