331 lines
12 KiB
Python
331 lines
12 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""YouTube relay session history — cloud pipeline (group_id as process key)."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sqlite3
|
|
import time
|
|
import uuid
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from .db import _connect, _lock, _row_to_dict
|
|
|
|
_ACTIVE: dict[str, int] = {}
|
|
|
|
|
|
def ensure_yt_relay_sessions(conn: sqlite3.Connection) -> None:
|
|
conn.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS yt_relay_sessions (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
session_uuid TEXT NOT NULL UNIQUE,
|
|
group_id TEXT NOT NULL DEFAULT '',
|
|
channel_name TEXT NOT NULL DEFAULT '',
|
|
anchor_name TEXT NOT NULL DEFAULT '',
|
|
source_url TEXT NOT NULL DEFAULT '',
|
|
source_room_id TEXT NOT NULL DEFAULT '',
|
|
stream_title TEXT NOT NULL DEFAULT '',
|
|
youtube_key_suffix 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 '',
|
|
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
|
|
)
|
|
"""
|
|
)
|
|
conn.execute(
|
|
"CREATE INDEX IF NOT EXISTS idx_yt_relay_sess_group ON yt_relay_sessions(group_id, started_at DESC)"
|
|
)
|
|
conn.execute(
|
|
"CREATE INDEX IF NOT EXISTS idx_yt_relay_sess_date ON yt_relay_sessions(push_date DESC, started_at DESC)"
|
|
)
|
|
|
|
|
|
def _push_date(ts: float) -> str:
|
|
try:
|
|
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
|
|
except (OSError, ValueError, OverflowError):
|
|
return ""
|
|
|
|
|
|
def _row_session(row: dict[str, Any]) -> dict[str, Any]:
|
|
out = dict(row)
|
|
meta = out.pop("metadata_json", "{}")
|
|
try:
|
|
out["metadata"] = json.loads(meta) if meta else {}
|
|
except json.JSONDecodeError:
|
|
out["metadata"] = {}
|
|
started = float(out.get("started_at") or 0)
|
|
ended = out.get("ended_at")
|
|
stored = float(out.get("duration_seconds") or 0)
|
|
if ended:
|
|
out["duration_seconds"] = int(max(0, float(ended) - started)) if started else int(stored)
|
|
elif stored > 0:
|
|
out["duration_seconds"] = int(stored)
|
|
elif started > 0:
|
|
out["duration_seconds"] = int(max(0, time.time() - started))
|
|
else:
|
|
out["duration_seconds"] = 0
|
|
out["process"] = out.get("group_id") or ""
|
|
return out
|
|
|
|
|
|
def start_session(
|
|
group_id: str,
|
|
*,
|
|
channel_name: str = "",
|
|
anchor_name: str = "",
|
|
source_url: str = "",
|
|
source_room_id: str = "",
|
|
youtube_key_suffix: str = "",
|
|
metadata: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
gid = str(group_id or "").strip()
|
|
now = time.time()
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_relay_sessions(conn)
|
|
open_row = conn.execute(
|
|
"SELECT id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1",
|
|
(gid,),
|
|
).fetchone()
|
|
if open_row:
|
|
sid = int(open_row[0])
|
|
_ACTIVE[gid] = sid
|
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (sid,)).fetchone()
|
|
return _row_session(_row_to_dict(row) or {"id": sid, "group_id": gid})
|
|
for other_gid, sid in list(_ACTIVE.items()):
|
|
if other_gid == gid:
|
|
continue
|
|
open_others = conn.execute(
|
|
"SELECT id, group_id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL",
|
|
(gid,),
|
|
).fetchall()
|
|
for r in open_others:
|
|
_close(conn, int(r[0]), ended_at=now, reason="source_switch")
|
|
session_uuid = str(uuid.uuid4())
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO yt_relay_sessions(
|
|
session_uuid, group_id, channel_name, anchor_name, source_url, source_room_id,
|
|
stream_title, youtube_key_suffix, started_at, duration_seconds, push_date,
|
|
status, end_reason, metadata_json, created_at, updated_at
|
|
) VALUES (?, ?, ?, ?, ?, ?, '', ?, ?, 0, ?, 'active', '', ?, ?, ?)
|
|
""",
|
|
(
|
|
session_uuid,
|
|
gid,
|
|
channel_name[:200],
|
|
anchor_name[:200],
|
|
source_url[:500],
|
|
source_room_id[:64],
|
|
youtube_key_suffix[:32],
|
|
now,
|
|
_push_date(now),
|
|
json.dumps(metadata or {}, ensure_ascii=False),
|
|
now,
|
|
now,
|
|
),
|
|
)
|
|
sid = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
|
|
conn.commit()
|
|
_ACTIVE[gid] = sid
|
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (sid,)).fetchone()
|
|
return _row_session(_row_to_dict(row) or {"id": sid, "group_id": gid})
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def end_session(group_id: str, *, reason: str = "stopped", ended_at: float | None = None) -> dict[str, Any] | None:
|
|
gid = str(group_id or "").strip()
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_relay_sessions(conn)
|
|
row = conn.execute(
|
|
"SELECT id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1",
|
|
(gid,),
|
|
).fetchone()
|
|
if not row:
|
|
_ACTIVE.pop(gid, None)
|
|
return None
|
|
sid = int(row[0])
|
|
session = _close(conn, sid, ended_at=ended_at, reason=reason)
|
|
conn.commit()
|
|
_ACTIVE.pop(gid, None)
|
|
return session
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _close(
|
|
conn: sqlite3.Connection,
|
|
session_id: int,
|
|
*,
|
|
ended_at: float | None = None,
|
|
reason: str = "",
|
|
) -> dict[str, Any]:
|
|
now = float(ended_at or time.time())
|
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (session_id,)).fetchone()
|
|
if not row:
|
|
return {"id": session_id}
|
|
data = _row_to_dict(row) or {}
|
|
started = float(data.get("started_at") or now)
|
|
duration = max(0.0, now - started)
|
|
conn.execute(
|
|
"""
|
|
UPDATE yt_relay_sessions SET
|
|
ended_at = ?, duration_seconds = ?, status = 'ended', end_reason = ?, updated_at = ?
|
|
WHERE id = ?
|
|
""",
|
|
(now, duration, str(reason or "")[:200], now, session_id),
|
|
)
|
|
updated = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (session_id,)).fetchone()
|
|
return _row_session(_row_to_dict(updated) or data)
|
|
|
|
|
|
def list_sessions(
|
|
*,
|
|
group_id: str = "",
|
|
q: str = "",
|
|
date_from: str = "",
|
|
date_to: str = "",
|
|
status: str = "",
|
|
limit: int = 50,
|
|
offset: int = 0,
|
|
) -> dict[str, Any]:
|
|
clauses: list[str] = []
|
|
params: list[Any] = []
|
|
if group_id.strip():
|
|
clauses.append("group_id = ?")
|
|
params.append(group_id.strip())
|
|
if status == "active":
|
|
clauses.append("ended_at IS NULL")
|
|
elif status == "ended":
|
|
clauses.append("ended_at IS NOT NULL")
|
|
if date_from.strip():
|
|
clauses.append("push_date >= ?")
|
|
params.append(date_from.strip())
|
|
if date_to.strip():
|
|
clauses.append("push_date <= ?")
|
|
params.append(date_to.strip())
|
|
if q.strip():
|
|
like = f"%{q.strip()}%"
|
|
clauses.append(
|
|
"(anchor_name LIKE ? OR source_url LIKE ? OR source_room_id LIKE ? OR channel_name LIKE ?)"
|
|
)
|
|
params.extend([like, like, like, like])
|
|
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
|
|
lim = max(1, min(int(limit), 200))
|
|
off = max(0, int(offset))
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_relay_sessions(conn)
|
|
rows = conn.execute(
|
|
f"SELECT * FROM yt_relay_sessions {where} ORDER BY started_at DESC LIMIT ? OFFSET ?",
|
|
(*params, lim, off),
|
|
).fetchall()
|
|
total = conn.execute(f"SELECT COUNT(*) FROM yt_relay_sessions {where}", params).fetchone()[0]
|
|
return {
|
|
"sessions": [_row_session(_row_to_dict(r) or {}) for r in rows],
|
|
"total": int(total or 0),
|
|
"limit": lim,
|
|
"offset": off,
|
|
}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def summarize_sessions(
|
|
*,
|
|
group_id: str = "",
|
|
q: str = "",
|
|
date_from: str = "",
|
|
date_to: str = "",
|
|
status: str = "",
|
|
top_anchors: int = 20,
|
|
) -> dict[str, Any]:
|
|
data = list_sessions(group_id=group_id, q=q, date_from=date_from, date_to=date_to, status=status, limit=5000, offset=0)
|
|
sessions = data.get("sessions") or []
|
|
now = time.time()
|
|
by_anchor: dict[str, dict[str, Any]] = {}
|
|
by_date: dict[str, dict[str, Any]] = {}
|
|
by_hour = [0] * 24
|
|
total_duration = 0.0
|
|
active_count = 0
|
|
duration_values: list[float] = []
|
|
|
|
for s in sessions:
|
|
dur = float(s.get("duration_seconds") or 0)
|
|
if not s.get("ended_at") and s.get("started_at"):
|
|
dur = max(dur, now - float(s["started_at"]))
|
|
active_count += 1
|
|
total_duration += dur
|
|
duration_values.append(dur)
|
|
anchor = str(s.get("anchor_name") or "未知").strip() or "未知"
|
|
ac = by_anchor.setdefault(anchor, {"anchor_name": anchor, "sessions": 0, "duration_seconds": 0.0})
|
|
ac["sessions"] += 1
|
|
ac["duration_seconds"] += dur
|
|
pd = str(s.get("push_date") or "")
|
|
if pd:
|
|
d = by_date.setdefault(pd, {"date": pd, "sessions": 0, "duration_seconds": 0.0, "anchors": set()})
|
|
d["sessions"] += 1
|
|
d["duration_seconds"] += dur
|
|
d["anchors"].add(anchor)
|
|
started = float(s.get("started_at") or 0)
|
|
if started > 0:
|
|
try:
|
|
by_hour[datetime.fromtimestamp(started).hour] += 1
|
|
except (OSError, ValueError, OverflowError):
|
|
pass
|
|
|
|
top = sorted(by_anchor.values(), key=lambda x: (-x["sessions"], -x["duration_seconds"]))[: max(1, top_anchors)]
|
|
for t in top:
|
|
t["hours_total"] = round(t["duration_seconds"] / 3600, 2)
|
|
|
|
dates_sorted = sorted(by_date.values(), key=lambda x: x["date"])
|
|
by_date_out = [
|
|
{
|
|
"date": d["date"],
|
|
"sessions": d["sessions"],
|
|
"hours": round(d["duration_seconds"] / 3600, 2),
|
|
"unique_anchors": len(d["anchors"]),
|
|
}
|
|
for d in dates_sorted[-60:]
|
|
]
|
|
|
|
avg_d = total_duration / len(sessions) if sessions else 0
|
|
return {
|
|
"overview": {
|
|
"sessions": len(sessions),
|
|
"unique_anchors": len(by_anchor),
|
|
"active_sessions": active_count,
|
|
"total_hours": round(total_duration / 3600, 2),
|
|
"avg_duration_seconds": int(avg_d),
|
|
"date_from": dates_sorted[0]["date"] if dates_sorted else "",
|
|
"date_to": dates_sorted[-1]["date"] if dates_sorted else "",
|
|
},
|
|
"top_anchors": top,
|
|
"by_hour": {"starts": by_hour, "labels": [f"{h:02d}:00" for h in range(24)]},
|
|
"by_date": by_date_out,
|
|
}
|
|
|
|
|
|
def get_session(session_id: int) -> dict[str, Any] | None:
|
|
with _lock:
|
|
conn = _connect()
|
|
try:
|
|
ensure_yt_relay_sessions(conn)
|
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (int(session_id),)).fetchone()
|
|
return _row_session(_row_to_dict(row) or {}) if row else None
|
|
finally:
|
|
conn.close()
|