"""Persistent scheduled recording queue shared by Twitch and YouTube. The worker uses the media application's SQLite database and runs even when no browser is open. UTC timestamps avoid client/server timezone ambiguity. """ from __future__ import annotations import os import sqlite3 import threading import time from datetime import datetime, timezone from pathlib import Path DB_PATH = Path(os.getenv('DB_PATH', str(Path(__file__).resolve().parent / 'media_library.db'))).expanduser().resolve() _LOCK = threading.Lock() _THREAD = None _STOP = threading.Event() def _db(): connection = sqlite3.connect(DB_PATH, timeout=30) connection.row_factory = sqlite3.Row return connection def initialize(): with _db() as db: db.execute('''CREATE TABLE IF NOT EXISTS scheduled_recordings ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, provider TEXT NOT NULL, media_key TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', start_at INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'scheduled', message TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL )''') db.execute('CREATE INDEX IF NOT EXISTS idx_scheduled_recordings_due ON scheduled_recordings(status,start_at)') db.commit() def schedule(user_id, provider, media_key, start_at, title=''): if provider not in {'twitch', 'youtube'}: raise ValueError('Unsupported recording type') key = str(media_key or '').strip() if not key: raise ValueError('Channel ID or video ID is required') try: start = datetime.fromisoformat(str(start_at).replace('Z', '+00:00')) if start.tzinfo is None: raise ValueError('Recording time must include a timezone') timestamp = int(start.timestamp()) except (TypeError, ValueError) as exc: raise ValueError('Enter a valid date and time with timezone') from exc now = int(time.time()) if timestamp < now + 15 or timestamp > now + 366 * 86400: raise ValueError('Scheduled time must be at least 15 seconds away and within one year') if provider == 'twitch': from twitch_jobs import get_channel if get_channel(int(user_id), int(key)) is None: raise ValueError('Twitch channel is unavailable to this account') else: import re if not re.fullmatch(r'[A-Za-z0-9_-]{11}', key): raise ValueError('YouTube recording requires a valid video ID') with _db() as db: cursor = db.execute('''INSERT INTO scheduled_recordings (user_id,provider,media_key,title,start_at,created_at) VALUES (?,?,?,?,?,?)''', (int(user_id), provider, key, str(title or '')[:300], timestamp, now)) db.commit() return {'id':cursor.lastrowid, 'status':'scheduled', 'start_at':timestamp} def list_jobs(user_id): with _db() as db: return [dict(row) for row in db.execute('''SELECT * FROM scheduled_recordings WHERE user_id=? ORDER BY start_at DESC LIMIT 80''', (int(user_id),))] def cancel(user_id, job_id): with _db() as db: cursor = db.execute("UPDATE scheduled_recordings SET status='cancelled' WHERE id=? AND user_id=? AND status='scheduled'",(int(job_id),int(user_id))) db.commit() if not cursor.rowcount: raise ValueError('No pending scheduled recording found') return {'cancelled':True} def _execute(job): if job['provider'] == 'twitch': from twitch_jobs import enqueue_recording enqueue_recording(job['user_id'], int(job['media_key'])) else: from cache_jobs import enqueue_cache_job enqueue_cache_job(user_id=job['user_id'], video_id=job['media_key'], mode='video', title=job['title']) def _tick(): now = int(time.time()) with _LOCK: with _db() as db: due=[dict(row) for row in db.execute('''SELECT * FROM scheduled_recordings WHERE status='scheduled' AND start_at<=? ORDER BY start_at LIMIT 15''',(now,))] for job in due: db.execute("UPDATE scheduled_recordings SET status='dispatching' WHERE id=? AND status='scheduled'", (job['id'],)) db.commit() for job in due: try: _execute(job) status, message='started','Recording job dispatched' except Exception as exc: status, message='failed',str(exc)[:400] with _db() as db: db.execute('UPDATE scheduled_recordings SET status=?,message=? WHERE id=?', (status,message,job['id'])) db.commit() def start(): global _THREAD initialize() with _db() as db: # A service restart during dispatch leaves the state visible and retryable. db.execute("UPDATE scheduled_recordings SET status='scheduled' WHERE status='dispatching'") db.commit() if _THREAD and _THREAD.is_alive(): return def worker(): while not _STOP.is_set(): try: _tick() except Exception as exc: print('[SCHEDULE] Worker error:',exc,flush=True) _STOP.wait(10) _THREAD=threading.Thread(target=worker, daemon=True,name='kronic-recording-schedule') _THREAD.start()