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
+53
View File
@@ -100,6 +100,22 @@ assets/ # scenemarshal.png / .ico
default_mode = auto default_mode = auto
default_path = default_path =
[TMDB]
base_url = https://api.themoviedb.org/3 # 国内直连不稳时可换镜像/反代
search_pool = 5 # 标题精确匹配后最多再查几个候选的详情
anime_genre_id = 16
[Media]
supported_exts = .mkv,.mp4,.avi # 流水线处理哪些
video_exts = .mkv,.mp4,.avi,.ts,.m2ts,.mov # 扫描/识别用的宽集
anime_dirs = 动漫节目,动漫电影 # 同名作品按分类目录消歧
live_dirs = 电视节目,电影,综艺
[Ads]
keywords = TG频道,@yunpantv # 字面量(音轨标题/标签里命中就处理)
patterns = link3\.cc,yunpantv,..,TG[ _]?CHANNEL # 正则,逗号分隔
clean_tags = true
[Subtitles] [Subtitles]
export = ass # 内嵌字幕默认导出 ASS(ass 轨 -c:s copy 保真) export = ass # 内嵌字幕默认导出 ASS(ass 轨 -c:s copy 保真)
languages = zh-CN,zh-TW,en,und languages = zh-CN,zh-TW,en,und
@@ -116,6 +132,13 @@ export_text_subs = true # TRANSCODE 片源若无外挂字幕则补 SRT
write_report = true write_report = true
report_dir = /hdd/sda1/Quark-Down/_reports report_dir = /hdd/sda1/Quark-Down/_reports
report_keep = 6 report_keep = 6
# 电视能力边界(换电视/播放器只改这几行)
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_codecs = ass,ssa
hdr_transfers = smpte2084,arib-std-b67
direct_containers = .mkv,.mp4
max_height = 2160
[Archive] [Archive]
media_root = /hdd/sda1/media media_root = /hdd/sda1/media
@@ -124,8 +147,38 @@ refresh_jellyfin = true
[Jellyfin] [Jellyfin]
url = http://127.0.0.1:8096 url = http://127.0.0.1:8096
api_key = <在服务器 config.ini 里> api_key = <在服务器 config.ini 里>
timeout = 60
retries = 3
report_path = adfix-report.json
[Naming]
title_max_chars = 120 # 标题先按字符截断
title_max_bytes = 120 # 再按 UTF-8 字节截断(文件名 255 字节上限)
fps_min = 49 # >= 该帧率才写 50fps/60fps
episode_label_chars = 40 # 综艺期名截断
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
[Advanced]
watch_delay = 15
remux_bitrate_1080p = 22.0
remux_bitrate_4k = 45.0
variety_cache_hours = 24 # 综艺单集播出日期缓存
remux_timeout = 7200 # 去广告重封装单文件超时(秒)
remux_size_tolerance = 0.10 # 重封装前后体积容差
remux_free_space_factor = 1.05
[System]
log_file_path = media_manager.log
tmdb_cache_path = tmdb_data.json
console_log_level = INFO
file_log_level = DEBUG
required_tools = ffmpeg,ffprobe,mkvpropedit # 启动自检
``` ```
所有项都有缺省值,老 `config.ini` 不补也能跑(缺项自动回落到代码里的默认值);
`scripts/config_upgrade.py` 可以把新增项批量补进已有配置。日常最常改的是
`[Ads] keywords/patterns`(新广告特征)和 `[Compatibility]`(换电视)。
## 6. 兼容性体检(preflight) ## 6. 兼容性体检(preflight)
四档结论: 四档结论:
+4 -3
View File
@@ -58,9 +58,10 @@ MEDIA_UID=0 media-rename -p /hdd/sda1/media jellyfin-fix --yes
`AirsAfterSeasonNumber`,存在 `BaseItems.Data` 的 JSON 里)原样保留: `AirsAfterSeasonNumber`,存在 `BaseItems.Data` 的 JSON 里)原样保留:
修前 457 条带这三个字段、437 条已放置,修后数字不变。 修前 457 条带这三个字段、437 条已放置,修后数字不变。
- NFO 用 `ElementTree` 读改写,只删命中的元素,其它标签(plot/actor/art/tmdbid…)原样保留。 - NFO 用 `ElementTree` 读改写,只删命中的元素,其它标签(plot/actor/art/tmdbid…)原样保留。
- 广告特征串同时补进了 `MetaCleanService.AD_PATTERN`: - 广告特征不再是写死的正则:`config.ini [Ads] keywords`(字面量)+ `[Ads] patterns`(正则,
新增 `TG[ _]?CHANNEL`、`TG频道`、`High Efficiency Video Coding`、`Chroma subsampling`, 逗号分隔)合成一条规则,文件重封装、NFO 清理、Jellyfin 修复共用同一份。加新特征直接改配置,
`clean_nfo()` 也把 `studio`、`tag` 纳入清理,这样整理流水线以后再遇到同样的片源会顺手清掉。 不用动代码。`clean_nfo()` 也把 `studio`、`tag` 纳入清理,这样整理流水线以后再遇到同样的片源
会顺手清掉。
## 五、验证(2026-11-20 10:46,两轮修完) ## 五、验证(2026-11-20 10:46,两轮修完)
+133 -2
View File
@@ -1,6 +1,7 @@
# src/core/config.py # src/core/config.py
import configparser import configparser
import re
import sys import sys
import os import os
from pathlib import Path from pathlib import Path
@@ -15,8 +16,22 @@ else:
CONFIG_PATH = BASE_DIR / 'config.ini' 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] [Run]
# 命令行未指定时的默认执行参数(CLI 参数优先) # 命令行未指定时的默认执行参数(CLI 参数优先)
@@ -31,15 +46,32 @@ api_key =
language = zh-CN language = zh-CN
timeout = 10 timeout = 10
max_retries = 3 max_retries = 3
# 接口根地址(国内直连不稳时可换镜像/反代)
base_url = https://api.themoviedb.org/3
# 搜索候选池大小:标题精确匹配后最多再查前 N 个的详情
search_pool = 5
# TMDB 的「动画」类型 id,用于同名作品按动漫/真人目录消歧
anime_genre_id = 16
[Media] [Media]
# 需要整理的视频扩展名(决定流水线处理哪些文件)
supported_exts = .mkv,.mp4,.avi 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 sidecar_exts = .nfo,.jpg,.jpeg,.png,.bif,.xml,.srt,.ass,.ssa,.vtt
exclude_dirs = exclude_dirs =
# 库里的分类目录:用于同名作品按「动画 / 真人」消歧
anime_dirs = 动漫节目,动漫电影
live_dirs = 电视节目,电影,综艺
[Ads] [Ads]
# 字面量关键字(直接匹配,逗号分隔);音轨标题、容器标签里命中即处理
keywords = TG频道,@yunpantv keywords = TG频道,@yunpantv
# 正则特征串(逗号分隔);与上面的 keywords 一起合成匹配规则
patterns = {_DEFAULT_AD_PATTERNS}
# 整理时清理文件容器内的广告元数据(无损重封装)
clean_tags = true
[Subtitles] [Subtitles]
# 导出格式:ass(原始保真,默认)/ srt(清洗后);可写 ass,srt 同时导出 # 导出格式:ass(原始保真,默认)/ srt(清洗后);可写 ass,srt 同时导出
@@ -64,6 +96,13 @@ skip_perfect_match = true
watch_delay = 15 watch_delay = 15
remux_bitrate_1080p = 22.0 remux_bitrate_1080p = 22.0
remux_bitrate_4k = 45.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] [Archive]
# 媒体库根目录(media-archive 使用) # 媒体库根目录(media-archive 使用)
@@ -74,6 +113,11 @@ refresh_jellyfin = true
[Jellyfin] [Jellyfin]
url = http://127.0.0.1:8096 url = http://127.0.0.1:8096
api_key = api_key =
# API 请求超时秒数与重试次数
timeout = 60
retries = 3
# 广告元数据修复报告(相对路径 = 仓库根目录)
report_path = adfix-report.json
[Compatibility] [Compatibility]
# 电视直传码率上限(1x1 WiFi 实测 ~70Mbps) # 电视直传码率上限(1x1 WiFi 实测 ~70Mbps)
@@ -90,12 +134,37 @@ write_report = true
report_dir = /hdd/sda1/Quark-Down/_reports report_dir = /hdd/sda1/Quark-Down/_reports
# 报告保留份数(<=0 表示不清理) # 报告保留份数(<=0 表示不清理)
report_keep = 6 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] [System]
log_file_path = media_manager.log log_file_path = media_manager.log
tmdb_cache_path = tmdb_data.json tmdb_cache_path = tmdb_data.json
console_log_level = INFO console_log_level = INFO
file_log_level = DEBUG 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() _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()} 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 配置 # 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_LANGUAGE = _parser.get('TMDB', 'language', fallback='zh-CN')
TMDB_TIMEOUT = _parser.getint('TMDB', 'timeout', fallback=10) TMDB_TIMEOUT = _parser.getint('TMDB', 'timeout', fallback=10)
TMDB_MAX_RETRIES = _parser.getint('TMDB', 'max_retries', fallback=3) 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. 媒体与广告 # 2. 媒体与广告
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts', fallback='.mkv,.mp4,.avi').lower().split(',')) 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', SIDECAR_EXTS = set(_parser.get('Media', 'sidecar_exts',
fallback='.nfo,.jpg,.jpeg,.png,.bif,.xml,.srt,.ass,.ssa,.vtt').lower().split(',')) 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()] 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', 'Media', 'extras_dirs',
fallback='extras,featurettes,behind the scenes,deleted scenes,interviews,scenes,shorts,trailers,samples' fallback='extras,featurettes,behind the scenes,deleted scenes,interviews,scenes,shorts,trailers,samples'
).split(',') if d.strip()] ).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) 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) WATCH_DELAY = _parser.getint('Advanced', 'watch_delay', fallback=15)
REMUX_BITRATE_1080P = _parser.getfloat('Advanced', 'remux_bitrate_1080p', fallback=22.0) REMUX_BITRATE_1080P = _parser.getfloat('Advanced', 'remux_bitrate_1080p', fallback=22.0)
REMUX_BITRATE_4K = _parser.getfloat('Advanced', 'remux_bitrate_4k', fallback=45.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 # 7. 归档与 Jellyfin
_media_root = _parser.get('Archive', 'media_root', fallback='/hdd/sda1/media').strip() _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) 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_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_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 入库前兼容性检查 # 7.5 入库前兼容性检查
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0) 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') or '/hdd/sda1/Quark-Down/_reports')
PREFLIGHT_REPORT_KEEP = _parser.getint('Compatibility', 'report_keep', fallback=6) 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. 系统与日志路径 # 8. 系统与日志路径
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log') _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) 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() CONSOLE_LOG_LEVEL = _parser.get('System', 'console_log_level', fallback='INFO').upper()
FILE_LOG_LEVEL = _parser.get('System', 'file_log_level', fallback='DEBUG').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) known = int(match.group(1)) if match else getattr(self.args, "show", None)
videos = [p for p in folder.rglob("*") 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: if not videos:
return None return None
probe = videos[0] probe = videos[0]
@@ -234,7 +234,7 @@ class MediaPipeline:
""" """
from services.metaclean import MetaCleanService 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: if not files:
return return
hits = [] hits = []
+3 -2
View File
@@ -2,12 +2,13 @@
import shutil import shutil
import subprocess import subprocess
from core import config
from .exceptions import MediaDependencyError from .exceptions import MediaDependencyError
from .logger import log # 💡 引入日志 from .logger import log # 💡 引入日志
def check_dependencies(): def check_dependencies():
"""检查系统依赖是否已正确安装""" """检查系统依赖是否已正确安装(列表见 config.ini [System] required_tools)"""
tools = ['ffmpeg', 'ffprobe', 'mkvpropedit', 'mediainfo'] tools = list(config.REQUIRED_TOOLS)
log.debug(f"正在检查系统依赖: {', '.join(tools)}") log.debug(f"正在检查系统依赖: {', '.join(tools)}")
missing = [tool for tool in tools if not shutil.which(tool)] missing = [tool for tool in tools if not shutil.which(tool)]
+4 -5
View File
@@ -5,15 +5,14 @@ import re
import subprocess import subprocess
import unicodedata import unicodedata
from pathlib import Path from pathlib import Path
from core import config
from core.constants import RegexPatterns from core.constants import RegexPatterns
class StringUtil: class StringUtil:
"""字符串与文件命名安全处理工具""" """字符串与文件命名安全处理工具"""
# media_title 允许的最大字符数(留足技术标签,避免触碰文件系统 255 字节上限) # 标题长度上限见 config.ini [Naming] title_max_chars / title_max_bytes
MAX_MEDIA_TITLE = 120
# 字节上限:文件名总长受 255 字节限制,CJK 一个字 3 字节,不能只按字符截 # 字节上限:文件名总长受 255 字节限制,CJK 一个字 3 字节,不能只按字符截
MAX_MEDIA_TITLE_BYTES = 120
# 前后带空格的破折号(- – — −)整体视为分隔符 → 点 # 前后带空格的破折号(- – — −)整体视为分隔符 → 点
# 例:Mission: Impossible - The Final Reckoning → Mission.Impossible.The.Final.Reckoning # 例:Mission: Impossible - The Final Reckoning → Mission.Impossible.The.Final.Reckoning
_SPACED_DASH = re.compile(r"\s+[-–—−]\s+") _SPACED_DASH = re.compile(r"\s+[-–—−]\s+")
@@ -66,8 +65,8 @@ class StringUtil:
for candidate in (title, fallback): for candidate in (title, fallback):
s = StringUtil.sanitize_title(candidate) s = StringUtil.sanitize_title(candidate)
if s: if s:
s = s[:StringUtil.MAX_MEDIA_TITLE] s = s[:config.TITLE_MAX_CHARS]
return StringUtil.truncate_bytes(s, StringUtil.MAX_MEDIA_TITLE_BYTES).strip('.') return StringUtil.truncate_bytes(s, config.TITLE_MAX_BYTES).strip('.')
return "" return ""
class FFprobeUtil: class FFprobeUtil:
+3 -2
View File
@@ -25,8 +25,9 @@ class MediaDirectoryWatcher(FileSystemEventHandler):
self._trigger(event.dest_path) self._trigger(event.dest_path)
def _trigger(self, path): def _trigger(self, path):
# 只对核心媒体文件的变动敏感 # 只对核心媒体文件的变动敏感(扩展名跟 [Media] supported_exts 走,
if any(path.lower().endswith(ext) for ext in ['.mkv', '.mp4', '.avi']): # 之前写死 .mkv/.mp4/.avi,配置里加的 .flv 落盘不会触发)
if any(path.lower().endswith(ext) for ext in config.SUPPORTED_EXTS):
if self._timer is not None: if self._timer is not None:
self._timer.cancel() self._timer.cancel()
# 重新启动倒计时 (防抖机制) # 重新启动倒计时 (防抖机制)
+8 -4
View File
@@ -29,7 +29,9 @@ from pathlib import Path
from core import config from core import config
from core.logger import log 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 界面里会显示成备注/类型/工作室/标签的那几个 # 参与扫描的字段:Jellyfin 界面里会显示成备注/类型/工作室/标签的那几个
_SCAN_FIELDS = "Path,Overview,Genres,Studios,Tags,Tagline,SeriesId" _SCAN_FIELDS = "Path,Overview,Genres,Studios,Tags,Tagline,SeriesId"
@@ -67,7 +69,8 @@ class JellyfinClient:
# ---------------------------------------------------------------- HTTP # ---------------------------------------------------------------- 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 = dict(params or {})
params.setdefault("api_key", self.key) params.setdefault("api_key", self.key)
url = f"{self.base}{path}?" + urllib.parse.urlencode(params) url = f"{self.base}{path}?" + urllib.parse.urlencode(params)
@@ -79,7 +82,7 @@ class JellyfinClient:
for attempt in range(1, retries + 1): for attempt in range(1, retries + 1):
try: try:
req = urllib.request.Request(url, data=data, headers=headers, method=method) 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() body = resp.read()
return json.loads(body) if body else None return json.loads(body) if body else None
except urllib.error.HTTPError as exc: except urllib.error.HTTPError as exc:
@@ -359,6 +362,7 @@ class JellyfinAdFixService:
@classmethod @classmethod
def write_report(cls, stats: dict) -> Path: 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") path.write_text(json.dumps(stats, ensure_ascii=False, indent=1), encoding="utf-8")
return path return path
+5 -13
View File
@@ -134,16 +134,8 @@ class MediaInfoService:
"vc1": "VC1", "prores": "ProRes", "theora": "Theora", "vc1": "VC1", "prores": "ProRes", "theora": "Theora",
} }
# 来源:发布名里的 token 最可靠,流参数分不出 WEB-DL 与 WEBRip # 来源:发布名里的 token 最可靠,流参数分不出 WEB-DL 与 WEBRip。
SOURCE_PATTERNS = [ # 正则与标签的对应表见 config.ini [Naming] 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"),
]
@staticmethod @staticmethod
def _main_video_stream(streams: list) -> dict: def _main_video_stream(streams: list) -> dict:
@@ -187,7 +179,7 @@ class MediaInfoService:
所以老文件改成 WEB-DL 后再回头猜只会更糟——只认名字。 所以老文件改成 WEB-DL 后再回头猜只会更糟——只认名字。
""" """
low = (name or "").lower() low = (name or "").lower()
for pattern, label in MediaInfoService.SOURCE_PATTERNS: for pattern, label in config.SOURCE_PATTERNS:
if re.search(pattern, low): if re.search(pattern, low):
return label return label
return "BluRay.REMUX" if tags.get("is_remux") else "WEB-DL" return "BluRay.REMUX" if tags.get("is_remux") else "WEB-DL"
@@ -210,14 +202,14 @@ class MediaInfoService:
@staticmethod @staticmethod
def fps_tag(stream: dict) -> str: 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" raw = stream.get("avg_frame_rate") or stream.get("r_frame_rate") or "0/0"
try: try:
num, den = raw.split("/") num, den = raw.split("/")
fps = float(num) / float(den) if float(den) else 0.0 fps = float(num) / float(den) if float(den) else 0.0
except (ValueError, ZeroDivisionError): except (ValueError, ZeroDivisionError):
return "" return ""
if fps >= 49: if fps >= config.FPS_MIN:
return f"{round(fps)}fps" return f"{round(fps)}fps"
return "" return ""
+8 -13
View File
@@ -13,24 +13,18 @@ Jellyfin 扫描时会把这些标签读成 plot / genre 写进 NFO,界面上
from __future__ import annotations from __future__ import annotations
import os import os
import re
import shutil import shutil
import subprocess import subprocess
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from pathlib import Path from pathlib import Path
from core import config
from core.logger import log from core.logger import log
from core.utils import FFprobeUtil from core.utils import FFprobeUtil
# 广告特征:域名、Telegram、QQ 群、以及魔改 ffmpeg 特有的编码描述 # 广告特征由 config.ini [Ads] keywords(字面量)+ patterns(正则)合成,
# TG_CHANNEL / TG频道 是发布组把「频道名」直接塞进 ©cmt 时留下的,Jellyfin 会把它 # 定义在 core/config.py;这里保留同名变量给本模块与其它调用方用。
# 当成工作室(studio)存下来;High Efficiency Video Coding 是同一批魔改 ffmpeg 把 AD_PATTERN = config.AD_PATTERN
# 编码器描述写进 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,
)
class MetaCleanService: class MetaCleanService:
@@ -44,7 +38,7 @@ class MetaCleanService:
@staticmethod @staticmethod
def _has_space(path: Path) -> bool: def _has_space(path: Path) -> bool:
try: 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 return shutil.disk_usage(path.parent).free > need
except OSError: except OSError:
return False return False
@@ -68,7 +62,7 @@ class MetaCleanService:
result = None result = None
for cmd in attempts: for cmd in attempts:
try: 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: except subprocess.TimeoutExpired:
tmp.unlink(missing_ok=True) tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装超时: {path.name}") log.warning(f"⚠️ 重封装超时: {path.name}")
@@ -85,7 +79,8 @@ class MetaCleanService:
# 体积变化过大说明流有问题,放弃替换 # 体积变化过大说明流有问题,放弃替换
old_size = path.stat().st_size old_size = path.stat().st_size
new_size = tmp.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) tmp.unlink(missing_ok=True)
log.warning(f"⚠️ 重封装后体积异常({old_size} → {new_size}),保留原文件: {path.name}") log.warning(f"⚠️ 重封装后体积异常({old_size} → {new_size}),保留原文件: {path.name}")
return False return False
+14 -18
View File
@@ -37,17 +37,13 @@ class PreflightResult:
class PreflightService: class PreflightService:
"""ffprobe 体检 + 补 AC3 音轨 + 报告输出。""" """ffprobe 体检 + 补 AC3 音轨 + 报告输出。"""
# 电视(Amlogic S905X3 + Jellyfin Android TV 0.20)实测可直传的编码 # 电视能力边界全部来自 config.ini [Compatibility]:
# 电视(Amlogic S905X3 + Jellyfin Android TV)实测可解码的编码: # direct_video_codecs / direct_sub_codecs / ass_codecs / hdr_transfers
# HEVC / H.264 / VC-1(的士速递4 实测 DirectPlay)/ MPEG-2(功夫、非洲和尚实测 DirectPlay) # direct_containers / max_height
# MPEG-4 实测被转码(花儿与少年 S03),故不列入 # 换电视或换播放器时改配置即可,不用动代码。
VIDEO_OK = {"hevc", "h264", "vc1", "mpeg2video"} # 历史实测(Amlogic S905X3 + Jellyfin Android TV):
SUB_OK = { # HEVC / H.264 / VC-1(的士速递4)/ MPEG-2(功夫、非洲和尚)可 DirectPlay;
"ass", "ssa", "subrip", "srt", "webvtt", "mov_text", # MPEG-4 实测被转码(花儿与少年 S03),故缺省不列入。
"hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "idx",
}
HDR_TRANSFERS = {"smpte2084", "arib-std-b67"}
ASS_OK = {"ass", "ssa"}
# ------------------------------------------------------------------ 评估 # ------------------------------------------------------------------ 评估
@@ -125,22 +121,22 @@ class PreflightService:
r.info.update( r.info.update(
codec=codec, width=width, height=height, level=level, codec=codec, width=width, height=height, level=level,
mbps=round(mbps, 1), dv_profile=dv_profile, 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, size_gb=round(size_gb, 1), audio=audios, subs=subs,
duration=int(float(fmt.get("duration") or 0)), duration=int(float(fmt.get("duration") or 0)),
) )
# 1. 容器 # 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} 需重新封装或转码") cls._raise(r, TRANSCODE, f"容器 {path.suffix} 需重新封装或转码")
r.actions.append("server_transcode") r.actions.append("server_transcode")
# 2. 视频编码 # 2. 视频编码
if codec not in cls.VIDEO_OK: if codec not in config.DIRECT_VIDEO_CODECS:
cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码") cls._raise(r, TRANSCODE, f"视频编码 {codec} 电视无法解码,需服务端转码")
r.actions.append("server_transcode") r.actions.append("server_transcode")
# 3. 分辨率 # 3. 分辨率
if height > 2160: if height > config.MAX_HEIGHT:
cls._raise(r, TRANSCODE, f"{height}p 超过 4K,需服务端缩放转码") cls._raise(r, TRANSCODE, f"{height}p 超过 {config.MAX_HEIGHT}p,需服务端缩放转码")
r.actions.append("server_transcode") r.actions.append("server_transcode")
# 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解 # 4. HEVC level(153 = 5.1):仅提示,很多片源 tag 偏高但实际能解
if codec == "hevc" and isinstance(level, int) and level > 153: if codec == "hevc" and isinstance(level, int) and level > 153:
@@ -159,11 +155,11 @@ class PreflightService:
# 7. 音频:只记录,不参与判定(默认音轨保持原样,音频是否转码交给 Jellyfin) # 7. 音频:只记录,不参与判定(默认音轨保持原样,音频是否转码交给 Jellyfin)
# 8. 字幕编码 # 8. 字幕编码
# 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: if bad:
r.reasons.append(f"未知字幕编码: {sorted(set(bad))}") r.reasons.append(f"未知字幕编码: {sorted(set(bad))}")
# 9. 大文件内嵌 ASS:客户端首次播放要现场抽取,会超时 # 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: 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 大文件,需提前抽外挂") cls._raise(r, PREP, f"内嵌 ASS + {size_gb:.0f}GB 大文件,需提前抽外挂")
r.actions.append("extract_ass") r.actions.append("extract_ass")
+2 -1
View File
@@ -19,6 +19,7 @@ import xml.etree.ElementTree as ET
from collections import defaultdict from collections import defaultdict
from pathlib import Path from pathlib import Path
from core import config
from core.logger import log from core.logger import log
from services.variety import VarietyService from services.variety import VarietyService
@@ -121,7 +122,7 @@ class SpecialsService:
def apply(cls, folder: Path, plans: list[dict]) -> dict: def apply(cls, folder: Path, plans: list[dict]) -> dict:
index: dict[tuple[str, int], Path] = {} index: dict[tuple[str, int], Path] = {}
for path in folder.rglob("*"): 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) match = _EP_RE.search(path.name)
if match: if match:
index.setdefault((match.group(1), int(match.group(2))), path) 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" endpoint = "tv" if mtype == "tv" else "movie"
try: 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) params=cls._params(), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
log.warning(f"⚠️ TMDB 详情请求异常 [{mtype}/{tmdb_id}]: {exc}") log.warning(f"⚠️ TMDB 详情请求异常 [{mtype}/{tmdb_id}]: {exc}")
@@ -73,7 +73,7 @@ class TMDBService:
if year_s: if year_s:
extra["first_air_date_year" if mtype == "tv" else "year"] = year_s extra["first_air_date_year" if mtype == "tv" else "year"] = year_s
try: 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) params=cls._params(extra), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
log.warning(f"⚠️ TMDB 搜索异常 [{title}]: {exc}") 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 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 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 = [] entities = []
for result in pool: for result in pool:
@@ -223,9 +223,8 @@ class TMDBService:
# 库里按「动漫 / 真人」分目录,同名候选可用所在分类消歧: # 库里按「动漫 / 真人」分目录,同名候选可用所在分类消歧:
# 苍兰诀就是典型——动漫版 tv/206534(2 季 50 集)与真人版 tv/130368(1 季 36 集)同名。 # 苍兰诀就是典型——动漫版 tv/206534(2 季 50 集)与真人版 tv/130368(1 季 36 集)同名。
ANIME_DIRS = {"动漫节目", "动漫电影"} # 分类目录与「动画」类型 id 见 config.ini [Media] anime_dirs / live_dirs 与
LIVE_DIRS = {"电视节目", "电影", "综艺"} # [TMDB] anime_genre_id(换库结构时改配置即可)。
ANIME_GENRE_ID = 16
@classmethod @classmethod
def _prefer_by_category(cls, path, entities): def _prefer_by_category(cls, path, entities):
@@ -234,16 +233,16 @@ class TMDBService:
parts = set(Path(path).parts) parts = set(Path(path).parts)
except (TypeError, ValueError): except (TypeError, ValueError):
return None return None
if parts & cls.ANIME_DIRS: if parts & config.ANIME_DIRS:
want_anime = True want_anime = True
elif parts & cls.LIVE_DIRS: elif parts & config.LIVE_DIRS:
want_anime = False want_anime = False
else: else:
return None return None
def is_anime(entity): def is_anime(entity):
genres = entity.get("details", {}).get("genres") or [] 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] picked = [e for e in entities if is_anime(e) == want_anime]
return picked or None return picked or None
@@ -349,7 +348,7 @@ class TMDBService:
return None return None
if key in cls._dead_ids: if key in cls._dead_ids:
return None 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: try:
resp = session.get(url, params=cls._params(), timeout=config.TMDB_TIMEOUT) resp = session.get(url, params=cls._params(), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
+7 -7
View File
@@ -43,7 +43,8 @@ _EP_NAME_SPECIAL = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋
class VarietyService: 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 索引
# TMDB 单集数据缓存有效期:综艺周更,超过这个时间必须重拉, # TMDB 单集数据缓存有效期见 config.ini [Advanced] variety_cache_hours:
# 否则新一期不会出现在索引里。 # 综艺周更,超过这个时间必须重拉,否则新一期不会出现在索引里。
CACHE_TTL_HOURS = 24
@classmethod @classmethod
def _fresh(cls, stamp: str) -> bool: def _fresh(cls, stamp: str) -> bool:
@@ -99,7 +99,7 @@ class VarietyService:
if when.tzinfo is None: if when.tzinfo is None:
when = when.replace(tzinfo=datetime.now().astimezone().tzinfo) when = when.replace(tzinfo=datetime.now().astimezone().tzinfo)
age = datetime.now().astimezone() - when age = datetime.now().astimezone() - when
return age.total_seconds() <= cls.CACHE_TTL_HOURS * 3600 return age.total_seconds() <= config.VARIETY_CACHE_HOURS * 3600
@classmethod @classmethod
def _index_from_cache(cls, payload: dict) -> dict: def _index_from_cache(cls, payload: dict) -> dict:
@@ -153,7 +153,7 @@ class VarietyService:
cached = entity.get("episode_air_dates") or {} cached = entity.get("episode_air_dates") or {}
if cached and cls._fresh(entity.get("episodes_fetched_at") or ""): if cached and cls._fresh(entity.get("episodes_fetched_at") or ""):
index = cls._index_from_cache(cached) 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 return index
session = TMDBService._get_session() session = TMDBService._get_session()
@@ -353,7 +353,7 @@ class VarietyService:
# 期名用「-」接在技术标签之后:`-<播出日期>.<期名>` # 期名用「-」接在技术标签之后:`-<播出日期>.<期名>`
# 日期写成 YYYYMMDD,既能一眼看出播出时间,也让常规整理识别为已规范。 # 日期写成 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("-", "") air_date = (candidate.get("air_date") or "").replace("-", "")
tail = ".".join(part for part in (air_date, ep_name) if part) tail = ".".join(part for part in (air_date, ep_name) if part)
if tail: if tail:
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""把 config.ini 里缺的新配置项补上(幂等,保留注释与原有值)。
默认值来自 `media/src/core/config.py` 的 `DEFAULT_CONFIG_CONTENT`:
以后模板里加了新 key,跑一次这个脚本就能补进已有部署,不用手抄。
用法::
python scripts/config_upgrade.py # 改 media/src/config.ini
python scripts/config_upgrade.py --dry-run # 只报告会补哪些项
python scripts/config_upgrade.py --path /path/config.ini
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT / "media" / "src"))
from core.config import CONFIG_PATH, DEFAULT_CONFIG_CONTENT # noqa: E402
def parse_template(text: str) -> dict[str, list[tuple[str, str]]]:
"""模板 → {节名: [(key, value)]}(忽略注释与空行)。"""
sections: dict[str, list[tuple[str, str]]] = {}
current = None
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
current = stripped[1:-1]
sections.setdefault(current, [])
elif current is not None and "=" in line and not stripped.startswith("#"):
key, _, value = line.partition("=")
sections[current].append((key.strip(), value.strip()))
return sections
def section_spans(lines: list[str]) -> dict[str, tuple[int, int]]:
"""每个节的 [起始行, 结束行) ;起始行是节标题本身。"""
starts = {}
for idx, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
starts[stripped[1:-1]] = idx
ordered = sorted(starts.values())
spans = {}
for name, start in starts.items():
later = [pos for pos in ordered if pos > start]
spans[name] = (start, later[0] if later else len(lines))
return spans
def main() -> int:
parser = argparse.ArgumentParser(description="补齐 config.ini 缺失的配置项")
parser.add_argument("--path", default=str(CONFIG_PATH), help="要升级的 config.ini")
parser.add_argument("--dry-run", action="store_true", help="只报告,不写文件")
args = parser.parse_args()
target = Path(args.path)
if not target.exists():
print(f"❌ 找不到配置文件: {target}")
return 1
template = parse_template(DEFAULT_CONFIG_CONTENT)
lines = target.read_text(encoding="utf-8").splitlines()
added: list[str] = []
added_keys: set[tuple[str, str]] = set()
for section, items in template.items():
spans = section_spans(lines)
if section not in spans:
lines += ["", f"[{section}]"]
spans = section_spans(lines)
start, end = spans[section]
existing = {line.split("=", 1)[0].strip()
for line in lines[start + 1:end] if "=" in line and not line.strip().startswith("#")}
# 插在本节最后一个非空行之后,避免把注释和上一节隔开
insert_at = end
while insert_at > start + 1 and not lines[insert_at - 1].strip():
insert_at -= 1
for key, value in items:
if key in existing or (section, key) in added_keys:
continue
lines.insert(insert_at, f"{key} = {value}")
insert_at += 1
added_keys.add((section, key))
added.append(f"[{section}] {key}")
if not added:
print("✅ 配置已是最新,无需补项")
return 0
print(f"将补 {len(added)} 项到 {target}:")
for item in added:
print(" +", item)
if args.dry_run:
print("(演练,未写入)")
return 0
backup = target.with_name(f"{target.name}.bak-{time.strftime('%Y%m%d-%H%M%S')}")
backup.write_text(target.read_text(encoding="utf-8"), encoding="utf-8")
target.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"✅ 已写入;备份 {backup.name}")
return 0
if __name__ == "__main__":
sys.exit(main())