douyinWEB/backend/app/db.py
eric c4fcc086be fix: show anchor names on blacklist; redesign settings with tabs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-23 08:25:02 -05:00

4559 lines
171 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import json
import sqlite3
import threading
import time
import uuid
from pathlib import Path
from typing import Any, Optional
from .config import settings
from .models import extract_room_id, normalize_room_url, push_date_from_ts
_lock = threading.RLock()
# Default soft targets (Beijing day). Channels may override via daily_min/daily_max.
SHORTS_DAILY_FORCE = 9
# TikTok official Content Posting / Direct Post guideline ~15/day
TIKTOK_DAILY_FORCE = 15
def _normalize_daily_quota(value: Any = None, *, default: int = 9, lo: int = 1, hi: int = 50) -> int:
"""Clamp channel daily quota to a sane range. No longer hard-forces a single global value."""
try:
n = int(value) if value is not None else int(default)
except Exception:
n = int(default)
return max(int(lo), min(int(hi), n))
def _force_daily_quota(value: Any = None) -> int:
# Backward-compatible name — now means "normalize", not "force overwrite".
return _normalize_daily_quota(value, default=SHORTS_DAILY_FORCE)
def _connect() -> sqlite3.Connection:
conn = sqlite3.connect(str(settings.sqlite_path), check_same_thread=False, timeout=8.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=8000")
conn.execute("PRAGMA foreign_keys=ON")
return conn
def init_db() -> None:
with _lock:
conn = _connect()
try:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS rooms (
id TEXT PRIMARY KEY,
url TEXT NOT NULL UNIQUE,
room_id TEXT NOT NULL DEFAULT '',
note TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
last_status TEXT NOT NULL DEFAULT 'unknown',
last_anchor TEXT NOT NULL DEFAULT '',
last_title TEXT NOT NULL DEFAULT '',
last_checked_at REAL NOT NULL DEFAULT 0,
next_check_at REAL NOT NULL DEFAULT 0,
error_count INTEGER NOT NULL DEFAULT 0,
last_error TEXT NOT NULL DEFAULT '',
active_session_id TEXT NOT NULL DEFAULT '',
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS blacklist (
id TEXT PRIMARY KEY,
value TEXT NOT NULL UNIQUE,
room_id TEXT NOT NULL DEFAULT '',
reason TEXT NOT NULL DEFAULT '',
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
room_id TEXT NOT NULL DEFAULT '',
room_pk TEXT NOT NULL DEFAULT '',
source_url TEXT NOT NULL DEFAULT '',
anchor_name TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
started_at REAL NOT NULL,
ended_at REAL,
duration_seconds REAL NOT NULL DEFAULT 0,
push_date TEXT NOT NULL DEFAULT '',
cover_path TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'active',
end_reason TEXT NOT NULL DEFAULT '',
metadata_json TEXT NOT NULL DEFAULT '{}',
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at DESC);
CREATE INDEX IF NOT EXISTS idx_sessions_room ON sessions(room_id);
CREATE INDEX IF NOT EXISTS idx_sessions_date ON sessions(push_date DESC);
CREATE INDEX IF NOT EXISTS idx_rooms_next ON rooms(next_check_at, enabled);
CREATE TABLE IF NOT EXISTS kv_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
ts REAL NOT NULL,
level TEXT NOT NULL DEFAULT 'info',
kind TEXT NOT NULL DEFAULT '',
room_id TEXT NOT NULL DEFAULT '',
room_pk TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
anchor_name TEXT NOT NULL DEFAULT '',
message TEXT NOT NULL DEFAULT '',
meta_json TEXT NOT NULL DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts DESC);
CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind, ts DESC);
CREATE TABLE IF NOT EXISTS channel_groups (
id TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
platform TEXT NOT NULL DEFAULT 'youtube',
channel_url TEXT NOT NULL DEFAULT '',
channel_key TEXT NOT NULL DEFAULT '',
channel_id TEXT NOT NULL DEFAULT '',
handle TEXT NOT NULL DEFAULT '',
urls TEXT NOT NULL DEFAULT '',
note TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
last_status TEXT NOT NULL DEFAULT 'unknown',
last_checked_at REAL NOT NULL DEFAULT 0,
next_check_at REAL NOT NULL DEFAULT 0,
last_title TEXT NOT NULL DEFAULT '',
last_live_video_id TEXT NOT NULL DEFAULT '',
last_live_url TEXT NOT NULL DEFAULT '',
error_count INTEGER NOT NULL DEFAULT 0,
last_error TEXT NOT NULL DEFAULT '',
active_session_id TEXT NOT NULL DEFAULT '',
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_channel_groups_platform ON channel_groups(platform, updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_channel_groups_key ON channel_groups(channel_key);
CREATE TABLE IF NOT EXISTS shorts_channels (
id TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
youtube_channel_id TEXT NOT NULL DEFAULT '',
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_min INTEGER NOT NULL DEFAULT 5,
daily_max INTEGER NOT NULL DEFAULT 9,
title_template TEXT NOT NULL DEFAULT '{anchor} 直播瞬间 #Shorts',
description_template TEXT NOT NULL DEFAULT '{anchor}\n{url}\n#Shorts #直播',
privacy TEXT NOT NULL DEFAULT 'public',
last_assigned_at REAL NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '',
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS shorts_jobs (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL DEFAULT '',
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 '',
status TEXT NOT NULL DEFAULT 'pending',
clip_path TEXT NOT NULL DEFAULT '',
clip_seconds REAL NOT NULL DEFAULT 0,
youtube_video_id TEXT NOT NULL DEFAULT '',
youtube_url TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
push_date TEXT NOT NULL DEFAULT '',
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
);
CREATE INDEX IF NOT EXISTS idx_shorts_jobs_status ON shorts_jobs(status, created_at);
CREATE INDEX IF NOT EXISTS idx_shorts_jobs_date ON shorts_jobs(push_date, channel_pk);
CREATE INDEX IF NOT EXISTS idx_shorts_jobs_session ON shorts_jobs(session_id);
"""
)
# migrations
cols = {r[1] for r in conn.execute("PRAGMA table_info(rooms)").fetchall()}
if "tags" not in cols:
conn.execute("ALTER TABLE rooms ADD COLUMN tags TEXT NOT NULL DEFAULT ''")
if "clip_sec" not in cols:
conn.execute("ALTER TABLE rooms ADD COLUMN clip_sec INTEGER NOT NULL DEFAULT 0")
gcols = {r[1] for r in conn.execute("PRAGMA table_info(channel_groups)").fetchall()}
for col, ddl in [
("last_status", "TEXT NOT NULL DEFAULT 'unknown'"),
("last_checked_at", "REAL NOT NULL DEFAULT 0"),
("next_check_at", "REAL NOT NULL DEFAULT 0"),
("last_title", "TEXT NOT NULL DEFAULT ''"),
("last_live_video_id", "TEXT NOT NULL DEFAULT ''"),
("last_live_url", "TEXT NOT NULL DEFAULT ''"),
("error_count", "INTEGER NOT NULL DEFAULT 0"),
("last_error", "TEXT NOT NULL DEFAULT ''"),
("active_session_id", "TEXT NOT NULL DEFAULT ''"),
]:
if col not in gcols:
conn.execute(f"ALTER TABLE channel_groups ADD COLUMN {col} {ddl}")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_channel_groups_next ON channel_groups(enabled, next_check_at)"
)
# shorts_jobs.upload_at for staggered uploads
sj_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()}
if "upload_at" not in sj_cols:
conn.execute("ALTER TABLE shorts_jobs ADD COLUMN upload_at REAL NOT NULL DEFAULT 0")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_shorts_jobs_upload ON shorts_jobs(status, upload_at)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_shorts_jobs_room_day ON shorts_jobs(room_id, push_date, status)"
)
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS tiktok_channels (
id TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
tiktok_open_id TEXT NOT NULL DEFAULT '',
tiktok_username TEXT NOT NULL DEFAULT '',
client_key TEXT NOT NULL DEFAULT '',
client_secret TEXT NOT NULL DEFAULT '',
refresh_token TEXT NOT NULL DEFAULT '',
access_token TEXT NOT NULL DEFAULT '',
token_expires_at REAL NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
daily_min INTEGER NOT NULL DEFAULT 9,
daily_max INTEGER NOT NULL DEFAULT 9,
title_template TEXT NOT NULL DEFAULT '',
description_template TEXT NOT NULL DEFAULT '',
privacy_level TEXT NOT NULL DEFAULT 'SELF_ONLY',
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 '',
note TEXT NOT NULL DEFAULT '',
cookie_saved_at REAL NOT NULL DEFAULT 0,
created_at REAL NOT NULL,
updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS tiktok_jobs (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL DEFAULT '',
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 '',
status TEXT NOT NULL DEFAULT 'pending',
clip_path TEXT NOT NULL DEFAULT '',
clip_seconds REAL NOT NULL DEFAULT 0,
tiktok_publish_id TEXT NOT NULL DEFAULT '',
tiktok_video_id 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
);
CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_status ON tiktok_jobs(status, created_at);
CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_date ON tiktok_jobs(push_date, channel_pk);
CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_room_day ON tiktok_jobs(room_id, push_date, status);
CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_upload ON tiktok_jobs(status, upload_at);
"""
)
tt_cols = {r[1] for r in conn.execute("PRAGMA table_info(tiktok_channels)").fetchall()}
if "cookie_saved_at" not in tt_cols:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN cookie_saved_at REAL NOT NULL DEFAULT 0"
)
if "socks_enabled" not in tt_cols:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN socks_enabled INTEGER NOT NULL DEFAULT 0"
)
if "socks_profile_id" not in tt_cols:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN socks_profile_id TEXT NOT NULL DEFAULT ''"
)
if "platform_limit_at" not in tt_cols:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN platform_limit_at REAL NOT NULL DEFAULT 0"
)
if "platform_limit_msg" not in tt_cols:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN platform_limit_msg TEXT NOT NULL DEFAULT ''"
)
if "platform_limit_probe_at" not in tt_cols:
conn.execute(
"ALTER TABLE tiktok_channels ADD COLUMN platform_limit_probe_at REAL NOT NULL DEFAULT 0"
)
for col, decl in (
("tiktok_uid", "TEXT NOT NULL DEFAULT ''"),
("nickname", "TEXT NOT NULL DEFAULT ''"),
("avatar_url", "TEXT NOT NULL DEFAULT ''"),
("follower_count", "INTEGER NOT NULL DEFAULT 0"),
("following_count", "INTEGER NOT NULL DEFAULT 0"),
("video_count", "INTEGER NOT NULL DEFAULT 0"),
("heart_count", "INTEGER NOT NULL DEFAULT 0"),
("profile_fetched_at", "REAL NOT NULL DEFAULT 0"),
("profile_error", "TEXT NOT NULL DEFAULT ''"),
):
if col not in tt_cols:
conn.execute(f"ALTER TABLE tiktok_channels ADD COLUMN {col} {decl}")
from . import caption_pool as _caption_pool
from . import x2_db as _x2_db
from . import x_clips_db as _x_clips_db
from . import yt_long_db as _yt_long_db
from . import yt_assign_db as _yt_assign_db
_x2_db.ensure_x2_tables(conn)
_x_clips_db.ensure_x_clips_tables(conn)
_yt_long_db.ensure_yt_long_tables(conn)
_yt_assign_db.ensure_yt_assign_tables(conn)
_caption_pool.ensure_caption_pool_table(conn)
_caption_pool.seed_caption_pool(conn)
sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()}
for col, ddl in [
("oauth_ok", "INTEGER NOT NULL DEFAULT -1"),
("oauth_checked_at", "REAL NOT NULL DEFAULT 0"),
("oauth_error", "TEXT NOT NULL DEFAULT ''"),
("last_status", "TEXT NOT NULL DEFAULT 'unknown'"),
("last_checked_at", "REAL NOT NULL DEFAULT 0"),
("last_title", "TEXT NOT NULL DEFAULT ''"),
("last_live_url", "TEXT NOT NULL DEFAULT ''"),
("last_live_video_id", "TEXT NOT NULL DEFAULT ''"),
("active_session_id", "TEXT NOT NULL DEFAULT ''"),
("oauth_profile_id", "TEXT NOT NULL DEFAULT ''"),
("yt_profile_json", "TEXT NOT NULL DEFAULT ''"),
("yt_profile_at", "REAL NOT NULL DEFAULT 0"),
]:
if col not in sc_cols:
conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}")
conn.commit()
_seed_defaults(conn)
# Do NOT overwrite per-channel daily quotas on every boot (was polluting operator settings).
try:
conn.execute(
"UPDATE shorts_channels SET daily_min = ?, daily_max = ? "
"WHERE IFNULL(daily_min,0) <= 0 OR IFNULL(daily_max,0) <= 0",
(SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE),
)
conn.execute(
"UPDATE tiktok_channels SET daily_min = ?, daily_max = ? "
"WHERE IFNULL(daily_min,0) <= 0 OR IFNULL(daily_max,0) <= 0",
(TIKTOK_DAILY_FORCE, TIKTOK_DAILY_FORCE),
)
conn.commit()
except Exception:
pass
finally:
conn.close()
# repair leftover duplicate actives from concurrent go-live races
try:
dedupe_active_sessions()
except Exception:
pass
try:
dedupe_shorts_jobs_room_day()
except Exception:
pass
def enforce_shorts_daily_force() -> int:
"""Deprecated no-op kept for API compatibility. Quotas are per-channel editable now."""
return 0
def _seed_defaults(conn: sqlite3.Connection) -> None:
defaults = {
"max_concurrency": settings.max_concurrency,
"min_request_gap_sec": settings.min_request_gap_sec,
"request_jitter_sec": settings.request_jitter_sec,
"offline_interval_sec": settings.offline_interval_sec,
"live_interval_sec": settings.live_interval_sec,
"error_backoff_base_sec": settings.error_backoff_base_sec,
"error_backoff_max_sec": settings.error_backoff_max_sec,
"global_pause_on_risk_sec": settings.global_pause_on_risk_sec,
"capture_cover_on_start": settings.capture_cover_on_start,
"monitor_enabled": True,
"dy_cookie": "",
"http_proxy": "",
"notify_webhook_url": "",
"notify_on_live": True,
"notify_on_offline": False,
"notify_ntfy_on_douyin_live": False,
"notify_on_risk": True,
"notify_on_shorts_fail": True,
"notify_on_shorts_ok": False,
"notify_on_shorts_quota": True,
"notify_on_watch_remind": True,
"watch_remind_window_sec": 1800,
"quiet_hours_enabled": False,
"quiet_hours_start": 2,
"quiet_hours_end": 7,
"quiet_hours_allow_priority": True,
"priority_interval_sec": 25.0,
# YouTube channel-group poller (youtubei.js sidecar)
"yt_monitor_enabled": True,
"yt_offline_interval_sec": 180.0,
"yt_live_interval_sec": 90.0,
"yt_batch_size": 8,
"yt_request_gap_sec": 2.0,
# Shorts pipeline
"shorts_enabled": False,
"shorts_clip_sec": 15,
"shorts_trigger": "tagged",
"shorts_tag": "shorts",
"shorts_dedupe_room_day": True,
"shorts_max_concurrent": 1,
"shorts_auto_upload": True,
"shorts_live_sample": True,
"shorts_live_sample_interval_sec": 180,
"shorts_live_sample_batch": 1,
"shorts_sample_any_live": True,
"shorts_upload_spread": True,
"shorts_upload_min_gap_sec": 720,
"shorts_channel_min_gap_sec": 2400,
"shorts_delete_clip_after_upload": True,
"shorts_auto_retry_failed": True,
"shorts_auto_retry_max_attempts": 3,
"shorts_auto_retry_interval_sec": 300,
"shorts_oauth_check_interval_sec": 3600,
"shorts_oauth_client_id": "",
"shorts_oauth_client_secret": "",
"shorts_oauth_redirect_uri": "https://dylive.nomadro.com/api/shorts/oauth/callback",
# Named OAuth apps A/B/C/D — configure once in settings; channels pick a profile
"shorts_oauth_profiles": [
{"id": "A", "label": "谷歌账号 A", "client_id": "", "client_secret": ""},
{"id": "B", "label": "谷歌账号 B", "client_id": "", "client_secret": ""},
{"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": ""},
{"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": ""},
],
# Studio browser cookies per OAuth profile — required for yt-long ad monetize
"yt_studio_cookies_by_profile": {},
"shorts_gcp_project_id": "live-473104",
"shorts_yt_daily_upload_limit": 90,
"shorts_yt_upload_blocked_until": 0,
"shorts_yt_uploads_pt_date": "",
"shorts_yt_uploads_pt_count": 0,
# Shorts upload SOCKS5 (optional, default off — does not affect monitor)
"shorts_upload_socks_enabled": False,
"shorts_upload_socks_profile_id": "residential-1",
"shorts_upload_socks_profiles": [
{
"id": "residential-1",
"label": "静态住宅 IP",
"type": "socks5",
"server": "185.124.61.35",
"port": 43676,
"username": "V0sI3BsI1bxgKRx",
"password": "QGwGeRTAa9YcVhM",
}
],
# TikTok pipeline (fully isolated from Shorts)
"tiktok_enabled": False,
"tiktok_clip_sec": 75,
"tiktok_trigger": "tagged",
"tiktok_tag": "shorts",
"tiktok_dedupe_room_day": True,
"tiktok_max_concurrent": 1,
"tiktok_auto_upload": True,
"tiktok_live_sample": True,
"tiktok_live_sample_interval_sec": 180,
"tiktok_live_sample_batch": 1,
"tiktok_sample_any_live": True,
"tiktok_upload_spread": True,
"tiktok_upload_min_gap_sec": 720,
"tiktok_channel_min_gap_sec": 2400,
"tiktok_delete_clip_after_upload": True,
# TikTok upload SOCKS profiles (pool); each account opts in via socks_enabled=0 by default
"tiktok_upload_socks_profiles": [],
# X2 (Twitter/X ops agent) ingest
"x2_ingest_token": "",
"x2_default_agent_label": "PVE-X2",
# X live-clip auto post (isolated from Shorts / TikTok)
"x_clips_enabled": False,
"x_clips_clip_sec": 18,
"x_clips_trigger": "tagged",
"x_clips_tag": "x",
"x_clips_dedupe_room_day": True,
"x_clips_max_concurrent": 1,
"x_clips_auto_post": True,
"x_clips_auto_post_paused_date": "",
"x_clips_live_sample": True,
"x_clips_live_sample_interval_sec": 180,
"x_clips_live_sample_batch": 1,
"x_clips_sample_any_live": True,
"x_clips_upload_spread": True,
"x_clips_upload_min_gap_sec": 600,
"x_clips_delete_clip_after_post": True,
"x_clips_daily_max": 20,
"x_clips_caption_template": "{anchor}",
"x_clips_account_username": "",
# YouTube long-form 9:16 masters (isolated; default OFF — does not affect Shorts)
"yt_long_enabled": False,
"yt_long_with_shorts": True,
"yt_long_auto_upload": True,
"yt_long_live_sample": True,
"yt_long_live_sample_interval_sec": 180,
"yt_long_live_sample_batch": 1,
"yt_long_daily_max": 70,
"yt_long_source_daily_max": 70,
"yt_long_channel_daily_max": 5,
"yt_long_min_sec": 180,
"yt_long_max_sec": 480,
"yt_long_dedupe_room_day": True,
"yt_long_max_concurrent": 1,
"yt_long_upload_min_gap_sec": 900,
"yt_long_delete_clip_after_upload": True,
"yt_long_landscape_16x9": False,
"yt_long_auto_match_source": True,
"yt_long_source_cap": 200,
"yt_long_title_template": "",
"yt_long_description_template": "",
"clip_cascade_enabled": True,
"clips_max_age_hours": 24,
"clips_min_free_gb": 12,
"yt_long_monetize_when_ypp": True,
"tiktok_auto_retry_failed": False,
"tiktok_auto_retry_max_attempts": 3,
"tiktok_auto_retry_interval_sec": 300,
"tiktok_oauth_check_interval_sec": 3600,
"tiktok_oauth_client_key": "",
"tiktok_oauth_client_secret": "",
"tiktok_oauth_redirect_uri": "https://dylive.nomadro.com/api/tiktok/oauth/callback/",
# Ops / audit / archive (all off by default — no behavior change on existing installs)
"settings_audit_enabled": True,
"db_backup_enabled": False,
"db_backup_interval_hours": 24,
"db_backup_keep_days": 7,
"ops_alerts_enabled": False,
"ops_alert_disk_enabled": False,
"ops_alert_quota_enabled": False,
"ops_alert_interval_sec": 900,
"ops_alert_cooldown_sec": 3600,
"ops_alert_failed_jobs_threshold": 50,
"notify_on_tiktok_unaudited": True,
"notify_webhook_standard_json": False,
"clip_archive_to_s3_enabled": False,
"readonly_username": "",
"readonly_password_hash": "",
}
for key, value in defaults.items():
row = conn.execute("SELECT 1 FROM kv_settings WHERE key = ?", (key,)).fetchone()
if not row:
conn.execute(
"INSERT INTO kv_settings(key, value) VALUES (?, ?)",
(key, json.dumps(value)),
)
conn.commit()
def get_settings_map() -> dict[str, Any]:
with _lock:
conn = _connect()
try:
return _settings_map_from_conn(conn)
finally:
conn.close()
def _settings_map_from_conn(conn: sqlite3.Connection) -> dict[str, Any]:
rows = conn.execute("SELECT key, value FROM kv_settings").fetchall()
out: dict[str, Any] = {}
for row in rows:
try:
out[row["key"]] = json.loads(row["value"])
except json.JSONDecodeError:
out[row["key"]] = row["value"]
return out
def monitor_status_data(*, light: bool = False) -> dict[str, Any]:
"""Settings + monitor counters in a single SQLite lock (desktop-friendly)."""
now = time.time()
with _lock:
conn = _connect()
try:
cfg = _settings_map_from_conn(conn)
rooms = int(conn.execute("SELECT COUNT(*) AS c FROM rooms").fetchone()["c"] or 0)
live = int(
conn.execute("SELECT COUNT(*) AS c FROM rooms WHERE last_status = 'live'").fetchone()["c"] or 0
)
bl = int(conn.execute("SELECT COUNT(*) AS c FROM blacklist").fetchone()["c"] or 0)
events = int(conn.execute("SELECT COUNT(*) AS c FROM events").fetchone()["c"] or 0)
counts = {"rooms": rooms, "live_rooms": live, "blacklist": bl, "events": events}
error_rooms_1h = 0
overdue: dict[str, Any] = {"count": 0, "oldest_next_check_at": None, "max_lag_sec": 0}
if not light:
cutoff = now - 3600
error_rooms_1h = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM rooms
WHERE enabled = 1 AND (
last_status = 'error'
OR (error_count > 0 AND last_checked_at >= ?)
)
""",
(cutoff,),
).fetchone()["c"]
or 0
)
grace_cutoff = now - 60
row = conn.execute(
"""
SELECT COUNT(*) AS c, MIN(next_check_at) AS oldest
FROM rooms
WHERE enabled = 1 AND next_check_at > 0 AND next_check_at <= ?
""",
(grace_cutoff,),
).fetchone()
oldest = float(row["oldest"] or 0)
overdue = {
"count": int(row["c"] or 0),
"oldest_next_check_at": oldest or None,
"max_lag_sec": round(max(0.0, now - oldest), 1) if oldest else 0,
}
return {
"settings": cfg,
"counts": counts,
"error_rooms_1h": error_rooms_1h,
"overdue": overdue,
}
finally:
conn.close()
def youtube_monitor_status_data() -> dict[str, Any]:
"""YouTube monitor settings + group counters in one lock."""
now = time.time()
with _lock:
conn = _connect()
try:
cfg = _settings_map_from_conn(conn)
platform = "youtube"
total = int(
conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ?",
(platform,),
).fetchone()["c"]
or 0
)
enabled = int(
conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ? AND enabled = 1",
(platform,),
).fetchone()["c"]
or 0
)
live = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND last_status = 'live'
""",
(platform,),
).fetchone()["c"]
or 0
)
errors = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND last_status = 'error'
""",
(platform,),
).fetchone()["c"]
or 0
)
overdue = int(
conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND next_check_at > 0 AND next_check_at <= ?
""",
(platform, now - 60),
).fetchone()["c"]
or 0
)
groups = {
"total": total,
"enabled": enabled,
"live": live,
"errors": errors,
"overdue": overdue,
}
return {"settings": cfg, "groups": groups}
finally:
conn.close()
def update_settings_map(patch: dict[str, Any], *, audit_actor: str = "") -> dict[str, Any]:
with _lock:
conn = _connect()
try:
for key, value in patch.items():
if value is None:
continue
conn.execute(
"INSERT INTO kv_settings(key, value) VALUES(?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(key, json.dumps(value)),
)
if "dy_cookie" in patch and patch.get("dy_cookie") is not None:
conn.execute(
"INSERT INTO kv_settings(key, value) VALUES(?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
("dy_cookie_updated_at", json.dumps(time.time())),
)
conn.commit()
finally:
conn.close()
try:
from .settings_audit import log_settings_patch
log_settings_patch(patch, actor=audit_actor)
except Exception:
pass
return get_settings_map()
def count_recent_error_rooms(*, within_sec: float = 3600) -> int:
cutoff = time.time() - within_sec
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT COUNT(*) AS c FROM rooms
WHERE enabled = 1 AND (
last_status = 'error'
OR (error_count > 0 AND last_checked_at >= ?)
)
""",
(cutoff,),
).fetchone()
return int(row["c"] or 0)
finally:
conn.close()
def overdue_rooms_stats(*, grace_sec: float = 60) -> dict[str, Any]:
"""Enabled rooms whose next_check_at is already due (poll backlog)."""
cutoff = time.time() - max(0.0, grace_sec)
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT COUNT(*) AS c, MIN(next_check_at) AS oldest
FROM rooms
WHERE enabled = 1 AND next_check_at > 0 AND next_check_at <= ?
""",
(cutoff,),
).fetchone()
oldest = float(row["oldest"] or 0)
lag = max(0.0, time.time() - oldest) if oldest else 0.0
return {
"count": int(row["c"] or 0),
"oldest_next_check_at": oldest or None,
"max_lag_sec": round(lag, 1) if oldest else 0,
}
finally:
conn.close()
def export_events_rows(
*,
kind: str = "",
q: str = "",
platform: str = "",
limit: int = 2000,
) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
if kind.strip():
clauses.append("kind = ?")
params.append(kind.strip())
if q.strip():
like = f"%{q.strip()}%"
clauses.append("(message LIKE ? OR anchor_name LIKE ? OR room_id LIKE ?)")
params.extend([like, like, like])
plat_sql, plat_params = _platform_clause(platform, room_col="room_id", meta_col="meta_json")
if plat_sql:
clauses.append(plat_sql)
params.extend(plat_params)
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
rows = conn.execute(
f"SELECT * FROM events {where} ORDER BY ts DESC LIMIT ?",
[*params, max(1, min(limit, 10000))],
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()
def _platform_clause(platform: str, *, room_col: str, meta_col: str) -> tuple[str, list[Any]]:
"""Filter by platform using room_id prefix and JSON metadata markers."""
p = (platform or "").strip().lower()
if p in ("youtube", "yt"):
return (
f"({room_col} LIKE 'yt:%' OR {room_col} LIKE 'shorts:%' OR {meta_col} LIKE '%\"platform\": \"youtube\"%' "
f"OR {meta_col} LIKE '%\"platform\":\"youtube\"%')",
[],
)
if p in ("shorts", "shorts_live"):
return (
f"({room_col} LIKE 'shorts:%' OR {meta_col} LIKE '%\"source\": \"shorts_live\"%' "
f"OR {meta_col} LIKE '%\"source\":\"shorts_live\"%')",
[],
)
if p in ("douyin", "dy"):
return (
f"({room_col} NOT LIKE 'yt:%' AND {room_col} NOT LIKE 'shorts:%' "
f"AND IFNULL({meta_col},'') NOT LIKE '%\"platform\": \"youtube\"%' "
f"AND IFNULL({meta_col},'') NOT LIKE '%\"platform\":\"youtube\"%')",
[],
)
return ("", [])
def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None:
if row is None:
return None
data = dict(row)
if "enabled" in data:
data["enabled"] = bool(data["enabled"])
if "tags" in data:
raw = data.get("tags") or ""
data["tags"] = [t.strip() for t in str(raw).split(",") if t.strip()]
if "urls" in data and "channel_url" in data:
# channel_groups.urls stored as newline-separated
raw_urls = str(data.get("urls") or "")
data["urls"] = [u for u in raw_urls.replace("\r\n", "\n").split("\n") if u.strip()]
data["url_count"] = len(data["urls"])
if "metadata_json" in data:
try:
data["metadata"] = json.loads(data.pop("metadata_json") or "{}")
except json.JSONDecodeError:
data["metadata"] = {}
if "meta_json" in data:
try:
data["meta"] = json.loads(data.pop("meta_json") or "{}")
except json.JSONDecodeError:
data["meta"] = {}
if data.get("cover_path"):
raw = str(data.get("cover_path") or "").strip()
# Prefer public S3 URL directly; keep proxy path as fallback for private/local
if raw.startswith("http://") or raw.startswith("https://"):
data["cover_url"] = raw
data["cover_proxy_url"] = f"/api/sessions/{data['id']}/cover"
else:
data["cover_url"] = f"/api/sessions/{data['id']}/cover"
data["cover_proxy_url"] = data["cover_url"]
else:
if "cover_path" in data:
data["cover_url"] = ""
data["cover_proxy_url"] = ""
if data.get("status") == "active" and data.get("started_at") and not data.get("ended_at"):
data["duration_seconds"] = int(max(0, time.time() - float(data["started_at"])))
return data
def _normalize_tags(tags: Any) -> str:
if tags is None:
return ""
if isinstance(tags, str):
parts = [t.strip() for t in tags.replace(",", ",").split(",") if t.strip()]
elif isinstance(tags, list):
parts = [str(t).strip() for t in tags if str(t).strip()]
else:
parts = []
# unique preserve order
seen: set[str] = set()
out: list[str] = []
for p in parts:
if p not in seen:
seen.add(p)
out.append(p)
return ",".join(out)
# ---------- rooms ----------
def list_rooms(
*,
q: str = "",
enabled: Optional[bool] = None,
status: str = "",
tag: str = "",
limit: int = 500,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
if q.strip():
like = f"%{q.strip()}%"
clauses.append("(url LIKE ? OR room_id LIKE ? OR note LIKE ? OR last_anchor LIKE ? OR tags LIKE ?)")
params.extend([like, like, like, like, like])
if enabled is not None:
clauses.append("enabled = ?")
params.append(1 if enabled else 0)
if status.strip():
clauses.append("last_status = ?")
params.append(status.strip())
if tag.strip():
clauses.append("(tags = ? OR tags LIKE ? OR tags LIKE ? OR tags LIKE ?)")
t = tag.strip()
params.extend([t, f"{t},%", f"%,{t}", f"%,{t},%"])
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
total = conn.execute(f"SELECT COUNT(*) AS c FROM rooms {where}", params).fetchone()["c"]
rows = conn.execute(
f"SELECT * FROM rooms {where} ORDER BY "
f"CASE last_status WHEN 'live' THEN 0 WHEN 'error' THEN 1 WHEN 'offline' THEN 2 ELSE 3 END, "
f"updated_at DESC LIMIT ? OFFSET ?",
[*params, max(1, min(limit, 2000)), max(0, offset)],
).fetchall()
return {
"rooms": [_row_to_dict(r) for r in rows],
"total": int(total),
"limit": limit,
"offset": offset,
}
finally:
conn.close()
def get_room(room_pk: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone()
return _row_to_dict(row)
finally:
conn.close()
PRIORITY_TAGS = {"重点", "收藏", "priority", "vip", "高优"}
FAVORITE_TAG = "收藏"
def is_favorite_tags(tags: Any) -> bool:
if isinstance(tags, str):
items = [t.strip() for t in tags.split(",") if t.strip()]
elif isinstance(tags, list):
items = [str(t).strip() for t in tags if str(t).strip()]
else:
items = []
return any(t in PRIORITY_TAGS for t in items)
def find_room(*, room_pk: str = "", room_id: str = "", url: str = "") -> dict[str, Any] | None:
pk = (room_pk or "").strip()
rid = (room_id or "").strip()
raw_url = (url or "").strip()
if rid.startswith("yt:"):
return None
with _lock:
conn = _connect()
try:
if pk:
row = conn.execute("SELECT * FROM rooms WHERE id = ?", (pk,)).fetchone()
if row:
return _row_to_dict(row)
if rid:
row = conn.execute("SELECT * FROM rooms WHERE room_id = ?", (rid,)).fetchone()
if row:
return _row_to_dict(row)
if raw_url:
normalized = normalize_room_url(raw_url)
extracted = extract_room_id(normalized)
if extracted:
row = conn.execute("SELECT * FROM rooms WHERE room_id = ?", (extracted,)).fetchone()
if row:
return _row_to_dict(row)
row = conn.execute("SELECT * FROM rooms WHERE url = ?", (normalized,)).fetchone()
if row:
return _row_to_dict(row)
return None
finally:
conn.close()
def quick_room_action(
action: str,
*,
room_pk: str = "",
room_id: str = "",
url: str = "",
reason: str = "",
) -> dict[str, Any]:
action = (action or "").strip().lower()
if action not in {"favorite", "unfavorite", "ban"}:
raise ValueError("不支持的快捷操作")
if (room_id or "").startswith("yt:") or "youtube.com" in (url or "").lower() or "youtu.be" in (url or "").lower():
raise ValueError("YouTube 请到「分组」管理,暂不支持抖音式收藏/拉黑")
room = find_room(room_pk=room_pk, room_id=room_id, url=url)
if action == "ban":
value = (url or "").strip() or (room or {}).get("url") or (room_id or room_pk or "").strip()
if not value:
raise ValueError("缺少可拉黑的房间号 / URL")
item = add_blacklist(value, reason=reason or "快捷拉黑")
return {"action": "ban", "item": item, "room": room}
# favorite / unfavorite
if not room:
seed = (url or "").strip() or (room_id or "").strip()
if not seed:
raise ValueError("找不到直播间,请提供房间号或 URL")
try:
room = create_room(seed, note="收藏时自动添加", enabled=True, tags=FAVORITE_TAG if action == "favorite" else "")
except ValueError as exc:
# already exists race / blacklisted
room = find_room(room_id=room_id, url=url or seed)
if not room:
raise exc
assert room is not None
pk = str(room["id"])
if action == "favorite":
bulk_rooms("add_tags", [pk], tags=FAVORITE_TAG)
# also keep 重点 for quieter-hours priority semantics users already know
bulk_rooms("add_tags", [pk], tags="重点")
else:
bulk_rooms("remove_tags", [pk], tags=f"{FAVORITE_TAG},重点")
room = get_room(pk)
return {
"action": action,
"room": room,
"favorited": is_favorite_tags((room or {}).get("tags")),
}
def create_room(url: str, note: str = "", enabled: bool = True, tags: Any = None) -> dict[str, Any]:
now = time.time()
normalized = normalize_room_url(url)
rid = extract_room_id(normalized)
if not rid:
raise ValueError("无法解析抖音直播间 URL / 房间号")
room_id = str(uuid.uuid4())
tags_s = _normalize_tags(tags)
with _lock:
conn = _connect()
try:
existing = conn.execute(
"SELECT id FROM rooms WHERE room_id = ? OR url = ?",
(rid, normalized),
).fetchone()
if existing:
raise ValueError("该直播间已存在")
blocked = _is_blacklisted_conn(conn, rid, normalized)
if blocked:
raise ValueError(f"该直播间在黑名单中:{blocked.get('reason') or blocked.get('value')}")
conn.execute(
"""
INSERT INTO rooms(
id, url, room_id, note, enabled, last_status, tags, created_at, updated_at, next_check_at
) VALUES (?, ?, ?, ?, ?, 'unknown', ?, ?, ?, ?)
""",
(room_id, normalized, rid, note.strip(), 1 if enabled else 0, tags_s, now, now, now),
)
conn.commit()
row = conn.execute("SELECT * FROM rooms WHERE id = ?", (room_id,)).fetchone()
return _row_to_dict(row) # type: ignore
finally:
conn.close()
def update_room(
room_pk: str,
*,
url: Optional[str] = None,
note: Optional[str] = None,
enabled: Optional[bool] = None,
tags: Any = None,
clip_sec: Optional[int] = None,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone()
if not row:
raise ValueError("直播间不存在")
new_url = normalize_room_url(url) if url else row["url"]
new_rid = extract_room_id(new_url)
new_note = note if note is not None else row["note"]
new_enabled = (1 if enabled else 0) if enabled is not None else row["enabled"]
new_tags = _normalize_tags(tags) if tags is not None else (row["tags"] if "tags" in row.keys() else "")
keys = row.keys()
cur_clip = int(row["clip_sec"] or 0) if "clip_sec" in keys else 0
new_clip = cur_clip
if clip_sec is not None:
try:
new_clip = int(clip_sec)
except Exception:
new_clip = 0
if new_clip < 0:
new_clip = 0
if new_clip > 120:
new_clip = 120
conn.execute(
"""
UPDATE rooms SET url = ?, room_id = ?, note = ?, enabled = ?, tags = ?, clip_sec = ?, updated_at = ?
WHERE id = ?
""",
(new_url, new_rid, new_note, new_enabled, new_tags, new_clip, time.time(), room_pk),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone()) # type: ignore
finally:
conn.close()
def room_clip_seconds(room_or_pk: Any, *, default: int = 15, platform: str = "shorts") -> int:
"""Per-room clip length override; 0 means use global default."""
room = None
if isinstance(room_or_pk, dict):
room = room_or_pk
elif room_or_pk:
room = get_room(str(room_or_pk))
override = 0
if room:
try:
override = int(room.get("clip_sec") or 0)
except Exception:
override = 0
if override > 0:
return max(5, min(120, override))
try:
d = int(default or 0)
except Exception:
d = 0
if d <= 0:
return 0
return max(5, min(120, d))
def get_kv(key: str) -> Any:
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT value FROM kv_settings WHERE key = ?", (key,)).fetchone()
if not row:
return None
try:
return json.loads(row["value"])
except Exception:
return row["value"]
finally:
conn.close()
def set_kv(key: str, value: Any) -> None:
with _lock:
conn = _connect()
try:
conn.execute(
"INSERT INTO kv_settings(key, value) VALUES(?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(key, json.dumps(value)),
)
conn.commit()
finally:
conn.close()
def bulk_rooms(action: str, ids: list[str], *, tags: Any = None) -> dict[str, Any]:
action = (action or "").strip().lower()
ids = [i for i in ids if i]
if not ids:
raise ValueError("未选择直播间")
if action not in {"enable", "disable", "delete", "set_tags", "add_tags", "remove_tags", "check_queue"}:
raise ValueError("不支持的批量操作")
affected = 0
now = time.time()
with _lock:
conn = _connect()
try:
if action == "delete":
for i in ids:
conn.execute("DELETE FROM rooms WHERE id = ?", (i,))
affected += 1
elif action == "enable":
for i in ids:
conn.execute(
"UPDATE rooms SET enabled = 1, next_check_at = ?, updated_at = ? WHERE id = ?",
(now, now, i),
)
affected += 1
elif action == "disable":
for i in ids:
conn.execute("UPDATE rooms SET enabled = 0, updated_at = ? WHERE id = ?", (now, i))
affected += 1
elif action == "set_tags":
tags_s = _normalize_tags(tags)
for i in ids:
conn.execute("UPDATE rooms SET tags = ?, updated_at = ? WHERE id = ?", (tags_s, now, i))
affected += 1
elif action == "add_tags":
add = [t for t in _normalize_tags(tags).split(",") if t]
for i in ids:
row = conn.execute("SELECT tags FROM rooms WHERE id = ?", (i,)).fetchone()
if not row:
continue
merged = _normalize_tags(((row["tags"] or "") + "," + ",".join(add)).strip(","))
conn.execute("UPDATE rooms SET tags = ?, updated_at = ? WHERE id = ?", (merged, now, i))
affected += 1
elif action == "remove_tags":
remove = set(t for t in _normalize_tags(tags).split(",") if t)
for i in ids:
row = conn.execute("SELECT tags FROM rooms WHERE id = ?", (i,)).fetchone()
if not row:
continue
cur = [t for t in str(row["tags"] or "").split(",") if t.strip()]
kept = [t for t in cur if t not in remove]
conn.execute(
"UPDATE rooms SET tags = ?, updated_at = ? WHERE id = ?",
(_normalize_tags(kept), now, i),
)
affected += 1
elif action == "check_queue":
for i in ids:
conn.execute(
"UPDATE rooms SET next_check_at = ?, updated_at = ? WHERE id = ?",
(now, now, i),
)
affected += 1
conn.commit()
finally:
conn.close()
return {"action": action, "affected": affected, "ids": ids}
def delete_room(room_pk: str) -> None:
with _lock:
conn = _connect()
try:
conn.execute("DELETE FROM rooms WHERE id = ?", (room_pk,))
conn.commit()
finally:
conn.close()
def due_rooms(limit: int = 20) -> list[dict[str, Any]]:
now = time.time()
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT * FROM rooms
WHERE enabled = 1 AND next_check_at <= ?
ORDER BY next_check_at ASC
LIMIT ?
""",
(now, limit),
).fetchall()
result = []
for row in rows:
item = _row_to_dict(row)
if item and not _is_blacklisted_conn(conn, item["room_id"], item["url"]):
result.append(item)
return result
finally:
conn.close()
def touch_room(
room_pk: str,
*,
last_status: str,
last_anchor: str = "",
last_title: str = "",
next_check_at: float,
error_count: int = 0,
last_error: str = "",
active_session_id: str = "",
) -> None:
with _lock:
conn = _connect()
try:
conn.execute(
"""
UPDATE rooms SET
last_status = ?,
last_anchor = COALESCE(NULLIF(?, ''), last_anchor),
last_title = COALESCE(NULLIF(?, ''), last_title),
last_checked_at = ?,
next_check_at = ?,
error_count = ?,
last_error = ?,
active_session_id = ?,
updated_at = ?
WHERE id = ?
""",
(
last_status,
last_anchor,
last_title,
time.time(),
next_check_at,
error_count,
last_error,
active_session_id,
time.time(),
room_pk,
),
)
conn.commit()
finally:
conn.close()
# ---------- blacklist ----------
def _is_blacklisted_conn(conn: sqlite3.Connection, room_id: str, url: str = "") -> dict[str, Any] | None:
rows = conn.execute("SELECT * FROM blacklist").fetchall()
rid = (room_id or "").lower()
url_l = (url or "").lower()
for row in rows:
val = (row["value"] or "").strip().lower()
br = (row["room_id"] or "").strip().lower()
if not val and not br:
continue
if br and br == rid:
return dict(row)
if val and (val == rid or val in url_l or (rid and val == rid)):
return dict(row)
if val and rid and val in rid:
return dict(row)
return None
def is_blacklisted(room_id: str, url: str = "") -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
return _is_blacklisted_conn(conn, room_id, url)
finally:
conn.close()
def _blacklist_resolve_anchor(conn: sqlite3.Connection, room_id: str, value: str) -> str:
rid = (room_id or "").strip()
val = (value or "").strip()
if rid:
row = conn.execute(
"SELECT last_anchor, note FROM rooms WHERE room_id = ? ORDER BY updated_at DESC LIMIT 1",
(rid,),
).fetchone()
if row:
name = str(row["last_anchor"] or row["note"] or "").strip()
if name:
return name
row = conn.execute(
"SELECT anchor_name FROM sessions WHERE room_id = ? ORDER BY started_at DESC LIMIT 1",
(rid,),
).fetchone()
if row and row["anchor_name"]:
return str(row["anchor_name"]).strip()
if val:
row = conn.execute(
"""
SELECT last_anchor, note FROM rooms
WHERE room_id = ? OR url LIKE ? OR note LIKE ? OR last_anchor LIKE ?
ORDER BY updated_at DESC LIMIT 1
""",
(val, f"%{val}%", f"%{val}%", f"%{val}%"),
).fetchone()
if row:
name = str(row["last_anchor"] or row["note"] or "").strip()
if name:
return name
return ""
def list_blacklist() -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
rows = conn.execute("SELECT * FROM blacklist ORDER BY created_at DESC").fetchall()
items: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
item["anchor_name"] = _blacklist_resolve_anchor(
conn, str(item.get("room_id") or ""), str(item.get("value") or "")
)
items.append(item)
return items
finally:
conn.close()
def add_blacklist(value: str, reason: str = "") -> dict[str, Any]:
text = (value or "").strip()
if not text:
raise ValueError("黑名单内容不能为空")
rid = extract_room_id(text)
item_id = str(uuid.uuid4())
now = time.time()
disabled_ids: list[str] = []
ended_sessions: list[str] = []
with _lock:
conn = _connect()
try:
conn.execute(
"INSERT INTO blacklist(id, value, room_id, reason, created_at) VALUES (?, ?, ?, ?, ?)",
(item_id, text, rid, reason.strip(), now),
)
rooms = conn.execute("SELECT * FROM rooms").fetchall()
for room in rooms:
hit = False
if rid and room["room_id"] == rid:
hit = True
val_l = text.lower()
if val_l and (
val_l == str(room["room_id"]).lower()
or val_l in str(room["url"]).lower()
or val_l in str(room["note"] or "").lower()
or val_l in str(room["last_anchor"] or "").lower()
):
hit = True
if not hit:
continue
conn.execute(
"UPDATE rooms SET enabled = 0, updated_at = ? WHERE id = ?",
(now, room["id"]),
)
disabled_ids.append(room["id"])
sid = room["active_session_id"] or ""
if sid:
row = conn.execute("SELECT * FROM sessions WHERE id = ? AND ended_at IS NULL", (sid,)).fetchone()
if row:
duration = max(0.0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = 'blacklisted', updated_at = ? WHERE id = ?
""",
(now, duration, now, sid),
)
conn.execute(
"UPDATE rooms SET active_session_id = '' WHERE id = ?",
(room["id"],),
)
ended_sessions.append(sid)
conn.commit()
item = dict(conn.execute("SELECT * FROM blacklist WHERE id = ?", (item_id,)).fetchone())
item["disabled_rooms"] = len(disabled_ids)
item["ended_sessions"] = len(ended_sessions)
return item
except sqlite3.IntegrityError as exc:
raise ValueError("黑名单已存在") from exc
finally:
conn.close()
def delete_blacklist(item_id: str) -> None:
with _lock:
conn = _connect()
try:
conn.execute("DELETE FROM blacklist WHERE id = ?", (item_id,))
conn.commit()
finally:
conn.close()
# ---------- events ----------
def add_event(
*,
kind: str,
message: str,
level: str = "info",
room_id: str = "",
room_pk: str = "",
session_id: str = "",
anchor_name: str = "",
meta: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
eid = str(uuid.uuid4())
now = time.time()
with _lock:
conn = _connect()
try:
conn.execute(
"""
INSERT INTO events(id, ts, level, kind, room_id, room_pk, session_id, anchor_name, message, meta_json)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
eid,
now,
level,
kind,
room_id,
room_pk,
session_id,
anchor_name,
message,
json.dumps(meta or {}, ensure_ascii=False),
),
)
conn.commit()
row = _row_to_dict(conn.execute("SELECT * FROM events WHERE id = ?", (eid,)).fetchone())
finally:
conn.close()
if row:
try:
from .events_bus import bus
bus.publish_sync(row)
except Exception:
pass
# Fire-and-forget PocketBase dual-write (do not block hot path)
try:
import asyncio
from . import pb_sync
try:
loop = asyncio.get_running_loop()
loop.create_task(pb_sync.sync_event(row))
except RuntimeError:
# Called from sync context without a loop
pass
except Exception:
pass
return row # type: ignore
def purge_events(*, older_than_days: float = 7, kind: str = "") -> int:
cutoff = time.time() - max(0.1, older_than_days) * 86400
with _lock:
conn = _connect()
try:
if kind.strip():
cur = conn.execute("DELETE FROM events WHERE ts < ? AND kind = ?", (cutoff, kind.strip()))
else:
cur = conn.execute("DELETE FROM events WHERE ts < ?", (cutoff,))
conn.commit()
return int(cur.rowcount or 0)
finally:
conn.close()
def _close_session_row(conn: sqlite3.Connection, row: sqlite3.Row, *, now: float, end_reason: str) -> None:
duration = max(0.0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = ?, updated_at = ? WHERE id = ?
""",
(now, duration, end_reason, now, row["id"]),
)
def dedupe_active_sessions() -> int:
"""Keep one active session per room_id / room_pk; end the rest as duplicates."""
now = time.time()
closed = 0
with _lock:
conn = _connect()
try:
rows = conn.execute(
"SELECT * FROM sessions WHERE status = 'active' AND ended_at IS NULL ORDER BY started_at ASC"
).fetchall()
keep_by_room_id: dict[str, str] = {}
keep_by_room_pk: dict[str, str] = {}
for row in rows:
rid = str(row["room_id"] or "")
rpk = str(row["room_pk"] or "")
sid = str(row["id"])
drop = False
if rid and rid in keep_by_room_id and keep_by_room_id[rid] != sid:
drop = True
if rpk and rpk in keep_by_room_pk and keep_by_room_pk[rpk] != sid:
drop = True
if drop:
_close_session_row(conn, row, now=now, end_reason="duplicate")
closed += 1
continue
if rid:
keep_by_room_id[rid] = sid
if rpk:
keep_by_room_pk[rpk] = sid
for rpk, sid in keep_by_room_pk.items():
conn.execute(
"UPDATE rooms SET active_session_id = ?, updated_at = ? WHERE id = ?",
(sid, now, rpk),
)
conn.commit()
return closed
finally:
conn.close()
def list_active_sessions(*, dedupe: bool = True, platform: str = "") -> list[dict[str, Any]]:
if dedupe:
dedupe_active_sessions()
with _lock:
conn = _connect()
try:
plat_sql, plat_params = _platform_clause(
platform, room_col="room_id", meta_col="metadata_json"
)
where = "WHERE status = 'active' AND ended_at IS NULL"
params: list[Any] = []
if plat_sql:
where += f" AND {plat_sql}"
params.extend(plat_params)
rows = conn.execute(
f"SELECT * FROM sessions {where} ORDER BY started_at DESC",
params,
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
finally:
conn.close()
def end_all_active_sessions(*, end_reason: str = "manual") -> int:
now = time.time()
with _lock:
conn = _connect()
try:
rows = conn.execute(
"SELECT id, started_at FROM sessions WHERE status = 'active' AND ended_at IS NULL"
).fetchall()
for row in rows:
duration = max(0.0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = ?, updated_at = ? WHERE id = ?
""",
(now, duration, end_reason, now, row["id"]),
)
conn.execute("UPDATE rooms SET active_session_id = '', updated_at = ?", (now,))
conn.commit()
return len(rows)
finally:
conn.close()
def export_rooms_rows() -> list[dict[str, Any]]:
data = list_rooms(limit=5000, offset=0)
return data["rooms"] # type: ignore
def anchor_profile(name_or_room: str) -> dict[str, Any] | None:
key = (name_or_room or "").strip()
if not key:
return None
with _lock:
conn = _connect()
try:
like = f"%{key}%"
sessions = [
_row_to_dict(r)
for r in conn.execute(
"""
SELECT * FROM sessions
WHERE anchor_name = ? OR room_id = ? OR anchor_name LIKE ? OR room_id LIKE ?
ORDER BY started_at DESC LIMIT 200
""",
(key, key, like, like),
).fetchall()
]
rooms = [
_row_to_dict(r)
for r in conn.execute(
"""
SELECT * FROM rooms
WHERE last_anchor = ? OR room_id = ? OR last_anchor LIKE ? OR room_id LIKE ?
ORDER BY updated_at DESC LIMIT 20
""",
(key, key, like, like),
).fetchall()
]
finally:
conn.close()
if not sessions and not rooms:
return None
now = time.time()
durations = []
total = 0.0
for s in sessions:
if not s:
continue
started = float(s.get("started_at") or 0)
ended = s.get("ended_at")
dur = float(ended) - started if ended else max(0.0, now - started)
durations.append(dur)
total += dur
anchor_name = ""
room_id = ""
if sessions and sessions[0]:
anchor_name = sessions[0].get("anchor_name") or ""
room_id = sessions[0].get("room_id") or ""
if rooms and rooms[0]:
anchor_name = anchor_name or rooms[0].get("last_anchor") or ""
room_id = room_id or rooms[0].get("room_id") or ""
return {
"anchor_name": anchor_name or key,
"room_id": room_id,
"rooms": rooms,
"sessions": sessions,
"overview": {
"sessions": len(sessions),
"total_hours": round(total / 3600.0, 2),
"avg_duration_seconds": int(sum(durations) / len(durations)) if durations else 0,
"active": sum(1 for s in sessions if s and not s.get("ended_at")),
"last_started_at": sessions[0].get("started_at") if sessions and sessions[0] else 0,
},
}
def list_anchors(*, limit: int = 50) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT
COALESCE(NULLIF(anchor_name, ''), room_id) AS name,
room_id,
COUNT(*) AS sessions,
SUM(CASE WHEN ended_at IS NULL THEN (? - started_at) ELSE duration_seconds END) AS duration_seconds,
MAX(started_at) AS last_started_at,
SUM(CASE WHEN ended_at IS NULL THEN 1 ELSE 0 END) AS active
FROM sessions
GROUP BY COALESCE(NULLIF(anchor_name, ''), room_id), room_id
ORDER BY sessions DESC, duration_seconds DESC
LIMIT ?
""",
(time.time(), max(1, min(limit, 200))),
).fetchall()
out = []
for r in rows:
out.append(
{
"anchor_name": r["name"],
"room_id": r["room_id"],
"sessions": int(r["sessions"] or 0),
"hours_total": round(float(r["duration_seconds"] or 0) / 3600.0, 2),
"last_started_at": r["last_started_at"],
"active": int(r["active"] or 0),
}
)
return out
finally:
conn.close()
def list_events(
*,
kind: str = "",
q: str = "",
platform: str = "",
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
if kind.strip():
clauses.append("kind = ?")
params.append(kind.strip())
if q.strip():
like = f"%{q.strip()}%"
clauses.append("(message LIKE ? OR anchor_name LIKE ? OR room_id LIKE ?)")
params.extend([like, like, like])
plat_sql, plat_params = _platform_clause(platform, room_col="room_id", meta_col="meta_json")
if plat_sql:
clauses.append(plat_sql)
params.extend(plat_params)
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
total = conn.execute(f"SELECT COUNT(*) AS c FROM events {where}", params).fetchone()["c"]
rows = conn.execute(
f"SELECT * FROM events {where} ORDER BY ts DESC LIMIT ? OFFSET ?",
[*params, max(1, min(limit, 500)), max(0, offset)],
).fetchall()
return {
"events": [_row_to_dict(r) for r in rows],
"total": int(total),
"limit": limit,
"offset": offset,
}
finally:
conn.close()
def list_all_tags() -> list[str]:
with _lock:
conn = _connect()
try:
rows = conn.execute("SELECT tags FROM rooms WHERE tags != ''").fetchall()
bag: set[str] = set()
for row in rows:
for t in str(row["tags"] or "").split(","):
if t.strip():
bag.add(t.strip())
return sorted(bag)
finally:
conn.close()
# ---------- sessions (helpers already above) ----------
def export_sessions_rows(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
tag: str = "",
platform: str = "",
limit: int = 5000,
) -> list[dict[str, Any]]:
data = list_sessions(
q=q,
date_from=date_from,
date_to=date_to,
status=status,
tag=tag,
platform=platform,
limit=limit,
offset=0,
)
return data["sessions"] # type: ignore
def counts() -> dict[str, int]:
with _lock:
conn = _connect()
try:
rooms = conn.execute("SELECT COUNT(*) AS c FROM rooms").fetchone()["c"]
enabled = conn.execute("SELECT COUNT(*) AS c FROM rooms WHERE enabled = 1").fetchone()["c"]
live = conn.execute("SELECT COUNT(*) AS c FROM rooms WHERE last_status = 'live'").fetchone()["c"]
bl = conn.execute("SELECT COUNT(*) AS c FROM blacklist").fetchone()["c"]
active = conn.execute("SELECT COUNT(*) AS c FROM sessions WHERE status = 'active'").fetchone()["c"]
events = conn.execute("SELECT COUNT(*) AS c FROM events").fetchone()["c"]
return {
"rooms": int(rooms),
"enabled_rooms": int(enabled),
"live_rooms": int(live),
"blacklist": int(bl),
"active_sessions": int(active),
"events": int(events),
}
finally:
conn.close()
# ---------- sessions ----------
def _is_yt_room_id(room_id: str) -> bool:
return str(room_id or "").startswith("yt:")
def _set_live_owner(conn, *, room_pk: str, session_id: str, now: float) -> None:
"""Mark Douyin room / YouTube group / Shorts channel as live with active session."""
cur = conn.execute(
"UPDATE rooms SET active_session_id = ?, last_status = 'live', updated_at = ? WHERE id = ?",
(session_id, now, room_pk),
)
if cur.rowcount:
return
cur = conn.execute(
"""
UPDATE channel_groups SET active_session_id = ?, last_status = 'live', updated_at = ?
WHERE id = ?
""",
(session_id, now, room_pk),
)
if cur.rowcount:
return
conn.execute(
"""
UPDATE shorts_channels SET active_session_id = ?, last_status = 'live', updated_at = ?
WHERE id = ?
""",
(session_id, now, room_pk),
)
def _clear_live_owner_for_session(conn, *, session_id: str, room_pk: str, now: float) -> None:
conn.execute(
"UPDATE rooms SET active_session_id = '', updated_at = ? WHERE active_session_id = ?",
(now, session_id),
)
if room_pk:
conn.execute(
"""
UPDATE channel_groups SET active_session_id = '', updated_at = ?
WHERE id = ? AND active_session_id = ?
""",
(now, room_pk, session_id),
)
conn.execute(
"""
UPDATE shorts_channels SET active_session_id = '', updated_at = ?
WHERE id = ? AND active_session_id = ?
""",
(now, room_pk, session_id),
)
def start_session(
*,
room_pk: str,
room_id: str,
source_url: str,
anchor_name: str,
title: str = "",
metadata: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""Idempotent: one active session per room. Concurrent calls reuse the existing row."""
now = time.time()
with _lock:
conn = _connect()
try:
existing = conn.execute(
"""
SELECT * FROM sessions
WHERE status = 'active' AND ended_at IS NULL
AND (room_pk = ? OR room_id = ?)
ORDER BY started_at ASC
LIMIT 1
""",
(room_pk, room_id),
).fetchone()
if existing:
extras = conn.execute(
"""
SELECT * FROM sessions
WHERE status = 'active' AND ended_at IS NULL
AND (room_pk = ? OR room_id = ?)
AND id != ?
""",
(room_pk, room_id, existing["id"]),
).fetchall()
for row in extras:
_close_session_row(conn, row, now=now, end_reason="duplicate")
conn.execute(
"""
UPDATE sessions SET anchor_name = COALESCE(NULLIF(?, ''), anchor_name),
title = COALESCE(NULLIF(?, ''), title),
source_url = COALESCE(NULLIF(?, ''), source_url),
updated_at = ?
WHERE id = ?
""",
(anchor_name, title, source_url, now, existing["id"]),
)
_set_live_owner(conn, room_pk=room_pk, session_id=existing["id"], now=now)
conn.commit()
out = _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (existing["id"],)).fetchone())
out["_reused"] = True
return out # type: ignore
sid = str(uuid.uuid4())
conn.execute(
"""
INSERT INTO sessions(
id, room_id, room_pk, source_url, anchor_name, title, started_at, ended_at,
duration_seconds, push_date, cover_path, status, end_reason, metadata_json,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 0, ?, '', 'active', '', ?, ?, ?)
""",
(
sid,
room_id,
room_pk,
source_url,
anchor_name,
title,
now,
push_date_from_ts(now),
json.dumps(metadata or {}, ensure_ascii=False),
now,
now,
),
)
_set_live_owner(conn, room_pk=room_pk, session_id=sid, now=now)
conn.commit()
out = _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (sid,)).fetchone())
out["_reused"] = False
return out # type: ignore
finally:
conn.close()
def end_session(session_id: str, *, end_reason: str = "offline") -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone()
if not row:
return None
if row["ended_at"]:
return _row_to_dict(row)
duration = max(0.0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = ?, updated_at = ? WHERE id = ?
""",
(now, duration, end_reason, now, session_id),
)
_clear_live_owner_for_session(
conn, session_id=session_id, room_pk=str(row["room_pk"] or ""), now=now
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone())
finally:
conn.close()
def end_active_sessions_for_room(
*,
room_pk: str = "",
room_id: str = "",
end_reason: str = "offline",
) -> list[dict[str, Any]]:
"""End all active sessions for a room (by pk and/or web rid)."""
now = time.time()
ended: list[dict[str, Any]] = []
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT * FROM sessions
WHERE status = 'active' AND ended_at IS NULL
AND (
(? != '' AND room_pk = ?)
OR (? != '' AND room_id = ?)
)
""",
(room_pk, room_pk, room_id, room_id),
).fetchall()
for row in rows:
duration = max(0.0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = ?, updated_at = ? WHERE id = ?
""",
(now, duration, end_reason, now, row["id"]),
)
item = _row_to_dict(row)
item["ended_at"] = now
item["duration_seconds"] = duration
item["status"] = "ended"
item["end_reason"] = end_reason
ended.append(item)
if room_pk:
conn.execute(
"UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, room_pk),
)
conn.execute(
"UPDATE channel_groups SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, room_pk),
)
conn.execute(
"UPDATE shorts_channels SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, room_pk),
)
conn.commit()
return ended
finally:
conn.close()
def reconcile_stale_active_sessions() -> dict[str, Any]:
"""Close active sessions whose room is not live (zombie timers)."""
closed = 0
kept = 0
details: list[dict[str, str]] = []
with _lock:
conn = _connect()
try:
rows = conn.execute(
"SELECT * FROM sessions WHERE status = 'active' AND ended_at IS NULL"
).fetchall()
now = time.time()
for row in rows:
room_id = str(row["room_id"] or "")
room_pk = str(row["room_pk"] or "")
stale = False
reason = "keep"
owner = None
if _is_yt_room_id(room_id):
if room_pk:
owner = conn.execute(
"SELECT * FROM channel_groups WHERE id = ?", (room_pk,)
).fetchone()
owner_status = (owner["last_status"] if owner else "") or ""
if not owner:
stale = True
reason = "no_group"
elif owner_status in {"offline", "error", "unknown"}:
stale = True
reason = f"group_{owner_status}"
elif owner["active_session_id"] and owner["active_session_id"] != row["id"]:
stale = True
reason = "orphaned"
elif str(room_id).startswith("shorts:"):
if room_pk:
owner = conn.execute(
"SELECT * FROM shorts_channels WHERE id = ?", (room_pk,)
).fetchone()
owner_status = (owner["last_status"] if owner else "") or ""
if not owner:
stale = True
reason = "no_shorts_channel"
elif owner_status in {"offline", "error", "unknown"}:
stale = True
reason = f"shorts_{owner_status}"
elif owner["active_session_id"] and owner["active_session_id"] != row["id"]:
stale = True
reason = "orphaned"
else:
room = None
if room_pk:
room = conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone()
if not room and room_id:
room = conn.execute(
"SELECT * FROM rooms WHERE room_id = ?", (room_id,)
).fetchone()
owner = room
room_status = (room["last_status"] if room else "") or ""
if not room:
stale = True
reason = "no_room"
elif room_status in {"offline", "error", "unknown"}:
stale = True
reason = f"room_{room_status}"
elif room["active_session_id"] and room["active_session_id"] != row["id"]:
stale = True
reason = "orphaned"
if stale:
duration = max(0.0, now - float(row["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = ?, updated_at = ? WHERE id = ?
""",
(now, duration, f"reconcile:{reason}", now, row["id"]),
)
if owner and (owner["active_session_id"] or "") == row["id"]:
if _is_yt_room_id(room_id):
conn.execute(
"UPDATE channel_groups SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, owner["id"]),
)
elif str(room_id).startswith("shorts:"):
conn.execute(
"UPDATE shorts_channels SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, owner["id"]),
)
else:
conn.execute(
"UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, owner["id"]),
)
closed += 1
details.append(
{"id": row["id"], "anchor": row["anchor_name"] or "", "reason": reason}
)
else:
kept += 1
conn.commit()
return {"closed": closed, "kept": kept, "details": details}
finally:
conn.close()
def set_session_cover(session_id: str, cover_path: str) -> None:
with _lock:
conn = _connect()
try:
conn.execute(
"UPDATE sessions SET cover_path = ?, updated_at = ? WHERE id = ?",
(cover_path, time.time(), session_id),
)
conn.commit()
finally:
conn.close()
def get_session(session_id: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
return _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone())
finally:
conn.close()
def list_sessions_missing_cover(*, limit: int = 50) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT * FROM sessions
WHERE cover_path IS NULL OR trim(cover_path) = ''
ORDER BY started_at DESC
LIMIT ?
""",
(max(1, min(limit, 500)),),
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()
def list_sessions(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
tag: str = "",
platform: str = "",
limit: int = 50,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
join = ""
if status == "active":
clauses.append("s.ended_at IS NULL")
elif status == "ended":
clauses.append("s.ended_at IS NOT NULL")
if date_from:
clauses.append("s.push_date >= ?")
params.append(date_from)
if date_to:
clauses.append("s.push_date <= ?")
params.append(date_to)
if q.strip():
like = f"%{q.strip()}%"
clauses.append(
"(s.anchor_name LIKE ? OR s.source_url LIKE ? OR s.room_id LIKE ? OR s.title LIKE ?)"
)
params.extend([like, like, like, like])
if tag.strip():
join = "LEFT JOIN rooms r ON r.id = s.room_pk"
t = tag.strip()
clauses.append("(r.tags = ? OR r.tags LIKE ? OR r.tags LIKE ? OR r.tags LIKE ?)")
params.extend([t, f"{t},%", f"%,{t}", f"%,{t},%"])
plat_sql, plat_params = _platform_clause(
platform, room_col="s.room_id", meta_col="s.metadata_json"
)
if plat_sql:
clauses.append(plat_sql)
params.extend(plat_params)
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
total = conn.execute(
f"SELECT COUNT(*) AS c FROM sessions s {join} {where}",
params,
).fetchone()["c"]
rows = conn.execute(
f"SELECT s.* FROM sessions s {join} {where} ORDER BY s.started_at DESC LIMIT ? OFFSET ?",
[*params, max(1, min(limit, 10000)), max(0, offset)],
).fetchall()
return {
"sessions": [_row_to_dict(r) for r in rows],
"total": int(total),
"limit": limit,
"offset": offset,
}
finally:
conn.close()
def list_upcoming_opens(*, limit: int = 20, priority_only: bool = False) -> list[dict[str, Any]]:
"""Heuristic next-open list from recent sessions + room tags."""
from .stats import summarize_anchor_schedule
priority_tags = {"重点", "收藏", "priority", "vip", "高优"}
with _lock:
conn = _connect()
try:
room_rows = conn.execute(
"""
SELECT id, room_id, url, last_anchor, last_status, tags, enabled
FROM rooms WHERE enabled = 1
"""
).fetchall()
rooms_by_rid = {str(r["room_id"]): _row_to_dict(r) for r in room_rows if r["room_id"]}
# Recent anchors with enough history
sess_groups = conn.execute(
"""
SELECT COALESCE(NULLIF(anchor_name, ''), room_id) AS name, room_id,
COUNT(*) AS c
FROM sessions
WHERE started_at > ?
GROUP BY COALESCE(NULLIF(anchor_name, ''), room_id), room_id
HAVING c >= 1
ORDER BY c DESC
LIMIT 120
""",
(time.time() - 14 * 86400,),
).fetchall()
session_cache: dict[str, list[dict[str, Any]]] = {}
for g in sess_groups:
name = str(g["name"] or "")
rid = str(g["room_id"] or "")
key = name or rid
if not key:
continue
rows = conn.execute(
"""
SELECT * FROM sessions
WHERE (anchor_name = ? OR room_id = ?)
ORDER BY started_at DESC LIMIT 80
""",
(key, rid or key),
).fetchall()
session_cache[key] = [_row_to_dict(x) for x in rows]
finally:
conn.close()
items: list[dict[str, Any]] = []
for key, sessions in session_cache.items():
room = rooms_by_rid.get(str(sessions[0].get("room_id") or "")) if sessions else None
tags = (room or {}).get("tags") or []
if isinstance(tags, str):
tags = [t.strip() for t in tags.split(",") if t.strip()]
is_priority = any(t in priority_tags for t in tags)
if priority_only and not is_priority:
continue
if room and room.get("last_status") == "live":
continue
schedule = summarize_anchor_schedule(sessions)
hint = schedule.get("next_open_hint")
if not hint or not hint.get("eta_ts"):
continue
n_sess = len(sessions)
avg_gap = schedule.get("avg_gap_hours")
confidence = 0.35
if n_sess >= 8 and avg_gap and float(avg_gap) < 48:
confidence = 0.85
elif n_sess >= 4:
confidence = 0.65
elif n_sess >= 2:
confidence = 0.5
if is_priority:
confidence = min(0.95, confidence + 0.1)
items.append(
{
"anchor_name": (sessions[0].get("anchor_name") if sessions else "") or key,
"room_id": (room or {}).get("room_id") or (sessions[0].get("room_id") if sessions else ""),
"room_pk": (room or {}).get("id") or "",
"url": (room or {}).get("url") or (sessions[0].get("source_url") if sessions else ""),
"tags": tags,
"priority": is_priority,
"last_status": (room or {}).get("last_status") or "offline",
"typical_open_hint": schedule.get("typical_open_hint") or "",
"peak_slot_label": schedule.get("peak_slot_label") or "",
"next_open_hint": hint,
"eta_ts": float(hint["eta_ts"]),
"confidence": round(confidence, 2),
"sessions_sampled": n_sess,
}
)
items.sort(key=lambda x: (0 if x.get("priority") else 1, float(x.get("eta_ts") or 0)))
return items[: max(1, min(limit, 50))]
def all_sessions_for_stats(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
tag: str = "",
platform: str = "",
) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
join = ""
if status == "active":
clauses.append("s.ended_at IS NULL")
elif status == "ended":
clauses.append("s.ended_at IS NOT NULL")
if date_from:
clauses.append("s.push_date >= ?")
params.append(date_from)
if date_to:
clauses.append("s.push_date <= ?")
params.append(date_to)
if q.strip():
like = f"%{q.strip()}%"
clauses.append(
"(s.anchor_name LIKE ? OR s.source_url LIKE ? OR s.room_id LIKE ? OR s.title LIKE ?)"
)
params.extend([like, like, like, like])
if tag.strip():
join = "LEFT JOIN rooms r ON r.id = s.room_pk"
t = tag.strip()
clauses.append("(r.tags = ? OR r.tags LIKE ? OR r.tags LIKE ? OR r.tags LIKE ?)")
params.extend([t, f"{t},%", f"%,{t}", f"%,{t},%"])
plat_sql, plat_params = _platform_clause(
platform, room_col="s.room_id", meta_col="s.metadata_json"
)
if plat_sql:
clauses.append(plat_sql)
params.extend(plat_params)
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
rows = conn.execute(
f"SELECT s.* FROM sessions s {join} {where} ORDER BY s.started_at ASC",
params,
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
finally:
conn.close()
def youtube_group_channel_stats(
*,
date_from: str = "",
date_to: str = "",
) -> list[dict[str, Any]]:
"""Per YouTube monitored channel: session counts / hours (Beijing push_date range)."""
with _lock:
conn = _connect()
try:
clauses = [
"(s.room_id LIKE 'yt:%' OR IFNULL(s.metadata_json,'') LIKE '%\"platform\": \"youtube\"%' "
"OR IFNULL(s.metadata_json,'') LIKE '%\"platform\":\"youtube\"%')"
]
params: list[Any] = [time.time()]
if date_from:
clauses.append("s.push_date >= ?")
params.append(date_from)
if date_to:
clauses.append("s.push_date <= ?")
params.append(date_to)
where = " AND ".join(clauses)
rows = conn.execute(
f"""
SELECT
s.room_pk AS group_id,
s.room_id AS room_id,
COALESCE(NULLIF(MAX(s.anchor_name), ''), MAX(s.room_id)) AS anchor_name,
COUNT(*) AS sessions,
SUM(CASE WHEN s.ended_at IS NULL THEN (? - s.started_at) ELSE s.duration_seconds END) AS duration_seconds,
MAX(s.started_at) AS last_started_at,
SUM(CASE WHEN s.ended_at IS NULL THEN 1 ELSE 0 END) AS active
FROM sessions s
WHERE {where}
GROUP BY s.room_pk, s.room_id
ORDER BY sessions DESC, duration_seconds DESC
""",
params,
).fetchall()
groups = {
str(g["id"]): g
for g in (
conn.execute(
"SELECT id, name, channel_id, channel_url, handle, enabled, last_status, last_title, last_live_url, last_checked_at FROM channel_groups WHERE platform = 'youtube'"
).fetchall()
)
}
out: list[dict[str, Any]] = []
for r in rows:
gid = str(r["group_id"] or "")
g = groups.get(gid) or {}
cid = ""
rid = str(r["room_id"] or "")
if rid.startswith("yt:"):
cid = rid[3:]
if not cid:
cid = str(g.get("channel_id") or "")
out.append(
{
"group_id": gid or None,
"name": str(g.get("name") or r["anchor_name"] or cid or rid),
"channel_id": cid,
"channel_url": str(g.get("channel_url") or ""),
"handle": str(g.get("handle") or ""),
"enabled": bool(g.get("enabled")) if g else None,
"last_status": str(g.get("last_status") or ("live" if int(r["active"] or 0) else "offline")),
"last_title": str(g.get("last_title") or ""),
"last_live_url": str(g.get("last_live_url") or ""),
"last_checked_at": g.get("last_checked_at"),
"room_id": rid,
"anchor_name": r["anchor_name"],
"sessions": int(r["sessions"] or 0),
"hours_total": round(float(r["duration_seconds"] or 0) / 3600.0, 2),
"last_started_at": r["last_started_at"],
"active": int(r["active"] or 0),
}
)
# Include enabled groups with zero sessions so ranking is complete
seen = {str(x.get("group_id") or "") for x in out if x.get("group_id")}
for gid, g in groups.items():
if gid in seen or not bool(g["enabled"]):
continue
out.append(
{
"group_id": gid,
"name": str(g["name"] or ""),
"channel_id": str(g["channel_id"] or ""),
"channel_url": str(g["channel_url"] or ""),
"handle": str(g["handle"] or ""),
"enabled": True,
"last_status": str(g["last_status"] or "offline"),
"last_title": str(g["last_title"] or ""),
"last_live_url": str(g["last_live_url"] or ""),
"last_checked_at": g["last_checked_at"],
"room_id": f"yt:{g['channel_id']}" if g["channel_id"] else "",
"anchor_name": str(g["name"] or ""),
"sessions": 0,
"hours_total": 0.0,
"last_started_at": None,
"active": 1 if str(g["last_status"] or "") == "live" else 0,
}
)
out.sort(key=lambda x: (-int(x.get("sessions") or 0), -float(x.get("hours_total") or 0)))
return out
finally:
conn.close()
# ---------- YouTube channel groups ----------
def _urls_to_storage(urls: Any) -> str:
from .models import normalize_url_list
return "\n".join(normalize_url_list(urls))
def list_channel_groups(
*,
q: str = "",
platform: str = "",
enabled: Optional[bool] = None,
limit: int = 200,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
if platform.strip():
clauses.append("platform = ?")
params.append(platform.strip())
if enabled is not None:
clauses.append("enabled = ?")
params.append(1 if enabled else 0)
if q.strip():
like = f"%{q.strip()}%"
clauses.append(
"(name LIKE ? OR channel_url LIKE ? OR channel_key LIKE ? OR handle LIKE ? OR channel_id LIKE ? OR note LIKE ? OR urls LIKE ?)"
)
params.extend([like, like, like, like, like, like, like])
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
total = conn.execute(f"SELECT COUNT(*) AS c FROM channel_groups {where}", params).fetchone()["c"]
rows = conn.execute(
f"SELECT * FROM channel_groups {where} ORDER BY updated_at DESC LIMIT ? OFFSET ?",
[*params, max(1, min(limit, 2000)), max(0, offset)],
).fetchall()
return {
"groups": [_row_to_dict(r) for r in rows],
"total": int(total),
"limit": limit,
"offset": offset,
}
finally:
conn.close()
def get_channel_group(group_id: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM channel_groups WHERE id = ?", (group_id,)).fetchone()
return _row_to_dict(row)
finally:
conn.close()
def create_channel_group(
*,
name: str,
channel_url: str,
urls: Any = "",
note: str = "",
platform: str = "youtube",
enabled: bool = True,
) -> dict[str, Any]:
from .models import extract_youtube_channel, normalize_youtube_channel_url
name_s = (name or "").strip()
if not name_s:
raise ValueError("分组名称不能为空")
info = extract_youtube_channel(channel_url)
normalized = normalize_youtube_channel_url(channel_url)
if not normalized:
raise ValueError("无效的 YouTube 频道 URL")
if not info.get("key"):
# still allow custom http URLs as channel_url, use url as key
info = {"channel_id": "", "handle": "", "key": normalized, "kind": "url"}
urls_s = _urls_to_storage(urls)
now = time.time()
gid = str(uuid.uuid4())
with _lock:
conn = _connect()
try:
# unique per platform+channel_key when key present
if info.get("key"):
exists = conn.execute(
"SELECT id FROM channel_groups WHERE platform = ? AND channel_key = ?",
(platform or "youtube", info["key"]),
).fetchone()
if exists:
raise ValueError(f"该频道已在分组中:{info['key']}")
conn.execute(
"""
INSERT INTO channel_groups(
id, name, platform, channel_url, channel_key, channel_id, handle,
urls, note, enabled, last_status, last_checked_at, next_check_at,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unknown', 0, ?, ?, ?)
""",
(
gid,
name_s,
(platform or "youtube").strip() or "youtube",
normalized,
info.get("key") or "",
info.get("channel_id") or "",
info.get("handle") or "",
urls_s,
(note or "").strip(),
1 if enabled else 0,
now, # due immediately
now,
now,
),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM channel_groups WHERE id = ?", (gid,)).fetchone()) # type: ignore
finally:
conn.close()
def update_channel_group(
group_id: str,
*,
name: Optional[str] = None,
channel_url: Optional[str] = None,
urls: Any = None,
note: Optional[str] = None,
platform: Optional[str] = None,
enabled: Optional[bool] = None,
) -> dict[str, Any]:
from .models import extract_youtube_channel, normalize_youtube_channel_url
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM channel_groups WHERE id = ?", (group_id,)).fetchone()
if not row:
raise ValueError("分组不存在")
new_name = (name if name is not None else row["name"]).strip()
if not new_name:
raise ValueError("分组名称不能为空")
new_platform = (platform if platform is not None else row["platform"]).strip() or "youtube"
new_note = note if note is not None else row["note"]
new_enabled = (1 if enabled else 0) if enabled is not None else int(row["enabled"])
new_urls = _urls_to_storage(urls) if urls is not None else row["urls"]
new_channel_url = row["channel_url"]
new_key = row["channel_key"]
new_cid = row["channel_id"]
new_handle = row["handle"]
if channel_url is not None:
info = extract_youtube_channel(channel_url)
new_channel_url = normalize_youtube_channel_url(channel_url)
if not new_channel_url:
raise ValueError("无效的 YouTube 频道 URL")
if not info.get("key"):
info = {"channel_id": "", "handle": "", "key": new_channel_url, "kind": "url"}
new_key = info.get("key") or ""
new_cid = info.get("channel_id") or ""
new_handle = info.get("handle") or ""
if new_key:
clash = conn.execute(
"SELECT id FROM channel_groups WHERE platform = ? AND channel_key = ? AND id != ?",
(new_platform, new_key, group_id),
).fetchone()
if clash:
raise ValueError(f"该频道已在其他分组中:{new_key}")
now = time.time()
conn.execute(
"""
UPDATE channel_groups SET
name = ?, platform = ?, channel_url = ?, channel_key = ?, channel_id = ?, handle = ?,
urls = ?, note = ?, enabled = ?, updated_at = ?
WHERE id = ?
""",
(
new_name,
new_platform,
new_channel_url,
new_key,
new_cid,
new_handle,
new_urls,
(new_note or "").strip(),
new_enabled,
now,
group_id,
),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM channel_groups WHERE id = ?", (group_id,)).fetchone()) # type: ignore
finally:
conn.close()
def delete_channel_group(group_id: str) -> bool:
with _lock:
conn = _connect()
try:
cur = conn.execute("DELETE FROM channel_groups WHERE id = ?", (group_id,))
conn.commit()
return cur.rowcount > 0
finally:
conn.close()
def bulk_channel_groups(action: str, ids: list[str]) -> dict[str, Any]:
if action not in {"enable", "disable", "delete"}:
raise ValueError("不支持的批量操作")
clean = [i for i in ids if i]
if not clean:
return {"action": action, "affected": 0, "ids": []}
affected = 0
now = time.time()
with _lock:
conn = _connect()
try:
if action == "delete":
for i in clean:
cur = conn.execute("DELETE FROM channel_groups WHERE id = ?", (i,))
affected += cur.rowcount
elif action == "enable":
for i in clean:
cur = conn.execute(
"UPDATE channel_groups SET enabled = 1, updated_at = ? WHERE id = ?",
(now, i),
)
affected += cur.rowcount
elif action == "disable":
for i in clean:
cur = conn.execute(
"UPDATE channel_groups SET enabled = 0, updated_at = ? WHERE id = ?",
(now, i),
)
affected += cur.rowcount
conn.commit()
finally:
conn.close()
return {"action": action, "affected": affected, "ids": clean}
def export_channel_groups_rows() -> list[dict[str, Any]]:
data = list_channel_groups(limit=5000, offset=0)
return data.get("groups") or []
def due_channel_groups(*, platform: str = "youtube", limit: int = 20) -> list[dict[str, Any]]:
now = time.time()
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT * FROM channel_groups
WHERE enabled = 1 AND platform = ? AND next_check_at <= ?
ORDER BY next_check_at ASC
LIMIT ?
""",
(platform or "youtube", now, max(1, min(limit, 50))),
).fetchall()
return [_row_to_dict(r) for r in rows if r]
finally:
conn.close()
def touch_channel_group(
group_id: str,
*,
last_status: str,
next_check_at: float,
last_title: str = "",
last_live_video_id: str = "",
last_live_url: str = "",
error_count: int = 0,
last_error: str = "",
active_session_id: str = "",
channel_id: str = "",
handle: str = "",
) -> None:
now = time.time()
with _lock:
conn = _connect()
try:
conn.execute(
"""
UPDATE channel_groups SET
last_status = ?,
last_checked_at = ?,
next_check_at = ?,
last_title = COALESCE(NULLIF(?, ''), last_title),
last_live_video_id = ?,
last_live_url = ?,
error_count = ?,
last_error = ?,
active_session_id = ?,
channel_id = COALESCE(NULLIF(?, ''), channel_id),
handle = COALESCE(NULLIF(?, ''), handle),
updated_at = ?
WHERE id = ?
""",
(
last_status,
now,
next_check_at,
last_title,
last_live_video_id,
last_live_url,
error_count,
last_error,
active_session_id,
channel_id,
handle,
now,
group_id,
),
)
conn.commit()
finally:
conn.close()
def channel_groups_live_stats(*, platform: str = "youtube") -> dict[str, Any]:
with _lock:
conn = _connect()
try:
total = conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ?",
(platform,),
).fetchone()["c"]
enabled = conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ? AND enabled = 1",
(platform,),
).fetchone()["c"]
live = conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ? AND enabled = 1 AND last_status = 'live'",
(platform,),
).fetchone()["c"]
errors = conn.execute(
"SELECT COUNT(*) AS c FROM channel_groups WHERE platform = ? AND enabled = 1 AND last_status = 'error'",
(platform,),
).fetchone()["c"]
now = time.time()
overdue = conn.execute(
"""
SELECT COUNT(*) AS c FROM channel_groups
WHERE platform = ? AND enabled = 1 AND next_check_at > 0 AND next_check_at <= ?
""",
(platform, now - 60),
).fetchone()["c"]
return {
"total": int(total),
"enabled": int(enabled),
"live": int(live),
"errors": int(errors),
"overdue": int(overdue),
}
finally:
conn.close()
# ---------- Shorts pipeline ----------
def list_shorts_channels(*, enabled: Optional[bool] = None) -> list[dict[str, Any]]:
"""Stable order for UI cards: created_at ASC (never reshuffle on assign/live checks)."""
with _lock:
conn = _connect()
try:
if enabled is None:
rows = conn.execute(
"SELECT * FROM shorts_channels ORDER BY created_at ASC, name COLLATE NOCASE ASC, id ASC"
).fetchall()
else:
rows = conn.execute(
"""
SELECT * FROM shorts_channels
WHERE enabled = ?
ORDER BY created_at ASC, name COLLATE NOCASE ASC, id ASC
""",
(1 if enabled else 0,),
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
finally:
conn.close()
def get_shorts_channel(channel_pk: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM shorts_channels WHERE id = ?", (channel_pk,)).fetchone()
return _row_to_dict(row)
finally:
conn.close()
def create_shorts_channel(
*,
name: str,
youtube_channel_id: str = "",
client_id: str = "",
client_secret: str = "",
refresh_token: str = "",
enabled: bool = True,
daily_min: int = 9,
daily_max: int = 9,
title_template: str = "{anchor} 直播瞬间 #Shorts",
description_template: str = "{anchor}\n{url}\n#Shorts #直播",
privacy: str = "public",
note: str = "",
oauth_profile_id: str = "",
) -> dict[str, Any]:
now = time.time()
cid = str(uuid.uuid4())
daily_min = _normalize_daily_quota(daily_min, default=SHORTS_DAILY_FORCE)
daily_max = _normalize_daily_quota(daily_max, default=SHORTS_DAILY_FORCE)
if daily_max < daily_min:
daily_max = daily_min
with _lock:
conn = _connect()
try:
conn.execute(
"""
INSERT INTO shorts_channels(
id, name, youtube_channel_id, client_id, client_secret, refresh_token,
enabled, daily_min, daily_max, title_template, description_template,
privacy, last_assigned_at, note, oauth_profile_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
""",
(
cid,
(name or "").strip() or "Shorts Channel",
(youtube_channel_id or "").strip(),
(client_id or "").strip(),
(client_secret or "").strip(),
(refresh_token or "").strip(),
1 if enabled else 0,
daily_min,
daily_max,
title_template or "{anchor} #Shorts",
description_template or "",
(privacy or "public").strip() or "public",
(note or "").strip(),
(oauth_profile_id or "").strip().upper(),
now,
now,
),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_channels WHERE id = ?", (cid,)).fetchone()) # type: ignore
finally:
conn.close()
def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]:
allowed = {
"name",
"youtube_channel_id",
"client_id",
"client_secret",
"refresh_token",
"enabled",
"daily_min",
"daily_max",
"title_template",
"description_template",
"privacy",
"note",
"oauth_profile_id",
"last_assigned_at",
"oauth_ok",
"oauth_checked_at",
"oauth_error",
"yt_profile_json",
"yt_profile_at",
}
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM shorts_channels WHERE id = ?", (channel_pk,)).fetchone()
if not row:
raise ValueError("Shorts 频道不存在")
sets: list[str] = []
params: list[Any] = []
for k, v in fields.items():
if k not in allowed or v is None:
continue
if k in {"daily_min", "daily_max"}:
v = _normalize_daily_quota(v, default=SHORTS_DAILY_FORCE)
if k == "enabled":
v = 1 if v else 0
if k == "oauth_profile_id":
v = str(v or "").strip().upper()
sets.append(f"{k} = ?")
params.append(v)
if not sets:
return _row_to_dict(row)
sets.append("updated_at = ?")
params.append(time.time())
params.append(channel_pk)
conn.execute(f"UPDATE shorts_channels SET {', '.join(sets)} WHERE id = ?", params)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_channels WHERE id = ?", (channel_pk,)).fetchone()) # type: ignore
finally:
conn.close()
def _unlink_shorts_clip_paths(paths: list[str]) -> int:
"""Best-effort delete local clip files. Safe outside DB lock."""
from pathlib import Path
deleted = 0
for raw in paths:
path = str(raw or "").strip()
if not path:
continue
try:
p = Path(path)
if p.is_file():
p.unlink()
deleted += 1
except Exception:
pass
return deleted
def delete_shorts_jobs_for_channel(channel_pk: str) -> dict[str, int]:
"""Delete all Shorts jobs for a channel and unlink their clip files."""
pk = str(channel_pk or "").strip()
if not pk:
return {"jobs": 0, "clips": 0}
clip_paths: list[str] = []
with _lock:
conn = _connect()
try:
rows = conn.execute(
"SELECT id, clip_path FROM shorts_jobs WHERE channel_pk = ?",
(pk,),
).fetchall()
for row in rows:
clip = str(row["clip_path"] or "").strip()
if clip:
clip_paths.append(clip)
conn.execute("DELETE FROM shorts_jobs WHERE channel_pk = ?", (pk,))
jobs = int(conn.total_changes)
conn.commit()
finally:
conn.close()
clips = _unlink_shorts_clip_paths(clip_paths)
return {"jobs": jobs, "clips": clips}
def delete_shorts_channel(channel_pk: str) -> dict[str, int]:
"""Delete channel and cascade: jobs + local clip materials."""
pk = str(channel_pk or "").strip()
stats = delete_shorts_jobs_for_channel(pk)
with _lock:
conn = _connect()
try:
conn.execute("DELETE FROM shorts_channels WHERE id = ?", (pk,))
stats["channel"] = int(conn.total_changes)
conn.commit()
finally:
conn.close()
return stats
def purge_orphan_shorts_jobs(*, limit: int = 500) -> dict[str, int]:
"""Remove jobs whose channel_pk no longer exists; delete clip files too."""
clip_paths: list[str] = []
job_ids: list[str] = []
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT j.id, j.clip_path
FROM shorts_jobs j
LEFT JOIN shorts_channels c ON c.id = j.channel_pk
WHERE TRIM(COALESCE(j.channel_pk, '')) != ''
AND c.id IS NULL
ORDER BY j.updated_at DESC
LIMIT ?
""",
(max(1, min(int(limit), 2000)),),
).fetchall()
for row in rows:
job_ids.append(str(row["id"]))
clip = str(row["clip_path"] or "").strip()
if clip:
clip_paths.append(clip)
if job_ids:
placeholders = ",".join("?" for _ in job_ids)
conn.execute(f"DELETE FROM shorts_jobs WHERE id IN ({placeholders})", tuple(job_ids))
jobs = len(job_ids)
conn.commit()
finally:
conn.close()
clips = _unlink_shorts_clip_paths(clip_paths)
return {"jobs": jobs, "clips": clips}
def touch_shorts_channel_live(
channel_pk: str,
*,
last_status: str,
last_title: str = "",
last_live_url: str = "",
last_live_video_id: str = "",
active_session_id: str = "",
) -> None:
now = time.time()
with _lock:
conn = _connect()
try:
conn.execute(
"""
UPDATE shorts_channels SET
last_status = ?,
last_checked_at = ?,
last_title = COALESCE(NULLIF(?, ''), last_title),
last_live_url = ?,
last_live_video_id = COALESCE(NULLIF(?, ''), last_live_video_id),
active_session_id = ?,
updated_at = ?
WHERE id = ?
""",
(
last_status,
now,
last_title,
last_live_url,
last_live_video_id,
active_session_id,
now,
channel_pk,
),
)
conn.commit()
finally:
conn.close()
def sync_shorts_channel_lives_from_map(entries: dict[str, Any]) -> dict[str, int]:
"""Persist Shorts upload-channel live edges into sessions (same analytics as Douyin)."""
from .notify import fire_ntfy_youtube
started = 0
ended = 0
touched = 0
for ch in list_shorts_channels():
pk = str(ch.get("id") or "")
if not pk:
continue
ref = f"shorts:{pk}"
entry = entries.get(ref) if isinstance(entries.get(ref), dict) else {}
is_live = bool(entry.get("is_live"))
rid = f"shorts:{pk}"
prev = str(ch.get("last_status") or "")
active_sid = str(ch.get("active_session_id") or "")
title = str(entry.get("title") or ch.get("last_title") or "")
live_url = str(entry.get("live_url") or "")
vid = ""
if "watch?v=" in live_url:
vid = live_url.split("watch?v=", 1)[-1].split("&", 1)[0].strip()
name = str(ch.get("name") or ch.get("youtube_channel_id") or pk)
if is_live:
if prev != "live" or not active_sid:
session = start_session(
room_pk=pk,
room_id=rid,
source_url=live_url
or f"https://www.youtube.com/channel/{ch.get('youtube_channel_id') or ''}",
anchor_name=name,
title=title,
metadata={
"platform": "youtube",
"source": "shorts_live",
"shorts_channel_pk": pk,
"channel_id": ch.get("youtube_channel_id"),
"live_url": live_url,
"video_id": vid,
"detect_source": entry.get("source") or "",
},
)
active_sid = str(session.get("id") or "")
if not session.get("_reused"):
started += 1
msg = f"Shorts 频道开播:{name}"
if title:
msg = f"Shorts 频道开播:{name} — {title}"
add_event(
kind="live",
level="info",
message=msg,
room_id=rid,
room_pk=pk,
session_id=active_sid,
anchor_name=name,
meta={
"platform": "youtube",
"source": "shorts_live",
"shorts_channel_pk": pk,
"channel_id": ch.get("youtube_channel_id"),
"live_url": live_url,
"url": live_url,
},
)
fire_ntfy_youtube(
"live",
{
"name": name,
"channel_type": "Shorts 上传频道",
"channel_id": str(ch.get("youtube_channel_id") or ""),
"title": title,
"live_url": live_url,
"video_id": vid,
"session_id": active_sid,
"shorts_channel_pk": pk,
"channel_url": f"https://www.youtube.com/channel/{ch.get('youtube_channel_id') or ''}".rstrip("/"),
"detect_source": str(entry.get("source") or "youtubei"),
"url": live_url,
},
)
touch_shorts_channel_live(
pk,
last_status="live",
last_title=title,
last_live_url=live_url,
last_live_video_id=vid,
active_session_id=active_sid,
)
touched += 1
else:
if prev == "live" or active_sid:
closed = end_active_sessions_for_room(room_pk=pk, room_id=rid, end_reason="offline")
ended += len(closed)
for item in closed:
add_event(
kind="offline",
level="info",
message=f"Shorts 频道停播:{name}",
room_id=rid,
room_pk=pk,
session_id=str(item.get("id") or ""),
anchor_name=name,
meta={
"platform": "youtube",
"source": "shorts_live",
"shorts_channel_pk": pk,
"duration_seconds": item.get("duration_seconds"),
},
)
fire_ntfy_youtube(
"offline",
{
"name": name,
"channel_type": "Shorts 上传频道",
"channel_id": str(ch.get("youtube_channel_id") or ""),
"title": str(item.get("title") or ch.get("last_title") or ""),
"live_url": str(ch.get("last_live_url") or live_url or ""),
"video_id": str(ch.get("last_live_video_id") or vid or ""),
"session_id": str(item.get("id") or ""),
"shorts_channel_pk": pk,
"channel_url": f"https://www.youtube.com/channel/{ch.get('youtube_channel_id') or ''}".rstrip("/"),
"duration_seconds": item.get("duration_seconds"),
"detect_source": str(entry.get("source") or "youtubei"),
},
)
touch_shorts_channel_live(
pk,
last_status="offline",
last_title="",
last_live_url="",
last_live_video_id="",
active_session_id="",
)
touched += 1
return {"started": started, "ended": ended, "touched": touched}
def shorts_live_channel_stats(*, date_from: str = "", date_to: str = "") -> list[dict[str, Any]]:
"""Per Shorts upload channel: live-session counts/hours."""
with _lock:
conn = _connect()
try:
clauses = [
"(s.room_id LIKE 'shorts:%' OR IFNULL(s.metadata_json,'') LIKE '%\"source\":\"shorts_live\"%' "
"OR IFNULL(s.metadata_json,'') LIKE '%\"source\": \"shorts_live\"%')"
]
params: list[Any] = [time.time()]
if date_from:
clauses.append("s.push_date >= ?")
params.append(date_from)
if date_to:
clauses.append("s.push_date <= ?")
params.append(date_to)
where = " AND ".join(clauses)
rows = conn.execute(
f"""
SELECT
s.room_pk AS channel_pk,
s.room_id AS room_id,
COALESCE(NULLIF(MAX(s.anchor_name), ''), MAX(s.room_id)) AS anchor_name,
COUNT(*) AS sessions,
SUM(CASE WHEN s.ended_at IS NULL THEN (? - s.started_at) ELSE s.duration_seconds END) AS duration_seconds,
MAX(s.started_at) AS last_started_at,
SUM(CASE WHEN s.ended_at IS NULL THEN 1 ELSE 0 END) AS active
FROM sessions s
WHERE {where}
GROUP BY s.room_pk, s.room_id
ORDER BY sessions DESC, duration_seconds DESC
""",
params,
).fetchall()
channels = {
str(c["id"]): dict(c)
for c in conn.execute(
"SELECT id, name, youtube_channel_id, enabled, last_status, last_title, last_live_url, last_checked_at, active_session_id FROM shorts_channels"
).fetchall()
}
out: list[dict[str, Any]] = []
seen: set[str] = set()
for r in rows:
pk = str(r["channel_pk"] or "")
ch = channels.get(pk) or {}
seen.add(pk)
out.append(
{
"id": pk or None,
"name": str(ch.get("name") or r["anchor_name"] or pk),
"youtube_channel_id": str(ch.get("youtube_channel_id") or ""),
"enabled": bool(ch.get("enabled")) if ch else None,
"last_status": str(
ch.get("last_status") or ("live" if int(r["active"] or 0) else "offline")
),
"last_title": str(ch.get("last_title") or ""),
"last_live_url": str(ch.get("last_live_url") or ""),
"last_checked_at": ch.get("last_checked_at"),
"room_id": str(r["room_id"] or ""),
"sessions": int(r["sessions"] or 0),
"hours_total": round(float(r["duration_seconds"] or 0) / 3600.0, 2),
"last_started_at": r["last_started_at"],
"active": int(r["active"] or 0),
}
)
for pk, ch in channels.items():
if pk in seen:
continue
out.append(
{
"id": pk,
"name": str(ch["name"] or ""),
"youtube_channel_id": str(ch["youtube_channel_id"] or ""),
"enabled": bool(ch["enabled"]),
"last_status": str(ch["last_status"] or "offline"),
"last_title": str(ch["last_title"] or ""),
"last_live_url": str(ch["last_live_url"] or ""),
"last_checked_at": ch["last_checked_at"],
"room_id": f"shorts:{pk}",
"sessions": 0,
"hours_total": 0.0,
"last_started_at": None,
"active": 1 if str(ch["last_status"] or "") == "live" else 0,
}
)
out.sort(
key=lambda x: (
-int(x.get("active") or 0),
-int(x.get("sessions") or 0),
-float(x.get("hours_total") or 0),
)
)
return out
finally:
conn.close()
# Jobs that consume a channel's Beijing-day quota (aligned with schedule_board.used).
_SHORTS_QUOTA_STATUSES = (
"pending",
"recording",
"recorded",
"scheduled",
"uploading",
"uploaded",
"done",
)
def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int:
placeholders = ",".join("?" for _ in _SHORTS_QUOTA_STATUSES)
with _lock:
conn = _connect()
try:
row = conn.execute(
f"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE channel_pk = ? AND push_date = ?
AND status IN ({placeholders})
""",
(channel_pk, push_date, *_SHORTS_QUOTA_STATUSES),
).fetchone()
return int(row["c"] if row else 0)
finally:
conn.close()
def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]:
"""Per enabled channel: used/gap toward daily_max for the Beijing day."""
day = push_date or push_date_from_ts(time.time())
rows: list[dict[str, Any]] = []
for ch in list_shorts_channels(enabled=True):
cid = str(ch["id"])
daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE)
daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE)
if daily_max < daily_min:
daily_max = daily_min
used = shorts_channel_upload_count(cid, day)
rows.append(
{
"id": cid,
"name": ch.get("name"),
"daily_min": daily_min,
"daily_max": daily_max,
"used": used,
"gap": max(0, daily_max - used),
"min_met": used >= daily_min,
"max_met": used >= daily_max,
}
)
rows.sort(key=lambda r: (0 if not r["min_met"] else 1, r["used"], r["id"]))
return rows
def shorts_total_quota_gap(push_date: str = "") -> int:
return sum(r["gap"] for r in shorts_channels_quota_summary(push_date))
def list_douyin_room_status_entries(
*,
room_ids: list[str] | None = None,
limit: int = 3000,
) -> list[dict[str, Any]]:
"""Monitor-backed Douyin room status rows for live-map (no network probe)."""
with _lock:
conn = _connect()
try:
base = """
SELECT room_id, url, last_status, last_anchor, last_checked_at,
active_session_id, enabled, note
FROM rooms
WHERE room_id != ''
AND room_id NOT LIKE 'yt:%'
AND room_id NOT LIKE 'shorts:%'
"""
if room_ids:
ids = [str(x).strip() for x in room_ids if str(x).strip()]
if not ids:
return []
placeholders = ",".join("?" * len(ids))
rows = conn.execute(
base + f" AND room_id IN ({placeholders})",
ids,
).fetchall()
else:
rows = conn.execute(
base + " ORDER BY updated_at DESC LIMIT ?",
(max(1, min(int(limit), 5000)),),
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()
def list_live_douyin_rooms_for_shorts(*, limit: int = 300) -> list[dict[str, Any]]:
"""Currently-live Douyin rooms from monitor state (no extra network)."""
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT * FROM rooms
WHERE enabled = 1
AND last_status = 'live'
AND room_id NOT LIKE 'yt:%'
ORDER BY last_checked_at DESC
LIMIT ?
""",
(max(1, min(int(limit), 1000)),),
).fetchall()
return [_row_to_dict(r) for r in rows]
finally:
conn.close()
def dedupe_shorts_jobs_room_day() -> int:
"""Keep one active job per room_id+push_date; mark extras skipped (prefer uploaded)."""
now = time.time()
skipped = 0
with _lock:
conn = _connect()
try:
groups = conn.execute(
"""
SELECT room_id, push_date, COUNT(*) AS c
FROM shorts_jobs
WHERE room_id != ''
AND status NOT IN ('failed', 'skipped')
GROUP BY room_id, push_date
HAVING c > 1
"""
).fetchall()
for g in groups:
rows = conn.execute(
"""
SELECT id, status, youtube_video_id, created_at, finished_at
FROM shorts_jobs
WHERE room_id = ? AND push_date = ?
AND status NOT IN ('failed', 'skipped')
ORDER BY
CASE WHEN youtube_video_id != '' THEN 0 ELSE 1 END,
CASE WHEN status = 'uploaded' THEN 0 ELSE 1 END,
created_at ASC
""",
(g["room_id"], g["push_date"]),
).fetchall()
if len(rows) <= 1:
continue
keep_id = rows[0]["id"]
for row in rows[1:]:
# Never skip a job that already has a YouTube id unless keeper also has one
if str(row["youtube_video_id"] or "").strip() and not str(rows[0]["youtube_video_id"] or "").strip():
continue
conn.execute(
"""
UPDATE shorts_jobs
SET status = 'skipped',
error = '同房间同日重复任务已跳过',
updated_at = ?,
finished_at = CASE WHEN finished_at = 0 THEN ? ELSE finished_at END
WHERE id = ? AND id != ? AND status NOT IN ('failed', 'skipped', 'uploaded')
AND youtube_video_id = ''
""",
(now, now, row["id"], keep_id),
)
skipped += int(conn.total_changes)
conn.commit()
return skipped
finally:
conn.close()
def room_ids_with_shorts_job_today(push_date: str) -> set[str]:
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT DISTINCT room_id FROM shorts_jobs
WHERE push_date = ?
AND room_id != ''
AND status NOT IN ('failed', 'skipped')
""",
(push_date,),
).fetchall()
return {str(r["room_id"]) for r in rows}
finally:
conn.close()
def pick_shorts_channel(
push_date: str,
cfg: dict[str, Any] | None = None,
*,
require_upload_quota: bool = True,
) -> dict[str, Any] | None:
"""Pick enabled channel with most room left today (Beijing day); under daily_min first."""
from .shorts_yt_quota import profile_id_for_channel, project_uploads_available
channels = list_shorts_channels(enabled=True)
if not channels:
return None
scored: list[tuple[int, int, float, dict[str, Any]]] = []
for ch in channels:
pid = profile_id_for_channel(ch)
if require_upload_quota and not project_uploads_available(cfg, profile_id=pid):
continue
used = shorts_channel_upload_count(str(ch["id"]), push_date)
daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE)
if used >= daily_max:
continue
daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE)
under = 0 if used < daily_min else 1
scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch))
if not scored:
return None
scored.sort(key=lambda x: (x[0], x[1], x[2]))
return scored[0][3]
def list_shorts_jobs(
*,
status: str = "",
push_date: str = "",
channel_pk: str = "",
session_id: str = "",
room_id: str = "",
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
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())
if session_id.strip():
clauses.append("session_id = ?")
params.append(session_id.strip())
if room_id.strip():
clauses.append("room_id = ?")
params.append(room_id.strip())
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
total = conn.execute(f"SELECT COUNT(*) AS c FROM shorts_jobs {where}", params).fetchone()["c"]
rows = conn.execute(
f"SELECT * FROM shorts_jobs {where} ORDER BY created_at DESC LIMIT ? OFFSET ?",
[*params, max(1, min(limit, 500)), max(0, offset)],
).fetchall()
return {"jobs": [_row_to_dict(r) for r in rows], "total": int(total)}
finally:
conn.close()
def get_shorts_job(job_id: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def create_shorts_job(
*,
session_id: str,
room_pk: str = "",
room_id: str = "",
source_url: str = "",
anchor_name: str = "",
stream_url: str = "",
channel_pk: str = "",
push_date: str = "",
force: bool = False,
) -> dict[str, Any] | None:
"""Create a Shorts job. Same room_id + Beijing day is unique unless force=True.
Returns None when a non-failed/skipped job already exists for that room/day.
"""
now = time.time()
jid = str(uuid.uuid4())
day = push_date or push_date_from_ts(now)
rid = str(room_id or "").strip()
with _lock:
conn = _connect()
try:
if rid and not force:
existing = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE room_id = ? AND push_date = ?
AND status NOT IN ('failed', 'skipped')
ORDER BY created_at ASC
LIMIT 1
""",
(rid, day),
).fetchone()
if existing:
return None
conn.execute(
"""
INSERT INTO shorts_jobs(
id, session_id, room_pk, room_id, source_url, anchor_name, stream_url,
channel_pk, status, clip_path, clip_seconds, youtube_video_id, youtube_url,
error, push_date, attempts, created_at, updated_at, started_at, finished_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', ?, 0, ?, ?, 0, 0)
""",
(
jid,
session_id,
room_pk,
rid,
source_url,
anchor_name,
stream_url,
channel_pk,
day,
now,
now,
),
)
if channel_pk:
conn.execute(
"UPDATE shorts_channels SET last_assigned_at = ?, updated_at = ? WHERE id = ?",
(now, now, channel_pk),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (jid,)).fetchone()) # type: ignore
finally:
conn.close()
def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
allowed = {
"status",
"clip_path",
"clip_seconds",
"youtube_video_id",
"youtube_url",
"error",
"channel_pk",
"stream_url",
"attempts",
"started_at",
"finished_at",
"upload_at",
}
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone()
if not row:
return None
sets: list[str] = []
params: list[Any] = []
for k, v in fields.items():
if k not in allowed or v is None:
continue
sets.append(f"{k} = ?")
params.append(v)
if not sets:
return _row_to_dict(row)
sets.append("updated_at = ?")
params.append(time.time())
params.append(job_id)
conn.execute(f"UPDATE shorts_jobs SET {', '.join(sets)} WHERE id = ?", params)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict[str, Any] | None:
"""Claim one due scheduled/recorded clip for upload.
skip_profile_ids: OAuth Client profiles whose YouTube project quota is exhausted
(e.g. {"A"}) — jobs for those channels are left alone so Client B can still upload.
"""
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:
rows = conn.execute(
"""
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
FROM shorts_jobs j
INNER JOIN shorts_channels c ON c.id = j.channel_pk
WHERE j.status = 'scheduled'
AND j.clip_path != ''
AND j.youtube_video_id = ''
AND j.upload_at > 0
AND j.upload_at <= ?
ORDER BY j.upload_at ASC, j.created_at ASC
LIMIT 30
""",
(now,),
).fetchall()
if not rows:
rows = conn.execute(
"""
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
FROM shorts_jobs j
INNER JOIN shorts_channels c ON c.id = j.channel_pk
WHERE j.status = 'recorded'
AND j.clip_path != ''
AND j.youtube_video_id = ''
AND j.upload_at > 0
AND j.upload_at <= ?
ORDER BY j.upload_at ASC
LIMIT 30
""",
(now,),
).fetchall()
picked = None
for row in rows:
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
if pid in skip:
continue
picked = row
break
if not picked:
return None
jid = picked["id"]
status = picked["status"]
conn.execute(
"""
UPDATE shorts_jobs
SET status = 'uploading', attempts = attempts + 1,
started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END,
updated_at = ?, error = ''
WHERE id = ? AND status = ?
""",
(now, now, jid, status),
)
if conn.total_changes == 0:
conn.rollback()
return None
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (jid,)).fetchone())
finally:
conn.close()
def claim_pending_shorts_record() -> dict[str, Any] | None:
"""Claim one pending job for recording."""
now = time.time()
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status = 'pending'
ORDER BY created_at ASC
LIMIT 1
"""
).fetchone()
if not row:
return None
jid = row["id"]
conn.execute(
"""
UPDATE shorts_jobs
SET status = 'recording', attempts = attempts + 1,
started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END,
updated_at = ?, error = ''
WHERE id = ? AND status = 'pending'
""",
(now, now, jid),
)
if conn.total_changes == 0:
conn.rollback()
return None
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (jid,)).fetchone())
finally:
conn.close()
def claim_shorts_job_record(job_id: str) -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET status = 'recording', attempts = attempts + 1,
started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END,
updated_at = ?, error = ''
WHERE id = ? AND status = 'pending'
""",
(now, now, job_id),
)
conn.commit()
if cur.rowcount == 0:
return None
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def claim_next_shorts_job() -> dict[str, Any] | None:
"""Prefer due upload, then pending record."""
job = claim_due_shorts_upload()
if job:
return job
return claim_pending_shorts_record()
def reclaim_stale_shorts_uploads(*, max_age_sec: float = 900.0, retry_at: float = 0) -> int:
"""Reset truly stuck uploading jobs back to scheduled.
Uses updated_at (heartbeat during upload). Default 15min — never reclaim a live upload.
"""
cutoff = time.time() - max(300.0, float(max_age_sec))
now = time.time()
upload_at = float(retry_at or now)
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET status = 'scheduled',
upload_at = ?,
error = '上传超时已重排(未完成)',
updated_at = ?,
started_at = 0
WHERE status = 'uploading'
AND clip_path != ''
AND youtube_video_id = ''
AND updated_at < ?
""",
(upload_at, now, cutoff),
)
conn.commit()
return int(cur.rowcount)
finally:
conn.close()
def reconcile_false_failed_shorts(*, limit: int = 200) -> int:
"""Restore jobs wrongly marked failed after a successful YouTube upload."""
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT id FROM shorts_jobs
WHERE status = 'failed'
AND youtube_video_id != ''
ORDER BY updated_at DESC
LIMIT ?
""",
(max(1, min(int(limit), 500)),),
).fetchall()
if not rows:
return 0
now = time.time()
fixed = 0
for row in rows:
conn.execute(
"""
UPDATE shorts_jobs
SET status = 'uploaded', error = '', clip_path = '',
finished_at = CASE WHEN finished_at = 0 THEN ? ELSE finished_at END,
updated_at = ?
WHERE id = ? AND status = 'failed' AND youtube_video_id != ''
""",
(now, now, row["id"]),
)
if conn.total_changes:
fixed += 1
conn.commit()
return fixed
finally:
conn.close()
def reconcile_missing_shorts_clips(*, limit: int = 200) -> int:
"""Reset jobs whose clip_path points to a deleted file → pending re-record."""
from pathlib import Path
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT id, clip_path FROM shorts_jobs
WHERE clip_path != ''
AND status IN ('recorded', 'scheduled', 'uploading')
ORDER BY updated_at DESC
LIMIT ?
""",
(max(1, min(int(limit), 500)),),
).fetchall()
fixed = 0
now = time.time()
for row in rows:
path = str(row["clip_path"] or "").strip()
if not path or Path(path).is_file():
continue
conn.execute(
"""
UPDATE shorts_jobs
SET status = 'pending', clip_path = '', clip_seconds = 0,
upload_at = 0, error = '成片已丢失,已重新排队录制',
finished_at = 0, updated_at = ?
WHERE id = ? AND status IN ('recorded', 'scheduled', 'uploading')
""",
(now, row["id"]),
)
if conn.total_changes:
fixed += 1
conn.commit()
return fixed
finally:
conn.close()
def claim_shorts_job_manual_upload(job_id: str) -> dict[str, Any] | None:
"""Flip scheduled/recorded clip to uploading for manual upload-now."""
now = time.time()
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone()
if not row:
return None
st = str(row["status"] or "")
if st not in {"scheduled", "recorded"}:
return None
if not str(row["clip_path"] or "").strip():
return None
conn.execute(
"""
UPDATE shorts_jobs
SET status = 'uploading', upload_at = ?, attempts = attempts + 1,
started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END,
updated_at = ?, error = ''
WHERE id = ? AND status = ?
""",
(now, now, now, job_id, st),
)
if conn.total_changes == 0:
conn.rollback()
return None
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def has_shorts_job_for_room_day(room_id: str, push_date: str, channel_id: str = "") -> bool:
"""Return True if a non-failed job already exists for room_id on push_date.
Dedup scope defaults to global room_id + push_date (Beijing day).
Optional channel_id filters by channel_pk (column name is channel_pk).
"""
if not room_id:
return False
with _lock:
conn = _connect()
try:
if channel_id:
row = conn.execute(
"""
SELECT 1 FROM shorts_jobs
WHERE room_id = ? AND push_date = ? AND channel_pk = ?
AND status NOT IN ('failed', 'skipped')
LIMIT 1
""",
(room_id, push_date, channel_id),
).fetchone()
else:
row = conn.execute(
"""
SELECT 1 FROM shorts_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 touch_shorts_upload_lease(job_id: str) -> bool:
"""Heartbeat while uploading. False if job already finished / not uploading."""
now = time.time()
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET updated_at = ?
WHERE id = ?
AND status = 'uploading'
AND youtube_video_id = ''
""",
(now, job_id),
)
conn.commit()
return int(cur.rowcount) > 0
finally:
conn.close()
def finalize_shorts_upload(
job_id: str,
*,
youtube_video_id: str,
youtube_url: str = "",
) -> bool:
"""Atomically mark uploaded. False if another worker already finalized."""
now = time.time()
vid = str(youtube_video_id or "").strip()
if not vid:
return False
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET status = 'uploaded',
youtube_video_id = ?,
youtube_url = ?,
error = '',
finished_at = ?,
updated_at = ?,
clip_path = ''
WHERE id = ?
AND youtube_video_id = ''
AND status IN ('uploading', 'scheduled', 'recorded')
""",
(vid, str(youtube_url or ""), now, now, job_id),
)
conn.commit()
return int(cur.rowcount) > 0
finally:
conn.close()
def shorts_stats(push_date: str = "") -> dict[str, Any]:
day = push_date or push_date_from_ts(time.time())
with _lock:
conn = _connect()
try:
by_status = {
r["status"]: int(r["c"])
for r in conn.execute(
"SELECT status, COUNT(*) AS c FROM shorts_jobs WHERE push_date = ? GROUP BY status",
(day,),
).fetchall()
}
channels = conn.execute("SELECT COUNT(*) AS c FROM shorts_channels WHERE enabled = 1").fetchone()["c"]
return {"push_date": day, "by_status": by_status, "enabled_channels": int(channels)}
finally:
conn.close()
def _classify_shorts_error(error: str) -> str:
err = (error or "").lower()
if not err.strip():
return "unknown"
if "oauth" in err or "refresh" in err or "授权" in err or "token" in err:
return "oauth"
if "成片" in err or "no such file" in err or "丢失" in err or "clip" in err:
return "missing_clip"
if "quota" in err or "rate" in err or "429" in err or "daily limit" in err:
return "quota"
if "video upload" in err or "video uploads" in err or "配额已用尽" in (error or ""):
return "quota"
if "ffmpeg" in err or "录制" in err or "stream" in err or "直播流" in err:
return "record"
if "上传" in err or "upload" in err or "youtube" in err or "googleapis" in err:
return "upload"
return "other"
def shorts_failed_groups(*, push_date: str = "", limit: int = 40) -> dict[str, Any]:
"""Group recent failed jobs by error category for ops panel."""
day = (push_date or "").strip()
with _lock:
conn = _connect()
try:
if day:
rows = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status = 'failed' AND push_date = ?
ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC
LIMIT ?
""",
(day, max(1, min(int(limit), 200))),
).fetchall()
else:
rows = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status = 'failed'
ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC
LIMIT ?
""",
(max(1, min(int(limit), 200)),),
).fetchall()
jobs = [_row_to_dict(r) for r in rows]
finally:
conn.close()
buckets: dict[str, dict[str, Any]] = {}
labels = {
"oauth": "OAuth / 授权",
"missing_clip": "成片丢失",
"quota": "配额 / 限流",
"record": "录制失败",
"upload": "上传失败",
"other": "其他",
"unknown": "未知",
}
for j in jobs:
cat = _classify_shorts_error(str(j.get("error") or ""))
bucket = buckets.setdefault(
cat,
{"category": cat, "label": labels.get(cat, cat), "count": 0, "jobs": []},
)
bucket["count"] += 1
if len(bucket["jobs"]) < 8:
bucket["jobs"].append(
{
"id": j.get("id"),
"anchor_name": j.get("anchor_name"),
"room_id": j.get("room_id"),
"channel_pk": j.get("channel_pk"),
"error": j.get("error"),
"push_date": j.get("push_date"),
"finished_at": j.get("finished_at"),
"updated_at": j.get("updated_at"),
}
)
groups = sorted(buckets.values(), key=lambda x: (-int(x["count"]), str(x["category"])))
return {"total": len(jobs), "groups": groups}
def shorts_stats_history(*, days: int = 7) -> dict[str, Any]:
"""Beijing-day upload/fail/pending counts for the last N days."""
n = max(1, min(int(days or 7), 30))
today = push_date_from_ts(time.time())
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
bj = ZoneInfo("Asia/Shanghai")
base = datetime.strptime(today, "%Y-%m-%d").replace(tzinfo=bj)
day_list = [(base - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(n - 1, -1, -1)]
with _lock:
conn = _connect()
try:
placeholders = ",".join("?" * len(day_list))
rows = conn.execute(
f"""
SELECT push_date, status, COUNT(*) AS c
FROM shorts_jobs
WHERE push_date IN ({placeholders})
GROUP BY push_date, status
""",
day_list,
).fetchall()
finally:
conn.close()
by_day: dict[str, dict[str, int]] = {d: {} for d in day_list}
for r in rows:
d = str(r["push_date"] or "")
if d in by_day:
by_day[d][str(r["status"] or "")] = int(r["c"])
series = []
for d in day_list:
st = by_day[d]
uploaded = int(st.get("uploaded") or 0) + int(st.get("done") or 0)
failed = int(st.get("failed") or 0)
queued = (
int(st.get("pending") or 0)
+ int(st.get("recording") or 0)
+ int(st.get("recorded") or 0)
+ int(st.get("scheduled") or 0)
+ int(st.get("uploading") or 0)
)
total = sum(st.values())
series.append(
{
"push_date": d,
"uploaded": uploaded,
"failed": failed,
"queued": queued,
"total": total,
"by_status": st,
"success_rate": round(uploaded / total, 3) if total else None,
}
)
return {"days": n, "series": series}
def shorts_channel_performance(*, days: int = 7) -> dict[str, Any]:
"""Per-channel uploaded/failed/success rate over recent Beijing days."""
n = max(1, min(int(days or 7), 30))
today = push_date_from_ts(time.time())
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
bj = ZoneInfo("Asia/Shanghai")
base = datetime.strptime(today, "%Y-%m-%d").replace(tzinfo=bj)
day_list = [(base - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(n - 1, -1, -1)]
channels = list_shorts_channels(enabled=None)
ch_map = {str(c["id"]): c for c in channels}
with _lock:
conn = _connect()
try:
placeholders = ",".join("?" * len(day_list))
rows = conn.execute(
f"""
SELECT channel_pk, status, COUNT(*) AS c
FROM shorts_jobs
WHERE push_date IN ({placeholders})
GROUP BY channel_pk, status
""",
day_list,
).fetchall()
finally:
conn.close()
by_ch: dict[str, dict[str, int]] = {}
for r in rows:
cid = str(r["channel_pk"] or "")
bucket = by_ch.setdefault(cid, {})
bucket[str(r["status"] or "")] = int(r["c"])
out = []
for cid, ch in ch_map.items():
st = by_ch.get(cid, {})
uploaded = int(st.get("uploaded") or 0) + int(st.get("done") or 0)
failed = int(st.get("failed") or 0)
decided = uploaded + failed
out.append(
{
"id": cid,
"name": ch.get("name") or "",
"enabled": bool(ch.get("enabled")),
"authorized": bool(str(ch.get("refresh_token") or "").strip()),
"uploaded": uploaded,
"failed": failed,
"pending": int(st.get("pending") or 0),
"scheduled": int(st.get("scheduled") or 0),
"total": sum(st.values()),
"success_rate": round(uploaded / decided, 3) if decided else None,
}
)
out.sort(key=lambda x: (-(x["uploaded"] or 0), -(x["total"] or 0), str(x["name"] or "")))
return {"days": n, "push_dates": day_list, "channels": out}
def list_failed_shorts_job_ids(*, push_date: str = "", limit: int = 50) -> list[str]:
day = (push_date or "").strip()
lim = max(1, min(int(limit), 100))
with _lock:
conn = _connect()
try:
if day:
rows = conn.execute(
"""
SELECT id FROM shorts_jobs
WHERE status = 'failed' AND push_date = ?
ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC
LIMIT ?
""",
(day, lim),
).fetchall()
else:
rows = conn.execute(
"""
SELECT id FROM shorts_jobs
WHERE status = 'failed'
ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC
LIMIT ?
""",
(lim,),
).fetchall()
return [str(r["id"]) for r in rows]
finally:
conn.close()
def list_auto_retry_failed_jobs(*, max_attempts: int = 3, limit: int = 8) -> list[dict[str, Any]]:
"""Failed jobs eligible for automatic re-queue (skip permanent OAuth errors)."""
lim = max(1, min(int(limit), 30))
max_att = max(1, min(int(max_attempts), 10))
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status = 'failed'
AND attempts < ?
AND COALESCE(finished_at, 0) > 0
AND finished_at < ?
ORDER BY finished_at ASC
LIMIT ?
""",
(max_att, time.time() - 60, lim),
).fetchall()
out: list[dict[str, Any]] = []
for r in rows:
job = _row_to_dict(r)
err = str(job.get("error") or "")
low = err.lower()
if "invalid_grant" in low:
continue
if "oauth" in low and ("刷新" in err or "授权" in err):
continue
if "频道不存在" in err:
continue
if _classify_shorts_error(err) == "quota":
continue
out.append(job)
return out
finally:
conn.close()
def shorts_upload_heatmap(*, days: int = 1) -> dict[str, Any]:
"""Beijing-hour distribution of uploaded / scheduled / failed jobs."""
from .timeutil import beijing_hour
n = max(1, min(int(days or 1), 14))
today = push_date_from_ts(time.time())
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
bj = ZoneInfo("Asia/Shanghai")
base = datetime.strptime(today, "%Y-%m-%d").replace(tzinfo=bj)
day_list = [(base - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(n - 1, -1, -1)]
with _lock:
conn = _connect()
try:
placeholders = ",".join("?" * len(day_list))
rows = conn.execute(
f"""
SELECT status, finished_at, upload_at, created_at, updated_at
FROM shorts_jobs
WHERE push_date IN ({placeholders})
AND status IN ('uploaded', 'done', 'scheduled', 'uploading', 'failed')
""",
day_list,
).fetchall()
finally:
conn.close()
uploaded_hours = [0] * 24
scheduled_hours = [0] * 24
failed_hours = [0] * 24
for r in rows:
st = str(r["status"] or "")
if st in {"uploaded", "done"}:
ts = float(r["finished_at"] or r["upload_at"] or r["created_at"] or 0)
if ts > 0:
uploaded_hours[beijing_hour(ts)] += 1
elif st in {"scheduled", "uploading"}:
ts = float(r["upload_at"] or r["created_at"] or 0)
if ts > 0:
scheduled_hours[beijing_hour(ts)] += 1
elif st == "failed":
ts = float(r["finished_at"] or r["updated_at"] or r["created_at"] or 0)
if ts > 0:
failed_hours[beijing_hour(ts)] += 1
return {
"days": n,
"push_dates": day_list,
"hours": list(range(24)),
"uploaded": uploaded_hours,
"scheduled": scheduled_hours,
"failed": failed_hours,
"peak_hour": max(range(24), key=lambda i: uploaded_hours[i]) if sum(uploaded_hours) else None,
}
def table_counts() -> dict[str, int]:
"""Row counts for PB drift diagnostics."""
with _lock:
conn = _connect()
try:
return {
"rooms": int(conn.execute("SELECT COUNT(*) FROM rooms").fetchone()[0]),
"sessions": int(conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]),
"groups": int(conn.execute("SELECT COUNT(*) FROM channel_groups").fetchone()[0]),
"events": int(conn.execute("SELECT COUNT(*) FROM events").fetchone()[0]),
"blacklist": int(conn.execute("SELECT COUNT(*) FROM blacklist").fetchone()[0]),
}
finally:
conn.close()