import json import os import re from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import Request, urlopen from dotenv import load_dotenv BASE_DIR = Path(__file__).resolve().parent load_dotenv(BASE_DIR / "config.env") YOUTUBE_METADATA_TIMEOUT = float(os.getenv("YOUTUBE_METADATA_TIMEOUT", "12")) YOUTUBE_OEMBED_URL = "https://www.youtube.com/oembed" YOUTUBE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$") INVALID_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]') WHITESPACE_RE = re.compile(r"\s+") def extract_youtube_id(value): """Extract an 11-character YouTube video ID from a path or filename.""" if value is None: return None stem = Path(str(value)).stem.strip() if YOUTUBE_ID_RE.fullmatch(stem): return stem bracketed = re.findall(r"\[([A-Za-z0-9_-]{11})\]", stem) if bracketed: return bracketed[-1] # Common downloader filenames end in a space/dot/dash/underscore plus ID. if len(stem) >= 11: candidate = stem[-11:] prefix = stem[:-11] if YOUTUBE_ID_RE.fullmatch(candidate): if not prefix or prefix[-1] in " ._-()[]": return candidate # Last resort: scan delimited tokens without assuming words are IDs. tokens = re.split(r"[\s.()\[\]]+", stem) for token in reversed(tokens): if YOUTUBE_ID_RE.fullmatch(token): return token return None def fetch_youtube_metadata(video_id, timeout=None): """Fetch title/channel metadata using YouTube's public oEmbed endpoint.""" if not YOUTUBE_ID_RE.fullmatch(str(video_id or "")): raise ValueError("Invalid YouTube video ID") query = urlencode({ "url": f"https://www.youtube.com/watch?v={video_id}", "format": "json", }) request = Request( f"{YOUTUBE_OEMBED_URL}?{query}", headers={ "User-Agent": "MediaServer-YouTubeMetadata/1.0", "Accept": "application/json", }, ) try: with urlopen(request, timeout=timeout or YOUTUBE_METADATA_TIMEOUT) as response: payload = json.loads(response.read().decode("utf-8")) except HTTPError as exc: if exc.code == 404: raise LookupError(f"YouTube metadata not found for {video_id}") from exc raise RuntimeError(f"YouTube HTTP error {exc.code} for {video_id}") from exc except URLError as exc: raise RuntimeError(f"YouTube request failed for {video_id}: {exc.reason}") from exc title = str(payload.get("title") or "").strip() if not title: raise LookupError(f"YouTube returned no title for {video_id}") return { "video_id": video_id, "title": title, "channel_name": str(payload.get("author_name") or "").strip() or None, "channel_url": str(payload.get("author_url") or "").strip() or None, } def safe_filename_title(title, max_length=180): """Return a filesystem-safe title while keeping normal punctuation readable.""" value = INVALID_FILENAME_CHARS.sub("", str(title or "")) value = WHITESPACE_RE.sub(" ", value).strip(" .") if not value: value = "YouTube Video" if len(value) > max_length: value = value[:max_length].rstrip(" .") return value def build_youtube_filename(title, video_id, suffix): """Build: Nice Video Title [VIDEO_ID].ext""" if not YOUTUBE_ID_RE.fullmatch(str(video_id or "")): raise ValueError("Invalid YouTube video ID") suffix = str(suffix or "") if suffix and not suffix.startswith("."): suffix = "." + suffix return f"{safe_filename_title(title)} [{video_id}]{suffix}"