Files
Kronic-Krusaders/music.py
T
2026-11-25 20:20:43 -06:00

1041 lines
35 KiB
Python

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