diff --git a/iptv.py b/iptv.py new file mode 100644 index 0000000..4d2feee --- /dev/null +++ b/iptv.py @@ -0,0 +1,1098 @@ +from __future__ import annotations + +import json +import os +import re +import sqlite3 +import subprocess +import threading +import time +import urllib.request +import urllib.error +import hashlib +import ipaddress +import socket +from urllib.parse import urlsplit +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") + +DB_PATH = Path(os.getenv("DB_PATH", BASE_DIR / "media_library.db")).expanduser().resolve() +FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg") +FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe") +IPTV_FETCH_TIMEOUT = max(3, int(os.getenv("IPTV_FETCH_TIMEOUT", "15"))) +IPTV_MAX_PLAYLIST_BYTES = max(1024 * 1024, int(os.getenv("IPTV_MAX_PLAYLIST_MB", "20")) * 1024 * 1024) +IPTV_USER_AGENT = os.getenv( + "IPTV_USER_AGENT", + "Mozilla/5.0 (Kronic Media Server IPTV)", +) +IPTV_TRANSCODE_MODE = os.getenv("IPTV_TRANSCODE_MODE", "auto").strip().lower() +IPTV_X264_PRESET = os.getenv("IPTV_X264_PRESET", "veryfast") +IPTV_X264_CRF = str(int(os.getenv("IPTV_X264_CRF", "22"))) +IPTV_AUDIO_BITRATE = os.getenv("IPTV_AUDIO_BITRATE", "160k") +IPTV_AUDIO_CHANNELS = max(1, min(6, int(os.getenv("IPTV_AUDIO_CHANNELS", "2")))) +IPTV_AUDIO_MODE = os.getenv("IPTV_AUDIO_MODE", "normalize").strip().lower() +IPTV_PROBE_TIMEOUT = max(3, int(os.getenv("IPTV_PROBE_TIMEOUT", "8"))) +IPTV_SNAPSHOT_DIR = Path(os.getenv("IPTV_SNAPSHOT_DIR", BASE_DIR / "iptv-snapshots")).expanduser().resolve() +IPTV_SNAPSHOT_TTL_MINUTES = max(1, int(os.getenv("IPTV_SNAPSHOT_TTL_MINUTES", "180"))) +IPTV_SNAPSHOT_TIMEOUT = max(3, int(os.getenv("IPTV_SNAPSHOT_TIMEOUT", "12"))) +IPTV_SNAPSHOT_WIDTH = max(240, int(os.getenv("IPTV_SNAPSHOT_WIDTH", "640"))) +IPTV_SNAPSHOT_CONCURRENCY = max(1, min(4, int(os.getenv("IPTV_SNAPSHOT_CONCURRENCY", "2")))) +_SNAPSHOT_SEMAPHORE = threading.BoundedSemaphore(IPTV_SNAPSHOT_CONCURRENCY) + + +# Explicit LAN exceptions: comma-separated hostnames or literal IPs, for trusted +# local IPTV receivers. Only admins configuring deployment should set this. +IPTV_TRUSTED_HOSTS = { + host.strip().lower().rstrip('.') for host in + os.getenv("IPTV_TRUSTED_HOSTS", "").split(",") if host.strip() +} + + +def validate_iptv_url(url: str) -> str: + """Reject local files, unsafe protocols and internal network targets by default. + + Note: validation at resolution time cannot completely defeat hostile DNS rebinding. + For internet-facing multi-tenant instances, isolate FFmpeg/playlist fetchers at + the network layer as well. + """ + value = str(url or "").strip() + if not value or len(value) > 4096 or any(ord(c) < 32 for c in value): + raise ValueError("Invalid IPTV URL.") + parsed = urlsplit(value) + if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname: + raise ValueError("IPTV URLs must use HTTP or HTTPS.") + if parsed.username is not None or parsed.password is not None: + raise ValueError("Credentials embedded in IPTV URLs are not supported.") + try: + port = parsed.port + except ValueError as exc: + raise ValueError("Invalid IPTV port.") from exc + if port is not None and port not in {80, 443, 8080, 8000, 8443}: + raise ValueError("IPTV URL port is not permitted.") + host = parsed.hostname.rstrip('.').lower() + if host in IPTV_TRUSTED_HOSTS: + return value + try: + addresses = socket.getaddrinfo(host, port or (443 if parsed.scheme.lower() == 'https' else 80), type=socket.SOCK_STREAM) + except OSError as exc: + raise ValueError("Unable to resolve IPTV hostname.") from exc + if not addresses: + raise ValueError("Unable to resolve IPTV hostname.") + for info in addresses: + ip = ipaddress.ip_address(info[4][0]) + if not ip.is_global: + raise ValueError("IPTV URL resolves to a private or reserved address.") + return value + + +class _SafePlaylistRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + validate_iptv_url(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +_SAFE_PLAYLIST_OPENER = urllib.request.build_opener(_SafePlaylistRedirect()) + +_ATTR_RE = re.compile(r'''([A-Za-z0-9_.-]+)=(?:"([^"]*)"|'([^']*)'|([^\s,]+))''') + + +def _db() -> sqlite3.Connection: + DB_PATH.parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(DB_PATH, timeout=15) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA busy_timeout = 15000") + return conn + + +def init_iptv_db() -> None: + with _db() as db: + db.executescript( + """ + CREATE TABLE IF NOT EXISTS iptv_collections ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_user_id INTEGER NOT NULL, + name TEXT NOT NULL, + is_public INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + UNIQUE(owner_user_id, name COLLATE NOCASE) + ); + + CREATE TABLE IF NOT EXISTS iptv_sources ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_user_id INTEGER NOT NULL, + collection_id INTEGER REFERENCES iptv_collections(id) ON DELETE SET NULL, + name TEXT NOT NULL, + source_type TEXT NOT NULL CHECK(source_type IN ('upload','url','channel')), + source_value TEXT NOT NULL DEFAULT '', + source_payload TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + is_public INTEGER NOT NULL DEFAULT 0, + last_refresh_at INTEGER, + last_error TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_iptv_sources_owner ON iptv_sources(owner_user_id); + + CREATE TABLE IF NOT EXISTS iptv_channels ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + source_id INTEGER NOT NULL REFERENCES iptv_sources(id) ON DELETE CASCADE, + stable_key TEXT NOT NULL, + name TEXT NOT NULL, + stream_url TEXT NOT NULL, + tvg_id TEXT NOT NULL DEFAULT '', + tvg_name TEXT NOT NULL DEFAULT '', + tvg_logo TEXT NOT NULL DEFAULT '', + group_name TEXT NOT NULL DEFAULT '', + channel_number TEXT NOT NULL DEFAULT '', + referrer TEXT NOT NULL DEFAULT '', + user_agent TEXT NOT NULL DEFAULT '', + raw_options_json TEXT NOT NULL DEFAULT '{}', + selected INTEGER NOT NULL DEFAULT 0, + hidden INTEGER NOT NULL DEFAULT 0, + sort_order INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL, + UNIQUE(source_id, stable_key) + ); + CREATE INDEX IF NOT EXISTS idx_iptv_channels_source ON iptv_channels(source_id); + CREATE INDEX IF NOT EXISTS idx_iptv_channels_selected ON iptv_channels(selected, hidden); + + CREATE TABLE IF NOT EXISTS iptv_channel_preferences ( + user_id INTEGER NOT NULL, + channel_id INTEGER NOT NULL REFERENCES iptv_channels(id) ON DELETE CASCADE, + hidden INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL, + PRIMARY KEY(user_id, channel_id) + ); + CREATE INDEX IF NOT EXISTS idx_iptv_channel_preferences_user + ON iptv_channel_preferences(user_id, hidden); + """ + ) + + collection_columns = { + row["name"] + for row in db.execute("PRAGMA table_info(iptv_collections)").fetchall() + } + if "is_public" not in collection_columns: + db.execute( + "ALTER TABLE iptv_collections ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0" + ) + + source_columns = { + row["name"] + for row in db.execute("PRAGMA table_info(iptv_sources)").fetchall() + } + if "is_public" not in source_columns: + db.execute( + "ALTER TABLE iptv_sources ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0" + ) + + # Older builds stored Hide directly on the channel row. Preserve those + # choices as owner-specific preferences, then clear the global flag. + now = int(time.time()) + db.execute( + """ + INSERT OR IGNORE INTO iptv_channel_preferences + (user_id, channel_id, hidden, updated_at) + SELECT s.owner_user_id, ch.id, 1, ? + FROM iptv_channels ch + JOIN iptv_sources s ON s.id=ch.source_id + WHERE ch.hidden=1 + """, + (now,), + ) + db.execute("UPDATE iptv_channels SET hidden=0 WHERE hidden<>0") + db.commit() + + +def _row(row: sqlite3.Row | None) -> dict[str, Any] | None: + return dict(row) if row is not None else None + + +def list_collections(user_id: int) -> list[dict[str, Any]]: + with _db() as db: + rows = db.execute( + """SELECT c.*, + (SELECT COUNT(*) FROM iptv_sources s WHERE s.collection_id=c.id) AS source_count, + (SELECT COUNT(*) FROM iptv_channels ch JOIN iptv_sources s ON s.id=ch.source_id + WHERE s.collection_id=c.id AND ch.selected=1) AS channel_count + FROM iptv_collections c + WHERE c.owner_user_id=? + ORDER BY c.name COLLATE NOCASE""", + (int(user_id),), + ).fetchall() + return [dict(r) for r in rows] + + +def create_collection(user_id: int, name: str, is_public: bool = False) -> dict[str, Any]: + name = str(name or "").strip() + if not name: + raise ValueError("Playlist name is required.") + now = int(time.time()) + try: + with _db() as db: + cur = db.execute( + "INSERT INTO iptv_collections(owner_user_id,name,is_public,created_at) VALUES(?,?,?,?)", + (int(user_id), name, 1 if is_public else 0, now), + ) + db.commit() + collection_id = int(cur.lastrowid) + except sqlite3.IntegrityError as exc: + raise ValueError("A playlist with that name already exists.") from exc + return {"id": collection_id, "name": name, "is_public": 1 if is_public else 0} + + +def delete_collection(user_id: int, collection_id: int) -> None: + with _db() as db: + result = db.execute( + "DELETE FROM iptv_collections WHERE id=? AND owner_user_id=?", + (int(collection_id), int(user_id)), + ) + if result.rowcount == 0: + raise KeyError("Playlist not found.") + db.commit() + + +def set_collection_public(user_id: int, collection_id: int, is_public: bool) -> None: + with _db() as db: + result = db.execute( + "UPDATE iptv_collections SET is_public=? WHERE id=? AND owner_user_id=?", + (1 if is_public else 0, int(collection_id), int(user_id)), + ) + if result.rowcount == 0: + raise KeyError("Playlist not found.") + db.commit() + + +def set_source_public(user_id: int, source_id: int, is_public: bool) -> None: + with _db() as db: + result = db.execute( + "UPDATE iptv_sources SET is_public=? WHERE id=? AND owner_user_id=?", + (1 if is_public else 0, int(source_id), int(user_id)), + ) + if result.rowcount == 0: + raise KeyError("IPTV source not found.") + db.commit() + + +def list_sources(user_id: int) -> list[dict[str, Any]]: + with _db() as db: + rows = db.execute( + """SELECT s.*, c.name AS collection_name, + (SELECT COUNT(*) FROM iptv_channels ch WHERE ch.source_id=s.id) AS channel_count, + (SELECT COUNT(*) FROM iptv_channels ch WHERE ch.source_id=s.id AND ch.selected=1) AS selected_count + FROM iptv_sources s + LEFT JOIN iptv_collections c ON c.id=s.collection_id + WHERE s.owner_user_id=? + ORDER BY COALESCE(c.name,''), s.name COLLATE NOCASE""", + (int(user_id),), + ).fetchall() + return [dict(r) for r in rows] + + +def _validate_collection(db: sqlite3.Connection, user_id: int, collection_id: int | None) -> int | None: + if collection_id in (None, "", 0, "0"): + return None + collection_id = int(collection_id) + row = db.execute( + "SELECT id FROM iptv_collections WHERE id=? AND owner_user_id=?", + (collection_id, int(user_id)), + ).fetchone() + if not row: + raise ValueError("Playlist does not belong to this user.") + return collection_id + + +def create_source( + user_id: int, + *, + name: str, + source_type: str, + source_value: str = "", + source_payload: str = "", + collection_id: int | None = None, + channel_name: str = "", + is_public: bool = False, +) -> dict[str, Any]: + name = str(name or "").strip() + source_type = str(source_type or "").strip().lower() + source_value = str(source_value or "").strip() + source_payload = str(source_payload or "") + + if source_type not in {"upload", "url", "channel"}: + raise ValueError("Invalid IPTV source type.") + if not name: + raise ValueError("A name is required.") + if source_type in {"url", "channel"}: + source_value = validate_iptv_url(source_value) + if source_type == "upload" and not source_payload.strip(): + raise ValueError("The uploaded M3U file is empty.") + if len(source_payload.encode("utf-8", "ignore")) > IPTV_MAX_PLAYLIST_BYTES: + raise ValueError("The uploaded playlist is too large.") + + now = int(time.time()) + with _db() as db: + collection_id = _validate_collection(db, user_id, collection_id) + cur = db.execute( + """INSERT INTO iptv_sources + (owner_user_id,collection_id,name,source_type,source_value,source_payload,enabled,is_public,created_at) + VALUES(?,?,?,?,?,?,1,?,?)""", + ( + int(user_id), + collection_id, + name, + source_type, + source_value, + source_payload, + 1 if is_public else 0, + now, + ), + ) + source_id = int(cur.lastrowid) + db.commit() + + if source_type == "channel": + channel_display = str(channel_name or name).strip() or name + channels = [{ + "name": channel_display, + "stream_url": source_value, + "tvg_id": "", + "tvg_name": channel_display, + "tvg_logo": "", + "group_name": "", + "channel_number": "", + "referrer": "", + "user_agent": "", + "raw_options": {}, + }] + _replace_source_channels(user_id, source_id, channels, direct_default_selected=True) + _mark_source_refresh(source_id, error="") + else: + refresh_source(user_id, source_id) + + return get_source(user_id, source_id) or {"id": source_id, "name": name} + + +def get_source(user_id: int, source_id: int) -> dict[str, Any] | None: + with _db() as db: + row = db.execute( + """SELECT s.*, c.name AS collection_name FROM iptv_sources s + LEFT JOIN iptv_collections c ON c.id=s.collection_id + WHERE s.id=? AND s.owner_user_id=?""", + (int(source_id), int(user_id)), + ).fetchone() + return _row(row) + + +def delete_source(user_id: int, source_id: int) -> None: + with _db() as db: + result = db.execute( + "DELETE FROM iptv_sources WHERE id=? AND owner_user_id=?", + (int(source_id), int(user_id)), + ) + if result.rowcount == 0: + raise KeyError("IPTV source not found.") + db.commit() + + +def move_source_to_collection(user_id: int, source_id: int, collection_id: int | None) -> None: + with _db() as db: + collection_id = _validate_collection(db, user_id, collection_id) + result = db.execute( + "UPDATE iptv_sources SET collection_id=? WHERE id=? AND owner_user_id=?", + (collection_id, int(source_id), int(user_id)), + ) + if result.rowcount == 0: + raise KeyError("IPTV source not found.") + db.commit() + + +def _fetch_playlist(url: str) -> str: + url = validate_iptv_url(url) + request = urllib.request.Request( + url, + headers={ + "User-Agent": IPTV_USER_AGENT, + "Accept": "application/x-mpegURL, application/vnd.apple.mpegurl, text/plain, */*", + }, + ) + try: + with _SAFE_PLAYLIST_OPENER.open(request, timeout=IPTV_FETCH_TIMEOUT) as response: + data = response.read(IPTV_MAX_PLAYLIST_BYTES + 1) + if len(data) > IPTV_MAX_PLAYLIST_BYTES: + raise ValueError("Remote playlist is too large.") + encoding = response.headers.get_content_charset() or "utf-8" + return data.decode(encoding, "replace") + except urllib.error.HTTPError as exc: + raise ValueError(f"Playlist HTTP error {exc.code}.") from exc + except urllib.error.URLError as exc: + raise ValueError(f"Could not fetch playlist: {exc.reason}") from exc + + +def refresh_source(user_id: int, source_id: int) -> dict[str, Any]: + source = get_source(user_id, source_id) + if not source: + raise KeyError("IPTV source not found.") + + source_type = source["source_type"] + if source_type == "channel": + _mark_source_refresh(source_id, error="") + return {"ok": True, "channels": 1} + + try: + if source_type == "upload": + text = source["source_payload"] + else: + text = _fetch_playlist(source["source_value"]) + channels = parse_m3u(text) + _replace_source_channels(user_id, source_id, channels, direct_default_selected=False) + _mark_source_refresh(source_id, error="") + return {"ok": True, "channels": len(channels)} + except Exception as exc: + _mark_source_refresh(source_id, error=str(exc)) + raise + + +def _mark_source_refresh(source_id: int, *, error: str) -> None: + with _db() as db: + db.execute( + "UPDATE iptv_sources SET last_refresh_at=?, last_error=? WHERE id=?", + (int(time.time()), str(error or ""), int(source_id)), + ) + db.commit() + + +def parse_m3u(text: str) -> list[dict[str, Any]]: + lines = [line.strip() for line in str(text or "").replace("\ufeff", "").splitlines()] + channels: list[dict[str, Any]] = [] + pending: dict[str, Any] | None = None + pending_options: dict[str, str] = {} + + for line in lines: + if not line: + continue + + if line.startswith("#EXTINF:"): + body = line.split(":", 1)[1] + attrs = {} + for match in _ATTR_RE.finditer(body): + attrs[match.group(1).lower()] = next( + value for value in match.groups()[1:] if value is not None + ) + comma_index = body.rfind(",") + name = body[comma_index + 1:].strip() if comma_index >= 0 else "Channel" + pending = { + "name": name or attrs.get("tvg-name") or "Channel", + "tvg_id": attrs.get("tvg-id", ""), + "tvg_name": attrs.get("tvg-name", ""), + "tvg_logo": attrs.get("tvg-logo", ""), + "group_name": attrs.get("group-title", ""), + "channel_number": attrs.get("tvg-chno", attrs.get("channel-number", "")), + "referrer": "", + "user_agent": "", + "raw_options": {}, + } + pending_options = {} + continue + + if line.startswith("#EXTVLCOPT:"): + key_value = line[len("#EXTVLCOPT:"):] + key, sep, value = key_value.partition("=") + if sep: + key = key.strip().lower() + value = value.strip() + pending_options[key] = value + if pending is not None: + if key in {"http-referrer", "http-referrer-url", "referrer"}: + pending["referrer"] = value + elif key in {"http-user-agent", "user-agent"}: + pending["user_agent"] = value + continue + + if line.startswith("#EXTHTTP:"): + payload = line[len("#EXTHTTP:"):].strip() + try: + headers = json.loads(payload) + if isinstance(headers, dict): + for key, value in headers.items(): + pending_options[f"header:{key}"] = str(value) + if pending is not None: + if str(key).lower() == "referer": + pending["referrer"] = str(value) + if str(key).lower() == "user-agent": + pending["user_agent"] = str(value) + except Exception: + pass + continue + + if line.startswith("#"): + continue + + if "://" not in line: + continue + + entry = pending or { + "name": line, + "tvg_id": "", + "tvg_name": "", + "tvg_logo": "", + "group_name": "", + "channel_number": "", + "referrer": "", + "user_agent": "", + "raw_options": {}, + } + entry = dict(entry) + entry["stream_url"] = line + entry["raw_options"] = dict(pending_options) + channels.append(entry) + pending = None + pending_options = {} + + return channels + + +def _stable_key(channel: dict[str, Any]) -> str: + tvg_id = str(channel.get("tvg_id") or "").strip().lower() + stream_url = str(channel.get("stream_url") or "").strip() + name = str(channel.get("name") or "").strip().lower() + seed = f"{tvg_id}\0{name}\0{stream_url}" + return hashlib.sha1(seed.encode("utf-8", "ignore")).hexdigest() + + +def _replace_source_channels( + user_id: int, + source_id: int, + channels: list[dict[str, Any]], + *, + direct_default_selected: bool, +) -> None: + now = int(time.time()) + with _db() as db: + source = db.execute( + "SELECT id FROM iptv_sources WHERE id=? AND owner_user_id=?", + (int(source_id), int(user_id)), + ).fetchone() + if not source: + raise KeyError("IPTV source not found.") + + existing = { + row["stable_key"]: (int(row["selected"]), int(row["hidden"])) + for row in db.execute( + "SELECT stable_key,selected,hidden FROM iptv_channels WHERE source_id=?", + (int(source_id),), + ).fetchall() + } + + seen = set() + for index, channel in enumerate(channels): + # A playlist may contain local file paths or arbitrary FFmpeg protocols. + # Do not store those as executable playback sources. + try: + validate_iptv_url(channel.get("stream_url")) + except ValueError: + continue + stable_key = _stable_key(channel) + seen.add(stable_key) + selected, hidden = existing.get( + stable_key, + (1 if direct_default_selected else 0, 0), + ) + db.execute( + """INSERT INTO iptv_channels + (source_id,stable_key,name,stream_url,tvg_id,tvg_name,tvg_logo,group_name, + channel_number,referrer,user_agent,raw_options_json,selected,hidden,sort_order,updated_at) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT(source_id,stable_key) DO UPDATE SET + name=excluded.name, + stream_url=excluded.stream_url, + tvg_id=excluded.tvg_id, + tvg_name=excluded.tvg_name, + tvg_logo=excluded.tvg_logo, + group_name=excluded.group_name, + channel_number=excluded.channel_number, + referrer=excluded.referrer, + user_agent=excluded.user_agent, + raw_options_json=excluded.raw_options_json, + sort_order=excluded.sort_order, + updated_at=excluded.updated_at""", + ( + int(source_id), stable_key, str(channel.get("name") or "Channel"), + str(channel.get("stream_url") or ""), str(channel.get("tvg_id") or ""), + str(channel.get("tvg_name") or ""), str(channel.get("tvg_logo") or ""), + str(channel.get("group_name") or ""), str(channel.get("channel_number") or ""), + str(channel.get("referrer") or ""), str(channel.get("user_agent") or ""), + json.dumps(channel.get("raw_options") or {}, ensure_ascii=False), + selected, hidden, index, now, + ), + ) + + if seen: + placeholders = ",".join("?" for _ in seen) + db.execute( + f"DELETE FROM iptv_channels WHERE source_id=? AND stable_key NOT IN ({placeholders})", + (int(source_id), *seen), + ) + else: + db.execute("DELETE FROM iptv_channels WHERE source_id=?", (int(source_id),)) + db.commit() + + +def list_channels( + user_id: int, + *, + source_id: int | None = None, + selected_only: bool = False, + collection_id: int | None = None, +) -> list[dict[str, Any]]: + user_id = int(user_id) + + # Source chooser/management is owner-only. The general selected-channel + # listing includes the user's own channels plus anything explicitly shared. + if source_id is not None: + access_clause = "s.owner_user_id=?" + else: + access_clause = "(s.owner_user_id=? OR s.is_public=1 OR COALESCE(c.is_public,0)=1)" + + clauses = [access_clause] + values: list[Any] = [user_id] + + if source_id is not None: + clauses.append("s.id=?") + values.append(int(source_id)) + + if collection_id is not None: + clauses.append("s.collection_id=?") + values.append(int(collection_id)) + + if selected_only: + clauses.extend([ + "ch.selected=1", + "s.enabled=1", + "COALESCE(pref.hidden,0)=0", + ]) + + with _db() as db: + rows = db.execute( + f"""SELECT + ch.*, + s.name AS source_name, + s.owner_user_id, + s.collection_id, + s.is_public AS source_is_public, + c.name AS collection_name, + COALESCE(c.is_public,0) AS collection_is_public, + COALESCE(pref.hidden,0) AS user_hidden, + CASE + WHEN s.owner_user_id=? THEN 0 + ELSE 1 + END AS is_shared, + CASE + WHEN s.owner_user_id=? THEN 'owned' + WHEN COALESCE(c.is_public,0)=1 THEN 'playlist' + WHEN s.is_public=1 THEN 'source' + ELSE '' + END AS public_via, + CASE + WHEN s.owner_user_id=? THEN COALESCE(c.name,'My Channels') + WHEN COALESCE(c.is_public,0)=1 THEN c.name + ELSE 'Shared Channels' + END AS display_collection_name + FROM iptv_channels ch + JOIN iptv_sources s ON s.id=ch.source_id + LEFT JOIN iptv_collections c ON c.id=s.collection_id + LEFT JOIN iptv_channel_preferences pref + ON pref.channel_id=ch.id AND pref.user_id=? + WHERE {' AND '.join(clauses)} + ORDER BY + CASE WHEN s.owner_user_id=? THEN 0 ELSE 1 END, + CASE + WHEN s.owner_user_id=? THEN COALESCE(c.name,'') + WHEN COALESCE(c.is_public,0)=1 THEN COALESCE(c.name,'') + ELSE 'Shared Channels' + END COLLATE NOCASE, + COALESCE(NULLIF(ch.group_name,''), s.name) COLLATE NOCASE, + ch.sort_order, + ch.name COLLATE NOCASE""", + ( + user_id, + user_id, + user_id, + user_id, + *values, + user_id, + user_id, + ), + ).fetchall() + + return [dict(r) for r in rows] + + +def get_channel(user_id: int, channel_id: int) -> dict[str, Any] | None: + user_id = int(user_id) + with _db() as db: + row = db.execute( + """SELECT + ch.*, + s.name AS source_name, + s.owner_user_id, + s.enabled AS source_enabled, + s.is_public AS source_is_public, + s.collection_id, + c.name AS collection_name, + COALESCE(c.is_public,0) AS collection_is_public, + CASE WHEN s.owner_user_id=? THEN 0 ELSE 1 END AS is_shared + FROM iptv_channels ch + JOIN iptv_sources s ON s.id=ch.source_id + LEFT JOIN iptv_collections c ON c.id=s.collection_id + WHERE ch.id=? + AND ( + s.owner_user_id=? + OR ( + ch.selected=1 + AND s.enabled=1 + AND (s.is_public=1 OR COALESCE(c.is_public,0)=1) + ) + )""", + (user_id, int(channel_id), user_id), + ).fetchone() + return _row(row) + + +def set_channel_selection(user_id: int, source_id: int, channel_ids: list[int]) -> int: + channel_ids = sorted({int(x) for x in channel_ids}) + with _db() as db: + source = db.execute( + "SELECT id FROM iptv_sources WHERE id=? AND owner_user_id=?", + (int(source_id), int(user_id)), + ).fetchone() + if not source: + raise KeyError("IPTV source not found.") + + db.execute( + "UPDATE iptv_channels SET selected=0 WHERE source_id=?", + (int(source_id),), + ) + + if channel_ids: + placeholders = ",".join("?" for _ in channel_ids) + db.execute( + f"UPDATE iptv_channels SET selected=1 WHERE source_id=? AND id IN ({placeholders})", + (int(source_id), *channel_ids), + ) + + db.commit() + return len(channel_ids) + + +def set_channel_hidden(user_id: int, channel_id: int, hidden: bool) -> None: + user_id = int(user_id) + channel_id = int(channel_id) + + # Users may hide any channel they can currently access, including a + # shared/public channel. This never changes the owner's master selection. + channel = get_channel(user_id, channel_id) + if not channel: + raise KeyError("Channel not found.") + + now = int(time.time()) + with _db() as db: + db.execute( + """INSERT INTO iptv_channel_preferences(user_id,channel_id,hidden,updated_at) + VALUES(?,?,?,?) + ON CONFLICT(user_id,channel_id) + DO UPDATE SET hidden=excluded.hidden, updated_at=excluded.updated_at""", + (user_id, channel_id, 1 if hidden else 0, now), + ) + db.commit() + + +def update_channel(user_id: int, channel_id: int, data: dict[str, Any]) -> None: + # Hide is a per-user preference and is allowed for shared channels. + if "hidden" in data: + set_channel_hidden( + user_id, + channel_id, + bool(data["hidden"]), + ) + + # Everything else changes the owner's master channel record and therefore + # remains owner-only. + allowed = {"name", "group_name", "selected"} + assignments = [] + values: list[Any] = [] + + for key in allowed: + if key not in data: + continue + + value = data[key] + if key == "selected": + value = 1 if bool(value) else 0 + else: + value = str(value or "").strip() + + assignments.append(f"{key}=?") + values.append(value) + + if not assignments: + return + + values.extend([ + int(channel_id), + int(user_id), + ]) + + with _db() as db: + result = db.execute( + f"""UPDATE iptv_channels SET {', '.join(assignments)} + WHERE id=? AND source_id IN + (SELECT id FROM iptv_sources WHERE owner_user_id=?)""", + tuple(values), + ) + if result.rowcount == 0: + raise KeyError("Channel not found.") + db.commit() + + +def _header_string(channel: dict[str, Any]) -> str: + headers: list[str] = [] + user_agent = str(channel.get("user_agent") or "").strip() + referrer = str(channel.get("referrer") or "").strip() + if user_agent: + headers.append(f"User-Agent: {user_agent}") + if referrer: + headers.append(f"Referer: {referrer}") + try: + options = json.loads(channel.get("raw_options_json") or "{}") + except Exception: + options = {} + if isinstance(options, dict): + for key, value in options.items(): + if not str(key).startswith("header:"): + continue + header_name = str(key).split(":", 1)[1].strip() + if header_name and value: + headers.append(f"{header_name}: {value}") + return "\r\n".join(headers) + ("\r\n" if headers else "") + + +def channel_snapshot_path(channel_id: int) -> Path: + IPTV_SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True) + return IPTV_SNAPSHOT_DIR / f"channel-{int(channel_id)}.jpg" + + +def ensure_channel_snapshot(channel: dict[str, Any], *, force: bool = False) -> Path | None: + """Return a cached still frame for a live channel, creating it on demand. + + Snapshot generation is deliberately concurrency-limited so opening the IPTV + grid cannot launch dozens of FFmpeg processes at once. + """ + try: + channel_id = int(channel["id"]) + except Exception: + return None + + destination = channel_snapshot_path(channel_id) + ttl_seconds = IPTV_SNAPSHOT_TTL_MINUTES * 60 + + if not force and destination.is_file(): + try: + if time.time() - destination.stat().st_mtime < ttl_seconds: + return destination + except OSError: + pass + + with _SNAPSHOT_SEMAPHORE: + # Another request may have generated it while this request waited. + if not force and destination.is_file(): + try: + if time.time() - destination.stat().st_mtime < ttl_seconds: + return destination + except OSError: + pass + + temporary = destination.with_suffix('.part.jpg') + temporary.unlink(missing_ok=True) + + command = [ + FFMPEG_BIN, + '-nostdin', + '-hide_banner', + '-loglevel', 'error', + '-rw_timeout', '10000000', + '-reconnect', '1', + '-reconnect_streamed', '1', + '-reconnect_delay_max', '3', + ] + headers = _header_string(channel) + if headers: + command.extend(['-headers', headers]) + validate_iptv_url(channel['stream_url']) + command.extend([ + '-i', channel['stream_url'], + '-map', '0:v:0?', + '-an', '-sn', '-dn', + '-frames:v', '1', + '-vf', f"scale='min({IPTV_SNAPSHOT_WIDTH},iw)':-2", + '-q:v', '4', + '-y', str(temporary), + ]) + + try: + result = subprocess.run( + command, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + timeout=IPTV_SNAPSHOT_TIMEOUT, + ) + if result.returncode != 0 or not temporary.is_file() or temporary.stat().st_size < 512: + temporary.unlink(missing_ok=True) + return destination if destination.is_file() else None + temporary.replace(destination) + return destination + except Exception: + temporary.unlink(missing_ok=True) + return destination if destination.is_file() else None + + +def probe_channel(channel: dict[str, Any]) -> dict[str, str]: + command = [ + FFPROBE_BIN, + "-v", "error", + "-analyzeduration", "3000000", + "-probesize", "3000000", + ] + headers = _header_string(channel) + if headers: + command.extend(["-headers", headers]) + validate_iptv_url(channel["stream_url"]) + command.extend([ + "-show_entries", "stream=codec_type,codec_name", + "-of", "json", + channel["stream_url"], + ]) + try: + result = subprocess.run( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=IPTV_PROBE_TIMEOUT, + check=True, + ) + payload = json.loads(result.stdout or "{}") + streams = payload.get("streams") or [] + video = next((x for x in streams if x.get("codec_type") == "video"), {}) + audio = next((x for x in streams if x.get("codec_type") == "audio"), {}) + return { + "video_codec": str(video.get("codec_name") or "").lower(), + "audio_codec": str(audio.get("codec_name") or "").lower(), + } + except Exception: + return {"video_codec": "", "audio_codec": ""} + + +def iptv_ffmpeg_command(channel: dict[str, Any]) -> tuple[list[str], dict[str, str]]: + probe = probe_channel(channel) + vcodec = probe["video_codec"] + acodec = probe["audio_codec"] + + mode = IPTV_TRANSCODE_MODE if IPTV_TRANSCODE_MODE in {"auto", "always", "copy"} else "auto" + if mode == "always": + copy_video = False + elif mode == "copy": + copy_video = True + else: + copy_video = vcodec in {"h264", "avc1"} + + # Live HLS/MPEG-TS commonly carries AAC in ADTS framing. MP4 requires + # AudioSpecificConfig instead, and some feeds cause FFmpeg's MP4 muxer to + # abort when AAC is copied verbatim. Normalizing audio to fresh AAC is + # inexpensive compared with video transcoding and also cleans timestamps. + # + # Set IPTV_AUDIO_MODE=copy if you explicitly want stream-copy audio. + copy_audio = ( + IPTV_AUDIO_MODE == "copy" + and acodec in {"aac", "mp3"} + ) + + command = [ + FFMPEG_BIN, + "-nostdin", + "-hide_banner", + "-loglevel", "warning", + "-fflags", "+genpts+discardcorrupt", + "-rw_timeout", "15000000", + "-reconnect", "1", + "-reconnect_streamed", "1", + "-reconnect_delay_max", "5", + ] + headers = _header_string(channel) + if headers: + command.extend(["-headers", headers]) + validate_iptv_url(channel["stream_url"]) + command.extend([ + "-i", channel["stream_url"], + "-map", "0:v:0?", + "-map", "0:a:0?", + "-sn", "-dn", + ]) + + if copy_video: + command.extend(["-c:v", "copy"]) + else: + command.extend([ + "-c:v", "libx264", + "-preset", IPTV_X264_PRESET, + "-crf", IPTV_X264_CRF, + "-profile:v", "high", + "-level:v", "4.1", + "-pix_fmt", "yuv420p", + ]) + + if copy_audio: + command.extend(["-c:a", "copy"]) + if acodec == "aac": + command.extend([ + "-bsf:a", + "aac_adtstoasc", + ]) + else: + command.extend([ + "-c:a", "aac", + "-b:a", IPTV_AUDIO_BITRATE, + "-ar", "48000", + "-ac", str(IPTV_AUDIO_CHANNELS), + "-af", "aresample=async=1:first_pts=0", + ]) + + command.extend([ + "-avoid_negative_ts", "make_zero", + "-map_metadata", "-1", + "-map_chapters", "-1", + "-movflags", "+frag_keyframe+empty_moov+default_base_moof+omit_tfhd_offset", + "-frag_duration", "2000000", + "-min_frag_duration", "1000000", + "-video_track_timescale", "90000", + "-max_interleave_delta", "0", + "-flush_packets", "1", + "-f", "mp4", + "pipe:1", + ]) + + probe["video_action"] = "copy" if copy_video else "h264" + probe["audio_action"] = ( + "copy+aac_adtstoasc" + if copy_audio and acodec == "aac" + else "copy" + if copy_audio + else "aac-normalize" + ) + return command, probe diff --git a/library_index.py b/library_index.py new file mode 100644 index 0000000..7e588db --- /dev/null +++ b/library_index.py @@ -0,0 +1,1146 @@ +import os +import shutil +import sqlite3 +import json +from datetime import datetime +from pathlib import Path +from dotenv import load_dotenv +from metadata_sidecar import apply_nfo_to_item, sidecar_signature + +BASE_DIR = Path(__file__).resolve().parent +load_dotenv(BASE_DIR / "config.env") +DB_PATH = Path(os.getenv("DB_PATH", BASE_DIR / "media_library.db")) + + +def get_db(): + conn = sqlite3.connect(DB_PATH) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + return conn + + +def column_exists(conn, table_name, column_name): + rows = conn.execute(f"PRAGMA table_info({table_name})").fetchall() + return any(row["name"] == column_name for row in rows) + + +def ensure_column(conn, table, column, definition): + if not column_exists(conn, table, column): + conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition}") + + +def init_db(): + conn = get_db() + c = conn.cursor() + + c.execute(""" + CREATE TABLE IF NOT EXISTS media_sources ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + path TEXT NOT NULL UNIQUE, + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL + ) + """) + ensure_column(conn, "media_sources", "library_type", "TEXT NOT NULL DEFAULT 'movies'") + ensure_column(conn, "media_sources", "artwork_preference", "TEXT NOT NULL DEFAULT 'jellyfin_first'") + + c.execute(""" + CREATE TABLE IF NOT EXISTS media_source_paths ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + source_id INTEGER NOT NULL, + path TEXT NOT NULL UNIQUE, + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + FOREIGN KEY(source_id) REFERENCES media_sources(id) ON DELETE CASCADE + ) + """) + + for source in c.execute("SELECT id, path FROM media_sources").fetchall(): + old_path = source["path"] + if not old_path: + continue + exists = c.execute("SELECT id FROM media_source_paths WHERE path = ?", (old_path,)).fetchone() + if not exists: + c.execute(""" + INSERT INTO media_source_paths (source_id, path, enabled, created_at) + VALUES (?, ?, 1, ?) + """, (source["id"], old_path, datetime.now().isoformat())) + + c.execute(""" + CREATE TABLE IF NOT EXISTS sorted_media ( + id INTEGER PRIMARY KEY, + original_path TEXT UNIQUE, + sorted_path TEXT, + relative_path TEXT, + type TEXT, + title TEXT, + season INTEGER, + episode INTEGER, + year INTEGER, + resolution TEXT, + updated_at TEXT + ) + """) + + for name, definition in [ + ("source_id", "INTEGER"), + ("current_path", "TEXT"), + ("source_path_id", "INTEGER"), + ("series_title", "TEXT"), + ("episode_title", "TEXT"), + ("duration_seconds", "REAL"), + ("added_at", "TEXT"), + ("title_override", "TEXT"), + ("series_title_override", "TEXT"), + ("episode_title_override", "TEXT"), + ("year_override", "INTEGER"), + ("season_override", "INTEGER"), + ("episode_override", "INTEGER"), + ("file_size", "INTEGER"), + ("file_mtime_ns", "INTEGER"), + ("video_codec", "TEXT"), + ("video_width", "INTEGER"), + ("video_height", "INTEGER"), + ("video_bitrate", "INTEGER"), + ("video_fps", "REAL"), + ("audio_tracks_json", "TEXT"), + ("probe_json", "TEXT"), + ("last_scanned_at", "TEXT"), + ("description", "TEXT"), + ("nfo_path", "TEXT"), + ("artwork_path", "TEXT"), + ("metadata_json", "TEXT"), + ("sidecar_mtime_ns", "INTEGER"), + ]: + ensure_column(conn, "sorted_media", name, definition) + + c.execute(""" + UPDATE sorted_media + SET current_path = CASE + WHEN sorted_path IS NOT NULL AND sorted_path != '' THEN sorted_path + ELSE original_path + END + WHERE current_path IS NULL OR current_path = '' + """) + + c.execute(""" + UPDATE sorted_media + SET added_at = COALESCE(NULLIF(added_at, ''), updated_at, ?) + WHERE added_at IS NULL OR added_at = '' + """, (datetime.now().isoformat(),)) + + c.execute(""" + CREATE TABLE IF NOT EXISTS playback_progress ( + media_id INTEGER PRIMARY KEY, + position_seconds REAL NOT NULL DEFAULT 0, + duration_seconds REAL, + completed INTEGER NOT NULL DEFAULT 0, + updated_at TEXT NOT NULL, + FOREIGN KEY(media_id) REFERENCES sorted_media(id) ON DELETE CASCADE + ) + """) + + c.execute(""" + CREATE TABLE IF NOT EXISTS transcoded_media ( + id INTEGER PRIMARY KEY, + source_path TEXT UNIQUE, + output_path TEXT, + codec_video TEXT, + codec_audio TEXT, + resolution TEXT, + transcoded_at TEXT + ) + """) + c.execute("CREATE TABLE IF NOT EXISTS app_settings (key TEXT PRIMARY KEY, value TEXT)") + # Existing installs used generated frames by default. Migrate once to the + # requested Jellyfin-first default, while honoring future manual overrides. + if not c.execute("SELECT 1 FROM app_settings WHERE key='jellyfin_default_migrated'").fetchone(): + c.execute("UPDATE media_sources SET artwork_preference='jellyfin_first' WHERE artwork_preference IS NULL OR artwork_preference='generated_first'") + c.execute("INSERT INTO app_settings(key,value) VALUES('jellyfin_default_migrated','1')") + + c.execute(""" + CREATE TABLE IF NOT EXISTS youtube_metadata ( + video_id TEXT PRIMARY KEY, + title TEXT NOT NULL, + channel_name TEXT, + channel_url TEXT, + fetched_at TEXT NOT NULL + ) + """) + + c.execute(""" + CREATE TABLE IF NOT EXISTS youtube_watch_history ( + video_id TEXT PRIMARY KEY, + title TEXT NOT NULL, + channel_name TEXT, + thumbnail_url TEXT, + duration_seconds REAL, + first_played_at TEXT NOT NULL, + last_played_at TEXT NOT NULL, + watch_count INTEGER NOT NULL DEFAULT 1 + ) + """) + + c.execute(""" + CREATE TABLE IF NOT EXISTS youtube_playback_progress ( + video_id TEXT PRIMARY KEY, + position_seconds REAL NOT NULL DEFAULT 0, + duration_seconds REAL, + completed INTEGER NOT NULL DEFAULT 0, + updated_at TEXT NOT NULL + ) + """) + + c.execute(""" + CREATE TABLE IF NOT EXISTS youtube_video_cache ( + video_id TEXT PRIMARY KEY, + title TEXT, + channel_name TEXT, + thumbnail_url TEXT, + duration_seconds REAL, + cache_path TEXT NOT NULL, + size_bytes INTEGER NOT NULL DEFAULT 0, + cached_at TEXT NOT NULL, + last_played_at TEXT NOT NULL + ) + """) + + conn.commit() + conn.close() + + +def add_effective_fields(item): + item = dict(item) + item["effective_title"] = item.get("title_override") if item.get("title_override") not in (None, "") else item.get("title") + item["effective_series_title"] = item.get("series_title_override") if item.get("series_title_override") not in (None, "") else item.get("series_title") + item["effective_episode_title"] = item.get("episode_title_override") if item.get("episode_title_override") not in (None, "") else item.get("episode_title") + item["effective_year"] = item.get("year_override") if item.get("year_override") is not None else item.get("year") + item["effective_season"] = item.get("season_override") if item.get("season_override") is not None else item.get("season") + item["effective_episode"] = item.get("episode_override") if item.get("episode_override") is not None else item.get("episode") + try: + item["audio_tracks"] = json.loads(item.get("audio_tracks_json") or "[]") + except Exception: + item["audio_tracks"] = [] + try: + item["probe"] = json.loads(item.get("probe_json") or "{}") + except Exception: + item["probe"] = {} + return item + + +def add_media_source(name, path, library_type="movies"): + source_path = Path(path).expanduser().resolve() + if not source_path.is_dir(): + raise ValueError(f"Directory does not exist: {source_path}") + name = (name or "").strip() + if not name: + raise ValueError("Library name cannot be empty") + library_type = (library_type or "movies").lower().strip() + if library_type not in {"movies", "shows"}: + raise ValueError("Library type must be movies or shows") + conn = get_db() + try: + cur = conn.execute(""" + INSERT INTO media_sources (name, path, library_type, enabled, created_at) + VALUES (?, ?, ?, 1, ?) + """, (name, str(source_path), library_type, datetime.now().isoformat())) + source_id = cur.lastrowid + conn.execute(""" + INSERT INTO media_source_paths (source_id, path, enabled, created_at) + VALUES (?, ?, 1, ?) + """, (source_id, str(source_path), datetime.now().isoformat())) + conn.commit() + return source_id + finally: + conn.close() + + +def get_media_sources(enabled_only=False): + conn = get_db() + try: + sql = "SELECT * FROM media_sources" + if enabled_only: + sql += " WHERE enabled = 1" + sql += " ORDER BY name COLLATE NOCASE" + rows = conn.execute(sql).fetchall() + out = [] + for row in rows: + source = dict(row) + paths = conn.execute("SELECT * FROM media_source_paths WHERE source_id = ? ORDER BY id", (source["id"],)).fetchall() + source["paths"] = [dict(p) for p in paths] + out.append(source) + return out + finally: + conn.close() + + +def set_media_source_artwork_preference(source_id, preference): + """Persist the thumbnail preference per library, without touching media.""" + allowed = {"generated_first", "jellyfin_first"} + if preference not in allowed: + raise ValueError("Invalid artwork preference") + conn = get_db() + try: + result = conn.execute( + "UPDATE media_sources SET artwork_preference=? WHERE id=?", + (preference, int(source_id)), + ) + if not result.rowcount: + raise ValueError("Library not found") + conn.commit() + finally: + conn.close() + + +def get_media_source(source_id): + conn = get_db() + try: + row = conn.execute("SELECT * FROM media_sources WHERE id = ?", (source_id,)).fetchone() + if not row: + return None + source = dict(row) + source["paths"] = [dict(p) for p in conn.execute("SELECT * FROM media_source_paths WHERE source_id = ? ORDER BY id", (source_id,)).fetchall()] + return source + finally: + conn.close() + + +def get_media_source_paths(source_id, enabled_only=False): + conn = get_db() + try: + sql = "SELECT * FROM media_source_paths WHERE source_id = ?" + params = [source_id] + if enabled_only: + sql += " AND enabled = 1" + sql += " ORDER BY id" + return [dict(r) for r in conn.execute(sql, params).fetchall()] + finally: + conn.close() + + +def add_media_source_path(source_id, path): + if not get_media_source(source_id): + raise ValueError("Library not found") + source_path = Path(path).expanduser().resolve() + if not source_path.is_dir(): + raise ValueError(f"Directory does not exist: {source_path}") + conn = get_db() + try: + cur = conn.execute(""" + INSERT INTO media_source_paths (source_id, path, enabled, created_at) + VALUES (?, ?, 1, ?) + """, (source_id, str(source_path), datetime.now().isoformat())) + conn.commit() + return cur.lastrowid + finally: + conn.close() + + +def remove_media_source_path(path_id): + conn = get_db() + try: + row = conn.execute("SELECT * FROM media_source_paths WHERE id = ?", (path_id,)).fetchone() + if not row: + raise ValueError("Library path not found") + count = conn.execute("SELECT COUNT(*) AS count FROM media_source_paths WHERE source_id = ?", (row["source_id"],)).fetchone()["count"] + if count <= 1: + raise ValueError("A library must have at least one folder. Remove the library itself instead.") + conn.execute("DELETE FROM media_source_paths WHERE id = ?", (path_id,)) + conn.commit() + finally: + conn.close() + + +def set_media_source_enabled(source_id, enabled): + conn = get_db() + try: + conn.execute("UPDATE media_sources SET enabled = ? WHERE id = ?", (1 if enabled else 0, source_id)) + conn.commit() + finally: + conn.close() + + +def set_media_source_type(source_id, library_type): + library_type = (library_type or "").lower().strip() + if library_type not in {"movies", "shows"}: + raise ValueError("Library type must be movies or shows") + conn = get_db() + try: + conn.execute("UPDATE media_sources SET library_type = ? WHERE id = ?", (library_type, source_id)) + conn.commit() + finally: + conn.close() + + +def remove_media_source(source_id): + conn = get_db() + try: + conn.execute("UPDATE sorted_media SET source_id = NULL, source_path_id = NULL WHERE source_id = ?", (source_id,)) + conn.execute("DELETE FROM media_source_paths WHERE source_id = ?", (source_id,)) + conn.execute("DELETE FROM media_sources WHERE id = ?", (source_id,)) + conn.commit() + finally: + conn.close() + + +def update_sorted_media(item): + current_path = Path(item.get("current_path") or item["original_path"]).resolve() + now = datetime.now().isoformat() + audio_tracks = item.get("audio_tracks") + if isinstance(audio_tracks, str): + audio_tracks_json = audio_tracks + else: + audio_tracks_json = json.dumps(audio_tracks or [], ensure_ascii=False, separators=(",", ":")) + probe = item.get("probe") + if isinstance(probe, str): + probe_json = probe + else: + probe_json = json.dumps(probe or {}, ensure_ascii=False, separators=(",", ":")) + + conn = get_db() + try: + conn.execute(""" + INSERT INTO sorted_media ( + original_path, sorted_path, current_path, relative_path, source_id, source_path_id, + type, title, series_title, episode_title, season, episode, year, resolution, + duration_seconds, file_size, file_mtime_ns, video_codec, video_width, video_height, + video_bitrate, video_fps, audio_tracks_json, probe_json, last_scanned_at, + added_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(original_path) DO UPDATE SET + current_path = excluded.current_path, + relative_path = excluded.relative_path, + source_id = excluded.source_id, + source_path_id = excluded.source_path_id, + type = excluded.type, + title = excluded.title, + series_title = excluded.series_title, + episode_title = excluded.episode_title, + season = excluded.season, + episode = excluded.episode, + year = excluded.year, + resolution = excluded.resolution, + duration_seconds = excluded.duration_seconds, + file_size = excluded.file_size, + file_mtime_ns = excluded.file_mtime_ns, + video_codec = excluded.video_codec, + video_width = excluded.video_width, + video_height = excluded.video_height, + video_bitrate = excluded.video_bitrate, + video_fps = excluded.video_fps, + audio_tracks_json = excluded.audio_tracks_json, + probe_json = excluded.probe_json, + last_scanned_at = excluded.last_scanned_at, + updated_at = excluded.updated_at + """, ( + item["original_path"], item.get("sorted_path"), str(current_path), item.get("relative_path"), + item.get("source_id"), item.get("source_path_id"), item.get("type"), item.get("title"), + item.get("series_title"), item.get("episode_title"), item.get("season"), item.get("episode"), + item.get("year"), item.get("resolution"), item.get("duration_seconds"), + item.get("file_size"), item.get("file_mtime_ns"), item.get("video_codec"), + item.get("video_width"), item.get("video_height"), item.get("video_bitrate"), + item.get("video_fps"), audio_tracks_json, probe_json, now, now, now, + )) + conn.execute( + """UPDATE sorted_media SET + description=?, + nfo_path=?, + artwork_path=?, + metadata_json=?, + sidecar_mtime_ns=? + WHERE original_path=?""", + ( + item.get("description") or "", + item.get("nfo_path") or "", + item.get("artwork_path") or "", + item.get("metadata_json") or "", + int(item.get("sidecar_mtime_ns") or 0), + item["original_path"], + ), + ) + conn.commit() + finally: + conn.close() + + +def apply_sidecar_to_item(item, path): + return apply_nfo_to_item(item, path) + + +def media_needs_probe(existing, path, deep=False): + if deep or not existing: + return True + try: + stat = Path(path).stat() + except OSError: + return False + if existing.get("file_size") is None or existing.get("file_mtime_ns") is None: + return True + if int(existing.get("file_size") or -1) != int(stat.st_size): + return True + if int(existing.get("file_mtime_ns") or -1) != int(stat.st_mtime_ns): + return True + # Populate new stream metadata on the first quick scan after upgrade. + if not existing.get("probe_json"): + return True + + # NFO/artwork changes should be picked up even when the media file itself + # did not change. + current_sidecar = int(sidecar_signature(path) or 0) + indexed_sidecar = int(existing.get("sidecar_mtime_ns") or 0) + if current_sidecar != indexed_sidecar: + return True + + return False + + +def touch_media_scan_state(media_id, *, source_id=None, source_path_id=None, relative_path=None, current_path=None): + conn = get_db() + try: + fields = ["last_scanned_at=?"] + values = [datetime.now().isoformat()] + for name, value in (("source_id", source_id), ("source_path_id", source_path_id), ("relative_path", relative_path), ("current_path", current_path)): + if value is not None: + fields.append(f"{name}=?") + values.append(value) + values.append(int(media_id)) + conn.execute(f"UPDATE sorted_media SET {', '.join(fields)} WHERE id=?", values) + conn.commit() + finally: + conn.close() + + +def _media_select_sql(): + return """ + SELECT sorted_media.*, media_sources.name AS source_name, + media_sources.library_type AS library_type, + media_source_paths.path AS physical_root + FROM sorted_media + LEFT JOIN media_sources ON sorted_media.source_id = media_sources.id + LEFT JOIN media_source_paths ON sorted_media.source_path_id = media_source_paths.id + """ + + +def get_sorted_media(source_id=None): + conn = get_db() + try: + sql = _media_select_sql() + params = [] + if source_id is not None: + sql += " WHERE sorted_media.source_id = ?" + params.append(source_id) + sql += " ORDER BY COALESCE(sorted_media.title_override, sorted_media.title) COLLATE NOCASE" + return [add_effective_fields(dict(r)) for r in conn.execute(sql, params).fetchall()] + finally: + conn.close() + + +def get_media_samples(source_id, limit=6): + try: + limit = max(1, min(12, int(limit))) + except (TypeError, ValueError): + limit = 6 + + conn = get_db() + try: + rows = conn.execute( + _media_select_sql() + + " WHERE sorted_media.source_id = ? ORDER BY RANDOM() LIMIT ?", + (int(source_id), limit), + ).fetchall() + return [add_effective_fields(dict(row)) for row in rows] + finally: + conn.close() + + +def get_media_by_id(media_id): + conn = get_db() + try: + row = conn.execute(_media_select_sql() + " WHERE sorted_media.id = ?", (media_id,)).fetchone() + return add_effective_fields(dict(row)) if row else None + finally: + conn.close() + + +def remove_media_index_by_current_path(path): + canonical = str(Path(path).resolve()) + conn = get_db() + try: + cur = conn.execute("DELETE FROM sorted_media WHERE current_path = ? OR original_path = ?", (canonical, canonical)) + conn.commit() + return cur.rowcount + finally: + conn.close() + + +def search_media(query, source_id=None, limit=500): + query = (query or "").strip() + if not query: + return [] + term = f"%{query}%" + conn = get_db() + try: + sql = _media_select_sql() + """ + WHERE ( + COALESCE(sorted_media.title_override, sorted_media.title, '') LIKE ? OR + COALESCE(sorted_media.series_title_override, sorted_media.series_title, '') LIKE ? OR + COALESCE(sorted_media.episode_title_override, sorted_media.episode_title, '') LIKE ? OR + COALESCE(sorted_media.relative_path, '') LIKE ? OR + CAST(COALESCE(sorted_media.year_override, sorted_media.year, '') AS TEXT) LIKE ? OR + COALESCE(media_sources.name, '') LIKE ? + ) + """ + params = [term] * 6 + if source_id is not None: + sql += " AND sorted_media.source_id = ?" + params.append(source_id) + sql += " ORDER BY COALESCE(sorted_media.title_override, sorted_media.title) COLLATE NOCASE LIMIT ?" + params.append(limit) + return [add_effective_fields(dict(r)) for r in conn.execute(sql, params).fetchall()] + finally: + conn.close() + + +def save_metadata_overrides(media_id, data): + conn = get_db() + try: + if not conn.execute("SELECT id FROM sorted_media WHERE id = ?", (media_id,)).fetchone(): + raise ValueError("Media not found") + conn.execute(""" + UPDATE sorted_media SET + title_override = ?, series_title_override = ?, episode_title_override = ?, + year_override = ?, season_override = ?, episode_override = ? + WHERE id = ? + """, ( + data.get("title") or None, + data.get("series_title") or None, + data.get("episode_title") or None, + data.get("year"), data.get("season"), data.get("episode"), media_id, + )) + conn.commit() + finally: + conn.close() + + +def reset_metadata_overrides(media_id): + conn = get_db() + try: + conn.execute(""" + UPDATE sorted_media SET + title_override = NULL, series_title_override = NULL, episode_title_override = NULL, + year_override = NULL, season_override = NULL, episode_override = NULL + WHERE id = ? + """, (media_id,)) + conn.commit() + finally: + conn.close() + + +def move_media(media_id, target_source_id, target_subfolder=None): + media = get_media_by_id(media_id) + target_source = get_media_source(target_source_id) + if not media: + raise ValueError("Media not found") + if not target_source: + raise ValueError("Destination library not found") + target_paths = [p for p in target_source["paths"] if p["enabled"]] + if not target_paths: + raise ValueError("Destination library has no enabled folders") + target_path_record = target_paths[0] + target_root = Path(target_path_record["path"]).resolve() + source_file = Path(media.get("current_path") or media["original_path"]).resolve() + if not source_file.is_file(): + raise FileNotFoundError(source_file) + destination_dir = target_root + if target_subfolder: + destination_dir = (target_root / target_subfolder).resolve() + try: + destination_dir.relative_to(target_root) + except ValueError: + raise ValueError("Destination escapes library root") + destination_dir.mkdir(parents=True, exist_ok=True) + destination_file = destination_dir / source_file.name + if destination_file.exists(): + raise FileExistsError(destination_file) + shutil.move(str(source_file), str(destination_file)) + relative_path = destination_file.relative_to(target_root) + conn = get_db() + try: + conn.execute(""" + UPDATE sorted_media SET current_path = ?, relative_path = ?, source_id = ?, source_path_id = ?, updated_at = ? + WHERE id = ? + """, (str(destination_file), str(relative_path), target_source_id, target_path_record["id"], datetime.now().isoformat(), media_id)) + conn.commit() + finally: + conn.close() + return {"media_id": media_id, "new_path": str(destination_file), "source_id": target_source_id, "source_path_id": target_path_record["id"]} + + +def get_playback_progress(media_id): + conn = get_db() + try: + row = conn.execute("SELECT * FROM playback_progress WHERE media_id = ?", (media_id,)).fetchone() + media = conn.execute("SELECT duration_seconds FROM sorted_media WHERE id = ?", (media_id,)).fetchone() + if not media: + return None + if not row: + return {"media_id": media_id, "position_seconds": 0.0, "duration_seconds": media["duration_seconds"], "completed": False, "updated_at": None} + result = dict(row) + if result.get("duration_seconds") is None: + result["duration_seconds"] = media["duration_seconds"] + result["completed"] = bool(result.get("completed")) + return result + finally: + conn.close() + + +def save_playback_progress(media_id, position_seconds, duration_seconds=None, completed=False): + position_seconds = max(0.0, float(position_seconds or 0)) + if duration_seconds is not None: + duration_seconds = max(0.0, float(duration_seconds)) + conn = get_db() + try: + if not conn.execute("SELECT id FROM sorted_media WHERE id = ?", (media_id,)).fetchone(): + raise ValueError("Media not found") + conn.execute(""" + INSERT INTO playback_progress (media_id, position_seconds, duration_seconds, completed, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(media_id) DO UPDATE SET + position_seconds = excluded.position_seconds, + duration_seconds = COALESCE(excluded.duration_seconds, playback_progress.duration_seconds), + completed = excluded.completed, + updated_at = excluded.updated_at + """, (media_id, position_seconds, duration_seconds, 1 if completed else 0, datetime.now().isoformat())) + conn.commit() + finally: + conn.close() + + +def reset_playback_progress(media_id): + conn = get_db() + try: + conn.execute("DELETE FROM playback_progress WHERE media_id = ?", (media_id,)) + conn.commit() + finally: + conn.close() + + +init_db() + +# ============================================================ +# YOUTUBE METADATA CACHE / APPLY HELPERS +# ============================================================ + +def get_youtube_metadata_cache(video_id): + conn = get_db() + try: + row = conn.execute( + "SELECT * FROM youtube_metadata WHERE video_id = ?", + (video_id,), + ).fetchone() + return dict(row) if row else None + finally: + conn.close() + + +def save_youtube_metadata_cache(video_id, title, channel_name=None, channel_url=None): + conn = get_db() + try: + conn.execute(""" + INSERT INTO youtube_metadata ( + video_id, + title, + channel_name, + channel_url, + fetched_at + ) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(video_id) DO UPDATE SET + title = excluded.title, + channel_name = excluded.channel_name, + channel_url = excluded.channel_url, + fetched_at = excluded.fetched_at + """, ( + video_id, + title, + channel_name, + channel_url, + datetime.now().isoformat(), + )) + conn.commit() + finally: + conn.close() + + +def set_media_title_override(media_id, title): + title = str(title or "").strip() + if not title: + raise ValueError("Title cannot be empty") + + conn = get_db() + try: + if not conn.execute( + "SELECT id FROM sorted_media WHERE id = ?", + (media_id,), + ).fetchone(): + raise ValueError("Media not found") + + conn.execute(""" + UPDATE sorted_media + SET title_override = ?, updated_at = ? + WHERE id = ? + """, ( + title, + datetime.now().isoformat(), + media_id, + )) + conn.commit() + finally: + conn.close() + + +def update_media_after_youtube_rename(media_id, title, new_path): + """Update DB after an explicit filesystem rename. original_path stays unchanged.""" + new_path = Path(new_path).resolve() + title = str(title or "").strip() + if not title: + raise ValueError("Title cannot be empty") + + conn = get_db() + try: + row = conn.execute(_media_select_sql() + " WHERE sorted_media.id = ?", (media_id,)).fetchone() + if not row: + raise ValueError("Media not found") + + media = dict(row) + relative_path = media.get("relative_path") + physical_root = media.get("physical_root") + + if physical_root: + try: + relative_path = str(new_path.relative_to(Path(physical_root).resolve())) + except ValueError: + pass + elif relative_path: + relative_path = str(Path(relative_path).with_name(new_path.name)) + + conn.execute(""" + UPDATE sorted_media + SET current_path = ?, relative_path = ?, title_override = ?, updated_at = ? + WHERE id = ? + """, ( + str(new_path), + relative_path, + title, + datetime.now().isoformat(), + media_id, + )) + conn.commit() + finally: + conn.close() + +# ============================================================ +# YOUTUBE WATCH HISTORY / PLAYBACK / VIDEO CACHE +# ============================================================ + +def record_youtube_watch( + video_id, + title, + channel_name=None, + thumbnail_url=None, + duration_seconds=None, +): + video_id = str(video_id or "").strip() + title = str(title or video_id).strip() or video_id + if not video_id: + raise ValueError("YouTube video ID is required") + + try: + duration_value = ( + float(duration_seconds) + if duration_seconds not in (None, "") + else None + ) + except (TypeError, ValueError): + duration_value = None + + now = datetime.now().isoformat() + conn = get_db() + try: + conn.execute(""" + INSERT INTO youtube_watch_history ( + video_id, + title, + channel_name, + thumbnail_url, + duration_seconds, + first_played_at, + last_played_at, + watch_count + ) + VALUES (?, ?, ?, ?, ?, ?, ?, 1) + ON CONFLICT(video_id) DO UPDATE SET + title = excluded.title, + channel_name = COALESCE(excluded.channel_name, youtube_watch_history.channel_name), + thumbnail_url = COALESCE(excluded.thumbnail_url, youtube_watch_history.thumbnail_url), + duration_seconds = COALESCE(excluded.duration_seconds, youtube_watch_history.duration_seconds), + last_played_at = excluded.last_played_at, + watch_count = youtube_watch_history.watch_count + 1 + """, ( + video_id, + title, + channel_name, + thumbnail_url, + duration_value, + now, + now, + )) + conn.commit() + finally: + conn.close() + + +def get_youtube_playback_progress(video_id): + video_id = str(video_id or "").strip() + conn = get_db() + try: + row = conn.execute( + "SELECT * FROM youtube_playback_progress WHERE video_id = ?", + (video_id,), + ).fetchone() + history = conn.execute( + "SELECT duration_seconds FROM youtube_watch_history WHERE video_id = ?", + (video_id,), + ).fetchone() + + if not row: + return { + "video_id": video_id, + "position_seconds": 0.0, + "duration_seconds": history["duration_seconds"] if history else None, + "completed": False, + "updated_at": None, + } + + result = dict(row) + if result.get("duration_seconds") is None and history: + result["duration_seconds"] = history["duration_seconds"] + result["completed"] = bool(result.get("completed")) + return result + finally: + conn.close() + + +def save_youtube_playback_progress( + video_id, + position_seconds, + duration_seconds=None, + completed=False, +): + video_id = str(video_id or "").strip() + if not video_id: + raise ValueError("YouTube video ID is required") + + position = max(0.0, float(position_seconds or 0)) + try: + duration = ( + max(0.0, float(duration_seconds)) + if duration_seconds not in (None, "") + else None + ) + except (TypeError, ValueError): + duration = None + + now = datetime.now().isoformat() + conn = get_db() + try: + conn.execute(""" + INSERT INTO youtube_playback_progress ( + video_id, + position_seconds, + duration_seconds, + completed, + updated_at + ) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(video_id) DO UPDATE SET + position_seconds = excluded.position_seconds, + duration_seconds = COALESCE(excluded.duration_seconds, youtube_playback_progress.duration_seconds), + completed = excluded.completed, + updated_at = excluded.updated_at + """, ( + video_id, + position, + duration, + 1 if completed else 0, + now, + )) + + if duration is not None: + conn.execute(""" + UPDATE youtube_watch_history + SET duration_seconds = COALESCE(duration_seconds, ?) + WHERE video_id = ? + """, (duration, video_id)) + + conn.commit() + finally: + conn.close() + + +def reset_youtube_playback_progress(video_id): + conn = get_db() + try: + conn.execute( + "DELETE FROM youtube_playback_progress WHERE video_id = ?", + (str(video_id),), + ) + conn.commit() + finally: + conn.close() + + +def get_youtube_video_cache(video_id): + conn = get_db() + try: + row = conn.execute( + "SELECT * FROM youtube_video_cache WHERE video_id = ?", + (str(video_id),), + ).fetchone() + return dict(row) if row else None + finally: + conn.close() + + +def save_youtube_video_cache( + video_id, + cache_path, + title=None, + channel_name=None, + thumbnail_url=None, + duration_seconds=None, + size_bytes=0, +): + now = datetime.now().isoformat() + try: + duration = ( + float(duration_seconds) + if duration_seconds not in (None, "") + else None + ) + except (TypeError, ValueError): + duration = None + + conn = get_db() + try: + conn.execute(""" + INSERT INTO youtube_video_cache ( + video_id, + title, + channel_name, + thumbnail_url, + duration_seconds, + cache_path, + size_bytes, + cached_at, + last_played_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(video_id) DO UPDATE SET + title = COALESCE(excluded.title, youtube_video_cache.title), + channel_name = COALESCE(excluded.channel_name, youtube_video_cache.channel_name), + thumbnail_url = COALESCE(excluded.thumbnail_url, youtube_video_cache.thumbnail_url), + duration_seconds = COALESCE(excluded.duration_seconds, youtube_video_cache.duration_seconds), + cache_path = excluded.cache_path, + size_bytes = excluded.size_bytes, + cached_at = excluded.cached_at, + last_played_at = excluded.last_played_at + """, ( + str(video_id), + title, + channel_name, + thumbnail_url, + duration, + str(cache_path), + int(size_bytes or 0), + now, + now, + )) + conn.commit() + finally: + conn.close() + + +def touch_youtube_video_cache(video_id): + conn = get_db() + try: + conn.execute( + "UPDATE youtube_video_cache SET last_played_at = ? WHERE video_id = ?", + (datetime.now().isoformat(), str(video_id)), + ) + conn.commit() + finally: + conn.close() + + +def list_youtube_video_cache(): + conn = get_db() + try: + return [dict(row) for row in conn.execute(""" + SELECT * FROM youtube_video_cache + ORDER BY last_played_at DESC, cached_at DESC + """).fetchall()] + finally: + conn.close() + + +def delete_youtube_video_cache_record(video_id): + conn = get_db() + try: + conn.execute( + "DELETE FROM youtube_video_cache WHERE video_id = ?", + (str(video_id),), + ) + conn.commit() + finally: + conn.close() + + +def get_youtube_history(limit=50): + limit = max(1, min(int(limit or 50), 500)) + conn = get_db() + try: + rows = conn.execute(""" + SELECT + h.video_id, + h.title, + h.channel_name, + h.thumbnail_url, + COALESCE(p.duration_seconds, h.duration_seconds) AS duration_seconds, + h.first_played_at, + h.last_played_at, + h.watch_count, + COALESCE(p.position_seconds, 0) AS position_seconds, + COALESCE(p.completed, 0) AS completed, + CASE WHEN c.video_id IS NULL THEN 0 ELSE 1 END AS cached, + c.size_bytes AS cache_size_bytes + FROM youtube_watch_history AS h + LEFT JOIN youtube_playback_progress AS p + ON h.video_id = p.video_id + LEFT JOIN youtube_video_cache AS c + ON h.video_id = c.video_id + ORDER BY h.last_played_at DESC + LIMIT ? + """, (limit,)).fetchall() + + results = [] + for row in rows: + item = dict(row) + item["completed"] = bool(item.get("completed")) + item["cached"] = bool(item.get("cached")) + results.append(item) + return results + finally: + conn.close() + diff --git a/metadata_sidecar.py b/metadata_sidecar.py new file mode 100644 index 0000000..c91a29d --- /dev/null +++ b/metadata_sidecar.py @@ -0,0 +1,477 @@ +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 "", + } diff --git a/recording_schedule.py b/recording_schedule.py new file mode 100644 index 0000000..f209df8 --- /dev/null +++ b/recording_schedule.py @@ -0,0 +1,135 @@ +"""Persistent scheduled recording queue shared by Twitch and YouTube. + +The worker uses the media application's SQLite database and runs even when +no browser is open. UTC timestamps avoid client/server timezone ambiguity. +""" +from __future__ import annotations + +import os +import sqlite3 +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + +DB_PATH = Path(os.getenv('DB_PATH', str(Path(__file__).resolve().parent / 'media_library.db'))).expanduser().resolve() +_LOCK = threading.Lock() +_THREAD = None +_STOP = threading.Event() + + +def _db(): + connection = sqlite3.connect(DB_PATH, timeout=30) + connection.row_factory = sqlite3.Row + return connection + + +def initialize(): + with _db() as db: + db.execute('''CREATE TABLE IF NOT EXISTS scheduled_recordings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + provider TEXT NOT NULL, + media_key TEXT NOT NULL, + title TEXT NOT NULL DEFAULT '', + start_at INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'scheduled', + message TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL + )''') + db.execute('CREATE INDEX IF NOT EXISTS idx_scheduled_recordings_due ON scheduled_recordings(status,start_at)') + db.commit() + + +def schedule(user_id, provider, media_key, start_at, title=''): + if provider not in {'twitch', 'youtube'}: + raise ValueError('Unsupported recording type') + key = str(media_key or '').strip() + if not key: + raise ValueError('Channel ID or video ID is required') + try: + start = datetime.fromisoformat(str(start_at).replace('Z', '+00:00')) + if start.tzinfo is None: + raise ValueError('Recording time must include a timezone') + timestamp = int(start.timestamp()) + except (TypeError, ValueError) as exc: + raise ValueError('Enter a valid date and time with timezone') from exc + now = int(time.time()) + if timestamp < now + 15 or timestamp > now + 366 * 86400: + raise ValueError('Scheduled time must be at least 15 seconds away and within one year') + if provider == 'twitch': + from twitch_jobs import get_channel + if get_channel(int(user_id), int(key)) is None: + raise ValueError('Twitch channel is unavailable to this account') + else: + import re + if not re.fullmatch(r'[A-Za-z0-9_-]{11}', key): + raise ValueError('YouTube recording requires a valid video ID') + with _db() as db: + cursor = db.execute('''INSERT INTO scheduled_recordings + (user_id,provider,media_key,title,start_at,created_at) VALUES (?,?,?,?,?,?)''', + (int(user_id), provider, key, str(title or '')[:300], timestamp, now)) + db.commit() + return {'id':cursor.lastrowid, 'status':'scheduled', 'start_at':timestamp} + + +def list_jobs(user_id): + with _db() as db: + return [dict(row) for row in db.execute('''SELECT * FROM scheduled_recordings + WHERE user_id=? ORDER BY start_at DESC LIMIT 80''', (int(user_id),))] + + +def cancel(user_id, job_id): + with _db() as db: + cursor = db.execute("UPDATE scheduled_recordings SET status='cancelled' WHERE id=? AND user_id=? AND status='scheduled'",(int(job_id),int(user_id))) + db.commit() + if not cursor.rowcount: + raise ValueError('No pending scheduled recording found') + return {'cancelled':True} + + +def _execute(job): + if job['provider'] == 'twitch': + from twitch_jobs import enqueue_recording + enqueue_recording(job['user_id'], int(job['media_key'])) + else: + from cache_jobs import enqueue_cache_job + enqueue_cache_job(user_id=job['user_id'], video_id=job['media_key'], mode='video', title=job['title']) + + +def _tick(): + now = int(time.time()) + with _LOCK: + with _db() as db: + due=[dict(row) for row in db.execute('''SELECT * FROM scheduled_recordings + WHERE status='scheduled' AND start_at<=? ORDER BY start_at LIMIT 15''',(now,))] + for job in due: + db.execute("UPDATE scheduled_recordings SET status='dispatching' WHERE id=? AND status='scheduled'", (job['id'],)) + db.commit() + for job in due: + try: + _execute(job) + status, message='started','Recording job dispatched' + except Exception as exc: + status, message='failed',str(exc)[:400] + with _db() as db: + db.execute('UPDATE scheduled_recordings SET status=?,message=? WHERE id=?', (status,message,job['id'])) + db.commit() + + +def start(): + global _THREAD + initialize() + with _db() as db: + # A service restart during dispatch leaves the state visible and retryable. + db.execute("UPDATE scheduled_recordings SET status='scheduled' WHERE status='dispatching'") + db.commit() + if _THREAD and _THREAD.is_alive(): + return + def worker(): + while not _STOP.is_set(): + try: _tick() + except Exception as exc: print('[SCHEDULE] Worker error:',exc,flush=True) + _STOP.wait(10) + _THREAD=threading.Thread(target=worker, daemon=True,name='kronic-recording-schedule') + _THREAD.start() diff --git a/twitch_stream.py b/twitch_stream.py new file mode 100644 index 0000000..e51b035 --- /dev/null +++ b/twitch_stream.py @@ -0,0 +1,489 @@ +from __future__ import annotations + +import json +import logging +import os +import re +import signal +import subprocess +import threading +import time +import xml.etree.ElementTree as ET +from dataclasses import dataclass +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") + +FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg") +FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe") + +TWITCH_RECORD_DIR = Path( + os.getenv("TWITCH_RECORD_DIR", "/blade-media/twitch-cache") +).expanduser().resolve() + +TWITCH_STREAM_TIMEOUT = max( + 5, + int(os.getenv("TWITCH_STREAM_TIMEOUT", "30")), +) + +TWITCH_SUPPORTED_CODECS = [ + item.strip().lower() + for item in os.getenv("TWITCH_SUPPORTED_CODECS", "h264").split(",") + if item.strip() +] + +logger = logging.getLogger("kronic.twitch") + + +class TwitchOffline(RuntimeError): + pass + + +class TwitchResolutionError(RuntimeError): + pass + + +@dataclass +class TwitchResolved: + url: str + channel: str + quality: str + stream: Any + available_qualities: list[str] + stream_id: str = "" + title: str = "" + author: str = "" + category: str = "" + + def as_dict(self): + return { + "url": self.url, + "channel": self.channel, + "quality": self.quality, + "available_qualities": list(self.available_qualities), + "stream_id": self.stream_id, + "title": self.title, + "author": self.author, + "category": self.category, + "live": True, + } + + +def normalize_twitch_url(value: str) -> tuple[str, str]: + value = str(value or "").strip() + if not value: + raise ValueError("Twitch channel or URL is required.") + + if re.fullmatch(r"[A-Za-z0-9_]{2,40}", value): + channel = value + return f"https://www.twitch.tv/{channel}", channel + + if not re.match(r"^https?://", value, re.I): + value = "https://" + value.lstrip("/") + + match = re.search( + r"(?:www\.)?twitch\.tv/([A-Za-z0-9_]{2,40})", + value, + re.I, + ) + if not match: + raise ValueError("Enter a Twitch channel name or twitch.tv channel URL.") + + channel = match.group(1) + return f"https://www.twitch.tv/{channel}", channel + + +def _new_session(): + try: + from streamlink import Streamlink + except ImportError as error: + raise RuntimeError( + "Streamlink is not installed in the Kronic virtualenv. " + "Run: pip install -r requirements-twitch.txt" + ) from error + + session = Streamlink() + session.set_option("stream-timeout", TWITCH_STREAM_TIMEOUT) + # Streamlink normally sits ~3 HLS segments behind live. Five segments + # adds ~67% headroom at the cost of additional live latency. + session.set_option("hls-live-edge", max(3, int(os.getenv("TWITCH_HLS_LIVE_EDGE", "5")))) + return session + + +def _plugin_options(): + options = {} + # Streamlink's Twitch plugin defaults to H.264. Explicitly keep Kronic's + # supported codec list conservative because browser playback is H.264/AAC. + if TWITCH_SUPPORTED_CODECS: + options["supported-codecs"] = ",".join(TWITCH_SUPPORTED_CODECS) + return options + + +def resolve_twitch( + value: str, + quality: str = "best", +) -> TwitchResolved: + url, channel = normalize_twitch_url(value) + session = _new_session() + + try: + plugin_name, plugin_class, resolved_url = session.resolve_url(url) + plugin = plugin_class( + session, + resolved_url, + options=_plugin_options(), + ) + streams = plugin.streams() + except Exception as error: + text = str(error) + if "No playable streams found" in text or "offline" in text.lower(): + raise TwitchOffline(f"{channel} is offline.") from error + raise TwitchResolutionError( + f"Streamlink could not resolve {channel}: {error}" + ) from error + + if not streams: + raise TwitchOffline(f"{channel} is offline.") + + available = [ + key for key in streams.keys() + if key not in {"best", "worst"} + ] + + requested = str(quality or "best").strip() + selected_name = requested if requested in streams else "best" + selected = streams.get(selected_name) + if selected is None: + # Streamlink normally exposes best/worst aliases, but be defensive. + selected_name, selected = next(iter(streams.items())) + + return TwitchResolved( + url=url, + channel=channel, + quality=selected_name, + stream=selected, + available_qualities=available, + stream_id=str(getattr(plugin, "id", "") or ""), + title=str(getattr(plugin, "title", "") or ""), + author=str(getattr(plugin, "author", "") or channel), + category=str(getattr(plugin, "category", "") or ""), + ) + + +def probe_twitch(value: str, quality: str = "best") -> dict: + try: + resolved = resolve_twitch(value, quality=quality) + except TwitchOffline: + url, channel = normalize_twitch_url(value) + return { + "url": url, + "channel": channel, + "live": False, + "available_qualities": [], + "quality": quality or "best", + "stream_id": "", + "title": "", + "author": channel, + "category": "", + } + return resolved.as_dict() + + +class TwitchFFmpegPipeline: + """Streamlink -> Python pipe -> FFmpeg. + + Streamlink owns Twitch/HLS specifics. FFmpeg owns browser-compatible + remuxing/transcoding. This works for HLSStream and MuxedHLSStream because + both expose Stream.open(). + """ + + def __init__( + self, + resolved: TwitchResolved, + *, + output_path: Path | None = None, + browser_output: bool = False, + ): + self.resolved = resolved + self.output_path = Path(output_path).resolve() if output_path else None + self.browser_output = bool(browser_output) + + self.source = None + self.process = None + self.pump_thread = None + self.stop_event = threading.Event() + self.stderr_chunks: list[bytes] = [] + self.stderr_thread = None + + def _ffmpeg_command(self): + command = [ + FFMPEG_BIN, + "-nostdin", + "-hide_banner", + "-loglevel", + "warning", + "-fflags", + "+genpts", + "-i", + "pipe:0", + "-map", + "0:v:0?", + "-map", + "0:a:0?", + "-c:v", + "copy", + "-c:a", + "aac", + "-b:a", + "192k", + "-ac", + "2", + ] + + if self.browser_output: + command.extend([ + "-movflags", + "frag_keyframe+empty_moov+default_base_moof", + "-f", + "mp4", + "pipe:1", + ]) + else: + command.extend([ + "-movflags", + "+faststart", + "-f", + "mp4", + "-y", + str(self.output_path), + ]) + + return command + + def start(self): + self.source = self.resolved.stream.open() + + self.process = subprocess.Popen( + self._ffmpeg_command(), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE if self.browser_output else subprocess.DEVNULL, + stderr=subprocess.PIPE, + bufsize=0, + ) + + def pump(): + try: + while not self.stop_event.is_set(): + chunk = self.source.read(256 * 1024) + if not chunk: + break + if not self.process or not self.process.stdin: + break + try: + self.process.stdin.write(chunk) + self.process.stdin.flush() + except (BrokenPipeError, OSError): + break + except Exception as error: + logger.debug("Twitch source pump ended: %s", error) + finally: + try: + if self.process and self.process.stdin: + self.process.stdin.close() + except Exception: + pass + + def collect_stderr(): + try: + if not self.process or not self.process.stderr: + return + while True: + chunk = self.process.stderr.read(8192) + if not chunk: + break + self.stderr_chunks.append(chunk) + total = sum(len(part) for part in self.stderr_chunks) + if total > 128 * 1024: + del self.stderr_chunks[:-8] + except Exception: + pass + + self.pump_thread = threading.Thread( + target=pump, + daemon=True, + name=f"twitch-pump-{self.resolved.channel}", + ) + self.stderr_thread = threading.Thread( + target=collect_stderr, + daemon=True, + name=f"twitch-ffmpeg-stderr-{self.resolved.channel}", + ) + self.pump_thread.start() + self.stderr_thread.start() + return self + + def stop(self, graceful=True): + self.stop_event.set() + + try: + if self.source is not None: + self.source.close() + except Exception: + pass + + if self.process is not None and self.process.poll() is None: + if graceful: + try: + self.process.send_signal(signal.SIGINT) + except Exception: + self.process.terminate() + else: + self.process.terminate() + + try: + self.process.wait(timeout=8 if graceful else 3) + except subprocess.TimeoutExpired: + self.process.kill() + try: + self.process.wait(timeout=2) + except Exception: + pass + + if self.pump_thread: + self.pump_thread.join(timeout=2) + if self.stderr_thread: + self.stderr_thread.join(timeout=1) + + def wait(self): + if not self.process: + return -1 + return self.process.wait() + + def stderr_text(self): + return b"".join(self.stderr_chunks).decode("utf-8", "replace") + + +def start_browser_pipeline(value: str, quality: str = "best"): + resolved = resolve_twitch(value, quality=quality) + pipeline = TwitchFFmpegPipeline( + resolved, + browser_output=True, + ).start() + return resolved, pipeline + + +def safe_recording_stem(resolved: TwitchResolved): + timestamp = time.strftime("%Y-%m-%d_%H-%M-%S") + title = resolved.title or resolved.channel + safe_title = re.sub(r"[^A-Za-z0-9._ -]+", "", title).strip() + safe_title = re.sub(r"\s+", " ", safe_title)[:100] or resolved.channel + return f"{resolved.channel} - {timestamp} - {safe_title}" + + +def write_twitch_nfo(path: Path, resolved: TwitchResolved): + root = ET.Element("movie") + + def add(tag, value): + if value in (None, ""): + return + child = ET.SubElement(root, tag) + child.text = str(value) + + add("title", resolved.title or f"{resolved.channel} Twitch Stream") + add("plot", f"Recorded live from Twitch channel {resolved.author or resolved.channel}.") + add("studio", resolved.author or resolved.channel) + add("genre", resolved.category) + add("source", "twitch") + add("webpage", resolved.url) + add("recorded", time.strftime("%Y-%m-%d %H:%M:%S")) + + if resolved.stream_id: + uid = ET.SubElement( + root, + "uniqueid", + {"type": "twitch", "default": "true"}, + ) + uid.text = resolved.stream_id + + tree = ET.ElementTree(root) + try: + ET.indent(tree, space=" ") + except AttributeError: + pass + tree.write( + path.with_suffix(".nfo"), + encoding="utf-8", + xml_declaration=True, + ) + + +def record_twitch( + value: str, + quality: str = "best", + *, + stop_check=None, + progress_callback=None, +): + TWITCH_RECORD_DIR.mkdir(parents=True, exist_ok=True) + resolved = resolve_twitch(value, quality=quality) + + final_path = TWITCH_RECORD_DIR / f"{safe_recording_stem(resolved)}.mp4" + part_path = final_path.with_suffix(".part.mp4") + + pipeline = TwitchFFmpegPipeline( + resolved, + output_path=part_path, + browser_output=False, + ).start() + + started = time.monotonic() + try: + while pipeline.process and pipeline.process.poll() is None: + if stop_check and stop_check(): + pipeline.stop(graceful=True) + break + + elapsed = max(0, int(time.monotonic() - started)) + hours, rem = divmod(elapsed, 3600) + minutes, seconds = divmod(rem, 60) + if progress_callback: + progress_callback( + f"recording live ยท {hours:02d}:{minutes:02d}:{seconds:02d}" + ) + time.sleep(1) + + returncode = pipeline.process.returncode if pipeline.process else -1 + finally: + if pipeline.process and pipeline.process.poll() is None: + pipeline.stop(graceful=True) + else: + pipeline.stop_event.set() + try: + if pipeline.source is not None: + pipeline.source.close() + except Exception: + pass + + if part_path.is_file() and part_path.stat().st_size > 0: + os.replace(part_path, final_path) + try: + write_twitch_nfo(final_path, resolved) + except Exception as error: + logger.warning("Could not write Twitch NFO: %s", error) + + return { + **resolved.as_dict(), + "output_path": str(final_path), + "size_bytes": final_path.stat().st_size, + "returncode": returncode, + } + + error = pipeline.stderr_text()[-4000:] + raise RuntimeError( + f"Twitch recording produced no playable file. " + f"FFmpeg return code {returncode}. {error}" + )