Peach: Local-first video metadata scraper and media manager.
feat(web): 外部入口改成只配镜像域名
longmeidao7161f139e7d9
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.tsindex 73ad1ee20..6dd483e0a 100644--- a/frontend/src/react/bundle.d.ts+++ b/frontend/src/react/bundle.d.ts@@ -37,14 +37,13 @@ export interface UninstallState {export interface PeachProxyState { mode: string; proxy_saved: boolean; needs_selection: boolean }-/** 人物资料页上的一枚外部入口。`placeholder` 是这一站的模板里该填的那个占位符。 */+/** 人物资料页上的一枚外部入口。只此一家的站点 `host` 与 `default_host` 都是 null。 */export interface EntryLinkSite {key: string;label: string;- placeholder: string;enabled: boolean;- template: string;- default_template: string;+ host: string | null;+ default_host: string | null;}export interface EntryLinksState { sites: EntryLinkSite[] }diff --git a/frontend/src/react/settings/entry-links-settings.tsx b/frontend/src/react/settings/entry-links-settings.tsxindex 77d11a4c1..68b2f1ba2 100644--- a/frontend/src/react/settings/entry-links-settings.tsx+++ b/frontend/src/react/settings/entry-links-settings.tsx@@ -1,8 +1,8 @@/* 「外部入口」:人物资料页上通向 みんなのAV、JavDB 与 MISSAV 的那三枚直达入口。*- * 每站一个开关加一条地址模板。地址由服务端拼(`peach.entry_links`),这一页交的只是- * 模板本身——站点 id 与规范名都在账本里,前端拿不到也不该拿。模板里的占位符由服务端- * 按站点给(`{javdb_id}`、`{minnano_id}`、`{name}`),所以提示里直接写它那一个。+ * 每站一个开关;JavDB 与 MISSAV 多一个镜像域名框,这两站主域名连不上时在这里换。地址+ * 由服务端拼(`peach.entry_links`),路径与占位符都在它那边——站点 id 与规范名都在账本+ * 里,前端拿不到也不该拿。`host` 是 null 的站点没有镜像可换,只画开关。** 校验也只在服务端:哪种地址算得上一条入口是它说了算,前端复制一份判定只会漂。 */import { useState, type FormEvent } from 'react';@@ -31,7 +31,8 @@ export function EntryLinksForm({ initial, receipt }: {event.preventDefault();const body = {sites: Object.fromEntries(sites.map((site) =>- [site.key, { enabled: site.enabled, template: site.template }])),+ [site.key, site.host === null ? { enabled: site.enabled }+ : { enabled: site.enabled, host: site.host }])),};void action.run('save', (signal) =>apiSend<EntryLinksState>('/api/configuration/entry-links', body, 'POST', signal),@@ -55,13 +56,14 @@ export function EntryLinksForm({ initial, receipt }: {<Stack divided><Help>账本里没有这个站点 id 的人物不显示它那一枚入口,地址不会退回站内搜索。JavDB 与 MISSAV 只收 JAV 女优,这两枚还要账本里有哪个 JAV 目录站给过她 id 才出现;- FC2 个人摄那类创作者没有这种 id,资料页上也就没有这一行。</Help>- {sites.map((site) => (- <Input key={site.key} id={`entry-link-${site.key}`} label={`${site.label} 地址模板`}- autoComplete="off" maxLength={300} value={site.template}- onChange={(template) => change(site.key, { template })}+ FC2 个人摄那类创作者没有这种 id,资料页上也就没有这一行。+ 这两站的主域名连不上时,把能打开的那个镜像域名填在下面,后面的路径由 Peach 自己拼。</Help>+ {sites.filter((site) => site.host !== null).map((site) => (+ <Input key={site.key} id={`entry-link-${site.key}`} label={`${site.label} 镜像域名`}+ autoComplete="off" maxLength={100} value={site.host ?? ''}+ onChange={(host) => change(site.key, { host })}validationBehavior="aria"- hint={`用 {${site.placeholder}} 占位,默认 ${site.default_template}`} />+ hint={`只写域名本身,默认 ${site.default_host}`} />))}{action.error ? <ErrorText>{action.error}</ErrorText> : null}</Stack>diff --git a/frontend/test/react/entry-links.test.tsx b/frontend/test/react/entry-links.test.tsxindex 6ccad7624..8211b41bd 100644--- a/frontend/test/react/entry-links.test.tsx+++ b/frontend/test/react/entry-links.test.tsx@@ -10,19 +10,13 @@ const data = (over: Partial<ConfigurationData> = {}): ConfigurationData => ({const state: EntryLinksState = {sites: [- { key: 'javdb', label: 'JavDB', placeholder: 'javdb_id', enabled: true,- template: 'https://javdb.com/actors/{javdb_id}?sort_type=4',- default_template: 'https://javdb.com/actors/{javdb_id}?sort_type=4' },- { key: 'minnano-av', label: 'minnano-av', placeholder: 'minnano_id', enabled: true,- template: 'https://www.minnano-av.com/actress{minnano_id}.html',- default_template: 'https://www.minnano-av.com/actress{minnano_id}.html' },- { key: 'missav', label: 'MISSAV', placeholder: 'name', enabled: false,- template: 'https://missav.ws/dm42/cn/actresses/{name}',- default_template: 'https://missav.ws/dm42/cn/actresses/{name}' },+ { key: 'javdb', label: 'JavDB', enabled: true, host: 'javdb.com', default_host: 'javdb.com' },+ { key: 'minnano-av', label: 'minnano-av', enabled: true, host: null, default_host: null },+ { key: 'missav', label: 'MISSAV', enabled: false, host: 'missav.ws', default_host: 'missav.ws' },],};-it('外部入口:三站各一颗开关与一条模板,保存发出开关与模板的实际值', async () => {+it('外部入口:三站各一颗开关,有镜像的两站各一个域名框,保存发出实际值', async () => {const fetcher = fetchMock(200, state);vi.stubGlobal('fetch', fetcher);const receipt = vi.fn();@@ -30,21 +24,20 @@ it('外部入口:三站各一颗开关与一条模板,保存发出开关与expect(switches(host).map((input) => input.getAttribute('aria-label'))).toEqual(['在资料页显示 JavDB 入口', '在资料页显示 minnano-av 入口', '在资料页显示 MISSAV 入口']);expect(switches(host).map((input) => input.checked)).toEqual([true, true, false]);- // 占位符按站给:提示里写错一个,改模板的人就会把服务端填不进去的名字写进地址。- expect(host.textContent).toContain('用 {javdb_id} 占位');- expect(host.textContent).toContain('用 {name} 占位');+ // みんなのAV 只此一家,没有域名可换,那一行就不该出现一个填了也没用的框。+ expect(host.querySelector('#entry-link-minnano-av')).toBeNull();+ expect(host.textContent).toContain('只写域名本身,默认 javdb.com');await click(switches(host)[2]);- await type(host.querySelector('#entry-link-minnano-av'),- 'https://www.minnano-av.com/actress{minnano_id}.html?x=1');+ await type(host.querySelector('#entry-link-javdb'), 'javdb521.com');expect(fetcher).not.toHaveBeenCalled();await submit(host.querySelector('form'));await settle();expect(fetcher.mock.calls[0]?.[0]).toBe('/api/configuration/entry-links');expect(sentBody(fetcher)).toEqual({sites: {- javdb: { enabled: true, template: 'https://javdb.com/actors/{javdb_id}?sort_type=4' },- 'minnano-av': { enabled: true, template: 'https://www.minnano-av.com/actress{minnano_id}.html?x=1' },- missav: { enabled: true, template: 'https://missav.ws/dm42/cn/actresses/{name}' },+ javdb: { enabled: true, host: 'javdb521.com' },+ 'minnano-av': { enabled: true },+ missav: { enabled: true, host: 'missav.ws' },},});expect(receipt).toHaveBeenCalledWith('已保存配置');diff --git a/src/peach/config.py b/src/peach/config.pyindex 78e91f9d8..533fd6c0f 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -141,5 +141,5 @@ class PeachSettings:taste_history_manifest: Path = STATE_DIR / "taste-history" / "manifest.json"# 自动追更频率是本机运行偏好,不属于 ledger 真相。follow_state_root: Path = STATE_DIR- # 人物页外部入口的开关与地址模板,同样是本机偏好。+ # 人物页外部入口的开关与镜像域名,同样是本机偏好。entry_links_root: Path = STATE_DIRdiff --git a/src/peach/entry_links.py b/src/peach/entry_links.pyindex a228d3277..4267d4661 100644--- a/src/peach/entry_links.py+++ b/src/peach/entry_links.py@@ -1,4 +1,4 @@-"""人物资料页的外部入口:几个站点的直达地址,以及它们的本机开关与模板。+"""人物资料页的外部入口:几个站点的直达地址,以及它们的本机开关与镜像域名。入口只由后端拼:地址要用的东西都在服务端——`entity_external_ref` 里的站点 id、`entity.canonical_name` 和 `entity_alias`。前端拿到的是一串带位置与标记的@@ -30,10 +30,16 @@**两种位置。** minnano-av 是一份资料页,和事务所官网、社媒是同一类东西,所以它排进上面那排链接里。JavDB 与 MISSAV 是「去看片」的入口,另起一行,用两站自己的标识。++**能改的只有域名。** JavDB 与 MISSAV 各有一排可换的镜像域名,主域名连不上时得跟着换,+所以配置页给这两站各留一个域名框;路径与占位符都由这里定死。整条模板不交给使用者填:+占位符写错换来的是一排看着正常、点开全是 404 的入口,而域名对不对点一次就知道。+みんなのAV 只此一家,它那一行只有开关。"""from __future__ import annotationsimport json+import refrom dataclasses import dataclassfrom pathlib import Pathfrom urllib.parse import quote@@ -65,6 +71,7 @@ class EntrySite:`provider` 空串表示这一站按名字拼,不需要账本里的 id。`label` 是页面上那枚入口的可读名字,`title` 是配置页和报错里的站点名。`mark` 是雪碧图里那枚标记的名字;MISSAV 没有可用的图形标识,它的 `mark` 是空串,由前端按站点自己的排版规则排字。+ `host` 是默认域名,`mirrored` 说这一站能不能在配置页换域名。"""key: str@@ -72,30 +79,32 @@ class EntrySite:title: strplaceholder: strprovider: str- template: str+ host: str+ path: strslot: strmark: strjav_only: bool = False+ mirrored: bool = FalseSITES: tuple[EntrySite, ...] = (# 页面上写站点自己的名字「みんなのAV」,取自它官网的 title;`minnano-av` 是域名和# 账本里的 provider,留给设置项的 key 与 `entity_external_ref` 用。EntrySite("minnano-av", "みんなのAV", "みんなのAV", "minnano_id", "minnano-av",- "https://www.minnano-av.com/actress{minnano_id}.html",+ "www.minnano-av.com", "/actress{minnano_id}.html",SLOT_PILL, "brand-minnano"),- # javdb 的演员页就是作品列表,`sort_type=4` 只是把它按发行日期排;两条地址落在同一页,- # 所以只留这一条,按用户平时点的那个排序走。EntrySite("javdb", "JavDB", "JavDB", "javdb_id", "javdb",- "https://javdb.com/actors/{javdb_id}?sort_type=4",- SLOT_MARK, "mark-javdb", jav_only=True),+ "javdb.com", "/actors/{javdb_id}",+ SLOT_MARK, "mark-javdb", jav_only=True, mirrored=True),EntrySite("missav", "MISSAV", "MISSAV", "name", "",- "https://missav.ws/cn/actresses/{name}",- SLOT_MARK, "", jav_only=True),+ "missav.ws", "/cn/actresses/{name}",+ SLOT_MARK, "", jav_only=True, mirrored=True),)_BY_KEY = {site.key: site for site in SITES}-#: 模板长度上限。地址栏塞得下的东西远不止这个数,但入口模板只有一个占位符要填。-_TEMPLATE_LIMIT = 300+#: 域名长度上限与形状。只认域名本身:字母数字、连字符和点,至少一个点。+_HOST_LIMIT = 100+_HOST_SHAPE = re.compile(r"[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?"+ r"(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+")#: 第二枚起的序号。用完退回括号数字,标签宁可长一点也不能两枚长得一模一样。_ORDINALS = "②③④⑤⑥⑦⑧⑨"#: 艺名类的别名来源。按子串认:来源串后面还挂着采集批次。@@ -103,8 +112,8 @@ _STAGE_NAME_SOURCES = ("avdb-actor-mapping", "javdb", "wiki")def defaults() -> dict:- """各站全开,模板即上面那几条。"""- return {site.key: {"enabled": True, "template": site.template} for site in SITES}+ """各站全开,域名即上面那几条。"""+ return {site.key: {"enabled": True, "host": site.host} for site in SITES}def _clean(saved: object) -> dict:@@ -119,9 +128,9 @@ def _clean(saved: object) -> dict:continueif isinstance(value.get("enabled"), bool):result[site.key]["enabled"] = value["enabled"]- template = value.get("template")- if isinstance(template, str) and _template_problem(site, template.strip()) == "":- result[site.key]["template"] = template.strip()+ host = _tidy_host(value.get("host"))+ if site.mirrored and _host_problem(site, host) == "":+ result[site.key]["host"] = hostreturn result@@ -134,41 +143,47 @@ def read(root: Path) -> dict:def snapshot(root: Path) -> dict:- """配置页要的形状:每站一行,带站名、占位符和可恢复的默认模板。"""+ """配置页要的形状:每站一行;能换域名的多给当前域名和可恢复的默认值。"""saved = read(root)return {"sites": [{"key": site.key,"label": site.title,- "placeholder": site.placeholder,"enabled": saved[site.key]["enabled"],- "template": saved[site.key]["template"],- "default_template": site.template,+ "host": saved[site.key]["host"] if site.mirrored else None,+ "default_host": site.host if site.mirrored else None,} for site in SITES]}-def _template_problem(site: EntrySite, template: str) -> str:- """模板不能用时的那一句原因;能用时是空串。"""- mark = "{" + site.placeholder + "}"- if not template:- return f"{site.title} 的地址模板不能为空"- if len(template) > _TEMPLATE_LIMIT:- return f"{site.title} 的地址模板请控制在 {_TEMPLATE_LIMIT} 个字符以内"- if any(char.isspace() for char in template):- return f"{site.title} 的地址模板里不能有空格"- if not template.startswith("https://"):- return f"{site.title} 的地址模板要以 https:// 开头"- if template.count(mark) != 1:- return f"{site.title} 的地址模板要且只要一个 {mark}"- if template.replace(mark, "").count("{") or template.replace(mark, "").count("}"):- return f"{site.title} 的地址模板里只认 {mark} 这一个占位符"+def _tidy_host(written: object) -> str:+ """把填进来的东西收成域名。++ 镜像地址多半是从别处整条复制过来的,带着 `https://` 和结尾的斜杠。这两样去掉就是+ 合法的域名,为它们弹一条错误只是让人手工删一遍。再往后的路径不收:那是在改地址+ 形状,不是换域名。+ """+ host = str(written or "").strip()+ for scheme in ("https://", "http://"):+ if host.lower().startswith(scheme):+ host = host[len(scheme):]+ return host.rstrip("/")+++def _host_problem(site: EntrySite, host: str) -> str:+ """域名不能用时的那一句原因;能用时是空串。"""+ if not host:+ return f"{site.title} 的镜像域名不能为空"+ if len(host) > _HOST_LIMIT:+ return f"{site.title} 的镜像域名请控制在 {_HOST_LIMIT} 个字符以内"+ if not _HOST_SHAPE.fullmatch(host):+ return f"{site.title} 这里只写域名本身,像 {site.host}"return ""def save(root: Path, body: dict) -> dict:- """写回各站的开关与模板。任一项不合规就整批不写。"""+ """写回各站的开关与镜像域名。任一项不合规就整批不写。"""rows = body.get("sites")if not isinstance(rows, dict):- raise ValueError("请提交每个站点的开关与地址模板")+ raise ValueError("请提交每个站点的开关与镜像域名")result = defaults()for site in SITES:row = rows.get(site.key)@@ -176,13 +191,16 @@ def save(root: Path, body: dict) -> dict:raise ValueError(f"缺少 {site.title} 的设置")if not isinstance(row.get("enabled"), bool):raise ValueError(f"{site.title} 的开关必须是 true 或 false")- template = row.get("template")- if not isinstance(template, str):- raise ValueError(f"{site.title} 的地址模板必须是文字")- problem = _template_problem(site, template.strip())+ result[site.key]["enabled"] = row["enabled"]+ if not site.mirrored:+ continue+ if not isinstance(row.get("host"), str):+ raise ValueError(f"{site.title} 的镜像域名必须是文字")+ host = _tidy_host(row["host"])+ problem = _host_problem(site, host)if problem:raise ValueError(problem)- result[site.key] = {"enabled": row["enabled"], "template": template.strip()}+ result[site.key]["host"] = hostpath = Path(root) / FILENAMEpath.parent.mkdir(parents=True, exist_ok=True)with FileLock(str(path) + ".lock", timeout=5):@@ -261,16 +279,16 @@ def build(settings: dict, canonical_name: str, refs, aliases=()) -> list[dict]:if not row.get("enabled", True) or (site.jav_only and not jav):continuevalues = ids.get(site.provider, []) if site.provider else ([written] if written else [])- template = str(row.get("template") or site.template)- if _template_problem(site, template):- template = site.template+ host = _tidy_host(row.get("host")) if site.mirrored else site.host+ if _host_problem(site, host):+ host = site.hostfor index, value in enumerate(values):ordinal = _ordinal(index)+ path = site.path.replace("{" + site.placeholder + "}", quote(value, safe=""))out.append({"site": site.key,"label": f"{site.label} {ordinal}".strip(),"ordinal": ordinal, "slot": site.slot, "mark": site.mark,- "url": template.replace("{" + site.placeholder + "}",- quote(value, safe=""))})+ "url": f"https://{host}{path}"})return outdiff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 91817d927..c0ea4c147 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -117,7 +117,7 @@ class WebContract:if follow_secrets_root is not None else SECRETS_DIR)self.follow_state_root = (Path(follow_state_root)if follow_state_root is not None else STATE_DIR)- # 人物页外部入口的开关与地址模板。和上面几个同一个道理:走实例属性,测试才+ # 人物页外部入口的开关与镜像域名。和上面几个同一个道理:走实例属性,测试才# 落得进临时目录,不会读到这台机器真实的偏好。self.entry_links_root = (Path(entry_links_root)if entry_links_root is not None else STATE_DIR)diff --git a/tests/test_desktop_settings.py b/tests/test_desktop_settings.pyindex 1c6b2e514..55c588fab 100644--- a/tests/test_desktop_settings.py+++ b/tests/test_desktop_settings.py@@ -151,15 +151,16 @@ class DesktopSettingsTests(unittest.TestCase):remove.assert_called_once_with(self.config,False)self.assertEqual(client.post('/api/configuration/startup',json={'enabled':'false','silent':True}).status_code,400)self.assertEqual(client.post('/api/configuration/peach-proxy',json={'mode':'proxy','proxy':'invalid'}).status_code,400)- # 外部入口:模板缺占位符时整批不写,落下去的会是一枚点过去必然落空的入口。- sites = {site.key: {'enabled': True, 'template': site.template}+ # 外部入口:域名不成形时整批不写,落下去的会是一排点过去必然落空的入口。+ sites = {site.key: ({'enabled': True, 'host': site.host} if site.mirrored+ else {'enabled': True})for site in entry_links.SITES}self.assertEqual(client.post('/api/configuration/entry-links',json={'sites':sites}).status_code,200)broken = {key: dict(row) for key, row in sites.items()}- broken['javdb']['template'] = 'https://javdb.com/actors/'+ broken['javdb']['host'] = 'javdb.com/actors'self.assertEqual(client.post('/api/configuration/entry-links',json={'sites':broken}).status_code,400)- self.assertEqual(entry_links.read(self.config.directory('state'))['javdb']['template'],- 'https://javdb.com/actors/{javdb_id}?sort_type=4')+ self.assertEqual(entry_links.read(self.config.directory('state'))['javdb']['host'],+ 'javdb.com')def test_startup_does_not_overwrite_another_installation(self):with patch.object(desktop_startup, 'startup_directory', return_value=self.root), patch.object(desktop_startup, 'shortcut', side_effect=[diff --git a/tests/test_entry_links.py b/tests/test_entry_links.pyindex a258efc9d..6116c4975 100644--- a/tests/test_entry_links.py+++ b/tests/test_entry_links.py@@ -26,7 +26,7 @@ class EntryLinkAddressTests(unittest.TestCase):# minnano-av 是一份资料页,排进上面那排链接;看片那两枚自己一行。self.assertEqual([row["slot"] for row in rows], ["pill", "mark", "mark"])self.assertEqual(rows[0]["url"], "https://www.minnano-av.com/actress155084.html")- self.assertEqual(rows[1]["url"], "https://javdb.com/actors/QDvG?sort_type=4")+ self.assertEqual(rows[1]["url"], "https://javdb.com/actors/QDvG")# 药丸上写站点自己的名字,取自 minnano-av 官网的 title。self.assertEqual([row["label"] for row in rows],["みんなのAV", "JavDB", "MISSAV"])@@ -43,8 +43,8 @@ class EntryLinkAddressTests(unittest.TestCase):self.assertEqual([row["label"] for row in pages], ["JavDB", "JavDB ②"])self.assertEqual([row["ordinal"] for row in pages], ["", "②"])self.assertEqual([row["url"] for row in pages],- ["https://javdb.com/actors/d45k9?sort_type=4",- "https://javdb.com/actors/ZX5z7?sort_type=4"])+ ["https://javdb.com/actors/d45k9",+ "https://javdb.com/actors/ZX5z7"])def test_a_site_without_an_id_is_absent_instead_of_a_search_address(self):rows = entry_links.build(entry_links.defaults(), "深田えいみ",@@ -126,11 +126,18 @@ class EntryLinkAddressTests(unittest.TestCase):rows = entry_links.build(settings, "七沢みあ", [ref("javdb", "NPD3")])self.assertEqual([row["site"] for row in rows], ["javdb"])- def test_a_custom_template_is_used_as_written(self):+ def test_a_mirror_domain_replaces_only_the_host(self):settings = entry_links.defaults()- settings["javdb"]["template"] = "https://javdb.com/actors/{javdb_id}/reviews"+ settings["javdb"]["host"] = "javdb521.com"rows = entry_links.build(settings, "七沢みあ", [ref("javdb", "NPD3")])- self.assertEqual(rows[0]["url"], "https://javdb.com/actors/NPD3/reviews")+ self.assertEqual(rows[0]["url"], "https://javdb521.com/actors/NPD3")++ def test_a_broken_domain_falls_back_to_the_default_site(self):+ """手改坏的域名拼出来是个不存在的主机名,那比退回默认站更难看出问题。"""+ settings = entry_links.defaults()+ settings["javdb"]["host"] = "javdb.com/actors"+ rows = entry_links.build(settings, "七沢みあ", [ref("javdb", "NPD3")])+ self.assertEqual(rows[0]["url"], "https://javdb.com/actors/NPD3")class EntryLinkSettingsFileTests(unittest.TestCase):@@ -139,47 +146,53 @@ class EntryLinkSettingsFileTests(unittest.TestCase):self.addCleanup(temporary.cleanup)self.root = Path(temporary.name).resolve()+ def body(self, **changed: dict) -> dict:+ """配置页提交的形状:每站一行,能换域名的带上域名。"""+ sites = {site.key: ({"enabled": True, "host": site.host} if site.mirrored+ else {"enabled": True})+ for site in entry_links.SITES}+ sites.update(changed)+ return {"sites": sites}+def test_an_absent_file_reads_as_every_site_open(self):saved = entry_links.read(self.root)self.assertEqual(sorted(saved), ["javdb", "minnano-av", "missav"])self.assertTrue(all(row["enabled"] for row in saved.values()))def test_saving_round_trips_through_the_snapshot(self):- body = {"sites": {site.key: {"enabled": True, "template": site.template}- for site in entry_links.SITES}}- body["sites"]["javdb"] = {"enabled": False,- "template": "https://javdb.com/actors/{javdb_id}"}- entry_links.save(self.root, body)+ entry_links.save(self.root, self.body(javdb={"enabled": False,+ "host": "javdb521.com"}))rows = {row["key"]: row for row in entry_links.snapshot(self.root)["sites"]}self.assertFalse(rows["javdb"]["enabled"])- self.assertEqual(rows["javdb"]["template"], "https://javdb.com/actors/{javdb_id}")- self.assertEqual(rows["javdb"]["default_template"],- "https://javdb.com/actors/{javdb_id}?sort_type=4")- self.assertEqual(rows["missav"]["placeholder"], "name")+ self.assertEqual(rows["javdb"]["host"], "javdb521.com")+ self.assertEqual(rows["javdb"]["default_host"], "javdb.com")self.assertEqual(rows["javdb"]["label"], "JavDB")+ # みんなのAV 没有镜像可换,配置页据此只给它一个开关。+ self.assertIsNone(rows["minnano-av"]["host"])+ self.assertIsNone(rows["minnano-av"]["default_host"])++ def test_a_pasted_address_is_trimmed_down_to_its_domain(self):+ """镜像地址多半是整条复制过来的,前缀与末尾的斜杠不值得弹一条错误。"""+ entry_links.save(self.root, self.body(missav={"enabled": True,+ "host": "https://missav.ai/"}))+ self.assertEqual(entry_links.read(self.root)["missav"]["host"], "missav.ai")- def test_a_template_without_its_placeholder_is_refused(self):- body = {"sites": {site.key: {"enabled": True, "template": site.template}- for site in entry_links.SITES}}- body["sites"]["javdb"]["template"] = "https://javdb.com/actors/"+ def test_an_address_with_a_path_is_refused(self):with self.assertRaises(ValueError) as caught:- entry_links.save(self.root, body)- self.assertIn("{javdb_id}", str(caught.exception))+ entry_links.save(self.root, self.body(+ javdb={"enabled": True, "host": "javdb.com/actors/{javdb_id}"}))+ self.assertIn("只写域名本身", str(caught.exception))- def test_a_plain_http_template_is_refused(self):- body = {"sites": {site.key: {"enabled": True, "template": site.template}- for site in entry_links.SITES}}- body["sites"]["missav"]["template"] = "http://missav.ws/cn/actresses/{name}"+ def test_an_empty_domain_is_refused(self):with self.assertRaises(ValueError) as caught:- entry_links.save(self.root, body)- self.assertIn("https://", str(caught.exception))+ entry_links.save(self.root, self.body(missav={"enabled": True, "host": " "}))+ self.assertIn("不能为空", str(caught.exception))def test_a_hand_broken_file_falls_back_instead_of_emptying_the_row(self):(self.root / entry_links.FILENAME).write_text(- json.dumps({"sites": {"javdb": {"template": "not a url"}}}), encoding="utf-8")+ json.dumps({"sites": {"javdb": {"host": "not a domain"}}}), encoding="utf-8")saved = entry_links.read(self.root)- self.assertEqual(saved["javdb"]["template"],- "https://javdb.com/actors/{javdb_id}?sort_type=4")+ self.assertEqual(saved["javdb"]["host"], "javdb.com")self.assertTrue(saved["javdb"]["enabled"])diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 05fc15b87..bdc344360 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -1041,7 +1041,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):entries = response.json()["entry_links"]self.assertEqual([row["site"] for row in entries], ["javdb", "missav"])self.assertEqual([row["slot"] for row in entries], ["mark", "mark"])- self.assertEqual(entries[0]["url"], "https://javdb.com/actors/NPD3?sort_type=4")+ self.assertEqual(entries[0]["url"], "https://javdb.com/actors/NPD3")self.assertTrue(entries[1]["url"].startswith("https://missav.ws/cn/actresses/%"))async def test_review_queue_is_readable_and_decisions_are_persisted(self):