Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(links): 驳回事务所时一并改写链接标签,存档链接的圆标按原站取

longmeidaofb90daab34b5
diff --git a/scripts/reject_agency.py b/scripts/reject_agency.py
index 26b9d3f7f..bce11a8bf 100644
--- a/scripts/reject_agency.py
+++ b/scripts/reject_agency.py
@@ -36,6 +36,7 @@ from peach.review_csv import read_rows # noqa: E402
from peach.scripting import ( # noqa: E402
add_ledger_write_args, counts_of, open_for_write, verify_after_write,
)
+from peach.social_links import classify, host_owners # noqa: E402
#: 驳回是人的判断,写入者按 `field_owners` 的归属串署名。
SOURCE = "user:manual"
@@ -104,8 +105,30 @@ def attach(connection, entity_id: int, raw: str, stamp: str) -> int:
return created
+def relabel_links(connection, entity_id: int, rejected: str, replacement: str, stamp: str) -> int:
+ """她名下标签写着这家事务所的官方链接,按域名归属重写标签。返回改了几条。
+
+ 采集时 minnano-av 的「所属事務所」被贴在同一页每条 official 链接上:三上悠亜那条
+ ONE'S DOUBLE 的个人页写着「株式会社Miss」。事务所驳回了,标签还替它说话。重写走
+ `classify`,与 `repair_link_labels.py` 同一套:域名归谁写谁,不知道就写她 AV 时期的
+ 事务所,再不知道写「官方网站」。
+ """
+ owners = host_owners(connection)
+ agency = split_name(replacement)[0] if replacement else ""
+ changed = 0
+ for link_id, label, url in connection.execute(
+ "SELECT id,label,url FROM entity_link WHERE entity_id=? AND link_kind='official'",
+ (entity_id,)).fetchall():
+ if agency_key(label) != agency_key(rejected):
+ continue
+ connection.execute("UPDATE entity_link SET label=?,updated_at=? WHERE id=?",
+ (classify(url, agency, owners.get)[1], stamp, link_id))
+ changed += 1
+ return changed
+
+
def apply_rows(connection, rows: list[dict[str, object]], stamp: str) -> dict[str, int]:
- done = {"驳回": 0, "归属": 0, "事务所": 0, "改挂": 0, "新建事务所": 0}
+ done = {"驳回": 0, "归属": 0, "事务所": 0, "改挂": 0, "新建事务所": 0, "链接标签": 0}
# 外键默认关着,删实体时要它把别名、链接、外部编号一并级联删掉;PRAGMA 只能在事务外设。
connection.commit()
connection.execute("PRAGMA foreign_keys=ON")
@@ -130,6 +153,7 @@ def apply_rows(connection, rows: list[dict[str, object]], stamp: str) -> dict[st
"checked_at": stamp}
connection.execute("UPDATE entity SET metadata_json=?,updated_at=? WHERE id=?",
(json.dumps(metadata, ensure_ascii=False), stamp, entity_id))
+ done["链接标签"] += relabel_links(connection, entity_id, str(row["agency"]), replacement, stamp)
if row.get("holds"):
connection.execute("DELETE FROM entity_membership WHERE member_id=? AND agency_id=?",
(entity_id, int(row["agency_id"])))
diff --git a/scripts/repair_link_labels.py b/scripts/repair_link_labels.py
index fc7ab8770..4a9ee9d5d 100644
--- a/scripts/repair_link_labels.py
+++ b/scripts/repair_link_labels.py
@@ -75,25 +75,37 @@ def agency_from_label(label: str, hostname: str, studios: set[str]) -> str:
return "" if label.strip("/") in {hostname, f"www.{hostname}"} else label
+def _metadata(text) -> dict:
+ try:
+ found = json.loads(text or "{}")
+ except (TypeError, ValueError):
+ return {}
+ return found if isinstance(found, dict) else {}
+
+
def collect(connection: sqlite3.Connection) -> list[dict[str, object]]:
"""每条女优 official 链接的重判结果。"""
owners = host_owners(connection)
studios = studio_names(connection)
rows: list[dict[str, object]] = []
- for link_id, entity_id, performer, kind, label, url, hostname in connection.execute(
- "SELECT l.id,l.entity_id,e.canonical_name,l.link_kind,l.label,l.url,l.hostname"
+ for link_id, entity_id, performer, kind, label, url, hostname, metadata in connection.execute(
+ "SELECT l.id,l.entity_id,e.canonical_name,l.link_kind,l.label,l.url,l.hostname,e.metadata_json"
" FROM entity_link l JOIN entity e ON e.id=l.entity_id"
" WHERE e.kind='performer' AND l.link_kind='official' ORDER BY l.id"
):
agency = agency_from_label(label, hostname, studios)
+ # 人判过不成立的事务所(`reject_agency.py`)不再当标签的依据:三上悠亜那条
+ # ONE'S DOUBLE 官网链接上写着的「株式会社Miss」就是这么一直留下来的。
+ rejected = bool(agency) and agency_key(agency) in rejected_agencies(_metadata(metadata))
+ agency = "" if rejected else agency
new_kind, new_label = classify(url, agency, owners.get)
owner = owners.get(owner_key(hostname), "")
if (new_kind, new_label) == (kind, label):
verdict, note = "keep", "标签与域名归属一致"
elif new_kind != kind:
verdict, note = "auto", f"{hostname} 是平台账号,不是 official"
- elif owner:
- verdict, note = "auto", f"{hostname} 归 {owner}"
+ elif owner or rejected:
+ verdict, note = "auto", (f"{hostname} 归 {owner}" if owner else f"「{label}」是已驳回的事务所")
else:
# 归属未知时 classify 会把原标签原样还回来,走不到这里;留着兜底。
verdict, note = "review", f"{hostname} 归属未取得"
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index 4bf99f3fe..0b73d3c54 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -30,7 +30,7 @@ from starlette.staticfiles import StaticFiles
from . import (
avatar_face, avatar_picker, avatar_provider, follow_assets, images,
- jav_poster_crop, link_marks, scraping_access, site_icons, subtitles,
+ jav_poster_crop, link_marks, scraping_access, site_icons, social_links, subtitles,
taste_history, timeline_sheets, web_follow, web_settings,
)
from .config import GENERATED_DIR
@@ -938,10 +938,12 @@ def _site_mark_response(state, url: str, root: Path):
if cached is None:
return JSONResponse({"error": "unavailable"}, status_code=404)
if not link_marks.is_fresh(cached, ttl=_metadata_ttl(state)):
+ page, locate = social_links.archive_view(url)
+
def fetch(target: str):
try:
upstream = state.http_transport.client.get(
- target, headers={"User-Agent": USER_AGENT},
+ locate(target), headers={"User-Agent": USER_AGENT},
timeout=8, follow_redirects=True)
except (OSError, httpx.HTTPError):
return None
@@ -950,7 +952,7 @@ def _site_mark_response(state, url: str, root: Path):
return upstream.content, upstream.headers.get("content-type", "")
# 两条通道都不适用时退回原样缩图:糊一点也好过露出地球图标。
- made = site_icons.best_mark(url, fetch, link_marks.render_mark,
+ made = site_icons.best_mark(page, fetch, link_marks.render_mark,
fallback=link_marks.plain_mark)
if made:
root.mkdir(parents=True, exist_ok=True)
diff --git a/src/peach/site_icons.py b/src/peach/site_icons.py
index 3f448f12f..44ce5b421 100644
--- a/src/peach/site_icons.py
+++ b/src/peach/site_icons.py
@@ -246,6 +246,12 @@ HOST_OVERRIDES: dict[str, tuple[str, ...]] = {
"https://images-assets-ht.project1content.com/BangBros/MA/Subsites/"
"6480a83860e9c0.34870333.png",
),
+ # ONE'S DOUBLE 2022 年关门,官网只剩存档;快照里的 favicon.ico 是 WordPress 的默认
+ # 图标,不是这家公司的。页脚那枚 SVG 标识与事务所页的字标是同一份(`studio_icons`)。
+ "ones-double.com": (
+ "https://web.archive.org/web/20220130000436id_/"
+ "https://ones-double.com/wp/assets/img/footer-logo.svg",
+ ),
}
diff --git a/src/peach/social_links.py b/src/peach/social_links.py
index 2dd9872e5..4a199a9a1 100644
--- a/src/peach/social_links.py
+++ b/src/peach/social_links.py
@@ -76,6 +76,27 @@ def is_archive(url: str) -> bool:
return under(host_of(url), ARCHIVE_HOSTS)
+#: 存档快照地址里的时间戳与原地址:`/web/20220512171503/https://ones-double.com/…`。
+ARCHIVE_PATH = re.compile(r"^/web/(\d{4,14})[a-z_]*/(https?://.+)$", re.I)
+
+
+def archive_view(url: str) -> tuple[str, Callable[[str], str]]:
+ """按哪个地址找站点图标,以及每个要取的地址怎么改写。
+
+ 存档快照的主机是存档站自己,照它找图标,每一家关了门的公司都会顶着 Internet Archive
+ 的图标。所以按快照里的原站去找,要取的每个地址都换成同一时刻的存档原件(`id_`
+ 返回的是原始字节,不带存档站插的工具栏)。不是存档快照的原样取。
+ """
+ parts = urlsplit(url)
+ path = parts.path + (f"?{parts.query}" if parts.query else "")
+ found = ARCHIVE_PATH.match(path) if is_archive(url) else None
+ if found is None:
+ return url, lambda target: target
+ stamp = found.group(1)
+ return found.group(2), lambda target: (
+ target if is_archive(target) else f"https://web.archive.org/web/{stamp}id_/{target}")
+
+
def canonical_url(url: str) -> str:
"""改过名的站点换成现主机,主机名一律小写;其余原样返回。
diff --git a/tests/test_agency_reject.py b/tests/test_agency_reject.py
index 5e7611631..e48042045 100644
--- a/tests/test_agency_reject.py
+++ b/tests/test_agency_reject.py
@@ -10,6 +10,7 @@ from peach.migrations import upgrade
from scripts.install_agencies import collect as agency_plan
from scripts.reject_agency import apply_rows, plan
from scripts.repair_link_labels import apply_rows as repair_labels
+from scripts.repair_link_labels import collect as collect_labels
ROOT = Path(__file__).resolve().parents[1]
MIGRATIONS = ROOT / "migrations"
@@ -69,7 +70,8 @@ class RejectTests(RejectFixture):
def test_her_only_company_goes_away_with_its_links_and_numbers(self):
_, done = self.reject("三上悠亚", "株式会社Miss")
- self.assertEqual(done, {"驳回": 1, "归属": 1, "事务所": 1, "改挂": 0, "新建事务所": 0})
+ self.assertEqual(done, {"驳回": 1, "归属": 1, "事务所": 1, "改挂": 0, "新建事务所": 0,
+ "链接标签": 0})
self.assertEqual(self.count("SELECT count(*) FROM entity WHERE id=30"), 0)
self.assertEqual(self.count("SELECT count(*) FROM entity_link WHERE entity_id=30"), 0)
self.assertEqual(
@@ -113,6 +115,31 @@ class RejectTests(RejectFixture):
self.assertEqual(self.metadata(11)["agency"]["name"], "ONE'S DOUBLE(ワンズダブル)")
self.assertEqual([item["agency"] for item in agency_plan(self.con)], ["ONE'S DOUBLE"])
+ def add_link(self, label, url, hostname):
+ self.con.execute(
+ "INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,created_at,updated_at)"
+ " VALUES(11,'official',?,?,?,'t','t')", (label, url, hostname))
+ self.con.commit()
+ return self.count("SELECT max(id) FROM entity_link")
+
+ def label(self, link_id):
+ return self.count("SELECT label FROM entity_link WHERE id=?", link_id)
+
+ def test_her_links_stop_speaking_for_the_rejected_agency(self):
+ """官网链接上贴着的那家被驳回:有 AV 时期事务所写它,别的标签不动。"""
+ wrong = self.add_link("株式会社Miss", "https://ones-double.com/people/mikami-yua/",
+ "ones-double.com")
+ other = self.add_link("FALENO", "https://faleno.jp/top/actress/", "faleno.jp")
+ _, done = self.reject("三上悠亚", "株式会社Miss", replacement="ONE'S DOUBLE(ワンズダブル)")
+ self.assertEqual(done["链接标签"], 1)
+ self.assertEqual((self.label(wrong), self.label(other)), ("ONE'S DOUBLE", "FALENO"))
+
+ def test_without_a_replacement_the_label_falls_back_to_the_generic_one(self):
+ wrong = self.add_link("株式会社Miss", "https://ones-double.com/people/mikami-yua/",
+ "ones-double.com")
+ self.reject("三上悠亚", "株式会社Miss")
+ self.assertEqual(self.label(wrong), "官方网站")
+
class WriteBackTests(RejectFixture):
"""驳回之后,站上那一格原样再来一遍:两条写回路径都要跳过。"""
@@ -132,6 +159,17 @@ class WriteBackTests(RejectFixture):
"new_label": "", "new_link_kind": "official"}], STAMP)
self.assertNotIn("agency", self.metadata(11))
+ def test_the_label_repair_rewrites_a_label_naming_a_rejected_agency(self):
+ """驳回早于链接采集时,标签修复自己认出来:写着已驳回事务所的标签判 auto。"""
+ self.reject("三上悠亚", "株式会社Miss")
+ self.con.execute(
+ "INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,created_at,updated_at)"
+ " VALUES(11,'official','株式会社Miss','https://ones-double.com/people/mikami-yua/',"
+ "'ones-double.com','t','t')")
+ found = [row for row in collect_labels(self.con) if row["entity_id"] == 11]
+ self.assertEqual([(row["verdict"], row["new_label"], row["agency"]) for row in found],
+ [("auto", "官方网站", "")])
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_site_icons.py b/tests/test_site_icons.py
index 09c5161b4..3913d302b 100644
--- a/tests/test_site_icons.py
+++ b/tests/test_site_icons.py
@@ -8,7 +8,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
-from peach import site_icons # noqa: E402
+from peach import site_icons, social_links # noqa: E402
def urls(candidates):
@@ -246,6 +246,34 @@ class DiscoverTests(unittest.TestCase):
self.assertEqual([c.scope for c in got], [site_icons.ENTITY_SCOPE])
+class ArchiveViewTests(unittest.TestCase):
+ """存档链接的圆标按原站找:图标是那家公司的,取图走同一份快照。"""
+
+ SNAPSHOT = ("https://web.archive.org/web/20220512171503/"
+ "https://ones-double.com/people/mikami-yua/")
+
+ def test_a_snapshot_is_looked_up_as_the_site_it_preserved(self):
+ page, locate = social_links.archive_view(self.SNAPSHOT)
+ self.assertEqual(page, "https://ones-double.com/people/mikami-yua/")
+ self.assertEqual(locate("https://ones-double.com/favicon.ico"),
+ "https://web.archive.org/web/20220512171503id_/"
+ "https://ones-double.com/favicon.ico")
+
+ def test_an_address_already_inside_the_archive_is_fetched_as_is(self):
+ _, locate = social_links.archive_view(self.SNAPSHOT)
+ pinned = site_icons.overrides_for("https://ones-double.com/")[0].url
+ self.assertEqual(locate(pinned), pinned)
+
+ def test_a_live_link_is_left_alone(self):
+ page, locate = social_links.archive_view("https://faleno.jp/top/")
+ self.assertEqual((page, locate("https://faleno.jp/favicon.ico")),
+ ("https://faleno.jp/top/", "https://faleno.jp/favicon.ico"))
+
+ def test_the_archive_front_page_is_not_a_snapshot(self):
+ page, _ = social_links.archive_view("https://web.archive.org/")
+ self.assertEqual(page, "https://web.archive.org/")
+
+
def reject_host_scope(candidate, data, content_type=""):
"""`harvest_studio_icons` 挂的那道守卫,这里用最小实现代表它。"""
return candidate.scope == site_icons.ENTITY_SCOPE