# -*- coding: utf-8 -*- """YouTube long-form (16:9) jobs — fully isolated from shorts_* / tiktok_* / x_clip_*.""" from __future__ import annotations import sqlite3 import time import uuid from typing import Any, Optional from .db import _connect, _lock, _row_to_dict from .timeutil import push_date_from_ts # Quota-consuming statuses for daily long-form caps _QUOTA_STATUSES = ("scheduled", "uploading", "uploaded") YT_LONG_DAILY_DEFAULT = 3 YT_LONG_MIN_SEC = 180 # 3 min YT_LONG_MAX_SEC = 480 # 8 min def ensure_yt_long_tables(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TABLE IF NOT EXISTS yt_long_jobs ( id TEXT PRIMARY KEY, room_pk TEXT NOT NULL DEFAULT '', room_id TEXT NOT NULL DEFAULT '', source_url TEXT NOT NULL DEFAULT '', anchor_name TEXT NOT NULL DEFAULT '', stream_url TEXT NOT NULL DEFAULT '', channel_pk TEXT NOT NULL DEFAULT '', shorts_job_id TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'pending', clip_path TEXT NOT NULL DEFAULT '', clip_seconds REAL NOT NULL DEFAULT 0, title TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', youtube_video_id TEXT NOT NULL DEFAULT '', youtube_url TEXT NOT NULL DEFAULT '', error TEXT NOT NULL DEFAULT '', push_date TEXT NOT NULL DEFAULT '', upload_at REAL NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, updated_at REAL NOT NULL, started_at REAL NOT NULL DEFAULT 0, finished_at REAL NOT NULL DEFAULT 0 ) """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_status ON yt_long_jobs(status, created_at)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_date ON yt_long_jobs(push_date, status)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_room_day ON yt_long_jobs(room_id, push_date, status)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_upload ON yt_long_jobs(status, upload_at)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_channel ON yt_long_jobs(channel_pk, push_date)" ) def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: from . import db settings = cfg if cfg is not None else db.get_settings_map() try: v = int(settings.get("yt_long_daily_max") or YT_LONG_DAILY_DEFAULT) except Exception: v = YT_LONG_DAILY_DEFAULT return max(0, min(50, v)) def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int: from . import db settings = cfg if cfg is not None else db.get_settings_map() try: v = int(settings.get("yt_long_channel_daily_max") or 1) except Exception: v = 1 return max(0, min(20, v)) def yt_long_quota_used(push_date: str = "") -> int: day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _QUOTA_STATUSES) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute( f""" SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND status IN ({placeholders}) """, (day, *_QUOTA_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: day = push_date or push_date_from_ts(time.time()) return max(0, yt_long_daily_max(cfg) - yt_long_quota_used(day)) def channel_quota_used(channel_pk: str, push_date: str = "") -> int: day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _QUOTA_STATUSES) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute( f""" SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders}) """, (day, channel_pk, *_QUOTA_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() def has_job_for_room_day(room_id: str, push_date: str) -> bool: if not room_id: return False with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute( """ SELECT 1 FROM yt_long_jobs WHERE room_id = ? AND push_date = ? AND status NOT IN ('failed', 'skipped') LIMIT 1 """, (room_id, push_date), ).fetchone() return bool(row) finally: conn.close() def create_yt_long_job( *, room_pk: str = "", room_id: str = "", source_url: str = "", anchor_name: str = "", stream_url: str = "", channel_pk: str = "", shorts_job_id: str = "", push_date: str = "", ) -> dict[str, Any]: now = time.time() day = push_date or push_date_from_ts(now) jid = str(uuid.uuid4()) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) conn.execute( """ INSERT INTO yt_long_jobs( id, room_pk, room_id, source_url, anchor_name, stream_url, channel_pk, shorts_job_id, status, push_date, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?) """, ( jid, room_pk, room_id, source_url, anchor_name, stream_url, channel_pk, shorts_job_id, day, now, now, ), ) conn.commit() return _row_to_dict( conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (jid,)).fetchone() ) # type: ignore finally: conn.close() def get_yt_long_job(job_id: str) -> dict[str, Any] | None: with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone() return _row_to_dict(row) if row else None finally: conn.close() def update_yt_long_job(job_id: str, **fields: Any) -> dict[str, Any] | None: if not fields: return get_yt_long_job(job_id) allowed = { "status", "clip_path", "clip_seconds", "title", "description", "youtube_video_id", "youtube_url", "error", "channel_pk", "stream_url", "upload_at", "attempts", "started_at", "finished_at", "anchor_name", "source_url", } sets: list[str] = [] params: list[Any] = [] for k, v in fields.items(): if k not in allowed: continue sets.append(f"{k} = ?") params.append(v) if not sets: return get_yt_long_job(job_id) sets.append("updated_at = ?") params.append(time.time()) params.append(job_id) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) conn.execute(f"UPDATE yt_long_jobs SET {', '.join(sets)} WHERE id = ?", params) conn.commit() row = conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone() return _row_to_dict(row) if row else None finally: conn.close() def list_yt_long_jobs(*, limit: int = 40, push_date: str = "") -> list[dict[str, Any]]: day = push_date.strip() with _lock: conn = _connect() try: ensure_yt_long_tables(conn) if day: rows = conn.execute( """ SELECT * FROM yt_long_jobs WHERE push_date = ? ORDER BY created_at DESC LIMIT ? """, (day, max(1, min(int(limit), 200))), ).fetchall() else: rows = conn.execute( """ SELECT * FROM yt_long_jobs ORDER BY created_at DESC LIMIT ? """, (max(1, min(int(limit), 200)),), ).fetchall() return [_row_to_dict(r) for r in rows] finally: conn.close() def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]: with _lock: conn = _connect() try: ensure_yt_long_tables(conn) rows = conn.execute( """ SELECT * FROM yt_long_jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT ? """, (max(1, min(int(limit), 20)),), ).fetchall() return [_row_to_dict(r) for r in rows] finally: conn.close() def claim_yt_long_job_record(job_id: str) -> dict[str, Any] | None: now = time.time() with _lock: conn = _connect() try: ensure_yt_long_tables(conn) cur = conn.execute( """ UPDATE yt_long_jobs SET status = 'recording', started_at = ?, updated_at = ?, attempts = attempts + 1 WHERE id = ? AND status = 'pending' """, (now, now, job_id), ) if cur.rowcount == 0: conn.rollback() return None conn.commit() return _row_to_dict( conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone() ) finally: conn.close() def claim_due_yt_long_upload() -> dict[str, Any] | None: now = time.time() with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute( """ SELECT * FROM yt_long_jobs WHERE status = 'scheduled' AND clip_path != '' AND upload_at > 0 AND upload_at <= ? ORDER BY upload_at ASC, created_at ASC LIMIT 1 """, (now,), ).fetchone() if not row: return None jid = str(row["id"]) cur = conn.execute( """ UPDATE yt_long_jobs SET status = 'uploading', updated_at = ?, attempts = attempts + 1 WHERE id = ? AND status = 'scheduled' """, (now, jid), ) if cur.rowcount == 0: conn.rollback() return None conn.commit() return _row_to_dict( conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (jid,)).fetchone() ) finally: conn.close() def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 900) -> int: cutoff = time.time() - max(120.0, float(max_age_sec)) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) cur = conn.execute( """ UPDATE yt_long_jobs SET status = 'pending', started_at = 0, error = 'recording_stale_reclaim', updated_at = ? WHERE status = 'recording' AND updated_at < ? """, (time.time(), cutoff), ) conn.commit() return int(cur.rowcount or 0) finally: conn.close() def reclaim_stale_yt_long_uploads(*, max_age_sec: float = 1800) -> int: cutoff = time.time() - max(180.0, float(max_age_sec)) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) cur = conn.execute( """ UPDATE yt_long_jobs SET status = 'scheduled', error = 'upload_stale_reclaim', updated_at = ? WHERE status = 'uploading' AND updated_at < ? AND IFNULL(youtube_video_id, '') = '' """, (time.time(), cutoff), ) conn.commit() return int(cur.rowcount or 0) finally: conn.close() def yt_long_stats(push_date: str = "") -> dict[str, Any]: day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _QUOTA_STATUSES) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) rows = conn.execute( """ SELECT status, COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? GROUP BY status """, (day,), ).fetchall() by_status = {str(r["status"]): int(r["c"]) for r in rows} used_row = conn.execute( f""" SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND status IN ({placeholders}) """, (day, *_QUOTA_STATUSES), ).fetchone() return { "push_date": day, "by_status": by_status, "used": int(used_row["c"]) if used_row else 0, } finally: conn.close()