Peach: Local-first video metadata scraper and media manager.
fix(web): 标签资料聚合遵守隐藏范围
longmeidaocad06cd61b24
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex d5124b5c0..57d937dbf 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -189,13 +189,13 @@ def region_facet_rows(rows) -> list[dict]:def _entity_asset_filter(connection, kind: str, name: str) -> tuple[str, list[int]]:"""名称按资料页身份解析,作品范围包含旗下厂牌或事务所成员。"""- from .web_entity import scope_predicate+ from .web_entity import _tag_scope_visibility, scope_predicateentity = resolve_entity(connection, kind, name)if entity is None:return "0", []- predicate = scope_predicate(kind, "entity_id")- return f"a.id IN (SELECT asset_id FROM asset_entity WHERE {predicate})", [entity["id"]]+ predicate = scope_predicate(kind, "scoped.entity_id") + _tag_scope_visibility(kind, "scoped.entity_id", "scoped.asset_id")+ return f"a.id IN (SELECT scoped.asset_id FROM asset_entity scoped WHERE {predicate})", [entity["id"]]def catalog_filter(contract: WebContract, args):diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex 675b000bf..aba5b3332 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -90,6 +90,14 @@ def scope_predicate(kind: str, column: str, subject: str = "?") -> str:return f"{column}={subject}"+def _tag_scope_visibility(kind: str, entity_column: str, asset_column: str) -> str:+ """标签资料的资产范围遵守当前用户的隐藏选择。"""+ if kind != "tag":+ return ""+ normalized = f"(SELECT normalized_name FROM entity WHERE id={entity_column})"+ return " AND " + tag_not_hidden(asset_column, normalized)++#: 索引页地址 → `entity.kind`。有资料页就该有索引页:只靠女优页上那个名字进事务所页的话,#: 名下没有关系的几十家等于只能靠猜地址。标签不在这里,它走另一条分支。INDEX_ENTITY_KINDS = {"performers": "performer", "creators": "creator",@@ -239,11 +247,12 @@ def q_entity(contract: WebContract, args):d['company_profile'] = company_profiles.public_profile(metadata)# 创作者在关注里的那一面(ADR-0096):绑在名下的来源和同名等确认的那几组。d["follow"] = web_follow.entity_follow(contract, c, d["id"]) if kind == "creator" else None- scope = scope_predicate(kind, "ae.entity_id")+ scope = scope_predicate(kind, "ae.entity_id") + _tag_scope_visibility(kind, "ae.entity_id", "a.id")count, rep = c.execute("SELECT count(DISTINCT " + video_work_key(contract, c) + "),""(SELECT a2.id FROM asset_entity ae2 CROSS JOIN asset a2 ON a2.id=ae2.asset_id "" WHERE " + scope_predicate(kind, "ae2.entity_id") ++ _tag_scope_visibility(kind, "ae2.entity_id", "a2.id") +" AND a2.medium='video' AND a2.snapshot_path IS NOT NULL " +(" AND " + solo_performer_clause("a2.id", "ae2.entity_id") if kind == "performer" else "") +" ORDER BY a2.size DESC LIMIT 1) "@@ -260,6 +269,7 @@ def q_entity(contract: WebContract, args):"JOIN entity tag ON tag.id=tagged.entity_id ""JOIN asset a ON a.id=scope.asset_id ""WHERE " + scope_predicate(kind, "scope.entity_id") ++ _tag_scope_visibility(kind, "scope.entity_id", "a.id") +" AND " + COUNTED_VIDEO + " AND tag.kind='tag' ""AND " + tag_is_not_a_performer_name("tag.normalized_name") + " "f"AND tag.canonical_name NOT IN ({','.join('?' for _ in LENGTH_TAGS)}) "@@ -289,6 +299,7 @@ def q_entity(contract: WebContract, args):"SELECT person.id,person.canonical_name k,count(DISTINCT " + video_work_key(contract, c) + ") n,""(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "" WHERE ae2.entity_id=person.id AND a2.medium='video' "+ + _tag_scope_visibility(kind, "scope.entity_id", "a2.id") +" AND a2.snapshot_path IS NOT NULL AND " + solo_performer_clause("a2.id", "person.id") +" ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"" COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep "@@ -297,6 +308,7 @@ def q_entity(contract: WebContract, args):"JOIN entity person ON person.id=co.entity_id ""JOIN asset a ON a.id=scope.asset_id ""WHERE " + scope_predicate(kind, "scope.entity_id") ++ _tag_scope_visibility(kind, "scope.entity_id", "a.id") +" AND " + COUNTED_VIDEO + " AND person.kind='performer' ""AND person.id<>? ""GROUP BY person.id,person.canonical_name "@@ -431,6 +443,7 @@ def entity_code_sets(contract: WebContract, c, kind: str, entity_id: int) -> lis"SELECT a.code,a.catalog_title,a.original_title,a.release_date ""FROM asset_entity ae CROSS JOIN asset a ON a.id=ae.asset_id ""WHERE " + scope_predicate(kind, "ae.entity_id") + " AND " + VISIBLE_CATALOG_ASSET ++ _tag_scope_visibility(kind, "ae.entity_id", "a.id") +" AND a.code IS NOT NULL AND a.code<>'' ORDER BY a.id", (entity_id,)):key = sample_images.code_key(row["code"])if not key:@@ -476,6 +489,7 @@ def q_entity_photos(contract: WebContract, args):# 图集和分页数的是同一批图,`total` 由图集相加,才对得上翻到底的张数。scoped = ("FROM asset_entity ae CROSS JOIN asset a ON a.id=ae.asset_id ""WHERE " + scope_predicate(kind, "ae.entity_id") ++ _tag_scope_visibility(kind, "ae.entity_id", "a.id") +" AND a.medium='image' AND a.name IS NOT NULL ""AND a.disposal IS NULL ")sets = [{diff --git a/tests/test_entity_redirect.py b/tests/test_entity_redirect.pyindex e8e856461..bfd154b8a 100644--- a/tests/test_entity_redirect.py+++ b/tests/test_entity_redirect.py@@ -274,6 +274,70 @@ class EntityRedirectRouteTests(unittest.TestCase):self.assertEqual(by_id.json()['total'], 1)self.assertEqual(by_id.json()['items'][0]['id'], 2)+ def test_tag_hidden_assets_are_excluded_from_profiles_photos_and_samples(self):+ with sqlite3.connect(self.app.state.settings.db_path) as connection:+ connection.executemany(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES(?,'tag',?,?,'t','t')",+ [(20, 'Tag A', 'tag a'), (21, 'Hidden only', 'hidden only'), (22, 'Visible only', 'visible only')])+ add_person(connection, 12, 'Hidden cast')+ connection.execute("UPDATE asset SET code='ABC-001',size=10,snapshot_path='visible.jpg' WHERE id=1")+ connection.executemany(+ "INSERT INTO asset(id,location,path,name,medium,size,code,snapshot_path,play_count)"+ " VALUES(?,'local',?,?,?,?,?,?,?)",+ [(2, r'R:\media\visible\2.jpg', '2.jpg', 'image', 10, None, None, 0),+ (3, r'R:\media\3.mp4', '3.mp4', 'video', 1000, 'ABC-002', 'hidden.jpg', 100),+ (4, r'R:\media\hidden\4.jpg', '4.jpg', 'image', 10, None, None, 0),+ (5, r'R:\media\5.mp4', '5.mp4', 'video', 500, 'ABC-003', 'hidden-cast.jpg', 0)])+ connection.executemany(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) VALUES(?,?,?,'test',1)",+ [(asset_id, 20, 'tag') for asset_id in (1, 2, 3, 4, 5)]+ + [(1, 22, 'tag'), (3, 21, 'tag'), (3, 10, 'performer'), (5, 12, 'performer')])+ connection.executemany(+ "INSERT INTO asset_tag_preference(profile_id,asset_id,normalized_tag,hidden,updated_at)"+ " VALUES('local-default',?,'tag a',1,0)", [(3,), (4,), (5,)])+ connection.executemany(+ "INSERT INTO code_sample_image(code,position,url,site,source,fetched_at)"+ " VALUES(?,1,'https://example.test/sample.jpg','dmm','test','t')",+ [('ABC-001',), ('ABC-002',), ('ABC-003',)])++ def read(path, kind='tag', entity_id=20):+ response = self.client.get(path, params={'kind': kind, 'id': entity_id, 't': 'secret'})+ self.assertEqual(response.status_code, 200, response.text)+ return response.json()++ profile = read('/api/entity')+ self.assertEqual(profile['asset_count'], 1)+ self.assertEqual(profile['representative_asset_id'], 1)+ self.assertEqual({tag['id']: tag['n'] for tag in profile['tags']}, {20: 1, 22: 1})+ self.assertEqual([(person['id'], person['n'], person['rep']) for person in profile['related_performers']],+ [(10, 1, 1)])+ photos = read('/api/photos')+ self.assertEqual(photos['total'], 1)+ self.assertEqual([item['id'] for item in photos['items']], [2])+ self.assertEqual({item['id']: item['n'] for item in photos['sets']}, {'code:ABC-001': 1, 2: 1})+ self.assertEqual(photos['sample_total'], 1)+ self.assertEqual(read('/api/entity', 'performer', 10)['asset_count'], 2)+ from peach.web_catalog import _entity_asset_filter, q_facets+ from peach.web_state import WebContract++ contract = WebContract(self.app.state.settings.db_path)+ with contract.read_connection() as connection:+ clause, params = _entity_asset_filter(connection, 'tag', 'Tag A')+ scoped_assets = connection.execute(f'SELECT a.id FROM asset a WHERE {clause} ORDER BY a.id', params).fetchall()+ self.assertEqual([row[0] for row in scoped_assets], [1, 2])+ facets = q_facets(contract, filters={'tag': 'Tag A'})+ self.assertEqual(facets['stats']['total'], profile['asset_count'])+ self.assertEqual({item['k']: item['n'] for item in facets['tags']}, {'Tag A': 1, 'Visible only': 1})++ with sqlite3.connect(self.app.state.settings.db_path) as connection:+ connection.execute("UPDATE asset_tag_preference SET hidden=0 WHERE normalized_tag='tag a'")+ self.assertEqual(read('/api/entity')['asset_count'], 3)+ restored = read('/api/photos')+ self.assertEqual(restored['total'], 2)+ self.assertEqual(restored['sample_total'], 3)+ self.assertEqual(q_facets(contract, filters={'tag': 'Tag A'})['stats']['total'], 3)+def test_an_old_image_address_redirects_to_the_target(self):body = picture("navy")(self.avatars / "performer-10.img").write_bytes(body)