# -*- coding: utf-8 -*- """YouTube Data API upload counters — per OAuth Client profile (A/B/C/D). Counters are display-only. This module must NEVER gate manual or worker uploads; YouTube API 429 responses are the sole authority. Client A exhaustion must NOT pause Client B either. """ from __future__ import annotations import time from typing import Any from . import db from .shorts_upload import quota_error_message from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90 QUOTA_MAP_KEY = "shorts_yt_quota_by_profile" def normalize_profile_id(raw: Any) -> str: pid = str(raw or "").strip().upper() return pid or "A" def profile_id_for_channel(channel: dict[str, Any] | None) -> str: return normalize_profile_id((channel or {}).get("oauth_profile_id")) def profile_id_for_job(job: dict[str, Any] | None) -> str: job = job or {} ch = db.get_shorts_channel(str(job.get("channel_pk") or "")) if ch: return profile_id_for_channel(ch) return normalize_profile_id(job.get("oauth_profile_id")) def yt_daily_limit(cfg: dict[str, Any] | None = None) -> int: settings = cfg if cfg is not None else db.get_settings_map() return max(1, int(settings.get("shorts_yt_daily_upload_limit") or YT_DAILY_UPLOAD_LIMIT_DEFAULT)) def _empty_entry() -> dict[str, Any]: return {"date": "", "count": 0, "blocked_until": 0.0} def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]: raw = cfg.get(QUOTA_MAP_KEY) out: dict[str, dict[str, Any]] = {} if isinstance(raw, dict): for k, v in raw.items(): pid = normalize_profile_id(k) if not isinstance(v, dict): continue out[pid] = { "date": str(v.get("date") or ""), "count": int(v.get("count") or 0), "blocked_until": float(v.get("blocked_until") or 0), } # One-time migrate legacy global counters into profile A if map empty if not out: legacy_until = float(cfg.get("shorts_yt_upload_blocked_until") or 0) legacy_date = str(cfg.get("shorts_yt_uploads_pt_date") or "") legacy_count = int(cfg.get("shorts_yt_uploads_pt_count") or 0) if legacy_date or legacy_count or legacy_until > time.time(): out["A"] = { "date": legacy_date, "count": legacy_count, "blocked_until": legacy_until if legacy_until > time.time() else 0.0, } return out def _save_quota_map(quota_map: dict[str, dict[str, Any]]) -> None: try: db.update_settings_map( { QUOTA_MAP_KEY: quota_map, # Clear legacy global block so it cannot freeze all profiles "shorts_yt_upload_blocked_until": 0, } ) except Exception: pass def _count_uploads_from_db_pt_day(profile_id: str, day: str = "") -> int: """Count upload API uses in the Pacific day for channels on this profile.""" pid = normalize_profile_id(profile_id) pt_day = day or pacific_day_from_ts(time.time()) start, end = pacific_day_bounds(pt_day) with db._lock: conn = db._connect() try: # Channels on this profile (empty profile_id counts as A) if pid == "A": ch_rows = conn.execute( """ SELECT id FROM shorts_channels WHERE UPPER(TRIM(oauth_profile_id)) = 'A' OR TRIM(oauth_profile_id) = '' OR oauth_profile_id IS NULL """ ).fetchall() else: ch_rows = conn.execute( """ SELECT id FROM shorts_channels WHERE UPPER(TRIM(oauth_profile_id)) = ? """, (pid,), ).fetchall() ch_ids = [str(r["id"]) for r in ch_rows] if not ch_ids: return 0 placeholders = ",".join("?" for _ in ch_ids) row = conn.execute( f""" SELECT COUNT(*) AS c FROM shorts_jobs WHERE youtube_video_id != '' AND finished_at >= ? AND finished_at < ? AND channel_pk IN ({placeholders}) """, (start, end, *ch_ids), ).fetchone() uploaded = int(row["c"] if row else 0) row2 = conn.execute( f""" SELECT COUNT(*) AS c FROM shorts_jobs WHERE status = 'uploading' AND clip_path != '' AND youtube_video_id = '' AND channel_pk IN ({placeholders}) """, tuple(ch_ids), ).fetchone() in_flight = int(row2["c"] if row2 else 0) row3 = conn.execute( f""" SELECT COUNT(*) AS c FROM shorts_jobs WHERE status IN ('failed', 'scheduled') AND error LIKE '%429%' AND updated_at >= ? AND updated_at < ? AND channel_pk IN ({placeholders}) """, (start, end, *ch_ids), ).fetchone() quota_fails = int(row3["c"] if row3 else 0) return uploaded + in_flight + quota_fails finally: conn.close() def _sync_profile_entry( profile_id: str, cfg: dict[str, Any], quota_map: dict[str, dict[str, Any]], ) -> dict[str, Any]: pid = normalize_profile_id(profile_id) entry = dict(quota_map.get(pid) or _empty_entry()) pt_day = pacific_day_from_ts(time.time()) stored_day = str(entry.get("date") or "") stored_count = int(entry.get("count") or 0) blocked_until = float(entry.get("blocked_until") or 0) if blocked_until and blocked_until <= time.time(): blocked_until = 0.0 if stored_day != pt_day: db_count = _count_uploads_from_db_pt_day(pid, pt_day) stored_count = max(stored_count, db_count) if stored_day else db_count stored_day = pt_day # New Pacific day clears block blocked_until = 0.0 entry = {"date": stored_day, "count": stored_count, "blocked_until": blocked_until} quota_map[pid] = entry return entry def yt_upload_budget( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", ) -> tuple[int, int, int]: """Return (limit, used, remaining) for one OAuth Client profile.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) limit = yt_daily_limit(settings) quota_map = _load_quota_map(settings) entry = _sync_profile_entry(profile_id, settings, quota_map) # Persist day roll if needed if settings.get(QUOTA_MAP_KEY) != quota_map: _save_quota_map(quota_map) settings[QUOTA_MAP_KEY] = quota_map used = int(entry.get("count") or 0) remaining = max(0, limit - used) return limit, used, remaining def note_yt_upload_attempt( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", ) -> None: """UI counter only — never gates uploads. YouTube API is the sole authority.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) pid = normalize_profile_id(profile_id) quota_map = _load_quota_map(settings) entry = _sync_profile_entry(pid, settings, quota_map) entry["count"] = int(entry.get("count") or 0) + 1 entry["date"] = pacific_day_from_ts(time.time()) entry["blocked_until"] = 0.0 quota_map[pid] = entry _save_quota_map(quota_map) def reserve_yt_upload_slot( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", ) -> bool: """Always allow. Local 90-count is informational only — never refuse uploads.""" note_yt_upload_attempt(cfg, profile_id=profile_id) return True def project_uploads_available( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", ) -> bool: """Never self-block. Local budget is display-only.""" _ = cfg, profile_id return True def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool: _ = cfg return True def profile_upload_blocked( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", ) -> tuple[bool, float]: """Self-imposed pause removed: always unblocked. Clears stale blocked_until.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) pid = normalize_profile_id(profile_id) quota_map = _load_quota_map(settings) entry = _sync_profile_entry(pid, settings, quota_map) if float(entry.get("blocked_until") or 0) > 0: entry["blocked_until"] = 0.0 quota_map[pid] = entry _save_quota_map(quota_map) return False, 0.0 def blocked_profile_ids(cfg: dict[str, Any] | None = None) -> set[str]: """No local upload pause — never skip profiles in the worker.""" _ = cfg return set() def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]: settings = dict(cfg if cfg is not None else db.get_settings_map()) profiles = ["A", "B", "C", "D"] seen = set(profiles) for ch in db.list_shorts_channels(enabled=None): pid = profile_id_for_channel(ch) if pid not in seen: profiles.append(pid) seen.add(pid) rows = [] for pid in profiles: limit, used, remaining = yt_upload_budget(settings, profile_id=pid) # Clear any legacy self-pause; never report blocked for local enforcement profile_upload_blocked(settings, profile_id=pid) rows.append( { "id": pid, "limit": limit, "used": used, "remaining": remaining, "exhausted_hint": used >= limit, "blocked": False, "blocked_until": 0.0, "reset_at": next_youtube_quota_reset_ts() if used >= limit else 0.0, } ) return rows def channel_ids_for_profile(profile_id: str) -> list[str]: pid = normalize_profile_id(profile_id) ids: list[str] = [] for ch in db.list_shorts_channels(enabled=None): if profile_id_for_channel(ch) == pid: ids.append(str(ch["id"])) return ids def pause_uploads_until_reset( cfg: dict[str, Any] | None = None, *, profile_id: str = "A", reason: str = "", ) -> float: """Legacy no-op: do NOT self-pause or defer jobs. Snap UI counter only.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) pid = normalize_profile_id(profile_id) until = next_youtube_quota_reset_ts() quota_map = _load_quota_map(settings) entry = _sync_profile_entry(pid, settings, quota_map) entry["blocked_until"] = 0.0 limit = yt_daily_limit(settings) entry["count"] = max(int(entry.get("count") or 0), limit) entry["date"] = pacific_day_from_ts(time.time()) quota_map[pid] = entry _save_quota_map(quota_map) _ = reason return until def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int: """No-op: never bulk-defer uploads for a Client. Manual upload must stay free.""" _ = profile_id, until_ts, reason return 0 def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int: """No-op: keep YouTube API error text on jobs for operator feedback.""" _ = cfg return 0 def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]: """No-op: never auto-pause Clients from local counters or past 429s.""" _ = cfg return {} def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None: """Wipe legacy blocked_until / global pause so uploads are never locally gated.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) quota_map = _load_quota_map(settings) changed = False for pid, entry in list(quota_map.items()): if float(entry.get("blocked_until") or 0) != 0: entry = dict(entry) entry["blocked_until"] = 0.0 quota_map[pid] = entry changed = True if changed or float(settings.get("shorts_yt_upload_blocked_until") or 0) > 0: _save_quota_map(quota_map) # Back-compat aliases used by older call sites (treat as profile A) def pause_uploads_until_reset_global(cfg: dict[str, Any] | None = None, *, reason: str = "") -> float: return pause_uploads_until_reset(cfg, profile_id="A", reason=reason)