Peach: Local-first video metadata scraper and media manager.
fix(web): 完善收藏与来源契约及窄屏控件定位
longmeidao2b9c0fa72508
diff --git a/frontend/e2e/card-layout.test.ts b/frontend/e2e/card-layout.test.tsindex 01982e275..30051523a 100644--- a/frontend/e2e/card-layout.test.ts+++ b/frontend/e2e/card-layout.test.ts@@ -105,6 +105,11 @@ describe('混排作品的画面框',()=>{card:Math.round(node.querySelector('[data-media-card]')!.getBoundingClientRect().right),page:document.documentElement.scrollWidth,view:document.documentElement.clientWidth,+ overflow:[...document.querySelectorAll('body *')].filter(element=>{+ const rect=element.getBoundingClientRect();+ if(rect.right<=document.documentElement.clientWidth||rect.width===0)return false;+ return true;+ }).slice(0,30).map(element=>({tag:element.tagName,attrs:[...element.attributes].map(a=>`${a.name}=${a.value}`).join(' '),right:Math.round(element.getBoundingClientRect().right)})),}));assert.ok(box.right<=box.view&&box.card<=box.view&&box.page<=box.view,JSON.stringify(box));}finally{await context.close()}diff --git a/frontend/src/react/components/segmented.tsx b/frontend/src/react/components/segmented.tsxindex 882c3d6de..a64184677 100644--- a/frontend/src/react/components/segmented.tsx+++ b/frontend/src/react/components/segmented.tsx@@ -46,6 +46,6 @@ export const SEGMENT_ICON = 'flex size-7 flex-none cursor-pointer items-center j* 六成,选中那一格换成浮层选中态那块玻璃(`../styles.css` 的 `[data-glass-segment]`)。 */export const SEGMENTED_GLASS_TRACK = 'inline-flex w-max max-w-full flex-none items-center gap-0.5 rounded-lg';-export const SEGMENT_GLASS = 'flex size-7.5 flex-none cursor-pointer items-center justify-center rounded-lg'+export const SEGMENT_GLASS = 'relative flex size-7.5 flex-none cursor-pointer items-center justify-center rounded-lg'+ ' text-(--glass-text)/62 outline-none transition-colors hover:text-(--glass-text)'+ ' focus-visible:ring-2 focus-visible:ring-border-focus-ring data-selected:text-(--glass-text)';diff --git a/src/peach/library_diagnostics.py b/src/peach/library_diagnostics.pyindex 74d30ac0f..4378bff40 100644--- a/src/peach/library_diagnostics.py+++ b/src/peach/library_diagnostics.py@@ -114,6 +114,29 @@ def library(settings, config):return {"groups": groups, "issue_at": issue_at}+SOURCE_CHECK_REASONS = {+ "proxy": "代理连接失败", "timeout": "来源连接超时", "network": "来源连接未取得",+ "auth_required": "来源要求登录或拒绝当前出口", "cloudflare_challenge": "来源要求人机验证",+ "cloudflare_blocked": "来源拦截当前出口", "ip_banned": "来源拦截当前出口",+ "geo_restricted": "来源限制当前地区", "rate_limited": "来源正在限流",+ "server_error": "来源服务异常", "parse_error": "资料解析失败",+ "not_found": "上次查询未命中", "cooldown": "来源正在冷却",+}+++def _source_health(cooling, failed, fresh, recent, connection_ok, reason_key):+ """来源诊断优先报告冷却与失败,再报告解析和连接证据。"""+ if cooling:+ return "warning", "来源正在冷却"+ if failed:+ return "warning", SOURCE_CHECK_REASONS.get(reason_key, "来源未取得资料")+ if fresh:+ return "ok", "资料解析通过"+ if recent and connection_ok:+ return "unknown", "连接检查通过;解析状态未取得"+ return "unknown", "当前解析状态未取得"++def sources(settings, config, *, now=None):now = time.time() if now is None else nowsuccess = {"minnano-av": None, "javdb": None}@@ -154,18 +177,10 @@ def sources(settings, config, *, now=None):key=lambda check: check["checked_at"], default={})recent = 0 <= now - float(last.get("checked_at", 0)) <= 86400reason_key = last.get("reason", "") if recent else ""- reasons = {"proxy": "代理连接失败", "timeout": "来源连接超时", "network": "来源连接未取得",- "auth_required": "来源要求登录或拒绝当前出口", "cloudflare_challenge": "来源要求人机验证",- "cloudflare_blocked": "来源拦截当前出口", "ip_banned": "来源拦截当前出口",- "geo_restricted": "来源限制当前地区", "rate_limited": "来源正在限流",- "server_error": "来源服务异常", "parse_error": "资料解析失败",- "not_found": "上次查询未命中", "cooldown": "来源正在冷却"}failed = recent and not last.get("ok") and reason_key != "not_found"- reason = ("来源正在冷却" if cooling else reasons.get(reason_key, "来源未取得资料") if failed- else "资料解析通过" if fresh else "连接检查通过;解析状态未取得" if recent and connection.get("ok")- else "当前解析状态未取得")+ status, reason = _source_health(cooling, failed, fresh, recent, connection.get("ok"), reason_key)result.append({"source": key, "label": SOURCES[key]["label"],- "status": "warning" if cooling or failed else "ok" if fresh else "unknown",+ "status": status,"reason": reason, "last_check_at": timestamp(last.get("checked_at")),"elapsed_s": last.get("elapsed_s"), "last_success_at": stamp,"cooldown_until": datetime.fromtimestamp(until, timezone.utc).isoformat() if cooling else None})diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex 78708892e..0433ef588 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -533,6 +533,15 @@ def _attach_index_following(connection, rows: list[dict]) -> None:row['following'] = row['entity_id'] in following+def _attach_index_favorites(connection, rows: list[dict]) -> None:+ """按规范实体身份附加名册收藏状态。"""+ from .web_library_shortcuts import favorite_ids++ favorites = favorite_ids(connection)+ for row in rows:+ row["favorite"] = row.get("entity_id") in favorites++def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category=""):"""全部艺人 / 创作者 / 厂牌 / 事务所 / 标签的索引页数据。"""with contract.read_connection() as c:@@ -626,10 +635,7 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")all_rows = [row for row in all_rows if row["cat"] == category]rows = all_rows[offset:offset + limit]has_more = offset + limit < len(all_rows)- from .web_library_shortcuts import favorite_ids- favorites = favorite_ids(c)- for row in rows:- row["favorite"] = row.get("entity_id") in favorites+ _attach_index_favorites(c, rows)if kind in INDEX_ENTITY_KINDS:entity_kind = INDEX_ENTITY_KINDS[kind]# 索引页一屏几十个圆头像,走的是和顶栏那排同一条两级链:规范实体图优先,diff --git a/src/peach/web_scraping.py b/src/peach/web_scraping.pyindex c446435bb..c94094340 100644--- a/src/peach/web_scraping.py+++ b/src/peach/web_scraping.py@@ -158,8 +158,39 @@ def w_scraping_settings(contract, body):return {"ok": True, "saved": save(contract.follow_secrets_root, str(body.get("source", "")), body)}+def _connection_failure(exc, label):+ """来源连接异常对应可操作的诊断说明。"""+ if isinstance(exc, SourcePaused):+ detail, message = "cooldown", "来源正在冷却,请稍后重试。"+ elif isinstance(exc, httpx.ProxyError):+ detail, message = "proxy", "代理连接失败,请检查 Peach 代理。"+ elif isinstance(exc, httpx.TimeoutException):+ detail, message = "timeout", "来源连接超时,请稍后重试或检查连接方式。"+ else:+ detail = "network"+ message = (f"连接未取得;{MOBILE_BROADBAND_HINT}" if label == "高清图片 CDN"+ else "连接未取得;此来源可能需要代理,请检查来源连接方式。")+ return {"ok": False, "kind": "unavailable", "reason": detail,+ "message": message, "error_type": type(exc).__name__}+++def _connection_message(detail, reason):+ """来源响应的失败原因决定用户下一步操作。"""+ from .metadata import reason_blames_credentials++ if detail == "cloudflare_challenge":+ return "来源返回人机验证页,请检查来源验证状态或更换出口。"+ if detail == "rate_limited":+ return "来源正在限流,请稍后重试。"+ if detail == "not_found":+ return "来源检查地址不存在,请核对站点地址。"+ if reason_blames_credentials(reason):+ return "来源要求登录或验证,请在官网完成登录后重试。"+ return f"{reason}。" if reason else "来源暂不可用,请稍后重试。"++def w_scraping_check(contract, body):- from .metadata import auth_wall_reason, reason_blames_credentials+ from .metadata import auth_wall_reasonsource = str(body.get("source", ""))if source not in SOURCES:raise ValueError("未知采集来源")@@ -205,28 +236,9 @@ def w_scraping_check(contract, body):# 成因锁死在凭据上才让人去登录。只剩状态码可看的 403 直接把# `auth_wall_reason` 那句原样给用户:出口 IP 被封时登录是白做,# 页面上再手写一份「请去登录」等于把人引去做错事。- if challenge:- result["message"] = "来源返回人机验证页,请检查来源验证状态或更换出口。"- elif detail == "rate_limited":- result["message"] = "来源正在限流,请稍后重试。"- elif detail == "not_found":- result["message"] = "来源检查地址不存在,请核对站点地址。"- elif reason_blames_credentials(reason):- result["message"] = "来源要求登录或验证,请在官网完成登录后重试。"- else:- result["message"] = f"{reason}。" if reason else "来源暂不可用,请稍后重试。"+ result["message"] = _connection_message(detail, reason)except Exception as exc:- detail = ("cooldown" if isinstance(exc, SourcePaused)- else "proxy" if isinstance(exc, httpx.ProxyError)- else "timeout" if isinstance(exc, httpx.TimeoutException) else "network")- result.update(ok=False, kind="unavailable",- reason=detail,- message=("来源正在冷却,请稍后重试。" if detail == "cooldown"- else "代理连接失败,请检查 Peach 代理。" if detail == "proxy"- else "来源连接超时,请稍后重试或检查连接方式。" if detail == "timeout"- else f"连接未取得;{MOBILE_BROADBAND_HINT}" if label == "高清图片 CDN"- else "连接未取得;此来源可能需要代理,请检查来源连接方式。"),- error_type=type(exc).__name__)+ result.update(_connection_failure(exc, label))result.update(checked_at=time.time(), elapsed_s=round(time.monotonic() - started, 2))if label == "来源页面":record_source_check(contract.follow_secrets_root, source, "connection", result)diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex f01d2db58..6e39cfbf8 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -2924,6 +2924,10 @@ PUBLIC_ROUTES = {# 是独立共享密钥(ADR-0041)。这一条因此不挂 require_*,但自己有三道门:通道没开、# 来源不在回环与私网、密钥对不上,任意一条不成立都回 404,见 `test_push_discovery`。("POST", "/api/inbox/clouddrive"),+ # 外部播放器没有浏览器会话;两条路由各自验证进程密钥签发的限时 HMAC,+ # 绑定单个资产与公开 Origin,验证后仍逐次检查媒体根目录。+ ("GET,HEAD", "/external-stream/{id}"),+ ("GET", "/external-playlist/{id}.m3u"),}diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 946d2e076..0102364f7 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -1131,6 +1131,7 @@ class WebDataTests(unittest.TestCase):"/api/search-history", "/api/review", "/api/playlists", "/api/playlist","/api/post-setup-tutorial","/api/library-shortcuts",+ "/api/custom-metadata","/api/follow", "/api/follow/credentials", "/api/follow/schedule","/api/follow/check", "/api/follow/resolve", "/api/follow/suggest","/api/taste/refresh",@@ -1150,6 +1151,7 @@ class WebDataTests(unittest.TestCase):"/api/activity", "/api/play", "/api/feedback", "/api/watch-later","/api/playlist","/api/library-shortcuts",+ "/api/custom-metadata","/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch","/api/search-history", "/api/trash/empty","/api/review/decision", "/api/review/genre",diff --git a/tests/test_studio_name_variant_merge.py b/tests/test_studio_name_variant_merge.pyindex a478a1a3a..fdafcb6af 100644--- a/tests/test_studio_name_variant_merge.py+++ b/tests/test_studio_name_variant_merge.py@@ -296,6 +296,7 @@ class ApplyTests(unittest.TestCase):self.connection.executescript("CREATE TABLE entity(id INTEGER PRIMARY KEY, kind TEXT, canonical_name TEXT,"" normalized_name TEXT, updated_at TEXT);"+ "CREATE TABLE profile(id INTEGER PRIMARY KEY, settings_json TEXT DEFAULT '{}', updated_at TEXT);""CREATE TABLE entity_alias(entity_id INTEGER, alias TEXT,"" normalized_alias TEXT, source TEXT, confidence REAL,"" UNIQUE(entity_id, normalized_alias));"diff --git a/tests/test_tag_renames.py b/tests/test_tag_renames.pyindex c483667a0..459908340 100644--- a/tests/test_tag_renames.py+++ b/tests/test_tag_renames.py@@ -18,6 +18,7 @@ _spec.loader.exec_module(_script)SCHEMA = """CREATE TABLE asset(id INTEGER PRIMARY KEY, location TEXT, path TEXT, name TEXT);+CREATE TABLE profile(id INTEGER PRIMARY KEY, settings_json TEXT DEFAULT '{}', updated_at TEXT);CREATE TABLE asset_tag(asset_id INTEGER, tag TEXT, confidence REAL DEFAULT 1.0, source TEXT,UNIQUE(asset_id,tag));diff --git a/web/dist/peach-app.js b/web/dist/peach-app.jsindex 4490ec6eb..c3a1acea3 100644--- a/web/dist/peach-app.js+++ b/web/dist/peach-app.js@@ -38999,7 +38999,7 @@ function Jj(e) {ref: t});}-var Yj = "inline-flex w-max max-w-full items-center gap-0.5 overflow-x-auto overscroll-x-contain rounded-2lg bg-background-tertiary-default p-1", Xj = "flex min-h-7 flex-none cursor-pointer items-center gap-1.5 rounded-md px-2.5 py-1 max-sm:px-2 text-body-medium whitespace-nowrap text-text-secondary outline-none transition-colors hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring data-focus-visible:ring-2 data-focus-visible:ring-border-focus-ring data-selected:bg-background-primary-default data-selected:text-text-primary data-selected:shadow-card dark:data-selected:bg-background-primary-hover", Bge = "flex size-7 flex-none cursor-pointer items-center justify-center rounded-md text-text-secondary outline-none transition-colors hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring data-focus-visible:ring-2 data-focus-visible:ring-border-focus-ring data-selected:bg-background-primary-default data-selected:text-text-primary data-selected:shadow-card dark:data-selected:bg-background-primary-hover", Zj = "inline-flex w-max max-w-full flex-none items-center gap-0.5 rounded-lg", Qj = "flex size-7.5 flex-none cursor-pointer items-center justify-center rounded-lg text-(--glass-text)/62 outline-none transition-colors hover:text-(--glass-text) focus-visible:ring-2 focus-visible:ring-border-focus-ring data-selected:text-(--glass-text)", $j = (e) => typeof e == "string" ? e : "", eM = (e) => e.aliases;+var Yj = "inline-flex w-max max-w-full items-center gap-0.5 overflow-x-auto overscroll-x-contain rounded-2lg bg-background-tertiary-default p-1", Xj = "flex min-h-7 flex-none cursor-pointer items-center gap-1.5 rounded-md px-2.5 py-1 max-sm:px-2 text-body-medium whitespace-nowrap text-text-secondary outline-none transition-colors hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring data-focus-visible:ring-2 data-focus-visible:ring-border-focus-ring data-selected:bg-background-primary-default data-selected:text-text-primary data-selected:shadow-card dark:data-selected:bg-background-primary-hover", Bge = "flex size-7 flex-none cursor-pointer items-center justify-center rounded-md text-text-secondary outline-none transition-colors hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring data-focus-visible:ring-2 data-focus-visible:ring-border-focus-ring data-selected:bg-background-primary-default data-selected:text-text-primary data-selected:shadow-card dark:data-selected:bg-background-primary-hover", Zj = "inline-flex w-max max-w-full flex-none items-center gap-0.5 rounded-lg", Qj = "relative flex size-7.5 flex-none cursor-pointer items-center justify-center rounded-lg text-(--glass-text)/62 outline-none transition-colors hover:text-(--glass-text) focus-visible:ring-2 focus-visible:ring-border-focus-ring data-selected:text-(--glass-text)", $j = (e) => typeof e == "string" ? e : "", eM = (e) => e.aliases;function tM(e, t = "") {let n = Rr(e);return n ? `<img data-follow-site-icon="" src="${n}" alt="${R(t)}"${t ? ` title="${R(t)}"` : ""} loading="lazy" data-drop="self">` : "";