douyinWEB/backend/app/db.py
eric 03888989d2 Proxy SeaweedFS covers through API so private buckets display in UI.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 09:42:56 -05:00

1174 lines
41 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);
"""
)
# 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 ''")
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,
"priority_interval_sec": 25.0,
}
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)),
)
conn.commit()
finally:
conn.close()
return get_settings_map()
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 "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"):
# Always expose via API proxy so SeaweedFS private buckets still display in UI
data["cover_url"] = f"/api/sessions/{data['id']}/cover"
else:
if "cover_path" in data:
data["cover_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()
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", "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 == "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
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 = "",
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])
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 = "",
limit: int = 5000,
) -> list[dict[str, Any]]:
data = list_sessions(q=q, date_from=date_from, date_to=date_to, status=status, 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 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(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
limit: int = 50,
offset: int = 0,
) -> dict[str, Any]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
if status == "active":
clauses.append("ended_at IS NULL")
elif status == "ended":
clauses.append("ended_at IS NOT NULL")
if date_from:
clauses.append("push_date >= ?")
params.append(date_from)
if date_to:
clauses.append("push_date <= ?")
params.append(date_to)
if q.strip():
like = f"%{q.strip()}%"
clauses.append("(anchor_name LIKE ? OR source_url LIKE ? OR room_id LIKE ? OR title LIKE ?)")
params.extend([like, like, like, like])
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
total = conn.execute(f"SELECT COUNT(*) AS c FROM sessions {where}", params).fetchone()["c"]
rows = conn.execute(
f"SELECT * FROM sessions {where} ORDER BY 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 all_sessions_for_stats(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
) -> list[dict[str, Any]]:
with _lock:
conn = _connect()
try:
clauses: list[str] = []
params: list[Any] = []
if status == "active":
clauses.append("ended_at IS NULL")
elif status == "ended":
clauses.append("ended_at IS NOT NULL")
if date_from:
clauses.append("push_date >= ?")
params.append(date_from)
if date_to:
clauses.append("push_date <= ?")
params.append(date_to)
if q.strip():
like = f"%{q.strip()}%"
clauses.append("(anchor_name LIKE ? OR source_url LIKE ? OR room_id LIKE ? OR title LIKE ?)")
params.extend([like, like, like, like])
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
rows = conn.execute(
f"SELECT * FROM sessions {where} ORDER BY started_at ASC",
params,
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
finally:
conn.close()