# src/core/utils.py import json import re import subprocess import unicodedata from pathlib import Path from core.constants import RegexPatterns class StringUtil: """字符串与文件命名安全处理工具""" # media_title 允许的最大字符数(留足技术标签,避免触碰文件系统 255 字节上限) MAX_MEDIA_TITLE = 120 # 字节上限:文件名总长受 255 字节限制,CJK 一个字 3 字节,不能只按字符截 MAX_MEDIA_TITLE_BYTES = 120 # 前后带空格的破折号(- – — −)整体视为分隔符 → 点 # 例:Mission: Impossible - The Final Reckoning → Mission.Impossible.The.Final.Reckoning _SPACED_DASH = re.compile(r"\s+[-–—−]\s+") # 白名单:字母/数字/下划线/连字符/点/撇号;其余(含路径特殊字符与空格)换成点 _NOT_ALLOWED = re.compile(r"[^\w\-.'’]+", re.UNICODE) @staticmethod def sanitize_title(title: str) -> str: """白名单清洗。 保留:字母(含中日韩、带重音)、数字、下划线、点、撇号、 以及词内连字符(Spider-Man)。 换成点:路径特殊字符(\\ / * ? : " < > |)、空格、其他标点。 删除:前后带空格的破折号(- 、– 、—)——它是分隔符,不是词的一部分。 例:C'è ancora domani → C'è.ancora.domani Mission: Impossible - The Final Reckoning → Mission.Impossible.The.Final.Reckoning """ if not title: return "" s = unicodedata.normalize("NFKC", str(title)) s = s.replace("’", "'").replace("‘", "'").replace("ʼ", "'") s = StringUtil._SPACED_DASH.sub(".", s) s = StringUtil._NOT_ALLOWED.sub(".", s) s = re.sub(r"\.{2,}", ".", s) s = re.sub(r"\.?-(?=\.|$)", "", s) # 「. - .」这类残渣 s = re.sub(r"\.{2,}", ".", s) return s.strip(". -") @staticmethod def truncate_bytes(text: str, limit: int) -> str: """按 UTF-8 字节截断(不切坏多字节字符),末尾多余的点去掉。 文件系统上限是 255 字节,CJK 一个字占 3 字节,只按字符数截会超限。 """ if not text: return "" raw = text.encode("utf-8") if len(raw) <= limit: return text return raw[:limit].decode("utf-8", errors="ignore").rstrip(". ") @staticmethod def media_title(title: str, fallback: str = "") -> str: """生成可直接用作文件名的标题:白名单清洗 + 超长截断。 title 为空或清洗后为空时退回 fallback(一般是 TMDB 本地化标题)。 """ for candidate in (title, fallback): s = StringUtil.sanitize_title(candidate) if s: s = s[:StringUtil.MAX_MEDIA_TITLE] return StringUtil.truncate_bytes(s, StringUtil.MAX_MEDIA_TITLE_BYTES).strip('.') return "" class FFprobeUtil: """FFprobe 探针调用与 JSON 解析工具""" @staticmethod def get_json(file_path: Path, *args) -> dict: cmd = ["ffprobe", "-v", "quiet", "-print_format", "json"] + list(args) + [str(file_path)] try: res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) if res.stdout.strip(): return json.loads(res.stdout) return {} except Exception: return {} class MediaUtil: """媒体文件分析与推断辅助工具""" @staticmethod def detect_subtitle_language(sub_path: Path) -> str: name = sub_path.name.lower() if RegexPatterns.SUB_LANG_CHT.search(name): return "zh-TW" if RegexPatterns.SUB_LANG_CHS.search(name): return "zh-CN" if RegexPatterns.SUB_LANG_ENG.search(name): return "en" try: content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000] if RegexPatterns.SUB_LANG_ZH_CHARS.search(content): return "zh-TW" if len(RegexPatterns.SUB_LANG_CHT_CHARS.findall(content)) > 5 else "zh-CN" return "und" except: return "und"