Peach: Local-first video metadata scraper and media manager.
refactor(follow): 检查更新只有一份流程,身份与播放写入回到数据层
longmeidao3848f6fd089b
diff --git a/src/peach/follow_check.py b/src/peach/follow_check.pynew file mode 100644index 000000000..df4389a98--- /dev/null+++ b/src/peach/follow_check.py@@ -0,0 +1,125 @@+"""一次「检查更新」的完整流程:取回 → 落库 → 顺带学一条作者别名。++Web 与命令行原本各写一遍,而两份并不等价:命令行那份没有往回翻页、没有凭据到位+之后的强制重取、也不学官方渠道的作者别名。同一句「检查更新」在网页上做的事比在+终端里多,而没有任何地方说明这一点——两处各自演化的结果,不是有意的取舍。++网络与落库都在这里,事务边界由调用方传进来的 `writer` 决定:Web 每条来源一个写+事务,命令行是一条连接加显式 commit。展示不在这里,`CheckResult` 交回给调用方。+"""+from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime, timezone+from typing import Mapping++from .follow import FollowHistoryEnd, FollowSourceError+from .follow_secrets import CredentialError+from .follow_sources import SourceFetch+from .follow_store import RecordOutcome+++@dataclass(frozen=True)+class CheckResult:+ """一条来源检查完之后发生了什么。++ 失败也是返回值而不是异常:逐条独立成败,一个来源缺凭据或被机器人验证挡住,+ 不该让其余来源的更新一起消失。+ """++ source_id: int+ provider: str+ ref: str+ label: str+ page: int = 0+ older: bool = False+ ok: bool = True+ status: str = "ok"+ error: str = ""+ message: str = ""+ exhausted: bool = False+ fetch: SourceFetch | None = None+ outcome: RecordOutcome | None = None+ author_alias_learned: dict | None = None+++def plan_check(store, credentials, *, source_id: int | None = None,+ older: bool = False, force: bool = False,+ backfill_providers: frozenset[str] = frozenset()) -> list[dict]:+ """要检查哪些来源,以及每条要不要绕过条件请求游标。只读,不联网。++ `force_media_reparse` 单独在这里算好:凭据已经存在、但旧候选还标着+ `media_needs_credential` 时,条件请求的 304 会让旧解析结果永久不变——显式检查+ 得无条件重取一次,凭据才真正生效。往回翻页时不算这个,那一页本来就没游标。++ `force=True` 是命令行 `--force` 那种无条件重取,对每条来源都成立。+ """+ rows = [dict(row) for row in store.sources(enabled_only=True)+ if (source_id is None or row["id"] == source_id)+ and (not older or row["provider"] in backfill_providers)]+ for row in rows:+ row["force_media_reparse"] = force or (+ not older and credentials.load(row["provider"]) is not None+ and store.source_needs_media_reparse(row["id"])+ )+ return rows+++def build_connector_for(provider: str, credentials, connector_factory):+ """按凭据仓库里现有的凭据造一个连接器。++ `connector_factory` 由调用方传进来(各自模块里的 `build_connector`),不在这里+ 直接引用:那样调用方替换它才有效,测试也才能只替自己那一处。+ """+ kwargs = {"credential": credentials.load(provider)}+ gofile_credential = credentials.load("gofile")+ if gofile_credential is not None:+ kwargs["gofile_credential"] = gofile_credential+ return connector_factory(provider, **kwargs)+++def run_check(row: Mapping, *, credentials, writer, connector_factory,+ older: bool = False, moment: datetime | None = None) -> CheckResult:+ """检查一条来源。++ `row` 是 `plan_check` 给出的那种字典。`writer` 是零参可调用对象,返回一个产出+ `FollowStore` 的上下文管理器;每次写都单独取一次,好让调用方决定提交粒度。+ """+ moment = moment or datetime.now(timezone.utc)+ source_id = int(row["id"])+ provider, ref = str(row["provider"]), str(row["ref"])+ page = (int(row["backfill_page"] or 0) + 1) if older else 0+ 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"))+ try:+ connector = build_connector_for(provider, credentials, connector_factory)+ fetch = connector.fetch(+ ref,+ etag=None if force else row["etag"],+ last_modified=None if force else row["last_modified"],+ page=page,+ )+ except FollowHistoryEnd:+ with writer() as store:+ store.record_history_end(source_id, moment)+ return CheckResult(**base, exhausted=True, message="没有更多历史内容")+ except CredentialError as error:+ return _record_failure(writer, base, error, moment, "unauthorized")+ except FollowSourceError as error:+ return _record_failure(writer, base, error, moment, "error")+ with writer() as store:+ outcome = store.record(+ source_id, fetch,+ creator_aliases=store.creator_aliases(row["entity_id"]),+ moment=moment, page=page)+ learned = store.learn_official_author_alias(provider, ref, fetch.candidates)+ return CheckResult(**base, fetch=fetch, outcome=outcome,+ author_alias_learned=learned)+++def _record_failure(writer, base: dict, error: Exception, moment: datetime,+ status: str) -> CheckResult:+ with writer() as store:+ store.record_error(base["source_id"], str(error), moment, status=status)+ return CheckResult(**base, ok=False, status=status, error=str(error))diff --git a/src/peach/follow_cli.py b/src/peach/follow_cli.pyindex ebbc1ed58..3265ab7cf 100644--- a/src/peach/follow_cli.py+++ b/src/peach/follow_cli.py@@ -6,16 +6,14 @@from __future__ import annotationsimport argparse+import contextlibimport sqlite3-from datetime import datetime, timezonefrom pathlib import Pathfrom .config import DATABASE_PATH, SECRETS_DIR, SHARED_DATA_ROOT, SOURCES_DIRfrom . import follow_providers-from .follow import FollowSourceError-from .follow_secrets import (- CREDENTIAL_GUIDE, CredentialError, credential_store_for,-)+from .follow_check import plan_check, run_check+from .follow_secrets import CREDENTIAL_GUIDE, credential_store_forfrom .follow_sources import CONNECTORS, build_connectorfrom .follow_store import FollowStore@@ -26,6 +24,9 @@ _SOURCE_URL = follow_providers.source_urls()#: 这些来源的每个条目是同一作品的一次发布,不是独立作品。_RELEASE_PROVIDERS = follow_providers.release_providers()+#: 支持往回翻页的来源,和 Web 那边同一份声明。+_BACKFILL_PROVIDERS = follow_providers.backfill_providers()+def _connect(db_path: Path) -> sqlite3.Connection:connection = sqlite3.connect(db_path, timeout=30)@@ -79,50 +80,52 @@ def _list(args) -> int:def _check(args) -> int:+ """检查更新。流程与 Web 的 `/api/follow/check` 共用 `follow_check.run_check`。++ 共用之前这两处并不等价:命令行没有 `--older` 往回翻页、凭据到位后的强制重取,+ 也不学官方渠道的作者别名。同一句「检查更新」在网页上做的事比在终端里多,+ 而没有任何地方说明这一点。+ """store, connection = _store(args)credentials = credential_store_for(args.secrets_root, shared_root=args.shared_root)+ older = bool(getattr(args, "older", False))failures = 0++ @contextlib.contextmanager+ def writer():+ # 命令行是一条连接,写完就地提交:一条来源失败不该回滚前面成功的那些。+ yield store+ connection.commit()+try:- rows = [row for row in store.sources(enabled_only=True)- if args.source is None or row["id"] == args.source]+ rows = plan_check(store, credentials, source_id=args.source, older=older,+ force=args.force, backfill_providers=_BACKFILL_PROVIDERS)if not rows:print("没有需要检查的来源。")return 0for row in rows:- moment = datetime.now(timezone.utc)- provider, ref = row["provider"], row["ref"]- try:- credential = credentials.load(provider)- connector = build_connector(- provider, credential=credential,- gofile_credential=credentials.load("gofile"))- fetch = connector.fetch(- ref,- etag=None if args.force else row["etag"],- last_modified=None if args.force else row["last_modified"])- except CredentialError as error:- store.record_error(row["id"], str(error), moment, status="unauthorized")- connection.commit()- print(f"! {provider}/{ref}:{error}")+ result = run_check(row, credentials=credentials, writer=writer,+ connector_factory=build_connector, older=older)+ tag = f"{result.provider}/{result.ref}"+ if not result.ok:+ print(f"! {tag}:{result.error}")failures += 1continue- except FollowSourceError as error:- store.record_error(row["id"], str(error), moment)- connection.commit()- print(f"! {provider}/{ref}:{error}")- failures += 1+ if result.exhausted:+ print(f"= {tag}:{result.message}")continue- outcome = store.record(- row["id"], fetch,- creator_aliases=store.creator_aliases(row["entity_id"]), moment=moment)- connection.commit()+ outcome = result.outcomeif outcome.not_modified:- print(f"= {provider}/{ref}:无变化")- else:- print(f"+ {provider}/{ref}:发现 {outcome.discovered},"- f"新增 {outcome.added},更新 {outcome.updated}")- if outcome.evidence_error:- print(f" ⚠ {outcome.evidence_error}")+ print(f"= {tag}:无变化")+ continue+ page = f"第 {result.page} 页:" if result.older else ""+ print(f"+ {tag}:{page}发现 {outcome.discovered},"+ f"新增 {outcome.added},更新 {outcome.updated}")+ if outcome.evidence_error:+ print(f" ⚠ {outcome.evidence_error}")+ if result.author_alias_learned:+ learned = result.author_alias_learned+ print(f" · 记下别名 {learned['alias']} → {learned['canonical']}")finally:connection.close()return 1 if failures else 0@@ -254,6 +257,8 @@ def register(commands) -> None:check = actions.add_parser("check", help="显式检查更新(唯一会联网的动作)")check.add_argument("--source", type=int, help="只检查这一个来源 id")check.add_argument("--force", action="store_true", help="忽略条件请求游标")+ check.add_argument("--older", action="store_true",+ help="往回抓一页历史(只对支持翻页的来源有效)")check.set_defaults(handler=_check)feed = actions.add_parser("feed", help="按作品分组显示追更结果(不联网)")diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 792f98369..ea0cbd7d7 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -469,6 +469,16 @@ class _BaseConnector:"""return str(item.thumb_url or "") or None+ @classmethod+ def profile_handle(cls, ref: str) -> str:+ """这条 ref 里可以当作者别名用的平台手柄,没有就返回空串。++ 只有官方渠道才有这种手柄:`fanbox/ffxivinitiala` 里的 `ffxivinitiala`+ 就是作者本人在那个平台的名字。归档站与标签站的 ref 是数字 id 或标签,+ 它们不是名字,学成别名只会造出一个假作者。+ """+ return ""+@classmethoddef is_history_end_error(cls, message: str) -> bool:"""一句已经落盘的错误文本,其实是「历史到底」吗?@@ -1602,6 +1612,11 @@ class FanboxConnector(_BaseConnector):provider = "fanbox"semantics = "work"_CREATOR_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")++ @classmethod+ def profile_handle(cls, ref: str) -> str:+ return str(ref or "").strip()+_IMPERSONATION = "firefox147"def __init__(self, *, detail_transport: HttpTransport | None = None, **kwargs):@@ -1751,6 +1766,11 @@ class SubscribeStarConnector(_BaseConnector):HOSTS = frozenset({"subscribestar.adult", "subscribestar.com"})_SLUG_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")+ @classmethod+ def profile_handle(cls, ref: str) -> str:+ # ref 带着站点主机名(`subscribestar.adult/initiala`),手柄只是最后那截。+ return str(ref or "").strip().rsplit("/", 1)[-1]+@classmethoddef _split_ref(cls, ref: str) -> tuple[str, str]:host, _, slug = str(ref or "").strip().partition("/")@@ -1820,6 +1840,14 @@ class PatreonConnector(_BaseConnector):_VANITY_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")_POST_RE = re.compile(r"/posts/(?:[^/?#]*-)?(\d{4,})(?:[/?#]|$)")+ @classmethod+ def profile_handle(cls, ref: str) -> str:+ value = str(ref or "").strip().strip("/")+ if value.startswith("user/") or value.isdigit():+ # 数字用户 id 页没有短名,`user/12345` 不是作者的名字。+ return ""+ return value.rsplit("/", 1)[-1]+def _url(self, ref: str) -> str:value = str(ref or "").strip()if value.startswith("user/") and value[5:].isdigit():@@ -2118,6 +2146,15 @@ def is_history_end_error(provider: str, message: str) -> bool:return factory is not None and factory.is_history_end_error(message)+def official_profile_handle(provider: str, ref: str) -> str:+ """这条来源的 ref 里那个可信的作者手柄,没有就返回空串。++ 分派到该站自己的连接器:ref 的形状是站点知识。+ """+ factory = CONNECTORS.get(str(provider or ""))+ return factory.profile_handle(ref) if factory is not None else ""++def build_connector(provider: str, **kwargs) -> FollowConnector:factory = CONNECTORS.get(provider)if factory is None:diff --git a/src/peach/follow_store.py b/src/peach/follow_store.pyindex c93db1f13..f756cb852 100644--- a/src/peach/follow_store.py+++ b/src/peach/follow_store.py@@ -11,13 +11,17 @@ from __future__ import annotationsimport hashlibimport json+import reimport sqlite3from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Path+from . import follow_providersfrom .follow import FollowSourceError, write_immutable-from .follow_sources import FollowCandidate, SourceFetch, canonical_source_ref+from .follow_sources import (+ FollowCandidate, SourceFetch, canonical_source_ref, official_profile_handle,+)from .follow_variants import classify, group_duplicates@@ -28,6 +32,40 @@ def _now_text(moment: datetime | None = None) -> str:return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")+#: 标签里跟在中点后面的服务名。`LazyProcrastinator · fanbox` 和 rule34video 上的+#: `lazyprocrastinator` 是同一个人,中点后面那截只说明他在哪个平台连载。+_LABEL_SERVICE_RE = re.compile(r"\s*[·|]\s*[A-Za-z0-9_\-]+\s*$")+_AUTHOR_NOISE_RE = re.compile(r"[^0-9a-z一-鿿]+")+_F95_TITLE_SUFFIX_RE = re.compile(r"\s+collections?\s*$", re.IGNORECASE)++#: 作者显示名与头像可信的官方渠道;归档站只作回退。+_OFFICIAL_IDENTITY_PROVIDERS = follow_providers.official_identity_providers()+++def normalized_author_name(value: str, *, provider: str = "") -> str:+ """作者别名表的身份键。++ 去掉「· 服务名」后缀,再去掉大小写、空格、连字符这些不影响身份的噪声。+ 归一化只做到这一步,不做模糊匹配:把两个碰巧相似的名字并成一个人,比让用户+ 自己看到两行严重得多。++ 这是**别名表的主键定义**,不是展示逻辑,所以它和别名读写放在同一层。+ """+ stripped = _LABEL_SERVICE_RE.sub("", str(value or "").strip())+ if provider == "f95zone":+ # F95 的线程标题说的是一个容器而不是另一个作者:真实数据是+ # `Lazy Procrastinator Collection`,而每一条作者来源都是+ # `LazyProcrastinator`,留着这个通用后缀会凭空多出一个分组。+ stripped = _F95_TITLE_SUFFIX_RE.sub("", stripped)+ return _AUTHOR_NOISE_RE.sub("", stripped.casefold())+++def author_display_text(value: str) -> str:+ """去掉不属于作者名的容器与服务名措辞,保留原始拼写。"""+ stripped = _LABEL_SERVICE_RE.sub("", str(value or "").strip())+ return _F95_TITLE_SUFFIX_RE.sub("", stripped).strip()++@dataclass(frozen=True)class FollowItemRow:id: int@@ -278,6 +316,14 @@ class FollowStore:return RecordOutcome(source_id, len(fetch.candidates), added, updated,evidence_path=evidence, evidence_error=evidence_error)+ def remove_source(self, source_id: int) -> None:+ """删掉一条来源登记。++ 原来是 Web 处理函数里一句裸 DELETE。哪张表、要不要连带清理,属于这一层的+ 知识;把它留在 Web 层意味着换存储结构时得去处理函数里找 SQL。+ """+ self._connect().execute("DELETE FROM follow_source WHERE id=?", (source_id,))+def record_error(self, source_id: int, message: str,moment: datetime | None = None, *, status: str = "error") -> None:stamp = _now_text(moment)@@ -449,6 +495,194 @@ class FollowStore:self._connect().execute("UPDATE follow_item SET status=? WHERE id=?", (status, item_id))+ # ---- 作者别名 -------------------------------------------------------++ def author_aliases(self) -> tuple[dict[str, str], list[dict]]:+ """全部跨站作者别名:`别名键 → 规范键` 的映射,以及按规范名分好的组。"""+ rows = self._connect().execute(+ "SELECT alias_key,alias_name,canonical_key,canonical_name,source "+ "FROM follow_author_alias ORDER BY canonical_name,alias_name"+ ).fetchall()+ mapping = {str(row["alias_key"]): str(row["canonical_key"]) for row in rows}+ groups: dict[str, dict] = {}+ for row in rows:+ canonical_key = str(row["canonical_key"])+ group = groups.setdefault(canonical_key, {+ "canonical_key": canonical_key,+ # 旧别名记录可能把 F95 的容器标题存成了规范显示名;只修正读投影,+ # 不在一次读取里偷偷改真实表。+ "canonical_name": author_display_text(row["canonical_name"]),+ "aliases": [],+ })+ if str(row["alias_key"]) != canonical_key:+ group["aliases"].append({+ "key": str(row["alias_key"]),+ "name": str(row["alias_name"]),+ "source": str(row["source"]),+ })+ return mapping, [group for group in groups.values() if group["aliases"]]++ def upsert_author_alias(self, canonical_name: str, alias_name: str, *,+ source: str, moment: datetime | None = None) -> dict | None:+ """写一条别名,且不让自动证据盖掉人的决定。++ 人工确认可以有意重新分组。自动学习窄得多:它只填一个此前未知的平台手柄,+ 任何已有映射(尤其是人工的)都不动。+ """+ canonical_key = normalized_author_name(canonical_name)+ alias_key = normalized_author_name(alias_name)+ if not canonical_key or not alias_key:+ raise ValueError("规范作者名和平台别名都不能为空")+ if canonical_key == alias_key:+ raise ValueError("这两个名字归一化后相同,不需要维护别名")++ connection = self._connect()+ stamp = _now_text(moment)+ mapping, _ = self.author_aliases()+ canonical_root = mapping.get(canonical_key, canonical_key)+ alias_root = mapping.get(alias_key, alias_key)+ if source != "manual":+ existing = connection.execute(+ "SELECT 1 FROM follow_author_alias WHERE alias_key=?", (alias_key,)+ ).fetchone()+ if existing is not None or alias_root != alias_key:+ return None+ canonical_row = connection.execute(+ "SELECT canonical_name FROM follow_author_alias WHERE canonical_key=? "+ "ORDER BY CASE WHEN alias_key=canonical_key THEN 0 ELSE 1 END LIMIT 1",+ (canonical_root,),+ ).fetchone()+ if canonical_row is not None:+ canonical_name = str(canonical_row["canonical_name"])+ elif canonical_root != alias_root:+ connection.execute(+ "UPDATE follow_author_alias SET canonical_key=?,canonical_name=?,"+ "updated_at=? WHERE canonical_key=?",+ (canonical_root, canonical_name, stamp, alias_root),+ )++ conflict = (+ "DO UPDATE SET canonical_key=excluded.canonical_key,"+ "canonical_name=excluded.canonical_name,alias_name=excluded.alias_name,"+ "source=excluded.source,updated_at=excluded.updated_at"+ if source == "manual" else "DO NOTHING"+ )+ sql = (+ "INSERT INTO follow_author_alias(alias_key,alias_name,canonical_key,"+ "canonical_name,source,created_at,updated_at) VALUES(?,?,?,?,?,?,?) "+ f"ON CONFLICT(alias_key) {conflict}"+ )+ connection.execute(+ sql, (canonical_root, canonical_name, canonical_root, canonical_name,+ source, stamp, stamp),+ )+ inserted = connection.execute(+ sql, (alias_key, alias_name, canonical_root, canonical_name,+ source, stamp, stamp),+ ).rowcount+ if source != "manual" and not inserted:+ return None+ return {"canonical": canonical_name, "alias": alias_name, "source": source}++ def remove_author_alias(self, alias_name: str) -> None:+ """删掉一条别名。规范名本身不能当别名删掉,那会拆散整个组。"""+ alias_key = normalized_author_name(alias_name)+ if not alias_key:+ raise ValueError("别名不能为空")+ connection = self._connect()+ row = connection.execute(+ "SELECT canonical_key FROM follow_author_alias WHERE alias_key=?",+ (alias_key,),+ ).fetchone()+ if row is None:+ raise ValueError("这个作者别名不存在")+ if str(row["canonical_key"]) == alias_key:+ raise ValueError("规范名不能作为别名移除")+ connection.execute(+ "DELETE FROM follow_author_alias WHERE alias_key=?", (alias_key,))++ def learn_official_author_alias(self, provider: str, ref: str,+ candidates) -> dict | None:+ """只从一个毫无歧义的官方资料页名字学一个平台手柄。++ 判据故意窄:这一次抓取里所有候选的署名归一化后必须只有一个,否则宁可不学。+ 自动证据永远不覆盖已有映射,见 `upsert_author_alias`。+ """+ if provider not in _OFFICIAL_IDENTITY_PROVIDERS:+ return None+ authors: dict[str, str] = {}+ for candidate in candidates:+ name = str(candidate.author or "").strip()+ key = normalized_author_name(name)+ if key:+ authors.setdefault(key, name)+ if len(authors) != 1:+ return None+ canonical_key, canonical_name = next(iter(authors.items()))+ handle = official_profile_handle(provider, ref)+ if not handle or normalized_author_name(handle) == canonical_key:+ return None+ return self.upsert_author_alias(canonical_name, handle,+ source=f"official:{provider}")++ # ---- 播放记录 -------------------------------------------------------++ def _item_status(self, item_id: int) -> str:+ row = self._connect().execute(+ "SELECT status FROM follow_item WHERE id=?", (item_id,)).fetchone()+ if row is None:+ # 「你给的 id 不存在」是请求错误,不是存储故障;调用方映射成 400。+ raise ValueError("follow item not found")+ return str(row["status"])++ def record_playback(self, item_id: int, moment: datetime | None = None) -> str:+ """记一次关注页直接播放,返回这条条目之后的状态。++ 候选无需先保存成 asset:关注页可以直接播,播过就不再是 `new`。+ """+ status = self._item_status(item_id)+ connection = self._connect()+ stamp = (moment or datetime.now(timezone.utc)).timestamp()+ connection.execute(+ "INSERT INTO follow_playback"+ "(follow_item_id,profile_id,play_count,last_played) "+ "VALUES(?,'local-default',1,?) ON CONFLICT(follow_item_id,profile_id) "+ "DO UPDATE SET play_count=follow_playback.play_count+1,"+ "last_played=excluded.last_played",+ (item_id, stamp),+ )+ if status != "new":+ return status+ connection.execute(+ "UPDATE follow_item SET status='seen' WHERE id=?", (item_id,))+ return "seen"++ def record_playback_activity(self, item_id: int, *, position: float = 0.0,+ duration: float = 0.0, delta: float = 0.0,+ ended: bool = False,+ moment: datetime | None = None) -> dict:+ """累计在线播放的真实时长与最远到达位置。"""+ self._item_status(item_id)+ position, duration, delta = (max(float(position), 0), max(float(duration), 0),+ max(float(delta), 0))+ ratio = 1.0 if ended else (min(position / duration, 1.0) if duration > 0 else 0.0)+ connection = self._connect()+ stamp = (moment or datetime.now(timezone.utc)).timestamp()+ connection.execute(+ "INSERT INTO follow_playback(follow_item_id,profile_id,play_count,"+ "play_seconds,max_reached,last_played) "+ "VALUES(?,'local-default',1,?,?,?) "+ "ON CONFLICT(follow_item_id,profile_id) DO UPDATE SET "+ "play_seconds=follow_playback.play_seconds+excluded.play_seconds,"+ "max_reached=max(follow_playback.max_reached,excluded.max_reached),"+ "last_played=excluded.last_played",+ (item_id, delta, ratio, stamp),+ )+ return dict(connection.execute(+ "SELECT play_seconds,max_reached FROM follow_playback "+ "WHERE follow_item_id=? AND profile_id='local-default'", (item_id,),+ ).fetchone())+def save_asset(self, item_id: int, *, confirm: bool = False,moment: datetime | None = None) -> int:"""把一个候选保存成 `location='online'` 的 asset。diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 660e86e2c..ad49cd848 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -6,15 +6,16 @@ APScheduler 任务触发。"""from __future__ import annotations+import contextlibimport htmlimport jsonimport osimport reimport urllib.parse-from datetime import datetime, timezonefrom . import follow_providers-from .follow import FollowHistoryEnd, FollowSourceError+from .follow import FollowSourceError+from .follow_check import plan_check, run_checkfrom .follow_discovery import discoverfrom .follow_secrets import (CREDENTIAL_GUIDE, CredentialError, CredentialStore, credential_store_for,@@ -24,7 +25,9 @@ from .follow_sources import (display_thumb_url, f95_attachment_media_items, is_history_end_error,parse_source_url, resource_links,)-from .follow_store import FollowStore, ReleaseGroup+from .follow_store import (+ FollowStore, ReleaseGroup, author_display_text, normalized_author_name,+)from .taste_history import read_creator_candidates@@ -37,7 +40,6 @@ _STATUSES = ("new", "seen", "saved", "ignored")#: 所以这里不是分页,只是别让一个失控的库把内存吃干的护栏。_ALL_ITEMS = 100_000_BACKFILL_PROVIDERS = follow_providers.backfill_providers()-_OFFICIAL_IDENTITY_PROVIDERS = follow_providers.official_identity_providers()def _store(contract, connection) -> FollowStore:@@ -319,34 +321,15 @@ def _group_payload(group: ReleaseGroup,}-#: 标签里跟在中点后面的服务名。`LazyProcrastinator · fanbox` 和 rule34video 上的-#: `lazyprocrastinator` 是同一个人,中点后面那截只说明他在哪个平台连载。-_LABEL_SERVICE_RE = re.compile(r"\s*[·|]\s*[A-Za-z0-9_\-]+\s*$")-_AUTHOR_NOISE_RE = re.compile(r"[^0-9a-z一-鿿]+")-_F95_TITLE_SUFFIX_RE = re.compile(r"\s+collections?\s*$", re.IGNORECASE)---def _normalized_author_name(value: str, *, provider: str = "") -> str:- stripped = _LABEL_SERVICE_RE.sub("", str(value or "").strip())- if provider == "f95zone":- # F95 thread titles describe a container, not a different author. The real- # data is ``Lazy Procrastinator Collection`` while every author source is- # ``LazyProcrastinator``; retaining the generic suffix creates a false group.- stripped = _F95_TITLE_SUFFIX_RE.sub("", stripped)- return _AUTHOR_NOISE_RE.sub("", stripped.casefold())---def _author_display_text(value: str) -> str:- """Remove container/service wording that is not part of an author name."""- stripped = _LABEL_SERVICE_RE.sub("", str(value or "").strip())- return _F95_TITLE_SUFFIX_RE.sub("", stripped).strip()--def _author_display_name(row) -> str:- """Return the readable author spelling carried by one follow source."""+ """一条追更来源上那个可读的作者拼写。++ 名字怎么算「同一个人」由 `follow_store` 定义(那是别名表的主键口径);+ 这里只决定「这一行显示哪个字段」。+ """if row["entity_id"] and row["entity_name"]:return str(row["entity_name"])- return _author_display_text(row["label"] or row["ref"] or "")+ return author_display_text(row["label"] or row["ref"] or "")def _source_metadata(row) -> dict:@@ -378,135 +361,13 @@ def author_key(row, aliases: dict[str, str] | None = None) -> str:normalized = recordedelse:label = str(row["label"] or row["ref"] or "")- normalized = _normalized_author_name(label, provider=str(row["provider"] or ""))+ normalized = normalized_author_name(label, provider=str(row["provider"] or ""))if normalized:normalized = (aliases or {}).get(normalized, normalized)return f"name:{normalized}"return f"source:{row['id']}"-def _follow_alias_state(connection) -> tuple[dict[str, str], list[dict]]:- rows = connection.execute(- "SELECT alias_key,alias_name,canonical_key,canonical_name,source "- "FROM follow_author_alias ORDER BY canonical_name,alias_name"- ).fetchall()- mapping = {str(row["alias_key"]): str(row["canonical_key"]) for row in rows}- groups: dict[str, dict] = {}- for row in rows:- canonical_key = str(row["canonical_key"])- group = groups.setdefault(canonical_key, {- "canonical_key": canonical_key,- # 旧别名记录可能把 F95 的容器标题保存成规范显示名;只修正读投影,- # 不在这个只读接口里偷偷改真实表。- "canonical_name": _author_display_text(row["canonical_name"]),- "aliases": [],- })- if str(row["alias_key"]) != canonical_key:- group["aliases"].append({- "key": str(row["alias_key"]),- "name": str(row["alias_name"]),- "source": str(row["source"]),- })- return mapping, [group for group in groups.values() if group["aliases"]]---def _upsert_follow_author_alias(connection, canonical_name: str, alias_name: str,- *, source: str) -> dict | None:- """Persist one alias without letting automatic evidence overwrite a decision.-- Manual confirmation may deliberately regroup an existing alias. Automatic learning is- narrower: it only fills a previously unknown platform handle and leaves every existing- mapping, especially a manual one, untouched.- """- canonical_key = _normalized_author_name(canonical_name)- alias_key = _normalized_author_name(alias_name)- if not canonical_key or not alias_key:- raise ValueError("规范作者名和平台别名都不能为空")- if canonical_key == alias_key:- raise ValueError("这两个名字归一化后相同,不需要维护别名")-- stamp = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")- mapping, _ = _follow_alias_state(connection)- canonical_root = mapping.get(canonical_key, canonical_key)- alias_root = mapping.get(alias_key, alias_key)- if source != "manual":- existing = connection.execute(- "SELECT 1 FROM follow_author_alias WHERE alias_key=?", (alias_key,)- ).fetchone()- if existing is not None or alias_root != alias_key:- return None- canonical_row = connection.execute(- "SELECT canonical_name FROM follow_author_alias WHERE canonical_key=? "- "ORDER BY CASE WHEN alias_key=canonical_key THEN 0 ELSE 1 END LIMIT 1",- (canonical_root,),- ).fetchone()- if canonical_row is not None:- canonical_name = str(canonical_row["canonical_name"])- elif canonical_root != alias_root:- connection.execute(- "UPDATE follow_author_alias SET canonical_key=?,canonical_name=?,updated_at=? "- "WHERE canonical_key=?",- (canonical_root, canonical_name, stamp, alias_root),- )-- conflict = (- "DO UPDATE SET canonical_key=excluded.canonical_key,"- "canonical_name=excluded.canonical_name,alias_name=excluded.alias_name,"- "source=excluded.source,updated_at=excluded.updated_at"- if source == "manual" else "DO NOTHING"- )- sql = (- "INSERT INTO follow_author_alias(alias_key,alias_name,canonical_key,"- "canonical_name,source,created_at,updated_at) VALUES(?,?,?,?,?,?,?) "- f"ON CONFLICT(alias_key) {conflict}"- )- connection.execute(- sql, (canonical_root, canonical_name, canonical_root, canonical_name,- source, stamp, stamp),- )- inserted = connection.execute(- sql, (alias_key, alias_name, canonical_root, canonical_name,- source, stamp, stamp),- ).rowcount- if source != "manual" and not inserted:- return None- return {"canonical": canonical_name, "alias": alias_name, "source": source}---def _official_profile_handle(provider: str, ref: str) -> str:- if provider == "fanbox":- return str(ref or "").strip()- if provider == "subscribestar":- return str(ref or "").strip().rsplit("/", 1)[-1]- if provider == "patreon":- value = str(ref or "").strip().strip("/")- if value.startswith("user/") or value.isdigit():- return ""- return value.rsplit("/", 1)[-1]- return ""---def _learn_official_author_alias(connection, provider: str, ref: str,- candidates) -> dict | None:- """Learn a platform handle only from one unambiguous official profile name."""- if provider not in _OFFICIAL_IDENTITY_PROVIDERS:- return None- authors: dict[str, str] = {}- for candidate in candidates:- name = str(candidate.author or "").strip()- key = _normalized_author_name(name)- if key:- authors.setdefault(key, name)- if len(authors) != 1:- return None- canonical_key, canonical_name = next(iter(authors.items()))- handle = _official_profile_handle(provider, ref)- if not handle or _normalized_author_name(handle) == canonical_key:- return None- return _upsert_follow_author_alias(- connection, canonical_name, handle, source=f"official:{provider}")--def _follow_alias_suggestions(rows, aliases: dict[str, str]) -> list[dict]:"""Suggest conservative cross-platform aliases; never merge automatically."""identities: dict[str, dict] = {}@@ -698,7 +559,7 @@ def q_follow_tags(contract, args) -> dict:with contract.database.read_connection() as connection:store = _store(contract, connection)source_rows = store.sources()- alias_map, _aliases = _follow_alias_state(connection)+ alias_map, _aliases = store.author_aliases()enabled = {int(row["id"]) for row in source_rows if row["enabled"]}by_source = {int(row["id"]): row for row in source_rows}items = tuple(item for item in store.items(limit=_ALL_ITEMS)@@ -748,7 +609,7 @@ def q_follow(contract, args) -> dict:with contract.database.read_connection() as connection:store = _store(contract, connection)source_rows = store.sources()- alias_map, author_aliases = _follow_alias_state(connection)+ alias_map, author_aliases = store.author_aliases()sources = [_source_payload(row, alias_map) for row in source_rows]alias_suggestions = _follow_alias_suggestions(source_rows, alias_map)enabled_source_ids = {int(row["id"]) for row in source_rows if row["enabled"]}@@ -868,60 +729,25 @@ def w_follow_status(contract, body) -> dict:return result-def _follow_playback_row(connection, item_id: int):- row = connection.execute(- "SELECT id,status FROM follow_item WHERE id=?", (item_id,),- ).fetchone()- if row is None:- raise ValueError("follow item not found")- return row--def w_follow_play(contract, body) -> dict:"""记录一次关注页直接播放;候选无需先保存成 asset。"""item_id = int(body["item"])contract.cache_bust()with contract.database.write_transaction() as connection:- row = _follow_playback_row(connection, item_id)- stamp = datetime.now(timezone.utc).timestamp()- connection.execute(- "INSERT INTO follow_playback(follow_item_id,profile_id,play_count,last_played) "- "VALUES(?,'local-default',1,?) ON CONFLICT(follow_item_id,profile_id) "- "DO UPDATE SET play_count=follow_playback.play_count+1,last_played=excluded.last_played",- (item_id, stamp),- )- if row["status"] == "new":- connection.execute(- "UPDATE follow_item SET status='seen' WHERE id=?", (item_id,),- )- return {"ok": True, "item": item_id, "status": "seen" if row["status"] == "new" else row["status"]}+ status = _store(contract, connection).record_playback(item_id)+ return {"ok": True, "item": item_id, "status": status}def w_follow_activity(contract, body) -> dict:"""累计关注页在线播放的真实时长与最远到达位置。"""item_id = int(body["item"])- position = max(float(body.get("position", 0)), 0)- duration = max(float(body.get("duration", 0)), 0)- delta = max(float(body.get("delta", 0)), 0)- ended = bool(body.get("ended"))- ratio = 1.0 if ended else (min(position / duration, 1.0) if duration > 0 else 0.0)contract.cache_bust()with contract.database.write_transaction() as connection:- _follow_playback_row(connection, item_id)- stamp = datetime.now(timezone.utc).timestamp()- connection.execute(- "INSERT INTO follow_playback(follow_item_id,profile_id,play_count,play_seconds,max_reached,last_played) "- "VALUES(?,'local-default',1,?,?,?) ON CONFLICT(follow_item_id,profile_id) DO UPDATE SET "- "play_seconds=follow_playback.play_seconds+excluded.play_seconds,"- "max_reached=max(follow_playback.max_reached,excluded.max_reached),"- "last_played=excluded.last_played",- (item_id, delta, ratio, stamp),- )- result = connection.execute(- "SELECT play_seconds,max_reached FROM follow_playback "- "WHERE follow_item_id=? AND profile_id='local-default'", (item_id,),- ).fetchone()- return {"ok": True, "item": item_id, **dict(result)}+ result = _store(contract, connection).record_playback_activity(+ item_id,+ position=body.get("position", 0), duration=body.get("duration", 0),+ delta=body.get("delta", 0), ended=bool(body.get("ended")))+ return {"ok": True, "item": item_id, **result}def w_follow_save(contract, body) -> dict:@@ -949,6 +775,52 @@ def w_follow_check(contract, body) -> dict:contract.follow_check_lock.release()+def _check_writer(contract):+ """给 `follow_check` 用的写事务工厂:每次写一条来源各自提交。"""+ @contextlib.contextmanager+ def writer():+ with contract.database.write_transaction() as connection:+ yield _store(contract, connection)+ return writer+++def _check_payload(result) -> dict:+ """把一次检查结果摊成界面用的载荷。++ 站名和来源标签按人看得懂的写法给,不让用户去猜 `rule34xxx` 是哪个站。+ """+ payload = {+ "source": result.source_id, "provider": result.provider,+ "provider_label": PROVIDER_LABELS.get(result.provider, result.provider),+ "ref": result.ref, "label": result.label, "ok": result.ok,+ # 这次读的是第几页,以及往回还剩没剩。界面据此说「已经抓到第 N 页」,+ # 而不是让用户点了一次不知道自己走到哪儿了。+ "page": result.page, "older": result.older,+ }+ if not result.ok:+ payload.update({"status": result.status, "error": result.error})+ return payload+ if result.exhausted:+ payload.update({"exhausted": True, "message": result.message})+ return payload+ fetch, outcome = result.fetch, result.outcome+ payload.update({+ "not_modified": outcome.not_modified, "discovered": outcome.discovered,+ "added": outcome.added, "updated": outcome.updated,+ # 抓到了但判为「不是 release」而丢掉的条数。丢了多少必须说出来,+ # 否则用户分不清少的是被过滤掉的还是根本没抓到——这次问「为什么这么少」+ # 就是因为界面从来没说过这类数字。+ "skipped": fetch.skipped,+ "skipped_compilations": fetch.skipped_compilations,+ # 列表判不出来、额外抓了详情页的条数。这是唯一会放大请求数的路径。+ "probed": fetch.probed,+ # 证据没存下来不算检查失败,但界面必须说出来,不能悄悄少一份原始响应。+ "evidence_error": outcome.evidence_error,+ "author_alias_learned": result.author_alias_learned,+ })+ return payload++def _run_follow_check(contract, body) -> dict:requested = body.get("source")source_id = requested if isinstance(requested, int) else None@@ -957,81 +829,14 @@ def _run_follow_check(contract, body) -> dict:# (rule34video 的作者页一页 24 条,实际 61 页)。用户点一次,往前挪一页。older = bool(body.get("older"))credentials = _credential_store(contract)- results: list[dict] = []with contract.database.read_connection() as connection:- store = _store(contract, connection)- rows = [dict(row) for row in store.sources(enabled_only=True)- if (source_id is None or row["id"] == source_id)- and (not older or row["provider"] in _BACKFILL_PROVIDERS)]- for row in rows:- row["force_media_reparse"] = (- not older and credentials.load(row["provider"]) is not None- and store.source_needs_media_reparse(row["id"])- )- for row in rows:- moment = datetime.now(timezone.utc)- provider, ref = row["provider"], row["ref"]- page = (row["backfill_page"] + 1) if older else 0- try:- connector_kwargs = {"credential": credentials.load(provider)}- gofile_credential = credentials.load("gofile")- if gofile_credential is not None:- connector_kwargs["gofile_credential"] = gofile_credential- connector = build_connector(provider, **connector_kwargs)- # 凭据已经存在但旧候选仍标着 needs_credential 时,条件请求的 304- # 会让旧解析结果永久不变。显式检查应无条件重取一次,让凭据真正生效。- fetch = connector.fetch(- ref,- etag=None if row["force_media_reparse"] else row["etag"],- last_modified=(None if row["force_media_reparse"]- else row["last_modified"]),- page=page,- )- except FollowHistoryEnd:- with contract.database.write_transaction() as connection:- _store(contract, connection).record_history_end(row["id"], moment)- results.append({- "source": row["id"], "provider": provider,- "provider_label": PROVIDER_LABELS.get(provider, provider),- "ref": ref, "label": row["label"], "ok": True,- "page": page, "older": older, "exhausted": True,- "message": "没有更多历史内容",- })- continue- except CredentialError as error:- results.append(_failure(contract, row, error, moment, "unauthorized"))- continue- except FollowSourceError as error:- results.append(_failure(contract, row, error, moment, "error"))- continue- with contract.database.write_transaction() as connection:- store = _store(contract, connection)- outcome = store.record(- row["id"], fetch,- creator_aliases=store.creator_aliases(row["entity_id"]), moment=moment,- page=page)- learned_alias = _learn_official_author_alias(- connection, provider, ref, fetch.candidates)- results.append({- "source": row["id"], "provider": provider,- "provider_label": PROVIDER_LABELS.get(provider, provider),- "ref": ref, "label": row["label"], "ok": True,- # 这次读的是第几页,以及往回还剩没剩。界面据此说「已经抓到第 N 页」,- # 而不是让用户点了一次不知道自己走到哪儿了。- "page": page, "older": older,- "not_modified": outcome.not_modified, "discovered": outcome.discovered,- "added": outcome.added, "updated": outcome.updated,- # 抓到了但判为「不是 release」而丢掉的条数。丢了多少必须说出来,- # 否则用户分不清少的是被过滤掉的还是根本没抓到——这次问「为什么这么少」- # 就是因为界面从来没说过这类数字。- "skipped": fetch.skipped,- "skipped_compilations": fetch.skipped_compilations,- # 列表判不出来、额外抓了详情页的条数。这是唯一会放大请求数的路径。- "probed": fetch.probed,- # 证据没存下来不算检查失败,但界面必须说出来,不能悄悄少一份原始响应。- "evidence_error": outcome.evidence_error,- "author_alias_learned": learned_alias,- })+ rows = plan_check(_store(contract, connection), credentials,+ source_id=source_id, older=older,+ backfill_providers=_BACKFILL_PROVIDERS)+ writer = _check_writer(contract)+ results = [_check_payload(run_check(+ row, credentials=credentials, writer=writer,+ connector_factory=build_connector, older=older)) for row in rows]return {"ok": True, "checked": len(results), "results": results}@@ -1053,17 +858,6 @@ def w_follow_schedule(contract, body) -> dict:)-def _failure(contract, row, error, moment, status) -> dict:- with contract.database.write_transaction() as connection:- _store(contract, connection).record_error(- row["id"], str(error), moment, status=status)- # 界面按人看得懂的站名和来源标签报失败,不让用户去猜 `rule34xxx` 是哪个站。- return {"source": row["id"], "provider": row["provider"],- "provider_label": PROVIDER_LABELS.get(row["provider"], row["provider"]),- "ref": row["ref"], "label": row["label"],- "ok": False, "status": status, "error": str(error)}--def _resolve_label(contract, parsed, credential) -> str:"""尽量把标签换成人看得懂的名字。@@ -1097,7 +891,7 @@ def w_follow_source(contract, body) -> dict:if not isinstance(source_id, int):raise ValueError("id must be an integer follow source id")with contract.database.write_transaction() as connection:- connection.execute("DELETE FROM follow_source WHERE id=?", (source_id,))+ _store(contract, connection).remove_source(source_id)return {"ok": True, "removed": source_id}if action == "enabled":source_id = body.get("id")@@ -1120,7 +914,7 @@ def w_follow_source(contract, body) -> dict: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_hint = normalized_author_name(author_hint) if author_hint else ""metadata = {"author_key": author_hint} if author_hint else Nonewith contract.database.write_transaction() as connection:source_id = _store(contract, connection).register(@@ -1148,21 +942,10 @@ def w_follow_author_alias(contract, body) -> dict:action = str(body.get("action") or "add")if action == "remove":alias_name = str(body.get("alias") or "").strip()- alias_key = _normalized_author_name(alias_name)- if not alias_key:- raise ValueError("别名不能为空")with contract.database.write_transaction() as connection:- row = connection.execute(- "SELECT canonical_key FROM follow_author_alias WHERE alias_key=?",- (alias_key,),- ).fetchone()- if row is None:- raise ValueError("这个作者别名不存在")- if str(row["canonical_key"]) == alias_key:- raise ValueError("规范名不能作为别名移除")- connection.execute(- "DELETE FROM follow_author_alias WHERE alias_key=?", (alias_key,))- _, groups = _follow_alias_state(connection)+ store = _store(contract, connection)+ store.remove_author_alias(alias_name)+ _, groups = store.author_aliases()return {"ok": True, "removed": alias_name, "author_aliases": groups}if action != "add":raise ValueError(f"unknown follow author alias action: {action}")@@ -1170,9 +953,9 @@ def w_follow_author_alias(contract, body) -> dict:canonical_name = str(body.get("canonical") or "").strip()alias_name = str(body.get("alias") or "").strip()with contract.database.write_transaction() as connection:- _upsert_follow_author_alias(- connection, canonical_name, alias_name, source="manual")- _, groups = _follow_alias_state(connection)+ store = _store(contract, connection)+ store.upsert_author_alias(canonical_name, alias_name, source="manual")+ _, groups = store.author_aliases()return {"ok": True, "canonical": canonical_name, "alias": alias_name,"author_aliases": groups}diff --git a/tests/test_follow_check.py b/tests/test_follow_check.pynew file mode 100644index 000000000..f5a74853b--- /dev/null+++ b/tests/test_follow_check.py@@ -0,0 +1,243 @@+"""「检查更新」这一段共用流程本身的测试。++以前 Web 与命令行各写一遍,两份不等价:命令行没有往回翻页、没有凭据到位后的强制+重取、也不学官方渠道的作者别名。这里锁住「同一句检查更新在两处做同样的事」。+"""+import contextlib+import sqlite3+import tempfile+import unittest+from datetime import datetime, timezone+from pathlib import Path++from peach.follow import FollowHistoryEnd, FollowSourceError+from peach.follow_check import plan_check, run_check+from peach.follow_secrets import CredentialError+from peach.follow_sources import FollowCandidate, SourceFetch+from peach.follow_store import FollowStore+from peach.migrations import discover+++ROOT = Path(__file__).resolve().parents[1]+MOMENT = datetime(2026, 9, 3, tzinfo=timezone.utc)+++class _Credentials:+ """只回答「有没有配」的凭据仓库替身;不带任何真实凭据值。"""++ def __init__(self, providers=()):+ self._providers = set(providers)++ def load(self, provider):+ return object() if provider in self._providers else None+++class _Connector:+ def __init__(self, fetch=None, error=None):+ self._fetch, self._error = fetch, error+ self.calls = []++ def fetch(self, ref, *, etag=None, last_modified=None, page=0):+ self.calls.append({"ref": ref, "etag": etag,+ "last_modified": last_modified, "page": page})+ if self._error is not None:+ raise self._error+ return self._fetch+++def _fetch(provider="fanbox", ref="ffxivinitiala", **kwargs):+ base = dict(provider=provider, ref=ref, semantics="work",+ request_url=f"https://{ref}.fanbox.cc/")+ base.update(kwargs)+ return SourceFetch(**base)+++class _CheckCase(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name).resolve()+ self.connection = sqlite3.connect(self.root / "ledger.db")+ self.connection.row_factory = sqlite3.Row+ for migration in discover(ROOT / "migrations"):+ self.connection.executescript(migration.sql)+ self.connection.commit()+ self.addCleanup(self.connection.close)+ self.store = FollowStore(lambda: self.connection,+ sources_root=self.root / "sources")++ @contextlib.contextmanager+ def writer(self):+ yield self.store++ def _register(self, **kwargs):+ base = dict(provider="fanbox", ref="ffxivinitiala", label="Initiala",+ url="https://ffxivinitiala.fanbox.cc/", semantics="work")+ base.update(kwargs)+ return self.store.register(**base)++ def _row(self, source_id):+ return next(dict(row) for row in self.store.sources()+ if row["id"] == source_id)++ def _run(self, source_id, connector, **kwargs):+ return run_check(self._row(source_id), credentials=_Credentials(),+ writer=self.writer,+ connector_factory=lambda provider, **kw: connector,+ moment=MOMENT, **kwargs)+++class PlanCheckTests(_CheckCase):+ def test_only_enabled_sources_are_planned(self):+ first = self._register()+ second = self._register(ref="other", url="https://other.fanbox.cc/")+ self.store.set_enabled(second, False)+ planned = plan_check(self.store, _Credentials())+ self.assertEqual([row["id"] for row in planned], [first])++ def test_paging_back_is_offered_only_where_it_actually_works(self):+ """官方渠道没有历史分页;把它列进往回翻页只会白打一次请求。"""+ self._register()+ archive = self._register(provider="kemono", ref="fanbox/1",+ url="https://kemono.cr/fanbox/user/1")+ planned = plan_check(self.store, _Credentials(), older=True,+ backfill_providers=frozenset({"kemono"}))+ self.assertEqual([row["id"] for row in planned], [archive])++ def test_a_credential_that_just_arrived_forces_one_unconditional_refetch(self):+ """凭据到位而旧候选还标着 needs_credential 时必须绕过条件请求游标。++ 否则上游回 304,旧解析结果永久不变——配了凭据却什么都没变,用户没法自己+ 看出原因。这一条以前只有 Web 那份有。+ """+ source_id = self._register(provider="rule34xxx", ref="tag",+ url="https://rule34.xxx/?tags=tag")+ self.store.record(source_id, _fetch(+ provider="rule34xxx", ref="tag", candidates=(+ FollowCandidate(provider="rule34xxx", external_id="1", title="a",+ extra={"media_needs_credential": True}),)),+ moment=MOMENT)+ planned = plan_check(self.store, _Credentials({"rule34xxx"}))+ self.assertTrue(planned[0]["force_media_reparse"])+ without = plan_check(self.store, _Credentials())+ self.assertFalse(without[0]["force_media_reparse"],+ "没配凭据就没有可生效的重解析,不该白打一次无条件请求")++ def test_paging_back_never_forces_a_refetch(self):+ """往回翻的那一页本来就没有游标,强制重取没有意义。"""+ source_id = self._register(provider="rule34xxx", ref="tag",+ url="https://rule34.xxx/?tags=tag")+ self.store.record(source_id, _fetch(+ provider="rule34xxx", ref="tag", candidates=(+ FollowCandidate(provider="rule34xxx", external_id="1", title="a",+ extra={"media_needs_credential": True}),)),+ moment=MOMENT)+ planned = plan_check(self.store, _Credentials({"rule34xxx"}), older=True,+ backfill_providers=frozenset({"rule34xxx"}))+ self.assertFalse(planned[0]["force_media_reparse"])++ def test_force_applies_to_every_source(self):+ """命令行的 `--force` 是无条件的,不依赖任何 needs_credential 痕迹。"""+ self._register()+ planned = plan_check(self.store, _Credentials(), force=True)+ self.assertTrue(planned[0]["force_media_reparse"])+++class RunCheckTests(_CheckCase):+ def test_a_normal_check_reads_the_first_page_with_the_stored_cursors(self):+ source_id = self._register()+ self.store.record(source_id, _fetch(etag='W/"1"', last_modified="Mon"),+ moment=MOMENT)+ connector = _Connector(_fetch(not_modified=True))+ result = self._run(source_id, connector)+ self.assertTrue(result.ok)+ self.assertEqual(connector.calls, [{"ref": "ffxivinitiala", "etag": 'W/"1"',+ "last_modified": "Mon", "page": 0}])+ self.assertTrue(result.outcome.not_modified)++ def test_paging_back_asks_for_the_next_page_and_drops_the_cursors(self):+ source_id = self._register(provider="kemono", ref="fanbox/1",+ url="https://kemono.cr/fanbox/user/1")+ connector = _Connector(_fetch(provider="kemono", ref="fanbox/1"))+ result = self._run(source_id, connector, older=True)+ self.assertEqual(result.page, 1)+ self.assertTrue(result.older)+ self.assertEqual(connector.calls[0]["page"], 1)+ # 第二次再往回,接着上一次走到的位置。+ connector = _Connector(_fetch(provider="kemono", ref="fanbox/1"))+ self.assertEqual(self._run(source_id, connector, older=True).page, 2)++ def test_the_end_of_history_is_recorded_not_reported_as_a_failure(self):+ source_id = self._register(provider="kemono", ref="fanbox/1",+ url="https://kemono.cr/fanbox/user/1")+ result = self._run(source_id, _Connector(error=FollowHistoryEnd("400")),+ older=True)+ self.assertTrue(result.ok)+ self.assertTrue(result.exhausted)+ self.assertEqual(result.message, "没有更多历史内容")+ self.assertEqual(self._row(source_id)["last_status"], "not_modified")+ self.assertEqual(self._row(source_id)["backfill_page"], 0,+ "翻到尽头不推进游标,否则下一次会跳过真实存在的一页")++ def test_a_missing_credential_is_its_own_status(self):+ source_id = self._register()+ result = self._run(source_id,+ _Connector(error=CredentialError("需要 user_id 与 api_key")))+ self.assertFalse(result.ok)+ self.assertEqual(result.status, "unauthorized")+ self.assertEqual(result.error, "需要 user_id 与 api_key")+ self.assertEqual(self._row(source_id)["last_status"], "unauthorized")+ self.assertNotIn("api_key", str(result.fetch or ""))++ def test_a_source_failure_is_a_return_value_not_an_exception(self):+ """逐条独立成败:一个来源被挡住不该让其余来源的更新一起消失。"""+ source_id = self._register()+ result = self._run(source_id, _Connector(error=FollowSourceError("HTTP 503")))+ self.assertFalse(result.ok)+ self.assertEqual(result.status, "error")+ self.assertEqual(self._row(source_id)["last_status"], "error")++ def test_an_official_profile_handle_is_learned_from_one_unambiguous_author(self):+ """fanbox 的 ref 就是作者本人的手柄,可以直接学成别名。++ 这一条以前只在 Web 那份检查里有,`peach follow check` 抓同一条来源不会学,+ 于是同一个人在命令行抓完之后仍然显示成两个作者。+ """+ source_id = self._register()+ result = self._run(source_id, _Connector(_fetch(candidates=(+ FollowCandidate(provider="fanbox", external_id="1", title="a",+ author="Initiala"),+ FollowCandidate(provider="fanbox", external_id="2", title="b",+ author="Initiala"),+ ))))+ self.assertEqual(result.author_alias_learned,+ {"canonical": "Initiala", "alias": "ffxivinitiala",+ "source": "official:fanbox"})+ mapping, _groups = self.store.author_aliases()+ self.assertEqual(mapping["ffxivinitiala"], "initiala")++ def test_two_different_authors_in_one_fetch_teach_nothing(self):+ source_id = self._register()+ result = self._run(source_id, _Connector(_fetch(candidates=(+ FollowCandidate(provider="fanbox", external_id="1", title="a",+ author="Initiala"),+ FollowCandidate(provider="fanbox", external_id="2", title="b",+ author="Someone Else"),+ ))))+ self.assertIsNone(result.author_alias_learned)+ self.assertEqual(self.store.author_aliases(), ({}, []))++ def test_an_archive_ref_is_never_learned_as_an_author_name(self):+ """`fanbox/30917150` 里的数字 id 不是名字,学成别名会造出一个假作者。"""+ source_id = self._register(provider="kemono", ref="fanbox/30917150",+ url="https://kemono.cr/fanbox/user/30917150")+ result = self._run(source_id, _Connector(_fetch(+ provider="kemono", ref="fanbox/30917150", candidates=(+ FollowCandidate(provider="kemono", external_id="1", title="a",+ author="Initiala"),))))+ self.assertIsNone(result.author_alias_learned)+ self.assertEqual(self.store.author_aliases(), ({}, []))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_follow_cli.py b/tests/test_follow_cli.pyindex bb55653ed..0dfab3721 100644--- a/tests/test_follow_cli.py+++ b/tests/test_follow_cli.py@@ -178,6 +178,72 @@ class FollowCliTests(unittest.TestCase):self.assertEqual(code, 1)self.assertIn("HTTP 503", output)+ def test_check_learns_an_official_author_handle_like_the_web_surface_does(self):+ """命令行抓完也要学作者别名,否则同一个人还是显示成两个作者。++ 以前只有 `/api/follow/check` 学:`peach follow check` 抓 fanbox 那条来源+ 什么都不记,而两处都叫「检查更新」,没有任何地方说明差别在哪。+ """+ self._run("add", "--provider", "fanbox", "--ref", "ffxivinitiala")+ fetch = _fetch(provider="fanbox", ref="ffxivinitiala",+ request_url="https://ffxivinitiala.fanbox.cc/",+ candidates=(+ FollowCandidate(provider="fanbox", external_id="1",+ title="A", author="Initiala"),))+ with mock.patch.object(follow_cli, "build_connector") as factory:+ factory.return_value.fetch.return_value = fetch+ code, output = self._run("check")+ self.assertEqual(code, 0)+ self.assertIn("记下别名 ffxivinitiala → Initiala", output)+ connection = sqlite3.connect(self.db)+ rows = connection.execute(+ "SELECT alias_key,canonical_key,source FROM follow_author_alias "+ "ORDER BY alias_key").fetchall()+ connection.close()+ self.assertEqual(rows, [("ffxivinitiala", "initiala", "official:fanbox"),+ ("initiala", "initiala", "official:fanbox")])++ def test_check_older_pages_back_only_where_paging_actually_works(self):+ """`--older` 往回抓一页;官方渠道没有历史分页,不会白打请求。"""+ self._run("add", "--provider", "kemono", "--ref", "fanbox/1")+ self._run("add", "--provider", "fanbox", "--ref", "ffxivinitiala")+ seen = []++ def factory(provider, **kwargs):+ connector = mock.Mock()++ def fetch(ref, *, etag=None, last_modified=None, page=0):+ seen.append((provider, page))+ return _fetch(provider=provider, ref=ref,+ request_url=f"https://{provider}.test/{ref}")++ connector.fetch.side_effect = fetch+ return connector++ with mock.patch.object(follow_cli, "build_connector", factory):+ code, output = self._run("check", "--older")+ self.assertEqual(code, 0)+ self.assertEqual(seen, [("kemono", 1)], "fanbox 不支持往回翻页")+ self.assertIn("第 1 页", output)++ def test_force_skips_the_conditional_cursors(self):+ self._add_one()+ seen = []++ def factory(provider, **kwargs):+ connector = mock.Mock()++ def fetch(ref, *, etag=None, last_modified=None, page=0):+ seen.append((etag, last_modified))+ return _fetch(not_modified=True)++ connector.fetch.side_effect = fetch+ return connector++ with mock.patch.object(follow_cli, "build_connector", factory):+ self._run("check", "--force")+ self.assertEqual(seen, [(None, None)])+def test_check_skips_disabled_sources(self):self._run("add", "--provider", "rule34video", "--ref", "lazyprocrastinator")connection = sqlite3.connect(self.db)diff --git a/tests/test_follow_connector_base.py b/tests/test_follow_connector_base.pyindex 8e4f5719d..773efa52a 100644--- a/tests/test_follow_connector_base.py+++ b/tests/test_follow_connector_base.py@@ -9,8 +9,9 @@ import unittestfrom peach.follow import FollowSourceErrorfrom peach.follow_sources import (CONNECTORS, KemonoConnector, _BaseConnector, display_thumb_url,- is_history_end_error,+ is_history_end_error, official_profile_handle,)+from peach.follow_store import _OFFICIAL_IDENTITY_PROVIDERSfrom peach.http import HttpResponse@@ -306,5 +307,54 @@ class NoPrivateReachIntoConnectorsTests(unittest.TestCase):)+class ProfileHandleTests(unittest.TestCase):+ """ref 里哪一截是作者本人的手柄,由各站自己的连接器说。++ 这些规则以前写在 `web_follow` 的一串 if/elif 里,而「ref 长什么形状」正是+ 连接器已经在解析、在校验的东西:同一份知识分在两层,改一处就会漂移。+ """++ def test_an_official_channel_ref_is_the_author_handle(self):+ cases = {+ "fanbox": ("ffxivinitiala", "ffxivinitiala"),+ "subscribestar": ("subscribestar.adult/initiala", "initiala"),+ "patreon": ("initiala", "initiala"),+ }+ for provider, (ref, expected) in cases.items():+ with self.subTest(provider=provider):+ self.assertEqual(official_profile_handle(provider, ref), expected)++ def test_a_numeric_patreon_user_page_has_no_handle(self):+ """`user/12345` 是内部 id,不是名字;学成别名会造出一个假作者。"""+ for ref in ("user/12345", "12345", "/user/12345/"):+ self.assertEqual(official_profile_handle("patreon", ref), "")++ def test_archive_and_tag_sites_offer_no_handle_at_all(self):+ cases = (("kemono", "fanbox/30917150"), ("coomer", "onlyfans/x"),+ ("pawchive", "fanbox/1"), ("rule34xxx", "lazyprocrastinator"),+ ("rule34video", "lazyprocrastinator"), ("f95zone", "50685"),+ ("rule34paheal", "tag"), ("simpcity", "thread"))+ for provider, ref in cases:+ with self.subTest(provider=provider):+ self.assertEqual(official_profile_handle(provider, ref), "")++ def test_every_connector_answers_this_question(self):+ """基类给了默认值,所以新增站点不会因为漏实现而炸在检查更新的中途。"""+ for provider, factory in CONNECTORS.items():+ with self.subTest(provider=provider):+ self.assertIsInstance(factory.profile_handle("anything"), str)+ self.assertEqual(official_profile_handle("not-registered", "x"), "")++ def test_only_the_official_identity_providers_actually_return_one(self):+ """能返回手柄的站必须正好是 `_OFFICIAL_IDENTITY_PROVIDERS` 那一组。++ 这两处一旦不一致,就会出现「明明解析出了手柄却永远不学」或者反过来+ 「学了一个不该信的名字」,而两种都不会报错。+ """+ answering = {provider for provider in CONNECTORS+ if official_profile_handle(provider, "some-name")}+ self.assertEqual(answering, set(_OFFICIAL_IDENTITY_PROVIDERS))++if __name__ == "__main__":unittest.main()diff --git a/tests/test_follow_providers.py b/tests/test_follow_providers.pyindex 202e83069..b74678722 100644--- a/tests/test_follow_providers.py+++ b/tests/test_follow_providers.py@@ -12,11 +12,8 @@ from peach.follow_secrets import (SYNCABLE_FIELDS,credential_store_for,)-from peach.web_follow import (- PROVIDER_LABELS,- _BACKFILL_PROVIDERS,- _OFFICIAL_IDENTITY_PROVIDERS,-)+from peach.follow_store import _OFFICIAL_IDENTITY_PROVIDERS+from peach.web_follow import PROVIDER_LABELS, _BACKFILL_PROVIDERSclass ProviderRegistryTests(unittest.TestCase):diff --git a/tests/test_follow_store.py b/tests/test_follow_store.pyindex c3ac73df0..cb1a6b8a5 100644--- a/tests/test_follow_store.py+++ b/tests/test_follow_store.py@@ -8,7 +8,9 @@ from pathlib import Pathfrom peach.follow import FollowSourceErrorfrom peach.follow_sources import FollowCandidate, SourceFetch-from peach.follow_store import FollowStore, ReleaseGroup+from peach.follow_store import (+ FollowStore, ReleaseGroup, author_display_text, normalized_author_name,+)from peach.migrations import discover@@ -560,5 +562,129 @@ class ReleaseGroupTests(unittest.TestCase):group.release_key = "other"+class AuthorIdentityTests(_StoreCase):+ """作者别名表的写入口径。以前这些 SQL 直接写在 Web 处理函数里。"""++ def test_the_container_suffix_is_not_part_of_the_author_name(self):+ """F95 的线程标题说的是一个容器,不是另一个作者。++ 真实数据是 `Lazy Procrastinator Collection`,而每一条作者来源都是+ `LazyProcrastinator`;留着这个通用后缀会凭空多出一个分组。+ """+ self.assertEqual(+ normalized_author_name("Lazy Procrastinator Collection",+ provider="f95zone"),+ normalized_author_name("LazyProcrastinator"))+ # 只对 F95 成立:别的站上 `Collection` 可能真是名字的一部分。+ self.assertNotEqual(+ normalized_author_name("Lazy Procrastinator Collection"),+ normalized_author_name("LazyProcrastinator"))++ def test_the_service_suffix_only_says_where_they_publish(self):+ self.assertEqual(normalized_author_name("LazyProcrastinator · fanbox"),+ normalized_author_name("lazyprocrastinator"))+ self.assertEqual(author_display_text("Billyhhyb · patreon"), "Billyhhyb")++ def test_a_manual_alias_maps_both_names_to_one_canonical_key(self):+ self.store.upsert_author_alias("Initiala", "ffxivinitiala", source="manual",+ moment=MOMENT)+ mapping, groups = self.store.author_aliases()+ self.assertEqual(mapping["ffxivinitiala"], "initiala")+ self.assertEqual(mapping["initiala"], "initiala")+ self.assertEqual([group["canonical_name"] for group in groups], ["Initiala"])+ self.assertEqual([alias["name"] for alias in groups[0]["aliases"]],+ ["ffxivinitiala"])++ def test_automatic_evidence_never_overwrites_a_decision(self):+ """人工确认可以有意重新分组;自动证据只填此前未知的手柄。"""+ self.store.upsert_author_alias("Initiala", "ffxivinitiala", source="manual",+ moment=MOMENT)+ self.assertIsNone(self.store.upsert_author_alias(+ "Someone Else", "ffxivinitiala", source="official:fanbox", moment=MOMENT))+ mapping, _groups = self.store.author_aliases()+ self.assertEqual(mapping["ffxivinitiala"], "initiala")++ def test_two_names_that_normalize_the_same_are_not_an_alias(self):+ for canonical, alias in (("Initiala", "initi-ala"), ("", "x"), ("x", "")):+ with self.assertRaises(ValueError):+ self.store.upsert_author_alias(canonical, alias, source="manual")++ def test_the_canonical_name_cannot_be_removed_as_an_alias(self):+ """删规范名会拆散整个组,剩下的别名指向一个不存在的键。"""+ self.store.upsert_author_alias("Initiala", "ffxivinitiala", source="manual",+ moment=MOMENT)+ with self.assertRaises(ValueError):+ self.store.remove_author_alias("Initiala")+ with self.assertRaises(ValueError):+ self.store.remove_author_alias("never-registered")+ with self.assertRaises(ValueError):+ self.store.remove_author_alias("")+ self.store.remove_author_alias("ffxivinitiala")+ self.assertEqual(self.store.author_aliases(), ({"initiala": "initiala"}, []))++ def test_an_official_handle_is_learned_only_from_one_unambiguous_author(self):+ learned = self.store.learn_official_author_alias(+ "fanbox", "ffxivinitiala",+ (_candidate("1", "a", provider="fanbox", author="Initiala"),))+ self.assertEqual(learned["alias"], "ffxivinitiala")+ self.assertEqual(learned["source"], "official:fanbox")+ # 归档站的 ref 是数字 id,不是名字。+ self.assertIsNone(self.store.learn_official_author_alias(+ "kemono", "fanbox/30917150",+ (_candidate("1", "a", provider="kemono", author="Initiala"),)))+++class SourceRemovalTests(_StoreCase):+ def test_removing_a_source_takes_it_out_of_the_listing(self):+ source_id = self._source()+ other = self._source(provider="rule34xxx", ref="tag")+ self.store.remove_source(source_id)+ self.assertEqual([row["id"] for row in self.store.sources()], [other])+++class PlaybackTests(_StoreCase):+ def _item(self):+ source_id = self._source()+ self.store.record(source_id, _fetch([_candidate("1", "Fiona")]),+ moment=MOMENT)+ return self.store.items()[0].id++ def test_playing_a_new_item_marks_it_seen_once(self):+ item_id = self._item()+ self.assertEqual(self.store.record_playback(item_id, MOMENT), "seen")+ # 已经播过的不再改状态:手动标成 ignored 之后再播不该被拉回 seen。+ self.store.set_status(item_id, "ignored")+ self.assertEqual(self.store.record_playback(item_id, MOMENT), "ignored")+ count = self.connection.execute(+ "SELECT play_count FROM follow_playback WHERE follow_item_id=?",+ (item_id,)).fetchone()[0]+ self.assertEqual(count, 2)++ def test_activity_accumulates_time_and_keeps_the_furthest_point(self):+ item_id = self._item()+ first = self.store.record_playback_activity(+ item_id, position=30, duration=100, delta=30, moment=MOMENT)+ self.assertEqual(first, {"play_seconds": 30.0, "max_reached": 0.3})+ # 往回拖再看一遍:时长累加,最远位置不倒退。+ second = self.store.record_playback_activity(+ item_id, position=10, duration=100, delta=10, moment=MOMENT)+ self.assertEqual(second, {"play_seconds": 40.0, "max_reached": 0.3})+ ended = self.store.record_playback_activity(+ item_id, position=99, duration=100, delta=1, ended=True, moment=MOMENT)+ self.assertEqual(ended["max_reached"], 1.0)++ def test_an_unknown_item_is_a_request_error_not_a_storage_failure(self):+ """调用方把 ValueError 映射成 400;这里不能变成 500。"""+ for call in (lambda: self.store.record_playback(9999),+ lambda: self.store.record_playback_activity(9999)):+ with self.assertRaises(ValueError):+ call()++ def test_nonsense_numbers_do_not_reach_the_database(self):+ item_id = self._item()+ result = self.store.record_playback_activity(+ item_id, position=-5, duration=0, delta=-3, moment=MOMENT)+ self.assertEqual(result, {"play_seconds": 0.0, "max_reached": 0.0})+if __name__ == "__main__":unittest.main()diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 5d9eda2e4..d63d01246 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -14,7 +14,7 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom unittest import mock-from peach import web_follow+from peach import follow_store, web_followfrom peach.follow import FollowHistoryEndfrom peach.follow import FollowSourceErrorfrom peach.follow_discovery import Discovery, ExternalSearch@@ -2088,9 +2088,9 @@ class FollowWebSourceTests(unittest.TestCase):self.assertNotEqual(key(label="", id=1), key(label="", id=2))def test_collection_is_container_copy_not_part_of_the_author_display_name(self):- self.assertEqual(web_follow._author_display_text("Billyhhyb Collection"),+ self.assertEqual(follow_store.author_display_text("Billyhhyb Collection"),"Billyhhyb")- self.assertEqual(web_follow._author_display_text("Billyhhyb · patreon"),+ self.assertEqual(follow_store.author_display_text("Billyhhyb · patreon"),"Billyhhyb")def test_avatars_only_come_from_providers_that_actually_serve_one(self):