895 lines
30 KiB
Python
895 lines
30 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""YouTube long-form (16:9) jobs — fully isolated from shorts_* / tiktok_* / x_clip_*."""
|
|
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
import time
|
|
import uuid
|
|
from typing import Any, Optional
|
|
|
|
from .db import _connect, _lock, _row_to_dict
|
|
from .timeutil import push_date_from_ts
|
|
|
|
# Quota-consuming statuses for daily long-form caps
|
|
_QUOTA_STATUSES = (
|
|
"pending",
|
|
"recording",
|
|
"recorded",
|
|
"scheduled",
|
|
"uploading",
|
|
"uploaded",
|
|
)
|
|
|
|
YT_LONG_DAILY_DEFAULT = 3
|
|
YT_LONG_MIN_SEC = 180 # 3 min
|
|
YT_LONG_MAX_SEC = 480 # 8 min
|
|
|
|
|
|
def ensure_yt_long_tables(conn: sqlite3.Connection) -> None:
|
|
conn.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS yt_long_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 1,
|
|
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)"
|
|
)
|
|
|
|
|
|
def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
|
from . import db
|
|
|
|
settings = cfg if cfg is not None else db.get_settings_map()
|
|
try:
|
|
v = int(settings.get("yt_long_daily_max") or YT_LONG_DAILY_DEFAULT)
|
|
except Exception:
|
|
v = YT_LONG_DAILY_DEFAULT
|
|
return max(0, min(50, v))
|
|
|
|
|
|
def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
|
from . import db
|
|
|
|
settings = cfg if cfg is not None else db.get_settings_map()
|
|
try:
|
|
v = int(settings.get("yt_long_channel_daily_max") or 1)
|
|
except Exception:
|
|
v = 1
|
|
return max(0, min(20, v))
|
|
|
|
|
|
def yt_long_quota_used(push_date: str = "") -> int:
|
|
day = push_date or push_date_from_ts(time.time())
|
|
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
row = conn.execute(
|
|
f"""
|
|
SELECT COUNT(*) AS c FROM yt_long_jobs
|
|
WHERE push_date = ? AND status IN ({placeholders})
|
|
""",
|
|
(day, *_QUOTA_STATUSES),
|
|
).fetchone()
|
|
return int(row["c"]) if row else 0
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int:
|
|
day = push_date or push_date_from_ts(time.time())
|
|
return max(0, yt_long_daily_max(cfg) - yt_long_quota_used(day))
|
|
|
|
|
|
def channel_quota_used(channel_pk: str, push_date: str = "") -> int:
|
|
day = push_date or push_date_from_ts(time.time())
|
|
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
row = conn.execute(
|
|
f"""
|
|
SELECT COUNT(*) AS c FROM yt_long_jobs
|
|
WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders})
|
|
""",
|
|
(day, channel_pk, *_QUOTA_STATUSES),
|
|
).fetchone()
|
|
return int(row["c"]) if row else 0
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def has_job_for_room_day(room_id: str, push_date: str) -> bool:
|
|
if not room_id:
|
|
return False
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
row = conn.execute(
|
|
"""
|
|
SELECT 1 FROM yt_long_jobs
|
|
WHERE room_id = ? AND push_date = ?
|
|
AND status NOT IN ('failed', 'skipped')
|
|
LIMIT 1
|
|
""",
|
|
(room_id, push_date),
|
|
).fetchone()
|
|
return bool(row)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def create_yt_long_job(
|
|
*,
|
|
room_pk: str = "",
|
|
room_id: str = "",
|
|
source_url: str = "",
|
|
anchor_name: str = "",
|
|
stream_url: str = "",
|
|
channel_pk: str = "",
|
|
shorts_job_id: str = "",
|
|
push_date: str = "",
|
|
) -> dict[str, Any]:
|
|
now = time.time()
|
|
day = push_date or push_date_from_ts(now)
|
|
jid = str(uuid.uuid4())
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO yt_long_jobs(
|
|
id, room_pk, room_id, source_url, anchor_name, stream_url,
|
|
channel_pk, shorts_job_id, status, push_date,
|
|
created_at, updated_at
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)
|
|
""",
|
|
(
|
|
jid,
|
|
room_pk,
|
|
room_id,
|
|
source_url,
|
|
anchor_name,
|
|
stream_url,
|
|
channel_pk,
|
|
shorts_job_id,
|
|
day,
|
|
now,
|
|
now,
|
|
),
|
|
)
|
|
conn.commit()
|
|
return _row_to_dict(
|
|
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (jid,)).fetchone()
|
|
) # type: ignore
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def get_yt_long_job(job_id: str) -> dict[str, Any] | None:
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
row = conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone()
|
|
return _row_to_dict(row) if row else None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def update_yt_long_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
|
|
if not fields:
|
|
return get_yt_long_job(job_id)
|
|
allowed = {
|
|
"status",
|
|
"clip_path",
|
|
"clip_seconds",
|
|
"title",
|
|
"description",
|
|
"youtube_video_id",
|
|
"youtube_url",
|
|
"error",
|
|
"channel_pk",
|
|
"stream_url",
|
|
"upload_at",
|
|
"attempts",
|
|
"started_at",
|
|
"finished_at",
|
|
"anchor_name",
|
|
"source_url",
|
|
}
|
|
sets: list[str] = []
|
|
params: list[Any] = []
|
|
for k, v in fields.items():
|
|
if k not in allowed:
|
|
continue
|
|
sets.append(f"{k} = ?")
|
|
params.append(v)
|
|
if not sets:
|
|
return get_yt_long_job(job_id)
|
|
sets.append("updated_at = ?")
|
|
params.append(time.time())
|
|
params.append(job_id)
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
conn.execute(f"UPDATE yt_long_jobs SET {', '.join(sets)} WHERE id = ?", params)
|
|
conn.commit()
|
|
row = conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone()
|
|
return _row_to_dict(row) if row else None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def list_yt_long_jobs(*, limit: int = 40, push_date: str = "") -> list[dict[str, Any]]:
|
|
day = push_date.strip()
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
if day:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM yt_long_jobs WHERE push_date = ?
|
|
ORDER BY created_at DESC LIMIT ?
|
|
""",
|
|
(day, max(1, min(int(limit), 200))),
|
|
).fetchall()
|
|
else:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM yt_long_jobs
|
|
ORDER BY created_at DESC LIMIT ?
|
|
""",
|
|
(max(1, min(int(limit), 200)),),
|
|
).fetchall()
|
|
return [_row_to_dict(r) for r in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]:
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM yt_long_jobs
|
|
WHERE status = 'pending'
|
|
ORDER BY created_at ASC
|
|
LIMIT ?
|
|
""",
|
|
(max(1, min(int(limit), 20)),),
|
|
).fetchall()
|
|
return [_row_to_dict(r) for r in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def claim_yt_long_job_record(job_id: str) -> dict[str, Any] | None:
|
|
now = time.time()
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
cur = conn.execute(
|
|
"""
|
|
UPDATE yt_long_jobs
|
|
SET status = 'recording', started_at = ?, updated_at = ?, attempts = attempts + 1
|
|
WHERE id = ? AND status = 'pending'
|
|
""",
|
|
(now, now, job_id),
|
|
)
|
|
if cur.rowcount == 0:
|
|
conn.rollback()
|
|
return None
|
|
conn.commit()
|
|
return _row_to_dict(
|
|
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone()
|
|
)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
|
now = time.time()
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_long_tables(conn)
|
|
row = conn.execute(
|
|
"""
|
|
SELECT * FROM yt_long_jobs
|
|
WHERE status = 'scheduled'
|
|
AND clip_path != ''
|
|
AND upload_at > 0
|
|
AND upload_at <= ?
|
|
ORDER BY upload_at ASC, created_at ASC
|
|
LIMIT 1
|
|
""",
|
|
(now,),
|
|
).fetchone()
|
|
if not row:
|
|
return None
|
|
jid = str(row["id"])
|
|
cur = conn.execute(
|
|
"""
|
|
UPDATE yt_long_jobs
|
|
SET status = 'uploading', updated_at = ?, attempts = attempts + 1
|
|
WHERE id = ? AND status = 'scheduled'
|
|
""",
|
|
(now, jid),
|
|
)
|
|
if cur.rowcount == 0:
|
|
conn.rollback()
|
|
return None
|
|
conn.commit()
|
|
return _row_to_dict(
|
|
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (jid,)).fetchone()
|
|
)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def 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 = 600) -> int:
|
|
"""Reclaim orphan recording rows (no worker). Use started_at when present."""
|
|
age = max(180.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 = 1,
|
|
title_template: str = "{anchor} street food live",
|
|
description_template: str = "{anchor}\n{url}\n#StreetFood #Live",
|
|
privacy: str = "public",
|
|
note: str = "",
|
|
source_shorts_channel_pk: str = "",
|
|
) -> dict[str, Any]:
|
|
now = time.time()
|
|
cid = str(uuid.uuid4())
|
|
dmax = max(0, min(20, int(daily_max or 1)))
|
|
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",
|
|
}
|
|
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 == "daily_max":
|
|
try:
|
|
v = max(0, min(20, 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 1)
|
|
else:
|
|
keep_dmax = 1
|
|
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": keep_dmax,
|
|
"privacy": str(ch.get("privacy") or "public"),
|
|
"note": f"synced from shorts:{src}",
|
|
"source_shorts_channel_pk": src,
|
|
}
|
|
if existing_id:
|
|
# Always refresh OAuth + identity from Shorts; keep local 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"],
|
|
enabled=payload["enabled"],
|
|
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="{anchor} street food live",
|
|
description_template="{anchor}\n{url}\n#StreetFood #Live",
|
|
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 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 _QUOTA_STATUSES)
|
|
channels = list_yt_long_channels(enabled=None)
|
|
board: list[dict[str, Any]] = []
|
|
total_gap = 0
|
|
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, *_QUOTA_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
|
|
board.append(
|
|
{
|
|
"id": cid,
|
|
"name": ch.get("name"),
|
|
"youtube_channel_id": ch.get("youtube_channel_id"),
|
|
"oauth_profile_id": ch.get("oauth_profile_id"),
|
|
"enabled": bool(ch.get("enabled")),
|
|
"authorized": bool(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": ch.get("oauth_ok"),
|
|
"oauth_error": ch.get("oauth_error") or "",
|
|
}
|
|
)
|
|
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()
|