Peach: Local-first video metadata scraper and media manager.
feat(follow): 关注作者建档成创作者实体
longmeidao7ffb540fd47d
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex 264351422..42c921109 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -84,7 +84,7 @@6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;浏览器历史现可用 SQLite 一致性副本增量进入私有源库,并生成不含 URL/标题的 creator/tag candidate 与聚合报告。旧 2026-08-13 原始包已确认不在 Windows 外置盘;仍需在 Mac 开启 iCloud Safari、完成首次导入,并把两端每周刷新装成系统计划任务。AI 结论不得直接改真相字段。7. **扫描与采集任务的参数标定**:无进展预警的 120 秒与单项动作预算(资料 90 秒、封面 240 秒)目前按最坏请求时长取的保守值;等一轮真实任务记录各阶段实测耗时后标定,同时确定完整问题文件的保留周期。-## 其他开放需求(64 项)+## 其他开放需求(65 项)本区包含尚未开始和部分已实现的需求;每项正文说明剩余工作,验收状态见「已核对的实施状态」。@@ -190,8 +190,9 @@71. **「已拥有」标记的浏览器扩展**(低):在 javdb、javbus、javlibrary 页面上给馆藏已有的番号标「已拥有」(JavBoss `content/jav-ownership.js`,凭 API 令牌查询)。Peach 侧要一个只读的按番号查询接口与独立令牌,和第 27 条的开放 API 同批设计。72. **关注页往回抓键的忙态闪动**(低):按下「抓更早的一页」后,忙态由 `starting`、`olderRun`、`running` 三者推出;POST 返回时 `starting` 先清,首次轮询回来前 `running` 仍是 false,按钮文字会短暂回到「抓更早的一页」。浏览器 e2e「检查更新与往回抓」偶发红就是撞上这一拍。忙态应从按下一直保持到首次轮询确认任务在跑或已结束。73. **关注链路剩下的两处重复回源**(低):一是直连图床的卡面缩略图,浏览器取一份,`FollowFaceIndex` 为算画面签名在服务端再取一份(每个地址一次,经按站冷却);要只取一次,得让卡面缩略图改经 Peach 代理并落盘,影响整个 `_thumb_url` 投影与远程访问的流量。二是 kemono 系判定为非资源帖的帖子不落库,每次检查仍会重探详情(每次最多 12 帖);要记住这类判定,需要在来源 metadata 里存一份有界的拒绝清单。+74. **关注作者建档的后续**(ADR-0096):名册「创作者」档只列有入库作品的实体,纯在线作者只在「在线」档,两档要合成一份;coomer 与 simpcity 来源的作者和发布账号之间补 `operates_account` 关系;Gumroad、Fantia 的归档 id 形状核实后再还原原站账号;已有 F95 来源按新的名片白名单重新解析一次;绑定后删除别名时,已绑的来源要能拆开。-合计:**71 项开放需求**,其中 7 项已有骨架,64 项其他开放需求。已完成的需求不在这里留痕,去 Git 历史查。+合计:**72 项开放需求**,其中 7 项已有骨架,65 项其他开放需求。已完成的需求不在这里留痕,去 Git 历史查。## 待执行的操作(40 项)diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 6e6df4021..4cbca7664 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -22,6 +22,8 @@ Babepedia 资料采集复用 `babepedia_page` 的主名与别名交叉核对、`FC2 卖家名册复用 `sources/fc2.py` 的 `label`、`seller_url` 来源契约、`normalise_code_key`、`upsert_asset_entity`、职业断言和 SQLite 备份。`import_fc2_sellers.py` 读取已有作品快照,不发起采集;账号地址、来源作品号和馆藏作品号必须一致。同名不同账号、作品来源冲突保留在复核产物,既有身份和资料不覆盖;计划按摄取同一判据把集合名归到已有账号,摄取不收的作品记跳过,回收站作品不挂卖家。写入归属为 `script:fc2-seller@<批次>`,统一撤回入口 `revert_auto_landing.py` 同时处理账号链接、别名、外部编号、卖家断言及来源关系;有后续资料或引用的实体保留。导航复用 `BoardTabs`,动画作者保留 `creator` 身份与资料路由,通过艺人分类浏览。不新增依赖或外部解析器。+关注作者建档(`follow_creators`,ADR-0096)复用关注页的作者归组 `web_follow.name_key`/`author_name`、`canonicalize_entity_name` 的平台名闸、`follow_sources.profile_link_identity` 的名片识别和后继派发(ADR-0040)。链接与别名按 `auto:follow-creator@<批次>` 记归属,`revert_auto_landing.py` 统一撤回;实体有其他引用时保留。资料页的同名确认复用 `Note` 与 Board `Button`,不新增依赖。+账号归属复用 `review_decision`、`creator_collection_base`、`write_owned_fields` 和全库归属审计。明确拒绝的资产与账号组合在自动摄取时跳过;用户写入保留复核入口。网黄博主只命中可信个人、内容创作者或发布账号断言,未分类账号保留全部名册入口。`attach_avatar_availability` 集中处理资料页、索引、搜索与统计的作品头像:发布账号缺少本人或出演职业证据时不提供作品帧兜底,已安装图片独立保留。来源核查清单、逐关系回执和备份存于 `peach-data/review/`。`entity_identity_research` 与 `apply_entity_identity_research.py` 复用规范实体写入、字段归属保护、只读预览、SQLite 备份及冻结计划。逐行撤回回执核对后续修改,新增实体有额外引用时拒绝删除;观看历史和人工判断不被回滚覆盖。diff --git a/scripts/revert_auto_landing.py b/scripts/revert_auto_landing.pyindex 2b14867d2..f79dc3096 100644--- a/scripts/revert_auto_landing.py+++ b/scripts/revert_auto_landing.py@@ -32,6 +32,10 @@ id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接西方发行方的无番号作品封面(`ASSET-ID-<id>.jpg`)在 `.scraping.json` 边车里记 `source` 与 `batch`(`auto:western-artwork@<时间>`)。撤回删掉封面与同组边车,作品回到没有封面的样子。+关注作者建档(ADR-0096)建下的创作者在 `entity.metadata_json` 里记 `source` 与 `batch`。撤回先删+这一批的链接与别名,再解绑关注来源;实体还被别的行引用(人挂上的作品、链接)就留着,没有才删。++ revert_auto_landing.py --source auto:follow-creatorrevert_auto_landing.py --source auto:performer-aliasrevert_auto_landing.py --source auto:performer-alias --batch auto:performer-alias@812revert_auto_landing.py --source auto:performer-profile@@ -54,8 +58,8 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))-from peach import (company_profiles, fc2_sellers, jav_poster_crop, record_rehome, sample_images, # noqa: E402- wants, western_artwork)+from peach import (company_profiles, fc2_sellers, follow_creators, jav_poster_crop, # noqa: E402+ record_rehome, sample_images, wants, western_artwork)from peach.config import COVER_DIR, GENERATED_DIR # noqa: E402from peach.metadata_auto_apply import UNION_TAGS_SOURCE # noqa: E402from peach.scripting import add_ledger_write_args, open_for_write, verify_after_write # noqa: E402@@ -296,6 +300,7 @@ def main(argv: list[str] | None = None) -> int:profiles = planned_profiles(connection, args.source, args.batch)companies = company_profiles.planned_revert(connection, args.source, args.batch)sellers = fc2_sellers.planned_revert(connection, args.source, args.batch)+ creators = follow_creators.planned_revert(connection, args.source, args.batch)refs = planned_refs(connection, args.source, args.batch)memberships = planned_memberships(connection, args.source, args.batch)makers = planned_makers(connection, args.source, args.batch)@@ -312,6 +317,8 @@ def main(argv: list[str] | None = None) -> int:for alias in aliases:print(f" - 别名 {alias['entity'][:20]:<20} {alias['alias'][:40]} {alias['source']}")print_profiles(profiles, companies)+ for creator in creators:+ print(f" - 建档 {creator['name'][:20]:<20} {creator['sources']} 个来源 {creator['batch']}")for ref in refs:print(f" - 编号 {ref['entity'][:20]:<20} {ref['provider']} {ref['id']} {ref['batch']}")for membership in memberships:@@ -328,7 +335,8 @@ def main(argv: list[str] | None = None) -> int:for rehome in rehomes:print(f" - 接回 {rehome['old_asset_id']:<8} → {rehome['new_asset_id']:<8} "f"{rehome['name'][:40]} {rehome['batch']}")- print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "公司资料": len(companies), "卖家": len(sellers), "编号": len(refs),+ print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "公司资料": len(companies), "卖家": len(sellers),+ "关注建档": len(creators), "编号": len(refs),"归属": len(memberships), "片商": len(makers), "标识文件": len(files), "封面": len(covers),"样张": sum(sample["count"] for sample in samples), "否决": len(rejections),"标签": len(tags), "接回": len(rehomes), "想要入库": len(acquired)})@@ -370,6 +378,8 @@ def main(argv: list[str] | None = None) -> int:restored = record_rehome.revert(connection, args.source, args.batch)reopened_wants = wants.revert(connection, args.source, args.batch)removed_seller_relations = fc2_sellers.revert(connection, sellers)+ # 链接与别名已在上面按批次删掉,剩下没有别的引用的实体才删得掉。+ creator_revert = follow_creators.revert(connection, creators)integrity, orphans = verify_after_write(connection)finally:connection.close()@@ -378,7 +388,8 @@ def main(argv: list[str] | None = None) -> int:"删除编号": len(refs), "删除归属": len(memberships), "删除片商": len(makers),"删除样张": removed_samples, "删除否决": len(rejections),"删除标签": len(tags), "删除扁平标签": removed_tag_rows, "重开决定": reopened,- "撤回接回": restored, "想要回到待找": reopened_wants, "卖家关系": removed_seller_relations, "删除文件": removed,+ "撤回接回": restored, "想要回到待找": reopened_wants, "卖家关系": removed_seller_relations,+ "解绑关注来源": creator_revert["unbound"], "删除建档实体": creator_revert["removed"], "删除文件": removed,"integrity_check": integrity, "foreign_key_check": orphans})return 0diff --git a/src/peach/follow_creators.py b/src/peach/follow_creators.pynew file mode 100644index 000000000..4efe77de9--- /dev/null+++ b/src/peach/follow_creators.py@@ -0,0 +1,374 @@+"""关注作者建档:关注来源里的作者落成 `creator` 实体(ADR-0096)。++关注页把同一个人在几个站上的来源归成一组(`web_follow.author_key`),但那一组只活在+关注页里:没有资料页,名册上点开只能回关注页筛选。这条后继把每一组落成一条创作者实体,+绑上它名下的来源,再把来源数据里已经有的正版发布渠道与社媒账号登记成实体链接。++判据全是确定的,不联网:++1. **建谁**:没绑实体、作者键是名字(`name:`)的每一组。名字取关注页那一份+ (`web_follow.author_name`),过 `canonicalize_entity_name('creator')` 那道平台名、+ 结构目录与转载站的闸,被挡的整组跳过。+2. **不建、等人**:账本里已有同名或同别名的创作者,或两组归一成同一个名字。姓名相同不能+ 自动建立关联(ADR-0095),这几组原样留着,摘要里列出来。+3. **并进已建的**:新来源与某个已建档实体名下的来源,在绑定前本来就归同一个名字键——+ 那是关注页自己的分组,不是新的同名推断,直接绑过去。+4. **链接**:官方来源自己的地址;归档站上的原始账号(FANBOX 的数字 id 就是 pixiv 用户 id,+ Patreon 用户 id 拼 `user?u=`,OnlyFans 用户名);名片里可信的那几条+ (`web_follow.trusted_profile_links`)。归档站与聚合站本身不登记,`follow_source`+ 的绑定就是它们的记录。++链接只在绑定那一刻写:之后人删掉的一条不会在下一轮又长回来。每条写入都带归属串+`auto:follow-creator` 与这一轮的批次号,`scripts/revert_auto_landing.py` 按它们整批撤回:+解绑来源、删链接与别名,实体本身只在没有别的引用时删。+"""+from __future__ import annotations++import json+import sqlite3+import time+from dataclasses import dataclass+from datetime import datetime, timezone+from urllib.parse import urlsplit++from .entities import canonicalize_entity_name, normalize_entity_name+from .followups import FollowupType, register++TASK_KEY = "follow-creator"+TASK_LABEL = "关注作者建档"++#: 这条后继写下的一切都带这个归属串,撤回按它认。+SOURCE = "auto:follow-creator"++#: 名片服务 → 链接种类与站名。正版发布渠道记 `official`,社媒记 `social`;+#: 站名与账本里已有的那批同写法(`X`、`Instagram`、`OnlyFans`)。+CHANNELS = {+ "fanbox": ("official", "FANBOX"),+ "patreon": ("official", "Patreon"),+ "subscribestar": ("official", "SubscribeStar"),+ "gumroad": ("official", "Gumroad"),+ "fantia": ("official", "Fantia"),+ "itchio": ("official", "itch.io"),+ "kofi": ("official", "Ko-fi"),+ "onlyfans": ("official", "OnlyFans"),+ "twitter": ("social", "X"),+ "pixiv": ("social", "pixiv"),+ "deviantart": ("social", "DeviantArt"),+ "instagram": ("social", "Instagram"),+ "bsky": ("social", "Bluesky"),+}++#: 名片手柄 → 规范地址。论坛正文里贴的地址带跟踪参数、`http`、`/posts` 之类,+#: 同一个账号三种写法;按手柄重拼,同一个人的同一个账号只登记一条。+_PROFILE_URLS = {+ "fanbox": "https://{}.fanbox.cc/",+ "patreon": "https://www.patreon.com/{}",+ "gumroad": "https://{}.gumroad.com/",+ "fantia": "https://fantia.jp/fanclubs/{}",+ "itchio": "https://{}.itch.io/",+ "kofi": "https://ko-fi.com/{}",+ "twitter": "https://x.com/{}",+ "pixiv": "https://www.pixiv.net/users/{}",+ "deviantart": "https://www.deviantart.com/{}",+ "instagram": "https://www.instagram.com/{}",+ "bsky": "https://bsky.app/profile/{}",+}++#: 自己就是正版渠道的关注来源:来源地址原样就是那个账号的主页。+_OFFICIAL_PROVIDERS = ("fanbox", "subscribestar", "patreon")++#: 归档站上 `服务/用户` 还原成原站账号。只收核实过形状的:FANBOX 归档的数字 id 是+#: pixiv 用户 id(`web_follow._official_avatar_url` 靠它取官方头像),Patreon 的是用户 id,+#: OnlyFans 的是用户名。Gumroad、Fantia 的归档 id 形状未核实,不还原。+_ARCHIVE_ACCOUNTS = {+ "fanbox": ("pixiv", "https://www.pixiv.net/users/{}", str.isdigit),+ "patreon": ("patreon", "https://www.patreon.com/user?u={}", str.isdigit),+ "onlyfans": ("onlyfans", "https://onlyfans.com/{}",+ lambda value: value.replace("_", "").replace(".", "").isalnum()),+}+++@dataclass+class Landing:+ """一位关注作者这一轮怎么处理。`action` 是 `create`、`join`、`hold` 或 `skip`。"""+ key: str+ name: str+ action: str+ source_ids: tuple[int, ...]+ links: tuple[dict, ...] = ()+ aliases: tuple[str, ...] = ()+ entity_id: int | None = None+ reason: str = ""+ providers: tuple[str, ...] = ()+++def source_links(row) -> list[dict]:+ """一条关注来源能证明的作者账号:`service`、`url` 与证据说明。"""+ from .follow_sources import KemonoConnector+ from .web_follow import trusted_profile_links++ provider = str(row["provider"] or "")+ found: list[dict] = []+ if provider in _OFFICIAL_PROVIDERS and row["url"]:+ found.append({"service": provider, "url": str(row["url"]),+ "evidence": f"{provider} 关注来源本身"})+ if provider in KemonoConnector.HOSTS:+ service, _, user = str(row["ref"] or "").partition("/")+ mapped = _ARCHIVE_ACCOUNTS.get(service)+ if mapped and user and mapped[2](user):+ found.append({"service": mapped[0], "url": mapped[1].format(user),+ "evidence": f"{provider} 归档的原站账号 {service}/{user}"})+ for link in trusted_profile_links(row):+ service = str(link.get("service") or "")+ handle = str(link.get("handle") or "").strip()+ if service not in CHANNELS or not handle:+ continue+ template = _PROFILE_URLS.get(service)+ if template:+ url = template.format(handle)+ else:+ # SubscribeStar 有 `.adult` 与 `.com` 两个主机,按名片上那个拼。+ host = (urlsplit(str(link.get("url") or "")).hostname or "").removeprefix("www.")+ if not host:+ continue+ url = f"https://{host}/{handle}"+ found.append({"service": service, "url": url,+ "evidence": f"{provider} 名片 {service}/{handle}"})+ return found+++def _group_links(rows) -> tuple[dict, ...]:+ """一组来源的链接去重。同一个 Patreon 账号既有手柄地址又有 `user?u=` 时只留手柄那条。"""+ found: dict[str, dict] = {}+ for row in rows:+ for link in source_links(row):+ found.setdefault(link["url"].casefold().rstrip("/"), link)+ by_handle = {link["service"] for link in found.values() if "user?u=" not in link["url"]}+ return tuple(link for link in found.values()+ if not ("user?u=" in link["url"] and link["service"] in by_handle))+++def _name_held(connection: sqlite3.Connection, normalized: str) -> int | None:+ """账本里已经叫这个名字(正名或别名)的创作者。"""+ row = connection.execute(+ "SELECT id FROM entity WHERE kind='creator' AND (normalized_name=? OR id IN"+ " (SELECT entity_id FROM entity_alias WHERE normalized_alias=?)) ORDER BY id LIMIT 1",+ (normalized, normalized)).fetchone()+ return int(row[0]) if row else None+++def plan(connection: sqlite3.Connection) -> list[Landing]:+ """这一轮每一位还没建档的关注作者怎么处理。只读,同样的账本给同样的结论。"""+ from .follow_store import FollowStore+ from .web_follow import _author_display_name, author_name, name_key++ store = FollowStore(lambda: connection)+ rows = store.sources()+ alias_map, alias_groups = store.author_aliases()+ canonical = {f"name:{group['canonical_key']}": str(group["canonical_name"] or "")+ for group in alias_groups}+ alias_names = {f"name:{group['canonical_key']}": [alias["name"] for alias in group["aliases"]]+ for group in alias_groups}+ joined: dict[str, set[int]] = {}+ pending: dict[str, list] = {}+ for row in rows:+ key = name_key(row, alias_map)+ if row["entity_id"]:+ joined.setdefault(key, set()).add(int(row["entity_id"]))+ elif key.startswith("name:"):+ pending.setdefault(key, []).append(row)+ landings: list[Landing] = []+ for key, group in sorted(pending.items()):+ ids = tuple(int(row["id"]) for row in group)+ providers = tuple(dict.fromkeys(str(row["provider"]) for row in group))+ links = _group_links(group)+ owners = joined.get(key, set())+ if len(owners) == 1:+ entity_id = next(iter(owners))+ landings.append(Landing(key, "", "join", ids, links, entity_id=entity_id,+ providers=providers,+ reason="同一名字键的来源已建档"))+ continue+ name = canonicalize_entity_name("creator", author_name(group, key, canonical))+ if len(owners) > 1:+ landings.append(Landing(key, name, "hold", ids, providers=providers,+ reason="同一名字键的来源分属几个实体"))+ continue+ if not name:+ landings.append(Landing(key, author_name(group, key, canonical), "skip", ids,+ providers=providers, reason="名字是平台、目录或转载站"))+ continue+ held = _name_held(connection, normalize_entity_name(name))+ if held is not None:+ landings.append(Landing(key, name, "hold", ids, links, entity_id=held,+ providers=providers, reason="账本里已有同名创作者"))+ continue+ normalized = normalize_entity_name(name)+ spellings = [_author_display_name(row) for row in group] + alias_names.get(key, [])+ aliases = tuple(dict.fromkeys(+ spelling for spelling in spellings+ if spelling and normalize_entity_name(spelling) not in ("", normalized)+ and _name_held(connection, normalize_entity_name(spelling)) is None))+ landings.append(Landing(key, name, "create", ids, links, aliases,+ providers=providers))+ # 两组归一成同一个名字:谁先谁后都是猜,两组都留给人。+ counts: dict[str, int] = {}+ for landing in landings:+ if landing.action == "create":+ counts[normalize_entity_name(landing.name)] = counts.get(+ normalize_entity_name(landing.name), 0) + 1+ for landing in landings:+ if landing.action == "create" and counts[normalize_entity_name(landing.name)] > 1:+ landing.action, landing.links, landing.aliases = "hold", (), ()+ landing.reason = "几组关注作者归一成同一个名字"+ return landings+++def apply(connection: sqlite3.Connection, landings: list[Landing], *, batch: str,+ source: str = SOURCE, now: str | None = None) -> dict:+ """把 `create` 与 `join` 两类写进账本。调用方给写事务;重跑不会多出行。"""+ stamp = now or datetime.now(timezone.utc).isoformat()+ created = bound = linked = aliased = 0+ for landing in landings:+ if landing.action not in ("create", "join"):+ continue+ entity_id = landing.entity_id+ if landing.action == "create":+ normalized = normalize_entity_name(landing.name)+ if _name_held(connection, normalized) is not None:+ continue+ entity_id = int(connection.execute(+ "INSERT INTO entity(kind,canonical_name,normalized_name,metadata_json,"+ "created_at,updated_at) VALUES('creator',?,?,?,?,?)",+ (landing.name, normalized,+ json.dumps({"source": source, "batch": batch, "author_key": landing.key},+ ensure_ascii=False), stamp, stamp)).lastrowid)+ created += 1+ bound += connection.execute(+ f"UPDATE follow_source SET entity_id=?,updated_at=? WHERE entity_id IS NULL"+ f" AND id IN ({','.join('?' * len(landing.source_ids))})",+ (entity_id, stamp, *landing.source_ids)).rowcount+ for link in landing.links:+ kind, label = CHANNELS[link["service"]]+ metadata = {"source": source, "batch": batch, "verdict": "关注来源",+ "evidence": link["evidence"], "installed_at": stamp}+ linked += connection.execute(+ "INSERT OR IGNORE INTO entity_link(entity_id,link_kind,label,url,hostname,"+ "is_sensitive,metadata_json,created_at,updated_at) VALUES(?,?,?,?,?,0,?,?,?)",+ (entity_id, kind, label, link["url"], urlsplit(link["url"]).hostname or "",+ json.dumps(metadata, ensure_ascii=False), stamp, stamp)).rowcount+ for alias in landing.aliases:+ aliased += connection.execute(+ "INSERT OR IGNORE INTO entity_alias(entity_id,alias,normalized_alias,source,"+ "confidence) VALUES(?,?,?,?,1.0)",+ (entity_id, alias, normalize_entity_name(alias), batch)).rowcount+ return {"created": created, "bound": bound, "links": linked, "aliases": aliased}+++#: 人在资料页上点「是同一个人」写下的归属。人的判断不进自动撤回。+CONFIRM_SOURCE = "user:follow-creator"+++def held_for(connection: sqlite3.Connection, entity_id: int) -> list[Landing]:+ """因为和这位创作者同名而等人的关注作者。"""+ return [landing for landing in plan(connection)+ if landing.action == "hold" and landing.entity_id == int(entity_id)]+++def confirm(connection: sqlite3.Connection, entity_id: int, key: str) -> dict:+ """人确认「关注里那位就是这位创作者」:绑上那一组来源,补上它们证明的账号。++ 只认此刻仍在等这位的那一组:页面停在旧状态时点下去,那组可能已经绑走或改了名。+ """+ landing = next((item for item in held_for(connection, entity_id) if item.key == key), None)+ if landing is None:+ raise ValueError("这组关注作者已经不在等确认了,刷新后再看")+ landing.action = "join"+ stamp = datetime.now(timezone.utc).isoformat()+ return apply(connection, [landing], batch=f"{CONFIRM_SOURCE}@{stamp}",+ source=CONFIRM_SOURCE, now=stamp)+++def summarize(landings: list[Landing]) -> dict:+ """活动页上那一行:建了几位、并进几组,等人的那几位写名字和原因。"""+ held = [f"{landing.name}({landing.reason})" for landing in landings+ if landing.action == "hold"]+ return {"create": sum(landing.action == "create" for landing in landings),+ "join": sum(landing.action == "join" for landing in landings),+ "hold": held[:12], "held": len(held),+ "skip": sum(landing.action == "skip" for landing in landings)}+++def declare(connection: sqlite3.Connection) -> list[dict]:+ """关注检查结算时声明的后继:有要建档或并入的作者就派一条,没有就不派。++ 一轮只派一条、键固定:后继自己把整张表看一遍,排着的那条没跑完时再声明也只是去重。+ """+ if not any(landing.action in ("create", "join") for landing in plan(connection)):+ return []+ return [{"key": f"{TASK_KEY}:all", "task_key": TASK_KEY, "label": TASK_LABEL}]+++def run(contract, key: str, handle) -> dict:+ """跑一轮建档。幂等:已绑的来源不再出现在计划里,重跑只是一张空计划。"""+ if key != f"{TASK_KEY}:all":+ raise ValueError(f"认不出这条关注作者建档后继:{key}")+ batch = f"{SOURCE}@{getattr(handle, 'run_id', None) or time.strftime('%Y%m%dT%H%M%S')}"+ with contract.database.write_transaction() as connection:+ landings = plan(connection)+ written = apply(connection, landings, batch=batch)+ if written["created"] or written["bound"]:+ contract.cache_bust()+ return {**summarize(landings), **written, "batch": batch}+++def _referenced(connection: sqlite3.Connection, entity_id: int) -> bool:+ """还有没有别的行指着这条实体。外键清单从 schema 读,新表不用回来改这里。"""+ for (table,) in connection.execute("SELECT name FROM sqlite_schema WHERE type='table'"):+ for foreign in connection.execute(f'PRAGMA foreign_key_list("{table}")'):+ if foreign[2] == "entity" and connection.execute(+ f'SELECT 1 FROM "{table}" WHERE "{foreign[3]}"=? LIMIT 1',+ (entity_id,)).fetchone():+ return True+ return False+++def planned_revert(connection: sqlite3.Connection, source: str, batch: str) -> list[dict]:+ """这条后继建下的实体。链接与别名由撤回脚本按 `source`/`batch` 另认。"""+ if source != SOURCE:+ return []+ found = []+ for row in connection.execute(+ "SELECT id,canonical_name,metadata_json FROM entity WHERE kind='creator'"+ " AND metadata_json LIKE ?", (f"%{SOURCE}%",)):+ try:+ metadata = json.loads(row[2] or "{}")+ except ValueError:+ continue+ if metadata.get("source") == SOURCE and (not batch or metadata.get("batch") == batch):+ sources = connection.execute(+ "SELECT count(*) FROM follow_source WHERE entity_id=?", (row[0],)).fetchone()[0]+ found.append({"entity_id": int(row[0]), "name": str(row[1]),+ "batch": str(metadata.get("batch") or ""), "sources": int(sources)})+ return found+++def revert(connection: sqlite3.Connection, rows: list[dict]) -> dict:+ """解绑来源,再删没有别的引用的实体。链接与别名要先由调用方删掉。++ 人后来给这位挂上的作品、资料或链接都算引用:那条实体就留着,只解绑来源。+ """+ unbound = removed = 0+ for row in rows:+ unbound += connection.execute(+ "UPDATE follow_source SET entity_id=NULL WHERE entity_id=?",+ (row["entity_id"],)).rowcount+ if not _referenced(connection, row["entity_id"]):+ removed += connection.execute(+ "DELETE FROM entity WHERE id=?", (row["entity_id"],)).rowcount+ return {"unbound": unbound, "removed": removed}+++#: 写账本:建实体、绑来源、登记链接都在一个写事务里,走写账本那一条串行通道。+TYPE = register(FollowupType(task_key=TASK_KEY, label=TASK_LABEL,+ writes_ledger=True, run=run))diff --git a/src/peach/follow_discovery.py b/src/peach/follow_discovery.pyindex 36dc3081a..89ee2e040 100644--- a/src/peach/follow_discovery.py+++ b/src/peach/follow_discovery.py@@ -484,8 +484,9 @@ MAX_PROFILE_THREADS = 2#: 名片手柄最多拿几个去其余来源再查一遍。每个手柄都要把名字类来源重问一轮。MAX_PROFILE_HANDLES = 4#: 名片上不当作者别名的服务。论坛账号名常常是搬运工自己的账号,-#: 而 pixiv 的身份是一串数字,当别名只会在列表里多出一个数字「作者」。-PROFILE_ALIAS_SKIP_SERVICES = frozenset({"pixiv", "f95zone", "simpcity"})+#: 而 pixiv、Fantia 的身份是一串数字,当别名只会在列表里多出一个数字「作者」;+#: Bluesky 的手柄连着域名,不是名字。+PROFILE_ALIAS_SKIP_SERVICES = frozenset({"pixiv", "fantia", "bsky", "f95zone", "simpcity"})#: 名片手柄会拿去再查一遍的来源:按名字、id 或标签查的那几家。_HANDLE_SEARCH_PROVIDERS = frozenset({"kemono", "coomer", "pawchive", "rule34video","rule34xxx", "simpcity"})diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 37427ea2c..fd5c460b1 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -2033,6 +2033,7 @@ _PROFILE_LINK_HOSTS = {"deviantart.com": "deviantart","instagram.com": "instagram","gumroad.com": "gumroad",+ "ko-fi.com": "kofi",}#: 这些站点的第一段路径是功能页而不是名字,取到了也不是手柄。_PROFILE_PATH_STOPWORDS = frozenset({@@ -2042,6 +2043,8 @@ _PROFILE_PATH_STOPWORDS = frozenset({_PROFILE_HANDLE_RE = re.compile(r"^[A-Za-z0-9._-]{2,64}$")_PIXIV_USER_RE = re.compile(r"(?:^|/)users/(\d{1,20})(?:$|/)")_XENFORO_MEMBER_RE = re.compile(r"^members/([^/.]+)\.(\d{1,20})/?$")+_BSKY_PROFILE_RE = re.compile(r"^profile/([^/]+)$")+_FANTIA_FANCLUB_RE = re.compile(r"^fanclubs/(\d{1,20})(?:$|/)")def profile_link_identity(url: str, *, forum_host: str = "") -> tuple[str, str] | None:@@ -2070,6 +2073,16 @@ def profile_link_identity(url: str, *, forum_host: str = "") -> tuple[str, str]if host == "pixiv.net":matched = _PIXIV_USER_RE.search(path)return ("pixiv", matched.group(1)) if matched else None+ if host.endswith(".itch.io"):+ handle = host.removesuffix(".itch.io")+ return ("itchio", handle) if _PROFILE_HANDLE_RE.match(handle) else None+ if host == "bsky.app":+ matched = _BSKY_PROFILE_RE.match(path)+ handle = matched.group(1) if matched else ""+ return ("bsky", handle) if _PROFILE_HANDLE_RE.match(handle) else None+ if host == "fantia.jp":+ matched = _FANTIA_FANCLUB_RE.match(path)+ return ("fantia", matched.group(1)) if matched else Noneif forum_host and host == forum_host.lower().removeprefix("www."):matched = _XENFORO_MEMBER_RE.match(path)return (forum_host.split(".")[0], matched.group(1)) if matched else Nonediff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex 024db8742..836d42edd 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -14,7 +14,8 @@ import timefrom urllib.parse import urlsplit-from . import company_profiles, entry_links, feeds, link_status, performer_header, web_feeds+from . import (company_profiles, entry_links, feeds, link_status, performer_header, web_feeds,+ web_follow)from .catalog_rules import (LENGTH_TAGS, dir_expr, photo_set_title, solo_performer_clause, tag_cat)from .entities import normalize_entity_name, resolve_entity, rewrite_flat_projectionfrom .social_links import ARCHIVE_HOSTS, is_archive@@ -207,6 +208,8 @@ def q_entity(contract: WebContract, args):d.update(performer_header.header(c, d["id"], d["canonical_name"]))elif kind in {'studio', 'agency'}:d['company_profile'] = company_profiles.public_profile(metadata)+ # 创作者在关注里的那一面(ADR-0096):绑在名下的来源和同名等确认的那几组。+ d["follow"] = web_follow.entity_follow(contract, c, d["id"]) if kind == "creator" else Nonescope = scope_predicate(kind, "ae.entity_id")count, rep = c.execute("SELECT count(DISTINCT " + video_work_key(contract) + "),"diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 0771285b6..297b7abf7 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -11,6 +11,7 @@ import htmlimport jsonimport osimport re+import sqlite3import timeimport threadingimport uuid@@ -18,7 +19,7 @@ import urllib.parsefrom pathlib import Path-from . import avatar_face, follow_assets, follow_providers, wants+from . import avatar_face, follow_assets, follow_creators, follow_providers, wantsfrom .follow import FollowSourceErrorfrom .follow_faces import annotate_groupfrom .follow_check import plan_check, run_check@@ -1131,6 +1132,14 @@ def author_key(row, aliases: dict[str, str] | None = None) -> str:entity = row["entity_id"]if entity:return f"entity:{entity}"+ return name_key(row, aliases)+++def name_key(row, aliases: dict[str, str] | None = None) -> str:+ """这条来源不看实体绑定时归到哪个作者:`name:` 加归一化的名字,名字都没有就按来源。++ 关注作者建档(ADR-0096)靠它认出「新加的这条来源和已经建档的那几条本来就是同一组」。+ """recorded = str(_source_metadata(row).get("author_key") or "").strip()if recorded:normalized = recorded@@ -1151,6 +1160,8 @@ def group_authors(source_rows, aliases: dict[str, str] | None = None,与 `author_key` 同一口径:来源标签、来源记下的作者键、别名表里指向同一人的键。"""keys = {int(row["id"]): author_key(row, aliases) for row in source_rows}+ # 别名表写的是名字键;绑了实体的那组键换成了 `entity:`,别名要跟着找到它。+ grouped_as = {name_key(row, aliases): keys[int(row["id"])] for row in source_rows}names: dict[str, set[str]] = {}for row in source_rows:spellings = names.setdefault(keys[int(row["id"])], set())@@ -1160,8 +1171,9 @@ def group_authors(source_rows, aliases: dict[str, str] | None = None,if raw:spellings.update((raw, (aliases or {}).get(raw, raw)))for alias, canonical in (aliases or {}).items():- if f"name:{canonical}" in names:- names[f"name:{canonical}"].add(alias)+ key = grouped_as.get(f"name:{canonical}")+ if key in names:+ names[key].add(alias)return {source_id: (key, frozenset(names.get(key, ()))) for source_id, key in keys.items()}@@ -1297,6 +1309,25 @@ def _official_profile_identities(metadata: dict) -> str:return ",".join(usable[:MAX_PROFILE_IDENTITIES])+def trusted_profile_links(row) -> list[dict]:+ """这条来源名片里能当作者本人账号的那几条。++ F95 的名片取自开楼正文,是作者自己贴的。booru 的 `official_links` 是作品出处,+ 合作作品会指向另一位作者,所以只留手柄就是这条来源作者名的那几条。+ """+ metadata = _source_metadata(row)+ raw = metadata.get("official_links")+ links = [link for link in (raw if isinstance(raw, list) else ()) if isinstance(link, dict)]+ if str(row["provider"] or "") == "f95zone":+ return links+ expected = {+ normalized_author_name(str(row["ref"] or "")),+ normalized_author_name(str(metadata.get("author_key") or "")),+ }+ return [link for link in links+ if normalized_author_name(str(link.get("handle") or "")) in expected]++def _official_avatar_url(row) -> str | None:"""Local resolver for an avatar from the creator's official profile.@@ -1313,18 +1344,7 @@ def _official_avatar_url(row) -> str | None:return Nonereturn "/follow-avatar?" + urllib.parse.urlencode({"service": service, "id": user})- metadata = _source_metadata(row)- if provider != "f95zone":- expected = {- normalized_author_name(str(row["ref"] or "")),- normalized_author_name(str(metadata.get("author_key") or "")),- }- links = metadata.get("official_links")- metadata = {**metadata, "official_links": [- link for link in (links if isinstance(links, list) else ())- if isinstance(link, dict)- and normalized_author_name(str(link.get("handle") or "")) in expected- ]}+ metadata = {**_source_metadata(row), "official_links": trusted_profile_links(row)}identity = _official_fanbox_identity(metadata)if identity:return "/follow-avatar?" + urllib.parse.urlencode(@@ -1498,6 +1518,23 @@ def q_follow_tags(contract, args) -> dict:"categories": categories}+def author_name(rows, key: str, canonical: dict[str, str]) -> str:+ """一位作者(同一作者键下的几条来源)叫什么。++ 次序跟关注页那一份分组标题一致:实体名最可靠,其次是别名表定的规范名,再次是有+ 官方主页那条来源的写法;都没有才在各条标签里选大写最多的那个——+ `LazyProcrastinator` 比 `lazyprocrastinator` 更像作者自己写的名字。+ """+ entity = next((str(row["entity_name"]) for row in rows+ if row["entity_id"] and row["entity_name"]), "")+ labels = [(name, bool(_official_avatar_url(row))) for row in rows+ if (name := _author_display_name(row))]+ official = next((name for name, has_official in labels if has_official), "")+ best = max((name for name, _ in labels),+ key=lambda text: sum(ch.isupper() for ch in text), default="")+ return entity or canonical.get(key) or official or best or key++def q_follow_authors(contract, args) -> dict:"""在线作者索引,供艺人页那一档「在线」列出关注来源里的人。@@ -1543,36 +1580,31 @@ def q_follow_authors(contract, args) -> dict:if not key or key not in counts:continueentry = grouped.setdefault(key, {"k": "", "key": key, "n": counts[key],- "avatar": "", "avatar_fallback": "",- "providers": [], "_entity": "",- "_official": "", "_labels": []})- if row["entity_id"] and row["entity_name"]:- entry["_entity"] = str(row["entity_name"])- name = _author_display_name(row)+ "entity_id": None, "avatar": "",+ "avatar_fallback": "", "providers": [],+ "_rows": []})+ entry["_rows"].append(row)+ if row["entity_id"]:+ entry["entity_id"] = int(row["entity_id"])official = _official_avatar_url(row)mirror = _avatar_url(row["provider"], row["ref"])- if official:- if not entry["avatar"]:- entry["avatar"] = official- if name and not entry["_official"]:- entry["_official"] = name+ if official and not entry["avatar"]:+ entry["avatar"] = officialif mirror and not entry["avatar_fallback"]:entry["avatar_fallback"] = mirror- if name:- entry["_labels"].append(name)provider = str(row["provider"] or "")if provider and provider not in entry["providers"]:entry["providers"].append(provider)+ # 和本地某位创作者同名、等人确认的那几位:格子上标出来,点开去那位的资料页确认。+ held = {landing.key: landing.entity_id for landing in follow_creators.plan(connection)+ if landing.action == "hold" and landing.entity_id is not None}+ held_names = {int(row[0]): str(row[1]) for row in connection.execute(+ f"SELECT id,canonical_name FROM entity WHERE id IN ({','.join('?' * len(held))})",+ tuple(held.values()))} if held else {}rows = []for key, entry in grouped.items():- # 挑名字的次序跟关注页那一份分组标题一致:实体名最可靠,其次是别名表定的- # 规范名,再次是有官方主页那条来源的写法;都没有才在各条标签里选大写最多的- # 那个——`LazyProcrastinator` 比 `lazyprocrastinator` 更像作者自己写的名字。- labels, entity, official = (entry.pop("_labels"), entry.pop("_entity"),- entry.pop("_official"))- best = max(labels, key=lambda text: sum(ch.isupper() for ch in text),- default="")- entry["k"] = entity or canonical.get(key) or official or best or key+ entry["held_by"] = held_names.get(held.get(key, 0), "")+ entry["k"] = author_name(entry.pop("_rows"), key, canonical)if entry["avatar_fallback"] == entry["avatar"]:entry["avatar_fallback"] = ""if not entry["avatar"]:@@ -2277,7 +2309,14 @@ def _run_follow_check(contract, body, job_id=None) -> dict:result["author"] = _author_display_name(row)results.append(result)progress()- return {"ok": True, "checked": len(results), "results": results}+ # 还没建档的关注作者交给建档后继(ADR-0096)。后继由结果声明、调度端统一派+ # (ADR-0040);这里判不出来只是这一轮不派,检查本身的结论不受影响。+ try:+ with contract.database.read_connection() as connection:+ followups = follow_creators.declare(connection)+ except sqlite3.Error:+ followups = []+ return {"ok": True, "checked": len(results), "results": results, "followups": followups}def q_follow_schedule(contract, _args) -> dict:@@ -2435,6 +2474,55 @@ def w_follow_source(contract, body) -> dict:"author_aliases_learned": learned}+def _author_updates(store, rows) -> int:+ """几条来源一共多少项更新,与关注页作者读数同一个口径:启用来源、去掉排除项的条目数。"""+ return sum(1 for row in rows if row["enabled"]+ for item in store.items(source_id=int(row["id"]), limit=_ALL_ITEMS)+ if not _excluded_item(item))+++def entity_follow(contract, connection, entity_id: int) -> dict | None:+ """创作者资料页上的关注那一块(ADR-0096):绑在他名下的来源,和同名等确认的那几组。++ 都没有就是 `None`,页面不画这一块。`key` 是关注页的作者键,页面拿它去关注页筛这一位。+ """+ store = _store(contract, connection)+ sources = store.sources()+ bound = [row for row in sources if row["entity_id"] == int(entity_id)]+ held = follow_creators.held_for(connection, entity_id)+ if not bound and not held:+ return None+ by_id = {int(row["id"]): row for row in sources}+ official = next((url for row in bound if (url := _official_avatar_url(row))), "")+ archive = next((url for row in bound if (url := _avatar_url(row["provider"], row["ref"]))), "")+ return {+ "key": f"entity:{int(entity_id)}" if bound else "",+ "n": _author_updates(store, bound),+ "providers": list(dict.fromkeys(+ PROVIDER_LABELS.get(row["provider"], row["provider"]) for row in bound)),+ "avatar": official or archive,+ "avatar_fallback": archive if official else "",+ "held": [{+ "key": landing.key, "name": landing.name,+ "providers": [PROVIDER_LABELS.get(provider, provider)+ for provider in landing.providers],+ "n": _author_updates(store, [by_id[source_id] for source_id in landing.source_ids]),+ "links": [link["url"] for link in landing.links],+ } for landing in held],+ }+++def w_follow_creator(contract, body) -> dict:+ """资料页上「是同一个人」:把同名等确认的那组关注作者绑到这位创作者名下。"""+ entity_id, key = body.get("entity_id"), str(body.get("key") or "")+ if type(entity_id) is not int or not key.startswith("name:"):+ raise ValueError("entity_id 与 key 都要给")+ with contract.database.write_transaction() as connection:+ written = follow_creators.confirm(connection, entity_id, key)+ contract.cache_bust()+ return {"ok": True, **written}++def w_follow_author_alias(contract, body) -> dict:"""Add or remove a user-confirmed cross-platform follow-author alias."""action = str(body.get("action") or "add")diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 248d34c3d..c539535be 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -68,6 +68,7 @@ from .web_follow import (w_follow_activity,w_follow_author_alias,w_follow_check,+ w_follow_creator,w_follow_credential,w_follow_image_dims,w_follow_media_hide,@@ -381,6 +382,7 @@ POST_HANDLERS = {"/api/follow/schedule": w_follow_schedule,"/api/follow/source": w_follow_source,"/api/follow/author-alias": w_follow_author_alias,+ "/api/follow/creator": w_follow_creator,"/api/follow/resolve": w_follow_resolve,"/api/follow/credential": w_follow_credential,"/api/follow/status": w_follow_status,diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 2196e49d5..c4b345c5c 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -176,6 +176,7 @@ class WebContract:#: 不认识任何一种后继,登记表在 `followups.REGISTRY` 里。from . import avatar_followup # noqa: F401 登记补头像后继from . import feed_followup # noqa: F401 登记取新作资料后继+ from . import follow_creators # noqa: F401 登记关注作者建档后继from . import performer_alias_followup # noqa: F401 登记补女优别名后继from . import performer_profile_followup # noqa: F401 登记补女优资料后继from . import sample_followup # noqa: F401 登记补番号样张后继diff --git a/tests/test_follow_creators.py b/tests/test_follow_creators.pynew file mode 100644index 000000000..f16ca688c--- /dev/null+++ b/tests/test_follow_creators.py@@ -0,0 +1,207 @@+"""关注作者建档(ADR-0096):建谁、等谁、并进谁,链接从哪来,认人与按批撤回。"""+import contextlib+import io+import json+import sqlite3+import tempfile+import unittest+from datetime import datetime, timezone+from pathlib import Path++from peach import follow_creators, web_follow+from peach.follow_sources import FollowCandidate, SourceFetch+from peach.follow_store import FollowStore+from peach.web_contract import WebContract, dispatch_api_get, dispatch_api_post+from peach.web_entity import q_entity+from peach.web_follow import author_key+from scripts import revert_auto_landing+from support.ledger import fresh_ledger++MOMENT = datetime(2026, 9, 1, tzinfo=timezone.utc)+++class FollowCreatorTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name).resolve()+ self.db = fresh_ledger(self.root)+ self.contract = WebContract(+ self.db, follow_sources_root=self.root / "sources",+ follow_secrets_root=self.root / "secrets", follow_shared_root=self.root / "shared",+ candidate_root=self.root / "generated", follow_state_root=self.root / "state")++ def source(self, provider, ref, label, metadata=None, items=1):+ with self.contract.database.write_transaction() as connection:+ store = FollowStore(lambda: connection, sources_root=self.contract.follow_sources_root)+ source_id = store.register(provider=provider, ref=ref, label=label,+ url=f"https://{provider}.test/{ref}", metadata=metadata,+ moment=MOMENT)+ candidates = tuple(FollowCandidate(+ provider=provider, external_id=f"{source_id}-{at}", title=f"{label} {source_id}-{at}",+ url=f"https://{provider}.test/{ref}/{at}") for at in range(items))+ store.record(source_id, SourceFetch(+ provider=provider, ref=ref, request_url=f"https://{provider}.test/{ref}",+ semantics="work", candidates=candidates, raw_body=b"<html/>"), moment=MOMENT)+ return source_id++ def creator(self, name):+ with self.contract.database.write_transaction() as connection:+ return int(connection.execute(+ "INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES('creator',?,?,?,?)", (name, name.casefold(), "2026", "2026")).lastrowid)++ def plan(self):+ with self.contract.database.read_connection() as connection:+ return {landing.key: landing for landing in follow_creators.plan(connection)}++ def run_followup(self):+ return follow_creators.run(self.contract, "follow-creator:all", None)++ def read(self, sql, *args):+ with self.contract.database.read_connection() as connection:+ return [tuple(row) for row in connection.execute(sql, args)]++ def jul3d(self):+ self.source("kemono", "fanbox/12345", "Jul3D", items=2)+ self.source("kemono", "patreon/777", "Jul3D")+ self.source("f95zone", "123", "Jul3D Collection", metadata={+ "author_key": "jul3d",+ "official_links": [+ {"service": "patreon", "handle": "jul3d", "url": "https://www.patreon.com/jul3d/posts"},+ {"service": "twitter", "handle": "Jul3D_", "url": "http://twitter.com/Jul3D_?s=20"},+ {"service": "discord", "handle": "abc", "url": "https://discord.gg/abc"},+ ]})++ def test_a_new_author_becomes_a_creator_with_its_channels_and_socials(self):+ self.jul3d()+ landing = self.plan()["name:jul3d"]+ self.assertEqual((landing.action, landing.name), ("create", "Jul3D"))+ self.assertEqual(sorted(link["url"] for link in landing.links), [+ "https://www.patreon.com/jul3d", "https://www.pixiv.net/users/12345", "https://x.com/Jul3D_"])++ result = self.run_followup()+ self.assertEqual((result["created"], result["bound"], result["links"]), (1, 3, 3))+ entity_id, metadata = self.read(+ "SELECT id,metadata_json FROM entity WHERE canonical_name='Jul3D'")[0]+ self.assertEqual(json.loads(metadata)["source"], follow_creators.SOURCE)+ self.assertEqual(sorted(self.read("SELECT link_kind,label FROM entity_link WHERE entity_id=?", entity_id)),+ [("official", "Patreon"), ("social", "X"), ("social", "pixiv")])+ self.assertEqual({row[0] for row in self.read("SELECT entity_id FROM follow_source")}, {entity_id})+ # 重跑是一张空计划。+ self.assertEqual(self.run_followup()["created"], 0)++ authors = dispatch_api_get(self.contract, "/api/follow/authors", {})["items"]+ self.assertEqual([(row["k"], row["key"], row["entity_id"]) for row in authors],+ [("Jul3D", f"entity:{entity_id}", entity_id)])+ # 资料页的读数与名册那一格数的是同一批更新。+ page = q_entity(self.contract, {"kind": "creator", "name": "Jul3D"})+ self.assertEqual((page["follow"]["key"], page["follow"]["n"], page["follow"]["held"]),+ (f"entity:{entity_id}", authors[0]["n"], []))++ def test_a_later_source_under_the_same_name_key_joins_the_existing_creator(self):+ self.jul3d()+ self.run_followup()+ later = self.source("kemono", "fanbox/99999", "Jul3D")+ entity_id = self.read("SELECT id FROM entity WHERE canonical_name='Jul3D'")[0][0]+ landing = self.plan()["name:jul3d"]+ self.assertEqual((landing.action, landing.entity_id), ("join", entity_id))+ with self.contract.database.read_connection() as connection:+ self.assertEqual(follow_creators.declare(connection)[0]["task_key"], "follow-creator")+ self.run_followup()+ self.assertEqual(self.read("SELECT entity_id FROM follow_source WHERE id=?", later), [(entity_id,)])+ self.assertIn(("https://www.pixiv.net/users/99999",),+ self.read("SELECT url FROM entity_link WHERE entity_id=?", entity_id))++ def test_a_same_named_creator_is_only_offered_until_the_user_confirms(self):+ held_id = self.creator("InitialA")+ source_id = self.source("kemono", "fanbox/4242", "InitialA", items=3)+ landing = self.plan()["name:initiala"]+ self.assertEqual((landing.action, landing.entity_id), ("hold", held_id))+ with self.contract.database.read_connection() as connection:+ self.assertEqual(follow_creators.declare(connection), [])+ self.run_followup()+ self.assertEqual(self.read("SELECT entity_id FROM follow_source"), [(None,)])++ authors = dispatch_api_get(self.contract, "/api/follow/authors", {})["items"]+ self.assertEqual([(row["key"], row["held_by"]) for row in authors], [("name:initiala", "InitialA")])+ follow = q_entity(self.contract, {"kind": "creator", "name": "InitialA"})["follow"]+ self.assertEqual(follow["key"], "")+ self.assertEqual([(group["key"], group["n"]) for group in follow["held"]], [("name:initiala", 3)])++ written = dispatch_api_post(self.contract, "/api/follow/creator",+ {"entity_id": held_id, "key": "name:initiala"})+ self.assertEqual((written["bound"], written["links"]), (1, 1))+ self.assertEqual(self.read("SELECT entity_id FROM follow_source WHERE id=?", source_id), [(held_id,)])+ link_metadata = json.loads(self.read("SELECT metadata_json FROM entity_link")[0][0])+ self.assertEqual(link_metadata["source"], follow_creators.CONFIRM_SOURCE)+ follow = q_entity(self.contract, {"kind": "creator", "name": "InitialA"})["follow"]+ self.assertEqual((follow["key"], follow["held"]), (f"entity:{held_id}", []))+ with self.assertRaises(ValueError):+ dispatch_api_post(self.contract, "/api/follow/creator", {"entity_id": held_id, "key": "name:initiala"})++ def test_revert_unbinds_the_batch_and_keeps_creators_people_rely_on(self):+ self.jul3d()+ held_id = self.creator("InitialA")+ self.source("kemono", "fanbox/4242", "InitialA")+ self.run_followup()+ dispatch_api_post(self.contract, "/api/follow/creator", {"entity_id": held_id, "key": "name:initiala"})+ with contextlib.redirect_stdout(io.StringIO()):+ revert_auto_landing.main(["--db", str(self.db), "--apply", "--backup", str(self.root / "backup.db"),+ "--source", follow_creators.SOURCE])+ self.assertEqual(self.read("SELECT canonical_name FROM entity WHERE kind='creator'"), [("InitialA",)])+ # 人认过的那一组不归自动撤回。+ self.assertEqual(sorted(row[0] or 0 for row in self.read("SELECT entity_id FROM follow_source")),+ [0, 0, 0, held_id])+ self.assertEqual(len(self.read("SELECT id FROM entity_link")), 1)+ with contextlib.closing(sqlite3.connect(self.db)) as connection:+ self.assertEqual(connection.execute("PRAGMA foreign_key_check").fetchall(), [])++ def test_the_follow_check_declares_the_followup_only_while_someone_is_waiting(self):+ self.jul3d()+ result = web_follow._run_follow_check(self.contract, {"sources": []})+ self.assertEqual([row["key"] for row in result["followups"]], ["follow-creator:all"])+ self.run_followup()+ self.assertEqual(web_follow._run_follow_check(self.contract, {"sources": []})["followups"], [])++ def test_author_key_follows_the_binding(self):+ self.jul3d()+ self.run_followup()+ with self.contract.database.read_connection() as connection:+ rows = FollowStore(lambda: connection).sources()+ self.assertEqual({author_key(row) for row in rows},+ {f"entity:{rows[0]['entity_id']}"})+++class SourceLinkTests(unittest.TestCase):+ def row(self, provider, ref, metadata=None, url=""):+ return {"provider": provider, "ref": ref, "url": url, "label": ref,+ "metadata_json": json.dumps(metadata or {})}++ def urls(self, row):+ return [link["url"] for link in follow_creators.source_links(row)]++ def test_archives_restore_only_the_account_shapes_that_were_checked(self):+ self.assertEqual(self.urls(self.row("kemono", "fanbox/123")), ["https://www.pixiv.net/users/123"])+ self.assertEqual(self.urls(self.row("coomer", "onlyfans/some.one_")), ["https://onlyfans.com/some.one_"])+ self.assertEqual(self.urls(self.row("kemono", "fanbox/name")), [])+ self.assertEqual(self.urls(self.row("kemono", "gumroad/123")), [])++ def test_an_official_source_is_its_own_channel(self):+ self.assertEqual(self.urls(self.row("subscribestar", "artist", url="https://subscribestar.adult/artist")),+ ["https://subscribestar.adult/artist"])++ def test_booru_profile_links_count_only_when_the_handle_is_the_author(self):+ row = self.row("rule34video", "artist", {"official_links": [+ {"service": "twitter", "handle": "artist", "url": "https://x.com/artist"},+ {"service": "twitter", "handle": "collaborator", "url": "https://x.com/collaborator"}]})+ self.assertEqual(self.urls(row), ["https://x.com/artist"])++ def test_subscribestar_keeps_the_host_from_the_profile(self):+ row = self.row("f95zone", "1", {"official_links": [+ {"service": "subscribestar", "handle": "artist", "url": "https://www.subscribestar.com/artist?x=1"}]})+ self.assertEqual(self.urls(row), ["https://subscribestar.com/artist"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex 49d1bb6f6..073f83eb4 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -1409,6 +1409,15 @@ class ProfileLinkTests(unittest.TestCase):"https://www.pixiv.net/en/users/30917150"),("pixiv", "30917150"))+ def test_shop_and_social_hosts_name_the_account(self):+ for url, identity in (+ ("https://jul3d.itch.io/", ("itchio", "jul3d")),+ ("https://ko-fi.com/artist", ("kofi", "artist")),+ ("https://bsky.app/profile/artist.bsky.social", ("bsky", "artist.bsky.social")),+ ("https://fantia.jp/fanclubs/12345", ("fantia", "12345"))):+ with self.subTest(url=url):+ self.assertEqual(follow_sources.profile_link_identity(url), identity)+def test_a_function_page_is_not_a_handle(self):self.assertIsNone(follow_sources.profile_link_identity("https://www.patreon.com/login"))diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 35dd7c8ed..fa16d8cf8 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -1015,7 +1015,7 @@ class WebDataTests(unittest.TestCase):"/api/follow/image-dims", "/api/follow/save","/api/follow/play", "/api/follow/activity","/api/follow/source", "/api/follow/resolve", "/api/follow/credential",- "/api/follow/author-alias", "/api/follow/schedule",+ "/api/follow/author-alias", "/api/follow/creator", "/api/follow/schedule","/api/taste/refresh", "/api/taste/source", "/api/settings","/api/entity-name", "/api/entity-alias","/api/organize/preview", "/api/organize/apply", "/api/organize/rollback",