# src/services/jellyfinmeta.py """Jellyfin 侧的广告元数据修复。 `MetaCleanService` 抹掉的是**文件**里的广告标签(重封装 `-map_metadata -1`), 但 Jellyfin 自己的库(jellyfin.db / NFO sidecar)里还留着当初扫描时抓进去的旧值, 界面上就还是备注(plot)、类型(genre)、工作室(studio)里的广告。 本服务只走 Jellyfin API + NFO sidecar: 1. 拉全库条目建 `Path → 条目` 索引(不靠剧名搜索,综艺集名千奇百怪搜不准) 2. 找出 Overview / Genres / Studios / Tags / Tagline 里带广告的条目 3. 清掉广告字段:工作室清空后继承所属剧集的真实工作室(TMDB 抓的) 4. 简介被污染的条目先置空,再让 Jellyfin 重新刮削(不动特典放置字段) 5. 清掉 NFO 里带广告的 plot / genre / studio 等标签(否则下次扫描又长回来) 6. 删掉广告生成的工作室 / 类型实体 第 4 步只对「简介仍带广告」的条目做 FullRefresh,且 `replaceAllMetadata=false`; 特典放置字段(AirsBeforeSeasonNumber 等)不归元数据提供器管,实测刷完仍在。 """ from __future__ import annotations import json import time import urllib.error import urllib.parse import urllib.request import xml.etree.ElementTree as ET from pathlib import Path from core import config from core.logger import log # 广告特征由 config.ini [Ads] keywords + patterns 合成(见 core/config.py) AD_PATTERN = config.AD_PATTERN # 扫描面全部来自 config.ini [Jellyfin]: # scan_fields(条目字段)/ item_types(条目类型)/ nfo_tags(要清的 NFO 标签) _SCAN_FIELDS = config.JELLYFIN_SCAN_FIELDS _ITEM_TYPES = config.JELLYFIN_ITEM_TYPES _NFO_TAGS = tuple(config.JELLYFIN_NFO_TAGS) # 广告实体(工作室/类型)只允许从这两种类型里删,避免误删媒体条目 _ENTITY_TYPES = {"Studio", "Genre"} class JellyfinClient: """极简 Jellyfin REST 客户端:带地址探测与重试。""" def __init__(self) -> None: self.key = config.JELLYFIN_API_KEY or "" self.base = self._resolve_base() self._user_id = "" def _resolve_base(self) -> str: base = (config.JELLYFIN_URL or "http://127.0.0.1:8096").rstrip("/") candidates = [base] if "127.0.0.1" in base or "localhost" in base: # 容器里访问不到宿主机 127.0.0.1(Jellyfin 跑在宿主机上) candidates += ["http://172.17.0.1:8096", "http://10.10.1.202:8096"] for url in candidates: try: req = urllib.request.Request(f"{url}/System/Info/Public") with urllib.request.urlopen(req, timeout=5) as resp: if resp.status == 200: return url except OSError: continue raise RuntimeError(f"连不上 Jellyfin(试过 {', '.join(candidates)})") # ---------------------------------------------------------------- HTTP def _request(self, path: str, method: str = "GET", payload=None, params=None, retries: int | None = None): retries = retries or config.JELLYFIN_RETRIES params = dict(params or {}) params.setdefault("api_key", self.key) url = f"{self.base}{path}?" + urllib.parse.urlencode(params) data = json.dumps(payload).encode() if payload is not None else None headers = {"X-Emby-Token": self.key, "Accept": "application/json"} if data: headers["Content-Type"] = "application/json" last = None for attempt in range(1, retries + 1): try: req = urllib.request.Request(url, data=data, headers=headers, method=method) with urllib.request.urlopen(req, timeout=config.JELLYFIN_TIMEOUT) as resp: body = resp.read() return json.loads(body) if body else None except urllib.error.HTTPError as exc: # 400/404 重试也没用,直接抛 if exc.code < 500: raise last = exc except OSError as exc: # 连接被掐、超时 last = exc if attempt < retries: time.sleep(1.5 * attempt) raise RuntimeError(f"{method} {path} 失败: {last}") def get(self, path: str, **params): return self._request(path, params=params) def post(self, path: str, payload=None, **params): return self._request(path, method="POST", payload=payload, params=params) def delete(self, path: str, **params): return self._request(path, method="DELETE", params=params) @property def user_id(self) -> str: if not self._user_id: users = self.get("/Users") or [] if not users: raise RuntimeError("Jellyfin 里没有用户,无法读取条目详情") self._user_id = users[0]["Id"] return self._user_id def item(self, item_id: str) -> dict: return self.get(f"/Users/{self.user_id}/Items/{item_id}") or {} def all_items(self) -> list[dict]: items, start = [], 0 while True: page = self.get("/Items", recursive="true", fields=_SCAN_FIELDS, includeItemTypes=_ITEM_TYPES, limit="2000", startIndex=str(start)) or {} batch = page.get("Items") or [] items.extend(batch) total = page.get("TotalRecordCount") or 0 start += len(batch) if not batch or start >= total: return items class JellyfinAdFixService: """把 Jellyfin 条目 / NFO 里的广告元数据改回干净内容。""" # ------------------------------------------------------------ 判定 @staticmethod def polluted_fields(item: dict) -> list[str]: hits = [] for field in ("Overview", "Genres", "Studios", "Tags", "Tagline"): value = item.get(field) if not value: continue texts = [v.get("Name") or "" for v in value] if field == "Studios" else ( value if isinstance(value, list) else [value]) if any(AD_PATTERN.search(str(t)) for t in texts): hits.append(field) return hits @staticmethod def _drop_bad(values, key=None): out = [] for value in values or []: text = (value.get(key) or "") if key else str(value) if not AD_PATTERN.search(text): out.append(value) return out # ------------------------------------------------------------ NFO @classmethod def clean_sidecars(cls, root: Path, dry_run: bool = False) -> dict: """清 NFO 里带广告的 plot/genre/studio 等标签(NFO 属主可能是 root)。""" stats = {"scanned": 0, "changed": 0, "denied": 0, "broken": 0} for nfo in root.rglob("*.nfo"): stats["scanned"] += 1 try: tree = ET.parse(nfo) except (ET.ParseError, OSError): stats["broken"] += 1 continue r = tree.getroot() changed = False for tag in _NFO_TAGS: for element in list(r.findall(tag)): if element.text and AD_PATTERN.search(element.text): r.remove(element) changed = True if not changed: continue if dry_run: stats["changed"] += 1 log.info(f"🧽 NFO(演练){nfo.name[:60]}") continue try: tree.write(nfo, encoding="utf-8", xml_declaration=True) stats["changed"] += 1 except OSError as exc: stats["denied"] += 1 log.warning(f"⚠️ NFO 写不进去({nfo.name}): {exc}") return stats # ------------------------------------------------------------ 条目 @classmethod def fix_items(cls, client: JellyfinClient, items: list[dict], targets: list[dict] | None = None, dry_run: bool = False) -> dict: targets = targets if targets is not None else [it for it in items if cls.polluted_fields(it)] stats = {"polluted": len(targets), "fixed": 0, "failed": 0, "refresh": 0} series_studios = { it["Id"]: it.get("Studios") or [] for it in items if it.get("Type", "").endswith("Series") } series_genres = { it["Id"]: it.get("Genres") or [] for it in items if it.get("Type", "").endswith("Series") } for item in targets: hits = cls.polluted_fields(item) label = f"{item.get('Name', '')[:40]:42}" log.info(f"🧽 {label} ← {', '.join(hits)}") if dry_run: continue try: dto = client.item(item["Id"]) except Exception as exc: # noqa: BLE001 - 单条失败不该中断整轮 stats["failed"] += 1 log.warning(f"⚠️ 读取条目失败 {label}: {exc}") continue dto["Studios"] = cls._drop_bad(dto.get("Studios"), key="Name") dto["Genres"] = cls._drop_bad(dto.get("Genres")) dto["Tags"] = cls._drop_bad(dto.get("Tags")) if dto.get("Tagline") and AD_PATTERN.search(dto["Tagline"]): dto["Tagline"] = "" # 工作室被广告顶掉了:继承剧集(Series)的真实工作室 if not dto.get("Studios") and dto.get("SeriesId"): dto["Studios"] = series_studios.get(dto["SeriesId"]) or [] # 类型同理:广告 genre 清掉后为空,继承剧集的真实类型 if not dto.get("Genres") and dto.get("SeriesId"): dto["Genres"] = series_genres.get(dto["SeriesId"]) or [] need_refresh = bool(dto.get("Overview") and AD_PATTERN.search(dto["Overview"])) if need_refresh: dto["Overview"] = "" try: client.post(f"/Items/{item['Id']}", dto) except Exception as exc: # noqa: BLE001 stats["failed"] += 1 log.warning(f"⚠️ 写回条目失败 {label}: {exc}") continue stats["fixed"] += 1 # 简介清空后让 Jellyfin 自己重新刮削;不动 replaceAllMetadata, # 避免把特典放置(AirsBeforeSeasonNumber)冲掉 if need_refresh: try: client.post(f"/Items/{item['Id']}/Refresh", metadataRefreshMode="FullRefresh", replaceAllMetadata="false", replaceImages="false") stats["refresh"] += 1 except Exception as exc: # noqa: BLE001 log.warning(f"⚠️ 触发重新刮削失败 {label}: {exc}") return stats # ------------------------------------------------------------ 实体 @classmethod def purge_entities(cls, client: JellyfinClient, dry_run: bool = False) -> dict: """删掉广告生成的工作室 / 类型实体(只删实体,不碰媒体条目)。""" stats = {"found": 0, "deleted": 0, "failed": 0} candidates = [] for path, kind in (("/Genres", "Genre"), ("/Studios", "Studio")): try: data = client.get(path, limit="500") or {} except Exception as exc: # noqa: BLE001 log.warning(f"⚠️ 读取 {kind} 列表失败: {exc}") continue for entity in data.get("Items") or []: name = entity.get("Name") or "" if AD_PATTERN.search(name): candidates.append(entity) # /Genres、/Studios 只列「被引用过」的实体;库里可能还留着孤儿实体, # 再按名字从 /Items 里捞一遍 try: rows = client.get("/Items", recursive="true", includeItemTypes="Genre,Studio", fields="Name,Path", limit="2000") or {} for entity in rows.get("Items") or []: name = entity.get("Name") or "" if AD_PATTERN.search(name) and entity.get("Id") not in {c.get("Id") for c in candidates}: candidates.append(entity) except Exception as exc: # noqa: BLE001 log.debug(f"按 /Items 兜底枚举实体失败(忽略): {exc}") for entity in candidates: stats["found"] += 1 name = entity.get("Name") or "" log.info(f"🗑 广告实体 [{entity.get('Type', '').split('.')[-1]}] {name[:60]}") if dry_run: continue if (entity.get("Type") or "").split(".")[-1] not in _ENTITY_TYPES: continue try: client.delete(f"/Items/{entity['Id']}") stats["deleted"] += 1 except Exception as exc: # noqa: BLE001 stats["failed"] += 1 log.warning(f"⚠️ 删除实体失败 {name[:40]}: {exc}") return stats # ------------------------------------------------------------ 主流程 @classmethod def repair(cls, root: Path | None = None, dry_run: bool = False, auto_execute: bool = False) -> dict: root = Path(root or config.MEDIA_ROOT) log.info("=" * 60) log.info(f"🩺 Jellyfin 广告元数据修复{'(演练)' if dry_run else ''}:库根 {root}") client = JellyfinClient() items = client.all_items() targets = [it for it in items if cls.polluted_fields(it)] log.info(f" 全库条目 {len(items)} 个,其中 {len(targets)} 个带广告字段") if not dry_run and not auto_execute: try: answer = input(f"⚠️ 是否修复以上 {len(targets)} 个条目(含 NFO 清理)?[y/n/q]: ").strip().lower() except EOFError: log.warning("⛔ 没有可用的终端输入,按取消处理。") return {"cancelled": True} if answer not in {"y", "yes"}: log.info("💤 任务已由用户取消。") return {"cancelled": True} # 1) NFO 先清:否则下一次扫描会把广告工作室再抓回来 nfo = cls.clean_sidecars(root, dry_run=dry_run) log.info(f" NFO:扫 {nfo['scanned']} 个,清理 {nfo['changed']} 个" + (f",无权限 {nfo['denied']} 个" if nfo["denied"] else "")) # 2) 条目字段 fixed = cls.fix_items(client, items, targets, dry_run=dry_run) log.info(f" 条目:带广告 {fixed['polluted']} 个,修复 {fixed['fixed']} 个" + (f",失败 {fixed['failed']} 个" if fixed["failed"] else "") + (f",重新刮削 {fixed['refresh']} 个" if fixed["refresh"] else "")) # 3) 广告实体 entities = cls.purge_entities(client, dry_run=dry_run) log.info(f" 实体:发现 {entities['found']} 个,删除 {entities['deleted']} 个" + (f",失败 {entities['failed']} 个" if entities["failed"] else "")) # 4) 复查 remaining = None if dry_run: log.info(" 复查:演练模式跳过") else: remaining = 0 for item in client.all_items(): if cls.polluted_fields(item): remaining += 1 log.warning(f" ⚠️ 复查仍带广告: {item.get('Name', '')[:50]}") log.info(f" 复查:仍带广告的条目 {remaining} 个") log.info("=" * 60) return {"root": str(root), "items": len(items), "nfo": nfo, "fields": fixed, "entities": entities, "remaining": remaining, "dry_run": dry_run} @classmethod def write_report(cls, stats: dict) -> Path: path = config.JELLYFIN_REPORT_PATH path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(stats, ensure_ascii=False, indent=1), encoding="utf-8") return path