# -*- coding: utf-8 -*- """YouTube long-form (9:16 default) 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 master *recording* (source material) _SOURCE_STATUSES = ( "pending", "recording", "recorded", "scheduled", "uploading", "uploaded", ) # Statuses that count toward YouTube *upload* caps (channel + global) _UPLOAD_STATUSES = ( "scheduled", "uploading", "uploaded", ) # Back-compat alias _QUOTA_STATUSES = _SOURCE_STATUSES YT_LONG_CHANNEL_DEFAULT = 5 # Beijing-day target per channel (normal) YT_LONG_CHANNEL_LIMITED = 4 # when shared YouTube API quota is limited (3 < n < 5) YT_LONG_DAILY_DEFAULT = 70 # 14 channels × 5 YT_LONG_SOURCE_DEFAULT = 70 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_channels ( id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', youtube_channel_id TEXT NOT NULL DEFAULT '', oauth_profile_id TEXT NOT NULL DEFAULT 'A', client_id TEXT NOT NULL DEFAULT '', client_secret TEXT NOT NULL DEFAULT '', refresh_token TEXT NOT NULL DEFAULT '', enabled INTEGER NOT NULL DEFAULT 1, daily_max INTEGER NOT NULL DEFAULT 5, title_template TEXT NOT NULL DEFAULT '{anchor} street food live', description_template TEXT NOT NULL DEFAULT '{anchor}\n{url}\n#StreetFood #Live', privacy TEXT NOT NULL DEFAULT 'public', note TEXT NOT NULL DEFAULT '', source_shorts_channel_pk TEXT NOT NULL DEFAULT '', last_assigned_at REAL NOT NULL DEFAULT 0, oauth_ok INTEGER NOT NULL DEFAULT -1, oauth_checked_at REAL NOT NULL DEFAULT 0, oauth_error TEXT NOT NULL DEFAULT '', created_at REAL NOT NULL, updated_at REAL NOT NULL ) """ ) 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)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_channels_enabled ON yt_long_channels(enabled, last_assigned_at)" ) # YPP / monetization cache (additive; safe on existing DBs) try: cols = {str(r[1]) for r in conn.execute("PRAGMA table_info(yt_long_channels)").fetchall()} except Exception: cols = set() if "ypp_ok" not in cols: try: conn.execute("ALTER TABLE yt_long_channels ADD COLUMN ypp_ok INTEGER NOT NULL DEFAULT -1") except Exception: pass if "ypp_checked_at" not in cols: try: conn.execute("ALTER TABLE yt_long_channels ADD COLUMN ypp_checked_at REAL NOT NULL DEFAULT 0") except Exception: pass if "monetize_default" not in cols: try: conn.execute("ALTER TABLE yt_long_channels ADD COLUMN monetize_default INTEGER NOT NULL DEFAULT 1") except Exception: pass def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: """YouTube long-form *upload* daily cap (not master recording cap).""" 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(200, v)) def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int: """Master recording daily cap — must cover cascade platform needs.""" from . import db settings = cfg if cfg is not None else db.get_settings_map() upload_cap = yt_long_daily_max(settings) try: v = int(settings.get("yt_long_source_daily_max") or 0) except Exception: v = 0 if v <= 0: v = max(upload_cap, YT_LONG_SOURCE_DEFAULT) try: hard = max(42, min(300, int(settings.get("yt_long_source_cap") or 200))) except Exception: hard = 200 return max(upload_cap, min(hard, v)) def youtube_api_upload_limited(cfg: dict[str, Any] | None = None) -> bool: """True when Shorts/yt-long share a YouTube Data API upload freeze for this BJ day.""" from . import db from .shorts_yt_quota import _load_quota_map settings = cfg if cfg is not None else db.get_settings_map() day = push_date_from_ts(time.time()) if str(settings.get("yt_long_quota_limited_day") or "") == day: return True now = time.time() try: for entry in _load_quota_map(settings).values(): if float((entry or {}).get("blocked_until") or 0) > now: return True except Exception: pass return False def mark_yt_long_api_limited(*, reason: str = "") -> None: """Pin BJ-day reduced long-upload caps after a shared YouTube API quota hit.""" from . import db day = push_date_from_ts(time.time()) patch: dict[str, Any] = {"yt_long_quota_limited_day": day} if reason: patch["yt_long_quota_limited_reason"] = str(reason)[:240] try: db.update_settings_map(patch) except Exception: pass def effective_yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int: """Per-channel Beijing-day upload target from operator setting. When shared YouTube API quota is limited, soft-cap at YT_LONG_CHANNEL_LIMITED (never raise above the saved default). """ base = yt_long_channel_daily_max(cfg) if base <= 0: return 0 if youtube_api_upload_limited(cfg): return min(base, YT_LONG_CHANNEL_LIMITED) return base def count_oauth_yt_long_channels(*, enabled_only: bool = True) -> int: rows = list_yt_long_channels(enabled=True if enabled_only else None) n = 0 for ch in rows: if enabled_only and not ch.get("enabled"): continue if str(ch.get("refresh_token") or "").strip(): n += 1 return n def reconcile_yt_long_upload_caps(cfg: dict[str, Any] | None = None) -> dict[str, Any]: """Align global upload cap with per-channel defaults. Respects operator-saved ``yt_long_channel_daily_max`` (and per-channel rows). Does **not** reset the global default back to 5. When API-limited, only clamps channel rows that exceed the effective per-channel cap. """ from . import db settings = cfg if cfg is not None else db.get_settings_map() limited = youtube_api_upload_limited(settings) per = effective_yt_long_channel_daily_max(settings) n = count_oauth_yt_long_channels(enabled_only=True) global_max = max(per, n * per) if n else max(per, YT_LONG_DAILY_DEFAULT) try: stored_global = int(settings.get("yt_long_daily_max") or 0) except Exception: stored_global = 0 if stored_global != global_max: try: db.update_settings_map({"yt_long_daily_max": global_max}) settings = db.get_settings_map() except Exception: pass touched = 0 # Only clamp when API-limited — never force every channel back to a hardcoded 5. if limited and per >= 0: for ch in list_yt_long_channels(enabled=None): if not str(ch.get("refresh_token") or "").strip(): continue try: cur = int(ch.get("daily_max") or 0) except Exception: cur = 0 if cur > per: try: update_yt_long_channel(str(ch.get("id") or ""), daily_max=per) touched += 1 except Exception: pass try: from .clip_cascade import ensure_source_covers_platforms ensure_source_covers_platforms(settings) except Exception: pass return { "ok": True, "limited": limited, "per_channel": per, "channels": n, "daily_max": global_max, "channels_updated": touched, "push_date": push_date_from_ts(time.time()), } 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 YT_LONG_CHANNEL_DEFAULT) except Exception: v = YT_LONG_CHANNEL_DEFAULT return max(0, min(50, v)) def set_yt_long_channel_daily_max( daily_max: int | None = None, *, apply_all: bool = False, enabled_only: bool = True, ) -> dict[str, Any]: """Save global per-channel daily_max default; optionally rewrite all yt_long channel rows.""" from . import db dmax = yt_long_channel_daily_max() if daily_max is None else max(0, min(50, int(daily_max))) db.update_settings_map({"yt_long_channel_daily_max": dmax}) updated = 0 if apply_all: for ch in list_yt_long_channels(enabled=True if enabled_only else None): pk = str(ch.get("id") or "").strip() if not pk: continue if enabled_only and not ch.get("enabled", True): continue try: cur = int(ch.get("daily_max") or 0) except Exception: cur = -1 if cur == dmax: continue try: update_yt_long_channel(pk, daily_max=dmax) updated += 1 except Exception: pass return { "ok": True, "daily_max": dmax, "apply_all": bool(apply_all), "updated_channels": updated, } def room_blocks_yt_long_sample(room_id: str, push_date: str, *, need_upload_slots: bool = False) -> bool: """Room-day dedupe. When YouTube upload slots remain, only block rooms that already have an in-flight job — finished cascade-only / uploaded rooms may be re-sampled so we can catch up channel daily targets with few live sources. """ rid = str(room_id or "").strip() day = push_date or push_date_from_ts(time.time()) if not rid: return True with _lock: conn = _connect() try: ensure_yt_long_tables(conn) if need_upload_slots: row = conn.execute( """ SELECT 1 AS o FROM yt_long_jobs WHERE room_id = ? AND push_date = ? AND status IN ('pending', 'recording', 'scheduled', 'uploading') LIMIT 1 """, (rid, day), ).fetchone() return bool(row) row = conn.execute( """ SELECT 1 AS o FROM yt_long_jobs WHERE room_id = ? AND push_date = ? AND status NOT IN ('failed', 'skipped') LIMIT 1 """, (rid, day), ).fetchone() return bool(row) finally: conn.close() def yt_long_source_used(push_date: str = "") -> int: day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _SOURCE_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, *_SOURCE_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() def yt_long_source_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_source_daily_max(cfg) - yt_long_source_used(day)) def yt_long_upload_used(push_date: str = "") -> int: day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _UPLOAD_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, *_UPLOAD_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() def yt_long_upload_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_upload_used(day)) def yt_long_quota_used(push_date: str = "") -> int: """UI/compat: YouTube upload usage.""" return yt_long_upload_used(push_date) def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int: """UI/compat: YouTube upload remaining.""" return yt_long_upload_gap(push_date, cfg) def channel_quota_used(channel_pk: str, push_date: str = "") -> int: """Per-channel YouTube upload usage (cascade-only masters do not count).""" day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _UPLOAD_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, *_UPLOAD_STATUSES), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() def list_cascade_only_ready(limit: int = 20, push_date: str = "") -> list[dict[str, Any]]: """Recorded masters waiting for a YouTube upload slot.""" day = push_date or push_date_from_ts(time.time()) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) rows = conn.execute( """ SELECT * FROM yt_long_jobs WHERE push_date = ? AND status = 'recorded' AND clip_path != '' AND IFNULL(youtube_video_id, '') = '' AND (upload_at = 0 OR IFNULL(error, '') LIKE 'cascade_only%') ORDER BY created_at ASC LIMIT ? """, (day, max(1, min(100, int(limit)))), ).fetchall() return [_row_to_dict(r) for r in rows] # type: ignore 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) rid = str(room_id or "").strip() if rid: # Only block while another job for this room is actively running. inflight = conn.execute( """ SELECT id FROM yt_long_jobs WHERE room_id = ? AND push_date = ? AND status IN ('pending', 'recording', 'scheduled', 'uploading') ORDER BY created_at DESC LIMIT 1 """, (rid, day), ).fetchone() if inflight: return _row_to_dict( conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (inflight["id"],)).fetchone() ) # type: ignore # Prefer reclaiming a cascade-only dead-end (no clip) over inserting a new row dead = conn.execute( """ SELECT id FROM yt_long_jobs WHERE room_id = ? AND push_date = ? AND status = 'recorded' AND IFNULL(error, '') LIKE 'cascade_only%' AND IFNULL(youtube_video_id, '') = '' ORDER BY created_at DESC LIMIT 1 """, (rid, day), ).fetchone() if dead: conn.execute( """ UPDATE yt_long_jobs SET status = 'pending', error = '', channel_pk = CASE WHEN ? != '' THEN ? ELSE channel_pk END, stream_url = CASE WHEN ? != '' THEN ? ELSE stream_url END, source_url = CASE WHEN ? != '' THEN ? ELSE source_url END, anchor_name = CASE WHEN ? != '' THEN ? ELSE anchor_name END, room_pk = CASE WHEN ? != '' THEN ? ELSE room_pk END, clip_path = '', clip_seconds = 0, upload_at = 0, started_at = 0, finished_at = 0, updated_at = ? WHERE id = ? """, ( str(channel_pk or ""), str(channel_pk or ""), str(stream_url or ""), str(stream_url or ""), str(source_url or ""), str(source_url or ""), str(anchor_name or ""), str(anchor_name or ""), str(room_pk or ""), str(room_pk or ""), now, str(dead["id"]), ), ) conn.commit() return _row_to_dict( conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (dead["id"],)).fetchone() ) # type: ignore 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, rid, 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 j.* FROM yt_long_jobs j INNER JOIN yt_long_channels c ON c.id = j.channel_pk WHERE j.status = 'pending' AND c.enabled = 1 ORDER BY j.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 delete_yt_long_jobs_for_channel(channel_pk: str) -> dict[str, int]: """Delete all yt-long jobs for a channel (keep channel row).""" pk = str(channel_pk or "").strip() if not pk: return {"jobs": 0} with _lock: conn = _connect() try: ensure_yt_long_tables(conn) cur = conn.execute("DELETE FROM yt_long_jobs WHERE channel_pk = ?", (pk,)) conn.commit() return {"jobs": int(cur.rowcount or 0)} 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 j.* FROM yt_long_jobs j INNER JOIN yt_long_channels c ON c.id = j.channel_pk WHERE j.status = 'scheduled' AND c.enabled = 1 AND j.clip_path != '' AND j.upload_at > 0 AND j.upload_at <= ? ORDER BY j.upload_at ASC, j.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 count_yt_long_jobs_by_status(status: str, *, push_date: str = "") -> int: day = push_date or "" with _lock: conn = _connect() try: ensure_yt_long_tables(conn) if day: row = conn.execute( "SELECT COUNT(*) AS c FROM yt_long_jobs WHERE status = ? AND push_date = ?", (status, day), ).fetchone() else: row = conn.execute( "SELECT COUNT(*) AS c FROM yt_long_jobs WHERE status = ?", (status,), ).fetchone() return int(row["c"]) if row else 0 finally: conn.close() def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 720) -> int: """Reclaim orphan recording rows. Never reclaim before ~12 min (3–8 min clip + encode slack).""" age = max(720.0, float(max_age_sec)) cutoff = time.time() - age 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 ( (IFNULL(started_at, 0) > 0 AND started_at < ?) OR (IFNULL(started_at, 0) <= 0 AND updated_at < ?) ) """, (time.time(), cutoff, 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() def list_yt_long_channels(*, enabled: Optional[bool] = None) -> list[dict[str, Any]]: with _lock: conn = _connect() try: ensure_yt_long_tables(conn) if enabled is None: rows = conn.execute( "SELECT * FROM yt_long_channels ORDER BY created_at ASC, name COLLATE NOCASE ASC" ).fetchall() else: rows = conn.execute( """ SELECT * FROM yt_long_channels WHERE enabled = ? ORDER BY created_at ASC, name COLLATE NOCASE ASC """, (1 if enabled else 0,), ).fetchall() return [_row_to_dict(r) for r in rows] finally: conn.close() def get_yt_long_channel(channel_pk: str) -> dict[str, Any] | None: with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute("SELECT * FROM yt_long_channels WHERE id = ?", (channel_pk,)).fetchone() return _row_to_dict(row) if row else None finally: conn.close() def create_yt_long_channel( *, name: str = "", youtube_channel_id: str = "", oauth_profile_id: str = "A", client_id: str = "", client_secret: str = "", refresh_token: str = "", enabled: bool = True, daily_max: int = YT_LONG_CHANNEL_DEFAULT, title_template: str = "", description_template: str = "", privacy: str = "public", note: str = "", source_shorts_channel_pk: str = "", ) -> dict[str, Any]: now = time.time() cid = str(uuid.uuid4()) dmax = max(0, min(50, int(daily_max if daily_max is not None else YT_LONG_CHANNEL_DEFAULT))) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) conn.execute( """ INSERT INTO yt_long_channels( id, name, youtube_channel_id, oauth_profile_id, client_id, client_secret, refresh_token, enabled, daily_max, title_template, description_template, privacy, note, source_shorts_channel_pk, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( cid, (name or "未命名长视频频道").strip()[:120], str(youtube_channel_id or "").strip()[:80], str(oauth_profile_id or "A").strip().upper()[:8] or "A", str(client_id or "").strip(), str(client_secret or "").strip(), str(refresh_token or "").strip(), 1 if enabled else 0, dmax, (title_template or "{anchor} street food live").strip()[:200], (description_template or "").strip()[:2000], privacy if privacy in {"public", "unlisted", "private"} else "public", (note or "").strip()[:200], str(source_shorts_channel_pk or "").strip(), now, now, ), ) conn.commit() return _row_to_dict( conn.execute("SELECT * FROM yt_long_channels WHERE id = ?", (cid,)).fetchone() ) # type: ignore finally: conn.close() def update_yt_long_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: allowed = { "name", "youtube_channel_id", "oauth_profile_id", "client_id", "client_secret", "refresh_token", "enabled", "daily_max", "title_template", "description_template", "privacy", "note", "source_shorts_channel_pk", "last_assigned_at", "oauth_ok", "oauth_checked_at", "oauth_error", "ypp_ok", "ypp_checked_at", "monetize_default", } sets: list[str] = [] params: list[Any] = [] for k, v in fields.items(): if k not in allowed: continue if k == "enabled": v = 1 if v else 0 if k == "monetize_default": v = 1 if v else 0 if k == "ypp_ok": try: v = int(v) except Exception: continue if k == "daily_max": try: v = max(0, min(50, int(v))) except Exception: continue if k == "oauth_profile_id": v = str(v or "A").strip().upper()[:8] or "A" sets.append(f"{k} = ?") params.append(v) if not sets: ch = get_yt_long_channel(channel_pk) if not ch: raise ValueError("频道不存在") return ch sets.append("updated_at = ?") params.append(time.time()) params.append(channel_pk) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) cur = conn.execute(f"UPDATE yt_long_channels SET {', '.join(sets)} WHERE id = ?", params) if cur.rowcount == 0: raise ValueError("频道不存在") conn.commit() return _row_to_dict( conn.execute("SELECT * FROM yt_long_channels WHERE id = ?", (channel_pk,)).fetchone() ) # type: ignore finally: conn.close() def delete_yt_long_channel(channel_pk: str) -> dict[str, int]: """Delete channel + its jobs only (never touches shorts_*).""" with _lock: conn = _connect() try: ensure_yt_long_tables(conn) jobs = conn.execute( "SELECT COUNT(*) AS c FROM yt_long_jobs WHERE channel_pk = ?", (channel_pk,), ).fetchone()["c"] conn.execute("DELETE FROM yt_long_jobs WHERE channel_pk = ?", (channel_pk,)) conn.execute("DELETE FROM yt_long_channels WHERE id = ?", (channel_pk,)) conn.commit() return {"jobs": int(jobs or 0)} finally: conn.close() def sync_channels_from_shorts() -> dict[str, Any]: """Copy/refresh Shorts channel rows into yt_long_channels (Shorts tables never written).""" from . import db created = 0 updated = 0 for ch in db.list_shorts_channels(enabled=None): src = str(ch.get("id") or "") if not src: continue existing_id = "" with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute( "SELECT id, daily_max FROM yt_long_channels WHERE source_shorts_channel_pk = ?", (src,), ).fetchone() if row: existing_id = str(row["id"]) keep_dmax = int(row["daily_max"] or YT_LONG_CHANNEL_DEFAULT) else: keep_dmax = yt_long_channel_daily_max() finally: conn.close() name = str(ch.get("name") or "频道").strip() or "频道" payload = { "name": name, "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), "oauth_profile_id": str(ch.get("oauth_profile_id") or "A"), "client_id": str(ch.get("client_id") or ""), "client_secret": str(ch.get("client_secret") or ""), "refresh_token": str(ch.get("refresh_token") or ""), "enabled": bool(ch.get("enabled", True)), "daily_max": max(YT_LONG_CHANNEL_DEFAULT, keep_dmax) if not existing_id else keep_dmax, "privacy": str(ch.get("privacy") or "public"), "note": f"synced from shorts:{src}", "source_shorts_channel_pk": src, } if existing_id: # Refresh OAuth + identity only — never overwrite local enabled/daily_max/templates update_yt_long_channel( existing_id, name=payload["name"], youtube_channel_id=payload["youtube_channel_id"], oauth_profile_id=payload["oauth_profile_id"], client_id=payload["client_id"], client_secret=payload["client_secret"], refresh_token=payload["refresh_token"], privacy=payload["privacy"], note=payload["note"], ) updated += 1 else: create_yt_long_channel( name=payload["name"], youtube_channel_id=payload["youtube_channel_id"], oauth_profile_id=payload["oauth_profile_id"], client_id=payload["client_id"], client_secret=payload["client_secret"], refresh_token=payload["refresh_token"], enabled=payload["enabled"], daily_max=payload["daily_max"], title_template="", description_template="", privacy=payload["privacy"], note=payload["note"], source_shorts_channel_pk=src, ) created += 1 return {"created": created, "updated": updated, "total": created + updated} def import_channels_from_shorts() -> dict[str, Any]: """Alias — always full sync (copy) from Shorts.""" return sync_channels_from_shorts() def ypp_ok_by_shorts_pk() -> dict[str, int]: """Map shorts channel pk -> yt_long ypp_ok (-1/0/1).""" out: dict[str, int] = {} with _lock: conn = _connect() try: ensure_yt_long_tables(conn) for row in conn.execute( "SELECT source_shorts_channel_pk, ypp_ok FROM yt_long_channels WHERE source_shorts_channel_pk != ''" ).fetchall(): pk = str(row["source_shorts_channel_pk"] or "").strip() if not pk: continue try: out[pk] = int(row["ypp_ok"] if row["ypp_ok"] is not None else -1) except Exception: out[pk] = -1 finally: conn.close() return out def get_yt_long_by_shorts_pk(shorts_pk: str) -> dict[str, Any] | None: pk = str(shorts_pk or "").strip() if not pk: return None with _lock: conn = _connect() try: ensure_yt_long_tables(conn) row = conn.execute( "SELECT * FROM yt_long_channels WHERE source_shorts_channel_pk = ? LIMIT 1", (pk,), ).fetchone() return dict(row) if row else None finally: conn.close() def public_yt_long_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: if not ch: return None out = dict(ch) rt = str(out.get("refresh_token") or "") cs = str(out.get("client_secret") or "") out["has_refresh_token"] = bool(rt.strip()) out["authorized"] = bool(rt.strip()) out["has_client_secret"] = bool(cs.strip()) out["refresh_token"] = ("***" + rt[-4:]) if len(rt) > 8 else ("***" if rt else "") out["client_secret"] = "***" if cs else "" return out def channel_board(push_date: str = "") -> dict[str, Any]: day = push_date or push_date_from_ts(time.time()) placeholders = ",".join("?" for _ in _UPLOAD_STATUSES) channels = list_yt_long_channels(enabled=None) board: list[dict[str, Any]] = [] total_gap = 0 from . import db as _db from . import youtube_manage shorts_profile_by_pk = youtube_manage.list_yt_profile_caches() shorts_by_pk: dict[str, dict[str, Any]] = { str(c.get("id") or ""): c for c in _db.list_shorts_channels(enabled=None) if c.get("id") } shorts_by_yt_id: dict[str, dict[str, Any]] = {} for sch in _db.list_shorts_channels(enabled=None): yid = str(sch.get("youtube_channel_id") or "").strip() if not yid: continue sn = youtube_manage._snippet_from_channel_row(sch) if sn: shorts_by_yt_id[yid] = sn with _lock: conn = _connect() try: ensure_yt_long_tables(conn) for ch in channels: cid = str(ch.get("id") or "") dmax = max(0, int(ch.get("daily_max") or 0)) used_row = conn.execute( f""" SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders}) """, (day, cid, *_UPLOAD_STATUSES), ).fetchone() used = int(used_row["c"]) if used_row else 0 by = { str(r["status"]): int(r["c"]) for r in conn.execute( """ SELECT status, COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND channel_pk = ? GROUP BY status """, (day, cid), ).fetchall() } gap = max(0, dmax - used) if ch.get("enabled") else 0 total_gap += gap try: ypp_ok = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1) except Exception: ypp_ok = -1 src_pk = str(ch.get("source_shorts_channel_pk") or "").strip() yid = str(ch.get("youtube_channel_id") or "").strip() yt_profile = None if src_pk and src_pk in shorts_profile_by_pk: yt_profile = shorts_profile_by_pk[src_pk] elif yid and yid in shorts_by_yt_id: yt_profile = shorts_by_yt_id[yid] oauth_row = ch if src_pk and src_pk in shorts_by_pk: sch = shorts_by_pk[src_pk] if str(sch.get("refresh_token") or "").strip(): oauth_row = sch oauth_meta: dict[str, Any] = {} try: from .yt_channel_meta import oauth_meta_from_channel oauth_meta = oauth_meta_from_channel(oauth_row) except Exception: oauth_meta = {} board.append( { "id": cid, "name": ch.get("name"), "youtube_channel_id": ch.get("youtube_channel_id"), "oauth_profile_id": oauth_meta.get("oauth_profile_id") or ch.get("oauth_profile_id"), "source_shorts_channel_pk": src_pk, "enabled": bool(ch.get("enabled")), "authorized": bool( oauth_meta.get("authorized") if oauth_meta else str(ch.get("refresh_token") or "").strip() ), "daily_max": dmax, "used": used, "gap": gap, "uploaded": int(by.get("uploaded") or 0), "scheduled": int(by.get("scheduled") or 0) + int(by.get("uploading") or 0), "pending": int(by.get("pending") or 0) + int(by.get("recording") or 0), "failed": int(by.get("failed") or 0), "oauth_ok": oauth_meta.get("oauth_ok", ch.get("oauth_ok")), "oauth_error": oauth_meta.get("oauth_error", ch.get("oauth_error") or ""), "brand_hint": oauth_meta.get("brand_hint") or "", "note": str(oauth_row.get("note") or ch.get("note") or ""), "ypp_ok": ypp_ok, "monetize_default": bool(int(ch.get("monetize_default") if ch.get("monetize_default") is not None else 1)), "yt_profile": yt_profile, } ) finally: conn.close() return {"push_date": day, "channels": board, "total_gap": total_gap} def list_yt_long_jobs_page( *, status: str = "", push_date: str = "", channel_pk: str = "", limit: int = 50, offset: int = 0, ) -> dict[str, Any]: clauses: list[str] = [] params: list[Any] = [] if status.strip(): clauses.append("status = ?") params.append(status.strip()) if push_date.strip(): clauses.append("push_date = ?") params.append(push_date.strip()) if channel_pk.strip(): clauses.append("channel_pk = ?") params.append(channel_pk.strip()) where = ("WHERE " + " AND ".join(clauses)) if clauses else "" lim = max(1, min(int(limit), 200)) off = max(0, int(offset)) with _lock: conn = _connect() try: ensure_yt_long_tables(conn) total = conn.execute(f"SELECT COUNT(*) AS c FROM yt_long_jobs {where}", params).fetchone()["c"] rows = conn.execute( f""" SELECT * FROM yt_long_jobs {where} ORDER BY created_at DESC LIMIT ? OFFSET ? """, [*params, lim, off], ).fetchall() return { "jobs": [_row_to_dict(r) for r in rows], "total": int(total), "limit": lim, "offset": off, } finally: conn.close() def list_yt_long_events(*, limit: int = 50, offset: int = 0) -> dict[str, Any]: """Read events with kind prefix yt_long_ — does not purge/alter other kinds.""" lim = max(1, min(int(limit), 200)) off = max(0, int(offset)) with _lock: conn = _connect() try: total = conn.execute( "SELECT COUNT(*) AS c FROM events WHERE kind LIKE 'yt_long%'" ).fetchone()["c"] rows = conn.execute( """ SELECT * FROM events WHERE kind LIKE 'yt_long%' ORDER BY ts DESC LIMIT ? OFFSET ? """, (lim, off), ).fetchall() return { "events": [_row_to_dict(r) for r in rows], "total": int(total), "limit": lim, "offset": off, } finally: conn.close()