douyinWEB/backend/app/db.py
eric 47d17aee3c Document YouTube groups and Shorts side-path; sync dual-platform pipeline.
Add isolated Shorts OAuth/clip/upload worker (default off), youtube-svc + group poller, Beijing time UX, and SHORTS.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 00:04:06 -05:00

2559 lines
93 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()
def _connect() -> sqlite3.Connection:
conn = sqlite3.connect(str(settings.sqlite_path), check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
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 ''")
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)"
)
conn.commit()
_seed_defaults(conn)
finally:
conn.close()
# repair leftover duplicate actives from concurrent go-live races
try:
dedupe_active_sessions()
except Exception:
pass
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_on_risk": True,
"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_oauth_client_id": "",
"shorts_oauth_client_secret": "",
"shorts_oauth_redirect_uri": "https://dylive.nomadro.com/api/shorts/oauth/callback",
"shorts_gcp_project_id": "live-473104",
}
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:
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
finally:
conn.close()
def update_settings_map(patch: dict[str, Any]) -> 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()
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 {meta_col} LIKE '%\"platform\": \"youtube\"%' "
f"OR {meta_col} LIKE '%\"platform\":\"youtube\"%')",
[],
)
if p in ("douyin", "dy"):
return (
f"({room_col} NOT LIKE 'yt:%' 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,
) -> 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 "")
conn.execute(
"""
UPDATE rooms SET url = ?, room_id = ?, note = ?, enabled = ?, tags = ?, updated_at = ?
WHERE id = ?
""",
(new_url, new_rid, new_note, new_enabled, new_tags, 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 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 list_blacklist() -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
rows = conn.execute("SELECT * FROM blacklist ORDER BY created_at DESC").fetchall()
return [dict(r) for r in rows]
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() -> list[dict[str, Any]]:
dedupe_active_sessions()
with _lock:
conn = _connect()
try:
rows = conn.execute(
"SELECT * FROM sessions WHERE status = 'active' AND ended_at IS NULL ORDER BY started_at DESC"
).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 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"]),
)
conn.execute(
"UPDATE rooms SET active_session_id = ?, last_status = 'live', updated_at = ? WHERE id = ?",
(existing["id"], now, room_pk),
)
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,
),
)
conn.execute(
"UPDATE rooms SET active_session_id = ?, last_status = 'live', updated_at = ? WHERE id = ?",
(sid, now, room_pk),
)
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),
)
conn.execute(
"UPDATE rooms SET active_session_id = '', updated_at = ? WHERE active_session_id = ?",
(now, session_id),
)
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.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 = None
if row["room_pk"]:
room = conn.execute("SELECT * FROM rooms WHERE id = ?", (row["room_pk"],)).fetchone()
if not room and row["room_id"]:
room = conn.execute(
"SELECT * FROM rooms WHERE room_id = ?", (row["room_id"],)
).fetchone()
room_status = (room["last_status"] if room else "") or ""
stale = False
reason = "keep"
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 room and (room["active_session_id"] or "") == row["id"]:
conn.execute(
"UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?",
(now, room["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
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"]),
}
)
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()
# ---------- 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]]:
with _lock:
conn = _connect()
try:
if enabled is None:
rows = conn.execute("SELECT * FROM shorts_channels ORDER BY updated_at DESC").fetchall()
else:
rows = conn.execute(
"SELECT * FROM shorts_channels WHERE enabled = ? ORDER BY updated_at DESC",
(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 = 5,
daily_max: int = 9,
title_template: str = "{anchor} 直播瞬间 #Shorts",
description_template: str = "{anchor}\n{url}\n#Shorts #直播",
privacy: str = "public",
note: str = "",
) -> dict[str, Any]:
now = time.time()
cid = str(uuid.uuid4())
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, 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,
max(0, int(daily_min)),
max(1, int(daily_max)),
title_template or "{anchor} #Shorts",
description_template or "",
(privacy or "public").strip() or "public",
(note or "").strip(),
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",
"last_assigned_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 == "enabled":
v = 1 if v else 0
sets.append(f"{k} = ?")
params.append(v)
if not sets:
return _row_to_dict(row) # type: ignore
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 delete_shorts_channel(channel_pk: str) -> None:
with _lock:
conn = _connect()
try:
conn.execute("DELETE FROM shorts_channels WHERE id = ?", (channel_pk,))
conn.commit()
finally:
conn.close()
def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int:
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE channel_pk = ? AND push_date = ?
AND status IN ('pending','recording','recorded','uploading','uploaded','done')
""",
(channel_pk, push_date),
).fetchone()
return int(row["c"] if row else 0)
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 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) -> dict[str, Any] | None:
channels = list_shorts_channels(enabled=True)
if not channels:
return None
scored: list[tuple[int, float, dict[str, Any]]] = []
for ch in channels:
used = shorts_channel_upload_count(str(ch["id"]), push_date)
daily_max = max(1, int(ch.get("daily_max") or 9))
if used >= daily_max:
continue
daily_min = max(0, int(ch.get("daily_min") or 5))
# prefer under-min, then least used, then least recently assigned
under = 0 if used < daily_min else 1
scored.append((under, used + float(ch.get("last_assigned_at") or 0) / 1e12, ch))
if not scored:
return None
scored.sort(key=lambda x: (x[0], x[1]))
return scored[0][2]
def list_shorts_jobs(
*,
status: str = "",
push_date: str = "",
channel_pk: 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())
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 = "",
) -> dict[str, Any]:
now = time.time()
jid = str(uuid.uuid4())
day = push_date or push_date_from_ts(now)
with _lock:
conn = _connect()
try:
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,
room_id,
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",
}
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_next_shorts_job() -> dict[str, Any] | None:
"""Atomically claim one pending/recorded job for processing."""
now = time.time()
with _lock:
conn = _connect()
try:
# prefer pending (need record), then recorded (need upload)
row = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status IN ('pending', 'recorded')
ORDER BY CASE status WHEN 'pending' THEN 0 ELSE 1 END, created_at ASC
LIMIT 1
"""
).fetchone()
if not row:
return None
jid = row["id"]
status = row["status"]
next_status = "recording" if status == "pending" else "uploading"
conn.execute(
"""
UPDATE shorts_jobs
SET status = ?, attempts = attempts + 1, started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END,
updated_at = ?, error = ''
WHERE id = ? AND status = ?
""",
(next_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 has_shorts_job_for_room_day(room_id: str, push_date: str) -> bool:
if not room_id:
return False
with _lock:
conn = _connect()
try:
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 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()