312 lines
8.6 KiB
Python
312 lines
8.6 KiB
Python
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()
|