Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: 追更拆成看和管两个页面,来源粘链接就能加

Peach local maintenancef22c8639c82f
diff --git a/README.md b/README.md
index 845c08eab..daa54de42 100644
--- a/README.md
+++ b/README.md
@@ -327,7 +327,8 @@ Per-Monitor V2 DPI,单击打开 `https://peach-win.local/`;右键可同步 L
| `/stats` | 统计 |
| `/immerse` | 沉浸模式 |
| `/quality-goals` | 已标记寻找高清、无水印或完整版的作品 |
-| `/follow` | 在线追更:按作品分组的更新流与来源状态 |
+| `/follow` | 在线追更:按作品分组的更新流,点开就去看 |
+| `/follow-manage` | 追更来源管理:粘链接添加、检查更新、移除来源、凭据状态 |
| `/trash` | 回收站 |
| `/mix/{seed_id}/{item_id}` | 自动 Mix 播放器与右侧队列 |
| `/playlists` | 播放列表管理;新建、改名、继续播放与删除 |
@@ -363,7 +364,7 @@ cookie 并重定向到不含口令的干净 URL;新设备不要再复制带口
写入 API:`POST /api/activity`、`/api/play`、`/api/feedback`、`/api/watch-later`、`/api/playlist`、
`/api/preference`、`/api/item-tag`、`/api/batch`、`/api/trash/empty`、`/api/follow/check`、
-`/api/follow/status`、`/api/follow/save`。标签隐藏只写本地 profile 覆盖,不销毁
+`/api/follow/status`、`/api/follow/save`、`/api/follow/source`。标签隐藏只写本地 profile 覆盖,不销毁
原始来源断言;搜索历史通过 `POST /api/search-history` 共享写入账本;媒体先进入回收站,只有显式清空回收站才永久删除。除上述明确端点外,`/api/*` 返回 404。公共页面不再使用
`/entity/{kind}/{name}`;内部 JSON 的 `/api/entity` 只是兼容契约,不暴露数据库路由结构。
@@ -441,6 +442,14 @@ f95zone.to(线程 `/latest` 页 + `latest_data.php`)。`FeedAdapter` 的 RSS
但这七个来源实测都没有可用 feed。取舍与站点证据见
[`ADR-0019`](docs/adr/0019-site-follow-connectors-and-variant-grouping.md)。
+看和管是两个页面,因为是两件事。左侧导航的 `/follow` 是**看**:一张卡片一个作品,
+点开就去看。管理区的 `/follow-manage` 是**管**:加来源、检查更新、移除来源、看凭据状态。
+
+加来源不用命令,把创作者页或线程的链接粘进输入框就行——kemono/coomer/pawchive 的
+创作者页、rule34video 的作者页、rule34.xxx 的标签页、f95zone 的线程都认得,认不出来
+会当场说清楚支持哪些形状,而不是静默登记一个永远抓不到东西的来源。登记后立刻检查一次;
+首次检查失败不回滚登记,错误显示在那一行上(rule34.xxx 缺 key 就是这种情况)。
+
联网只发生在显式调用:CLI 是 `peach follow check`,界面是「检查更新」按钮。服务启动、
健康检查、普通浏览和首页「换一批」都不联网。**不绕过机器人验证**——simpcity.cr 挂着
DDoS-Guard 质询,连接器只登记不可用并原样报出原因。
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index 11e7d9b21..e7cd5e5d2 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -6,7 +6,7 @@
1. **寻找更好版本**:已经能逐条标记「高清 / 无水印 / 完整版」等目标;后续仍需相似内容匹配、候选去重、来源发现和人工替换确认。
2. **现代自适应播放**:Video.js、Range、统计面板和面向 115/PikPak 原生 MP4 的按需 HLS 清单已经上线;自适应码率、多路清单、快速首帧和来源层大块预取优化仍未完成。
-3. **在线追更**:kemono/coomer/pawchive、rule34video、rule34.xxx、f95zone 五类连接器、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、`peach follow` 与 `/follow` 页面已上线;仍缺定时轮询(APScheduler)、媒体下载落地,以及 simpcity 的可用入口(DDoS-Guard,未取得)。
+3. **在线追更**:kemono/coomer/pawchive、rule34video、rule34.xxx、f95zone 五类连接器、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、`peach follow`、看的 `/follow` 与管的 `/follow-manage` 两个页面(粘链接即可添加来源)已上线;仍缺定时轮询(APScheduler)、媒体下载落地,以及 simpcity 的可用入口(DDoS-Guard,未取得)。
4. **首尾帧出处与不完整候选**:已有受限 FFmpeg 首尾抽帧、Windows 内置 OCR、证据帧缓存、来源/Full version 候选和 `/review`;仍需决定全库批次范围,并把用户批准后的不完整版判断接到更好版本目标。
5. **厂牌 Logo 补齐与持续校验**:14 个已确认社交 handle 已有内容缓存、provenance、精确/感知哈希、质量与重复门槛及健康报告;仍有 72 个厂牌没有可信 handle,必须继续从官网/公开来源取证,不能猜账号。
diff --git a/src/peach/api.py b/src/peach/api.py
index f660cf5a3..ccbc2dd23 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -661,6 +661,7 @@ def create_app(
@app.api_route("/duplicates", methods=["GET", "HEAD"])
@app.api_route("/quality-goals", methods=["GET", "HEAD"])
@app.api_route("/follow", methods=["GET", "HEAD"])
+ @app.api_route("/follow-manage", methods=["GET", "HEAD"])
def client_route(request: Request, item_id: int | None = None,
seed_id: int | None = None, mix_item_id: int | None = None,
playlist_id: int | None = None, playlist_item_id: int | None = None,
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index 29f6e7995..ae9858984 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -638,6 +638,118 @@ class SimpCityConnector(_BaseConnector):
raise FollowSourceError(self.blocked_reason)
+@dataclass(frozen=True)
+class ParsedSource:
+ """从一条粘进来的链接认出来的订阅。"""
+
+ provider: str
+ ref: str
+ url: str
+ label: str
+ semantics: str
+
+
+#: 每个来源的条目语义:`work` 是每条一个独立作品,`release` 是同一作品的历次发布。
+_SEMANTICS = {"f95zone": "release", "simpcity": "release"}
+
+_KEMONO_HOSTS = {"kemono.cr": "kemono", "coomer.st": "coomer", "pawchive.pw": "pawchive"}
+_KEMONO_PATH_RE = re.compile(r"^/([a-z0-9_\-]{1,32})/user/([A-Za-z0-9_\-.]{1,64})")
+_R34V_PATH_RE = re.compile(r"^/models/([a-z0-9][a-z0-9_\-]{0,80})")
+_THREAD_PATH_RE = re.compile(r"^/threads/(?:[^/]*?\.)?(\d{1,12})")
+
+
+#: 线程 slug 里从这个 token 起就不是作品名了:f95 的惯例是
+#: `<作品名>-<发布日期>-<作者手柄>`,日期之后全是元数据。
+_SLUG_TAIL_RE = re.compile(r"^(?:19|20)\d{2}$|^v?\d+(?:\.\d+)+[a-z]?$")
+
+
+def _slug_label(slug: str) -> str:
+ words = [word for word in re.split(r"[-_]+", slug) if word]
+ kept: list[str] = []
+ for word in words:
+ if kept and _SLUG_TAIL_RE.match(word):
+ break
+ kept.append(word)
+ return " ".join(kept).strip() or re.sub(r"[-_]+", " ", slug).strip() or slug
+
+
+def parse_source_url(raw_url: str) -> ParsedSource:
+ """把一条来源链接认成可登记的订阅。
+
+ 只做纯解析,不联网。认不出来就抛 `FollowSourceError` 并说清楚支持哪些形状——
+ 与其静默登记一个永远抓不到东西的来源,不如当场说不认识。
+ """
+ text = (raw_url or "").strip()
+ if not text:
+ raise FollowSourceError("请先粘贴一条来源链接")
+ if "://" not in text:
+ text = "https://" + text
+ try:
+ parsed = urllib.parse.urlsplit(text)
+ except ValueError as exc:
+ raise FollowSourceError("这不是一条合法链接") from exc
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise FollowSourceError("只接受 http(s) 链接")
+ if parsed.username is not None or parsed.password is not None:
+ raise FollowSourceError("链接里不能带账号密码")
+ host = parsed.hostname.lower()
+ bare = host[4:] if host.startswith("www.") else host
+ path = parsed.path or "/"
+
+ provider = _KEMONO_HOSTS.get(bare)
+ if provider:
+ matched = _KEMONO_PATH_RE.match(path)
+ if not matched:
+ raise FollowSourceError(
+ f"{bare} 的链接要指向某个创作者,形如 "
+ f"https://{bare}/fanbox/user/30917150")
+ service, user = matched.group(1), matched.group(2)
+ return ParsedSource(provider, f"{service}/{user}",
+ f"https://{bare}/{service}/user/{user}",
+ f"{user} · {service}", "work")
+
+ if bare == "rule34video.com":
+ matched = _R34V_PATH_RE.match(path)
+ if not matched:
+ raise FollowSourceError(
+ "rule34video 的链接要指向作者页,形如 "
+ "https://rule34video.com/models/lazyprocrastinator/")
+ slug = matched.group(1)
+ return ParsedSource("rule34video", slug,
+ f"https://rule34video.com/models/{slug}/",
+ _slug_label(slug), "work")
+
+ if bare in ("rule34.xxx", "api.rule34.xxx"):
+ tags = urllib.parse.parse_qs(parsed.query).get("tags", [""])[0].strip()
+ if not tags:
+ raise FollowSourceError(
+ "rule34.xxx 的链接要带标签,形如 "
+ "https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator")
+ return ParsedSource("rule34xxx", tags,
+ "https://rule34.xxx/index.php?page=post&s=list"
+ f"&tags={urllib.parse.quote(tags)}",
+ _slug_label(tags), "work")
+
+ if bare == "f95zone.to":
+ matched = _THREAD_PATH_RE.match(path)
+ if not matched:
+ raise FollowSourceError(
+ "f95zone 的链接要指向一个线程,形如 "
+ "https://f95zone.to/threads/xxx.50685/")
+ thread = matched.group(1)
+ slug = path.split("/threads/", 1)[1].rsplit(".", 1)[0] if "." in path else ""
+ return ParsedSource("f95zone", thread,
+ f"https://f95zone.to/threads/{thread}/",
+ _slug_label(slug) or f"线程 {thread}", "release")
+
+ if bare == "simpcity.cr":
+ raise FollowSourceError(SimpCityConnector.blocked_reason)
+
+ raise FollowSourceError(
+ f"不认识 {bare}。当前支持 kemono.cr、coomer.st、pawchive.pw 的创作者页,"
+ "rule34video.com 的作者页,rule34.xxx 的标签页,以及 f95zone.to 的线程。")
+
+
CONNECTORS: dict[str, type] = {
"kemono": KemonoConnector,
"coomer": KemonoConnector,
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 2a73eb08a..9c3f8b9df 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -37,7 +37,8 @@ from .platform import (
)
from .repository import LedgerDatabase
from .web_follow import (
- q_follow, q_follow_credentials, w_follow_check, w_follow_save, w_follow_status,
+ q_follow, q_follow_credentials, w_follow_check, w_follow_save, w_follow_source,
+ w_follow_status,
)
from .web_activity import (
DEFAULT_PROFILE_ID,
@@ -2556,6 +2557,7 @@ GET_HANDLERS = {
POST_HANDLERS = {
"/api/follow/check": w_follow_check,
+ "/api/follow/source": w_follow_source,
"/api/follow/status": w_follow_status,
"/api/follow/save": w_follow_save,
"/api/activity": w_activity,
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 3ebedc36c..9cb1333f9 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -9,7 +9,7 @@ from datetime import datetime, timezone
from .follow import FollowSourceError
from .follow_secrets import CredentialError, CredentialStore
-from .follow_sources import CONNECTORS, build_connector
+from .follow_sources import CONNECTORS, KemonoConnector, build_connector, parse_source_url
from .follow_store import FollowStore, ReleaseGroup
@@ -181,6 +181,60 @@ def _failure(contract, row, error, moment, status) -> dict:
"ok": False, "status": status, "error": str(error)}
+def _resolve_label(contract, parsed, credential) -> str:
+ """尽量把标签换成人看得懂的名字。
+
+ kemono 系有 profile 端点,一次请求就能把 `30917150 · fanbox` 换成创作者名;
+ 取不到就保留从链接推出来的标签,不猜。
+ """
+ if parsed.provider not in KemonoConnector.HOSTS:
+ return parsed.label
+ connector = KemonoConnector(provider=parsed.provider, credential=credential)
+ service, _, user = parsed.ref.partition("/")
+ try:
+ response = connector._get(
+ f"https://{connector.host}/api/v1/{service}/user/{user}/profile")
+ if response.status != 200:
+ return parsed.label
+ name = (connector._json(response) or {}).get("name")
+ except (FollowSourceError, CredentialError):
+ return parsed.label
+ return f"{name} · {service}" if name else parsed.label
+
+
+def w_follow_source(contract, body) -> dict:
+ """粘一条来源链接就登记,并立刻检查一次。
+
+ 登记成功但首次检查失败不算失败:来源已经在列表里,错误显示在它那一行上——
+ rule34.xxx 缺 key 就是这种情况,把它整个回滚掉反而让人不知道发生了什么。
+ """
+ action = str(body.get("action") or "add")
+ if action == "remove":
+ source_id = body.get("id")
+ 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,))
+ return {"ok": True, "removed": source_id}
+ if action != "add":
+ raise ValueError(f"unknown follow source action: {action}")
+
+ parsed = parse_source_url(str(body.get("url") or ""))
+ credentials = CredentialStore(contract.follow_secrets_root)
+ credential = credentials.load(parsed.provider)
+ label = str(body.get("label") or "").strip() or _resolve_label(
+ contract, parsed, credential)
+ with contract.database.write_transaction() as connection:
+ source_id = _store(contract, connection).register(
+ provider=parsed.provider, ref=parsed.ref, label=label, url=parsed.url,
+ semantics=parsed.semantics)
+ checked = w_follow_check(contract, {"source": source_id})
+ outcome = next((row for row in checked["results"]
+ if row["source"] == source_id), None)
+ return {"ok": True, "source": source_id, "provider": parsed.provider,
+ "ref": parsed.ref, "label": label, "checked": outcome}
+
+
def q_follow_credentials(contract, _args) -> dict:
"""只报告凭据是否存在与字段名,绝不返回凭据值。"""
store = CredentialStore(contract.follow_secrets_root)
diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.py
index 8a49d3591..fc32abfe8 100644
--- a/tests/test_follow_sources.py
+++ b/tests/test_follow_sources.py
@@ -17,7 +17,7 @@ from peach.follow_secrets import Credential, CredentialError, CredentialStore
from peach.follow_sources import (
USER_AGENT, F95ZoneConnector, KemonoConnector, Rule34VideoConnector,
Rule34XxxConnector, SimpCityConnector, build_connector, _iso_from_relative,
- origin_group_key,
+ origin_group_key, parse_source_url,
)
from peach.http import HttpResponse
@@ -357,6 +357,71 @@ class OriginGroupKeyTests(unittest.TestCase):
self.assertIsNone(origin_group_key(value))
+class ParseSourceUrlTests(unittest.TestCase):
+ """粘进来的链接怎么认。纯解析,不联网。"""
+
+ def test_each_supported_host_maps_to_its_provider_and_ref(self):
+ cases = {
+ "https://kemono.cr/fanbox/user/30917150": ("kemono", "fanbox/30917150"),
+ "https://coomer.st/onlyfans/user/abc": ("coomer", "onlyfans/abc"),
+ "https://pawchive.pw/patreon/user/123": ("pawchive", "patreon/123"),
+ "https://rule34video.com/models/lazyprocrastinator/":
+ ("rule34video", "lazyprocrastinator"),
+ "https://rule34.xxx/index.php?page=post&s=list&tags=lazyprocrastinator":
+ ("rule34xxx", "lazyprocrastinator"),
+ "https://f95zone.to/threads/lazy-collection.50685/": ("f95zone", "50685"),
+ }
+ for url, expected in cases.items():
+ parsed = parse_source_url(url)
+ self.assertEqual((parsed.provider, parsed.ref), expected, url)
+
+ def test_a_deep_link_is_narrowed_to_the_creator(self):
+ parsed = parse_source_url("https://kemono.cr/fanbox/user/30917150/post/11406814")
+ self.assertEqual(parsed.ref, "fanbox/30917150")
+ self.assertEqual(parsed.url, "https://kemono.cr/fanbox/user/30917150")
+
+ def test_threads_get_release_semantics_and_others_get_work(self):
+ self.assertEqual(parse_source_url("https://f95zone.to/threads/x.1/").semantics,
+ "release")
+ self.assertEqual(
+ parse_source_url("https://rule34video.com/models/abc/").semantics, "work")
+
+ def test_a_bare_host_is_accepted_and_www_is_ignored(self):
+ self.assertEqual(parse_source_url("rule34video.com/models/abc/").provider,
+ "rule34video")
+ self.assertEqual(parse_source_url("https://www.rule34video.com/models/abc/").ref,
+ "abc")
+
+ def test_the_thread_slug_becomes_a_readable_label(self):
+ parsed = parse_source_url(
+ "https://f95zone.to/threads/lazy-procrastinator-collection.50685/")
+ self.assertEqual(parsed.label, "lazy procrastinator collection")
+
+ def test_the_label_stops_at_the_release_date_not_at_the_end_of_the_slug(self):
+ # f95 的 slug 惯例是 `<作品名>-<发布日期>-<作者手柄>`,全取会得到一长串元数据。
+ parsed = parse_source_url(
+ "https://f95zone.to/threads/"
+ "lazy-procrastinator-collection-2026-06-28-lazyprocrastinator-lazyprocrast.50685/")
+ self.assertEqual(parsed.label, "lazy procrastinator collection")
+
+ def test_the_right_host_with_the_wrong_path_says_what_shape_is_expected(self):
+ for url, hint in (
+ ("https://kemono.cr/posts", "fanbox/user"),
+ ("https://rule34video.com/latest-updates/", "models"),
+ ("https://rule34.xxx/index.php?page=post&s=view&id=1", "tags="),
+ ("https://f95zone.to/latest", "threads"),
+ ):
+ with self.assertRaises(FollowSourceError) as caught:
+ parse_source_url(url)
+ self.assertIn(hint, str(caught.exception), url)
+
+ def test_credentials_and_non_http_urls_are_refused(self):
+ for url in ("https://user:[email protected]/fanbox/user/1",
+ "ftp://kemono.cr/fanbox/user/1", ""):
+ with self.assertRaises(FollowSourceError):
+ parse_source_url(url)
+
+
class BuildConnectorTests(unittest.TestCase):
def test_registry_maps_the_three_kemono_hosts_to_distinct_providers(self):
for provider in ("kemono", "coomer", "pawchive"):
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 73e6c97ab..95047ab33 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -208,6 +208,88 @@ class FollowContractTests(unittest.TestCase):
self.assertEqual(group["variants"][0]["summary"], "New batch up Gofile")
+class FollowSourceAddTests(FollowContractTests):
+ """粘链接登记来源。首次检查用注入的连接器,测试不联网。"""
+
+ def _add(self, url, fetch=None):
+ with mock.patch.object(web_follow, "build_connector") as factory:
+ factory.return_value.fetch.return_value = fetch or SourceFetch(
+ provider="rule34video", ref="x", request_url="https://x.test/",
+ semantics="work", not_modified=True)
+ return self._post("/api/follow/source", {"action": "add", "url": url})
+
+ def test_pasting_a_creator_link_registers_and_checks_it(self):
+ result = self._add("https://rule34video.com/models/lazyprocrastinator/")
+ self.assertTrue(result["ok"])
+ self.assertEqual(result["provider"], "rule34video")
+ self.assertEqual(result["ref"], "lazyprocrastinator")
+ self.assertTrue(result["checked"]["ok"])
+ self.assertEqual(self._get()["sources"][0]["url"],
+ "https://rule34video.com/models/lazyprocrastinator/")
+
+ def test_a_thread_link_is_registered_with_release_semantics(self):
+ self._add("https://f95zone.to/threads/"
+ "lazy-procrastinator-collection-2026-06-28-lazyprocrast.50685/")
+ source = self._get()["sources"][0]
+ self.assertEqual(source["provider"], "f95zone")
+ self.assertEqual(source["ref"], "50685")
+ self.assertEqual(source["semantics"], "release")
+ self.assertEqual(source["label"], "lazy procrastinator collection")
+
+ def test_a_kemono_link_keeps_its_service_and_user(self):
+ self._add("https://kemono.cr/fanbox/user/30917150")
+ source = self._get()["sources"][0]
+ self.assertEqual(source["provider"], "kemono")
+ self.assertEqual(source["ref"], "fanbox/30917150")
+
+ def test_the_same_link_twice_does_not_duplicate_the_source(self):
+ self._add("https://rule34video.com/models/lazyprocrastinator/")
+ self._add("https://rule34video.com/models/lazyprocrastinator/")
+ self.assertEqual(len(self._get()["sources"]), 1)
+
+ def test_a_failing_first_check_still_leaves_the_source_registered(self):
+ # rule34.xxx 缺 key 就是这种情况。整个回滚掉反而让人不知道发生了什么。
+ with mock.patch.object(web_follow, "build_connector") as factory:
+ factory.return_value.fetch.side_effect = CredentialError("需要 user_id")
+ result = self._post("/api/follow/source", {
+ "action": "add",
+ "url": "https://rule34.xxx/index.php?page=post&s=list&tags=lazy"})
+ self.assertTrue(result["ok"])
+ self.assertFalse(result["checked"]["ok"])
+ source = self._get()["sources"][0]
+ self.assertEqual(source["last_status"], "unauthorized")
+ self.assertIn("user_id", source["last_error"])
+
+ def test_an_unknown_host_is_refused_with_the_supported_list(self):
+ with self.assertRaises(FollowSourceError) as caught:
+ self._post("/api/follow/source",
+ {"action": "add", "url": "https://example.test/creator"})
+ self.assertIn("kemono.cr", str(caught.exception))
+
+ def test_simpcity_is_refused_with_the_bot_check_reason(self):
+ with self.assertRaises(FollowSourceError) as caught:
+ self._post("/api/follow/source",
+ {"action": "add", "url": "https://simpcity.cr/threads/x.1/"})
+ self.assertIn("DDoS-Guard", str(caught.exception))
+
+ def test_removing_a_source_takes_its_items_with_it(self):
+ self._seed()
+ source_id = self._get()["sources"][0]["id"]
+ self.assertTrue(self._get()["groups"])
+ self._post("/api/follow/source", {"action": "remove", "id": source_id})
+ payload = self._get()
+ self.assertEqual(payload["sources"], [])
+ self.assertEqual(payload["groups"], [])
+
+ def test_remove_requires_an_integer_id(self):
+ with self.assertRaises(ValueError):
+ self._post("/api/follow/source", {"action": "remove", "id": "1"})
+
+ def test_unknown_actions_are_rejected(self):
+ with self.assertRaises(ValueError):
+ self._post("/api/follow/source", {"action": "explode"})
+
+
class FollowWebSourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
@@ -220,11 +302,33 @@ class FollowWebSourceTests(unittest.TestCase):
if needle not in self.page:
self.fail(f"Web 表面缺少:{needle!r}" + (f"({message})" if message else ""))
- def test_follow_is_a_manage_section_with_its_own_route(self):
- self.assertPageContains("['follow','在线追更','globe']")
- self.assertPageContains("if(path==='/follow')return 'follow'")
- self.assertPageContains("if(section==='follow'){openFollow();return}")
+ def test_watching_lives_in_the_left_rail_and_managing_stays_in_the_manage_area(self):
+ # 看和管是两件事,两个页面:左侧导航进「看」,管理区进「管」。
+ self.assertPageContains("['follow','在线追更','globe'],\n ['immerse'")
+ self.assertPageContains("if(k==='follow'){openFollow();return}")
+ self.assertPageContains("if(k==='follow')return path==='/follow';")
+ self.assertPageContains("['follow','追更来源','globe']")
+ self.assertPageContains("if(path==='/follow-manage')return 'follow'")
+ self.assertPageContains("if(section==='follow'){openFollowManage();return}")
+
+ def test_both_follow_routes_restore_on_reload(self):
self.assertPageContains("if(path==='/follow'){await openFollow(false);return}")
+ self.assertPageContains(
+ "if(path==='/follow-manage'){await openFollowManage(false);return}")
+
+ def test_sources_are_added_by_pasting_a_link_not_by_a_command(self):
+ self.assertPageContains('id="followAdd"')
+ self.assertPageContains('placeholder="https://kemono.cr/fanbox/user/30917150"')
+ self.assertPageContains("'/api/follow/source'")
+ self.assertPageContains("data-follow-remove")
+
+ def test_the_watch_page_does_not_carry_source_management(self):
+ # 输入框、移除、凭据都只属于管理页;看的那页保持干净。
+ page = self.page
+ watch = page[page.index("function renderFollow(){"):page.index("async function openFollow")]
+ for management in ("followAdd", "data-follow-remove", "fcreds", "data-follow-bulk"):
+ if management in watch:
+ self.fail(f"看的那一页不应出现管理控件:{management!r}")
def test_approximate_timestamps_are_labelled_as_approximate(self):
# 站点只给「1 周前」时换算值不是发布时间,界面必须照实说。
@@ -250,7 +354,8 @@ class FollowWebSourceTests(unittest.TestCase):
def test_network_check_is_an_explicit_button_not_an_auto_refresh(self):
self.assertPageContains("data-follow-check")
# 「换一批」自动刷新绝不能顺手触发一次联网检查。
- self.assertPageContains("if(location.pathname==='/follow')return;")
+ self.assertPageContains(
+ "if(location.pathname==='/follow'||location.pathname==='/follow-manage')return;")
def test_every_entered_state_can_be_left_again(self):
self.assertPageContains("""item.status==='seen'||item.status==='ignored'""")
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 4a48e4116..d63e06ac1 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -381,6 +381,7 @@ class WebDataTests(unittest.TestCase):
"/api/search-history", "/api/trash/empty", "/api/review/decision",
"/api/purge-missing", "/api/review/auto-apply",
"/api/follow/check", "/api/follow/status", "/api/follow/save",
+ "/api/follow/source",
})
with self.assertRaises(rm_web.ContractRouteNotFound):
rm_web.dispatch_api_get(self.contract, "/api/typo", {})
diff --git a/web/app.css b/web/app.css
index a27382905..951ffca31 100644
--- a/web/app.css
+++ b/web/app.css
@@ -1146,3 +1146,34 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
不能要求先横滑才发现。窄屏下让它独占一行。 */
.follow .reviewtabs{flex-wrap:wrap;overflow-x:visible}
.follow .reviewtabs .fcheck{margin-left:0;flex:1 1 100%;justify-content:center}}
+
+/* ── 追更管理页 ── */
+.fhead{display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap;margin-bottom:16px}
+.fhead h2{margin:0 0 4px;font-size:20px}
+.fhead>div{flex:1 1 320px;min-width:0}
+.fhead p{margin:0;color:var(--muted);font-size:12px;line-height:1.6;max-width:62ch}
+.faddform{display:flex;gap:8px;flex-wrap:wrap;align-items:center;flex:1 1 340px}
+.faddform input{flex:1 1 260px;min-width:0;border:1px solid var(--border-15);border-radius:9px;background:var(--overlay-5);color:var(--ink);padding:9px 12px;font-size:13px}
+.faddform input:focus-visible{outline:2px solid var(--tungsten);outline-offset:1px;border-color:var(--tungsten)}
+.faddform button{border:1px solid var(--tungsten);border-radius:9px;background:var(--tungsten);color:#fff;font-weight:600;padding:9px 18px;font-size:13px;cursor:pointer;white-space:nowrap}
+.faddform button:disabled{opacity:.6;cursor:default}
+.faddform [data-follow-add-state]{flex:1 1 100%;font-size:11.5px;color:var(--drop);min-height:1em}
+.fsource .fremove{color:var(--drop)}
+.fsource .fremove:hover{border-color:var(--drop);color:var(--drop)}
+.fwarn{margin:0 0 12px;padding:9px 12px;border:1px solid var(--drop);border-radius:9px;color:var(--drop);font-size:12px}
+.flink{border:0;background:none;padding:0;color:var(--tungsten);font:inherit;cursor:pointer;text-decoration:underline}
+.fcontent,.fcreds{margin-top:22px}
+.fcontent h3,.fcreds h3{margin:0 0 8px;font-size:15px}
+.fcontent>p.mono{margin:0 0 10px;color:var(--muted);font-size:12px}
+.fbulk{display:flex;gap:8px;flex-wrap:wrap}
+.fbulk button{border:1px solid var(--border-15);border-radius:8px;background:transparent;color:var(--ink-2);padding:6px 13px;font-size:12px;cursor:pointer}
+.fbulk button:hover:not(:disabled){border-color:var(--tungsten);color:var(--ink)}
+.fcreds ul{list-style:none;margin:0 0 8px;padding:0;display:grid;gap:5px}
+.fcred{display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:6px 12px;border:1px solid var(--line-soft);border-radius:9px;font-size:12px}
+.fcred b{min-width:100px}
+.fcred .mono{color:var(--muted);font-size:11.5px}
+.fcred.bad{border-color:var(--drop)}
+.fcred i{font-style:normal;color:var(--drop);font-size:11.5px}
+.fcreds p{margin:4px 0 0;color:var(--muted);font-size:11.5px}
+@media (max-width:640px){.faddform{flex:1 1 100%}.faddform input{flex:1 1 100%}
+ .faddform button{flex:1 1 100%}}
diff --git a/web/app.js b/web/app.js
index a46d9daf2..14d36f94b 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1190,9 +1190,12 @@ async function openQualityGoals(push=true){
}
/* ── 在线追更 ──
- 一张卡片 = 一个作品,不是一条抓取记录。同一作品在本站的 alt 与 WIP 折进卡片内部,
- 跨站的同一作品折成「另见」,这样 24 条 rule34video 记录读起来才是 20 个作品。
- 联网只发生在用户点「检查更新」的那一刻——页面加载、换一批、popstate 都不联网。 */
+ 两个页面,因为是两件事:
+ - `/follow`(左侧导航)是**看**:一张卡片一个作品,点开就去看。本站的 alt 与 WIP
+ 折进卡片内部,跨站的同一作品折成「另见」,24 条抓取记录才读成 20 个作品。
+ - `/follow-manage`(管理区)是**管**:加来源、检查更新、移除来源、看凭据状态,
+ 以及对内容做批量标记。
+ 联网只发生在管理页点「检查更新」的那一刻——看的那一页不联网。 */
let followData=null,followFilter='new',followBusy=false;
const FOLLOW_FILTERS=[['new','未看'],['seen','已看'],['saved','已保存'],['ignored','已忽略'],['','全部']];
@@ -1263,36 +1266,36 @@ function followCard(group){
</div></article>`;
}
-function followSourceRow(source){
- const state=source.last_status||'未检查';
- const bad=state==='error'||state==='unauthorized';
- return `<li class="fsource${bad?' bad':''}">
- <b>${esc(source.label)}</b><span class="mono">${esc(source.provider_label)}</span>
- <span class="mono">${esc(source.last_checked_at?source.last_checked_at.replace('T',' ').slice(0,16):'未检查')}</span>
- <span class="fstatus">${esc(state)}</span>
- <button data-follow-check="${source.id}">检查</button>
- ${source.last_error?`<i>${esc(source.last_error)}</i>`:''}</li>`;
-}
-
+/* ── 看的那一页 ── */
function renderFollow(){
const groups=followData.groups||[],counts=followData.counts||{};
+ const sources=followData.sources||[];
+ const broken=sources.filter(s=>s.last_status==='error'||s.last_status==='unauthorized');
$('#stats').innerHTML=`<div class="follow">
- <ul class="fsources">${(followData.sources||[]).map(followSourceRow).join('')||
- '<li class="empty">还没有登记追更来源。用 <code>peach follow add</code> 添加。</li>'}</ul>
<div class="reviewtabs">${FOLLOW_FILTERS.map(([key,label])=>
`<button data-follow-filter="${key}" aria-pressed="${key===followFilter}">${label}${
key?` <span class="n mono">${counts[key]||0}</span>`:''}</button>`).join('')}
- <button class="fcheck" data-follow-check="">${icon('refresh-cw')}检查更新</button></div>
+ <button class="fcheck" data-follow-manage>${icon('settings')}管理来源</button></div>
+ ${broken.length?`<p class="fwarn">${broken.length} 个来源上次检查失败,去
+ <button class="flink" data-follow-manage>管理来源</button>看原因。</p>`:''}
<div class="followlist">${groups.length?groups.map(followCard).join('')
- :'<p class="empty">没有符合条件的追更条目</p>'}</div></div>`;
- wireFollow();
+ :sources.length?'<p class="empty">没有符合条件的追更条目</p>'
+ :`<p class="empty">还没有追更来源。<button class="flink" data-follow-manage>去添加</button></p>`}</div></div>`;
+ wireFollowItems();
+ $('#stats').querySelectorAll('[data-follow-filter]').forEach(button=>button.onclick=()=>{
+ followFilter=button.dataset.followFilter;openFollow(false)});
+ $('#stats').querySelectorAll('[data-follow-manage]').forEach(button=>
+ button.onclick=()=>openFollowManage());
}
async function openFollow(push=true){
- releaseHoverPreviews();disposeStage(false);document.body.classList.remove('entity-open');
+ releaseHoverPreviews();disposeStage(false);
+ document.body.classList.remove('entity-open','index-open');
if(push)route('/follow');
- buildManageBar();$('#stats').hidden=false;$('#index').hidden=true;$('#grid').innerHTML='';
+ $('#stats').hidden=false;$('#index').hidden=true;$('#grid').innerHTML='';
$('#count').textContent='';$('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;
+ $('#tiers').style.display='none';$('#tagbar').style.display='none';
+ $('#managebar').hidden=true;$('#manageTitle').hidden=true;buildEdge();
$('#stats').innerHTML='<div class="follow"><p class="empty">正在读取…</p></div>';
followData=await api(`/api/follow?limit=300${followFilter?`&status=${followFilter}`:''}`);
if(location.pathname!=='/follow')return;
@@ -1300,10 +1303,106 @@ async function openFollow(push=true){
window.scrollTo({top:0,behavior:'smooth'});
}
-function wireFollow(){
+/* ── 管的那一页 ── */
+function followSourceRow(source){
+ const state=source.last_status||'未检查';
+ const bad=state==='error'||state==='unauthorized';
+ return `<li class="fsource${bad?' bad':''}">
+ <b>${esc(source.label)}</b><span class="mono">${esc(source.provider_label)}</span>
+ <span class="mono">${esc(source.last_checked_at?source.last_checked_at.replace('T',' ').slice(0,16):'未检查')}</span>
+ <span class="fstatus">${esc(state)}</span>
+ <button data-follow-check="${source.id}">检查</button>
+ <button class="fremove" data-follow-remove="${source.id}" title="不再追这个来源">移除</button>
+ ${source.last_error?`<i>${esc(source.last_error)}</i>`:''}</li>`;
+}
+
+function followCredentialRow(row){
+ const state=row.present?'已配置':'未配置';
+ return `<li class="fcred${row.world_readable?' bad':''}"><b>${esc(row.provider)}</b>
+ <span>${state}</span><span class="mono">${esc((row.fields||[]).join(', ')||'—')}</span>
+ ${row.world_readable?'<i>文件权限过宽</i>':''}</li>`;
+}
+
+function renderFollowManage(credentials){
+ const sources=followData.sources||[],counts=followData.counts||{};
+ $('#stats').innerHTML=`<div class="follow followmanage">
+ <header class="fhead"><div>
+ <p>粘一条创作者页或线程的链接就能追。支持 kemono.cr、coomer.st、pawchive.pw 的创作者页,
+ rule34video.com 的作者页,rule34.xxx 的标签页,f95zone.to 的线程。</p></div>
+ <form class="faddform" id="followAdd">
+ <input name="url" type="url" required spellcheck="false"
+ placeholder="https://kemono.cr/fanbox/user/30917150" aria-label="来源链接">
+ <button type="submit">添加</button>
+ <span data-follow-add-state aria-live="polite"></span>
+ </form></header>
+ <ul class="fsources">${sources.map(followSourceRow).join('')||
+ '<li class="empty">还没有登记追更来源。把链接粘进上面的输入框。</li>'}</ul>
+ <div class="reviewtabs">
+ <button class="fcheck" data-follow-check="">${icon('refresh-cw')}检查全部更新</button>
+ <button data-follow-view>${icon('globe')}去看更新</button></div>
+ <section class="fcontent"><h3>内容</h3>
+ <p class="mono">未看 ${counts.new||0} · 已看 ${counts.seen||0} ·
+ 已保存 ${counts.saved||0} · 已忽略 ${counts.ignored||0}</p>
+ <div class="fbulk">
+ <button data-follow-bulk="seen">把「未看」全部标记为已看</button>
+ <button data-follow-bulk="ignored">把「未看」全部忽略</button></div></section>
+ <section class="fcreds"><h3>凭据</h3>
+ <ul>${(credentials.providers||[]).map(followCredentialRow).join('')}</ul>
+ <p class="mono">目录:${esc(credentials.root||'')}</p>
+ <p>凭据只留在本机,不进 Git、URL、日志或 ledger。这里只显示字段名,不显示值。</p>
+ </section></div>`;
+ wireFollowManage();
+}
+
+async function openFollowManage(push=true){
+ releaseHoverPreviews();disposeStage(false);
+ document.body.classList.remove('entity-open','index-open');
+ if(push)route('/follow-manage');
+ buildManageBar();
+ $('#stats').hidden=false;$('#index').hidden=true;$('#grid').innerHTML='';
+ $('#count').textContent='';$('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;
+ $('#stats').innerHTML='<div class="follow"><p class="empty">正在读取…</p></div>';
+ const [data,credentials]=await Promise.all([
+ api('/api/follow?limit=1'),api('/api/follow/credentials')]);
+ if(location.pathname!=='/follow-manage')return;
+ followData=data;
+ renderFollowManage(credentials);
+ window.scrollTo({top:0,behavior:'smooth'});
+}
+
+/* ── 共用接线 ── */
+function wireFollowItems(){
const root=$('#stats');
- root.querySelectorAll('[data-follow-filter]').forEach(button=>button.onclick=()=>{
- followFilter=button.dataset.followFilter;openFollow(false)});
+ root.querySelectorAll('[data-follow-status]').forEach(button=>button.onclick=async()=>{
+ await followWrite(button,'/api/follow/status',
+ {item:+button.dataset.followStatus,to:button.dataset.to})});
+ root.querySelectorAll('[data-follow-save]').forEach(button=>button.onclick=async()=>{
+ await followWrite(button,'/api/follow/save',{item:+button.dataset.followSave})});
+}
+
+function wireFollowManage(){
+ const root=$('#stats'),form=root.querySelector('#followAdd');
+ if(form)form.onsubmit=async event=>{
+ event.preventDefault();
+ const state=form.querySelector('[data-follow-add-state]'),button=form.querySelector('button');
+ const url=new FormData(form).get('url');
+ button.disabled=true;state.textContent='识别中…';
+ try{
+ await api('/api/follow/source',{method:'POST',body:JSON.stringify({action:'add',url})});
+ /* 登记成功但首次检查失败不算失败:来源已经在列表里,错误显示在它那一行上。
+ rule34.xxx 缺 key 就是这种情况。 */
+ form.reset();await openFollowManage(false);
+ }catch(error){state.textContent=error.message||'添加失败';button.disabled=false}
+ };
+ root.querySelectorAll('[data-follow-remove]').forEach(button=>button.onclick=async()=>{
+ if(!confirm('不再追这个来源?已经抓到的条目会一并移除,媒体本身不受影响。'))return;
+ button.disabled=true;
+ try{
+ await api('/api/follow/source',{method:'POST',
+ body:JSON.stringify({action:'remove',id:+button.dataset.followRemove})});
+ await openFollowManage(false);
+ }catch(error){button.disabled=false;alert(error.message)}
+ });
root.querySelectorAll('[data-follow-check]').forEach(button=>button.onclick=async()=>{
if(followBusy)return;
followBusy=true;const label=button.innerHTML;button.disabled=true;
@@ -1312,18 +1411,29 @@ function wireFollow(){
const id=button.dataset.followCheck;
const result=await api('/api/follow/check',{method:'POST',
body:JSON.stringify(id?{source:+id}:{})});
- const failed=(result.results||[]).filter(r=>!r.ok);
// 一个来源失败不该让其余来源的更新一起消失,所以逐条报,不整体报错。
+ const failed=(result.results||[]).filter(r=>!r.ok);
if(failed.length)console.warn('追更检查失败:',failed);
- await openFollow(false);
+ await openFollowManage(false);
}catch(e){button.innerHTML=label;alert('检查更新失败:'+e.message)}
finally{followBusy=false;button.disabled=false}
});
- root.querySelectorAll('[data-follow-status]').forEach(button=>button.onclick=async()=>{
- await followWrite(button,'/api/follow/status',
- {item:+button.dataset.followStatus,to:button.dataset.to})});
- root.querySelectorAll('[data-follow-save]').forEach(button=>button.onclick=async()=>{
- await followWrite(button,'/api/follow/save',{item:+button.dataset.followSave})});
+ root.querySelectorAll('[data-follow-bulk]').forEach(button=>button.onclick=async()=>{
+ const to=button.dataset.followBulk;
+ if(!confirm(`把当前全部「未看」标记为${to==='seen'?'已看':'已忽略'}?`))return;
+ button.disabled=true;
+ try{
+ const pending=await api('/api/follow?status=new&limit=1000');
+ const ids=(pending.groups||[]).flatMap(g=>[g.primary,...g.variants,...g.duplicates])
+ .filter(item=>item.status==='new').map(item=>item.id);
+ for(const id of ids){
+ await api('/api/follow/status',{method:'POST',body:JSON.stringify({item:id,to})});
+ }
+ await openFollowManage(false);
+ }catch(error){button.disabled=false;alert(error.message)}
+ });
+ root.querySelectorAll('[data-follow-view]').forEach(button=>
+ button.onclick=()=>openFollow());
}
async function followWrite(button,path,body){
@@ -1339,6 +1449,7 @@ async function followWrite(button,path,body){
}
}
+
function wireReviewAssets(root){
/* 复核页不再自造「多选模式」和框选:交互与主网格一致——点一下切换,Shift 选一段。
多一套只在这一页生效的选择方式,用户得先发现它、再记住它。 */
@@ -1843,6 +1954,7 @@ const EDGE_ICONS=[
['jav','JAV','jav'],
['flagged','已标记','star'],
['playlists','播放列表','list-filter'],
+ ['follow','在线追更','globe'],
['immerse','沉浸模式','play'],
['manage','管理','settings'],
];
@@ -1853,7 +1965,7 @@ const MANAGE_SECTIONS=[
['ads','疑似广告','alert'],
['dupes','重复文件','hard-drive'],
['quality','高清版','sparkles'],
- ['follow','在线追更','globe'],
+ ['follow','追更来源','globe'],
['trash','回收站','trash'],
['review','人工复核','square-check-big'],
];
@@ -1864,7 +1976,7 @@ function manageSection(){
if(path==='/trash')return 'trash';
if(path==='/duplicates')return 'dupes';
if(path==='/quality-goals')return 'quality';
- if(path==='/follow')return 'follow';
+ if(path==='/follow-manage')return 'follow';
return state.state==='ads'?'ads':'';
}
function buildManageBar(){
@@ -1894,7 +2006,7 @@ function openManage(section='stats'){
if(section==='review'){openReview();return}
if(section==='dupes'){openDuplicates();return}
if(section==='quality'){openQualityGoals();return}
- if(section==='follow'){openFollow();return}
+ if(section==='follow'){openFollowManage();return}
state.orient='';state.state=section==='trash'?'trash':'ads';
route(section==='trash'?'/trash':'/');
showHomeSurfaces();buildEdge();buildBars();load(true);
@@ -1954,6 +2066,7 @@ function navOn(k){
if(k==='performers'||k==='tags')return path==='/'+k;
if(k==='immerse')return path==='/immerse';
if(k==='playlists')return path==='/playlists'||path.startsWith('/playlists/');
+ if(k==='follow')return path==='/follow';
if(k==='jav')return javActive();
if(k==='shorts')return state.orient==='竖屏';
// 首页只在真的停在首页列表上时亮:管理区、索引页、实体页都不算,
@@ -1979,6 +2092,7 @@ function buildEdge(){
closeDrawerAfterNav(); // 点了就收起抽屉,且短暂禁止悬停把它立刻弹回
if(k==='immerse'){openTok();return}
if(k==='playlists'){openPlaylists();return}
+ if(k==='follow'){openFollow();return}
if(k==='manage'){openManage();return}
if(k==='jav'){toggleJavMode();return}
if(k==='performers'||k==='tags'){openIndex(k);return}
@@ -2793,9 +2907,9 @@ async function refreshAll(automatic=false){
if(location.pathname==='/duplicates'){await openDuplicates(false);return}
if(location.pathname==='/quality-goals'){await openQualityGoals(false);return}
if(location.pathname==='/playlists'){await openPlaylists(false);return}
- /* 追更页刻意不参与「换一批」自动刷新:重画要重新取数,而取数之后紧接着的
+ /* 两个追更页都刻意不参与「换一批」自动刷新:重画要重新取数,而管理页上紧接着的
动作是联网检查,自动触发等于替用户决定什么时候去打站点。 */
- if(location.pathname==='/follow')return;
+ if(location.pathname==='/follow'||location.pathname==='/follow-manage')return;
await openStats(false);return
} // 统计/复核页只刷新当前表面
if(!$('#index').hidden){return}
@@ -2859,6 +2973,7 @@ async function restoreRoute(){
if(path==='/duplicates'){await openDuplicates(false);return}
if(path==='/quality-goals'){await openQualityGoals(false);return}
if(path==='/follow'){await openFollow(false);return}
+ if(path==='/follow-manage'){await openFollowManage(false);return}
if(path==='/immerse'){await openTok(undefined,false);return}
showHomeSurfaces();disposeStage(false);
}