from __future__ import annotations import os import sqlite3 import threading import time from pathlib import Path from dotenv import load_dotenv from twitch_stream import ( TwitchOffline, probe_twitch, record_twitch, normalize_twitch_url, ) 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() TWITCH_WATCH_INTERVAL = max( 10, int(os.getenv("TWITCH_WATCH_INTERVAL", "30")), ) _THREAD = None _STOP = threading.Event() _RECORD_THREADS = {} _RECORD_LOCK = threading.Lock() def _db(): db = sqlite3.connect(DB_PATH, timeout=30) db.row_factory = sqlite3.Row return db def init_twitch_db(): with _db() as db: db.executescript(""" CREATE TABLE IF NOT EXISTS twitch_channels ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, url TEXT NOT NULL, channel_name TEXT NOT NULL, quality TEXT NOT NULL DEFAULT 'best', auto_record INTEGER NOT NULL DEFAULT 0, enabled INTEGER NOT NULL DEFAULT 1, live INTEGER NOT NULL DEFAULT 0, stream_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '', author TEXT NOT NULL DEFAULT '', category TEXT NOT NULL DEFAULT '', available_qualities TEXT NOT NULL DEFAULT '', last_checked_at INTEGER, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, UNIQUE(user_id, channel_name) ); CREATE TABLE IF NOT EXISTS twitch_recordings ( id INTEGER PRIMARY KEY AUTOINCREMENT, channel_id INTEGER NOT NULL, user_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'queued', message TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '', stream_id TEXT NOT NULL DEFAULT '', output_path TEXT NOT NULL DEFAULT '', error TEXT NOT NULL DEFAULT '', cancel_requested INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER ); CREATE INDEX IF NOT EXISTS idx_twitch_recordings_status ON twitch_recordings(status, created_at); """) db.execute( """UPDATE twitch_recordings SET status='failed', message='interrupted by service restart', error='Recording was interrupted by Media Server restart.', finished_at=? WHERE status='recording'""", (int(time.time()),), ) db.commit() def add_channel(user_id: int, value: str, quality: str = "best"): url, channel = normalize_twitch_url(value) now = int(time.time()) with _db() as db: row = db.execute( "SELECT id FROM twitch_channels WHERE user_id=? AND channel_name=?", (int(user_id), channel.lower()), ).fetchone() if row: channel_id = int(row["id"]) db.execute( """UPDATE twitch_channels SET url=?, quality=?, enabled=1, updated_at=? WHERE id=?""", (url, quality or "best", now, channel_id), ) else: cur = db.execute( """INSERT INTO twitch_channels( user_id,url,channel_name,quality,created_at,updated_at ) VALUES(?,?,?,?,?,?)""", ( int(user_id), url, channel.lower(), quality or "best", now, now, ), ) channel_id = int(cur.lastrowid) db.commit() refresh_channel(user_id, channel_id) return get_channel(user_id, channel_id) def get_channel(user_id: int, channel_id: int): with _db() as db: row = db.execute( "SELECT * FROM twitch_channels WHERE id=? AND user_id=?", (int(channel_id), int(user_id)), ).fetchone() return dict(row) if row else None def list_channels(user_id: int): with _db() as db: rows = db.execute( """SELECT * FROM twitch_channels WHERE user_id=? ORDER BY channel_name""", (int(user_id),), ).fetchall() return [dict(row) for row in rows] def delete_channel(user_id: int, channel_id: int): channel = get_channel(user_id, channel_id) if not channel: return False active = active_recording_for_channel(channel_id) if active: raise ValueError("Stop the active recording before removing this channel.") with _db() as db: db.execute( "DELETE FROM twitch_channels WHERE id=? AND user_id=?", (int(channel_id), int(user_id)), ) db.commit() return True def set_auto_record(user_id: int, channel_id: int, enabled: bool): with _db() as db: cur = db.execute( """UPDATE twitch_channels SET auto_record=?,updated_at=? WHERE id=? AND user_id=?""", ( 1 if enabled else 0, int(time.time()), int(channel_id), int(user_id), ), ) db.commit() if cur.rowcount != 1: raise ValueError("Twitch channel not found.") return get_channel(user_id, channel_id) def set_quality(user_id: int, channel_id: int, quality: str): quality = str(quality or "best").strip() or "best" with _db() as db: cur = db.execute( """UPDATE twitch_channels SET quality=?,updated_at=? WHERE id=? AND user_id=?""", ( quality, int(time.time()), int(channel_id), int(user_id), ), ) db.commit() if cur.rowcount != 1: raise ValueError("Twitch channel not found.") return get_channel(user_id, channel_id) def refresh_channel(user_id: int, channel_id: int): channel = get_channel(user_id, channel_id) if not channel: raise ValueError("Twitch channel not found.") status = probe_twitch( channel["url"], quality=channel.get("quality") or "best", ) now = int(time.time()) qualities = ",".join(status.get("available_qualities") or []) with _db() as db: db.execute( """UPDATE twitch_channels SET live=?, stream_id=?, title=?, author=?, category=?, available_qualities=?, last_checked_at=?, updated_at=? WHERE id=?""", ( 1 if status.get("live") else 0, str(status.get("stream_id") or ""), str(status.get("title") or ""), str(status.get("author") or ""), str(status.get("category") or ""), qualities, now, now, int(channel_id), ), ) db.commit() return get_channel(user_id, channel_id) def list_recordings(user_id: int, limit=50): with _db() as db: rows = db.execute( """SELECT r.*,c.channel_name,c.url,c.quality FROM twitch_recordings r JOIN twitch_channels c ON c.id=r.channel_id WHERE r.user_id=? ORDER BY r.id DESC LIMIT ?""", (int(user_id), max(1, min(int(limit), 200))), ).fetchall() return [dict(row) for row in rows] def active_recording_for_channel(channel_id: int): with _db() as db: row = db.execute( """SELECT * FROM twitch_recordings WHERE channel_id=? AND status IN ('queued','recording') ORDER BY id DESC LIMIT 1""", (int(channel_id),), ).fetchone() return dict(row) if row else None def enqueue_recording(user_id: int, channel_id: int): channel = get_channel(user_id, channel_id) if not channel: raise ValueError("Twitch channel not found.") existing = active_recording_for_channel(channel_id) if existing: return existing now = int(time.time()) with _db() as db: cur = db.execute( """INSERT INTO twitch_recordings( channel_id,user_id,status,message,created_at ) VALUES(?,?,'queued','checking Twitch stream…',?)""", (int(channel_id), int(user_id), now), ) job_id = int(cur.lastrowid) db.commit() _start_record_thread(job_id) return get_recording(user_id, job_id) def get_recording(user_id: int, job_id: int): with _db() as db: row = db.execute( "SELECT * FROM twitch_recordings WHERE id=? AND user_id=?", (int(job_id), int(user_id)), ).fetchone() return dict(row) if row else None def stop_recording(user_id: int, job_id: int): with _db() as db: row = db.execute( "SELECT * FROM twitch_recordings WHERE id=? AND user_id=?", (int(job_id), int(user_id)), ).fetchone() if not row: raise ValueError("Twitch recording job not found.") if row["status"] in {"complete", "failed", "cancelled"}: return dict(row) db.execute( """UPDATE twitch_recordings SET cancel_requested=1, message='stopping recording…' WHERE id=?""", (int(job_id),), ) db.commit() return get_recording(user_id, job_id) def clear_finished_recordings(user_id: int): with _db() as db: cur = db.execute( """DELETE FROM twitch_recordings WHERE user_id=? AND status IN ('complete','failed','cancelled')""", (int(user_id),), ) db.commit() return int(cur.rowcount or 0) def _cancel_requested(job_id: int): with _db() as db: row = db.execute( "SELECT cancel_requested FROM twitch_recordings WHERE id=?", (int(job_id),), ).fetchone() return bool(row and row["cancel_requested"]) def _update_recording(job_id: int, **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 twitch_recordings SET {', '.join(sets)} WHERE id=?", args, ) db.commit() def _record_worker(job_id: int): try: with _db() as db: job = db.execute( "SELECT * FROM twitch_recordings WHERE id=?", (int(job_id),), ).fetchone() if not job: return channel = db.execute( "SELECT * FROM twitch_channels WHERE id=?", (int(job["channel_id"]),), ).fetchone() if not channel: raise RuntimeError("Twitch channel was removed.") try: status = refresh_channel( int(job["user_id"]), int(job["channel_id"]), ) except Exception as error: raise RuntimeError(f"Could not refresh Twitch channel: {error}") from error if not status.get("live"): _update_recording( job_id, status="failed", message="channel is offline", error=f"{status.get('channel_name') or 'Channel'} is not live.", finished_at=int(time.time()), ) return _update_recording( job_id, status="recording", message="recording live · 00:00:00", title=status.get("title") or "", stream_id=status.get("stream_id") or "", started_at=int(time.time()), ) def progress(message): _update_recording(job_id, message=message) result = record_twitch( status["url"], quality=status.get("quality") or "best", stop_check=lambda: _cancel_requested(job_id), progress_callback=progress, ) cancelled = _cancel_requested(job_id) _update_recording( job_id, status="cancelled" if cancelled else "complete", message="recording saved" if cancelled else "complete", output_path=result.get("output_path") or "", finished_at=int(time.time()), ) except Exception as error: _update_recording( job_id, status="failed", message="failed", error=str(error)[:4000], finished_at=int(time.time()), ) print( "[TWITCH] recording failed", {"job_id": job_id, "error": str(error)}, flush=True, ) finally: with _RECORD_LOCK: _RECORD_THREADS.pop(int(job_id), None) def _start_record_thread(job_id: int): with _RECORD_LOCK: existing = _RECORD_THREADS.get(int(job_id)) if existing and existing.is_alive(): return thread = threading.Thread( target=_record_worker, args=(int(job_id),), daemon=True, name=f"twitch-record-{job_id}", ) _RECORD_THREADS[int(job_id)] = thread thread.start() def _watch_loop(): while not _STOP.is_set(): try: with _db() as db: rows = db.execute( """SELECT * FROM twitch_channels WHERE enabled=1 AND auto_record=1 ORDER BY id""" ).fetchall() for row in rows: if _STOP.is_set(): break channel = dict(row) try: refreshed = refresh_channel( int(channel["user_id"]), int(channel["id"]), ) if refreshed.get("live"): active = active_recording_for_channel( int(channel["id"]) ) if not active: enqueue_recording( int(channel["user_id"]), int(channel["id"]), ) except Exception as error: print( "[TWITCH] watcher check failed", { "channel": channel.get("channel_name"), "error": str(error), }, flush=True, ) if _STOP.wait(0.5): break except Exception as error: print("[TWITCH] watcher error:", error, flush=True) _STOP.wait(TWITCH_WATCH_INTERVAL) def start_twitch_watcher(): global _THREAD if _THREAD and _THREAD.is_alive(): return _STOP.clear() _THREAD = threading.Thread( target=_watch_loop, daemon=True, name="twitch-live-watcher", ) _THREAD.start()