feat(pipeline): 批量整理、归档服务化与 watch 全自动

- main/pipeline: -p 改为 append,多目录走 run_batch(共享一次确认与一次执行);
  单目录整理后自动接归档,多目录只整理
- services/archive: 归档从脚本抽成服务,三道闸(有视频/无下载残留/有唯一 TMDB 建议),
  Jellyfin 刷新走 172.17.0.1 回退
- watcher: 改为监听 .qkdownloading 的消失/移走事件并归并到下载根下一级目录,
  _running/_pending 互斥,下载判定用 is_download_complete()
- task: notes + add_note(),预览按五阶段固定顺序打印;execute() 返回统计
- config: AUTO_ARCHIVE / FOLLOW_SPECIALS / DOWNLOADING_EXTS / WATCH_SETTLE_SECONDS
This commit is contained in:
ali
2026-11-21 21:09:40 +08:00
parent 201e9e8745
commit 753063401f
9 changed files with 1243 additions and 111 deletions
+573
View File
@@ -0,0 +1,573 @@
# src/services/archive.py
"""归档:把整理好的媒体目录移动进媒体库的对应分类(支持增量合并)。
从 scripts/media_archive.py 搬入,行为保持一致,差别只有三点:
1. 不再 sys.exit —— 失败抛 ArchiveError,取消抛 ArchiveCancelled,由调用方映射退出码;
2. 配置统一走 core.config(不再自己解析 config.ini,避免宿主机/容器两套路径语义);
3. Jellyfin 刷新沿用 specials.py 的「容器内 172.17.0.1 回退」,不再写死 127.0.0.1。
合并规则(与原脚本一致):
· 目标没有的文件 → 搬进去
· 同名且大小近似相同 → 视为重复下载,跳过
· 同名不同大小,或同集号(SxxEyy)已存在不同文件 → 冲突,跳过并留在源目录(绝不覆盖)
"""
from __future__ import annotations
import errno
import os
import re
import shutil
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from pathlib import Path
from core import config, tmdb_store
from core.logger import log
GENRE_ANIMATION = 16
GENRE_REALITY = 10764
GENRE_TALK = 10767
CHINESE = {"zh", "cn", "cmn", "yue"}
HK_TW = {"TW", "HK"}
CATEGORY_SUFFIX_LIVE = "电视节目"
CATEGORY_SUFFIX_MOVIE = "电影"
EPISODE_RE = re.compile(r"[Ss](\d{1,2})[Ee](\d{1,4})")
class ArchiveError(Exception):
"""归档前置条件不满足或执行失败。"""
class ArchiveCancelled(Exception):
"""用户在分类选择或确认环节取消。"""
@dataclass
class ArchiveResult:
src: Path
dest: Path | None = None
merged: bool = False
moved: int = 0
moved_bytes: int = 0
dupes: list = field(default_factory=list)
conflicts: list = field(default_factory=list)
src_removed: bool = False
skipped: str | None = None # 非交互模式下被闸门跳过时的原因
@property
def ok(self) -> bool:
return self.skipped is None
class ArchiveService:
# ------------------------------------------------------------------ 基础
@staticmethod
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"
@staticmethod
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
import json
return json.loads(body.decode("utf-8")), resp.status
# ------------------------------------------------------------------ 识别
@staticmethod
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"
@staticmethod
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
@staticmethod
def tmdb_id_of(name: str) -> str | None:
m = re.search(r"tmdbid-(\d+)", name)
return m.group(1) if m else None
@classmethod
def tmdb_info(cls, tmdb_id: str, kind: str) -> dict | None:
"""取 TMDB 实体(含 details);命中共享缓存则不回源。"""
if not config.TMDB_API_KEY:
return None
key = tmdb_store.entity_key(kind, tmdb_id)
try:
entity = tmdb_store.snapshot(config.TMDB_CACHE_PATH)["entities"].get(key)
except Exception: # noqa: BLE001 缓存损坏不应阻断归档
entity = None
if entity and (entity.get("details") or {}).get("genres") is not None:
log.debug(f"⚡ TMDB 详情命中缓存: {key}")
return entity
endpoint = "tv" if kind == "tv" else "movie"
query = urllib.parse.urlencode({"api_key": config.TMDB_API_KEY,
"language": config.TMDB_LANGUAGE})
url = f"{config.TMDB_BASE_URL}/{endpoint}/{tmdb_id}?{query}"
try:
data, _ = cls._http_json(url, timeout=float(config.TMDB_TIMEOUT))
except (urllib.error.URLError, TimeoutError, ValueError, OSError):
return None
if not data:
return None
entity = tmdb_store.build_entity(kind, tmdb_id, data)
try:
with tmdb_store.transaction(config.TMDB_CACHE_PATH) as db:
tmdb_store.put_entity(db, entity)
except OSError as exc:
log.warning(f"⚠️ TMDB 缓存写入失败(不影响本次归档): {exc}")
return entity
@staticmethod
def region_of(entity: dict) -> str:
details = entity.get("details") or {}
lang = (details.get("original_language") or "").lower()
countries = {str(c).upper() for c in (details.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 "欧美"
@classmethod
def suggest_category(cls, kind: str, info: dict | None) -> str | None:
if not info:
return None
genres = {int(g.get("id", 0)) for g in (info.get("details") or {}).get("genres", [])
if isinstance(g, dict)}
region = cls.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 = CATEGORY_SUFFIX_LIVE if kind == "tv" else CATEGORY_SUFFIX_MOVIE
prefix = "TV" if kind == "tv" else "MOVIE"
return f"{top}/{prefix}-{region}"
# ------------------------------------------------------------------ 分类
@staticmethod
def list_categories(root: Path) -> list[str]:
if not root.exists():
raise ArchiveError(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
@staticmethod
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
# ------------------------------------------------------------------ 移动
@staticmethod
def _owner_hint() -> str:
try:
import grp
import pwd
ent = pwd.getpwuid(os.getuid())
group = grp.getgrgid(os.getgid()).gr_name
return f"{ent.pw_name}:{group}"
except (ImportError, KeyError):
return f"{os.getuid()}:{os.getgid()}"
@classmethod
def unwritable_targets(cls, dest: Path, rels: list[Path] | None) -> list[Path]:
"""返回落点中当前用户不可写的目录(去重保序)。
rels=None 表示整目录移动,只检查 dest 的父目录;否则按新增文件逐个向上找
最近的已存在父目录。Jellyfin 以 root 保存元数据时会创建 root 目录,普通用户
写不进去,移动会半路 PermissionError 并留下已移动的部分文件,所以先统一预检。
"""
parents = [dest.parent] if rels is None else [(dest / rel).parent for rel in rels]
bad: list[Path] = []
for parent in parents:
probe = parent
while not probe.exists() and probe != probe.parent and probe != dest.parent:
probe = probe.parent
if probe.exists() and not os.access(probe, os.W_OK | os.X_OK) and probe not in bad:
bad.append(probe)
return bad
@classmethod
def _assert_writable(cls, dest: Path, rels: list[Path] | None) -> None:
bad = cls.unwritable_targets(dest, rels)
if not bad:
return
quoted = " ".join(f'"{p}"' for p in bad)
raise ArchiveError(
"目标目录不可写,已中止(未移动任何文件):\n"
+ "\n".join(f" - {p}" for p in bad)
+ "\n 常见原因:Jellyfin 以 root 保存元数据时创建了目录。"
+ f"\n 修复:sudo chown -R {cls._owner_hint()} {quoted}"
)
@staticmethod
def move_to(src: Path, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(src, dest)
except OSError as exc:
if exc.errno != errno.EXDEV:
raise
shutil.move(str(src), str(dest))
@staticmethod
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
@classmethod
def plan_merge(cls, src: Path, dest: Path) -> dict:
existing_eps: dict[tuple[str, str], Path] = {}
for p in dest.rglob("*"):
if p.is_file():
key = cls._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:
old_size = target.stat().st_size
new_size = path.stat().st_size
except OSError:
old_size = new_size = -1
# 同一份文件重新封装/复制时容器元数据会有几十~几百字节出入,
# 差值小于 1MB 或 0.1% 就按重复处理,否则整批近似文件都会被报成冲突
tol = max(1_048_576, int(max(old_size, new_size) * 0.001))
if old_size >= 0 and abs(old_size - new_size) <= tol:
dupes.append(rel)
else:
conflicts.append((rel, "同名不同大小"))
continue
key = cls._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}
@classmethod
def merge_into(cls, src: Path, dest: Path) -> dict:
plan = cls.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 as exc:
if exc.errno != errno.EXDEV:
raise
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,
}
# ------------------------------------------------------------------ Jellyfin
@staticmethod
def _jellyfin_base() -> str:
"""容器内访问不到 127.0.0.1(Jellyfin 在宿主机),按 specials 的先例回退。"""
base = (config.JELLYFIN_URL or "").rstrip("/")
if not base:
return ""
if "127.0.0.1" in base or "localhost" in base:
candidates = [base, "http://172.17.0.1:8096", "http://10.10.1.202:8096"]
for url in candidates:
try:
req = urllib.request.Request(f"{url}/System/Info/Public")
with urllib.request.urlopen(req, timeout=3) as resp:
if resp.status == 200:
return url
except OSError:
continue
return base
@classmethod
def refresh_jellyfin(cls) -> str:
if not config.REFRESH_JELLYFIN:
return "已按 [Archive] refresh_jellyfin=false 跳过刷新"
key = config.JELLYFIN_API_KEY
if not key:
return "未配置 Jellyfin api_key,跳过刷新"
base = cls._jellyfin_base()
if not base:
return "未配置 Jellyfin 地址,跳过刷新"
try:
_, status = cls._http_json(f"{base}/Library/Refresh",
headers={"X-Emby-Token": key}, method="POST", timeout=10)
return f"已触发 Jellyfin 库刷新(HTTP {status})"
except Exception as exc: # noqa: BLE001 刷新失败不影响归档结果
return f"⚠️ Jellyfin 刷新失败: {exc}"
# ------------------------------------------------------------------ 分类选择
@staticmethod
def choose_category(cats: list[str], suggestion: str | None) -> str | None:
log.info("可选分类:")
for idx, cat in enumerate(cats, 1):
mark = " ← 建议" if suggestion and cat == suggestion else ""
log.info(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
# 中文输入法可能打出全角「q」「1」,先归一化再判断
raw = unicodedata.normalize("NFKC", raw)
if raw.lower() in {"q", "quit", "exit"}:
return None
if not raw:
if suggestion:
return suggestion
log.warning("⚠️ 没有建议,请显式输入编号")
continue
if raw.isdigit():
idx = int(raw)
if 1 <= idx <= len(cats):
return cats[idx - 1]
log.warning(f"⚠️ 编号超出范围(1-{len(cats)})")
continue
picked = ArchiveService.resolve_category(config.MEDIA_ROOT, raw, cats)
if picked:
return picked
log.warning("⚠️ 没有匹配到唯一分类,请重试")
# ------------------------------------------------------------------ 闸门
@classmethod
def download_incomplete(cls, src: Path) -> list[Path]:
"""返回残留的下载临时文件(非交互归档前的硬闸门)。"""
exts = getattr(config, "DOWNLOADING_EXTS", set())
if not exts:
return []
hits: list[Path] = []
for p in src.rglob("*"):
if p.is_file() and p.suffix.lower() in exts:
hits.append(p)
return hits
@classmethod
def _gate(cls, src: Path) -> str | None:
"""自动归档的三道闸;返回跳过原因,None 表示可以继续。"""
videos = [p for p in src.rglob("*")
if p.is_file() and p.suffix.lower() in config.VIDEO_EXTS]
if not videos:
return "目录内没有视频文件"
residues = cls.download_incomplete(src)
if residues:
return f"仍有未下载完的文件({residues[0].name}),本次不归档"
return None
# ------------------------------------------------------------------ 主流程
@classmethod
def run(cls, src: Path, to: str | None = None, yes: bool = False,
dry_run: bool = False, non_interactive: bool = False,
merge: bool = True, refresh: bool = True) -> ArchiveResult:
"""归档一个目录。
non_interactive=True 用于「整理完自动归档」:不提问,闸门不满足就返回
result.skipped(不算失败);分类只接受唯一建议,没建议就跳过。
"""
src = Path(src).resolve()
result = ArchiveResult(src=src)
if not src.is_dir():
raise ArchiveError(f"目录不存在: {src}")
media_root = config.MEDIA_ROOT
if src.parent == media_root or media_root in src.parents:
raise ArchiveError(f"源目录已经在媒体库里了: {src}")
if non_interactive:
reason = cls._gate(src)
if reason:
result.skipped = reason
log.info(f"⏭ 跳过归档:{reason}")
return result
kind = cls.detect_kind(src)
tmdb_id = cls.tmdb_id_of(src.name)
info = cls.tmdb_info(tmdb_id, kind) if tmdb_id else None
suggestion = cls.suggest_category(kind, info)
cats = cls.list_categories(media_root)
if suggestion and suggestion not in cats:
suggestion = None
files, size = cls.count_media(src)
label = "剧集" if kind == "tv" else "电影"
title = (info or {}).get("title") or src.name
log.info(f"📁 源目录 : {src}")
log.info(f"🎬 识别 : {label} | {title}"
+ (f" | tmdbid-{tmdb_id}" if tmdb_id else " | 无 tmdbid"))
if tmdb_id and info is None:
log.warning("⚠️ TMDB 查询失败(网络或 api_key),将不提供分类建议")
log.info(f"📦 内容 : {files} 个文件, {cls.human_size(size)}")
if to:
category = cls.resolve_category(media_root, to, cats)
if not category:
raise ArchiveError(f"分类不存在: {to}\n可用: " + ", ".join(cats))
elif non_interactive:
if not suggestion:
result.skipped = "没有唯一的 TMDB 分类建议"
log.info(f"⏭ 跳过归档:{result.skipped},请手动归档")
return result
category = suggestion
else:
category = cls.choose_category(cats, suggestion)
if not category:
raise ArchiveCancelled("用户取消")
dest = media_root / category / src.name
if dest.exists() and not merge:
raise ArchiveError(f"目标已存在,未移动: {dest}")
merging = dest.exists()
merge_plan = None
if merging:
merge_plan = cls.plan_merge(src, dest)
log.info(f"➡️ 目标已存在,按增量合并: {dest}")
log.info(f" 新增 {len(merge_plan['new'])} 个文件")
if merge_plan["dupes"]:
log.info(f" 跳过同名同大小 {len(merge_plan['dupes'])} 个(重复下载)")
if merge_plan["conflicts"]:
log.warning(f" ⚠️ 冲突 {len(merge_plan['conflicts'])} 个(不覆盖、不移动)")
for rel, reason in merge_plan["conflicts"][:10]:
log.warning(f" - {rel} ← {reason}")
else:
log.info(f"➡️ 将移动到: {dest}")
if dry_run:
log.info("(dry-run,未执行移动)")
result.dest = dest
result.merged = merging
return result
cls._assert_writable(dest, merge_plan["new"] if merging else None)
if not yes:
try:
confirm = unicodedata.normalize("NFKC", input("确认归档?[Y/n]: ")).strip().lower()
except EOFError:
confirm = "n"
if confirm not in {"", "y", "yes"}:
raise ArchiveCancelled("用户取消")
result.dest = dest
result.merged = merging
if merging:
rep = cls.merge_into(src, dest)
after_files, after_size = cls.count_media(dest)
result.moved = rep["moved"]
result.moved_bytes = rep["moved_bytes"]
result.dupes = rep["dupes"]
result.conflicts = rep["conflicts"]
result.src_removed = rep["src_removed"]
log.info(f"✅ 增量合并完成: {dest}")
log.info(f" 新增 {rep['moved']} 个文件, {cls.human_size(rep['moved_bytes'])}")
if rep["dupes"]:
log.info(f" 跳过重复 {len(rep['dupes'])} 个(目标已有同名同大小文件)")
log.info(f" 目标现有 {after_files} 个文件, {cls.human_size(after_size)}")
if not rep["src_removed"]:
log.warning(f" ⚠️ 源目录仍有残留,请人工确认: {src}")
else:
cls.move_to(src, dest)
new_files, new_size = cls.count_media(dest)
if src.exists():
raise ArchiveError(f"移动后源目录仍存在,请手工检查: {src}")
if new_files != files or new_size != size:
raise ArchiveError(
f"文件数/体积校验不一致: 源 {files}/{size} → 目标 {new_files}/{new_size}")
result.moved = new_files
result.moved_bytes = new_size
log.info(f"✅ 归档完成: {dest}")
log.info(f" 校验通过: {new_files} 个文件, {cls.human_size(new_size)}")
if refresh:
log.info("🎞️ " + cls.refresh_jellyfin())
return result
+33 -2
View File
@@ -10,6 +10,7 @@
"""
import json
import os
import time
from dataclasses import dataclass, field
from pathlib import Path
@@ -357,8 +358,8 @@ class PreflightService:
return report
@classmethod
def scan(cls, root: Path) -> list:
"""check 模式:只体检不动文件。"""
def _scan_root(cls, root: Path) -> list:
"""单个根目录体检(只读),返回 [(path, PreflightResult)]。"""
results = []
files = [
p for p in root.rglob("*")
@@ -372,12 +373,42 @@ class PreflightService:
detail = f"{r.info.get('codec')} {r.info.get('height')}p {r.info.get('mbps')}Mbps"
log.info(f"{mark} {r.verdict:<7} {p.name} [{detail}]"
+ (f" | {', '.join(r.reasons)}" if r.reasons else ""))
return results
@staticmethod
def _log_counts(results: list) -> None:
counts = {}
for _, r in results:
counts[r.verdict] = counts.get(r.verdict, 0) + 1
log.info(f"📊 共 {len(results)} 个文件: " +
", ".join(f"{k}={v}" for k, v in sorted(counts.items())))
@staticmethod
def _common_root(roots: list) -> Path:
if len(roots) == 1:
return Path(roots[0])
try:
return Path(os.path.commonpath([str(Path(r)) for r in roots]))
except ValueError: # 跨盘符(Windows)无法求公共前缀
return Path(roots[0])
@classmethod
def scan(cls, root: Path) -> list:
"""check 模式:只体检不动文件。"""
results = cls._scan_root(root)
cls._log_counts(results)
cls.write_report(root, results)
return results
@classmethod
def scan_many(cls, roots: list) -> list:
"""多目录体检:合并成一份报告(否则一次多选会吃掉全部 report_keep)。"""
results = []
for root in roots:
if len(roots) > 1:
log.info(f"— 体检 {Path(root)}")
results.extend(cls._scan_root(Path(root)))
cls._log_counts(results)
cls.write_report(cls._common_root(roots), results)
return results
+4 -4
View File
@@ -157,7 +157,7 @@ class SpecialsService:
key = config.JELLYFIN_API_KEY or ""
if not base or not key:
log.warning("⚠️ 未配置 Jellyfin 地址或 API Key,跳过 API 写入")
return {"written": 0, "missing": len(plans), "failed": 0}
return {"written": 0, "missing": len(plans), "failed": 0, "skipped": "no-config"}
headers = {"X-Emby-Token": key, "Content-Type": "application/json"}
@@ -179,7 +179,7 @@ class SpecialsService:
break
else:
log.warning(f"⚠️ 连不上 Jellyfin(试过 {', '.join(candidates)})")
return {"written": 0, "missing": len(plans), "failed": 0}
return {"written": 0, "missing": len(plans), "failed": 0, "skipped": "unreachable"}
def get(path: str, **params):
params.setdefault("api_key", key)
@@ -192,7 +192,7 @@ class SpecialsService:
series = (search.get("Items") or [])
if not series:
log.warning(f"⚠️ Jellyfin 里找不到剧集: {show_name}")
return {"written": 0, "missing": len(plans), "failed": 0}
return {"written": 0, "missing": len(plans), "failed": 0, "skipped": "no-series"}
series_id = series[0]["Id"]
episodes = get(f"/Shows/{series_id}/Episodes", season="0", limit="500").get("Items") or []
by_number = {item.get("IndexNumber"): item for item in episodes}
@@ -218,7 +218,7 @@ class SpecialsService:
except OSError as exc:
log.warning(f"⚠️ API 写入失败 S00E{cand['ep']}: {exc}")
failed += 1
return {"written": written, "missing": missing, "failed": failed}
return {"written": written, "missing": missing, "failed": failed, "skipped": None}
@classmethod
def preview(cls, plans: list[dict], limit: int = 10) -> None: