507 lines
14 KiB
Python
507 lines
14 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
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()
|
|
|
|
CACHE_JOB_POLL_SECONDS = max(
|
|
0.25,
|
|
float(os.getenv("CACHE_JOB_POLL_SECONDS", "1")),
|
|
)
|
|
CACHE_JOB_KEEP = max(
|
|
20,
|
|
int(os.getenv("CACHE_JOB_KEEP", "200")),
|
|
)
|
|
|
|
_WORKER = None
|
|
_STOP = threading.Event()
|
|
|
|
|
|
def _db():
|
|
db = sqlite3.connect(DB_PATH, timeout=30)
|
|
db.row_factory = sqlite3.Row
|
|
return db
|
|
|
|
|
|
def init_cache_jobs_db():
|
|
with _db() as db:
|
|
db.executescript("""
|
|
CREATE TABLE IF NOT EXISTS cache_jobs (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
user_id INTEGER,
|
|
video_id TEXT NOT NULL,
|
|
mode TEXT NOT NULL,
|
|
title TEXT NOT NULL DEFAULT '',
|
|
artist TEXT NOT NULL DEFAULT '',
|
|
thumbnail TEXT NOT NULL DEFAULT '',
|
|
duration_seconds REAL,
|
|
status TEXT NOT NULL DEFAULT 'queued',
|
|
progress REAL NOT NULL DEFAULT 0,
|
|
message TEXT NOT NULL DEFAULT '',
|
|
error TEXT NOT NULL DEFAULT '',
|
|
output_path TEXT NOT NULL DEFAULT '',
|
|
is_live INTEGER NOT NULL DEFAULT 0,
|
|
cancel_requested INTEGER NOT NULL DEFAULT 0,
|
|
created_at INTEGER NOT NULL,
|
|
started_at INTEGER,
|
|
finished_at INTEGER
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_cache_jobs_status
|
|
ON cache_jobs(status, created_at);
|
|
CREATE INDEX IF NOT EXISTS idx_cache_jobs_video
|
|
ON cache_jobs(video_id, mode);
|
|
""")
|
|
|
|
columns = {
|
|
row["name"]
|
|
for row in db.execute("PRAGMA table_info(cache_jobs)").fetchall()
|
|
}
|
|
for name, ddl in (
|
|
("is_live", "INTEGER NOT NULL DEFAULT 0"),
|
|
("cancel_requested", "INTEGER NOT NULL DEFAULT 0"),
|
|
):
|
|
if name not in columns:
|
|
db.execute(
|
|
f"ALTER TABLE cache_jobs ADD COLUMN {name} {ddl}"
|
|
)
|
|
|
|
# A finite VOD job can be retried after restart. A live recording
|
|
# cannot be resumed continuously, so mark it interrupted instead.
|
|
db.execute(
|
|
"""UPDATE cache_jobs
|
|
SET status='failed',
|
|
message='interrupted by service restart',
|
|
error='Live recording was interrupted by service restart.',
|
|
finished_at=?,
|
|
cancel_requested=0
|
|
WHERE status='running' AND is_live=1""",
|
|
(int(time.time()),),
|
|
)
|
|
db.execute(
|
|
"""UPDATE cache_jobs
|
|
SET status='queued',
|
|
progress=0,
|
|
message='requeued after service restart',
|
|
started_at=NULL,
|
|
cancel_requested=0
|
|
WHERE status='running' AND is_live=0"""
|
|
)
|
|
db.commit()
|
|
|
|
|
|
def enqueue_cache_job(
|
|
*,
|
|
user_id: int | None,
|
|
video_id: str,
|
|
mode: str,
|
|
title: str = "",
|
|
artist: str = "",
|
|
thumbnail: str = "",
|
|
duration_seconds=None,
|
|
):
|
|
mode = str(mode or "").strip().lower()
|
|
if mode not in {"video", "music"}:
|
|
raise ValueError("mode must be 'video' or 'music'")
|
|
|
|
video_id = str(video_id or "").strip()
|
|
if not video_id:
|
|
raise ValueError("video_id is required")
|
|
|
|
now = int(time.time())
|
|
with _db() as db:
|
|
existing = db.execute(
|
|
"""SELECT * FROM cache_jobs
|
|
WHERE video_id=? AND mode=?
|
|
AND status IN ('queued','running')
|
|
ORDER BY id DESC LIMIT 1""",
|
|
(video_id, mode),
|
|
).fetchone()
|
|
|
|
if existing:
|
|
return dict(existing)
|
|
|
|
cur = db.execute(
|
|
"""INSERT INTO cache_jobs(
|
|
user_id,video_id,mode,title,artist,thumbnail,duration_seconds,
|
|
status,progress,message,is_live,cancel_requested,created_at
|
|
) VALUES(?,?,?,?,?,?,?,'queued',0,'queued',0,0,?)""",
|
|
(
|
|
user_id,
|
|
video_id,
|
|
mode,
|
|
title,
|
|
artist,
|
|
thumbnail,
|
|
duration_seconds,
|
|
now,
|
|
),
|
|
)
|
|
job_id = int(cur.lastrowid)
|
|
db.commit()
|
|
|
|
return get_cache_job(job_id)
|
|
|
|
|
|
def get_cache_job(job_id: int):
|
|
with _db() as db:
|
|
row = db.execute(
|
|
"SELECT * FROM cache_jobs WHERE id=?",
|
|
(int(job_id),),
|
|
).fetchone()
|
|
return dict(row) if row else None
|
|
|
|
|
|
def list_cache_jobs(limit: int = 100):
|
|
limit = max(1, min(int(limit or 100), 500))
|
|
with _db() as db:
|
|
rows = db.execute(
|
|
"""SELECT * FROM cache_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_cache_jobs(statuses=None):
|
|
statuses = statuses or ("complete", "failed", "cancelled")
|
|
allowed = {"complete", "failed", "cancelled"}
|
|
statuses = [
|
|
str(status).lower()
|
|
for status in statuses
|
|
if str(status).lower() in allowed
|
|
]
|
|
if not statuses:
|
|
return 0
|
|
|
|
placeholders = ",".join("?" for _ in statuses)
|
|
with _db() as db:
|
|
cur = db.execute(
|
|
f"DELETE FROM cache_jobs WHERE status IN ({placeholders})",
|
|
statuses,
|
|
)
|
|
db.commit()
|
|
return int(cur.rowcount or 0)
|
|
|
|
|
|
def remove_cache_job(job_id: int):
|
|
with _db() as db:
|
|
row = db.execute(
|
|
"SELECT status FROM cache_jobs WHERE id=?",
|
|
(int(job_id),),
|
|
).fetchone()
|
|
if not row:
|
|
return False
|
|
if row["status"] not in {"complete", "failed", "cancelled"}:
|
|
raise ValueError("Only finished jobs can be removed.")
|
|
db.execute("DELETE FROM cache_jobs WHERE id=?", (int(job_id),))
|
|
db.commit()
|
|
return True
|
|
|
|
|
|
def retry_cache_job(job_id: int):
|
|
with _db() as db:
|
|
row = db.execute(
|
|
"SELECT * FROM cache_jobs WHERE id=?",
|
|
(int(job_id),),
|
|
).fetchone()
|
|
if not row:
|
|
raise ValueError("Cache job not found.")
|
|
if row["status"] not in {"failed", "cancelled"}:
|
|
raise ValueError("Only failed or cancelled jobs can be retried.")
|
|
|
|
db.execute(
|
|
"""UPDATE cache_jobs SET
|
|
status='queued',
|
|
progress=0,
|
|
message='queued',
|
|
error='',
|
|
output_path='',
|
|
is_live=0,
|
|
cancel_requested=0,
|
|
started_at=NULL,
|
|
finished_at=NULL
|
|
WHERE id=?""",
|
|
(int(job_id),),
|
|
)
|
|
db.commit()
|
|
return get_cache_job(job_id)
|
|
|
|
|
|
def cancel_cache_job(job_id: int):
|
|
with _db() as db:
|
|
row = db.execute(
|
|
"SELECT * FROM cache_jobs WHERE id=?",
|
|
(int(job_id),),
|
|
).fetchone()
|
|
if not row:
|
|
raise ValueError("Cache job not found.")
|
|
|
|
if row["status"] == "queued":
|
|
db.execute(
|
|
"""UPDATE cache_jobs SET
|
|
status='cancelled',
|
|
progress=0,
|
|
message='cancelled',
|
|
cancel_requested=1,
|
|
finished_at=?
|
|
WHERE id=?""",
|
|
(int(time.time()), int(job_id)),
|
|
)
|
|
elif row["status"] == "running":
|
|
db.execute(
|
|
"""UPDATE cache_jobs SET
|
|
cancel_requested=1,
|
|
message=CASE
|
|
WHEN is_live=1 THEN 'stopping live recording…'
|
|
ELSE 'cancelling…'
|
|
END
|
|
WHERE id=?""",
|
|
(int(job_id),),
|
|
)
|
|
elif row["status"] in {"complete", "failed", "cancelled"}:
|
|
return dict(row)
|
|
db.commit()
|
|
|
|
return get_cache_job(job_id)
|
|
|
|
|
|
def _update_job(job_id, **values):
|
|
if not values:
|
|
return
|
|
columns = []
|
|
args = []
|
|
for key, value in values.items():
|
|
columns.append(f"{key}=?")
|
|
args.append(value)
|
|
args.append(int(job_id))
|
|
with _db() as db:
|
|
db.execute(
|
|
f"UPDATE cache_jobs SET {', '.join(columns)} WHERE id=?",
|
|
args,
|
|
)
|
|
db.commit()
|
|
|
|
|
|
def _cancel_requested(job_id):
|
|
with _db() as db:
|
|
row = db.execute(
|
|
"SELECT cancel_requested FROM cache_jobs WHERE id=?",
|
|
(int(job_id),),
|
|
).fetchone()
|
|
return bool(row and row["cancel_requested"])
|
|
|
|
|
|
def _claim_next_job():
|
|
with _db() as db:
|
|
db.execute("BEGIN IMMEDIATE")
|
|
row = db.execute(
|
|
"""SELECT * FROM cache_jobs
|
|
WHERE status='queued'
|
|
ORDER BY id
|
|
LIMIT 1"""
|
|
).fetchone()
|
|
if not row:
|
|
db.commit()
|
|
return None
|
|
|
|
if row["cancel_requested"]:
|
|
db.execute(
|
|
"""UPDATE cache_jobs
|
|
SET status='cancelled',
|
|
message='cancelled',
|
|
finished_at=?
|
|
WHERE id=?""",
|
|
(int(time.time()), int(row["id"])),
|
|
)
|
|
db.commit()
|
|
return None
|
|
|
|
now = int(time.time())
|
|
updated = db.execute(
|
|
"""UPDATE cache_jobs
|
|
SET status='running',
|
|
started_at=?,
|
|
progress=0,
|
|
message='starting',
|
|
error='',
|
|
cancel_requested=0
|
|
WHERE id=? AND status='queued'""",
|
|
(now, int(row["id"])),
|
|
)
|
|
db.commit()
|
|
|
|
if updated.rowcount != 1:
|
|
return None
|
|
|
|
return get_cache_job(int(row["id"]))
|
|
|
|
|
|
def _prune_jobs():
|
|
with _db() as db:
|
|
ids = [
|
|
row["id"]
|
|
for row in db.execute(
|
|
"""SELECT id FROM cache_jobs
|
|
WHERE status IN ('complete','failed','cancelled')
|
|
ORDER BY id DESC
|
|
LIMIT -1 OFFSET ?""",
|
|
(CACHE_JOB_KEEP,),
|
|
).fetchall()
|
|
]
|
|
if ids:
|
|
placeholders = ",".join("?" for _ in ids)
|
|
db.execute(
|
|
f"DELETE FROM cache_jobs WHERE id IN ({placeholders})",
|
|
ids,
|
|
)
|
|
db.commit()
|
|
|
|
|
|
def _run_job(job):
|
|
job_id = int(job["id"])
|
|
|
|
def progress(percent, message="caching"):
|
|
values = {
|
|
"progress": max(
|
|
0.0,
|
|
min(100.0, float(percent or 0)),
|
|
),
|
|
"message": str(message or ""),
|
|
}
|
|
if str(message or "").startswith("recording live"):
|
|
values["is_live"] = 1
|
|
_update_job(job_id, **values)
|
|
|
|
try:
|
|
if job["mode"] == "video":
|
|
from youtube_stream import (
|
|
CacheJobCancelled,
|
|
build_youtube_video_cache,
|
|
)
|
|
|
|
try:
|
|
path, _cached = build_youtube_video_cache(
|
|
job["video_id"],
|
|
progress_callback=progress,
|
|
cancel_check=lambda: _cancel_requested(job_id),
|
|
)
|
|
except CacheJobCancelled as cancelled:
|
|
_update_job(
|
|
job_id,
|
|
status="cancelled",
|
|
progress=100 if cancelled.output_path else 0,
|
|
message=(
|
|
"live recording saved"
|
|
if cancelled.output_path
|
|
else "cancelled"
|
|
),
|
|
output_path=str(cancelled.output_path or ""),
|
|
finished_at=int(time.time()),
|
|
)
|
|
return
|
|
|
|
else:
|
|
from youtube_stream import (
|
|
CacheJobCancelled,
|
|
build_seekable_music_cache,
|
|
)
|
|
from music import register_cached_youtube_audio
|
|
|
|
try:
|
|
path, duration, _cached = build_seekable_music_cache(
|
|
job["video_id"],
|
|
progress_callback=progress,
|
|
cancel_check=lambda: _cancel_requested(job_id),
|
|
)
|
|
except CacheJobCancelled:
|
|
_update_job(
|
|
job_id,
|
|
status="cancelled",
|
|
progress=0,
|
|
message="cancelled",
|
|
finished_at=int(time.time()),
|
|
)
|
|
return
|
|
|
|
register_cached_youtube_audio(
|
|
video_id=job["video_id"],
|
|
path=path,
|
|
title=job.get("title") or "",
|
|
artist=job.get("artist") or "",
|
|
thumbnail=job.get("thumbnail") or "",
|
|
duration=duration or job.get("duration_seconds"),
|
|
)
|
|
|
|
_update_job(
|
|
job_id,
|
|
status="complete",
|
|
progress=100,
|
|
message=(
|
|
"live recording complete"
|
|
if get_cache_job(job_id).get("is_live")
|
|
else "complete"
|
|
),
|
|
output_path=str(path),
|
|
finished_at=int(time.time()),
|
|
)
|
|
|
|
except Exception as error:
|
|
_update_job(
|
|
job_id,
|
|
status="failed",
|
|
message="failed",
|
|
error=str(error)[:4000],
|
|
finished_at=int(time.time()),
|
|
)
|
|
print(
|
|
"[CACHE] job failed",
|
|
{
|
|
"job_id": job_id,
|
|
"mode": job.get("mode"),
|
|
"video_id": job.get("video_id"),
|
|
"error": str(error),
|
|
},
|
|
flush=True,
|
|
)
|
|
|
|
|
|
def _worker_loop():
|
|
while not _STOP.is_set():
|
|
job = _claim_next_job()
|
|
if not job:
|
|
_STOP.wait(CACHE_JOB_POLL_SECONDS)
|
|
continue
|
|
_run_job(job)
|
|
_prune_jobs()
|
|
|
|
|
|
def start_cache_worker():
|
|
global _WORKER
|
|
if _WORKER and _WORKER.is_alive():
|
|
return
|
|
_STOP.clear()
|
|
_WORKER = threading.Thread(
|
|
target=_worker_loop,
|
|
daemon=True,
|
|
name="media-cache-worker",
|
|
)
|
|
_WORKER.start()
|