478 lines
14 KiB
Python
478 lines
14 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import urllib.request
|
|
import xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent
|
|
load_dotenv(BASE_DIR / "config.env")
|
|
|
|
YTDLP_METADATA_ENRICH = os.getenv(
|
|
"YOUTUBE_METADATA_ENRICH",
|
|
"true",
|
|
).lower() not in {"0", "false", "no", "off"}
|
|
|
|
YTDLP_WRITE_INFO_JSON = os.getenv(
|
|
"YOUTUBE_WRITE_INFO_JSON",
|
|
"true",
|
|
).lower() not in {"0", "false", "no", "off"}
|
|
|
|
ARTWORK_TIMEOUT = max(
|
|
3,
|
|
int(os.getenv("METADATA_ARTWORK_TIMEOUT", "20")),
|
|
)
|
|
|
|
_IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp")
|
|
|
|
|
|
def _safe_sidecar(path: Path, media_path: str | Path) -> Path | None:
|
|
"""Only serve sidecars that resolve beneath the directory containing the media."""
|
|
root = Path(media_path).resolve().parent
|
|
try:
|
|
resolved = path.resolve(strict=True)
|
|
resolved.relative_to(root)
|
|
except (OSError, ValueError, RuntimeError):
|
|
return None
|
|
return resolved if resolved.is_file() else None
|
|
|
|
|
|
def _text(node, *names):
|
|
for name in names:
|
|
child = node.find(name)
|
|
if child is not None and child.text:
|
|
value = child.text.strip()
|
|
if value:
|
|
return value
|
|
return ""
|
|
|
|
|
|
def _int_text(node, *names):
|
|
value = _text(node, *names)
|
|
if not value:
|
|
return None
|
|
match = re.search(r"-?\d+", value)
|
|
return int(match.group(0)) if match else None
|
|
|
|
|
|
def _all_text(node, name):
|
|
values = []
|
|
for child in node.findall(name):
|
|
if child.text and child.text.strip():
|
|
values.append(child.text.strip())
|
|
return values
|
|
|
|
|
|
def nfo_candidates(media_path: str | Path):
|
|
path = Path(media_path)
|
|
# Prefer matching episode NFO over generic movie/show metadata.
|
|
return [
|
|
path.with_suffix(".nfo"),
|
|
path.parent / "movie.nfo",
|
|
path.parent / "episode.nfo",
|
|
path.parent / "musicvideo.nfo",
|
|
path.parent / "tvshow.nfo",
|
|
]
|
|
|
|
|
|
def artwork_candidates(media_path: str | Path):
|
|
path = Path(media_path)
|
|
names = [f"{path.stem}-poster", f"{path.stem}-thumb", f"{path.stem}-primary", path.stem,
|
|
"poster", "folder", "cover", "primary", "thumb", "landscape", "backdrop"]
|
|
return [path.parent / f"{name}{ext}" for name in names for ext in _IMAGE_EXTS]
|
|
|
|
|
|
def _trickplay_candidates(media_path: str | Path):
|
|
"""Jellyfin trickplay is fallback imagery, not a movie poster."""
|
|
path = Path(media_path)
|
|
folder = path.parent / f"{path.stem}.trickplay"
|
|
if not folder.is_dir():
|
|
return []
|
|
candidates = []
|
|
# Prefer first contact sheet at the largest available supported resolution.
|
|
for subdir in folder.iterdir():
|
|
if subdir.is_dir():
|
|
for name in ("0.jpg", "0.jpeg", "0.png", "1.jpg", "1.jpeg"):
|
|
candidate = subdir / name
|
|
if candidate.is_file():
|
|
candidates.append(candidate)
|
|
break
|
|
def sort_key(p):
|
|
try: width = int(p.parent.name.split("-", 1)[0])
|
|
except ValueError: width = 0
|
|
return (-width, p.parent.name)
|
|
return sorted(candidates, key=sort_key)
|
|
|
|
|
|
def find_nfo(media_path: str | Path):
|
|
for candidate in nfo_candidates(media_path):
|
|
safe = _safe_sidecar(candidate, media_path)
|
|
if safe is not None:
|
|
return safe
|
|
return None
|
|
|
|
|
|
def find_artwork(media_path: str | Path):
|
|
for candidate in artwork_candidates(media_path):
|
|
safe = _safe_sidecar(candidate, media_path)
|
|
if safe is not None:
|
|
return safe
|
|
# Trickplay contact sheets are grids of frames, not cover artwork.
|
|
# A single-frame generated thumbnail is the fallback when no sidecar poster exists.
|
|
return None
|
|
|
|
|
|
def sidecar_signature(media_path: str | Path):
|
|
newest = 0
|
|
for candidate in nfo_candidates(media_path) + artwork_candidates(media_path):
|
|
try:
|
|
safe = _safe_sidecar(candidate, media_path)
|
|
if safe is not None:
|
|
newest = max(newest, int(safe.stat().st_mtime_ns))
|
|
except OSError:
|
|
pass
|
|
return newest
|
|
|
|
|
|
def read_nfo(media_path: str | Path) -> dict[str, Any]:
|
|
nfo = find_nfo(media_path)
|
|
art = find_artwork(media_path)
|
|
if nfo is None:
|
|
return {
|
|
"nfo_path": "",
|
|
"artwork_path": str(art) if art else "",
|
|
"sidecar_mtime_ns": sidecar_signature(media_path),
|
|
}
|
|
|
|
try:
|
|
root = ET.parse(nfo).getroot()
|
|
except Exception as error:
|
|
return {
|
|
"nfo_path": str(nfo),
|
|
"artwork_path": str(art) if art else "",
|
|
"sidecar_mtime_ns": sidecar_signature(media_path),
|
|
"nfo_error": str(error),
|
|
}
|
|
|
|
uniqueids = {}
|
|
for child in root.findall("uniqueid"):
|
|
value = (child.text or "").strip()
|
|
if value:
|
|
uniqueids[str(child.attrib.get("type") or "default")] = value
|
|
|
|
artists = _all_text(root, "artist")
|
|
genres = _all_text(root, "genre")
|
|
tags = _all_text(root, "tag")
|
|
|
|
result = {
|
|
"root": root.tag,
|
|
"title": _text(root, "title", "name"),
|
|
"sort_title": _text(root, "sorttitle"),
|
|
"original_title": _text(root, "originaltitle"),
|
|
"series_title": _text(root, "showtitle", "series"),
|
|
"episode_title": _text(root, "episodetitle"),
|
|
"year": _int_text(root, "year"),
|
|
"season": _int_text(root, "season"),
|
|
"episode": _int_text(root, "episode"),
|
|
"plot": _text(root, "plot", "outline", "description"),
|
|
"album": _text(root, "album"),
|
|
"artist": _text(root, "albumartist") or (artists[0] if artists else ""),
|
|
"artists": artists,
|
|
"channel": _text(root, "studio", "channel", "uploader"),
|
|
"premiered": _text(root, "premiered", "aired", "date"),
|
|
"runtime": _text(root, "runtime"),
|
|
"genres": genres,
|
|
"tags": tags,
|
|
"uniqueids": uniqueids,
|
|
"nfo_path": str(nfo),
|
|
"artwork_path": str(art) if art else "",
|
|
"sidecar_mtime_ns": sidecar_signature(media_path),
|
|
}
|
|
|
|
# An NFO may reference a local artwork file explicitly.
|
|
thumb = _text(root, "thumb")
|
|
if thumb and not result["artwork_path"]:
|
|
thumb_path = Path(thumb)
|
|
if not thumb_path.is_absolute():
|
|
thumb_path = nfo.parent / thumb_path
|
|
safe_thumb = _safe_sidecar(thumb_path, media_path)
|
|
if safe_thumb is not None and not any(part.endswith(".trickplay") for part in safe_thumb.parts):
|
|
if safe_thumb.suffix.lower() in _IMAGE_EXTS:
|
|
result["artwork_path"] = str(safe_thumb)
|
|
|
|
return result
|
|
|
|
|
|
def apply_nfo_to_item(item: dict[str, Any], media_path: str | Path):
|
|
sidecar = read_nfo(media_path)
|
|
item = dict(item)
|
|
|
|
if sidecar.get("title"):
|
|
item["title"] = sidecar["title"]
|
|
if sidecar.get("series_title"):
|
|
item["series_title"] = sidecar["series_title"]
|
|
if sidecar.get("episode_title"):
|
|
item["episode_title"] = sidecar["episode_title"]
|
|
if sidecar.get("year") is not None:
|
|
item["year"] = sidecar["year"]
|
|
if sidecar.get("season") is not None:
|
|
item["season"] = sidecar["season"]
|
|
if sidecar.get("episode") is not None:
|
|
item["episode"] = sidecar["episode"]
|
|
|
|
item["description"] = sidecar.get("plot") or item.get("description") or ""
|
|
item["nfo_path"] = sidecar.get("nfo_path") or ""
|
|
item["artwork_path"] = sidecar.get("artwork_path") or ""
|
|
item["sidecar_mtime_ns"] = int(sidecar.get("sidecar_mtime_ns") or 0)
|
|
item["metadata_json"] = json.dumps(
|
|
sidecar,
|
|
ensure_ascii=False,
|
|
separators=(",", ":"),
|
|
)
|
|
return item
|
|
|
|
|
|
def _safe_xml_text(value):
|
|
if value is None:
|
|
return ""
|
|
return str(value)
|
|
|
|
|
|
def _add_text(root, tag, value):
|
|
if value in (None, "", []):
|
|
return
|
|
child = ET.SubElement(root, tag)
|
|
child.text = _safe_xml_text(value)
|
|
|
|
|
|
def _write_xml(path: Path, root):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tree = ET.ElementTree(root)
|
|
try:
|
|
ET.indent(tree, space=" ")
|
|
except AttributeError:
|
|
pass
|
|
temp = path.with_suffix(path.suffix + ".tmp")
|
|
tree.write(temp, encoding="utf-8", xml_declaration=True)
|
|
os.replace(temp, path)
|
|
return path
|
|
|
|
|
|
def download_artwork(url: str, destination: str | Path):
|
|
url = str(url or "").strip()
|
|
destination = Path(destination)
|
|
if not url:
|
|
return None
|
|
|
|
if destination.is_file() and destination.stat().st_size > 0:
|
|
return destination
|
|
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
temp = destination.with_suffix(destination.suffix + ".tmp")
|
|
request = urllib.request.Request(
|
|
url,
|
|
headers={
|
|
"User-Agent": "Mozilla/5.0 KronicMedia/1.0",
|
|
},
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=ARTWORK_TIMEOUT) as response:
|
|
with open(temp, "wb") as handle:
|
|
shutil.copyfileobj(response, handle)
|
|
if temp.stat().st_size <= 0:
|
|
temp.unlink(missing_ok=True)
|
|
return None
|
|
os.replace(temp, destination)
|
|
return destination
|
|
except Exception:
|
|
try:
|
|
temp.unlink(missing_ok=True)
|
|
except OSError:
|
|
pass
|
|
return None
|
|
|
|
|
|
def enrich_youtube_info(video_id: str, existing: dict | None = None):
|
|
info = dict(existing or {})
|
|
if not YTDLP_METADATA_ENRICH:
|
|
return info
|
|
|
|
# If the resolver already returned the important fields, avoid an extra
|
|
# network extraction.
|
|
if (
|
|
info.get("title")
|
|
and (info.get("thumbnail") or info.get("thumbnails"))
|
|
and info.get("description") is not None
|
|
):
|
|
return info
|
|
|
|
try:
|
|
import yt_dlp
|
|
except Exception:
|
|
return info
|
|
|
|
url = f"https://www.youtube.com/watch?v={video_id}"
|
|
options = {
|
|
"quiet": True,
|
|
"no_warnings": True,
|
|
"skip_download": True,
|
|
"noplaylist": True,
|
|
"extract_flat": False,
|
|
}
|
|
|
|
try:
|
|
with yt_dlp.YoutubeDL(options) as ydl:
|
|
fetched = ydl.extract_info(url, download=False) or {}
|
|
except Exception:
|
|
return info
|
|
|
|
for key, value in fetched.items():
|
|
if info.get(key) in (None, "", [], {}):
|
|
info[key] = value
|
|
return info
|
|
|
|
|
|
def youtube_metadata(video_id: str, info: dict | None = None):
|
|
info = enrich_youtube_info(video_id, info)
|
|
thumbnails = info.get("thumbnails") or []
|
|
thumbnail = info.get("thumbnail") or ""
|
|
if not thumbnail and thumbnails:
|
|
for item in reversed(thumbnails):
|
|
if isinstance(item, dict) and item.get("url"):
|
|
thumbnail = item["url"]
|
|
break
|
|
|
|
return {
|
|
"video_id": video_id,
|
|
"title": info.get("title") or video_id,
|
|
"description": info.get("description") or "",
|
|
"channel": info.get("channel") or info.get("uploader") or "",
|
|
"channel_id": info.get("channel_id") or info.get("uploader_id") or "",
|
|
"webpage_url": info.get("webpage_url") or f"https://www.youtube.com/watch?v={video_id}",
|
|
"thumbnail": thumbnail,
|
|
"duration": info.get("duration"),
|
|
"upload_date": info.get("upload_date") or "",
|
|
"timestamp": info.get("timestamp"),
|
|
"live_status": info.get("live_status") or "",
|
|
"is_live": bool(info.get("is_live")),
|
|
"categories": info.get("categories") or [],
|
|
"tags": info.get("tags") or [],
|
|
"raw": info,
|
|
}
|
|
|
|
|
|
def write_video_sidecar(
|
|
media_path: str | Path,
|
|
video_id: str,
|
|
info: dict | None = None,
|
|
):
|
|
media_path = Path(media_path).resolve()
|
|
meta = youtube_metadata(video_id, info)
|
|
|
|
nfo_path = media_path.with_suffix(".nfo")
|
|
art_path = media_path.with_suffix(".jpg")
|
|
|
|
root = ET.Element("movie")
|
|
_add_text(root, "title", meta["title"])
|
|
_add_text(root, "plot", meta["description"])
|
|
_add_text(root, "studio", meta["channel"])
|
|
_add_text(root, "premiered", meta["upload_date"])
|
|
_add_text(root, "runtime", meta["duration"])
|
|
_add_text(root, "source", "youtube")
|
|
_add_text(root, "webpage", meta["webpage_url"])
|
|
|
|
uid = ET.SubElement(root, "uniqueid", {"type": "youtube", "default": "true"})
|
|
uid.text = str(video_id)
|
|
|
|
if meta["thumbnail"]:
|
|
_add_text(root, "thumb", art_path.name)
|
|
|
|
for category in meta["categories"]:
|
|
_add_text(root, "genre", category)
|
|
for tag in meta["tags"]:
|
|
_add_text(root, "tag", tag)
|
|
|
|
_write_xml(nfo_path, root)
|
|
if meta["thumbnail"]:
|
|
download_artwork(meta["thumbnail"], art_path)
|
|
|
|
if YTDLP_WRITE_INFO_JSON:
|
|
info_path = media_path.with_suffix(".info.json")
|
|
clean = dict(meta["raw"])
|
|
# Keep sidecars serializable even when extractor internals contain
|
|
# special objects.
|
|
try:
|
|
info_path.write_text(
|
|
json.dumps(clean, ensure_ascii=False, indent=2, default=str),
|
|
encoding="utf-8",
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
return {
|
|
"nfo_path": str(nfo_path),
|
|
"artwork_path": str(art_path) if art_path.is_file() else "",
|
|
"metadata": meta,
|
|
}
|
|
|
|
|
|
def write_audio_sidecar(
|
|
media_path: str | Path,
|
|
*,
|
|
title: str,
|
|
artist: str = "",
|
|
artists=None,
|
|
album: str = "",
|
|
year=None,
|
|
duration=None,
|
|
cover_url: str = "",
|
|
spotify_id: str = "",
|
|
spotify_url: str = "",
|
|
youtube_id: str = "",
|
|
description: str = "",
|
|
isrc: str = "",
|
|
list_name: str = "",
|
|
):
|
|
media_path = Path(media_path).resolve()
|
|
nfo_path = media_path.with_suffix(".nfo")
|
|
art_path = media_path.with_suffix(".jpg")
|
|
|
|
root = ET.Element("audio")
|
|
_add_text(root, "title", title)
|
|
for value in (artists or ([artist] if artist else [])):
|
|
_add_text(root, "artist", value)
|
|
_add_text(root, "album", album)
|
|
_add_text(root, "year", year)
|
|
_add_text(root, "runtime", duration)
|
|
_add_text(root, "plot", description)
|
|
_add_text(root, "isrc", isrc)
|
|
_add_text(root, "playlist", list_name)
|
|
_add_text(root, "source", "kronic-music")
|
|
|
|
if spotify_id:
|
|
uid = ET.SubElement(root, "uniqueid", {"type": "spotify", "default": "true"})
|
|
uid.text = spotify_id
|
|
if youtube_id:
|
|
uid = ET.SubElement(root, "uniqueid", {"type": "youtube"})
|
|
uid.text = youtube_id
|
|
if spotify_url:
|
|
_add_text(root, "spotifyurl", spotify_url)
|
|
|
|
if cover_url:
|
|
_add_text(root, "thumb", art_path.name)
|
|
|
|
_write_xml(nfo_path, root)
|
|
if cover_url:
|
|
download_artwork(cover_url, art_path)
|
|
|
|
return {
|
|
"nfo_path": str(nfo_path),
|
|
"artwork_path": str(art_path) if art_path.is_file() else "",
|
|
}
|