diff --git a/mediainfo.py b/mediainfo.py
new file mode 100644
index 0000000..baae5a3
--- /dev/null
+++ b/mediainfo.py
@@ -0,0 +1,283 @@
+import os
+import re
+import unicodedata
+from pathlib import Path
+
+from dotenv import load_dotenv
+from guessit import guessit
+from pymediainfo import MediaInfo
+
+BASE_DIR = Path(__file__).resolve().parent
+load_dotenv(BASE_DIR / "config.env")
+MIN_MEDIA_DURATION = float(os.getenv("MIN_MEDIA_DURATION", "30"))
+
+VIDEO_EXTENSIONS = {
+ ".mkv", ".mp4", ".m4v", ".avi", ".mov", ".webm",
+ ".mpg", ".mpeg", ".ts", ".m2ts", ".wmv",
+}
+
+NOISE_TOKENS = {
+ "480p", "576p", "720p", "1080p", "1080i", "1440p", "2160p", "4k", "8k",
+ "bluray", "blu-ray", "bdrip", "brrip", "web", "webdl", "web-dl", "webrip", "web-rip",
+ "hdtv", "dvdrip", "remux", "x264", "x265", "h264", "h265", "hevc", "avc", "av1",
+ "aac", "aac2", "ac3", "eac3", "ddp", "ddp5", "ddp51", "truehd", "atmos", "dts", "dtshd",
+ "proper", "repack", "internal", "hdr", "hdr10", "hdr10plus", "dolbyvision", "dv",
+}
+
+KNOWN_PREFIXES = ("wanshow", "wan show")
+
+ACRONYMS = {
+ "ai": "AI", "amd": "AMD", "arc": "Arc", "cpu": "CPU", "cpus": "CPUs",
+ "ddr4": "DDR4", "ddr5": "DDR5", "gpu": "GPU", "gpus": "GPUs", "hdr": "HDR",
+ "intel": "Intel", "linux": "Linux", "mac": "Mac", "nvidia": "NVIDIA", "oled": "OLED",
+ "pc": "PC", "pcs": "PCs", "ram": "RAM", "ssd": "SSD", "usb": "USB", "vr": "VR",
+ "wan": "WAN", "wifi": "WiFi",
+}
+
+SMALL_WORDS = {
+ "a", "an", "and", "as", "at", "but", "by", "for", "from", "in", "into", "of", "on",
+ "or", "the", "to", "vs", "with",
+}
+
+
+def normalize_number(value):
+ if value is None:
+ return None
+ if isinstance(value, (list, tuple)):
+ if not value:
+ return None
+ value = value[0]
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def looks_like_random_id(token):
+ token = str(token).strip()
+ if len(token) < 8 or len(token) > 20 or " " in token:
+ return False
+ letters = [c for c in token if c.isalpha()]
+ has_upper = any(c.isupper() for c in letters)
+ has_lower = any(c.islower() for c in letters)
+ has_digit = any(c.isdigit() for c in token)
+ has_separator = "-" in token or "_" in token
+ return has_digit and ((has_upper and has_lower) or has_separator)
+
+
+def smart_title_case(text):
+ words = text.split()
+ output = []
+ for index, word in enumerate(words):
+ stripped = word.strip()
+ if not stripped:
+ continue
+ lower = stripped.lower()
+ if lower in ACRONYMS:
+ output.append(ACRONYMS[lower])
+ continue
+ if index > 0 and lower in SMALL_WORDS:
+ output.append(lower)
+ continue
+ if any(c.isupper() for c in stripped[1:]) and any(c.islower() for c in stripped):
+ output.append(stripped)
+ continue
+ if any(c.isdigit() for c in stripped):
+ output.append(stripped if stripped.isupper() else stripped[:1].upper() + stripped[1:])
+ continue
+ output.append(stripped[:1].upper() + stripped[1:].lower())
+ return " ".join(output)
+
+
+def remove_known_prefixes(text):
+ cleaned = text.strip()
+ lowered = cleaned.lower()
+ for prefix in KNOWN_PREFIXES:
+ if lowered == prefix:
+ return ""
+ for sep in (" ", "-", "_"):
+ if lowered.startswith(prefix + sep):
+ return cleaned[len(prefix) + 1:].strip()
+ return cleaned
+
+
+def remove_trailing_random_id(text):
+ parts = text.split()
+ if parts and looks_like_random_id(parts[-1]):
+ parts.pop()
+ return " ".join(parts)
+
+
+def remove_noise_tokens(text):
+ output = []
+ for token in text.split():
+ normalized = token.lower().strip("[](){}.,")
+ if normalized in NOISE_TOKENS:
+ continue
+ output.append(token)
+ return " ".join(output)
+
+
+def clean_title(value):
+ if value is None:
+ return None
+ text = unicodedata.normalize("NFKC", str(value)).strip()
+ if not text:
+ return None
+ suffix = Path(text).suffix.lower()
+ if suffix in VIDEO_EXTENSIONS:
+ text = Path(text).stem
+ text = re.sub(r"[._]+", " ", text)
+ text = re.sub(r"\s*-\s*", " ", text)
+ text = remove_known_prefixes(text)
+ text = remove_trailing_random_id(text)
+ text = remove_noise_tokens(text)
+ text = re.sub(r"\[[^\]]+\]", " ", text)
+ text = re.sub(r"\{[^}]+\}", " ", text)
+ text = re.sub(r"\s+", " ", text).strip(" -_.")
+ return smart_title_case(text) if text else None
+
+
+MOVIE_FOLDER_PATTERN = re.compile(r"^(?P
.+?)\s*\((?P\d{4})\)\s*$")
+
+
+def clean_parent_movie_folder(path):
+ parent_name = Path(path).parent.name.strip()
+ match = MOVIE_FOLDER_PATTERN.match(parent_name)
+ if not match:
+ return None, None
+ return clean_title(match.group("title")), normalize_number(match.group("year"))
+
+
+def list_media_files(root):
+ root = Path(root).resolve()
+ files = []
+ if not root.is_dir():
+ return files
+ for path in root.rglob("*"):
+ try:
+ if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS:
+ files.append(path)
+ except OSError:
+ continue
+ files.sort(key=lambda p: str(p).lower())
+ return files
+
+
+def extract_resolution(media_info):
+ for track in media_info.tracks:
+ if track.track_type != "Video":
+ continue
+ width = getattr(track, "width", None)
+ height = getattr(track, "height", None)
+ if width and height:
+ try:
+ return f"{int(width)}x{int(height)}"
+ except (TypeError, ValueError):
+ pass
+ return None
+
+
+def extract_duration_seconds(media_info):
+ for wanted in ("General", "Video"):
+ for track in media_info.tracks:
+ if track.track_type != wanted:
+ continue
+ duration = getattr(track, "duration", None)
+ if duration is None:
+ continue
+ try:
+ duration_ms = float(duration)
+ if duration_ms >= 0:
+ return duration_ms / 1000.0
+ except (TypeError, ValueError):
+ pass
+ return None
+
+
+def is_short_media(duration_seconds, minimum_duration=None):
+ if minimum_duration is None:
+ minimum_duration = MIN_MEDIA_DURATION
+ if duration_seconds is None:
+ return False
+ try:
+ return float(duration_seconds) < float(minimum_duration)
+ except (TypeError, ValueError):
+ return False
+
+
+def inspect_media_file(path):
+ path = Path(path).resolve()
+ guessed = guessit(path.name)
+ media_info = MediaInfo.parse(str(path))
+
+ resolution = extract_resolution(media_info)
+ duration_seconds = extract_duration_seconds(media_info)
+ short_media = is_short_media(duration_seconds)
+
+ guessed_type = guessed.get("type")
+ season = normalize_number(guessed.get("season"))
+ episode = normalize_number(guessed.get("episode"))
+ guessed_year = normalize_number(guessed.get("year"))
+ guessed_title = clean_title(guessed.get("title"))
+ episode_title = clean_title(guessed.get("episode_title"))
+ filename_title = clean_title(path.stem)
+ parent_title, parent_year = clean_parent_movie_folder(path)
+
+ media_type = "episode" if guessed_type == "episode" or season is not None or episode is not None else "movie"
+ series_title = guessed_title if media_type == "episode" else None
+
+ if media_type == "movie":
+ title = parent_title or guessed_title or filename_title or path.stem
+ year = parent_year or guessed_year
+ else:
+ title = series_title or guessed_title or filename_title or path.stem
+ year = guessed_year
+
+ return {
+ "original_path": str(path),
+ "type": media_type,
+ "title": title,
+ "series_title": series_title,
+ "episode_title": episode_title,
+ "season": season,
+ "episode": episode,
+ "year": year,
+ "resolution": resolution,
+ "duration_seconds": duration_seconds,
+ "is_short_media": short_media,
+ }
+
+
+def get_full_mediainfo(path):
+ path = Path(path).resolve()
+ if not path.is_file():
+ raise FileNotFoundError(path)
+ media_info = MediaInfo.parse(str(path))
+ guessed = guessit(path.name)
+ normalized = inspect_media_file(path)
+ try:
+ media_info_data = media_info.to_data()
+ except Exception:
+ media_info_data = {"tracks": [track.to_data() for track in media_info.tracks]}
+ return {
+ "file": path.name,
+ "guessit": dict(guessed),
+ "normalized": normalized,
+ "mediainfo": media_info_data,
+ }
+
+
+def scan_media(root):
+ results = []
+ for path in list_media_files(root):
+ try:
+ item = inspect_media_file(path)
+ if item.get("is_short_media"):
+ duration = item.get("duration_seconds") or 0
+ print(f"[MEDIAINFO] Skipping short media ({duration:.1f}s): {path}")
+ continue
+ results.append(item)
+ except Exception as exc:
+ print(f"[MEDIAINFO] {path}: {exc}")
+ return results
diff --git a/music.py b/music.py
new file mode 100644
index 0000000..f842248
--- /dev/null
+++ b/music.py
@@ -0,0 +1,1040 @@
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+import time
+import re
+import subprocess
+import threading
+from pathlib import Path
+from urllib.error import HTTPError, URLError
+from urllib.request import Request, urlopen
+from metadata_sidecar import write_audio_sidecar
+
+from dotenv import load_dotenv
+
+BASE_DIR = Path(__file__).resolve().parent
+load_dotenv(BASE_DIR / "config.env")
+DB_PATH = Path(os.getenv("DB_PATH", str(BASE_DIR / "media_library.db"))).expanduser().resolve()
+KRONIC_MUSIC_API_URL = os.getenv(
+ "KRONIC_MUSIC_API_URL",
+ "",
+).rstrip("/")
+
+KRONIC_RESOLVER_URL = os.getenv(
+ "KRONIC_RESOLVER_URL",
+ "http://127.0.0.1:3030",
+).rstrip("/")
+
+
+def _music_api_candidates() -> list[str]:
+ """
+ Prefer an explicitly configured music API, but always retain the embedded
+ resolver as a safe fallback. This protects upgrades from older configs
+ that pointed KRONIC_MUSIC_API_URL at the media server on :7060.
+ """
+ candidates = []
+
+ for value in (
+ KRONIC_MUSIC_API_URL,
+ KRONIC_RESOLVER_URL,
+ "http://127.0.0.1:3030",
+ ):
+ value = str(value or "").rstrip("/")
+ if value and value not in candidates:
+ candidates.append(value)
+
+ return candidates
+MUSIC_RESOLVE_TIMEOUT = max(30.0, float(os.getenv("MUSIC_RESOLVE_TIMEOUT", "900")))
+MUSIC_IMPORT_MAX_ITEMS = max(1, int(os.getenv("MUSIC_IMPORT_MAX_ITEMS", "500")))
+
+MUSIC_CACHE_DIR = Path(
+ os.getenv(
+ "MUSIC_CACHE_DIR",
+ os.path.join(os.getenv("YOUTUBE_CACHE_DIR", "/blade-media/youtube-cache"), "music"),
+ )
+).expanduser().resolve()
+FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe")
+MUSIC_RECONCILE_INTERVAL = max(15, int(os.getenv("MUSIC_RECONCILE_INTERVAL", "60")))
+MUSIC_SPOTIFY_MATCH_MIN_SCORE = max(
+ 0.0,
+ min(1.0, float(os.getenv("MUSIC_SPOTIFY_MATCH_MIN_SCORE", "0.72"))),
+)
+MUSIC_EXTENSIONS = {".m4a", ".mp3", ".aac", ".flac", ".ogg", ".opus", ".wav"}
+_RECONCILE_THREAD = None
+_RECONCILE_STOP = threading.Event()
+
+
+def _db():
+ db = sqlite3.connect(DB_PATH, timeout=30)
+ db.row_factory = sqlite3.Row
+ db.execute("PRAGMA foreign_keys=ON")
+ return db
+
+
+def init_music_db():
+ with _db() as db:
+ db.executescript("""
+ CREATE TABLE IF NOT EXISTS music_imports (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ source_url TEXT NOT NULL,
+ source_type TEXT NOT NULL DEFAULT 'spotify',
+ name TEXT NOT NULL DEFAULT '',
+ added_by_user_id INTEGER,
+ created_at INTEGER NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS music_tracks (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ import_id INTEGER REFERENCES music_imports(id) ON DELETE SET NULL,
+ spotify_id TEXT NOT NULL DEFAULT '',
+ spotify_url TEXT NOT NULL DEFAULT '',
+ title TEXT NOT NULL,
+ artist TEXT NOT NULL DEFAULT '',
+ artists_json TEXT NOT NULL DEFAULT '[]',
+ album TEXT NOT NULL DEFAULT '',
+ duration_seconds REAL,
+ cover_url TEXT NOT NULL DEFAULT '',
+ year INTEGER,
+ isrc TEXT NOT NULL DEFAULT '',
+ list_name TEXT NOT NULL DEFAULT '',
+ list_position INTEGER,
+ youtube_url TEXT NOT NULL DEFAULT '',
+ youtube_id TEXT NOT NULL,
+ local_path TEXT NOT NULL DEFAULT '',
+ source_kind TEXT NOT NULL DEFAULT 'spotify',
+ metadata_source TEXT NOT NULL DEFAULT '',
+ spotify_match_score REAL,
+ spotify_match_status TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_music_tracks_spotify_id
+ ON music_tracks(spotify_id) WHERE spotify_id<>'';
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_music_tracks_spotify_url
+ ON music_tracks(spotify_url) WHERE spotify_url<>'';
+ CREATE INDEX IF NOT EXISTS idx_music_tracks_title ON music_tracks(title);
+ CREATE INDEX IF NOT EXISTS idx_music_tracks_artist ON music_tracks(artist);
+ CREATE INDEX IF NOT EXISTS idx_music_tracks_list ON music_tracks(list_name, list_position);
+ """)
+ columns = {
+ row["name"]
+ for row in db.execute("PRAGMA table_info(music_tracks)").fetchall()
+ }
+ for name, ddl in (
+ ("local_path", "TEXT NOT NULL DEFAULT ''"),
+ ("source_kind", "TEXT NOT NULL DEFAULT 'spotify'"),
+ ("metadata_source", "TEXT NOT NULL DEFAULT ''"),
+ ("spotify_match_score", "REAL"),
+ ("spotify_match_status", "TEXT NOT NULL DEFAULT ''"),
+ ):
+ if name not in columns:
+ db.execute(f"ALTER TABLE music_tracks ADD COLUMN {name} {ddl}")
+
+ # Older builds allowed the same YouTube ID to exist more than once.
+ # Reconcile those rows before creating the unique index so startup
+ # cannot fail on an existing database.
+ duplicate_video_ids = db.execute(
+ """SELECT youtube_id
+ FROM music_tracks
+ WHERE youtube_id<>''
+ GROUP BY youtube_id
+ HAVING COUNT(*)>1"""
+ ).fetchall()
+
+ for duplicate in duplicate_video_ids:
+ video_id = duplicate["youtube_id"]
+ rows = db.execute(
+ """SELECT *
+ FROM music_tracks
+ WHERE youtube_id=?
+ ORDER BY
+ CASE WHEN local_path<>'' THEN 0 ELSE 1 END,
+ CASE WHEN spotify_id<>'' THEN 0 ELSE 1 END,
+ updated_at DESC,
+ id ASC""",
+ (video_id,),
+ ).fetchall()
+
+ if not rows:
+ continue
+
+ keeper = dict(rows[0])
+ keeper_id = int(keeper["id"])
+
+ def first_nonempty(field, default=""):
+ for row in rows:
+ value = row[field]
+ if value not in (None, "", "[]"):
+ return value
+ return default
+
+ merged_local_path = first_nonempty("local_path", "")
+ merged_spotify_id = first_nonempty("spotify_id", "")
+ merged_spotify_url = first_nonempty("spotify_url", "")
+ merged_title = first_nonempty("title", video_id)
+ merged_artist = first_nonempty("artist", "")
+ merged_artists_json = first_nonempty("artists_json", "[]")
+ merged_album = first_nonempty("album", "")
+ merged_duration = None
+ for row in rows:
+ if row["duration_seconds"] not in (None, 0, 0.0):
+ merged_duration = row["duration_seconds"]
+ break
+ merged_cover = first_nonempty("cover_url", "")
+ merged_year = None
+ for row in rows:
+ if row["year"] not in (None, ""):
+ merged_year = row["year"]
+ break
+ merged_isrc = first_nonempty("isrc", "")
+ merged_list_name = first_nonempty("list_name", "")
+ merged_list_position = None
+ for row in rows:
+ if row["list_position"] is not None:
+ merged_list_position = row["list_position"]
+ break
+ merged_youtube_url = first_nonempty("youtube_url", "")
+ merged_source_kind = first_nonempty("source_kind", "spotify")
+ merged_metadata_source = first_nonempty("metadata_source", "")
+ merged_match_status = first_nonempty("spotify_match_status", "")
+
+ merged_match_score = None
+ scores = [
+ row["spotify_match_score"]
+ for row in rows
+ if row["spotify_match_score"] is not None
+ ]
+ if scores:
+ merged_match_score = max(scores)
+
+ db.execute(
+ """UPDATE music_tracks SET
+ spotify_id=?,
+ spotify_url=?,
+ title=?,
+ artist=?,
+ artists_json=?,
+ album=?,
+ duration_seconds=?,
+ cover_url=?,
+ year=?,
+ isrc=?,
+ list_name=?,
+ list_position=?,
+ youtube_url=?,
+ local_path=?,
+ source_kind=?,
+ metadata_source=?,
+ spotify_match_score=?,
+ spotify_match_status=?,
+ updated_at=?
+ WHERE id=?""",
+ (
+ merged_spotify_id,
+ merged_spotify_url,
+ merged_title,
+ merged_artist,
+ merged_artists_json,
+ merged_album,
+ merged_duration,
+ merged_cover,
+ merged_year,
+ merged_isrc,
+ merged_list_name,
+ merged_list_position,
+ merged_youtube_url,
+ merged_local_path,
+ merged_source_kind,
+ merged_metadata_source,
+ merged_match_score,
+ merged_match_status,
+ int(time.time()),
+ keeper_id,
+ ),
+ )
+
+ duplicate_ids = [
+ int(row["id"])
+ for row in rows[1:]
+ ]
+ if duplicate_ids:
+ placeholders = ",".join("?" for _ in duplicate_ids)
+ db.execute(
+ f"DELETE FROM music_tracks WHERE id IN ({placeholders})",
+ duplicate_ids,
+ )
+
+ print(
+ "[MUSIC] merged duplicate youtube_id",
+ {
+ "youtube_id": video_id,
+ "kept_id": keeper_id,
+ "removed": len(duplicate_ids),
+ },
+ flush=True,
+ )
+
+ # Do the same for duplicate local paths before creating that index.
+ duplicate_paths = db.execute(
+ """SELECT local_path
+ FROM music_tracks
+ WHERE local_path<>''
+ GROUP BY local_path
+ HAVING COUNT(*)>1"""
+ ).fetchall()
+
+ for duplicate in duplicate_paths:
+ local_path = duplicate["local_path"]
+ rows = db.execute(
+ """SELECT id
+ FROM music_tracks
+ WHERE local_path=?
+ ORDER BY updated_at DESC, id ASC""",
+ (local_path,),
+ ).fetchall()
+
+ if len(rows) <= 1:
+ continue
+
+ keeper_id = int(rows[0]["id"])
+ duplicate_ids = [int(row["id"]) for row in rows[1:]]
+
+ placeholders = ",".join("?" for _ in duplicate_ids)
+ db.execute(
+ f"DELETE FROM music_tracks WHERE id IN ({placeholders})",
+ duplicate_ids,
+ )
+
+ print(
+ "[MUSIC] merged duplicate local_path",
+ {
+ "local_path": local_path,
+ "kept_id": keeper_id,
+ "removed": len(duplicate_ids),
+ },
+ flush=True,
+ )
+
+ db.execute(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_music_tracks_youtube_id "
+ "ON music_tracks(youtube_id) WHERE youtube_id<>''"
+ )
+ db.execute(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_music_tracks_local_path "
+ "ON music_tracks(local_path) WHERE local_path<>''"
+ )
+ db.commit()
+
+
+def _post_json(url: str, data: dict) -> dict:
+ request = Request(
+ url,
+ data=json.dumps(data).encode("utf-8"),
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ try:
+ with urlopen(request, timeout=MUSIC_RESOLVE_TIMEOUT) as response:
+ return json.loads(response.read().decode("utf-8", "replace"))
+ except HTTPError as error:
+ body = error.read().decode("utf-8", "replace") if error.fp else ""
+ raise RuntimeError(f"Music resolver HTTP {error.code}: {body[:1500]}") from error
+ except URLError as error:
+ raise RuntimeError(f"Music resolver unavailable: {error}") from error
+
+
+def resolve_spotify(query: str, limit: int | None = None) -> dict:
+ payload = {
+ "url": query,
+ "limit": int(limit or MUSIC_IMPORT_MAX_ITEMS),
+ }
+
+ errors = []
+
+ for base_url in _music_api_candidates():
+ try:
+ return _post_json(
+ f"{base_url}/api/music/spotify/resolve",
+ payload,
+ )
+ except RuntimeError as error:
+ message = str(error)
+ errors.append(f"{base_url}: {message}")
+
+ # A 404 normally means an old config is pointing at the Media
+ # Server (:7060) instead of the embedded resolver (:3030).
+ # Try the next known resolver endpoint automatically.
+ if "HTTP 404" in message:
+ continue
+
+ # Connection failures on a configured alias may also be recovered
+ # by the local embedded resolver.
+ if "resolver unavailable" in message.lower():
+ continue
+
+ raise
+
+ raise RuntimeError(
+ "No Kronic music resolver endpoint accepted the request. "
+ + " | ".join(errors)
+ )
+
+
+
+def resolve_spotify_track_metadata(spotify_url: str) -> dict:
+ payload = {"url": str(spotify_url or "").strip()}
+ if not payload["url"]:
+ raise ValueError("spotify_url is required")
+
+ errors = []
+ for base_url in _music_api_candidates():
+ try:
+ return _post_json(
+ f"{base_url}/api/music/spotify/track-metadata",
+ payload,
+ )
+ except RuntimeError as error:
+ message = str(error)
+ errors.append(f"{base_url}: {message}")
+ if "HTTP 404" in message or "resolver unavailable" in message.lower():
+ continue
+ raise
+
+ raise RuntimeError(
+ "No Spotify exact-metadata endpoint accepted the request. "
+ + " | ".join(errors)
+ )
+
+
+def resolve_spotify_metadata(
+ title: str,
+ artist: str = "",
+ duration: float | None = None,
+) -> dict:
+ payload = {
+ "title": str(title or "").strip(),
+ "artist": str(artist or "").strip(),
+ "duration": duration,
+ "limit": 8,
+ }
+
+ errors = []
+ for base_url in _music_api_candidates():
+ try:
+ return _post_json(
+ f"{base_url}/api/music/spotify/metadata",
+ payload,
+ )
+ except RuntimeError as error:
+ message = str(error)
+ errors.append(f"{base_url}: {message}")
+ if "HTTP 404" in message or "resolver unavailable" in message.lower():
+ continue
+ raise
+
+ raise RuntimeError(
+ "No Spotify metadata endpoint accepted the request. "
+ + " | ".join(errors)
+ )
+
+
+def _get_json(url: str, timeout: float = 60.0) -> dict:
+ try:
+ with urlopen(url, timeout=timeout) as response:
+ return json.loads(response.read().decode("utf-8", "replace"))
+ except Exception:
+ return {}
+
+
+def _probe_audio_file(path: Path) -> dict:
+ command = [
+ FFPROBE_BIN,
+ "-v", "error",
+ "-show_entries",
+ "format=duration:format_tags=title,artist,album,album_artist,date",
+ "-of", "json",
+ str(path),
+ ]
+ try:
+ result = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ timeout=20,
+ check=False,
+ )
+ if result.returncode != 0:
+ return {}
+ payload = json.loads(result.stdout or "{}")
+ except Exception:
+ return {}
+
+ fmt = payload.get("format") or {}
+ tags = fmt.get("tags") or {}
+ try:
+ duration = float(fmt.get("duration") or 0) or None
+ except (TypeError, ValueError):
+ duration = None
+
+ return {
+ "title": tags.get("title") or "",
+ "artist": tags.get("artist") or tags.get("album_artist") or "",
+ "album": tags.get("album") or "",
+ "year": tags.get("date") or "",
+ "duration": duration,
+ }
+
+
+def _youtube_id_from_path(path: Path) -> str:
+ stem = path.stem
+ return stem if re.fullmatch(r"[A-Za-z0-9_-]{11}", stem) else ""
+
+
+def _youtube_metadata(video_id: str) -> dict:
+ if not video_id:
+ return {}
+ base = KRONIC_RESOLVER_URL or "http://127.0.0.1:3030"
+ return _get_json(
+ f"{base}/api/video/{video_id}",
+ timeout=60,
+ )
+
+
+def _cover_from_youtube_info(info: dict) -> str:
+ cover = str(info.get("thumbnail") or "")
+ if cover:
+ return cover
+ thumbs = info.get("thumbnails") or []
+ if thumbs and isinstance(thumbs[-1], dict):
+ return str(thumbs[-1].get("url") or "")
+ return ""
+
+
+def get_track(track_id: int) -> dict | None:
+ with _db() as db:
+ row = db.execute(
+ "SELECT * FROM music_tracks WHERE id=?",
+ (int(track_id),),
+ ).fetchone()
+ if not row:
+ return None
+ item = dict(row)
+ try:
+ item["artists"] = json.loads(item.pop("artists_json") or "[]")
+ except Exception:
+ item["artists"] = []
+ return item
+
+
+def _upsert_cached_track(
+ *,
+ local_path: Path,
+ youtube_id: str = "",
+ title: str = "",
+ artist: str = "",
+ album: str = "",
+ cover_url: str = "",
+ duration: float | None = None,
+ source_kind: str = "local",
+) -> int:
+ local_path = local_path.expanduser().resolve()
+ now = int(time.time())
+
+ with _db() as db:
+ row = db.execute(
+ "SELECT id FROM music_tracks WHERE local_path=?",
+ (str(local_path),),
+ ).fetchone()
+
+ if row is None and youtube_id:
+ row = db.execute(
+ "SELECT id FROM music_tracks WHERE youtube_id=?",
+ (youtube_id,),
+ ).fetchone()
+
+ if row:
+ track_id = int(row["id"])
+ db.execute(
+ """UPDATE music_tracks SET
+ youtube_id=CASE WHEN ?<>'' THEN ? ELSE youtube_id END,
+ title=CASE WHEN title='' OR title=youtube_id THEN ? ELSE title END,
+ artist=CASE WHEN artist='' THEN ? ELSE artist END,
+ album=CASE WHEN album='' THEN ? ELSE album END,
+ duration_seconds=COALESCE(duration_seconds, ?),
+ cover_url=CASE WHEN cover_url='' THEN ? ELSE cover_url END,
+ local_path=?,
+ source_kind=?,
+ updated_at=?
+ WHERE id=?""",
+ (
+ youtube_id, youtube_id,
+ title or local_path.stem,
+ artist,
+ album,
+ duration,
+ cover_url,
+ str(local_path),
+ source_kind,
+ now,
+ track_id,
+ ),
+ )
+ else:
+ cur = db.execute(
+ """INSERT INTO music_tracks(
+ import_id,spotify_id,spotify_url,title,artist,artists_json,
+ album,duration_seconds,cover_url,year,isrc,list_name,list_position,
+ youtube_url,youtube_id,local_path,source_kind,metadata_source,
+ spotify_match_score,spotify_match_status,created_at,updated_at
+ ) VALUES(
+ NULL,'','',?,?,'[]',?,?,? ,NULL,'','',NULL,'',?,?,?,'',
+ NULL,'pending',?,?
+ )""",
+ (
+ title or local_path.stem,
+ artist,
+ album,
+ duration,
+ cover_url,
+ youtube_id,
+ str(local_path),
+ source_kind,
+ now,
+ now,
+ ),
+ )
+ track_id = int(cur.lastrowid)
+
+ db.commit()
+
+ return track_id
+
+
+def enrich_track_from_spotify(track_id: int) -> dict:
+ track = get_track(track_id)
+ if not track:
+ return {"matched": False, "reason": "track missing"}
+
+ title = str(track.get("title") or "").strip()
+ artist = str(track.get("artist") or "").strip()
+ if not title:
+ return {"matched": False, "reason": "no title"}
+
+ try:
+ result = resolve_spotify_metadata(
+ title,
+ artist,
+ track.get("duration_seconds"),
+ )
+ except Exception as error:
+ with _db() as db:
+ db.execute(
+ "UPDATE music_tracks SET spotify_match_status=?,updated_at=? WHERE id=?",
+ (f"error: {error}"[:500], int(time.time()), int(track_id)),
+ )
+ db.commit()
+ return {"matched": False, "reason": str(error)}
+
+ best = result.get("best")
+ if not best:
+ status = "no-match"
+ with _db() as db:
+ db.execute(
+ "UPDATE music_tracks SET spotify_match_status=?,updated_at=? WHERE id=?",
+ (status, int(time.time()), int(track_id)),
+ )
+ db.commit()
+ return {"matched": False, "reason": status}
+
+ score = float(best.get("score") or 0)
+ if score < MUSIC_SPOTIFY_MATCH_MIN_SCORE:
+ with _db() as db:
+ db.execute(
+ "UPDATE music_tracks SET spotify_match_score=?,spotify_match_status=?,updated_at=? WHERE id=?",
+ (score, "low-confidence", int(time.time()), int(track_id)),
+ )
+ db.commit()
+ return {"matched": False, "score": score, "reason": "low-confidence"}
+
+ now = int(time.time())
+ artists = best.get("artists") or []
+ with _db() as db:
+ db.execute(
+ """UPDATE music_tracks SET
+ spotify_id=?,
+ spotify_url=?,
+ title=?,
+ artist=?,
+ artists_json=?,
+ album=?,
+ duration_seconds=COALESCE(?,duration_seconds),
+ cover_url=CASE WHEN ?<>'' THEN ? ELSE cover_url END,
+ year=?,
+ isrc=?,
+ metadata_source='spotify',
+ spotify_match_score=?,
+ spotify_match_status='matched',
+ updated_at=?
+ WHERE id=?""",
+ (
+ str(best.get("spotify_id") or ""),
+ str(best.get("spotify_url") or ""),
+ str(best.get("title") or title),
+ str(best.get("artist") or artist),
+ json.dumps(artists, ensure_ascii=False),
+ str(best.get("album") or ""),
+ best.get("duration"),
+ str(best.get("cover") or ""),
+ str(best.get("cover") or ""),
+ best.get("year"),
+ str(best.get("isrc") or ""),
+ score,
+ now,
+ int(track_id),
+ ),
+ )
+ db.commit()
+
+ return {"matched": True, "score": score, "track_id": int(track_id)}
+
+
+def write_track_sidecar(track_id: int):
+ track = get_track(track_id)
+ if not track:
+ return None
+
+ local_path = Path(track.get("local_path") or "")
+ if not local_path.is_file():
+ return None
+
+ return write_audio_sidecar(
+ local_path,
+ title=str(track.get("title") or local_path.stem),
+ artist=str(track.get("artist") or ""),
+ artists=track.get("artists") or [],
+ album=str(track.get("album") or ""),
+ year=track.get("year"),
+ duration=track.get("duration_seconds"),
+ cover_url=str(track.get("cover_url") or ""),
+ spotify_id=str(track.get("spotify_id") or ""),
+ spotify_url=str(track.get("spotify_url") or ""),
+ youtube_id=str(track.get("youtube_id") or ""),
+ isrc=str(track.get("isrc") or ""),
+ list_name=str(track.get("list_name") or ""),
+ )
+
+
+def repair_spotify_import_metadata(import_id: int) -> dict:
+ with _db() as db:
+ rows = db.execute(
+ """SELECT id,spotify_url,spotify_id,title,artist,album,cover_url,year,isrc
+ FROM music_tracks
+ WHERE import_id=?
+ ORDER BY list_position,id""",
+ (int(import_id),),
+ ).fetchall()
+
+ checked = 0
+ repaired = 0
+ errors = []
+
+ for row in rows:
+ checked += 1
+ track_id = int(row["id"])
+ try:
+ data = None
+ spotify_url = str(row["spotify_url"] or "").strip()
+ if spotify_url:
+ try:
+ data = resolve_spotify_track_metadata(spotify_url)
+ except Exception:
+ data = None
+
+ best = (data or {}).get("track") if isinstance(data, dict) else None
+
+ if not best:
+ fuzzy = resolve_spotify_metadata(
+ str(row["title"] or ""),
+ str(row["artist"] or ""),
+ None,
+ )
+ best = fuzzy.get("best") if isinstance(fuzzy, dict) else None
+
+ if not best:
+ continue
+
+ with _db() as db:
+ db.execute(
+ """UPDATE music_tracks SET
+ title=CASE WHEN ?<>'' THEN ? ELSE title END,
+ artist=CASE WHEN ?<>'' THEN ? ELSE artist END,
+ artists_json=CASE WHEN ?<>'[]' THEN ? ELSE artists_json END,
+ album=CASE WHEN ?<>'' THEN ? ELSE album END,
+ duration_seconds=COALESCE(?,duration_seconds),
+ cover_url=CASE WHEN ?<>'' THEN ? ELSE cover_url END,
+ year=COALESCE(?,year),
+ isrc=CASE WHEN ?<>'' THEN ? ELSE isrc END,
+ metadata_source='spotify',
+ updated_at=?
+ WHERE id=?""",
+ (
+ str(best.get("title") or ""), str(best.get("title") or ""),
+ str(best.get("artist") or ""), str(best.get("artist") or ""),
+ json.dumps(best.get("artists") or [], ensure_ascii=False),
+ json.dumps(best.get("artists") or [], ensure_ascii=False),
+ str(best.get("album") or ""), str(best.get("album") or ""),
+ best.get("duration"),
+ str(best.get("cover") or ""), str(best.get("cover") or ""),
+ best.get("year"),
+ str(best.get("isrc") or ""), str(best.get("isrc") or ""),
+ int(time.time()),
+ track_id,
+ ),
+ )
+ db.commit()
+ repaired += 1
+ write_track_sidecar(track_id)
+ except Exception as error:
+ errors.append({"track_id": track_id, "error": str(error)})
+
+ return {
+ "checked": checked,
+ "repaired": repaired,
+ "errors": errors,
+ }
+
+
+def register_cached_youtube_audio(
+ *,
+ video_id: str,
+ path: str | Path,
+ title: str = "",
+ artist: str = "",
+ thumbnail: str = "",
+ duration: float | None = None,
+) -> dict:
+ path = Path(path).expanduser().resolve()
+
+ track_id = _upsert_cached_track(
+ local_path=path,
+ youtube_id=str(video_id or ""),
+ title=title or str(video_id or path.stem),
+ artist=artist,
+ cover_url=thumbnail,
+ duration=duration,
+ source_kind="youtube-cache",
+ )
+
+ result = enrich_track_from_spotify(track_id)
+ try:
+ write_track_sidecar(track_id)
+ except Exception as error:
+ print("[MUSIC] sidecar write failed:", error, flush=True)
+ return {
+ "track_id": track_id,
+ "spotify": result,
+ }
+
+
+def reconcile_music_files(limit: int = 100) -> dict:
+ MUSIC_CACHE_DIR.mkdir(parents=True, exist_ok=True)
+ added = 0
+ enriched = 0
+ checked = 0
+ errors = []
+
+ paths = [
+ path for path in MUSIC_CACHE_DIR.iterdir()
+ if path.is_file()
+ and path.suffix.lower() in MUSIC_EXTENSIONS
+ and not path.name.endswith(".part")
+ ]
+
+ for path in sorted(paths)[:max(1, int(limit or 100))]:
+ checked += 1
+ try:
+ with _db() as db:
+ row = db.execute(
+ "SELECT id,spotify_id,spotify_match_status FROM music_tracks WHERE local_path=?",
+ (str(path.resolve()),),
+ ).fetchone()
+
+ if row:
+ if not row["spotify_id"] and row["spotify_match_status"] in ("", "pending", "error"):
+ result = enrich_track_from_spotify(int(row["id"]))
+ if result.get("matched"):
+ enriched += 1
+ continue
+
+ probe = _probe_audio_file(path)
+ video_id = _youtube_id_from_path(path)
+ info = _youtube_metadata(video_id) if video_id else {}
+
+ title = (
+ str(probe.get("title") or "").strip()
+ or str(info.get("title") or "").strip()
+ or path.stem
+ )
+ artist = (
+ str(probe.get("artist") or "").strip()
+ or str(info.get("channel") or info.get("uploader") or info.get("artist") or "").strip()
+ )
+ album = str(probe.get("album") or "").strip()
+ duration = probe.get("duration") or info.get("duration")
+ cover = _cover_from_youtube_info(info)
+
+ track_id = _upsert_cached_track(
+ local_path=path,
+ youtube_id=video_id,
+ title=title,
+ artist=artist,
+ album=album,
+ cover_url=cover,
+ duration=duration,
+ source_kind="folder-scan",
+ )
+ added += 1
+
+ result = enrich_track_from_spotify(track_id)
+ if result.get("matched"):
+ enriched += 1
+ try:
+ write_track_sidecar(track_id)
+ except Exception:
+ pass
+
+ except Exception as error:
+ errors.append({"path": str(path), "error": str(error)})
+
+ return {
+ "checked": checked,
+ "added": added,
+ "enriched": enriched,
+ "errors": errors,
+ }
+
+
+def _reconcile_loop():
+ while not _RECONCILE_STOP.is_set():
+ try:
+ reconcile_music_files(limit=5000)
+ except Exception as error:
+ print("[MUSIC] reconcile failed:", error, flush=True)
+ _RECONCILE_STOP.wait(MUSIC_RECONCILE_INTERVAL)
+
+
+def start_music_reconciler():
+ global _RECONCILE_THREAD
+ if _RECONCILE_THREAD and _RECONCILE_THREAD.is_alive():
+ return
+ _RECONCILE_STOP.clear()
+ _RECONCILE_THREAD = threading.Thread(
+ target=_reconcile_loop,
+ daemon=True,
+ name="music-folder-reconcile",
+ )
+ _RECONCILE_THREAD.start()
+
+
+def import_music(query: str, user_id: int | None = None) -> dict:
+ data = resolve_spotify(query, MUSIC_IMPORT_MAX_ITEMS)
+ items = list(data.get("items") or [])
+ now = int(time.time())
+ list_names = [str(item.get("list_name") or "").strip() for item in items if item.get("list_name")]
+ import_name = list_names[0] if list_names else str(data.get("source_type") or "Spotify import").title()
+
+ inserted = 0
+ updated = 0
+ with _db() as db:
+ cur = db.execute(
+ "INSERT INTO music_imports(source_url,source_type,name,added_by_user_id,created_at) VALUES(?,?,?,?,?)",
+ (query, str(data.get("source_type") or "spotify"), import_name, user_id, now),
+ )
+ import_id = int(cur.lastrowid)
+
+ for item in items:
+ spotify_id = str(item.get("spotify_id") or "")
+ spotify_url = str(item.get("spotify_url") or "")
+ existing = None
+ if spotify_id:
+ existing = db.execute("SELECT id FROM music_tracks WHERE spotify_id=?", (spotify_id,)).fetchone()
+ if existing is None and spotify_url:
+ existing = db.execute("SELECT id FROM music_tracks WHERE spotify_url=?", (spotify_url,)).fetchone()
+
+ values = (
+ import_id, spotify_id, spotify_url,
+ str(item.get("title") or item.get("youtube_id") or "Unknown"),
+ str(item.get("artist") or ""),
+ json.dumps(item.get("artists") or [], ensure_ascii=False),
+ str(item.get("album") or ""), item.get("duration"),
+ str(item.get("cover") or ""), item.get("year"),
+ str(item.get("isrc") or ""), str(item.get("list_name") or ""),
+ item.get("list_position"), str(item.get("youtube_url") or ""),
+ str(item.get("youtube_id") or ""), now,
+ )
+ if not values[14]:
+ continue
+
+ if existing:
+ db.execute("""
+ UPDATE music_tracks SET
+ import_id=?,spotify_id=?,spotify_url=?,title=?,artist=?,artists_json=?,album=?,
+ duration_seconds=?,cover_url=?,year=?,isrc=?,list_name=?,list_position=?,youtube_url=?,
+ youtube_id=?,updated_at=? WHERE id=?
+ """, values + (int(existing["id"]),))
+ updated += 1
+ else:
+ db.execute("""
+ INSERT INTO music_tracks(
+ import_id,spotify_id,spotify_url,title,artist,artists_json,album,duration_seconds,
+ cover_url,year,isrc,list_name,list_position,youtube_url,youtube_id,created_at,updated_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ """, values + (now,))
+ inserted += 1
+ db.execute(
+ "UPDATE music_tracks SET source_kind='spotify',metadata_source='spotify',"
+ "spotify_match_status='matched',spotify_match_score=1.0 "
+ "WHERE import_id=?",
+ (import_id,),
+ )
+ db.commit()
+
+ return {
+ "import_id": import_id,
+ "source_type": data.get("source_type"),
+ "resolved": len(items),
+ "inserted": inserted,
+ "updated": updated,
+ "errors": data.get("errors") or [],
+ }
+
+
+def list_tracks(limit: int = 500, search: str = "") -> list[dict]:
+ limit = max(1, min(int(limit or 500), 5000))
+ search = str(search or "").strip()
+ sql = "SELECT * FROM music_tracks"
+ values = []
+ if search:
+ like = f"%{search}%"
+ sql += " WHERE title LIKE ? COLLATE NOCASE OR artist LIKE ? COLLATE NOCASE OR album LIKE ? COLLATE NOCASE OR list_name LIKE ? COLLATE NOCASE"
+ values.extend([like, like, like, like])
+ sql += " ORDER BY CASE WHEN list_name='' THEN 1 ELSE 0 END, list_name COLLATE NOCASE, COALESCE(list_position,999999), artist COLLATE NOCASE, title COLLATE NOCASE LIMIT ?"
+ values.append(limit)
+ with _db() as db:
+ rows = db.execute(sql, values).fetchall()
+ result=[]
+ for row in rows:
+ item=dict(row)
+ try: item["artists"] = json.loads(item.pop("artists_json") or "[]")
+ except Exception: item["artists"]=[]
+ result.append(item)
+ return result
+
+
+def delete_track(track_id: int) -> None:
+ with _db() as db:
+ db.execute("DELETE FROM music_tracks WHERE id=?", (int(track_id),))
+ db.commit()
diff --git a/music_import_jobs.py b/music_import_jobs.py
new file mode 100644
index 0000000..b0b3d4c
--- /dev/null
+++ b/music_import_jobs.py
@@ -0,0 +1,311 @@
+from __future__ import annotations
+
+import os
+import sqlite3
+import threading
+import time
+import socket
+from urllib.parse import urlparse
+from pathlib import Path
+
+from dotenv import load_dotenv
+
+BASE_DIR = Path(__file__).resolve().parent
+load_dotenv(BASE_DIR / "config.env")
+DB_PATH = Path(
+ os.getenv("DB_PATH", str(BASE_DIR / "media_library.db"))
+).expanduser().resolve()
+
+POLL_SECONDS = max(
+ 0.5,
+ float(os.getenv("MUSIC_IMPORT_JOB_POLL_SECONDS", "1")),
+)
+
+RESOLVER_WAIT_SECONDS = max(
+ 1.0,
+ float(os.getenv("MUSIC_IMPORT_RESOLVER_WAIT_SECONDS", "2")),
+)
+
+_RESOLVER_URL = (
+ os.getenv("KRONIC_MUSIC_API_URL")
+ or os.getenv("KRONIC_RESOLVER_URL")
+ or "http://127.0.0.1:3030"
+).rstrip("/")
+
+
+def _resolver_address():
+ parsed = urlparse(_RESOLVER_URL)
+ host = parsed.hostname or "127.0.0.1"
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
+ return host, port
+
+
+def _resolver_ready():
+ host, port = _resolver_address()
+ try:
+ with socket.create_connection((host, port), timeout=1.0):
+ return True
+ except OSError:
+ return False
+
+
+def _resolver_unavailable_error(error):
+ text = str(error or "").lower()
+ needles = (
+ "connection refused",
+ "resolver unavailable",
+ "urlopen error",
+ "failed to establish a new connection",
+ "connection reset",
+ "connection aborted",
+ "timed out",
+ )
+ return any(needle in text for needle in needles)
+
+_THREAD = None
+_STOP = threading.Event()
+
+
+def _db():
+ db = sqlite3.connect(DB_PATH, timeout=30)
+ db.row_factory = sqlite3.Row
+ return db
+
+
+def init_music_import_jobs():
+ with _db() as db:
+ db.executescript("""
+ CREATE TABLE IF NOT EXISTS music_import_jobs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER,
+ query TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'queued',
+ message TEXT NOT NULL DEFAULT '',
+ resolved INTEGER NOT NULL DEFAULT 0,
+ inserted INTEGER NOT NULL DEFAULT 0,
+ updated INTEGER NOT NULL DEFAULT 0,
+ repaired INTEGER NOT NULL DEFAULT 0,
+ errors INTEGER NOT NULL DEFAULT 0,
+ result_import_id INTEGER,
+ error TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL,
+ started_at INTEGER,
+ finished_at INTEGER
+ );
+ CREATE INDEX IF NOT EXISTS idx_music_import_jobs_status
+ ON music_import_jobs(status,created_at);
+ """)
+ # Imports are idempotent/upsert-based; interrupted work is safe to retry.
+ db.execute(
+ """UPDATE music_import_jobs
+ SET status='queued',
+ message='requeued after service restart',
+ started_at=NULL
+ WHERE status='running'"""
+ )
+ db.commit()
+
+
+def enqueue_music_import(query: str, user_id: int | None = None):
+ query = str(query or "").strip()
+ if not query:
+ raise ValueError("Spotify URL or music query is required")
+
+ now = int(time.time())
+ with _db() as db:
+ existing = db.execute(
+ """SELECT * FROM music_import_jobs
+ WHERE query=? AND status IN ('queued','running')
+ ORDER BY id DESC LIMIT 1""",
+ (query,),
+ ).fetchone()
+ if existing:
+ return dict(existing)
+
+ cur = db.execute(
+ """INSERT INTO music_import_jobs(
+ user_id,query,status,message,created_at
+ ) VALUES(?,?,'queued','queued',?)""",
+ (user_id, query, now),
+ )
+ job_id = int(cur.lastrowid)
+ db.commit()
+ return get_music_import_job(job_id)
+
+
+def get_music_import_job(job_id: int):
+ with _db() as db:
+ row = db.execute(
+ "SELECT * FROM music_import_jobs WHERE id=?",
+ (int(job_id),),
+ ).fetchone()
+ return dict(row) if row else None
+
+
+def list_music_import_jobs(limit=20):
+ limit = max(1, min(int(limit or 20), 100))
+ with _db() as db:
+ rows = db.execute(
+ """SELECT * FROM music_import_jobs
+ ORDER BY
+ CASE status WHEN 'running' THEN 0 WHEN 'queued' THEN 1 ELSE 2 END,
+ id DESC
+ LIMIT ?""",
+ (limit,),
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+
+def clear_music_import_jobs():
+ with _db() as db:
+ cur = db.execute(
+ """DELETE FROM music_import_jobs
+ WHERE status IN ('complete','failed')"""
+ )
+ db.commit()
+ return int(cur.rowcount or 0)
+
+
+def _claim():
+ with _db() as db:
+ db.execute("BEGIN IMMEDIATE")
+ row = db.execute(
+ """SELECT * FROM music_import_jobs
+ WHERE status='queued'
+ ORDER BY id LIMIT 1"""
+ ).fetchone()
+ if not row:
+ db.commit()
+ return None
+
+ cur = db.execute(
+ """UPDATE music_import_jobs
+ SET status='running',
+ message='resolving Spotify metadata and YouTube matches…',
+ started_at=?,
+ error=''
+ WHERE id=? AND status='queued'""",
+ (int(time.time()), int(row["id"])),
+ )
+ db.commit()
+ if cur.rowcount != 1:
+ return None
+ return get_music_import_job(int(row["id"]))
+
+
+def _update(job_id, **values):
+ if not values:
+ return
+ sets = []
+ args = []
+ for key, value in values.items():
+ sets.append(f"{key}=?")
+ args.append(value)
+ args.append(int(job_id))
+ with _db() as db:
+ db.execute(
+ f"UPDATE music_import_jobs SET {', '.join(sets)} WHERE id=?",
+ args,
+ )
+ db.commit()
+
+
+def _run(job):
+ from music import import_music, repair_spotify_import_metadata
+
+ job_id = int(job["id"])
+ try:
+ result = import_music(
+ job["query"],
+ user_id=job.get("user_id"),
+ )
+ _update(
+ job_id,
+ message="repairing Spotify artwork and track metadata…",
+ resolved=int(result.get("resolved") or 0),
+ inserted=int(result.get("inserted") or 0),
+ updated=int(result.get("updated") or 0),
+ errors=len(result.get("errors") or []),
+ result_import_id=result.get("import_id"),
+ )
+
+ repair = repair_spotify_import_metadata(
+ int(result["import_id"])
+ )
+
+ _update(
+ job_id,
+ status="complete",
+ message="complete",
+ repaired=int(repair.get("repaired") or 0),
+ errors=(
+ len(result.get("errors") or [])
+ + len(repair.get("errors") or [])
+ ),
+ finished_at=int(time.time()),
+ )
+ except Exception as error:
+ if _resolver_unavailable_error(error):
+ _update(
+ job_id,
+ status="queued",
+ message="waiting for Kronic resolver…",
+ error="",
+ started_at=None,
+ finished_at=None,
+ )
+ print(
+ "[MUSIC] import waiting for resolver",
+ {"job_id": job_id, "error": str(error)},
+ flush=True,
+ )
+ return
+
+ _update(
+ job_id,
+ status="failed",
+ message="failed",
+ error=str(error)[:4000],
+ finished_at=int(time.time()),
+ )
+ print(
+ "[MUSIC] background import failed",
+ {"job_id": job_id, "error": str(error)},
+ flush=True,
+ )
+
+
+def _loop():
+ while not _STOP.is_set():
+ # stream_server intentionally starts the embedded resolver in a
+ # background thread. Do not claim Spotify jobs until its TCP listener
+ # is actually available, otherwise a queued import can fail during
+ # the first seconds of service startup.
+ if not _resolver_ready():
+ _STOP.wait(RESOLVER_WAIT_SECONDS)
+ continue
+
+ job = _claim()
+ if not job:
+ _STOP.wait(POLL_SECONDS)
+ continue
+
+ _run(job)
+
+ # A transient resolver outage can requeue the job. Avoid a tight loop
+ # while the resolver is still coming back.
+ if not _resolver_ready():
+ _STOP.wait(RESOLVER_WAIT_SECONDS)
+
+
+def start_music_import_worker():
+ global _THREAD
+ if _THREAD and _THREAD.is_alive():
+ return
+ _STOP.clear()
+ _THREAD = threading.Thread(
+ target=_loop,
+ daemon=True,
+ name="spotify-import-worker",
+ )
+ _THREAD.start()
diff --git a/playback_planner.py b/playback_planner.py
new file mode 100644
index 0000000..acec869
--- /dev/null
+++ b/playback_planner.py
@@ -0,0 +1,841 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import subprocess
+import threading
+import time
+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")
+
+BROWSER_CACHE_DIR = Path(
+ os.getenv(
+ "BROWSER_CACHE_DIR",
+ str(BASE_DIR / "browser-cache"),
+ )
+).expanduser().resolve()
+
+BROWSER_CACHE_MAX_GB = max(
+ 0.0,
+ float(os.getenv("BROWSER_CACHE_MAX_GB", "100")),
+)
+
+BROWSER_AUDIO_CHANNELS = max(
+ 1,
+ min(
+ 6,
+ int(os.getenv("BROWSER_AUDIO_CHANNELS", "2")),
+ ),
+)
+
+BROWSER_AUDIO_BITRATE = os.getenv(
+ "BROWSER_AUDIO_BITRATE",
+ "192k",
+)
+
+BROWSER_X264_PRESET = os.getenv(
+ "BROWSER_X264_PRESET",
+ "veryfast",
+)
+
+BROWSER_X264_CRF = str(
+ int(os.getenv("BROWSER_X264_CRF", "21"))
+)
+
+QUALITY_BITRATES = {
+ 720: os.getenv("QUALITY_720P_BITRATE", "3500k"),
+ 480: os.getenv("QUALITY_480P_BITRATE", "1800k"),
+ 360: os.getenv("QUALITY_360P_BITRATE", "900k"),
+}
+
+_probe_lock = threading.Lock()
+_probe_cache: dict[str, tuple[tuple[int, int], dict[str, Any]]] = {}
+
+_cache_locks_guard = threading.Lock()
+_cache_locks: dict[str, threading.Lock] = {}
+
+
+def _fingerprint(path: Path) -> tuple[int, int]:
+ stat = path.stat()
+ return (
+ int(stat.st_size),
+ int(stat.st_mtime_ns),
+ )
+
+
+def _cache_lock(key: str) -> threading.Lock:
+ with _cache_locks_guard:
+ lock = _cache_locks.get(key)
+ if lock is None:
+ lock = threading.Lock()
+ _cache_locks[key] = lock
+ return lock
+
+
+def probe_media(path: str | Path) -> dict[str, Any]:
+ path = Path(path).resolve()
+ fingerprint = _fingerprint(path)
+ cache_key = str(path)
+
+ with _probe_lock:
+ cached = _probe_cache.get(cache_key)
+ if cached and cached[0] == fingerprint:
+ return dict(cached[1])
+
+ command = [
+ FFPROBE_BIN, "-v", "error",
+ "-show_streams", "-show_format", "-of", "json", str(path),
+ ]
+ result = subprocess.run(
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, timeout=30, check=True,
+ )
+ raw = json.loads(result.stdout or "{}")
+ streams = raw.get("streams") or []
+ videos = [x for x in streams if x.get("codec_type") == "video"]
+ audios = [x for x in streams if x.get("codec_type") == "audio"]
+ video = videos[0] if videos else {}
+ audio = audios[0] if audios else {}
+ format_data = raw.get("format") or {}
+
+ audio_tracks = []
+ for ordinal, stream in enumerate(audios):
+ tags = stream.get("tags") or {}
+ disposition = stream.get("disposition") or {}
+ channels = _safe_int(stream.get("channels"))
+ layout = str(stream.get("channel_layout") or "").strip()
+ language = str(tags.get("language") or "").strip().lower()
+ title = str(tags.get("title") or "").strip()
+ codec = str(stream.get("codec_name") or "").lower()
+ audio_tracks.append({
+ "ordinal": ordinal,
+ "stream_index": _safe_int(stream.get("index")),
+ "codec": codec,
+ "codec_long_name": str(stream.get("codec_long_name") or ""),
+ "language": language,
+ "title": title,
+ "channels": channels,
+ "channel_layout": layout,
+ "bit_rate": _safe_int(stream.get("bit_rate")),
+ "sample_rate": _safe_int(stream.get("sample_rate")),
+ "default": bool(disposition.get("default")),
+ })
+
+ info = {
+ "path": str(path),
+ "suffix": path.suffix.lower(),
+ "size": fingerprint[0],
+ "mtime_ns": fingerprint[1],
+ "container": str(format_data.get("format_name") or "").lower(),
+ "duration": _safe_float(format_data.get("duration")),
+ "video_codec": str(video.get("codec_name") or "").lower(),
+ "video_profile": str(video.get("profile") or ""),
+ "pixel_format": str(video.get("pix_fmt") or "").lower(),
+ "width": _safe_int(video.get("width")),
+ "height": _safe_int(video.get("height")),
+ "video_bitrate": _safe_int(video.get("bit_rate")),
+ "fps": _frame_rate(video.get("avg_frame_rate") or video.get("r_frame_rate")),
+ "audio_codec": str(audio.get("codec_name") or "").lower(),
+ "audio_channels": _safe_int(audio.get("channels")),
+ "audio_sample_rate": _safe_int(audio.get("sample_rate")),
+ "audio_tracks": audio_tracks,
+ }
+ with _probe_lock:
+ _probe_cache[cache_key] = (fingerprint, dict(info))
+ return info
+
+
+def quality_options(info: dict[str, Any]) -> list[dict[str, Any]]:
+ height = int(info.get("height") or 0)
+ native = f"{height}p" if height else "Original"
+ options = [{"value": "original", "label": f"Original {native}" if height else "Original", "height": height or None}]
+ for target in (720, 480, 360):
+ if height > target:
+ options.append({"value": str(target), "label": f"{target}p", "height": target, "bitrate": QUALITY_BITRATES[target]})
+ return options
+
+
+def _safe_float(value: Any) -> float | None:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _safe_int(value: Any) -> int | None:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _frame_rate(value: Any) -> float | None:
+ text = str(value or "").strip()
+ if not text:
+ return None
+
+ if "/" in text:
+ numerator, denominator = text.split("/", 1)
+ try:
+ denominator_value = float(denominator)
+ if denominator_value == 0:
+ return None
+ return float(numerator) / denominator_value
+ except (TypeError, ValueError):
+ return None
+
+ return _safe_float(text)
+
+
+def _truthy(value: Any) -> bool:
+ return str(value or "").strip().lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ "probably",
+ "maybe",
+ }
+
+
+def _browser_name(value: Any) -> str:
+ value = str(value or "").strip().lower()
+ if value in {
+ "firefox",
+ "chrome",
+ "edge",
+ "safari",
+ "unknown",
+ }:
+ return value
+ return "unknown"
+
+
+def plan_playback(
+ path: str | Path,
+ *,
+ capabilities: dict[str, Any] | None = None,
+ browser: str = "unknown",
+ force_compat: bool = False,
+ quality: str = "original",
+ audio_stream_index: int | None = None,
+) -> dict[str, Any]:
+ info = probe_media(path)
+ capabilities = capabilities or {}
+ browser = _browser_name(browser)
+ quality = str(quality or "original").lower().strip()
+ requested_height = None if quality == "original" else _safe_int(quality)
+ if requested_height not in {None, 720, 480, 360}:
+ requested_height = None
+ quality = "original"
+
+ tracks = info.get("audio_tracks") or []
+ selected_audio = None
+ if audio_stream_index is not None:
+ selected_audio = next((t for t in tracks if t.get("stream_index") == int(audio_stream_index)), None)
+ if selected_audio is None and tracks:
+ selected_audio = next((t for t in tracks if t.get("default")), tracks[0])
+ selected_audio_index = selected_audio.get("stream_index") if selected_audio else None
+ selected_audio_codec = (selected_audio or {}).get("codec") or info.get("audio_codec") or ""
+
+ def finalize(plan: dict[str, Any]) -> dict[str, Any]:
+ plan["selected_audio_stream_index"] = selected_audio_index
+ plan["selected_audio"] = selected_audio
+ plan["selected_quality"] = quality
+ plan.setdefault("quality_options", quality_options(info))
+ return plan
+
+ suffix = info["suffix"]
+ vcodec = info["video_codec"]
+ acodec = selected_audio_codec
+
+ supports_h264 = _truthy(
+ capabilities.get("h264", True)
+ )
+ supports_av1 = _truthy(
+ capabilities.get("av1", False)
+ )
+ supports_hevc = _truthy(
+ capabilities.get("hevc", False)
+ )
+ supports_webm_vp9 = _truthy(
+ capabilities.get("webm_vp9", False)
+ )
+ supports_webm_av1 = _truthy(
+ capabilities.get("webm_av1", False)
+ )
+
+ is_mp4 = suffix in {
+ ".mp4",
+ ".m4v",
+ ".mov",
+ }
+ is_webm = suffix == ".webm"
+
+ if requested_height is not None and int(info.get("height") or 0) > requested_height:
+ plan = _plan(
+ "transcode_stream", info, browser,
+ f"Manual {requested_height}p lower-bandwidth transcode selected.",
+ seek_mode="server",
+ )
+ plan["requested_height"] = requested_height
+ plan["video_bitrate"] = QUALITY_BITRATES[requested_height]
+ return finalize(plan)
+
+ # A retry requested by the frontend must use the most conservative path.
+ # Do not select remux_cache again or the retry simply repeats the same
+ # startup failure.
+ if force_compat:
+ return finalize(_plan(
+ "transcode_stream",
+ info,
+ browser,
+ "Forced compatibility retry: H.264/AAC live transcode.",
+ seek_mode="server",
+ ))
+
+ video_direct = False
+
+ if vcodec in {
+ "h264",
+ "avc1",
+ }:
+ video_direct = supports_h264
+ elif vcodec == "av1":
+ video_direct = supports_av1
+ elif vcodec in {
+ "hevc",
+ "h265",
+ }:
+ video_direct = supports_hevc
+ elif vcodec in {
+ "vp9",
+ "vp09",
+ }:
+ video_direct = supports_webm_vp9
+
+ if vcodec == "av1" and is_webm:
+ video_direct = supports_webm_av1
+
+ audio_mp4_direct = acodec in {
+ "",
+ "aac",
+ "mp3",
+ }
+
+ audio_webm_direct = acodec in {
+ "",
+ "opus",
+ "vorbis",
+ }
+
+ default_track = next((t for t in tracks if t.get("default")), tracks[0] if tracks else None)
+ default_audio_index = default_track.get("stream_index") if default_track else None
+ alternate_audio_selected = (
+ audio_stream_index is not None
+ and selected_audio_index is not None
+ and selected_audio_index != default_audio_index
+ )
+
+ # The most stable path is an ordinary seekable source that the browser
+ # already supports. Never run FFmpeg simply because it exists.
+ if (
+ is_mp4
+ and video_direct
+ and audio_mp4_direct
+ and not alternate_audio_selected
+ ):
+ return finalize(_plan(
+ "direct",
+ info,
+ browser,
+ "Source is already browser-compatible MP4.",
+ seek_mode="client",
+ ))
+
+ if (
+ is_webm
+ and video_direct
+ and audio_webm_direct
+ and not alternate_audio_selected
+ ):
+ return finalize(_plan(
+ "direct",
+ info,
+ browser,
+ "Source is already browser-compatible WebM.",
+ seek_mode="client",
+ ))
+
+ # H.264 is already the desired compatibility video codec. Repackage it
+ # once into a normal +faststart MP4 instead of feeding Firefox an endless
+ # fragmented MP4 pipe on every playback.
+ if vcodec in {
+ "h264",
+ "avc1",
+ } and supports_h264:
+ return finalize(_plan(
+ "remux_stream",
+ info,
+ browser,
+ (
+ "H.264 video can be copied immediately while the selected "
+ "audio track is normalized for browser playback."
+ ),
+ seek_mode="server",
+ ))
+
+ # Unsupported video codecs must be transcoded while playing. Waiting for
+ # a full movie-length H.264 cache before first playback would be a poor UX.
+ return finalize(_plan(
+ "transcode_stream",
+ info,
+ browser,
+ (
+ f"{vcodec or 'unknown'} video is not directly usable by this "
+ "browser; stream a normalized H.264/AAC fragmented MP4."
+ ),
+ seek_mode="server",
+ ))
+
+
+def _plan(
+ mode: str,
+ info: dict[str, Any],
+ browser: str,
+ reason: str,
+ *,
+ seek_mode: str,
+) -> dict[str, Any]:
+ return {
+ "mode": mode,
+ "seek_mode": seek_mode,
+ "browser": browser,
+ "reason": reason,
+ "source": info,
+ "quality_options": quality_options(info),
+ }
+
+
+def cache_path_for(
+ source_path: str | Path,
+ *,
+ media_id: int | str,
+) -> Path:
+ source_path = Path(source_path).resolve()
+ size, mtime_ns = _fingerprint(source_path)
+
+ digest = hashlib.sha1(
+ (
+ f"{source_path}\0"
+ f"{size}\0"
+ f"{mtime_ns}\0"
+ "compat-mp4-v2"
+ ).encode("utf-8")
+ ).hexdigest()[:20]
+
+ return (
+ BROWSER_CACHE_DIR
+ / f"{media_id}-{digest}.mp4"
+ )
+
+
+def compatibility_cache_status(
+ source_path: str | Path,
+ *,
+ media_id: int | str,
+) -> dict[str, Any]:
+ path = cache_path_for(
+ source_path,
+ media_id=media_id,
+ )
+
+ return {
+ "cached": path.is_file()
+ and path.stat().st_size > 0,
+ "path": str(path),
+ "size_bytes": (
+ path.stat().st_size
+ if path.is_file()
+ else 0
+ ),
+ }
+
+
+def ensure_remux_cache(
+ source_path: str | Path,
+ *,
+ media_id: int | str,
+) -> Path:
+ source_path = Path(source_path).resolve()
+ BROWSER_CACHE_DIR.mkdir(
+ parents=True,
+ exist_ok=True,
+ )
+
+ destination = cache_path_for(
+ source_path,
+ media_id=media_id,
+ )
+ lock = _cache_lock(str(destination))
+
+ with lock:
+ if (
+ destination.is_file()
+ and destination.stat().st_size > 0
+ ):
+ try:
+ os.utime(destination, None)
+ except OSError:
+ pass
+ return destination
+
+ info = probe_media(source_path)
+ temporary = destination.with_suffix(
+ ".part.mp4"
+ )
+ temporary.unlink(missing_ok=True)
+
+ command = [
+ FFMPEG_BIN,
+ "-nostdin",
+ "-hide_banner",
+ "-loglevel",
+ "warning",
+ "-fflags",
+ "+genpts+discardcorrupt",
+ "-i",
+ str(source_path),
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a:0?",
+ "-sn",
+ "-dn",
+ "-c:v",
+ "copy",
+ ]
+
+ if info.get("audio_codec") in {
+ "",
+ "aac",
+ "mp3",
+ }:
+ command.extend(
+ [
+ "-c:a",
+ "copy",
+ ]
+ )
+ else:
+ command.extend(
+ [
+ "-c:a",
+ "aac",
+ "-b:a",
+ BROWSER_AUDIO_BITRATE,
+ "-ar",
+ "48000",
+ "-ac",
+ str(BROWSER_AUDIO_CHANNELS),
+ "-af",
+ "aresample=async=1:first_pts=0",
+ ]
+ )
+
+ command.extend(
+ [
+ "-avoid_negative_ts",
+ "make_zero",
+ "-map_metadata",
+ "-1",
+ "-map_chapters",
+ "-1",
+ "-movflags",
+ "+faststart",
+ "-f",
+ "mp4",
+ "-y",
+ str(temporary),
+ ]
+ )
+
+ result = subprocess.run(
+ command,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+
+ if (
+ result.returncode != 0
+ or not temporary.is_file()
+ or temporary.stat().st_size <= 0
+ ):
+ temporary.unlink(
+ missing_ok=True
+ )
+ raise RuntimeError(
+ "FFmpeg compatibility remux failed: "
+ + (
+ result.stderr[-4000:]
+ if result.stderr
+ else f"return code {result.returncode}"
+ )
+ )
+
+ temporary.replace(destination)
+ prune_browser_cache()
+
+ return destination
+
+
+def remux_stream_command(
+ source_path: str | Path,
+ *,
+ start_seconds: float = 0.0,
+ audio_stream_index: int | None = None,
+) -> list[str]:
+ """
+ Start immediately for H.264 sources that only need container/audio cleanup.
+
+ Video is copied. Audio is normalized to AAC. Output is fragmented MP4 so
+ the browser can begin playback before the entire movie has been remuxed.
+ """
+ source_path = Path(source_path).resolve()
+
+ command = [
+ FFMPEG_BIN,
+ "-nostdin",
+ "-hide_banner",
+ "-loglevel",
+ "warning",
+ "-fflags",
+ "+genpts+discardcorrupt",
+ ]
+
+ if start_seconds > 0:
+ command.extend([
+ "-ss",
+ f"{start_seconds:.3f}",
+ ])
+
+ command.extend([
+ "-i",
+ str(source_path),
+ "-map",
+ "0:v:0",
+ "-map",
+ (f"0:{audio_stream_index}?" if audio_stream_index is not None else "0:a:0?"),
+ "-sn",
+ "-dn",
+ "-c:v",
+ "copy",
+ "-c:a",
+ "aac",
+ "-b:a",
+ BROWSER_AUDIO_BITRATE,
+ "-ar",
+ "48000",
+ "-ac",
+ str(BROWSER_AUDIO_CHANNELS),
+ "-af",
+ "aresample=async=1:first_pts=0",
+ "-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",
+ ])
+
+ return command
+
+
+def transcode_stream_command(
+ source_path: str | Path,
+ *,
+ start_seconds: float = 0.0,
+ audio_stream_index: int | None = None,
+ target_height: int | None = None,
+ video_bitrate: str | None = None,
+) -> list[str]:
+ source_path = Path(source_path).resolve()
+
+ command = [
+ FFMPEG_BIN,
+ "-nostdin",
+ "-hide_banner",
+ "-loglevel",
+ "warning",
+ "-fflags",
+ "+genpts+discardcorrupt",
+ ]
+
+ if start_seconds > 0:
+ command.extend(
+ [
+ "-ss",
+ f"{start_seconds:.3f}",
+ ]
+ )
+
+ command.extend(
+ [
+ "-i",
+ str(source_path),
+ "-map",
+ "0:v:0",
+ "-map",
+ (f"0:{audio_stream_index}?" if audio_stream_index is not None else "0:a:0?"),
+ "-sn",
+ "-dn",
+ "-c:v",
+ "libx264",
+ "-preset",
+ BROWSER_X264_PRESET,
+ "-crf",
+ BROWSER_X264_CRF,
+ "-profile:v",
+ "high",
+ "-level:v",
+ "4.1",
+ "-pix_fmt",
+ "yuv420p",
+ ]
+ )
+
+ if target_height:
+ command.extend(["-vf", f"scale=-2:{int(target_height)}"])
+ if video_bitrate:
+ command.extend([
+ "-b:v", str(video_bitrate),
+ "-maxrate", str(video_bitrate),
+ "-bufsize", str(video_bitrate),
+ ])
+
+ command.extend(
+ [
+ "-c:a",
+ "aac",
+ "-b:a",
+ BROWSER_AUDIO_BITRATE,
+ "-ar",
+ "48000",
+ "-ac",
+ str(BROWSER_AUDIO_CHANNELS),
+ "-af",
+ "aresample=async=1:first_pts=0",
+ "-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",
+ "-f",
+ "mp4",
+ "pipe:1",
+ ]
+ )
+
+ return command
+
+
+def prune_browser_cache() -> None:
+ if (
+ BROWSER_CACHE_MAX_GB
+ <= 0
+ or not BROWSER_CACHE_DIR.is_dir()
+ ):
+ return
+
+ maximum = int(
+ BROWSER_CACHE_MAX_GB
+ * 1024
+ * 1024
+ * 1024
+ )
+
+ files = [
+ path
+ for path in BROWSER_CACHE_DIR.glob("*.mp4")
+ if path.is_file()
+ ]
+
+ entries = []
+ total = 0
+
+ for path in files:
+ try:
+ stat = path.stat()
+ except OSError:
+ continue
+
+ total += stat.st_size
+ entries.append(
+ (
+ stat.st_mtime,
+ stat.st_size,
+ path,
+ )
+ )
+
+ if total <= maximum:
+ return
+
+ entries.sort(
+ key=lambda item: item[0]
+ )
+
+ for _mtime, size, path in entries:
+ if total <= maximum:
+ break
+
+ try:
+ path.unlink()
+ total -= size
+ except OSError:
+ pass
diff --git a/resolver_manager.py b/resolver_manager.py
new file mode 100644
index 0000000..ee12f8d
--- /dev/null
+++ b/resolver_manager.py
@@ -0,0 +1,277 @@
+from __future__ import annotations
+
+import atexit
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from urllib.error import URLError
+from urllib.request import urlopen
+
+from dotenv import load_dotenv
+
+
+BASE_DIR = Path(__file__).resolve().parent
+load_dotenv(BASE_DIR / "config.env")
+
+KRONIC_DIR = Path(
+ os.getenv(
+ "KRONIC_DIR",
+ str(BASE_DIR / "kronic"),
+ )
+).expanduser().resolve()
+
+RESOLVER_HOST = os.getenv(
+ "KRONIC_RESOLVER_HOST",
+ "127.0.0.1",
+).strip() or "127.0.0.1"
+
+RESOLVER_PORT = int(
+ os.getenv(
+ "KRONIC_RESOLVER_PORT",
+ "3030",
+ )
+)
+
+RESOLVER_START_TIMEOUT = float(
+ os.getenv(
+ "KRONIC_RESOLVER_START_TIMEOUT",
+ "30",
+ )
+)
+
+RESOLVER_URL = (
+ f"http://{RESOLVER_HOST}:{RESOLVER_PORT}"
+)
+
+_PROCESS: subprocess.Popen | None = None
+_LOCK = threading.Lock()
+_OWNS_PROCESS = False
+
+
+def _health_url() -> str:
+ return f"{RESOLVER_URL}/health"
+
+
+def resolver_is_ready(
+ timeout: float = 1.0,
+) -> bool:
+ try:
+ with urlopen(
+ _health_url(),
+ timeout=timeout,
+ ) as response:
+ if response.status < 200 or response.status >= 300:
+ return False
+
+ # The Kronic resolver currently returns JSON, but health only
+ # needs a successful HTTP response.
+ try:
+ json.loads(
+ response.read().decode(
+ "utf-8",
+ "replace",
+ )
+ )
+ except Exception:
+ pass
+
+ return True
+
+ except Exception:
+ return False
+
+
+def _required_paths() -> list[Path]:
+ return [
+ KRONIC_DIR / "resolver" / "__init__.py",
+ KRONIC_DIR / "resolver" / "app.py",
+ KRONIC_DIR / "resolver" / "app_spotdl.py",
+ KRONIC_DIR / "resolver" / "spotdl_router.py",
+ KRONIC_DIR / "resolver" / "models.py",
+ KRONIC_DIR / "resolver" / "net.py",
+ KRONIC_DIR / "resolver" / "ytdlp_service.py",
+ ]
+
+
+def validate_resolver_tree() -> None:
+ missing = [
+ path
+ for path in _required_paths()
+ if not path.is_file()
+ ]
+
+ if missing:
+ formatted = "\n".join(
+ f" - {path}"
+ for path in missing
+ )
+ raise RuntimeError(
+ "Kronic resolver files are missing:\n"
+ f"{formatted}\n"
+ "Expected the resolver beneath "
+ f"{KRONIC_DIR}"
+ )
+
+
+def start_resolver() -> bool:
+ """
+ Start kronic.resolver.app_spotdl:app as a child of the media server.
+
+ Returns True when this process started the resolver.
+ Returns False when a compatible resolver was already listening.
+ """
+ global _PROCESS, _OWNS_PROCESS
+
+ with _LOCK:
+ if _PROCESS is not None and _PROCESS.poll() is None:
+ return True
+
+ # If something is already listening and healthy, use it rather than
+ # starting a duplicate listener.
+ if resolver_is_ready():
+ print(
+ f"[RESOLVER] Existing resolver detected at {RESOLVER_URL}",
+ flush=True,
+ )
+ _OWNS_PROCESS = False
+ return False
+
+ validate_resolver_tree()
+
+ command = [
+ sys.executable,
+ "-m",
+ "uvicorn",
+ "kronic.resolver.app_spotdl:app",
+ "--host",
+ RESOLVER_HOST,
+ "--port",
+ str(RESOLVER_PORT),
+ "--log-level",
+ os.getenv(
+ "KRONIC_RESOLVER_LOG_LEVEL",
+ "warning",
+ ),
+ ]
+
+ env = os.environ.copy()
+ env.setdefault(
+ "PYTHONUNBUFFERED",
+ "1",
+ )
+
+ print(
+ "[RESOLVER] Starting embedded Kronic resolver:",
+ " ".join(command),
+ flush=True,
+ )
+
+ _PROCESS = subprocess.Popen(
+ command,
+ cwd=str(BASE_DIR),
+ env=env,
+ stdin=subprocess.DEVNULL,
+ )
+ _OWNS_PROCESS = True
+
+ deadline = (
+ time.monotonic()
+ + RESOLVER_START_TIMEOUT
+ )
+
+ while time.monotonic() < deadline:
+ process = _PROCESS
+
+ if process is None:
+ break
+
+ return_code = process.poll()
+ if return_code is not None:
+ _PROCESS = None
+ _OWNS_PROCESS = False
+ raise RuntimeError(
+ "Embedded Kronic resolver exited during startup "
+ f"with return code {return_code}"
+ )
+
+ if resolver_is_ready(
+ timeout=1.0
+ ):
+ print(
+ f"[RESOLVER] Ready at {RESOLVER_URL}",
+ flush=True,
+ )
+ return True
+
+ time.sleep(0.25)
+
+ stop_resolver()
+
+ raise RuntimeError(
+ "Embedded Kronic resolver did not become ready within "
+ f"{RESOLVER_START_TIMEOUT:.1f} seconds"
+ )
+
+
+def stop_resolver() -> None:
+ global _PROCESS, _OWNS_PROCESS
+
+ with _LOCK:
+ process = _PROCESS
+ owns_process = _OWNS_PROCESS
+
+ _PROCESS = None
+ _OWNS_PROCESS = False
+
+ if process is None or not owns_process:
+ return
+
+ if process.poll() is not None:
+ return
+
+ print(
+ "[RESOLVER] Stopping embedded Kronic resolver...",
+ flush=True,
+ )
+
+ try:
+ process.terminate()
+ process.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=3)
+ except Exception as error:
+ print(
+ f"[RESOLVER] Stop error: {error}",
+ flush=True,
+ )
+
+
+def resolver_status() -> dict:
+ process = _PROCESS
+
+ return {
+ "url": RESOLVER_URL,
+ "ready": resolver_is_ready(),
+ "managed": bool(
+ process is not None
+ and _OWNS_PROCESS
+ ),
+ "pid": (
+ process.pid
+ if process is not None
+ and process.poll() is None
+ else None
+ ),
+ "kronic_dir": str(KRONIC_DIR),
+ }
+
+
+atexit.register(
+ stop_resolver
+)