refactor(config): 设备能力/外部服务/阈值等硬编码收敛到 config.ini(P0+P1)

This commit is contained in:
ali
2026-11-20 11:11:42 +08:00
parent 0289ca9d66
commit cc46f8e3c3
15 changed files with 366 additions and 82 deletions
+133 -2
View File
@@ -1,6 +1,7 @@
# src/core/config.py
import configparser
import re
import sys
import os
from pathlib import Path
@@ -15,8 +16,22 @@ else:
CONFIG_PATH = BASE_DIR / 'config.ini'
# 广告特征正则的缺省值([Ads] patterns):逗号分隔的正则片段。
# 单独抽出来是为了让 ini 模板和「读不到配置时的回退」用同一份,避免两处漂移。
_DEFAULT_AD_PATTERNS = (
r"link3\.cc,yunpantv,ysepan\.com,TG@,Qqun@,WOW64\),Advanced Audio Codec Low Comp,"
r"912484288,TG[ _]?CHANNEL,TG频道,High Efficiency Video Coding,Chroma subsampling"
)
# 发布来源判定:`正则=标签`,按顺序命中第一个。
# 只认文件名里的 token(实测流参数分不出 WEB-DL 与 WEBRip),可按发布组习惯增删。
_DEFAULT_SOURCE_PATTERNS = (
"remux=BluRay.REMUX,blu-?ray|bd-?rip|bdrip=BluRay,web-?rip=WEBRip,web-?dl=WEB-DL,"
"hdtv=HDTV,dvdrip|dvd-?rip=DVDRip,hdrip=HDRip"
)
# 💡 初始配置模板:当文件不存在时自动生成
DEFAULT_CONFIG_CONTENT = """# Media Manager 初始配置文件
DEFAULT_CONFIG_CONTENT = f"""# Media Manager 初始配置文件
[Run]
# 命令行未指定时的默认执行参数(CLI 参数优先)
@@ -31,15 +46,32 @@ api_key =
language = zh-CN
timeout = 10
max_retries = 3
# 接口根地址(国内直连不稳时可换镜像/反代)
base_url = https://api.themoviedb.org/3
# 搜索候选池大小:标题精确匹配后最多再查前 N 个的详情
search_pool = 5
# TMDB 的「动画」类型 id,用于同名作品按动漫/真人目录消歧
anime_genre_id = 16
[Media]
# 需要整理的视频扩展名(决定流水线处理哪些文件)
supported_exts = .mkv,.mp4,.avi
# 扫描/识别用的视频扩展名(比上面宽:综艺、特典目录常见 .ts/.m2ts/.mov)
video_exts = .mkv,.mp4,.avi,.ts,.m2ts,.mov
# 跟随视频一起改名的附属文件;字幕包含在内,改名时保留原有语言/标记后缀
sidecar_exts = .nfo,.jpg,.jpeg,.png,.bif,.xml,.srt,.ass,.ssa,.vtt
exclude_dirs =
# 库里的分类目录:用于同名作品按「动画 / 真人」消歧
anime_dirs = 动漫节目,动漫电影
live_dirs = 电视节目,电影,综艺
[Ads]
# 字面量关键字(直接匹配,逗号分隔);音轨标题、容器标签里命中即处理
keywords = TG频道,@yunpantv
# 正则特征串(逗号分隔);与上面的 keywords 一起合成匹配规则
patterns = {_DEFAULT_AD_PATTERNS}
# 整理时清理文件容器内的广告元数据(无损重封装)
clean_tags = true
[Subtitles]
# 导出格式:ass(原始保真,默认)/ srt(清洗后);可写 ass,srt 同时导出
@@ -64,6 +96,13 @@ skip_perfect_match = true
watch_delay = 15
remux_bitrate_1080p = 22.0
remux_bitrate_4k = 45.0
# 综艺单集数据(TMDB 播出日期)缓存有效小时数
variety_cache_hours = 24
# 重封装(去广告元数据)单文件超时秒数与体积容差
remux_timeout = 7200
remux_size_tolerance = 0.10
# 重封装前要求的磁盘余量系数(文件体积 × 该系数)
remux_free_space_factor = 1.05
[Archive]
# 媒体库根目录(media-archive 使用)
@@ -74,6 +113,11 @@ refresh_jellyfin = true
[Jellyfin]
url = http://127.0.0.1:8096
api_key =
# API 请求超时秒数与重试次数
timeout = 60
retries = 3
# 广告元数据修复报告(相对路径 = 仓库根目录)
report_path = adfix-report.json
[Compatibility]
# 电视直传码率上限(1x1 WiFi 实测 ~70Mbps)
@@ -90,12 +134,37 @@ write_report = true
report_dir = /hdd/sda1/Quark-Down/_reports
# 报告保留份数(<=0 表示不清理)
report_keep = 6
# 电视(Amlogic S905X3 + Jellyfin Android TV)实测可直传的视频编码
direct_video_codecs = hevc,h264,vc1,mpeg2video
# 可直传的字幕编码(含图形字幕;不在表里的只提示不拦截)
direct_sub_codecs = ass,ssa,subrip,srt,webvtt,mov_text,hdmv_pgs_subtitle,dvd_subtitle,dvb_subtitle,idx
# 算作「ASS 特效字幕」的编码
ass_codecs = ass,ssa
# HDR 的 color_transfer 取值
hdr_transfers = smpte2084,arib-std-b67
# 电视能直接播的容器
direct_containers = .mkv,.mp4
# 超过该高度需要服务端缩放转码
max_height = 2160
[System]
log_file_path = media_manager.log
tmdb_cache_path = tmdb_data.json
console_log_level = INFO
file_log_level = DEBUG
# 启动时检查的二进制(在 PATH 里找不到就报错退出)
required_tools = ffmpeg,ffprobe,mkvpropedit
[Naming]
# 媒体标题:先按字符数截断,再按 UTF-8 字节数截断(文件名总长受 255 字节限制)
title_max_chars = 120
title_max_bytes = 120
# 高帧率才写进文件名:>= 该值记 50fps / 60fps
fps_min = 49
# 综艺期名截断长度
episode_label_chars = 40
# 发布来源判定:正则=标签(按顺序取第一个命中)
source_patterns = {_DEFAULT_SOURCE_PATTERNS}
"""
_parser = configparser.ConfigParser()
@@ -123,6 +192,21 @@ def _csv_set_or_all(section: str, key: str, fallback: str = 'all'):
return {item.strip() for item in raw.split(',') if item.strip()}
def _csv_list(section: str, key: str, fallback: str = '') -> list:
raw = _parser.get(section, key, fallback=fallback).strip()
return [item.strip() for item in raw.split(',') if item.strip()]
def _pairs(section: str, key: str, fallback: str = '') -> list[tuple[str, str]]:
"""`正则=标签,正则=标签` → [(正则, 标签)],按书写顺序。"""
pairs = []
for item in _csv_list(section, key, fallback=fallback):
pattern, sep, label = item.partition('=')
if sep and pattern.strip() and label.strip():
pairs.append((pattern.strip(), label.strip()))
return pairs
# --- 核心数据解耦 ---
# 1. TMDB 配置
@@ -130,9 +214,16 @@ TMDB_API_KEY = _parser.get('TMDB', 'api_key', fallback='')
TMDB_LANGUAGE = _parser.get('TMDB', 'language', fallback='zh-CN')
TMDB_TIMEOUT = _parser.getint('TMDB', 'timeout', fallback=10)
TMDB_MAX_RETRIES = _parser.getint('TMDB', 'max_retries', fallback=3)
TMDB_BASE_URL = (_parser.get('TMDB', 'base_url', fallback='https://api.themoviedb.org/3').strip()
or 'https://api.themoviedb.org/3').rstrip('/')
TMDB_SEARCH_POOL = _parser.getint('TMDB', 'search_pool', fallback=5)
TMDB_ANIME_GENRE_ID = _parser.getint('TMDB', 'anime_genre_id', fallback=16)
# 2. 媒体与广告
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts', fallback='.mkv,.mp4,.avi').lower().split(','))
# 扫描/识别用的宽集:综艺、特典目录里常见 .ts/.m2ts/.mov
VIDEO_EXTS = {e.lower() for e in _csv_set(
'Media', 'video_exts', fallback='.mkv,.mp4,.avi,.ts,.m2ts,.mov')}
SIDECAR_EXTS = set(_parser.get('Media', 'sidecar_exts',
fallback='.nfo,.jpg,.jpeg,.png,.bif,.xml,.srt,.ass,.ssa,.vtt').lower().split(','))
EXCLUDE_DIRS = [d.strip() for d in _parser.get('Media', 'exclude_dirs', fallback='').split(',') if d.strip()]
@@ -143,7 +234,19 @@ EXTRAS_DIRS = [d.strip().lower() for d in _parser.get(
'Media', 'extras_dirs',
fallback='extras,featurettes,behind the scenes,deleted scenes,interviews,scenes,shorts,trailers,samples'
).split(',') if d.strip()]
AD_KEYWORDS = _parser.get('Ads', 'keywords', fallback='推广信息').split(',')
# 同名作品按「动画 / 真人」消歧:库里是按这两个分类目录摆放的
ANIME_DIRS = _csv_set('Media', 'anime_dirs', fallback='动漫节目,动漫电影')
LIVE_DIRS = _csv_set('Media', 'live_dirs', fallback='电视节目,电影,综艺')
# 广告特征:keywords 是字面量(转义后匹配),patterns 是正则片段,二者合成一条规则。
# 这样「往配置里加关键词」对文件重封装、NFO 清理、Jellyfin 修复同时生效。
AD_KEYWORDS = _csv_list('Ads', 'keywords', fallback='推广信息')
_AD_PATTERN_PARTS = [re.escape(k) for k in AD_KEYWORDS] + _csv_list(
'Ads', 'patterns', fallback=_DEFAULT_AD_PATTERNS)
if not _AD_PATTERN_PARTS:
_AD_PATTERN_PARTS = [re.escape('推广信息')]
AD_PATTERN = re.compile('|'.join(_AD_PATTERN_PARTS), re.I)
# 整理时清理文件容器内的广告元数据(无损重封装)
CLEAN_AD_TAGS = _parser.getboolean('Ads', 'clean_tags', fallback=True)
@@ -184,6 +287,10 @@ SKIP_PERFECT_MATCH = _parser.getboolean('Features', 'skip_perfect_match', fallba
WATCH_DELAY = _parser.getint('Advanced', 'watch_delay', fallback=15)
REMUX_BITRATE_1080P = _parser.getfloat('Advanced', 'remux_bitrate_1080p', fallback=22.0)
REMUX_BITRATE_4K = _parser.getfloat('Advanced', 'remux_bitrate_4k', fallback=45.0)
VARIETY_CACHE_HOURS = _parser.getint('Advanced', 'variety_cache_hours', fallback=24)
REMUX_TIMEOUT = _parser.getint('Advanced', 'remux_timeout', fallback=7200)
REMUX_SIZE_TOLERANCE = _parser.getfloat('Advanced', 'remux_size_tolerance', fallback=0.10)
REMUX_FREE_SPACE_FACTOR = _parser.getfloat('Advanced', 'remux_free_space_factor', fallback=1.05)
# 7. 归档与 Jellyfin
_media_root = _parser.get('Archive', 'media_root', fallback='/hdd/sda1/media').strip()
@@ -191,6 +298,11 @@ MEDIA_ROOT = Path(_media_root)
REFRESH_JELLYFIN = _parser.getboolean('Archive', 'refresh_jellyfin', fallback=True)
JELLYFIN_URL = _parser.get('Jellyfin', 'url', fallback='http://127.0.0.1:8096').strip() or 'http://127.0.0.1:8096'
JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
JELLYFIN_TIMEOUT = _parser.getint('Jellyfin', 'timeout', fallback=60)
JELLYFIN_RETRIES = _parser.getint('Jellyfin', 'retries', fallback=3)
_raw_report_path = _parser.get('Jellyfin', 'report_path', fallback='adfix-report.json').strip() or 'adfix-report.json'
JELLYFIN_REPORT_PATH = (Path(_raw_report_path) if os.path.isabs(_raw_report_path)
else BASE_DIR.parent.parent / _raw_report_path)
# 7.5 入库前兼容性检查
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0)
@@ -205,6 +317,17 @@ PREFLIGHT_REPORT_DIR = Path(
or '/hdd/sda1/Quark-Down/_reports')
PREFLIGHT_REPORT_KEEP = _parser.getint('Compatibility', 'report_keep', fallback=6)
# 电视(Amlogic S905X3 + Jellyfin Android TV)的能力边界:换电视/换播放器只改这里
DIRECT_VIDEO_CODECS = _csv_set('Compatibility', 'direct_video_codecs',
fallback='hevc,h264,vc1,mpeg2video')
DIRECT_SUB_CODECS = _csv_set('Compatibility', 'direct_sub_codecs',
fallback='ass,ssa,subrip,srt,webvtt,mov_text,hdmv_pgs_subtitle,'
'dvd_subtitle,dvb_subtitle,idx')
ASS_CODECS = _csv_set('Compatibility', 'ass_codecs', fallback='ass,ssa')
HDR_TRANSFERS = _csv_set('Compatibility', 'hdr_transfers', fallback='smpte2084,arib-std-b67')
DIRECT_CONTAINERS = _csv_set('Compatibility', 'direct_containers', fallback='.mkv,.mp4')
MAX_HEIGHT = _parser.getint('Compatibility', 'max_height', fallback=2160)
# 8. 系统与日志路径
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log')
LOG_FILE_PATH = BASE_DIR / _raw_log_path if not os.path.isabs(_raw_log_path) else Path(_raw_log_path)
@@ -214,3 +337,11 @@ TMDB_CACHE_PATH = BASE_DIR / _raw_cache_path if not os.path.isabs(_raw_cache_pat
CONSOLE_LOG_LEVEL = _parser.get('System', 'console_log_level', fallback='INFO').upper()
FILE_LOG_LEVEL = _parser.get('System', 'file_log_level', fallback='DEBUG').upper()
REQUIRED_TOOLS = _csv_list('System', 'required_tools', fallback='ffmpeg,ffprobe,mkvpropedit')
# 9. 命名规则
TITLE_MAX_CHARS = _parser.getint('Naming', 'title_max_chars', fallback=120)
TITLE_MAX_BYTES = _parser.getint('Naming', 'title_max_bytes', fallback=120)
FPS_MIN = _parser.getfloat('Naming', 'fps_min', fallback=49.0)
EPISODE_LABEL_CHARS = _parser.getint('Naming', 'episode_label_chars', fallback=40)
SOURCE_PATTERNS = _pairs('Naming', 'source_patterns', fallback=_DEFAULT_SOURCE_PATTERNS)
+2 -2
View File
@@ -159,7 +159,7 @@ class MediaPipeline:
known = int(match.group(1)) if match else getattr(self.args, "show", None)
videos = [p for p in folder.rglob("*")
if p.is_file() and p.suffix.lower() in {".mkv", ".mp4", ".avi"}]
if p.is_file() and p.suffix.lower() in config.VIDEO_EXTS]
if not videos:
return None
probe = videos[0]
@@ -234,7 +234,7 @@ class MediaPipeline:
"""
from services.metaclean import MetaCleanService
files = [f for f in self.valid_files if f.suffix.lower() in (".mp4", ".mkv", ".mov", ".ts", ".m2ts")]
files = [f for f in self.valid_files if f.suffix.lower() in config.VIDEO_EXTS]
if not files:
return
hits = []
+3 -2
View File
@@ -2,12 +2,13 @@
import shutil
import subprocess
from core import config
from .exceptions import MediaDependencyError
from .logger import log # 💡 引入日志
def check_dependencies():
"""检查系统依赖是否已正确安装"""
tools = ['ffmpeg', 'ffprobe', 'mkvpropedit', 'mediainfo']
"""检查系统依赖是否已正确安装(列表见 config.ini [System] required_tools)"""
tools = list(config.REQUIRED_TOOLS)
log.debug(f"正在检查系统依赖: {', '.join(tools)}")
missing = [tool for tool in tools if not shutil.which(tool)]
+4 -5
View File
@@ -5,15 +5,14 @@ import re
import subprocess
import unicodedata
from pathlib import Path
from core import config
from core.constants import RegexPatterns
class StringUtil:
"""字符串与文件命名安全处理工具"""
# media_title 允许的最大字符数(留足技术标签,避免触碰文件系统 255 字节上限)
MAX_MEDIA_TITLE = 120
# 标题长度上限见 config.ini [Naming] title_max_chars / title_max_bytes
# 字节上限:文件名总长受 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+")
@@ -66,8 +65,8 @@ class StringUtil:
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('.')
s = s[:config.TITLE_MAX_CHARS]
return StringUtil.truncate_bytes(s, config.TITLE_MAX_BYTES).strip('.')
return ""
class FFprobeUtil:
+3 -2
View File
@@ -25,8 +25,9 @@ class MediaDirectoryWatcher(FileSystemEventHandler):
self._trigger(event.dest_path)
def _trigger(self, path):
# 只对核心媒体文件的变动敏感
if any(path.lower().endswith(ext) for ext in ['.mkv', '.mp4', '.avi']):
# 只对核心媒体文件的变动敏感(扩展名跟 [Media] supported_exts 走,
# 之前写死 .mkv/.mp4/.avi,配置里加的 .flv 落盘不会触发)
if any(path.lower().endswith(ext) for ext in config.SUPPORTED_EXTS):
if self._timer is not None:
self._timer.cancel()
# 重新启动倒计时 (防抖机制)
+8 -4
View File
@@ -29,7 +29,9 @@ from pathlib import Path
from core import config
from core.logger import log
from services.metaclean import AD_PATTERN
# 广告特征由 config.ini [Ads] keywords + patterns 合成(见 core/config.py)
AD_PATTERN = config.AD_PATTERN
# 参与扫描的字段:Jellyfin 界面里会显示成备注/类型/工作室/标签的那几个
_SCAN_FIELDS = "Path,Overview,Genres,Studios,Tags,Tagline,SeriesId"
@@ -67,7 +69,8 @@ class JellyfinClient:
# ---------------------------------------------------------------- HTTP
def _request(self, path: str, method: str = "GET", payload=None, params=None, retries: int = 3):
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)
@@ -79,7 +82,7 @@ class JellyfinClient:
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=60) as resp:
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:
@@ -359,6 +362,7 @@ class JellyfinAdFixService:
@classmethod
def write_report(cls, stats: dict) -> Path:
path = config.BASE_DIR.parent.parent / "adfix-report.json"
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
+5 -13
View File
@@ -134,16 +134,8 @@ class MediaInfoService:
"vc1": "VC1", "prores": "ProRes", "theora": "Theora",
}
# 来源:发布名里的 token 最可靠,流参数分不出 WEB-DL 与 WEBRip
SOURCE_PATTERNS = [
(r"remux", "BluRay.REMUX"),
(r"blu-?ray|bd-?rip|bdrip", "BluRay"),
(r"web-?rip", "WEBRip"),
(r"web-?dl", "WEB-DL"),
(r"hdtv", "HDTV"),
(r"dvdrip|dvd-?rip", "DVDRip"),
(r"hdrip", "HDRip"),
]
# 来源:发布名里的 token 最可靠,流参数分不出 WEB-DL 与 WEBRip。
# 正则与标签的对应表见 config.ini [Naming] source_patterns,可按发布组习惯增删。
@staticmethod
def _main_video_stream(streams: list) -> dict:
@@ -187,7 +179,7 @@ class MediaInfoService:
所以老文件改成 WEB-DL 后再回头猜只会更糟——只认名字。
"""
low = (name or "").lower()
for pattern, label in MediaInfoService.SOURCE_PATTERNS:
for pattern, label in config.SOURCE_PATTERNS:
if re.search(pattern, low):
return label
return "BluRay.REMUX" if tags.get("is_remux") else "WEB-DL"
@@ -210,14 +202,14 @@ class MediaInfoService:
@staticmethod
def fps_tag(stream: dict) -> str:
"""高帧率才写进文件名:>=49 记 50fps / 60fps,其余不写。"""
"""高帧率才写进文件名:>= config.FPS_MIN 记 50fps / 60fps,其余不写。"""
raw = stream.get("avg_frame_rate") or stream.get("r_frame_rate") or "0/0"
try:
num, den = raw.split("/")
fps = float(num) / float(den) if float(den) else 0.0
except (ValueError, ZeroDivisionError):
return ""
if fps >= 49:
if fps >= config.FPS_MIN:
return f"{round(fps)}fps"
return ""
+8 -13
View File
@@ -13,24 +13,18 @@ Jellyfin 扫描时会把这些标签读成 plot / genre 写进 NFO,界面上
from __future__ import annotations
import os
import re
import shutil
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
from core import config
from core.logger import log
from core.utils import FFprobeUtil
# 广告特征:域名、Telegram、QQ 群、以及魔改 ffmpeg 特有的编码描述
# TG_CHANNEL / TG频道 是发布组把「频道名」直接塞进 ©cmt 时留下的,Jellyfin 会把它
# 当成工作室(studio)存下来;High Efficiency Video Coding 是同一批魔改 ffmpeg 把
# 编码器描述写进 genre 的结果(截断后只剩前半截),所以都要算命中
AD_PATTERN = re.compile(
r"link3\.cc|yunpantv|ysepan\.com|TG@|Qqun@|WOW64\)|Advanced Audio Codec Low Comp"
r"|912484288|TG[ _]?CHANNEL|TG频道|High Efficiency Video Coding|Chroma subsampling",
re.I,
)
# 广告特征由 config.ini [Ads] keywords(字面量)+ patterns(正则)合成,
# 定义在 core/config.py;这里保留同名变量给本模块与其它调用方用。
AD_PATTERN = config.AD_PATTERN
class MetaCleanService:
@@ -44,7 +38,7 @@ class MetaCleanService:
@staticmethod
def _has_space(path: Path) -> bool:
try:
need = int(path.stat().st_size * 1.05)
need = int(path.stat().st_size * config.REMUX_FREE_SPACE_FACTOR)
return shutil.disk_usage(path.parent).free > need
except OSError:
return False
@@ -68,7 +62,7 @@ class MetaCleanService:
result = None
for cmd in attempts:
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
result = subprocess.run(cmd, capture_output=True, text=True, timeout=config.REMUX_TIMEOUT)
except subprocess.TimeoutExpired:
tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装超时: {path.name}")
@@ -85,7 +79,8 @@ class MetaCleanService:
# 体积变化过大说明流有问题,放弃替换
old_size = path.stat().st_size
new_size = tmp.stat().st_size
if not (old_size * 0.90 <= new_size <= old_size * 1.10):
tolerance = config.REMUX_SIZE_TOLERANCE
if not (old_size * (1 - tolerance) <= new_size <= old_size * (1 + tolerance)):
tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装后体积异常({old_size} → {new_size}),保留原文件: {path.name}")
return False
+14 -18
View File
@@ -37,17 +37,13 @@ class PreflightResult:
class PreflightService:
"""ffprobe 体检 + 补 AC3 音轨 + 报告输出。"""
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码
# 电视(Amlogic S905X3 + Jellyfin Android TV)实测可解码的编码:
# HEVC / H.264 / VC-1(的士速递4 实测 DirectPlay)/ MPEG-2(功夫、非洲和尚实测 DirectPlay)
# MPEG-4 实测被转码(花儿与少年 S03),故不列入
VIDEO_OK = {"hevc", "h264", "vc1", "mpeg2video"}
SUB_OK = {
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text",
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
}
HDR_TRANSFERS = {"smpte2084", "arib-std-b67"}
ASS_OK = {"ass", "ssa"}
# 电视能力边界全部来自 config.ini [Compatibility]:
# direct_video_codecs / direct_sub_codecs / ass_codecs / hdr_transfers
# direct_containers / max_height
# 换电视或换播放器时改配置即可,不用动代码。
# 历史实测(Amlogic S905X3 + Jellyfin Android TV):
# HEVC / H.264 / VC-1(的士速递4)/ MPEG-2(功夫、非洲和尚)可 DirectPlay;
# MPEG-4 实测被转码(花儿与少年 S03),故缺省不列入。
# ------------------------------------------------------------------ 评估
@@ -125,22 +121,22 @@ class PreflightService:
r.info.update(
codec=codec, width=width, height=height, level=level,
mbps=round(mbps, 1), dv_profile=dv_profile,
hdr=transfer in cls.HDR_TRANSFERS, color_transfer=transfer,
hdr=transfer in config.HDR_TRANSFERS, color_transfer=transfer,
size_gb=round(size_gb, 1), audio=audios, subs=subs,
duration=int(float(fmt.get("duration") or 0)),
)
# 1. 容器
if path.suffix.lower() not in {".mkv", ".mp4"}:
if path.suffix.lower() not in config.DIRECT_CONTAINERS:
cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码")
r.actions.append("server_transcode")
# 2. 视频编码
if codec not in cls.VIDEO_OK:
if codec not in config.DIRECT_VIDEO_CODECS:
cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码")
r.actions.append("server_transcode")
# 3. 分辨率
if height > 2160:
cls._raise(r, TRANSCODE, f"{height}p 超过 4K,需服务端缩放转码")
if height > config.MAX_HEIGHT:
cls._raise(r, TRANSCODE, f"{height}p 超过 {config.MAX_HEIGHT}p,需服务端缩放转码")
r.actions.append("server_transcode")
# 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解
if codec == "hevc" and isinstance(level, int) and level > 153:
@@ -159,11 +155,11 @@ class PreflightService:
# 7. 音频:只记录,不参与判定(默认音轨保持原样,音频是否转码交给 Jellyfin)
# 8. 字幕编码
# 8. 字幕编码
bad = [s["codec"] for s in subs if s["codec"] not in cls.SUB_OK]
bad = [s["codec"] for s in subs if s["codec"] not in config.DIRECT_SUB_CODECS]
if bad:
r.reasons.append(f"未知字幕编码: {sorted(set(bad))}")
# 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时
has_ass = any(s["codec"] in cls.ASS_OK for s in subs)
has_ass = any(s["codec"] in config.ASS_CODECS for s in subs)
if has_ass and size_gb > config.PRE_EXTRACT_ASS_GB and 'ass' not in config.SUBTITLE_EXPORT:
cls._raise(r, PREP, f"内嵌 ASS + {size_gb:.0f}GB 大文件,需提前抽外挂")
r.actions.append("extract_ass")
+2 -1
View File
@@ -19,6 +19,7 @@ import xml.etree.ElementTree as ET
from collections import defaultdict
from pathlib import Path
from core import config
from core.logger import log
from services.variety import VarietyService
@@ -121,7 +122,7 @@ class SpecialsService:
def apply(cls, folder: Path, plans: list[dict]) -> dict:
index: dict[tuple[str, int], Path] = {}
for path in folder.rglob("*"):
if path.is_file() and path.suffix.lower() in (".mp4", ".mkv"):
if path.is_file() and path.suffix.lower() in config.VIDEO_EXTS:
match = _EP_RE.search(path.name)
if match:
index.setdefault((match.group(1), int(match.group(2))), path)
+9 -10
View File
@@ -51,7 +51,7 @@ class TMDBService:
endpoint = "tv" if mtype == "tv" else "movie"
try:
resp = session.get(f"https://api.themoviedb.org/3/{endpoint}/{tmdb_id}",
resp = session.get(f"{config.TMDB_BASE_URL}/{endpoint}/{tmdb_id}",
params=cls._params(), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001
log.warning(f"⚠️ TMDB 详情请求异常 [{mtype}/{tmdb_id}]: {exc}")
@@ -73,7 +73,7 @@ class TMDBService:
if year_s:
extra["first_air_date_year" if mtype == "tv" else "year"] = year_s
try:
resp = session.get(f"https://api.themoviedb.org/3/search/{endpoint}",
resp = session.get(f"{config.TMDB_BASE_URL}/search/{endpoint}",
params=cls._params(extra), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001
log.warning(f"⚠️ TMDB 搜索异常 [{title}]: {exc}")
@@ -185,7 +185,7 @@ class TMDBService:
if store.normalize_title(r.get("title") or r.get("name") or "") == target
or store.normalize_title(r.get("original_title") or r.get("original_name") or "") == target
]
pool = (exact or results)[:5]
pool = (exact or results)[:max(1, config.TMDB_SEARCH_POOL)]
entities = []
for result in pool:
@@ -223,9 +223,8 @@ class TMDBService:
# 库里按「动漫 / 真人」分目录,同名候选可用所在分类消歧:
# 苍兰诀就是典型——动漫版 tv/206534(2 季 50 集)与真人版 tv/130368(1 季 36 集)同名。
ANIME_DIRS = {"动漫节目", "动漫电影"}
LIVE_DIRS = {"电视节目", "电影", "综艺"}
ANIME_GENRE_ID = 16
# 分类目录与「动画」类型 id 见 config.ini [Media] anime_dirs / live_dirs 与
# [TMDB] anime_genre_id(换库结构时改配置即可)。
@classmethod
def _prefer_by_category(cls, path, entities):
@@ -234,16 +233,16 @@ class TMDBService:
parts = set(Path(path).parts)
except (TypeError, ValueError):
return None
if parts & cls.ANIME_DIRS:
if parts & config.ANIME_DIRS:
want_anime = True
elif parts & cls.LIVE_DIRS:
elif parts & config.LIVE_DIRS:
want_anime = False
else:
return None
def is_anime(entity):
genres = entity.get("details", {}).get("genres") or []
return cls.ANIME_GENRE_ID in {g.get("id") for g in genres}
return config.TMDB_ANIME_GENRE_ID in {g.get("id") for g in genres}
picked = [e for e in entities if is_anime(e) == want_anime]
return picked or None
@@ -349,7 +348,7 @@ class TMDBService:
return None
if key in cls._dead_ids:
return None
url = f"https://api.themoviedb.org/3/{mtype}/{tmdb_id}/season/{season_number}"
url = f"{config.TMDB_BASE_URL}/{mtype}/{tmdb_id}/season/{season_number}"
try:
resp = session.get(url, params=cls._params(), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001
+7 -7
View File
@@ -43,7 +43,8 @@ _EP_NAME_SPECIAL = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋
class VarietyService:
VIDEO_EXTS = {".mkv", ".mp4", ".avi", ".ts", ".m2ts", ".mov"}
# 扫描用的视频扩展名(比 [Media] supported_exts 宽,含 .ts/.m2ts/.mov)
VIDEO_EXTS = config.VIDEO_EXTS
# ---------------------------------------------------------------- 日期与季
@@ -86,9 +87,8 @@ class VarietyService:
# ---------------------------------------------------------------- TMDB 索引
# TMDB 单集数据缓存有效期:综艺周更,超过这个时间必须重拉,
# 否则新一期不会出现在索引里。
CACHE_TTL_HOURS = 24
# TMDB 单集数据缓存有效期见 config.ini [Advanced] variety_cache_hours:
# 综艺周更,超过这个时间必须重拉,否则新一期不会出现在索引里。
@classmethod
def _fresh(cls, stamp: str) -> bool:
@@ -99,7 +99,7 @@ class VarietyService:
if when.tzinfo is None:
when = when.replace(tzinfo=datetime.now().astimezone().tzinfo)
age = datetime.now().astimezone() - when
return age.total_seconds() <= cls.CACHE_TTL_HOURS * 3600
return age.total_seconds() <= config.VARIETY_CACHE_HOURS * 3600
@classmethod
def _index_from_cache(cls, payload: dict) -> dict:
@@ -153,7 +153,7 @@ class VarietyService:
cached = entity.get("episode_air_dates") or {}
if cached and cls._fresh(entity.get("episodes_fetched_at") or ""):
index = cls._index_from_cache(cached)
log.info(f"📅 TMDB 索引命中缓存({cls.CACHE_TTL_HOURS}h 内,{len(index)} 个播出日期)")
log.info(f"📅 TMDB 索引命中缓存({config.VARIETY_CACHE_HOURS}h 内,{len(index)} 个播出日期)")
return index
session = TMDBService._get_session()
@@ -353,7 +353,7 @@ class VarietyService:
# 期名用「-」接在技术标签之后:`-<播出日期>.<期名>`
# 日期写成 YYYYMMDD,既能一眼看出播出时间,也让常规整理识别为已规范。
ep_name = StringUtil.sanitize_title(candidate["name"])[:40].strip(".")
ep_name = StringUtil.sanitize_title(candidate["name"])[:config.EPISODE_LABEL_CHARS].strip(".")
air_date = (candidate.get("air_date") or "").replace("-", "")
tail = ".".join(part for part in (air_date, ep_name) if part)
if tail: