fix(archive): 修复 MEDIA_ROOT 未定义崩溃,支持剧集增量合并
- MEDIA_ROOT 在赋值前被引用(61facaa 重构遗留),任何归档都会 NameError; 改为先解析配置再判断「是否已在库内」,并在模块级占位 - 目标目录已存在时改为增量合并:缺的搬入、同名同大小跳过、 同名不同大小与同集号不同文件视为冲突跳过(绝不覆盖、不删数据) - 新增 --no-merge 保留旧的「目标存在即报错」行为
This commit is contained in:
+144
-5
@@ -11,6 +11,12 @@
|
||||
说明:
|
||||
源目录与媒体库同在 /hdd/sda1,正常情况下 os.rename 即可瞬间完成;
|
||||
跨文件系统时自动回退 shutil.move。
|
||||
|
||||
目标目录已存在时按「增量合并」处理(剧集通常分多批下载):
|
||||
· 目标没有的文件 → 搬进去
|
||||
· 同名且大小相同 → 视为重复下载,跳过
|
||||
· 同名但大小不同,或同集号(SxxEyy)已存在不同文件 → 冲突,跳过并留在源目录
|
||||
需要旧的「目标存在就报错」行为时加 --no-merge。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -26,6 +32,10 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
# 媒体库根目录(main() 里根据 config.ini 赋值;模块级先占位,避免任何早于赋值的使用炸 NameError)
|
||||
MEDIA_ROOT: Path | None = None
|
||||
|
||||
|
||||
def resolve_media_root(cfg: configparser.ConfigParser) -> Path:
|
||||
env = os.environ.get("SCENEMARSHAL_MEDIA_ROOT") or os.environ.get("SCENERENAME_MEDIA_ROOT")
|
||||
if env:
|
||||
@@ -183,6 +193,100 @@ def move_to(src: Path, dest: Path) -> None:
|
||||
shutil.move(str(src), str(dest))
|
||||
|
||||
|
||||
EPISODE_RE = re.compile(r"[Ss](\d{1,2})[Ee](\d{1,4})")
|
||||
|
||||
|
||||
def _episode_key(path: Path) -> tuple[str, str] | None:
|
||||
m = EPISODE_RE.search(path.name)
|
||||
return (m.group(1), m.group(2)) if m else None
|
||||
|
||||
|
||||
def plan_merge(src: Path, dest: Path) -> dict:
|
||||
"""规划增量合并:哪些文件是新增、哪些同名重复、哪些冲突。
|
||||
|
||||
剧集不会一天更新完,所以归档常常要合并进已存在的剧目录。
|
||||
规则:目标缺 → 新增;同名同大小 → 重复跳过;同名不同大小 → 冲突跳过(绝不覆盖);
|
||||
同集号但文件名不同(例如 mp4 换了 mkv)→ 也算冲突,避免 Jellyfin 出现两集重复。
|
||||
"""
|
||||
existing_eps: dict[tuple[str, str], Path] = {}
|
||||
for p in dest.rglob("*"):
|
||||
if p.is_file():
|
||||
key = _episode_key(p)
|
||||
if key:
|
||||
existing_eps.setdefault(key, p)
|
||||
|
||||
new: list[Path] = []
|
||||
dupes: list[Path] = []
|
||||
conflicts: list[tuple[Path, str]] = []
|
||||
|
||||
for path in sorted(p for p in src.rglob("*") if p.is_file()):
|
||||
rel = path.relative_to(src)
|
||||
target = dest / rel
|
||||
if target.exists():
|
||||
try:
|
||||
same = target.stat().st_size == path.stat().st_size
|
||||
except OSError:
|
||||
same = False
|
||||
if same:
|
||||
dupes.append(rel)
|
||||
else:
|
||||
conflicts.append((rel, "同名不同大小"))
|
||||
continue
|
||||
|
||||
key = _episode_key(path)
|
||||
if key and key in existing_eps:
|
||||
conflicts.append((rel, f"同集号已存在: {existing_eps[key].relative_to(dest)}"))
|
||||
continue
|
||||
|
||||
new.append(rel)
|
||||
if key:
|
||||
existing_eps.setdefault(key, target)
|
||||
|
||||
return {"new": new, "dupes": dupes, "conflicts": conflicts}
|
||||
|
||||
|
||||
def merge_into(src: Path, dest: Path) -> dict:
|
||||
"""按 plan_merge 的计划把 src 合并进 dest,返回执行结果。"""
|
||||
plan = plan_merge(src, dest)
|
||||
moved = 0
|
||||
moved_bytes = 0
|
||||
|
||||
for rel in plan["new"]:
|
||||
path = src / rel
|
||||
target = dest / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
os.rename(path, target)
|
||||
except OSError:
|
||||
shutil.move(str(path), str(target))
|
||||
moved += 1
|
||||
try:
|
||||
moved_bytes += target.stat().st_size
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# 清掉搬空的子目录
|
||||
for d in sorted((p for p in src.rglob("*") if p.is_dir()), key=lambda p: -len(p.parts)):
|
||||
try:
|
||||
d.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
src_removed = False
|
||||
try:
|
||||
src.rmdir()
|
||||
src_removed = True
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"moved": moved,
|
||||
"moved_bytes": moved_bytes,
|
||||
"dupes": plan["dupes"],
|
||||
"conflicts": plan["conflicts"],
|
||||
"src_removed": src_removed,
|
||||
}
|
||||
|
||||
|
||||
def refresh_jellyfin(cfg: configparser.ConfigParser) -> str:
|
||||
if cfg.has_section("Archive") and not cfg.getboolean("Archive", "refresh_jellyfin", fallback=True):
|
||||
return "已按 [Archive] refresh_jellyfin=false 跳过刷新"
|
||||
@@ -244,16 +348,21 @@ def main() -> int:
|
||||
parser.add_argument("--dry-run", action="store_true", help="只显示识别结果,不移动")
|
||||
parser.add_argument("--yes", action="store_true", help="跳过最终确认")
|
||||
parser.add_argument("--no-jellyfin", action="store_true", help="不触发 Jellyfin 刷新")
|
||||
parser.add_argument("--no-merge", action="store_true",
|
||||
help="目标目录已存在时直接报错,不做增量合并")
|
||||
args = parser.parse_args()
|
||||
|
||||
src = Path(args.path_opt or args.path).resolve()
|
||||
if not src.is_dir():
|
||||
die(f"目录不存在: {src}")
|
||||
|
||||
# 先解析媒体库根目录,再做"是否已在库里"的判断(顺序反了会 NameError)
|
||||
cfg = load_config()
|
||||
MEDIA_ROOT = resolve_media_root(cfg)
|
||||
|
||||
if src.parent == MEDIA_ROOT or MEDIA_ROOT in src.parents:
|
||||
die(f"源目录已经在媒体库里了: {src}")
|
||||
|
||||
cfg = load_config()
|
||||
MEDIA_ROOT = resolve_media_root(cfg)
|
||||
kind = detect_kind(src)
|
||||
tmdb_id = tmdb_id_of(src.name)
|
||||
info = tmdb_info(tmdb_id, kind, cfg) if tmdb_id else None
|
||||
@@ -283,15 +392,30 @@ def main() -> int:
|
||||
return 0
|
||||
|
||||
dest = MEDIA_ROOT / category / src.name
|
||||
merging = dest.exists() and not args.no_merge
|
||||
if dest.exists() and args.no_merge:
|
||||
die(f"目标已存在,未移动: {dest}")
|
||||
|
||||
merge_plan = None
|
||||
if merging:
|
||||
merge_plan = plan_merge(src, dest)
|
||||
print(f"\n➡️ 目标已存在,按增量合并: {dest}")
|
||||
print(f" 新增 {len(merge_plan['new'])} 个文件")
|
||||
if merge_plan["dupes"]:
|
||||
print(f" 跳过同名同大小 {len(merge_plan['dupes'])} 个(重复下载)")
|
||||
if merge_plan["conflicts"]:
|
||||
print(f" ⚠️ 冲突 {len(merge_plan['conflicts'])} 个(不覆盖、不移动):")
|
||||
for rel, reason in merge_plan["conflicts"][:10]:
|
||||
print(f" - {rel} ← {reason}")
|
||||
if len(merge_plan["conflicts"]) > 10:
|
||||
print(f" … 另有 {len(merge_plan['conflicts']) - 10} 个")
|
||||
else:
|
||||
print(f"\n➡️ 将移动到: {dest}")
|
||||
|
||||
if args.dry_run:
|
||||
print("(dry-run,未执行移动)")
|
||||
return 0
|
||||
|
||||
if dest.exists():
|
||||
die(f"目标已存在,未移动: {dest}")
|
||||
|
||||
if not args.yes:
|
||||
try:
|
||||
confirm = input("确认归档?[Y/n]: ").strip().lower()
|
||||
@@ -301,6 +425,21 @@ def main() -> int:
|
||||
print("已取消。")
|
||||
return 0
|
||||
|
||||
if merging:
|
||||
rep = merge_into(src, dest)
|
||||
after_files, after_size = count_media(dest)
|
||||
print(f"✅ 增量合并完成: {dest}")
|
||||
print(f" 新增 {rep['moved']} 个文件, {human_size(rep['moved_bytes'])}")
|
||||
if rep["dupes"]:
|
||||
print(f" 跳过重复 {len(rep['dupes'])} 个(目标已有同名同大小文件)")
|
||||
if rep["conflicts"]:
|
||||
print(f" ⚠️ 冲突 {len(rep['conflicts'])} 个仍留在源目录,未覆盖:")
|
||||
for rel, reason in rep["conflicts"][:10]:
|
||||
print(f" - {rel} ← {reason}")
|
||||
print(f" 目标现有 {after_files} 个文件, {human_size(after_size)}")
|
||||
if not rep["src_removed"]:
|
||||
print(f" ⚠️ 源目录仍有残留,请人工确认: {src}")
|
||||
else:
|
||||
move_to(src, dest)
|
||||
|
||||
new_files, new_size = count_media(dest)
|
||||
|
||||
Reference in New Issue
Block a user