Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(follow): 查找进度按来源计数,进度环逐个来源真实上涨

longmeidaoa3be2da84784
diff --git a/src/peach/follow_discovery.py b/src/peach/follow_discovery.py
index 0f8ad20a0..ee95de945 100644
--- a/src/peach/follow_discovery.py
+++ b/src/peach/follow_discovery.py
@@ -359,13 +359,40 @@ def _f95_candidates(term: str, transport,
return _forum_candidates("f95zone", "f95zone.to", term, connector)
+DEFAULT_PROVIDERS = ("kemono", "coomer", "pawchive", "fanbox", "rule34video",
+ "rule34xxx", "simpcity", "f95zone")
+
+
+def discovery_plan(term: str, providers: tuple[str, ...] | None = None) -> tuple[str, ...]:
+ """这一轮实际会去问的来源,按执行顺序。
+
+ 数字的词不去 rule34video / rule34.xxx / simpcity 碰运气——那三个都按名字或
+ 标签查——fanbox 只是把归档身份换算成官方页。计划先算出来,调用方才能把
+ 进度摊到每个来源上,而不是整轮查完只跳一格。
+ """
+ wanted = providers or DEFAULT_PROVIDERS
+ tasks = [provider for provider in ("kemono", "coomer", "pawchive")
+ if provider in wanted]
+ if "fanbox" in wanted:
+ tasks.append("fanbox")
+ if not _NUMERIC_RE.match(term):
+ tasks.extend(provider for provider in ("rule34video", "rule34xxx", "simpcity")
+ if provider in wanted)
+ if "f95zone" in wanted:
+ tasks.append("f95zone")
+ return tuple(tasks)
+
+
def discover(term: str, *, secrets_root: Path, state_root: Path,
shared_root: Path | None = None, transport=None,
- providers: tuple[str, ...] | None = None) -> Discovery:
+ providers: tuple[str, ...] | None = None,
+ on_progress=None) -> Discovery:
"""把一个裸 id 或名字拿去各来源问一遍。
只回**查到的**结果,每个都带上「为什么认为它命中」。查不到就是查不到,
不按命名规律拼一个看起来像的链接——那种猜测登记之后永远抓不到东西。
+ `on_progress(provider, index, total)` 在每个来源开查前调一次,供界面
+ 显示当前点名到哪一家;不传就不发。
"""
text = (term or "").strip()
if not text:
@@ -377,32 +404,34 @@ def discover(term: str, *, secrets_root: Path, state_root: Path,
credentials = credential_store_for(secrets_root, shared_root=shared_root)
index = CreatorIndex(state_root, transport=transport)
- wanted = providers or ("kemono", "coomer", "pawchive", "fanbox", "rule34video",
- "rule34xxx", "f95zone", "simpcity")
+ tasks = discovery_plan(text, providers)
found: list[Candidate] = []
failures: dict[str, str] = {}
external_searches: list[ExternalSearch] = []
def run(name: str, fn) -> None:
- if name not in wanted:
- return
try:
found.extend(fn())
except (FollowSourceError, CredentialError) as error:
failures[name] = str(error)
- for provider in ("kemono", "coomer", "pawchive"):
- run(provider, lambda provider=provider: _kemono_candidates(provider, text, index))
- run("fanbox", lambda: _fanbox_candidates(found, transport))
- if not _NUMERIC_RE.match(text):
- run("rule34video", lambda: _rule34video_candidates(text, transport))
- run("rule34xxx",
- lambda: _rule34xxx_candidates(text, transport,
- credentials.load("rule34xxx")))
- run("simpcity", lambda: _simpcity_candidates(text, transport,
- credentials.load("simpcity")))
- run("f95zone", lambda: _f95_candidates(text, transport,
- credentials.load("f95zone")))
- if "f95zone" in wanted and not any(row.provider == "f95zone" for row in found):
+ runners = {
+ "kemono": lambda: _kemono_candidates("kemono", text, index),
+ "coomer": lambda: _kemono_candidates("coomer", text, index),
+ "pawchive": lambda: _kemono_candidates("pawchive", text, index),
+ "fanbox": lambda: _fanbox_candidates(found, transport),
+ "rule34video": lambda: _rule34video_candidates(text, transport),
+ "rule34xxx": lambda: _rule34xxx_candidates(text, transport,
+ credentials.load("rule34xxx")),
+ "simpcity": lambda: _simpcity_candidates(text, transport,
+ credentials.load("simpcity")),
+ "f95zone": lambda: _f95_candidates(text, transport,
+ credentials.load("f95zone")),
+ }
+ for position, name in enumerate(tasks):
+ if on_progress:
+ on_progress(name, position, len(tasks))
+ run(name, runners[name])
+ if "f95zone" in tasks and not any(row.provider == "f95zone" for row in found):
external_searches.append(_f95_external_search(text))
return Discovery(text, tuple(found), failures, tuple(external_searches))
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index c47e7b54d..0ff510c41 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -19,7 +19,7 @@ import urllib.parse
from . import follow_assets, follow_providers
from .follow import FollowSourceError
from .follow_check import plan_check, run_check
-from .follow_discovery import discover
+from .follow_discovery import discover, discovery_plan
from .follow_secrets import (
CREDENTIAL_GUIDE, CredentialError, CredentialStore, credential_store_for,
)
@@ -1080,11 +1080,35 @@ def w_follow_resolve(contract, body, *, progress=None) -> dict:
known = {(row["provider"], canonical_source_ref(row["provider"], row["ref"])) for row in
(_source_payload(r) for r in _existing_sources(contract))}
+
+ # 进度按来源计,不按行计:一行检索词背后是十几个来源各查各的,
+ # 行数当分母只会整轮卡在 0% 然后跳满。计划先算一遍(不联网),
+ # 每行链接算 1 个单位,检索词行按 discovery_plan 的来源数算。
+ def plan_units(line: str) -> int:
+ try:
+ parse_source_url(line)
+ return 1
+ except FollowSourceError:
+ if "://" in line or "/" in line:
+ return 0
+ return len(discovery_plan(line))
+
+ total_units = sum(plan_units(line) for line in lines)
+ done_units = 0
+
+ def source_progress(line_index: int):
+ def note(provider: str, position: int, plan_total: int) -> None:
+ if progress is not None:
+ label = PROVIDER_LABELS.get(provider, provider)
+ progress(
+ checked=done_units + position, total=total_units,
+ message=f"查找关注来源:来源 {done_units + position + 1}/{total_units} · {label}"
+ + (f"(第 {line_index + 1}/{len(lines)} 行)" if len(lines) > 1 else ""))
+
+ return note
+
results = []
for index, line in enumerate(lines):
- if progress:
- progress(checked=index, total=len(lines),
- message=f"查找关注来源:已完成 {index} / {len(lines)} 行,正在解析第 {index + 1} 行")
try:
parsed = parse_source_url(line)
except FollowSourceError as url_error:
@@ -1095,7 +1119,8 @@ def w_follow_resolve(contract, body, *, progress=None) -> dict:
try:
found = discover(line, secrets_root=contract.follow_secrets_root,
shared_root=contract.follow_shared_root,
- state_root=contract.follow_state_root)
+ state_root=contract.follow_state_root,
+ on_progress=source_progress(index))
except (FollowSourceError, CredentialError) as term_error:
results.append({"line": line, "kind": "error", "error": str(term_error)})
continue
@@ -1109,11 +1134,13 @@ def w_follow_resolve(contract, body, *, progress=None) -> dict:
"external_searches": [_external_search_payload(search)
for search in found.external_searches],
})
+ done_units += len(discovery_plan(line))
continue
results.append({"line": line, "kind": "url",
"candidates": [{**_candidate_payload(parsed),
"known": (parsed.provider, canonical_source_ref(
parsed.provider, parsed.ref)) in known}]})
+ done_units += 1
return {"ok": True, "results": results}
diff --git a/tests/test_follow_discovery.py b/tests/test_follow_discovery.py
index 7ddea5a8e..cf1c299aa 100644
--- a/tests/test_follow_discovery.py
+++ b/tests/test_follow_discovery.py
@@ -7,8 +7,8 @@ from pathlib import Path
from peach.follow import FollowSourceError
from peach.follow_discovery import (
- CREATOR_INDEX_TTL_SECONDS, CreatorIndex, discover, identity_key,
- search_variants, spelling_variants,
+ CREATOR_INDEX_TTL_SECONDS, DEFAULT_PROVIDERS, CreatorIndex, discover,
+ discovery_plan, identity_key, search_variants, spelling_variants,
)
from peach.follow_secrets import CredentialError
from peach.http import HttpResponse
@@ -98,6 +98,21 @@ class SearchVariantTests(unittest.TestCase):
self.assertEqual(spelling_variants("Ria_neearts"),
("Ria_neearts", "Ria-neearts", "Rianeearts", "Ria neearts"))
+
+class DiscoveryPlanTests(unittest.TestCase):
+ def test_a_handle_includes_the_name_searching_sources(self):
+ tasks = discovery_plan("suzutaro3d")
+ self.assertEqual(tasks, DEFAULT_PROVIDERS)
+
+ def test_a_numeric_word_skips_the_name_searching_sources(self):
+ tasks = discovery_plan("30917150")
+ for skipped in ("rule34video", "rule34xxx", "simpcity"):
+ self.assertNotIn(skipped, tasks)
+
+ def test_a_restricted_provider_paid_respects_the_selection(self):
+ self.assertEqual(discovery_plan("Lazy", providers=("kemono",)),
+ ("kemono",))
+
def test_a_handle_without_separators_has_only_itself(self):
self.assertEqual(spelling_variants("lazyprocrastinator"), ("lazyprocrastinator",))
@@ -154,6 +169,15 @@ class DiscoverTests(_DiscoveryCase):
self.assertEqual(by_provider["rule34video"].ref, "lazyprocrastinator")
self.assertEqual(by_provider["f95zone"].ref, "50685")
+ def test_each_source_reports_itself_before_it_runs(self):
+ notes = []
+ found = discover("LazyProcrastinator", secrets_root=self.secrets,
+ state_root=self.state, transport=_router(self.ROUTES),
+ providers=("kemono", "fanbox"),
+ on_progress=lambda *args: notes.append(args))
+ self.assertEqual(notes, [("kemono", 0, 2), ("fanbox", 1, 2)])
+ self.assertTrue(found.candidates)
+
def test_every_candidate_says_why_it_matched(self):
found = self._discover("LazyProcrastinator", self.ROUTES,
providers=("kemono", "rule34video", "f95zone"))
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 35e6b7ae5..1da1f67af 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -1273,6 +1273,25 @@ class FollowSourceAddTests(FollowContractTests):
"evidence": "链接直接指明", "known": False,
}])
+ def test_resolve_progress_counts_sources_instead_of_lines(self):
+ """一行的背后是十几个来源在查:进度按来源数走,环才会逐个涨过去。"""
+ ticks = []
+
+ def fake_discover(line, **kwargs):
+ note = kwargs["on_progress"]
+ note("kemono", 0, 8)
+ note("f95zone", 7, 8)
+ return Discovery(line, external_searches=())
+
+ with mock.patch.object(web_follow, "discover", side_effect=fake_discover):
+ web_follow.w_follow_resolve(self.contract, {
+ "lines": ["suzutaro3d", "https://kemono.cr/fanbox/user/30917150"],
+ }, progress=lambda **fields: ticks.append(fields))
+ self.assertEqual([tick["checked"] for tick in ticks], [0, 7])
+ self.assertTrue(all(tick["total"] == 9 for tick in ticks))
+ self.assertIn("Kemono", ticks[0]["message"])
+ self.assertIn("F95zone", ticks[1]["message"])
+
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/")
diff --git a/web/css/22-followmanage.css b/web/css/22-followmanage.css
index 4d70ec28b..4094499c0 100644
--- a/web/css/22-followmanage.css
+++ b/web/css/22-followmanage.css
@@ -224,9 +224,10 @@ th[aria-sort="ascending"] .ftsort svg,th[aria-sort="descending"] .ftsort svg{opa
`--border-10` 配 `--surface` 会让它在同一列里比 `.fsec` 亮一档、边又淡一档,
读起来像另一种东西浮在页面上。 */
.followtask{border:1px solid var(--field-ring);border-radius:var(--surface-radius);background:var(--ground);margin-bottom:16px}
-/* 进度卡常住在说明行(data-follow-add-state 是 p.fnote)里,说明色不许往里灌:
- 任务标签要与正文同色可读,百分比那行保留 board 自己的更淡小字。 */
-p.fnote>.followtask{color:var(--ink-2)}
+/* 进度卡常住在说明行(data-follow-add-state 是 p.fnote)的 data-follow-job
+ 挂载层里,说明的字号与颜色不许往里面灌:任务标签与正文同色可读,
+ 百分比那行保留 board 自己的更淡小字。 */
+p.fnote .followtask{color:var(--ink-2)}
.followtask>.geist-fieldset-content{padding:20px;min-width:0;overflow-wrap:anywhere}
.followmanage .followtask{margin-bottom:0}
.fcheckfail strong{font-weight:600}