Include latest server fixes for yt-long/disk/ops and related frontend. Exclude .bak scratch files.
1653 lines
59 KiB
Python
1653 lines
59 KiB
Python
# -*- 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 = 480 # 8 min
|
||
YT_LONG_MAX_SEC = 900 # 15 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_enabled_upload_cap(cfg: dict[str, Any] | None = None) -> int:
|
||
"""Sum of daily_max for enabled oauth yt_long channels (authoritative upload/master cap)."""
|
||
per = effective_yt_long_channel_daily_max(cfg)
|
||
total = 0
|
||
n = 0
|
||
for ch in list_yt_long_channels(enabled=True):
|
||
if not ch.get("enabled", True):
|
||
continue
|
||
if not str(ch.get("refresh_token") or "").strip():
|
||
continue
|
||
n += 1
|
||
try:
|
||
row_max = int(ch.get("daily_max") or 0)
|
||
except Exception:
|
||
row_max = 0
|
||
if row_max <= 0:
|
||
row_max = per
|
||
# Soft API limit: never count above effective per-channel cap.
|
||
total += min(row_max, per) if per > 0 else row_max
|
||
if n <= 0:
|
||
return max(0, per)
|
||
return max(0, total)
|
||
|
||
|
||
def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||
"""Master recording daily cap — equals enabled long-upload quota (not Shorts fleet)."""
|
||
from . import db
|
||
|
||
settings = cfg if cfg is not None else db.get_settings_map()
|
||
upload_cap = yt_long_enabled_upload_cap(settings)
|
||
if upload_cap <= 0:
|
||
upload_cap = yt_long_daily_max(settings)
|
||
return max(0, upload_cap)
|
||
|
||
|
||
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)
|
||
# Enabled channels only — never multiply by disabled Account B rows.
|
||
global_max = yt_long_enabled_upload_cap(settings)
|
||
if global_max <= 0:
|
||
global_max = max(per, n * per) if n else max(per, 0)
|
||
try:
|
||
stored_global = int(settings.get("yt_long_daily_max") or 0)
|
||
except Exception:
|
||
stored_global = 0
|
||
patch: dict[str, Any] = {}
|
||
if stored_global != global_max:
|
||
patch["yt_long_daily_max"] = global_max
|
||
# Keep source in lockstep with enabled upload cap (clear Shorts-inflated 63 etc.).
|
||
try:
|
||
stored_src = int(settings.get("yt_long_source_daily_max") or 0)
|
||
except Exception:
|
||
stored_src = 0
|
||
if stored_src != global_max:
|
||
patch["yt_long_source_daily_max"] = global_max
|
||
if patch:
|
||
try:
|
||
db.update_settings_map(patch)
|
||
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]]:
|
||
"""Pending masters ready to record.
|
||
|
||
Channel may be empty when YouTube upload slots were full at enqueue time
|
||
(cascade-only path). Those jobs must still be claimable for recording.
|
||
"""
|
||
with _lock:
|
||
conn = _connect()
|
||
try:
|
||
ensure_yt_long_tables(conn)
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT j.* FROM yt_long_jobs j
|
||
LEFT JOIN yt_long_channels c ON c.id = j.channel_pk AND j.channel_pk != ''
|
||
WHERE j.status = 'pending'
|
||
AND (
|
||
IFNULL(j.channel_pk, '') = ''
|
||
OR 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(*, skip_profile_ids: set[str] | None = None) -> dict[str, Any] | None:
|
||
now = time.time()
|
||
skip = {str(x).strip().upper() for x in (skip_profile_ids or set()) if str(x).strip()}
|
||
with _lock:
|
||
conn = _connect()
|
||
try:
|
||
ensure_yt_long_tables(conn)
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id,
|
||
IFNULL(c.oauth_ok, -1) AS ch_oauth_ok
|
||
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 IFNULL(c.oauth_ok, -1) != 0
|
||
AND j.clip_path != ''
|
||
AND j.upload_at > 0
|
||
AND j.upload_at <= ?
|
||
ORDER BY j.upload_at ASC, j.created_at ASC
|
||
LIMIT 40
|
||
""",
|
||
(now,),
|
||
).fetchall()
|
||
import os
|
||
picked = None
|
||
for row in rows:
|
||
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
|
||
if pid in skip:
|
||
continue
|
||
path = str(row["clip_path"] or "").strip()
|
||
if not (path and os.path.isfile(path) and os.path.getsize(path) > 1024):
|
||
conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status='pending', clip_path='', clip_seconds=0, upload_at=0,
|
||
started_at=0, error='成片丢失,已重新排队录制', updated_at=?
|
||
WHERE id=? AND status='scheduled'
|
||
""",
|
||
(now, str(row["id"])),
|
||
)
|
||
continue
|
||
picked = row
|
||
break
|
||
if not picked:
|
||
conn.commit()
|
||
return None
|
||
jid = str(picked["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 defer_profile_yt_long_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
|
||
"""Push due auto-uploads for this OAuth Client past cool-down."""
|
||
pid = str(profile_id or "A").strip().upper() or "A"
|
||
until = float(until_ts or 0)
|
||
if until <= time.time():
|
||
return 0
|
||
now = time.time()
|
||
moved = 0
|
||
with _lock:
|
||
conn = _connect()
|
||
try:
|
||
ensure_yt_long_tables(conn)
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT j.id FROM yt_long_jobs j
|
||
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||
WHERE j.status = 'scheduled'
|
||
AND j.clip_path != ''
|
||
AND j.upload_at > 0
|
||
AND j.upload_at <= ?
|
||
AND UPPER(TRIM(COALESCE(NULLIF(c.oauth_profile_id, ''), 'A'))) = ?
|
||
""",
|
||
(now + 30, pid),
|
||
).fetchall()
|
||
for row in rows:
|
||
conn.execute(
|
||
"UPDATE yt_long_jobs SET upload_at = ?, error = ?, updated_at = ? WHERE id = ?",
|
||
(until + 15, (reason or "YouTube 接口配额冷静中,稍后自动重试")[:300], now, str(row["id"])),
|
||
)
|
||
moved += 1
|
||
if moved:
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
return moved
|
||
|
||
|
||
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 = 1200) -> int:
|
||
"""Reclaim orphan recording rows. Never reclaim before ~20 min (8–15 min clip + encode slack)."""
|
||
age = max(1200.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:
|
||
"""Requeue orphan uploading rows; scale age by clip length; drop if file gone."""
|
||
import os
|
||
|
||
base = max(1800.0, float(max_age_sec))
|
||
now = time.time()
|
||
n = 0
|
||
with _lock:
|
||
conn = _connect()
|
||
try:
|
||
ensure_yt_long_tables(conn)
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT id, clip_path, clip_seconds, updated_at, attempts
|
||
FROM yt_long_jobs
|
||
WHERE status = 'uploading' AND IFNULL(youtube_video_id, '') = ''
|
||
"""
|
||
).fetchall()
|
||
for row in rows:
|
||
jid = str(row["id"])
|
||
clip_sec = float(row["clip_seconds"] or 0)
|
||
# Allow ~3x clip duration + 10m encode/upload slack (15m clip => ~55m)
|
||
need = max(base, clip_sec * 3.0 + 600.0)
|
||
if float(row["updated_at"] or 0) > now - need:
|
||
continue
|
||
path = str(row["clip_path"] or "").strip()
|
||
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
|
||
attempts = int(row["attempts"] or 0)
|
||
if alive:
|
||
backoff = min(3600.0, 60.0 * (2 ** min(6, max(0, attempts - 1))))
|
||
conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status = 'scheduled',
|
||
error = 'upload_stale_reclaim',
|
||
upload_at = ?,
|
||
updated_at = ?
|
||
WHERE id = ? AND status = 'uploading'
|
||
""",
|
||
(now + backoff, now, jid),
|
||
)
|
||
else:
|
||
conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status = 'pending',
|
||
clip_path = '',
|
||
clip_seconds = 0,
|
||
upload_at = 0,
|
||
started_at = 0,
|
||
error = '成片丢失,已重新排队录制',
|
||
updated_at = ?
|
||
WHERE id = ? AND status = 'uploading'
|
||
""",
|
||
(now, jid),
|
||
)
|
||
n += 1
|
||
if n:
|
||
conn.commit()
|
||
return n
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def heal_yt_long_orphan_jobs() -> dict[str, int]:
|
||
"""Self-heal impossible/orphan jobs so every enabled channel can progress."""
|
||
import os
|
||
|
||
now = time.time()
|
||
missing = 0
|
||
promoted = 0
|
||
restart_orphans = 0
|
||
with _lock:
|
||
conn = _connect()
|
||
try:
|
||
ensure_yt_long_tables(conn)
|
||
# 1) Already have YouTube id but stuck in scheduled/uploading → uploaded
|
||
cur = conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status = 'uploaded',
|
||
error = CASE
|
||
WHEN IFNULL(error,'') = '' THEN 'heal_promoted_existing_video_id'
|
||
ELSE error
|
||
END,
|
||
finished_at = CASE WHEN IFNULL(finished_at,0)=0 THEN ? ELSE finished_at END,
|
||
updated_at = ?
|
||
WHERE status IN ('scheduled', 'uploading', 'recorded')
|
||
AND IFNULL(youtube_video_id, '') != ''
|
||
""",
|
||
(now, now),
|
||
)
|
||
promoted = int(cur.rowcount or 0)
|
||
|
||
# 2) uploading after process restart is never resumed → requeue/fail by file
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT id, clip_path, clip_seconds, attempts
|
||
FROM yt_long_jobs
|
||
WHERE status = 'uploading' AND IFNULL(youtube_video_id, '') = ''
|
||
"""
|
||
).fetchall()
|
||
for row in rows:
|
||
jid = str(row["id"])
|
||
path = str(row["clip_path"] or "").strip()
|
||
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
|
||
attempts = int(row["attempts"] or 0)
|
||
if alive:
|
||
backoff = min(900.0, 30.0 * (2 ** min(5, max(0, attempts - 1))))
|
||
conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status = 'scheduled',
|
||
error = 'upload_restart_requeue',
|
||
upload_at = ?,
|
||
updated_at = ?
|
||
WHERE id = ? AND status = 'uploading'
|
||
""",
|
||
(now + backoff, now, jid),
|
||
)
|
||
else:
|
||
conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status = 'pending',
|
||
clip_path = '',
|
||
clip_seconds = 0,
|
||
upload_at = 0,
|
||
started_at = 0,
|
||
error = '成片丢失,已重新排队录制',
|
||
updated_at = ?
|
||
WHERE id = ? AND status = 'uploading'
|
||
""",
|
||
(now, jid),
|
||
)
|
||
restart_orphans += 1
|
||
|
||
# 3) scheduled/recorded without master file → re-record
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT id, clip_path, status, error
|
||
FROM yt_long_jobs
|
||
WHERE status IN ('scheduled', 'recorded')
|
||
AND IFNULL(youtube_video_id, '') = ''
|
||
"""
|
||
).fetchall()
|
||
for row in rows:
|
||
err = str(row["error"] or "")
|
||
if err.startswith("cascade_only"):
|
||
continue
|
||
path = str(row["clip_path"] or "").strip()
|
||
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
|
||
if alive:
|
||
continue
|
||
conn.execute(
|
||
"""
|
||
UPDATE yt_long_jobs
|
||
SET status = 'pending',
|
||
clip_path = '',
|
||
clip_seconds = 0,
|
||
upload_at = 0,
|
||
started_at = 0,
|
||
error = '成片丢失,已重新排队录制',
|
||
updated_at = ?
|
||
WHERE id = ?
|
||
""",
|
||
(now, str(row["id"])),
|
||
)
|
||
missing += 1
|
||
|
||
if missing or promoted or restart_orphans:
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
return {
|
||
"requeued_missing_clip": missing,
|
||
"promoted_existing_video_id": promoted,
|
||
"restart_upload_orphans": restart_orphans,
|
||
}
|
||
|
||
|
||
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()
|
||
}
|
||
uploaded = int(by.get("uploaded") or 0)
|
||
# Progress / gap follow uploaded (Shorts parity); used keeps slot reservation.
|
||
gap = max(0, dmax - uploaded) 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": uploaded,
|
||
"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()
|