- MEDIA_ROOT 在赋值前被引用(61facaa 重构遗留),任何归档都会 NameError; 改为先解析配置再判断「是否已在库内」,并在模块级占位 - 目标目录已存在时改为增量合并:缺的搬入、同名同大小跳过、 同名不同大小与同集号不同文件视为冲突跳过(绝不覆盖、不删数据) - 新增 --no-merge 保留旧的「目标存在即报错」行为
460 lines
16 KiB
Python
460 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
"""把整理好的媒体目录归档进 /hdd/sda1/media 的对应分类。
|
||
|
||
用法:
|
||
media-archive # 归档当前目录
|
||
media-archive <目录>
|
||
media-archive --to 电视节目/TV-日韩 # 指定分类,跳过选择
|
||
media-archive --dry-run # 只显示建议,不移动
|
||
media-archive --yes # 不询问确认(配合 --to 用于脚本)
|
||
|
||
说明:
|
||
源目录与媒体库同在 /hdd/sda1,正常情况下 os.rename 即可瞬间完成;
|
||
跨文件系统时自动回退 shutil.move。
|
||
|
||
目标目录已存在时按「增量合并」处理(剧集通常分多批下载):
|
||
· 目标没有的文件 → 搬进去
|
||
· 同名且大小相同 → 视为重复下载,跳过
|
||
· 同名但大小不同,或同集号(SxxEyy)已存在不同文件 → 冲突,跳过并留在源目录
|
||
需要旧的「目标存在就报错」行为时加 --no-merge。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import configparser
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import sys
|
||
import urllib.error
|
||
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:
|
||
return Path(env)
|
||
raw = cfg.get("Archive", "media_root", fallback="").strip() if cfg.has_section("Archive") else ""
|
||
return Path(raw or "/hdd/sda1/media")
|
||
CONFIG_PATH = Path(
|
||
os.environ.get(
|
||
"SCENERENAME_CONFIG",
|
||
"/home/ali/docker/tools/python/media/src/config.ini",
|
||
)
|
||
)
|
||
|
||
TMDB_API = "https://api.themoviedb.org/3"
|
||
GENRE_ANIMATION = 16
|
||
GENRE_REALITY = 10764
|
||
GENRE_TALK = 10767
|
||
CHINESE = {"zh", "cn", "cmn", "yue"}
|
||
HK_TW = {"TW", "HK"}
|
||
|
||
|
||
# --------------------------------------------------------------------- 基础
|
||
|
||
def die(msg: str) -> None:
|
||
print(f"❌ {msg}", file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
|
||
def load_config() -> configparser.ConfigParser:
|
||
cfg = configparser.ConfigParser()
|
||
if CONFIG_PATH.exists():
|
||
cfg.read(CONFIG_PATH, encoding="utf-8")
|
||
return cfg
|
||
|
||
|
||
def http_json(url: str, headers: dict | None = None, method: str = "GET", timeout: float = 10.0):
|
||
req = urllib.request.Request(url, headers=headers or {}, method=method)
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
body = resp.read()
|
||
if not body:
|
||
return None, resp.status
|
||
return json.loads(body.decode("utf-8")), resp.status
|
||
|
||
|
||
def human_size(num: int) -> str:
|
||
for unit in ("B", "KB", "MB", "GB", "TB"):
|
||
if num < 1024 or unit == "TB":
|
||
return f"{num:.1f} {unit}" if unit != "B" else f"{num} B"
|
||
num /= 1024
|
||
return f"{num:.1f} TB"
|
||
|
||
|
||
# --------------------------------------------------------------------- 识别
|
||
|
||
def detect_kind(path: Path) -> str:
|
||
"""有 Season 目录或 SxxExx 文件 → tv,否则 movie。"""
|
||
for child in path.iterdir():
|
||
if child.is_dir() and re.match(r"^(season\s*\d+|s\d{1,2})$", child.name, re.I):
|
||
return "tv"
|
||
for child in path.rglob("*"):
|
||
if child.is_file() and re.search(r"[.\s_-]S\d{1,2}E\d{1,3}", child.name):
|
||
return "tv"
|
||
return "movie"
|
||
|
||
|
||
def count_media(path: Path) -> tuple[int, int]:
|
||
files = [p for p in path.rglob("*") if p.is_file()]
|
||
total = sum(p.stat().st_size for p in files)
|
||
return len(files), total
|
||
|
||
|
||
def tmdb_id_of(name: str) -> str | None:
|
||
m = re.search(r"tmdbid-(\d+)", name)
|
||
return m.group(1) if m else None
|
||
|
||
|
||
def tmdb_info(tmdb_id: str, kind: str, cfg: configparser.ConfigParser) -> dict | None:
|
||
if not cfg.has_section("TMDB"):
|
||
return None
|
||
api_key = (cfg.get("TMDB", "api_key", fallback="") or "").strip()
|
||
if not api_key:
|
||
return None
|
||
language = cfg.get("TMDB", "language", fallback="zh-CN").strip() or "zh-CN"
|
||
endpoint = "tv" if kind == "tv" else "movie"
|
||
query = urllib.parse.urlencode({"api_key": api_key, "language": language})
|
||
url = f"{TMDB_API}/{endpoint}/{tmdb_id}?{query}"
|
||
try:
|
||
data, _ = http_json(url, timeout=float(cfg.get("TMDB", "timeout", fallback="10")))
|
||
return data or None
|
||
except (urllib.error.URLError, TimeoutError, ValueError):
|
||
return None
|
||
|
||
|
||
def region_of(info: dict) -> str:
|
||
lang = (info.get("original_language") or "").lower()
|
||
countries = {str(c).upper() for c in (info.get("origin_country") or []) if c}
|
||
if lang in CHINESE or "CN" in countries or "HK" in countries or "TW" in countries:
|
||
return "港台" if countries & HK_TW else "华语"
|
||
if lang in {"ja", "ko"}:
|
||
return "日韩"
|
||
return "欧美"
|
||
|
||
|
||
def suggest_category(kind: str, info: dict | None) -> str | None:
|
||
if not info:
|
||
return None
|
||
genres = {int(g.get("id", 0)) for g in info.get("genres", []) if isinstance(g, dict)}
|
||
region = region_of(info)
|
||
|
||
if genres & {GENRE_REALITY, GENRE_TALK}:
|
||
return "综艺/TVSHOW-华语"
|
||
|
||
if GENRE_ANIMATION in genres:
|
||
top = "动漫节目" if kind == "tv" else "动漫电影"
|
||
prefix = "TV" if kind == "tv" else "MOVIE"
|
||
return f"{top}/{prefix}-{region}"
|
||
|
||
top = "电视节目" if kind == "tv" else "电影"
|
||
prefix = "TV" if kind == "tv" else "MOVIE"
|
||
return f"{top}/{prefix}-{region}"
|
||
|
||
|
||
# --------------------------------------------------------------------- 分类
|
||
|
||
def list_categories(root: Path) -> list[str]:
|
||
if not root.exists():
|
||
die(f"媒体库根目录不存在: {root}")
|
||
cats: list[str] = []
|
||
for top in sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(".")):
|
||
subs = sorted(p.name for p in top.iterdir() if p.is_dir())
|
||
if subs:
|
||
cats.extend(f"{top.name}/{s}" for s in subs)
|
||
else:
|
||
cats.append(top.name)
|
||
return cats
|
||
|
||
|
||
def resolve_category(root: Path, raw: str, cats: list[str]) -> str | None:
|
||
raw = raw.strip().strip("/")
|
||
if raw in cats:
|
||
return raw
|
||
matches = [c for c in cats if raw.lower() in c.lower()]
|
||
if len(matches) == 1:
|
||
return matches[0]
|
||
return None
|
||
|
||
|
||
# --------------------------------------------------------------------- 动作
|
||
|
||
def move_to(src: Path, dest: Path) -> None:
|
||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||
try:
|
||
os.rename(src, dest)
|
||
except OSError:
|
||
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 跳过刷新"
|
||
if not cfg.has_section("Jellyfin"):
|
||
return "未配置 [Jellyfin],跳过刷新"
|
||
api_key = (cfg.get("Jellyfin", "api_key", fallback="") or "").strip()
|
||
base = (cfg.get("Jellyfin", "url", fallback="http://127.0.0.1:8096") or "").rstrip("/")
|
||
if not api_key:
|
||
return "未配置 Jellyfin api_key,跳过刷新"
|
||
try:
|
||
_, status = http_json(
|
||
f"{base}/Library/Refresh",
|
||
headers={"X-Emby-Token": api_key},
|
||
method="POST",
|
||
timeout=10,
|
||
)
|
||
return f"已触发 Jellyfin 库刷新(HTTP {status})"
|
||
except Exception as exc: # noqa: BLE001
|
||
return f"⚠️ Jellyfin 刷新失败: {exc}"
|
||
|
||
|
||
def choose_category(cats: list[str], suggestion: str | None) -> str | None:
|
||
print("\n可选分类:")
|
||
for idx, cat in enumerate(cats, 1):
|
||
mark = " ← 建议" if suggestion and cat == suggestion else ""
|
||
print(f" {idx:>2}. {cat}{mark}")
|
||
|
||
while True:
|
||
hint = f"回车接受建议 [{suggestion}]" if suggestion else "输入编号或分类关键字"
|
||
try:
|
||
raw = input(f"\n请选择分类({hint},q 取消): ").strip()
|
||
except EOFError:
|
||
return None
|
||
if raw.lower() in {"q", "quit", "exit"}:
|
||
return None
|
||
if not raw:
|
||
if suggestion:
|
||
return suggestion
|
||
print("⚠️ 没有建议,请显式输入编号")
|
||
continue
|
||
if raw.isdigit():
|
||
idx = int(raw)
|
||
if 1 <= idx <= len(cats):
|
||
return cats[idx - 1]
|
||
print(f"⚠️ 编号超出范围(1-{len(cats)})")
|
||
continue
|
||
picked = resolve_category(MEDIA_ROOT, raw, cats)
|
||
if picked:
|
||
return picked
|
||
print("⚠️ 没有匹配到唯一分类,请重试")
|
||
|
||
|
||
def main() -> int:
|
||
global MEDIA_ROOT
|
||
parser = argparse.ArgumentParser(description="把整理好的媒体目录归档进媒体库")
|
||
parser.add_argument("path", nargs="?", default=".", help="要归档的目录(默认当前目录)")
|
||
parser.add_argument("-p", "--path", dest="path_opt", help="要归档的目录(覆盖位置参数)")
|
||
parser.add_argument("--to", dest="target", help="直接指定分类,如 电视节目/TV-日韩")
|
||
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}")
|
||
|
||
kind = detect_kind(src)
|
||
tmdb_id = tmdb_id_of(src.name)
|
||
info = tmdb_info(tmdb_id, kind, cfg) if tmdb_id else None
|
||
suggestion = suggest_category(kind, info)
|
||
|
||
cats = list_categories(MEDIA_ROOT)
|
||
if suggestion and suggestion not in cats:
|
||
suggestion = None
|
||
|
||
files, size = count_media(src)
|
||
label = "剧集" if kind == "tv" else "电影"
|
||
title = (info or {}).get("name") or (info or {}).get("title") or src.name
|
||
print(f"📁 源目录 : {src}")
|
||
print(f"🎬 识别 : {label} | {title}" + (f" | tmdbid-{tmdb_id}" if tmdb_id else " | 无 tmdbid"))
|
||
if tmdb_id and info is None:
|
||
print("⚠️ TMDB 查询失败(网络或 api_key),将不提供分类建议")
|
||
print(f"📦 内容 : {files} 个文件, {human_size(size)}")
|
||
|
||
if args.target:
|
||
category = resolve_category(MEDIA_ROOT, args.target, cats)
|
||
if not category:
|
||
die(f"分类不存在: {args.target}\n可用: " + ", ".join(cats))
|
||
else:
|
||
category = choose_category(cats, suggestion)
|
||
if not category:
|
||
print("已取消。")
|
||
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 not args.yes:
|
||
try:
|
||
confirm = input("确认归档?[Y/n]: ").strip().lower()
|
||
except EOFError:
|
||
confirm = "n"
|
||
if confirm not in {"", "y", "yes"}:
|
||
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)
|
||
if src.exists():
|
||
die(f"移动后源目录仍存在,请手工检查: {src}")
|
||
if new_files != files or new_size != size:
|
||
die(f"文件数/体积校验不一致: 源 {files}/{size} → 目标 {new_files}/{new_size}")
|
||
print(f"✅ 归档完成: {dest}")
|
||
print(f" 校验通过: {new_files} 个文件, {human_size(new_size)}")
|
||
|
||
if not args.no_jellyfin:
|
||
print("🎞️ " + refresh_jellyfin(cfg))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|