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()