Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(follow): fanbox 支持全量回抓并补收存量封面

longmeidao919b921ca190
diff --git a/src/peach/follow_providers.py b/src/peach/follow_providers.py
index eca64b505..9942436aa 100644
--- a/src/peach/follow_providers.py
+++ b/src/peach/follow_providers.py
@@ -64,9 +64,11 @@ PROVIDERS: dict[str, ProviderSpec] = {
spec.key: spec
for spec in (
# 官方渠道:只读公开免费发布,身份可信,所以优先做主条目;媒体走各自详情接口,
- # 不经本地代理,因此没有 hosts。
+ # 不经本地代理,因此没有 hosts。fanbox 的站点分页是 `post.paginateCreator`
+ # 给出的游标页清单,能稳定走完整个创作者,所以同样可回填。
ProviderSpec("fanbox", "FANBOX", source_url="https://{ref}.fanbox.cc/",
- url_hosts=("fanbox.cc",), priority=1, official_identity=True),
+ url_hosts=("fanbox.cc",), priority=1, official_identity=True,
+ backfill=True),
ProviderSpec("subscribestar", "SubscribeStar", source_url="https://{ref}",
url_hosts=("subscribestar.adult", "subscribestar.com"),
priority=2, official_identity=True),
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index e58cba63e..d43fff38f 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -2139,9 +2139,10 @@ class FanboxConnector(_BaseConnector):
provider = "fanbox"
#: 2026-08-27 实测公开接口单页 10 条,整页都能补上。
DEFAULT_ENRICH_BUDGET = 10
- #: 正文类型只有 post.info 给。详情被 Cloudflare 挡回来时它是 null,所以拿它
- #: 当判据能让那一行下一轮再试一次,而不是当成「已经补齐」。
- ENRICHED_MARK = "post_type"
+ #: 详情补齐一轮的标记:补全阶段在 extra 里写 `cover_harvested`。拿新键当判据,
+ #: 按 `post_type` 判成已补齐的旧行缺这一个键,下一轮检查会各重探一次详情——
+ #: 封面是这次才收进媒体清单的,旧行只有重探才能拿到。
+ ENRICHED_MARK = "cover_harvested"
_CREATOR_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
@classmethod
@@ -2192,20 +2193,25 @@ class FanboxConnector(_BaseConnector):
creator = str(ref or "").strip()
if not self._CREATOR_RE.fullmatch(creator):
raise FollowSourceError(f"fanbox 的 ref 必须是创作者 id,收到:{ref!r}")
- if page:
- raise FollowSourceError("fanbox 官方来源暂不支持向前翻页")
# 2026-08-27 实测公开接口单页为 10 条;不要把本地通用上限 100 原样塞给站点。
query = urllib.parse.urlencode({"creatorId": creator,
"limit": min(self.max_items, 10)})
url = f"https://api.fanbox.cc/post.listCreator?{query}"
- common, response = self._request(url, ref=creator, etag=etag,
- last_modified=last_modified)
+ if page:
+ # 历史页是另一份资源,没有配过条件的缓存凭据,不带 If-None-Match。
+ common, response = self._request(self._history_page_url(creator, page),
+ ref=creator)
+ else:
+ common, response = self._request(url, ref=creator, etag=etag,
+ last_modified=last_modified)
if response is None:
return SourceFetch(not_modified=True, **common)
payload = self.parse_json(response)
posts = ((payload or {}).get("body") or {}).get("posts")
if not isinstance(posts, list):
raise FollowSourceError("fanbox 返回的帖子列表格式不符")
+ if page and not posts:
+ raise FollowHistoryEnd("没有更多历史内容")
listed, skipped = [], 0
for post in posts[:self.max_items]:
if not isinstance(post, dict) or not str(post.get("id") or "").isdigit():
@@ -2219,6 +2225,27 @@ class FanboxConnector(_BaseConnector):
return SourceFetch(candidates=candidates, skipped=skipped,
probed=probed, raw_body=response.body, **common)
+ def _history_page_url(self, creator: str, page: int) -> str:
+ """第 page 页历史(page 从 1 起)对应的站点游标地址。
+
+ 站点自己的分页是 `post.paginateCreator`:先给一份按新到旧排序的游标页
+ 清单,每张页 URL 用 `firstPublishedDatetime`+`firstId` 定位、含端点——
+ 第 1 张就是最新一页,往后逐页更旧。公开接口不认 `offset` 参数,数字
+ 偏移翻不动页。游标清单走完(page 超出张数)就是没有更多历史。
+ """
+ common, response = self._request(
+ "https://api.fanbox.cc/post.paginateCreator?"
+ + urllib.parse.urlencode({"creatorId": creator}), ref=creator)
+ if response is None:
+ raise FollowSourceError("fanbox 历史页清单意外返回 304")
+ payload = self.parse_json(response)
+ pages = ((payload or {}).get("body") or {}).get("pageUrls")
+ if not isinstance(pages, list) or not pages:
+ raise FollowSourceError("fanbox 的历史页清单格式不符")
+ if not 0 < page <= len(pages):
+ raise FollowHistoryEnd("没有更多历史内容")
+ return str(pages[page - 1])
+
def _listed(self, post: dict, creator: str) -> FollowCandidate:
"""只用 post.listCreator 给的字段造一条候选。不联网。
@@ -2271,6 +2298,7 @@ class FanboxConnector(_BaseConnector):
summary=detail["summary"] or candidate.summary,
extra={**candidate.extra, "links": links, "media_items": media_items,
"media_error": None,
+ "cover_harvested": True,
"post_type": detail.get("post_type"),
"image_count": detail.get("image_count", 0),
"video_count": detail.get("video_count", 0),
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 769fb7778..a128722a9 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -145,6 +145,7 @@ _ENRICHED_PREDICATES = {
"published_at": "published_at IS NOT NULL AND published_at<>''",
"tag_types": "json_extract(metadata_json,'$.tag_types') IS NOT NULL",
"post_type": "json_extract(metadata_json,'$.post_type') IS NOT NULL",
+ "cover_harvested": "json_extract(metadata_json,'$.cover_harvested') IS NOT NULL",
}
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index ffaced5a5..e1682cff3 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -1871,6 +1871,21 @@ def _run_follow_check(contract, body, job_id=None) -> dict:
row, credentials=credentials, writer=writer,
connector_factory=build_connector, older=older, progress=progress,
initial_days=initial_days))
+ if older and body.get("backfill_all"):
+ # 全量回抓:一页记完接着抓下一页,直到站点说没有更多、某一页失败,
+ # 或游标不再前进(防环)。游标推进落在 ledger 的 `backfill_page`,
+ # 每轮把结果页写回工作行,下一轮从那里接着算。
+ rounds = 0
+ while (result.get("ok") and not result.get("exhausted")
+ and isinstance(result.get("page"), int) and rounds < 500):
+ if job_id and contract.follow_job.snapshot() is None:
+ break
+ row["backfill_page"] = result["page"]
+ result = _check_payload(run_check(
+ row, credentials=credentials, writer=writer,
+ connector_factory=build_connector, older=True, progress=progress,
+ initial_days=initial_days))
+ rounds += 1
result["author"] = _author_display_name(row)
results.append(result)
progress()
diff --git a/tests/test_follow_providers.py b/tests/test_follow_providers.py
index 394cc22e9..c7e4af218 100644
--- a/tests/test_follow_providers.py
+++ b/tests/test_follow_providers.py
@@ -61,11 +61,13 @@ class ProviderRegistryTests(unittest.TestCase):
self.assertEqual(follow_providers.PROVIDERS[key].hosts, ())
self.assertNotIn(key, _PROVIDER_HOSTS)
- def test_backfill_providers_are_archive_sites_with_real_paging(self):
- """只有支持真实历史分页的来源才显示「抓更早一页」;官方渠道不支持。"""
- self.assertTrue(_BACKFILL_PROVIDERS.isdisjoint(_OFFICIAL_IDENTITY_PROVIDERS))
- for key in _BACKFILL_PROVIDERS:
- self.assertIn(key, CONNECTORS)
+ def test_backfill_providers_are_sites_with_real_paging(self):
+ """「抓更早一页」只给历史页走得完的来源:归档站按偏移翻页,fanbox 走
+ 站点自己的游标清单(`post.paginateCreator`)。官方身份与可回填是两回事:
+ fanbox 两者都是,subscribestar、patreon 没有公开分页就不进这一档。"""
+ self.assertTrue(_BACKFILL_PROVIDERS <= set(CONNECTORS))
+ self.assertIn("fanbox", _BACKFILL_PROVIDERS)
+ self.assertTrue(_BACKFILL_PROVIDERS.isdisjoint({"subscribestar", "patreon"}))
def test_registry_carries_no_credential_policy(self):
"""凭据同步策略必须留在 CREDENTIAL_GUIDE 里逐字段声明,不进这张通用表。
diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.py
index 7f8dce1ad..563f65ee0 100644
--- a/tests/test_follow_sources.py
+++ b/tests/test_follow_sources.py
@@ -311,11 +311,49 @@ class OfficialConnectorTests(unittest.TestCase):
self.assertEqual(result.candidates[0].extra["links"],
["https://gofile.io/d/OS2Qz9"])
self.assertEqual(result.candidates[0].extra["post_type"], "article")
+ self.assertTrue(result.candidates[0].extra["cover_harvested"])
self.assertEqual(result.candidates[0].extra["image_count"], 2)
self.assertEqual(result.candidates[0].extra["video_count"], 0)
self.assertEqual(result.candidates[0].extra["file_count"], 0)
self.assertEqual(result.probed, 1)
+ def test_fanbox_history_pages_follow_the_site_cursor_list(self):
+ seen = []
+ def route(request):
+ seen.append(request.url)
+ if "paginateCreator" in request.url:
+ return HttpResponse(200, {}, json.dumps({"body": {"pageUrls": [
+ "https://api.fanbox.cc/post.listCreator?creatorId=x&firstId=11",
+ "https://api.fanbox.cc/post.listCreator?creatorId=x&firstId=21",
+ ]}}).encode())
+ return HttpResponse(200, {}, FANBOX_JSON)
+ result = FanboxConnector(transport=_routed(route)).fetch("ffxivinitiala", page=2)
+ self.assertIn("paginateCreator", seen[0])
+ self.assertIn("firstId=21", seen[1])
+ # 其余请求是第二阶段的详情补全。
+ self.assertTrue(all("post.info" in url for url in seen[2:]))
+ self.assertEqual(result.candidates[0].external_id, "12489354")
+
+ def test_fanbox_history_walk_ends_when_the_cursor_list_runs_out(self):
+ def route(request):
+ return HttpResponse(200, {}, json.dumps({"body": {"pageUrls": [
+ "https://api.fanbox.cc/post.listCreator?creatorId=x&firstId=11",
+ ]}}).encode())
+ connector = FanboxConnector(transport=_routed(route))
+ with self.assertRaises(FollowHistoryEnd):
+ connector.fetch("ffxivinitiala", page=2)
+
+ def test_fanbox_history_walk_ends_on_an_empty_cursor_page(self):
+ def route(request):
+ if "paginateCreator" in request.url:
+ return HttpResponse(200, {}, json.dumps({"body": {"pageUrls": [
+ "https://api.fanbox.cc/post.listCreator?creatorId=x&firstId=11",
+ ]}}).encode())
+ return HttpResponse(200, {}, json.dumps({"body": {"posts": []}}).encode())
+ connector = FanboxConnector(transport=_routed(route))
+ with self.assertRaises(FollowHistoryEnd):
+ connector.fetch("ffxivinitiala", page=1)
+
def test_a_fanbox_video_post_keeps_the_cover_as_its_thumbnail(self):
"""视频帖的缩略图退回列表封面,不拿视频地址当图。
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 739f542ce..daa2d9104 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -292,6 +292,35 @@ class FollowContractTests(unittest.TestCase):
if row["provider"] == "f95zone")
self.assertFalse(source["can_backfill"])
+ def test_backfill_all_walks_pages_until_history_ends(self):
+ self._seed()
+ pages = []
+
+ class _Paged:
+ provider, semantics = "rule34video", "work"
+
+ def fetch(self, ref, *, etag=None, last_modified=None, page=0):
+ pages.append(page)
+ if page > 3:
+ raise FollowHistoryEnd("没有更多历史内容")
+ return SourceFetch(provider="rule34video", ref=ref,
+ request_url="https://rule34video.test/x",
+ semantics="work", candidates=(), raw_body=b"<html/>")
+
+ original = web_follow.build_connector
+ web_follow.build_connector = lambda provider, **kwargs: _Paged()
+ self.addCleanup(setattr, web_follow, "build_connector", original)
+
+ result = self._post("/api/follow/check", {"older": True, "backfill_all": True})
+ # 从游标 0 起步:抓 1、2、3,第 4 页就是尽头;游标停在最后成功的那页。
+ self.assertEqual(pages, [1, 2, 3, 4])
+ self.assertTrue(result["results"][0]["exhausted"])
+ with self.contract.database.read_connection() as connection:
+ state = connection.execute(
+ "SELECT backfill_page FROM follow_source WHERE id=?",
+ (self._get()["groups"][0]["primary"]["source_id"],)).fetchone()[0]
+ self.assertEqual(state, 3)
+
def test_history_end_is_a_neutral_success_and_does_not_advance_cursor(self):
source_id = self._seed()