Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(follow): 首次采集补足 30 条,查找先读 F95 名片并随登记写下别名

longmeidao043724230555
diff --git a/docs/BOARD_UI.md b/docs/BOARD_UI.md
index 801661f18..95f6571d4 100644
--- a/docs/BOARD_UI.md
+++ b/docs/BOARD_UI.md
@@ -12,7 +12,7 @@
## 创作者别名与扫描操作
-创作者别名区域依次提供「手动添加别名」、待合并与已保存列表。关注设置中的「首次采集历史范围」默认最近 30 天,可选 7 天、90 天或不限时间;按发布时间排除较早内容,无日期条目仍保留。每个新来源首次采集时固定边界,重试和自动更新沿用;已有来源不追溯处理,手动历史分页先补回首页被跳过的内容,再向前翻页。列表统计包含全部已导入的未看条目。
+创作者别名区域依次提供「手动添加别名」、待合并与已保存列表。查找关注来源先问 F95zone,登录后读命中线程首楼名片上的其他平台手柄,再拿手柄去其余来源查;勾选登记带手柄的结果时,手柄直接存为检索词的别名,不进待合并。关注设置中的「首次采集历史范围」默认最近 30 天,可选 7 天、90 天或不限时间;按发布时间排除较早内容,无日期条目仍保留;范围内不足 30 条时补入范围外最近的条目,首页不够就往前翻页(最多 5 页),边界随之挪到收下的最早一条。每个新来源首次采集时固定边界,重试和自动更新沿用;已有来源不追溯处理,手动历史分页先补回首页被跳过的内容,再向前翻页。列表统计包含全部已导入的未看条目。
2026-09-13 核对 [Table](https://www.boardui.com/components/table) 和 [Data Table](https://www.boardui.com/components/data-table)。实时表格使用 `role="grid"`,单元格为 14px、内边距 10px 12px;页面 CSS 部署标识为 `dpl_QqDLotDUMyvoaXmnBoPEK5tSk8mc`。官方 `https://www.boardui.com/r/table.json` 的 SHA-256 为 `fc12a8f2f4012d9e983e0b9bbb10f9fe3288d74046566d2623d60e7056c50d88`。
diff --git a/src/peach/follow_check.py b/src/peach/follow_check.py
index cea287c67..085d07040 100644
--- a/src/peach/follow_check.py
+++ b/src/peach/follow_check.py
@@ -14,11 +14,20 @@ from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from typing import Mapping
+from . import follow_providers
from .follow import FollowHistoryEnd, FollowSourceError
from .follow_secrets import CredentialError
-from .follow_sources import SourceFetch, enrichment_mark, within_history
+from .follow_sources import SourceFetch, enrichment_mark, history_window, published_stamp
from .follow_store import RecordOutcome
+#: 新来源首次采集至少收下多少条。历史范围只按天数算时,更新稀疏的作者一条都
+#: 进不来;按条数又会让高产作者一下子塞满未看。取 30:大约一屏,kemono 一页 50
+#: 条不必翻页,rule34video(一页 24)、fanbox(一页 10)翻一两页就够。
+INITIAL_HISTORY_FLOOR = 30
+#: 为补足下限最多往前翻几页。每页都是真实请求,下限不值得拿无界的翻页去换。
+MAX_FLOOR_PAGES = 5
+_BACKFILL_PROVIDERS = follow_providers.backfill_providers()
+
@dataclass(frozen=True)
class CheckResult:
@@ -106,19 +115,15 @@ def run_check(row: Mapping, *, credentials, writer, connector_factory,
base = {"source_id": source_id, "provider": provider, "ref": ref,
"label": str(row["label"] or ""), "page": page, "older": older}
force = bool(row.get("force_media_reparse")) or replay_first
- history_after = metadata.get('initial_history_after')
- if 'initial_history_after' not in metadata and not row.get('last_checked_at'):
- history_after = ((moment - timedelta(days=initial_days)).isoformat()
- if initial_days and not older else '')
- with writer() as store:
- store.merge_source_metadata(source_id, {'initial_history_after': history_after}, moment)
- cutoff = datetime.fromisoformat(history_after) if history_after and not older else None
+ cutoff, floor = _history_limits(row, metadata, writer, moment,
+ older=older, initial_days=initial_days)
try:
connector = build_connector_for(
provider, credentials, connector_factory,
enrich_skip=frozenset(row.get("enrich_skip") or ()))
connector.history_after = cutoff
connector.history_skipped = 0
+ connector.history_floor = floor
if progress is not None:
connector.progress = progress
fetch = connector.fetch(
@@ -135,7 +140,7 @@ def run_check(row: Mapping, *, credentials, writer, connector_factory,
return _record_failure(writer, base, error, moment, "unauthorized")
except FollowSourceError as error:
return _record_failure(writer, base, error, moment, "error")
- candidates = tuple(candidate for candidate in fetch.candidates if within_history(candidate, cutoff))
+ candidates = history_window(fetch.candidates, cutoff, floor)
history_skipped = getattr(connector, 'history_skipped', 0) + len(fetch.candidates) - len(candidates)
fetch = replace(fetch, candidates=candidates)
with writer() as store:
@@ -148,11 +153,76 @@ def run_check(row: Mapping, *, credentials, writer, connector_factory,
source_id, fetch,
creator_aliases=store.creator_aliases(row["entity_id"]),
moment=moment, page=page)
+ if floor and not fetch.not_modified:
+ fetch, outcome = _fill_floor(row, connector, writer, fetch, outcome, cutoff, floor, moment)
+ with writer() as store:
learned = store.learn_official_author_alias(provider, ref, fetch.candidates)
return CheckResult(**base, fetch=fetch, outcome=outcome,
author_alias_learned=learned, history_skipped=history_skipped)
+def _history_limits(row, metadata: dict, writer, moment: datetime, *,
+ older: bool, initial_days: int) -> tuple[datetime | None, int]:
+ """这次检查的历史边界与条数下限;新来源首次检查时把两者固定进 metadata。
+
+ 重试和自动更新沿用固定下来的值,不按当时的设置重算。往回翻页不设边界。
+ """
+ history_after = metadata.get('initial_history_after')
+ floor = int(metadata.get('initial_history_floor') or 0)
+ if 'initial_history_after' not in metadata and not row.get('last_checked_at'):
+ history_after = ((moment - timedelta(days=initial_days)).isoformat()
+ if initial_days and not older else '')
+ floor = INITIAL_HISTORY_FLOOR if history_after else 0
+ with writer() as store:
+ store.merge_source_metadata(int(row["id"]), {'initial_history_after': history_after,
+ 'initial_history_floor': floor}, moment)
+ if not history_after or older:
+ return None, 0
+ return datetime.fromisoformat(history_after), floor
+
+
+def _fill_floor(row, connector, writer, fetch, outcome, cutoff, floor, moment):
+ """首次采集不足下限时往前翻页补足,再把边界挪到实际收下的最早一条。
+
+ 往前翻的页整页收下,回填游标因此和「已经抓到第几页」一致,之后手动加载更早
+ 接着往前走,不会漏掉半页。边界跟着挪,是为了之后的常规检查仍把这些条目
+ 算在范围内,不在每次检查里重复报「跳过」。
+ """
+ source_id, provider, ref = int(row["id"]), str(row["provider"]), str(row["ref"])
+ kept = list(fetch.candidates)
+ totals = {"discovered": outcome.discovered, "added": outcome.added, "updated": outcome.updated}
+ counts = {"skipped": fetch.skipped, "skipped_compilations": fetch.skipped_compilations,
+ "probed": fetch.probed}
+ page = 0
+ connector.history_after = None
+ while len(kept) < floor and provider in _BACKFILL_PROVIDERS and page < MAX_FLOOR_PAGES:
+ page += 1
+ try:
+ more = connector.fetch(ref, etag=None, last_modified=None, page=page)
+ except FollowHistoryEnd:
+ break
+ except (CredentialError, FollowSourceError):
+ # 首页已经落库,补页失败只是这次补得少,之后手动加载更早还能接着翻。
+ break
+ with writer() as store:
+ extra = store.record(source_id, more,
+ creator_aliases=store.creator_aliases(row["entity_id"]),
+ moment=moment, page=page)
+ kept.extend(more.candidates)
+ for key in totals:
+ totals[key] += getattr(extra, key)
+ for key in counts:
+ counts[key] += getattr(more, key)
+ stamps = [stamp for stamp in map(published_stamp, kept) if stamp is not None]
+ patch = {'initial_history_floor': 0}
+ if stamps and min(stamps) < cutoff:
+ patch['initial_history_after'] = min(stamps).isoformat()
+ with writer() as store:
+ store.merge_source_metadata(source_id, patch, moment)
+ return (replace(fetch, candidates=tuple(kept), **counts),
+ replace(outcome, **totals))
+
+
def _record_failure(writer, base: dict, error: Exception, moment: datetime,
status: str) -> CheckResult:
with writer() as store:
diff --git a/src/peach/follow_discovery.py b/src/peach/follow_discovery.py
index 607857ac8..e133b713c 100644
--- a/src/peach/follow_discovery.py
+++ b/src/peach/follow_discovery.py
@@ -14,7 +14,7 @@ import re
import time
import urllib.parse
from concurrent.futures import ThreadPoolExecutor
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from pathlib import Path
from .follow import FollowSourceError
@@ -77,6 +77,8 @@ class Candidate:
semantics: str
#: 为什么认为它命中了。界面照实显示,不要替用户断言「就是这个」。
evidence: str
+ #: 作者名片上与检索词不同的手柄。人勾选登记这一条时,它们随之记成检索词的别名。
+ aliases: tuple[str, ...] = ()
@dataclass(frozen=True)
@@ -230,19 +232,19 @@ def _kemono_candidates(provider: str, term: str, index: CreatorIndex) -> list[Ca
def _fanbox_candidates(archive_candidates: list[Candidate], transport) -> list[Candidate]:
"""Resolve verified FANBOX archive identities to their official creator pages."""
- user_ids = []
+ user_ids: dict[str, tuple[str, ...]] = {}
for candidate in archive_candidates:
service, separator, user_id = candidate.ref.partition("/")
if (candidate.provider in KemonoConnector.HOSTS and separator
and service == "fanbox" and user_id.isdigit()
and user_id not in user_ids):
- user_ids.append(user_id)
+ user_ids[user_id] = candidate.aliases
candidates = []
- for user_id in user_ids[:MAX_CANDIDATES_PER_SOURCE]:
+ for user_id, aliases in list(user_ids.items())[:MAX_CANDIDATES_PER_SOURCE]:
profile = resolve_official_profile("fanbox", user_id, transport=transport)
candidates.append(Candidate(
"fanbox", profile.creator_id, profile.url,
- profile.name, "work", "FANBOX 官方资料与归档身份一致",
+ profile.name, "work", "FANBOX 官方资料与归档身份一致", aliases,
))
return candidates
@@ -459,28 +461,71 @@ def _f95_candidates(term: str, transport,
return _forum_candidates("f95zone", "f95zone.to", term, connector)
-DEFAULT_PROVIDERS = ("kemono", "coomer", "pawchive", "fanbox", "rule34video",
- "rule34xxx", "simpcity", "f95zone")
+#: 最多读几个 F95 命中线程的首楼名片。每读一个是一次登录态请求,排在后面的命中
+#: 多半是标题碰巧带这个词的别人的线程。
+MAX_PROFILE_THREADS = 2
+#: 名片手柄最多拿几个去其余来源再查一遍。每个手柄都要把名字类来源重问一轮。
+MAX_PROFILE_HANDLES = 4
+#: 名片上不当作者别名的服务。论坛账号名常常是搬运工自己的账号,
+#: 而 pixiv 的身份是一串数字,当别名只会在列表里多出一个数字「作者」。
+PROFILE_ALIAS_SKIP_SERVICES = frozenset({"pixiv", "f95zone", "simpcity"})
+#: 名片手柄会拿去再查一遍的来源:按名字、id 或标签查的那几家。
+_HANDLE_SEARCH_PROVIDERS = frozenset({"kemono", "coomer", "pawchive", "rule34video",
+ "rule34xxx", "simpcity"})
+#: 只按名字或标签查、纯数字的词不去碰运气的来源。
+_NAME_ONLY_PROVIDERS = frozenset({"rule34video", "rule34xxx", "simpcity"})
+
+DEFAULT_PROVIDERS = ("f95zone", "kemono", "coomer", "pawchive", "fanbox", "rule34video",
+ "rule34xxx", "simpcity")
def discovery_plan(term: str, providers: tuple[str, ...] | None = None) -> tuple[str, ...]:
"""这一轮实际会去问的来源,按执行顺序。
- 数字的词不去 rule34video / rule34.xxx / simpcity 碰运气——那三个都按名字或
- 标签查——fanbox 只是把归档身份换算成官方页。计划先算出来,调用方才能把
- 进度摊到每个来源上,而不是整轮查完只跳一格。
+ F95 排第一:它的线程首楼整理了作者在其他平台的账号,名片上的手柄要赶在其余
+ 来源开查之前拿到。数字的词不去 rule34video / rule34.xxx / simpcity 碰运气——
+ 那三个都按名字或标签查——fanbox 只是把归档身份换算成官方页。计划先算出来,
+ 调用方才能把进度摊到每个来源上,而不是整轮查完只跳一格。
"""
wanted = providers or DEFAULT_PROVIDERS
- tasks = [provider for provider in ("kemono", "coomer", "pawchive")
- if provider in wanted]
- if "fanbox" in wanted:
- tasks.append("fanbox")
- if not _NUMERIC_RE.match(term):
- tasks.extend(provider for provider in ("rule34video", "rule34xxx", "simpcity")
- if provider in wanted)
- if "f95zone" in wanted:
- tasks.append("f95zone")
- return tuple(tasks)
+ return tuple(provider for provider in DEFAULT_PROVIDERS if provider in wanted
+ and not (provider in _NAME_ONLY_PROVIDERS and _NUMERIC_RE.match(term)))
+
+
+def _f95_profile_handles(candidates: list[Candidate], term: str, transport,
+ credential: Credential | None) -> tuple[list[Candidate], list[str]]:
+ """F95 命中线程首楼名片上、与检索词不同的手柄。
+
+ 搜 `cekc` 只能在 rule34.xxx 上碰到以它开头的标签,作者在那里写作 `Ceeeeekc`;
+ F95 首楼替人把这些写法整理好了。读名片要登录 cookie,没有就不读,查找照常。
+ 返回带上各自手柄的 F95 候选,以及去重后要拿去其余来源再查的手柄。
+ """
+ if credential is None or not credential.values.get("cookie"):
+ return candidates, []
+ connector = F95ZoneConnector(transport=transport, credential=credential)
+ wanted = identity_key(term)
+ handles: dict[str, str] = {}
+ marked: list[Candidate] = []
+ for index, candidate in enumerate(candidates):
+ if index >= MAX_PROFILE_THREADS:
+ marked.append(candidate)
+ continue
+ try:
+ links = connector.thread_profile(candidate.ref)["links"]
+ except (FollowSourceError, CredentialError):
+ links = ()
+ own: list[str] = []
+ for link in links:
+ handle = str(link.get("handle") or "").strip()
+ key = identity_key(handle)
+ if (str(link.get("service") or "") in PROFILE_ALIAS_SKIP_SERVICES
+ or not key or key == wanted):
+ continue
+ if handle not in own:
+ own.append(handle)
+ handles.setdefault(key, handle)
+ marked.append(replace(candidate, aliases=tuple(own)) if own else candidate)
+ return marked, list(handles.values())[:MAX_PROFILE_HANDLES]
def discover(term: str, *, secrets_root: Path, state_root: Path,
@@ -509,24 +554,48 @@ def discover(term: str, *, secrets_root: Path, state_root: Path,
failures: dict[str, str] = {}
external_searches: list[ExternalSearch] = []
+ handles: list[str] = []
+
def run(name: str, fn) -> None:
try:
- found.extend(fn())
+ found.extend(fn(text))
except (FollowSourceError, CredentialError) as error:
failures[name] = str(error)
+ if name not in _HANDLE_SEARCH_PROVIDERS:
+ return
+ for handle in handles:
+ if name in _NAME_ONLY_PROVIDERS and _NUMERIC_RE.match(handle):
+ continue
+ try:
+ hits = fn(handle)
+ except (FollowSourceError, CredentialError):
+ # 检索词本身那一问的成败已经报过;手柄是追加的一轮,问不成就少这几条。
+ continue
+ known = {(row.provider, canonical_source_ref(row.provider, row.ref)) for row in found}
+ found.extend(
+ replace(hit, evidence=f"F95 首楼名片上的手柄 {handle}:{hit.evidence}",
+ aliases=(handle,))
+ for hit in hits
+ if (hit.provider, canonical_source_ref(hit.provider, hit.ref)) not in known)
+
+ def f95(term: str) -> list[Candidate]:
+ credential = credentials.load("f95zone")
+ hits, learned = _f95_profile_handles(
+ _f95_candidates(term, transport, credential), term, transport, credential)
+ handles.extend(learned)
+ return hits
runners = {
- "kemono": lambda: _kemono_candidates("kemono", text, index),
- "coomer": lambda: _kemono_candidates("coomer", text, index),
- "pawchive": lambda: _kemono_candidates("pawchive", text, index),
- "fanbox": lambda: _fanbox_candidates(found, transport),
- "rule34video": lambda: _rule34video_candidates(text, transport),
- "rule34xxx": lambda: _rule34xxx_candidates(text, transport,
- credentials.load("rule34xxx")),
- "simpcity": lambda: _simpcity_candidates(text, transport,
- credentials.load("simpcity")),
- "f95zone": lambda: _f95_candidates(text, transport,
- credentials.load("f95zone")),
+ "f95zone": f95,
+ "kemono": lambda term: _kemono_candidates("kemono", term, index),
+ "coomer": lambda term: _kemono_candidates("coomer", term, index),
+ "pawchive": lambda term: _kemono_candidates("pawchive", term, index),
+ "fanbox": lambda _term: _fanbox_candidates(found, transport),
+ "rule34video": lambda term: _rule34video_candidates(term, transport),
+ "rule34xxx": lambda term: _rule34xxx_candidates(term, transport,
+ credentials.load("rule34xxx")),
+ "simpcity": lambda term: _simpcity_candidates(term, transport,
+ credentials.load("simpcity")),
}
for position, name in enumerate(tasks):
if on_progress:
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index ad4fa635f..655209c11 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -186,17 +186,38 @@ class SourceFetch:
raw_body: bytes | None = field(default=None, repr=False, compare=False)
-def within_history(candidate: FollowCandidate, after: datetime | None) -> bool:
- """有限历史范围只排除日期明确且早于边界的条目。"""
- if after is None or not candidate.published_at:
- return True
+def published_stamp(candidate: FollowCandidate) -> datetime | None:
+ """候选的发布时间;没有或解析不了就是 `None`。"""
+ if not candidate.published_at:
+ return None
try:
stamp = datetime.fromisoformat(str(candidate.published_at).replace('Z', '+00:00'))
except (TypeError, ValueError, OverflowError):
- return True
- if stamp.tzinfo is None:
- stamp = stamp.replace(tzinfo=timezone.utc)
- return stamp >= after
+ return None
+ return stamp if stamp.tzinfo is not None else stamp.replace(tzinfo=timezone.utc)
+
+
+def within_history(candidate: FollowCandidate, after: datetime | None) -> bool:
+ """有限历史范围只排除日期明确且早于边界的条目。"""
+ stamp = published_stamp(candidate) if after is not None else None
+ return stamp is None or stamp >= after
+
+
+def history_window(candidates, after: datetime | None, floor: int = 0) -> tuple:
+ """有限历史范围内的条目;不足 `floor` 条时按列表顺序补入更早的,补满为止。
+
+ 列表是新的在前,所以补进来的是边界之外最近的那几条。
+ """
+ within = sum(1 for candidate in candidates if within_history(candidate, after))
+ spare = max(0, floor - within)
+ kept = []
+ for candidate in candidates:
+ if within_history(candidate, after):
+ kept.append(candidate)
+ elif spare:
+ kept.append(candidate)
+ spare -= 1
+ return tuple(kept)
def _iso_utc(value: datetime) -> str:
@@ -448,12 +469,21 @@ class _BaseConnector:
self.progress = None
self.history_after = None
self.history_skipped = 0
+ #: 首次采集的条数下限。边界之外最多放行这么多条,精确裁剪由 `run_check`
+ #: 按 `history_window` 做:连接器逐条判断时还不知道后面有几条落在边界内。
+ self.history_floor = 0
+ self._history_spares: set[str] = set()
def within_history(self, candidate: FollowCandidate) -> bool:
- accepted = within_history(candidate, self.history_after)
- if not accepted:
- self.history_skipped += 1
- return accepted
+ if within_history(candidate, self.history_after):
+ return True
+ key = str(candidate.external_id)
+ if key in self._history_spares or len(self._history_spares) < self.history_floor:
+ # 同一条可能先在列表阶段、再在补全阶段各问一次,按 id 记住才不重复占名额。
+ self._history_spares.add(key)
+ return True
+ self.history_skipped += 1
+ return False
def _headers(self) -> dict[str, str]:
return {"User-Agent": USER_AGENT}
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 43fd19df6..2e4832b31 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -23,8 +23,8 @@ from .follow import FollowSourceError
from .follow_check import plan_check, run_check
from .web_settings import follow_initial_days
from .follow_discovery import (
- MAX_SUGGESTIONS, archive_suggestions, discover, discovery_plan, no_backoff,
- suggest_term, tag_suggestions,
+ MAX_SUGGESTIONS, PROFILE_ALIAS_SKIP_SERVICES, archive_suggestions, discover,
+ discovery_plan, no_backoff, suggest_term, tag_suggestions,
)
from .follow_image_dims import positive_dims
from .follow_secrets import (
@@ -1005,9 +1005,6 @@ def group_authors(source_rows, aliases: dict[str, str] | None = None,
#: 一次最多提议多少条别名。这是给人一条条看的清单,不是批处理。
MAX_ALIAS_SUGGESTIONS = 12
-#: 名片手柄不值得提议成别名的服务。论坛账号名常常是搬运工自己的账号,
-#: 而 pixiv 的身份是一串数字,当别名只会在列表里多出一个数字「作者」。
-_ALIAS_SKIP_SERVICES = frozenset({"pixiv", "f95zone", "simpcity"})
def _profile_link_suggestions(rows, aliases: dict[str, str]) -> list[dict]:
@@ -1032,7 +1029,7 @@ def _profile_link_suggestions(rows, aliases: dict[str, str]) -> list[dict]:
service = str(link.get("service") or "")
handle = str(link.get("handle") or "").strip()
alias_key = normalized_author_name(handle)
- if service in _ALIAS_SKIP_SERVICES or not alias_key:
+ if service in PROFILE_ALIAS_SKIP_SERVICES or not alias_key:
continue
if aliases.get(alias_key, alias_key) == aliases.get(
canonical_key, canonical_key):
@@ -2117,6 +2114,30 @@ def _profile_links(provider: str, ref: str, credential) -> list[dict] | None:
return None
+def _discovery_aliases(body) -> list[str]:
+ aliases = body.get("aliases") or []
+ if not isinstance(aliases, list) or len(aliases) > MAX_DISCOVERY_ALIASES:
+ raise ValueError(f"aliases must be a list of at most {MAX_DISCOVERY_ALIASES} names")
+ return [str(alias).strip() for alias in aliases]
+
+
+def _save_discovery_aliases(store, author_name: str, aliases: list[str]) -> list[dict]:
+ """查找结果带来的名片手柄,随登记一步记成检索词的别名。
+
+ 人勾选登记这一条就是确认,不再落进「待合并」等人第二次点。自动来源不覆盖
+ 已有映射,人工改过的分组不动。
+ """
+ author_key = normalized_author_name(author_name) if author_name else ""
+ learned = []
+ for alias in aliases:
+ if not author_key or normalized_author_name(alias) in {"", author_key}:
+ continue
+ row = store.upsert_author_alias(author_name, alias, source="profile:f95zone")
+ if row is not None:
+ learned.append(row)
+ return learned
+
+
def w_follow_source(contract, body) -> dict:
"""粘一条来源链接就登记,并立刻检查一次。
@@ -2151,17 +2172,20 @@ def w_follow_source(contract, body) -> dict:
credential = credentials.load(parsed.provider)
label = str(body.get("label") or "").strip() or _resolve_label(
contract, parsed, credential)
- author_hint = str(body.get("author") or "").strip()
- author_hint = normalized_author_name(author_hint) if author_hint else ""
+ author_name = str(body.get("author") or "").strip()
+ author_hint = normalized_author_name(author_name) if author_name else ""
+ aliases = _discovery_aliases(body)
metadata = {"author_key": author_hint} if author_hint else {}
links = _profile_links(parsed.provider, parsed.ref, credential)
if links is not None:
metadata["official_links"] = links
metadata = metadata or None
with contract.database.write_transaction() as connection:
- source_id = _store(contract, connection).register(
+ store = _store(contract, connection)
+ source_id = store.register(
provider=parsed.provider, ref=parsed.ref, label=label, url=parsed.url,
semantics=parsed.semantics, metadata=metadata)
+ learned = _save_discovery_aliases(store, author_name, aliases)
checked = ({"results": []} if body.get("defer_check") else
w_follow_check(contract, {"source": source_id}))
outcome = next((row for row in checked["results"]
@@ -2178,7 +2202,8 @@ def w_follow_source(contract, body) -> dict:
"已登记,另一次检查正在进行,这条稍后再查"),
}
return {"ok": True, "source": source_id, "provider": parsed.provider,
- "ref": parsed.ref, "label": label, "checked": outcome}
+ "ref": parsed.ref, "label": label, "checked": outcome,
+ "author_aliases_learned": learned}
def w_follow_author_alias(contract, body) -> dict:
@@ -2206,6 +2231,8 @@ def w_follow_author_alias(contract, body) -> dict:
#: 一次最多解析多少行。粘一屏链接是正常的,粘一整个书签导出不是。
MAX_RESOLVE_LINES = 40
+#: 登记一条来源时最多随带写下几个名片别名;名片本身最多认八个身份。
+MAX_DISCOVERY_ALIASES = 8
def _candidate_payload(candidate, *, author: str = "") -> dict:
@@ -2213,6 +2240,7 @@ def _candidate_payload(candidate, *, author: str = "") -> dict:
"provider_label": PROVIDER_LABELS.get(candidate.provider, candidate.provider),
"ref": canonical_source_ref(candidate.provider, candidate.ref),
"url": candidate.url, "label": candidate.label, "author": author,
+ "aliases": list(getattr(candidate, "aliases", ())),
"semantics": candidate.semantics, "evidence": candidate.evidence}
diff --git a/tests/test_complexity_ratchet.py b/tests/test_complexity_ratchet.py
index 781ee4b0d..c1e57bc2d 100644
--- a/tests/test_complexity_ratchet.py
+++ b/tests/test_complexity_ratchet.py
@@ -57,7 +57,6 @@ BASELINE: dict[str, int] = {
"scripts/clean_names.py:run": 33,
"scripts/harvest_studio_icons.py:icon_row": 32,
"scripts/smoke_desktop.py:main": 32,
- "src/peach/follow_check.py:run_check": 32,
"src/peach/jav_cover_fetch.py:best_cover": 32,
"scripts/find_ads.py:find_candidates": 31,
"scripts/rehome_unknown_jav.py:build_plan": 31,
diff --git a/tests/test_follow_check.py b/tests/test_follow_check.py
index e807868ac..5ddcff668 100644
--- a/tests/test_follow_check.py
+++ b/tests/test_follow_check.py
@@ -8,7 +8,7 @@ import json
import sqlite3
import tempfile
import unittest
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from peach.follow import FollowHistoryEnd, FollowSourceError
@@ -292,21 +292,51 @@ class RunCheckTests(_CheckCase):
self.assertEqual(self.store.author_aliases(), ({}, []))
+class _PagedConnector(_Connector):
+ """按页码回不同结果的连接器替身;没登记的页就是翻到了尽头。"""
+
+ def __init__(self, pages):
+ super().__init__()
+ self.pages = pages
+
+ def fetch(self, ref, *, etag=None, last_modified=None, page=0):
+ self.calls.append({"ref": ref, "etag": etag,
+ "last_modified": last_modified, "page": page})
+ value = self.pages.get(page, FollowHistoryEnd("没有更多历史内容"))
+ if isinstance(value, Exception):
+ raise value
+ return value
+
+
+def _dated(prefix, count, start, provider="kemono"):
+ """`count` 条从 `start` 起逐日往前的候选,新的在前。"""
+ return tuple(FollowCandidate(provider=provider, external_id=f"{prefix}-{n}", title=f"{prefix}-{n}",
+ published_at=(start - timedelta(days=n)).isoformat())
+ for n in range(count))
+
+
class InitialHistoryTests(_CheckCase):
- def candidates(self):
+ def sample(self):
return tuple(FollowCandidate(provider='fanbox', external_id=key, title=key,
published_at=date) for key, date in (
('old', '2026-01-01T00:00:00Z'),
('boundary', '2026-08-04T00:00:00Z'),
('new', '2026-09-02T00:00:00Z'), ('undated', None)))
+ def candidates(self):
+ """落在 30 天内的已经够下限,边界之外的那条照常跳过。"""
+ return _dated('recent', 30, datetime(2026, 9, 2, tzinfo=timezone.utc),
+ provider='fanbox') + self.sample()
+
def test_first_check_keeps_recent_and_undated_items_and_pins_the_boundary(self):
source = self._register()
connector = _Connector(_fetch(candidates=self.candidates()))
result = self._run(source, connector, initial_days=30)
self.assertEqual(result.history_skipped, 1)
- self.assertEqual({item.external_id for item in self.store.items(source_id=source)},
- {'boundary', 'new', 'undated'})
+ stored = {item.external_id for item in self.store.items(source_id=source)}
+ self.assertTrue({'boundary', 'new', 'undated'} <= stored)
+ self.assertNotIn('old', stored)
+ self.assertEqual([call['page'] for call in connector.calls], [0], "够下限就不往前翻")
boundary = json.loads(self._row(source)['metadata_json'])['initial_history_after']
result = self._run(source, connector, initial_days=0)
self.assertEqual(result.history_skipped, 1)
@@ -339,11 +369,71 @@ class InitialHistoryTests(_CheckCase):
connector.history_after = datetime(2026, 8, 4, tzinfo=timezone.utc)
visited = []
connector._enrich_one = lambda candidate: visited.append(candidate.external_id) or candidate
- candidates, probed = connector.enrich(self.candidates())
+ candidates, probed = connector.enrich(self.sample())
self.assertEqual(visited, ['boundary', 'new', 'undated'])
self.assertEqual(probed, 3)
self.assertEqual(connector.history_skipped, 1)
+ def test_the_connector_lets_through_at_most_the_floor_of_older_entries(self):
+ from peach.follow_sources import _BaseConnector
+ connector = _BaseConnector(enrich_budget=0)
+ connector.history_after = datetime(2026, 8, 4, tzinfo=timezone.utc)
+ connector.history_floor = 1
+ listed = self.sample() + (FollowCandidate(provider='fanbox', external_id='older',
+ title='older', published_at='2025-01-01T00:00:00Z'),)
+ candidates, _probed = connector.enrich(listed)
+ self.assertEqual([c.external_id for c in candidates], ['old', 'boundary', 'new', 'undated'])
+ # 同一条再问一次仍放行,不重复占名额。
+ self.assertTrue(connector.within_history(listed[0]))
+ self.assertEqual(connector.history_skipped, 1)
+
+ def test_a_sparse_author_is_topped_up_with_the_newest_older_entries(self):
+ """30 天里只有一条时补到 30 条,边界挪到收下的最早一条,之后的检查不再报跳过。"""
+ source = self._register(provider='kemono', ref='fanbox/1', url='https://kemono.cr/fanbox/user/1')
+ start = datetime(2026, 7, 1, tzinfo=timezone.utc)
+ page = _fetch(provider='kemono', ref='fanbox/1', candidates=(
+ FollowCandidate(provider='kemono', external_id='new', title='new',
+ published_at='2026-09-02T00:00:00Z'),) + _dated('old', 40, start))
+ connector = _PagedConnector({0: page})
+ result = self._run(source, connector, initial_days=30)
+ self.assertEqual(result.outcome.added, 30)
+ self.assertEqual(result.history_skipped, 11)
+ self.assertEqual([call['page'] for call in connector.calls], [0])
+ metadata = json.loads(self._row(source)['metadata_json'])
+ self.assertEqual(metadata['initial_history_after'], (start - timedelta(days=28)).isoformat())
+ self.assertEqual(metadata['initial_history_floor'], 0)
+ self.assertTrue(metadata['initial_history_first_page_pending'])
+ again = self._run(source, _PagedConnector({0: page}), initial_days=30)
+ self.assertEqual(again.history_skipped, 11)
+ self.assertEqual(len(self.store.items(source_id=source)), 30)
+
+ def test_a_short_first_page_pages_back_until_the_floor_is_met(self):
+ source = self._register(provider='kemono', ref='fanbox/1', url='https://kemono.cr/fanbox/user/1')
+ start = datetime(2026, 6, 1, tzinfo=timezone.utc)
+ pages = {n: _fetch(provider='kemono', ref='fanbox/1',
+ candidates=_dated(f'p{n}', 12, start - timedelta(days=20 * n)))
+ for n in range(4)}
+ connector = _PagedConnector(pages)
+ result = self._run(source, connector, initial_days=30)
+ self.assertEqual([call['page'] for call in connector.calls], [0, 1, 2])
+ self.assertEqual(result.outcome.added, 36, "往前翻的页整页收下")
+ self.assertEqual(len(result.fetch.candidates), 36)
+ row = self._row(source)
+ self.assertEqual(row['backfill_page'], 2)
+ self.assertEqual(json.loads(row['metadata_json'])['initial_history_after'],
+ (start - timedelta(days=40 + 11)).isoformat())
+
+ def test_the_top_up_stops_quietly_at_the_end_of_history(self):
+ source = self._register(provider='kemono', ref='fanbox/1', url='https://kemono.cr/fanbox/user/1')
+ page = _fetch(provider='kemono', ref='fanbox/1',
+ candidates=_dated('old', 5, datetime(2026, 6, 1, tzinfo=timezone.utc)))
+ connector = _PagedConnector({0: page})
+ result = self._run(source, connector, initial_days=30)
+ self.assertTrue(result.ok)
+ self.assertEqual([call['page'] for call in connector.calls], [0, 1])
+ self.assertEqual(result.outcome.added, 5)
+ self.assertEqual(json.loads(self._row(source)['metadata_json'])['initial_history_floor'], 0)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_follow_discovery.py b/tests/test_follow_discovery.py
index 9bf7d999d..116a8fc17 100644
--- a/tests/test_follow_discovery.py
+++ b/tests/test_follow_discovery.py
@@ -46,6 +46,11 @@ SIMPCITY_SEARCH_RESULTS = b"""<html><body>
R34_AUTOCOMPLETE_HIT = json.dumps(
[{"label": "ria-neearts (248)", "value": "ria-neearts"},
{"label": "riahri (156)", "value": "riahri"}]).encode()
+R34_CEEEEEKC = json.dumps([{"label": "ceeeeekc (40)", "value": "ceeeeekc"}]).encode()
+# 首楼名片:一个与检索词不同的手柄、一个同名手柄、一个 pixiv 数字 id。
+F95_PROFILE_PAGE = b"""<html><body><article class="message"><div class="message-userContent">
+<a href="https://twitter.com/Ceeeeekc">X</a><a href="https://www.patreon.com/cekc">Patreon</a>
+<a href="https://www.pixiv.net/users/123456">pixiv</a></div></article></body></html>"""
FANBOX_PROFILE = ("<html><meta name='metadata' content='"
+ json.dumps({"urlContext": {"host": {"creatorId": "lazyprocrast"}}})
.replace("'", "&#39;")
@@ -121,6 +126,11 @@ class DiscoveryPlanTests(unittest.TestCase):
tasks = discovery_plan("suzutaro3d")
self.assertEqual(tasks, DEFAULT_PROVIDERS)
+ def test_f95zone_is_asked_first_so_its_profile_handles_reach_the_rest(self):
+ self.assertEqual(discovery_plan("cekc")[0], "f95zone")
+ self.assertEqual(discovery_plan("Lazy", providers=("kemono", "f95zone")),
+ ("f95zone", "kemono"))
+
def test_a_numeric_word_skips_the_name_searching_sources(self):
tasks = discovery_plan("30917150")
for skipped in ("rule34video", "rule34xxx", "simpcity"):
@@ -433,6 +443,23 @@ class DiscoverTests(_DiscoveryCase):
transport=call, providers=("f95zone",))
self.assertEqual(queries, ["strauzek"])
+ def test_f95_profile_handles_are_searched_on_the_other_sources(self):
+ """搜 `cekc` 在 rule34.xxx 上碰不到 `Ceeeeekc`;F95 首楼名片上写着这个手柄。"""
+ self._write_credential("f95zone", {"cookie": "xf_user=1"})
+ routes = {"latest_data.php": HttpResponse(200, {}, F95_MISS),
+ "/search/search": HttpResponse(200, {}, F95_SEARCH_RESULTS),
+ "f95zone.to/search/": HttpResponse(200, {}, F95_SEARCH_FORM),
+ "f95zone.to/threads/146348/": HttpResponse(200, {}, F95_PROFILE_PAGE),
+ "autocomplete.php?q=cekc": HttpResponse(200, {}, b"[]"),
+ "autocomplete.php?q=Ceeeeekc": HttpResponse(200, {}, R34_CEEEEEKC)}
+ found = self._discover("cekc", routes, providers=("rule34xxx", "f95zone"))
+ self.assertEqual([(c.provider, c.ref) for c in found.candidates],
+ [("f95zone", "146348"), ("rule34xxx", "ceeeeekc")])
+ f95, tag = found.candidates
+ self.assertEqual(f95.aliases, ("Ceeeeekc",), "与检索词同名的 patreon 手柄和 pixiv 数字 id 不算别名")
+ self.assertEqual(tag.aliases, ("Ceeeeekc",))
+ self.assertTrue(tag.evidence.startswith("F95 首楼名片上的手柄 Ceeeeekc:"))
+
def test_without_a_cookie_the_forum_search_is_skipped_not_guessed(self):
calls = []
found = self._discover("Ria_neearts", {"latest_data.php": HttpResponse(200, {}, F95_MISS)},
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index d40aa42bb..e310b9907 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -2173,6 +2173,29 @@ class FollowSourceAddTests(FollowContractTests):
source = self._get()["sources"][0]
self.assertEqual(source["author_key"], "name:lazyprocrastinator")
+ def test_discovery_profile_aliases_are_saved_with_the_source_in_one_step(self):
+ """勾选登记名片手柄查到的来源就是确认;别名不再落进待合并等第二次点。"""
+ with mock.patch.object(web_follow, "build_connector") as factory:
+ factory.return_value.fetch.return_value = SourceFetch(
+ provider="rule34xxx", ref="ceeeeekc",
+ request_url="https://rule34.xxx/x", semantics="work",
+ not_modified=True)
+ added = self._post("/api/follow/source", {
+ "action": "add",
+ "url": "https://rule34.xxx/index.php?page=post&s=list&tags=ceeeeekc",
+ "author": "cekc", "aliases": ["Ceeeeekc", "cekc"],
+ })
+ self.assertEqual(added["author_aliases_learned"], [
+ {"canonical": "cekc", "alias": "Ceeeeekc", "source": "profile:f95zone"}])
+ payload = self._get()
+ self.assertEqual(payload["sources"][0]["author_key"], "name:cekc")
+ self.assertEqual([alias["name"] for alias in payload["author_aliases"][0]["aliases"]],
+ ["Ceeeeekc"])
+ self.assertEqual(payload["alias_suggestions"], [])
+ with self.assertRaises(ValueError):
+ self._post("/api/follow/source", {"action": "add", "aliases": "Ceeeeekc",
+ "url": "https://rule34video.com/models/x/"})
+
def test_a_name_miss_exposes_the_google_f95_fallback_without_adding_it(self):
fallback = ExternalSearch(
provider="f95zone", label="用 Google 继续查找 F95zone",
@@ -2203,7 +2226,7 @@ class FollowSourceAddTests(FollowContractTests):
self.assertEqual(row["candidates"], [{
"provider": "fanbox", "provider_label": "FANBOX",
"ref": "lazyprocrast", "url": "https://lazyprocrast.fanbox.cc/",
- "label": "lazyprocrast", "author": "", "semantics": "work",
+ "label": "lazyprocrast", "author": "", "aliases": [], "semantics": "work",
"evidence": "链接直接指明", "known": False,
}])
diff --git a/web/app.js b/web/app.js
index 49cf44dea..9e23f1d25 100644
--- a/web/app.js
+++ b/web/app.js
@@ -7604,7 +7604,7 @@ function renderFollowPicks(results){
const failures=Object.entries(row.failures||{});
const items=(row.candidates||[]).map((c,ci)=>`<label class="fpickitem${c.known?' known':''}" data-provider="${esc(c.provider_label||'')}">
${checkboxHtml(`data-pick="${index}-${ci}" value="${esc(c.url)}"`
- +` data-author="${esc(c.author||'')}"`
+ +` data-author="${esc(c.author||'')}" data-aliases="${esc(JSON.stringify(c.aliases||[]))}"`
+` data-label="${esc(c.label)}"${c.known?' disabled':' checked'}`)}
<span><b>${esc(c.provider_label)}</b> ${esc(c.label)}
<i>${esc(c.known?'已经关注':c.evidence)}</i></span></label>`).join('');
@@ -7644,7 +7644,7 @@ function renderFollowPicks(results){
try{
const registered=await api('/api/follow/source',{method:'POST',body:JSON.stringify(
{action:'add',url:input.value,label:input.dataset.label,
- author:input.dataset.author,defer_check:true})});
+ author:input.dataset.author,aliases:JSON.parse(input.dataset.aliases||'[]'),defer_check:true})});
sources.push(registered.source);
}catch(error){
// 一条失败不该把其余的一起丢掉,逐条报。
diff --git a/web/index.html b/web/index.html
index fac530b8d..4840adc4f 100644
--- a/web/index.html
+++ b/web/index.html
@@ -306,7 +306,7 @@
<div class="settingrow"><span><b>搜索记录</b><small>保存在 Peach 账本,所有访问端同步。</small></span><div id="searchHistoryLimitSetting"></div></div>
</section>
<section class="settinggroup"><h3>关注</h3>
- <div class="settingrow"><span><b>首次采集历史范围</b><small>按发布时间限制新来源首次导入的内容,默认最近 30 天。没有日期的条目仍会导入;已有内容不受影响,支持历史分页的来源可手动加载更早。</small><small id="followInitialDaysState" aria-live="polite"></small></span><div id="followInitialDaysSetting"></div></div>
+ <div class="settingrow"><span><b>首次采集历史范围</b><small>按发布时间限制新来源首次导入的内容,默认最近 30 天;范围内不足 30 条时补到 30 条。没有日期的条目仍会导入;已有内容不受影响,支持历史分页的来源可手动加载更早。</small><small id="followInitialDaysState" aria-live="polite"></small></span><div id="followInitialDaysSetting"></div></div>
<div class="settingrow"><span><b>关注自动更新</b><small id="followScheduleState" aria-live="polite">读取运行状态…</small></span><div id="followScheduleSetting"></div></div>
<div class="settingrow"><span><b>头像与站点图标刷新</b><small>创作者头像、来源图标和外链圆标保存在本机,到期后下次显示时重新取一次;视频与图片不保存。</small></span><div id="metadataRefreshSetting"></div></div>
</section>