Prefer location.assign for endscreen leave, and ship hub analytics/charts plus host deploy helpers. Co-authored-by: Cursor <cursoragent@cursor.com>
1383 lines
49 KiB
Python
1383 lines
49 KiB
Python
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import threading
|
||
import time
|
||
import uuid
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from src.douyin_source_display import (
|
||
_entry_for_title,
|
||
_url_entries_from_lines,
|
||
extract_douyin_source_meta,
|
||
)
|
||
from src.youtube_live_store import _connect, extract_first_url, extract_source_room_id, extract_youtube_key_suffix
|
||
|
||
_RELAY_SESSIONS_TABLE = "youtube_relay_sessions"
|
||
_RECORDING_LINE_RE = re.compile(
|
||
r"正在录制\s*\d+\s*(?:个|路)\s*[::]\s*([^[\n]+?)\[原画\s*([0-9:]+)\]",
|
||
re.IGNORECASE,
|
||
)
|
||
_PUSH_START_RE = re.compile(r"开始推流到 YouTube:\s*(.+?)\s*$")
|
||
_STREAM_TITLE_TS_RE = re.compile(r"_(?P<ts>\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})$")
|
||
_LOG_TS_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}):")
|
||
_INCOMING_URL_RE = re.compile(r"传入地址:\s*(https?://\S+)", re.IGNORECASE)
|
||
_FAIL_ADDR_RE = re.compile(
|
||
r"获取失败的地址是:\('原画',\s*'(https?://[^']+)',\s*'主播:\s*([^']+)'\)"
|
||
)
|
||
_ANCHOR_LABEL_RE = re.compile(r"主播[::]\s*([^\s'\"()]+)")
|
||
|
||
_ACTIVE_BY_PROCESS: dict[str, int] = {}
|
||
|
||
|
||
def _json_dumps(value: Any) -> str:
|
||
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)
|
||
|
||
|
||
def _json_loads(raw: str | None, fallback: Any) -> Any:
|
||
if not raw:
|
||
return fallback
|
||
try:
|
||
return json.loads(raw)
|
||
except json.JSONDecodeError:
|
||
return fallback
|
||
|
||
|
||
def _normalize_process(process: str) -> str:
|
||
return (process or "").strip() or "youtube"
|
||
|
||
|
||
def _covers_dir(base_dir: Path | None = None) -> Path:
|
||
root = base_dir or Path(os.environ.get("LIVE_PROJECT_ROOT") or Path(__file__).resolve().parent.parent)
|
||
path = root / "runtime" / "youtube_relay" / "covers"
|
||
path.mkdir(parents=True, exist_ok=True)
|
||
return path
|
||
|
||
|
||
def _ensure_schema(conn) -> None:
|
||
conn.execute(
|
||
f"""
|
||
CREATE TABLE IF NOT EXISTS {_RELAY_SESSIONS_TABLE} (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
session_uuid TEXT NOT NULL UNIQUE,
|
||
process 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 '',
|
||
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
|
||
)
|
||
"""
|
||
)
|
||
conn.execute(
|
||
f"CREATE INDEX IF NOT EXISTS idx_relay_sessions_process "
|
||
f"ON {_RELAY_SESSIONS_TABLE}(process, started_at DESC)"
|
||
)
|
||
conn.execute(
|
||
f"CREATE INDEX IF NOT EXISTS idx_relay_sessions_room "
|
||
f"ON {_RELAY_SESSIONS_TABLE}(source_room_id)"
|
||
)
|
||
conn.execute(
|
||
f"CREATE INDEX IF NOT EXISTS idx_relay_sessions_date "
|
||
f"ON {_RELAY_SESSIONS_TABLE}(push_date DESC, started_at DESC)"
|
||
)
|
||
conn.commit()
|
||
|
||
|
||
def _connect_relay(db_path: Path | None = None):
|
||
conn = _connect(db_path)
|
||
_ensure_schema(conn)
|
||
return conn
|
||
|
||
|
||
def _row_to_session(row) -> dict[str, Any]:
|
||
data = dict(row)
|
||
data["metadata"] = _json_loads(data.pop("metadata_json", "{}"), {})
|
||
stored_duration = int(float(data.get("duration_seconds") or 0))
|
||
if data.get("ended_at"):
|
||
data["duration_seconds"] = stored_duration
|
||
elif stored_duration > 0:
|
||
data["duration_seconds"] = stored_duration
|
||
else:
|
||
data["duration_seconds"] = int(max(0, time.time() - float(data.get("started_at") or time.time())))
|
||
data["cover_url"] = f"/hub/youtube/relay/sessions/{data['id']}/cover" if data.get("cover_path") else ""
|
||
return data
|
||
|
||
|
||
def _push_date_from_ts(ts: float) -> str:
|
||
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
|
||
|
||
|
||
def _parse_stream_title(stream_title: str) -> tuple[str, str]:
|
||
title = (stream_title or "").strip()
|
||
match = _STREAM_TITLE_TS_RE.search(title)
|
||
if not match:
|
||
return title, ""
|
||
anchor = title[: match.start()].rstrip("_")
|
||
stamp = match.group("ts")
|
||
push_date = stamp.split("_", 1)[0] if "_" in stamp else ""
|
||
return anchor, push_date
|
||
|
||
|
||
def _timestamp_from_stream_title(stream_title: str) -> float | None:
|
||
match = _STREAM_TITLE_TS_RE.search(stream_title or "")
|
||
if not match:
|
||
return None
|
||
try:
|
||
return datetime.strptime(match.group("ts"), "%Y-%m-%d_%H-%M-%S").timestamp()
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def _parse_log_line_ts(line: str) -> float | None:
|
||
match = _LOG_TS_RE.match(line.strip())
|
||
if not match:
|
||
return None
|
||
try:
|
||
return datetime.strptime(match.group(1), "%Y-%m-%dT%H:%M:%S").timestamp()
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def _parse_local_wall_time(line: str, log_ts: float | None) -> float | None:
|
||
if log_ts is None:
|
||
return None
|
||
local_hms = ""
|
||
for part in reversed(line.split("|")):
|
||
token = part.strip()
|
||
if re.fullmatch(r"\d{2}:\d{2}:\d{2}", token):
|
||
local_hms = token
|
||
break
|
||
if not local_hms:
|
||
return log_ts
|
||
try:
|
||
base = datetime.fromtimestamp(log_ts)
|
||
hour, minute, second = (int(x) for x in local_hms.split(":"))
|
||
return base.replace(hour=hour, minute=minute, second=second, microsecond=0).timestamp()
|
||
except (ValueError, OSError):
|
||
return log_ts
|
||
|
||
|
||
def _clean_douyin_url(url: str) -> str:
|
||
return extract_first_url(url) or ""
|
||
|
||
|
||
def _build_anchor_url_index(url_lines: str) -> dict[str, tuple[str, str]]:
|
||
index: dict[str, tuple[str, str]] = {}
|
||
for entry in _url_entries_from_lines(url_lines):
|
||
title = (entry.get("source_title") or "").strip()
|
||
url = _clean_douyin_url(entry.get("source_url") or "")
|
||
room_id = entry.get("room_id") or ""
|
||
if title and url:
|
||
index[title] = (url, room_id)
|
||
return index
|
||
|
||
|
||
def _resolve_anchor_url(
|
||
anchor: str,
|
||
url_index: dict[str, tuple[str, str]],
|
||
url_lines: str,
|
||
log_url_index: dict[str, tuple[str, str]] | None = None,
|
||
) -> tuple[str, str]:
|
||
name = (anchor or "").strip()
|
||
if not name:
|
||
return "", ""
|
||
if log_url_index and name in log_url_index:
|
||
return log_url_index[name]
|
||
entry = _entry_for_title(_url_entries_from_lines(url_lines), name)
|
||
if entry:
|
||
return _clean_douyin_url(entry["source_url"]), entry["room_id"]
|
||
if name in url_index:
|
||
url, room_id = url_index[name]
|
||
return _clean_douyin_url(url), room_id
|
||
meta = extract_douyin_source_meta(url_lines, name)
|
||
url = _clean_douyin_url(str(meta.get("source_url") or ""))
|
||
room_id = str(meta.get("source_room_id") or "")
|
||
if url:
|
||
return url, room_id
|
||
return _lookup_room_id(name, url_lines)
|
||
|
||
|
||
def _parse_duration_token(token: str) -> int:
|
||
parts = [int(part) for part in (token or "0").split(":")]
|
||
if len(parts) == 3:
|
||
return parts[0] * 3600 + parts[1] * 60 + parts[2]
|
||
if len(parts) == 2:
|
||
return parts[0] * 60 + parts[1]
|
||
return 0
|
||
|
||
|
||
def _lookup_room_id(anchor_name: str, url_lines: str) -> tuple[str, str]:
|
||
anchor = (anchor_name or "").strip()
|
||
for line in (url_lines or "").splitlines():
|
||
stripped = line.strip()
|
||
if not stripped or stripped.startswith("#"):
|
||
continue
|
||
if anchor and anchor not in stripped:
|
||
continue
|
||
url = extract_first_url(stripped)
|
||
room_id = extract_source_room_id(stripped, url)
|
||
if url:
|
||
return url, room_id
|
||
meta = extract_douyin_source_meta(url_lines, anchor)
|
||
return str(meta.get("source_url") or ""), str(meta.get("source_room_id") or "")
|
||
|
||
|
||
def _close_session_row(
|
||
conn,
|
||
row_id: int,
|
||
*,
|
||
ended_at: float | None = None,
|
||
reason: str = "",
|
||
duration_seconds: int | None = None,
|
||
) -> None:
|
||
row = conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (row_id,)).fetchone()
|
||
if not row or row["ended_at"]:
|
||
return
|
||
end = float(ended_at or time.time())
|
||
duration = duration_seconds
|
||
if duration is None:
|
||
duration = int(max(0, end - float(row["started_at"])))
|
||
conn.execute(
|
||
f"""
|
||
UPDATE {_RELAY_SESSIONS_TABLE}
|
||
SET ended_at = ?, duration_seconds = ?, status = 'ended', end_reason = ?, updated_at = ?
|
||
WHERE id = ?
|
||
""",
|
||
(end, int(duration), (reason or "")[:500], end, row_id),
|
||
)
|
||
process = str(row["process"] or "")
|
||
if _ACTIVE_BY_PROCESS.get(process) == row_id:
|
||
_ACTIVE_BY_PROCESS.pop(process, None)
|
||
|
||
|
||
def close_active_relay_sessions(
|
||
process: str,
|
||
*,
|
||
reason: str = "",
|
||
ended_at: float | None = None,
|
||
db_path: Path | None = None,
|
||
) -> list[dict[str, Any]]:
|
||
proc = _normalize_process(process)
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
rows = conn.execute(
|
||
f"SELECT id FROM {_RELAY_SESSIONS_TABLE} WHERE process = ? AND ended_at IS NULL ORDER BY started_at DESC",
|
||
(proc,),
|
||
).fetchall()
|
||
for row in rows:
|
||
_close_session_row(conn, int(row["id"]), ended_at=ended_at, reason=reason)
|
||
conn.commit()
|
||
if not rows:
|
||
return []
|
||
ids = [int(row["id"]) for row in rows]
|
||
return [
|
||
_row_to_session(item)
|
||
for item in conn.execute(
|
||
f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id IN ({','.join('?' * len(ids))})",
|
||
ids,
|
||
).fetchall()
|
||
]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def start_relay_session(
|
||
*,
|
||
process: str,
|
||
anchor_name: str,
|
||
source_url: str = "",
|
||
source_room_id: str = "",
|
||
stream_title: str = "",
|
||
channel_name: str = "",
|
||
youtube_key_suffix: str = "",
|
||
metadata: dict[str, Any] | None = None,
|
||
capture_cover_url: str = "",
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any]:
|
||
proc = _normalize_process(process)
|
||
now = time.time()
|
||
anchor = (anchor_name or "").strip()
|
||
if not source_url:
|
||
source_url = extract_first_url(stream_title)
|
||
if not source_room_id:
|
||
source_room_id = extract_source_room_id(source_url, anchor_name, stream_title)
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
open_rows = conn.execute(
|
||
f"SELECT id, anchor_name FROM {_RELAY_SESSIONS_TABLE} WHERE process = ? AND ended_at IS NULL",
|
||
(proc,),
|
||
).fetchall()
|
||
for row in open_rows:
|
||
if str(row["anchor_name"] or "").strip() == anchor and anchor:
|
||
session = _row_to_session(
|
||
conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(row["id"]),)).fetchone()
|
||
)
|
||
conn.commit()
|
||
return session
|
||
_close_session_row(conn, int(row["id"]), ended_at=now, reason="source_switch")
|
||
session_uuid = str(uuid.uuid4())
|
||
push_date = _push_date_from_ts(now)
|
||
_, title_date = _parse_stream_title(stream_title)
|
||
if title_date:
|
||
push_date = title_date
|
||
title_started = _timestamp_from_stream_title(stream_title)
|
||
if title_started:
|
||
now = title_started
|
||
conn.execute(
|
||
f"""
|
||
INSERT INTO {_RELAY_SESSIONS_TABLE}(
|
||
session_uuid, process, channel_name, anchor_name, source_url, source_room_id,
|
||
stream_title, youtube_key_suffix, started_at, duration_seconds, push_date,
|
||
cover_path, status, metadata_json, created_at, updated_at
|
||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, '', 'active', ?, ?, ?)
|
||
""",
|
||
(
|
||
session_uuid,
|
||
proc,
|
||
channel_name or "",
|
||
anchor,
|
||
source_url or "",
|
||
source_room_id or "",
|
||
stream_title or "",
|
||
youtube_key_suffix or "",
|
||
now,
|
||
push_date,
|
||
_json_dumps(metadata or {}),
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
session_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||
_ACTIVE_BY_PROCESS[proc] = session_id
|
||
conn.commit()
|
||
session = _row_to_session(
|
||
conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (session_id,)).fetchone()
|
||
)
|
||
finally:
|
||
conn.close()
|
||
cover_url = capture_cover_url or source_url
|
||
if cover_url:
|
||
threading.Thread(
|
||
target=_capture_cover_safe,
|
||
args=(session["id"], cover_url, db_path),
|
||
daemon=True,
|
||
).start()
|
||
return session
|
||
|
||
|
||
def end_relay_session(
|
||
process: str,
|
||
*,
|
||
anchor_name: str = "",
|
||
reason: str = "",
|
||
ended_at: float | None = None,
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any] | None:
|
||
proc = _normalize_process(process)
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
if anchor_name.strip():
|
||
row = conn.execute(
|
||
f"""
|
||
SELECT id FROM {_RELAY_SESSIONS_TABLE}
|
||
WHERE process = ? AND ended_at IS NULL AND anchor_name = ?
|
||
ORDER BY started_at DESC LIMIT 1
|
||
""",
|
||
(proc, anchor_name.strip()),
|
||
).fetchone()
|
||
else:
|
||
row = conn.execute(
|
||
f"""
|
||
SELECT id FROM {_RELAY_SESSIONS_TABLE}
|
||
WHERE process = ? AND ended_at IS NULL
|
||
ORDER BY started_at DESC LIMIT 1
|
||
""",
|
||
(proc,),
|
||
).fetchone()
|
||
if not row:
|
||
conn.commit()
|
||
return None
|
||
_close_session_row(conn, int(row["id"]), ended_at=ended_at, reason=reason or "ended")
|
||
conn.commit()
|
||
closed = conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(row["id"]),)).fetchone()
|
||
return _row_to_session(closed) if closed else None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def on_relay_push_start(
|
||
*,
|
||
process: str,
|
||
anchor_name: str,
|
||
record_url: str | None,
|
||
stream_title: str,
|
||
real_url: str,
|
||
channel_name: str = "",
|
||
youtube_ini_text: str = "",
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any]:
|
||
source_url = (record_url or "").strip() or extract_first_url(record_url or "")
|
||
if not source_url and real_url:
|
||
source_url = real_url
|
||
room_id = extract_source_room_id(record_url or "", real_url or "", anchor_name)
|
||
return start_relay_session(
|
||
process=process,
|
||
anchor_name=anchor_name,
|
||
source_url=source_url,
|
||
source_room_id=room_id,
|
||
stream_title=stream_title,
|
||
channel_name=channel_name,
|
||
youtube_key_suffix=extract_youtube_key_suffix(youtube_ini_text),
|
||
metadata={"real_url": real_url, "record_url": record_url or ""},
|
||
capture_cover_url=real_url or source_url,
|
||
db_path=db_path,
|
||
)
|
||
|
||
|
||
def on_relay_push_end(
|
||
process: str,
|
||
*,
|
||
anchor_name: str,
|
||
reason: str = "push_stopped",
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any] | None:
|
||
return end_relay_session(process, anchor_name=anchor_name, reason=reason, db_path=db_path)
|
||
|
||
|
||
def sync_relay_from_recent_log(
|
||
process: str,
|
||
recent_log: str,
|
||
*,
|
||
channel_name: str = "",
|
||
url_lines: str = "",
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any] | None:
|
||
proc = _normalize_process(process)
|
||
anchor = ""
|
||
duration_token = ""
|
||
for line in reversed((recent_log or "").splitlines()):
|
||
match = _RECORDING_LINE_RE.search(line)
|
||
if match:
|
||
anchor = match.group(1).strip(" :?")
|
||
duration_token = match.group(2).strip()
|
||
break
|
||
if not anchor:
|
||
if "无录制任务" in (recent_log or "")[-2000:]:
|
||
closed = close_active_relay_sessions(proc, reason="idle", db_path=db_path)
|
||
return {"closed": closed}
|
||
return None
|
||
source_url, room_id = _lookup_room_id(anchor, url_lines)
|
||
if not source_url:
|
||
meta = extract_douyin_source_meta(url_lines, recent_log)
|
||
source_url = str(meta.get("source_url") or "")
|
||
room_id = str(meta.get("source_room_id") or room_id)
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
row = conn.execute(
|
||
f"""
|
||
SELECT id, anchor_name FROM {_RELAY_SESSIONS_TABLE}
|
||
WHERE process = ? AND ended_at IS NULL
|
||
ORDER BY started_at DESC LIMIT 1
|
||
""",
|
||
(proc,),
|
||
).fetchone()
|
||
if row and str(row["anchor_name"] or "").strip() == anchor:
|
||
if duration_token:
|
||
duration = _parse_duration_token(duration_token)
|
||
conn.execute(
|
||
f"UPDATE {_RELAY_SESSIONS_TABLE} SET duration_seconds = ?, updated_at = ? WHERE id = ?",
|
||
(duration, time.time(), int(row["id"])),
|
||
)
|
||
conn.commit()
|
||
return _row_to_session(
|
||
conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(row["id"]),)).fetchone()
|
||
)
|
||
finally:
|
||
conn.close()
|
||
if row:
|
||
end_relay_session(proc, anchor_name=str(row["anchor_name"] or ""), reason="source_switch", db_path=db_path)
|
||
session = start_relay_session(
|
||
process=proc,
|
||
anchor_name=anchor,
|
||
source_url=source_url,
|
||
source_room_id=room_id,
|
||
channel_name=channel_name,
|
||
metadata={"sync": "recent_log", "duration_token": duration_token},
|
||
capture_cover_url=source_url,
|
||
db_path=db_path,
|
||
)
|
||
if duration_token and session.get("id"):
|
||
duration = _parse_duration_token(duration_token)
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
conn.execute(
|
||
f"UPDATE {_RELAY_SESSIONS_TABLE} SET duration_seconds = ?, updated_at = ? WHERE id = ?",
|
||
(duration, time.time(), int(session["id"])),
|
||
)
|
||
conn.commit()
|
||
session = _row_to_session(
|
||
conn.execute(f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ?", (int(session["id"]),)).fetchone()
|
||
)
|
||
finally:
|
||
conn.close()
|
||
return session
|
||
|
||
|
||
def _capture_cover_safe(session_id: int, stream_url: str, db_path: Path | None) -> None:
|
||
try:
|
||
capture_relay_cover(session_id, stream_url, db_path=db_path)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def capture_relay_cover(session_id: int, stream_url: str, *, db_path: Path | None = None) -> str:
|
||
url = (stream_url or "").strip()
|
||
if not url:
|
||
return ""
|
||
covers = _covers_dir()
|
||
out_path = covers / f"{session_id}.jpg"
|
||
headers = (
|
||
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
|
||
"Referer: https://live.douyin.com/\r\n"
|
||
)
|
||
cmd = [
|
||
"ffmpeg",
|
||
"-hide_banner",
|
||
"-loglevel",
|
||
"error",
|
||
"-y",
|
||
"-headers",
|
||
headers,
|
||
"-rw_timeout",
|
||
"15000000",
|
||
"-i",
|
||
url,
|
||
"-frames:v",
|
||
"1",
|
||
"-q:v",
|
||
"3",
|
||
str(out_path),
|
||
]
|
||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=25)
|
||
if proc.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 128:
|
||
return ""
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
conn.execute(
|
||
f"UPDATE {_RELAY_SESSIONS_TABLE} SET cover_path = ?, updated_at = ? WHERE id = ?",
|
||
(str(out_path), time.time(), session_id),
|
||
)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
return str(out_path)
|
||
|
||
|
||
def get_relay_cover_path(session_id: int | str, *, db_path: Path | None = None) -> Path | None:
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
row = conn.execute(
|
||
f"SELECT cover_path FROM {_RELAY_SESSIONS_TABLE} WHERE id = ? OR session_uuid = ?",
|
||
(session_id, str(session_id)),
|
||
).fetchone()
|
||
if not row:
|
||
return None
|
||
path = Path(str(row["cover_path"] or ""))
|
||
return path if path.is_file() else None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def list_relay_sessions(
|
||
*,
|
||
process: str = "",
|
||
q: str = "",
|
||
date_from: str = "",
|
||
date_to: str = "",
|
||
status: str = "",
|
||
limit: int = 50,
|
||
offset: int = 0,
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any]:
|
||
clauses: list[str] = []
|
||
params: list[Any] = []
|
||
if process:
|
||
clauses.append("process = ?")
|
||
params.append(_normalize_process(process))
|
||
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.strip())
|
||
if date_to:
|
||
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 stream_title LIKE ? OR channel_name LIKE ?)"
|
||
)
|
||
params.extend([like, like, like, like, like])
|
||
where = "WHERE " + " AND ".join(clauses) if clauses else ""
|
||
safe_limit = max(1, min(int(limit), 200))
|
||
safe_offset = max(0, int(offset))
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
rows = conn.execute(
|
||
f"SELECT * FROM {_RELAY_SESSIONS_TABLE} {where} ORDER BY started_at DESC LIMIT ? OFFSET ?",
|
||
(*params, safe_limit, safe_offset),
|
||
).fetchall()
|
||
total = conn.execute(f"SELECT COUNT(*) FROM {_RELAY_SESSIONS_TABLE} {where}", params).fetchone()[0]
|
||
return {
|
||
"sessions": [_row_to_session(row) for row in rows],
|
||
"total": int(total),
|
||
"limit": safe_limit,
|
||
"offset": safe_offset,
|
||
}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _relay_filter_clause(
|
||
*,
|
||
process: str = "",
|
||
q: str = "",
|
||
date_from: str = "",
|
||
date_to: str = "",
|
||
status: str = "",
|
||
) -> tuple[str, list[Any]]:
|
||
clauses: list[str] = []
|
||
params: list[Any] = []
|
||
if process:
|
||
clauses.append("process = ?")
|
||
params.append(_normalize_process(process))
|
||
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.strip())
|
||
if date_to:
|
||
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 stream_title LIKE ? OR channel_name LIKE ?)"
|
||
)
|
||
params.extend([like, like, like, like, like])
|
||
where = "WHERE " + " AND ".join(clauses) if clauses else ""
|
||
return where, params
|
||
|
||
|
||
def _session_effective_duration(row: dict[str, Any], now: float) -> float:
|
||
started = float(row.get("started_at") or 0)
|
||
ended = row.get("ended_at")
|
||
stored = float(row.get("duration_seconds") or 0)
|
||
if ended:
|
||
return max(0.0, float(ended) - started) if started else max(0.0, stored)
|
||
if stored > 0:
|
||
return stored
|
||
if started > 0:
|
||
return max(0.0, now - started)
|
||
return 0.0
|
||
|
||
|
||
def summarize_relay_sessions(
|
||
*,
|
||
process: str = "",
|
||
q: str = "",
|
||
date_from: str = "",
|
||
date_to: str = "",
|
||
status: str = "",
|
||
top_anchors: int = 20,
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Aggregate relay sessions for charting: frequency, time-of-day, weekday, duration."""
|
||
where, params = _relay_filter_clause(
|
||
process=process,
|
||
q=q,
|
||
date_from=date_from,
|
||
date_to=date_to,
|
||
status=status,
|
||
)
|
||
now = time.time()
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
rows = conn.execute(
|
||
f"SELECT * FROM {_RELAY_SESSIONS_TABLE} {where} ORDER BY started_at ASC",
|
||
params,
|
||
).fetchall()
|
||
finally:
|
||
conn.close()
|
||
|
||
sessions = [_row_to_session(row) for row in rows]
|
||
by_hour_starts = [0] * 24
|
||
by_hour_minutes = [0.0] * 24
|
||
by_weekday_starts = [0] * 7 # Mon=0
|
||
by_weekday_minutes = [0.0] * 7
|
||
heatmap_starts = [[0 for _ in range(24)] for _ in range(7)]
|
||
heatmap_minutes = [[0.0 for _ in range(24)] for _ in range(7)]
|
||
by_date: dict[str, dict[str, Any]] = {}
|
||
by_anchor: dict[str, dict[str, Any]] = {}
|
||
duration_values: list[float] = []
|
||
duration_buckets = {
|
||
"<15m": 0,
|
||
"15-60m": 0,
|
||
"1-3h": 0,
|
||
"3-6h": 0,
|
||
"6-12h": 0,
|
||
">=12h": 0,
|
||
}
|
||
active_count = 0
|
||
total_duration = 0.0
|
||
|
||
for session in sessions:
|
||
started = float(session.get("started_at") or 0)
|
||
if started <= 0:
|
||
continue
|
||
duration = _session_effective_duration(session, now)
|
||
total_duration += duration
|
||
duration_values.append(duration)
|
||
if not session.get("ended_at"):
|
||
active_count += 1
|
||
|
||
if duration < 15 * 60:
|
||
duration_buckets["<15m"] += 1
|
||
elif duration < 60 * 60:
|
||
duration_buckets["15-60m"] += 1
|
||
elif duration < 3 * 3600:
|
||
duration_buckets["1-3h"] += 1
|
||
elif duration < 6 * 3600:
|
||
duration_buckets["3-6h"] += 1
|
||
elif duration < 12 * 3600:
|
||
duration_buckets["6-12h"] += 1
|
||
else:
|
||
duration_buckets[">=12h"] += 1
|
||
|
||
try:
|
||
start_dt = datetime.fromtimestamp(started)
|
||
except (OSError, ValueError, OverflowError):
|
||
continue
|
||
hour = start_dt.hour
|
||
weekday = start_dt.weekday()
|
||
push_date = (session.get("push_date") or start_dt.strftime("%Y-%m-%d")).strip()
|
||
by_hour_starts[hour] += 1
|
||
by_weekday_starts[weekday] += 1
|
||
heatmap_starts[weekday][hour] += 1
|
||
|
||
# Occupancy: distribute duration across hours the session covers.
|
||
cursor = started
|
||
end_ts = float(session.get("ended_at") or (started + duration))
|
||
if end_ts < cursor:
|
||
end_ts = cursor
|
||
guard = 0
|
||
while cursor < end_ts and guard < 48 * 7:
|
||
guard += 1
|
||
try:
|
||
cur_dt = datetime.fromtimestamp(cursor)
|
||
except (OSError, ValueError, OverflowError):
|
||
break
|
||
next_hour = cur_dt.replace(minute=0, second=0, microsecond=0).timestamp() + 3600
|
||
slice_end = min(end_ts, next_hour)
|
||
minutes = max(0.0, (slice_end - cursor) / 60.0)
|
||
h = cur_dt.hour
|
||
wd = cur_dt.weekday()
|
||
by_hour_minutes[h] += minutes
|
||
by_weekday_minutes[wd] += minutes
|
||
heatmap_minutes[wd][h] += minutes
|
||
cursor = slice_end
|
||
|
||
day = by_date.setdefault(
|
||
push_date,
|
||
{"date": push_date, "sessions": 0, "duration_seconds": 0.0, "anchors": set()},
|
||
)
|
||
day["sessions"] += 1
|
||
day["duration_seconds"] += duration
|
||
anchor = (session.get("anchor_name") or "").strip() or "(unknown)"
|
||
day["anchors"].add(anchor)
|
||
|
||
room = (session.get("source_room_id") or "").strip()
|
||
url = (session.get("source_url") or "").strip()
|
||
key = room or url or anchor
|
||
item = by_anchor.setdefault(
|
||
key,
|
||
{
|
||
"anchor_name": anchor,
|
||
"source_room_id": room,
|
||
"source_url": url,
|
||
"sessions": 0,
|
||
"duration_seconds": 0.0,
|
||
"active_sessions": 0,
|
||
"first_started_at": started,
|
||
"last_started_at": started,
|
||
"hour_counts": [0] * 24,
|
||
"weekday_counts": [0] * 7,
|
||
"dates": set(),
|
||
"channels": set(),
|
||
"processes": set(),
|
||
"avg_gap_hours": None,
|
||
"_starts": [],
|
||
},
|
||
)
|
||
if not item["anchor_name"] or item["anchor_name"] == "(unknown)":
|
||
item["anchor_name"] = anchor
|
||
if room and not item["source_room_id"]:
|
||
item["source_room_id"] = room
|
||
if url and not item["source_url"]:
|
||
item["source_url"] = url
|
||
item["sessions"] += 1
|
||
item["duration_seconds"] += duration
|
||
if not session.get("ended_at"):
|
||
item["active_sessions"] += 1
|
||
item["first_started_at"] = min(float(item["first_started_at"]), started)
|
||
item["last_started_at"] = max(float(item["last_started_at"]), started)
|
||
item["hour_counts"][hour] += 1
|
||
item["weekday_counts"][weekday] += 1
|
||
item["dates"].add(push_date)
|
||
if session.get("channel_name"):
|
||
item["channels"].add(str(session["channel_name"]))
|
||
if session.get("process"):
|
||
item["processes"].add(str(session["process"]))
|
||
item["_starts"].append(started)
|
||
|
||
weekday_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
||
weekday_names_zh = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||
|
||
anchors_out: list[dict[str, Any]] = []
|
||
for item in by_anchor.values():
|
||
starts = sorted(float(x) for x in item.pop("_starts"))
|
||
gaps = [ (starts[i] - starts[i - 1]) / 3600.0 for i in range(1, len(starts)) ]
|
||
peak_hour = max(range(24), key=lambda h: item["hour_counts"][h])
|
||
peak_weekday = max(range(7), key=lambda d: item["weekday_counts"][d])
|
||
dates = sorted(item.pop("dates"))
|
||
sessions_n = int(item["sessions"])
|
||
dur = float(item["duration_seconds"])
|
||
span_days = max(1, len(dates))
|
||
anchors_out.append(
|
||
{
|
||
**item,
|
||
"channels": sorted(item.pop("channels")),
|
||
"processes": sorted(item.pop("processes")),
|
||
"dates_active": len(dates),
|
||
"date_first": dates[0] if dates else "",
|
||
"date_last": dates[-1] if dates else "",
|
||
"avg_duration_seconds": dur / sessions_n if sessions_n else 0.0,
|
||
"sessions_per_active_day": sessions_n / span_days if span_days else 0.0,
|
||
"hours_total": dur / 3600.0,
|
||
"peak_hour": peak_hour,
|
||
"peak_weekday": peak_weekday,
|
||
"peak_weekday_label": weekday_names_zh[peak_weekday],
|
||
"avg_gap_hours": (sum(gaps) / len(gaps)) if gaps else None,
|
||
"median_gap_hours": (sorted(gaps)[len(gaps) // 2] if gaps else None),
|
||
}
|
||
)
|
||
anchors_out.sort(key=lambda x: (-x["sessions"], -x["duration_seconds"], x["anchor_name"]))
|
||
top_n = max(1, min(int(top_anchors), 100))
|
||
top_anchors_list = anchors_out[:top_n]
|
||
|
||
dates_out = []
|
||
for date_key in sorted(by_date.keys()):
|
||
day = by_date[date_key]
|
||
dates_out.append(
|
||
{
|
||
"date": date_key,
|
||
"sessions": int(day["sessions"]),
|
||
"duration_seconds": float(day["duration_seconds"]),
|
||
"hours": float(day["duration_seconds"]) / 3600.0,
|
||
"unique_anchors": len(day["anchors"]),
|
||
}
|
||
)
|
||
|
||
duration_values.sort()
|
||
median_duration = (
|
||
duration_values[len(duration_values) // 2] if duration_values else 0.0
|
||
)
|
||
insights: list[dict[str, str]] = []
|
||
if sessions:
|
||
busiest_hour = max(range(24), key=lambda h: by_hour_starts[h])
|
||
busiest_day = max(range(7), key=lambda d: by_weekday_starts[d])
|
||
top = top_anchors_list[0] if top_anchors_list else None
|
||
insights.append(
|
||
{
|
||
"zh": f"共 {len(sessions)} 场推流,累计 {total_duration / 3600.0:.1f} 小时,覆盖 {len(by_anchor)} 位主播。",
|
||
"en": f"{len(sessions)} sessions, {total_duration / 3600.0:.1f}h total, {len(by_anchor)} anchors.",
|
||
}
|
||
)
|
||
insights.append(
|
||
{
|
||
"zh": f"最常开播时段:{busiest_hour:02d}:00–{busiest_hour:02d}:59;最常开播星期:{weekday_names_zh[busiest_day]}。",
|
||
"en": f"Peak start hour: {busiest_hour:02d}:00; peak weekday: {weekday_names[busiest_day]}.",
|
||
}
|
||
)
|
||
if top:
|
||
insights.append(
|
||
{
|
||
"zh": (
|
||
f"最高频主播「{top['anchor_name']}」:{top['sessions']} 场 / "
|
||
f"{top['hours_total']:.1f}h,峰值 {top['peak_hour']:02d}:00({top['peak_weekday_label']}),"
|
||
f"活跃 {top['dates_active']} 天。"
|
||
),
|
||
"en": (
|
||
f"Top anchor «{top['anchor_name']}»: {top['sessions']} sessions / "
|
||
f"{top['hours_total']:.1f}h, peaks {top['peak_hour']:02d}:00 "
|
||
f"({weekday_names[top['peak_weekday']]}), {top['dates_active']} active days."
|
||
),
|
||
}
|
||
)
|
||
if active_count:
|
||
insights.append(
|
||
{
|
||
"zh": f"当前仍有 {active_count} 路进行中。",
|
||
"en": f"{active_count} session(s) still active.",
|
||
}
|
||
)
|
||
|
||
return {
|
||
"overview": {
|
||
"sessions": len(sessions),
|
||
"unique_anchors": len(by_anchor),
|
||
"active_sessions": active_count,
|
||
"total_duration_seconds": total_duration,
|
||
"total_hours": total_duration / 3600.0,
|
||
"avg_duration_seconds": (total_duration / len(sessions)) if sessions else 0.0,
|
||
"median_duration_seconds": median_duration,
|
||
"date_from": dates_out[0]["date"] if dates_out else date_from,
|
||
"date_to": dates_out[-1]["date"] if dates_out else date_to,
|
||
"days_span": len(dates_out),
|
||
},
|
||
"by_anchor": anchors_out,
|
||
"top_anchors": top_anchors_list,
|
||
"by_hour": {
|
||
"starts": by_hour_starts,
|
||
"minutes": [round(x, 2) for x in by_hour_minutes],
|
||
"labels": [f"{h:02d}:00" for h in range(24)],
|
||
},
|
||
"by_weekday": {
|
||
"starts": by_weekday_starts,
|
||
"minutes": [round(x, 2) for x in by_weekday_minutes],
|
||
"labels": weekday_names,
|
||
"labels_zh": weekday_names_zh,
|
||
},
|
||
"heatmap": {
|
||
"starts": heatmap_starts,
|
||
"minutes": [[round(v, 2) for v in row] for row in heatmap_minutes],
|
||
"weekday_labels": weekday_names,
|
||
"weekday_labels_zh": weekday_names_zh,
|
||
"hour_labels": [f"{h:02d}" for h in range(24)],
|
||
},
|
||
"by_date": dates_out,
|
||
"duration_buckets": duration_buckets,
|
||
"insights": insights,
|
||
}
|
||
|
||
|
||
def get_relay_session(session_id: int | str, *, db_path: Path | None = None) -> dict[str, Any]:
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
row = conn.execute(
|
||
f"SELECT * FROM {_RELAY_SESSIONS_TABLE} WHERE id = ? OR session_uuid = ?",
|
||
(session_id, str(session_id)),
|
||
).fetchone()
|
||
return _row_to_session(row) if row else {}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def clear_imported_relay_sessions(process: str, *, db_path: Path | None = None) -> int:
|
||
proc = _normalize_process(process)
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
cur = conn.execute(
|
||
f"DELETE FROM {_RELAY_SESSIONS_TABLE} WHERE process = ? AND end_reason = 'imported_from_log'",
|
||
(proc,),
|
||
)
|
||
conn.commit()
|
||
return int(cur.rowcount or 0)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _finalize_import_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||
started_at = float(payload.get("started_at") or 0)
|
||
duration = int(payload.get("duration_seconds") or 0)
|
||
ended_at = payload.get("ended_at")
|
||
if ended_at is None and duration > 0 and started_at > 0:
|
||
ended_at = started_at + duration
|
||
payload["ended_at"] = ended_at
|
||
payload["duration_seconds"] = duration
|
||
return payload
|
||
|
||
|
||
def _new_import_payload(
|
||
*,
|
||
process: str,
|
||
anchor_name: str,
|
||
stream_title: str = "",
|
||
started_at: float,
|
||
push_date: str = "",
|
||
source_url: str = "",
|
||
source_room_id: str = "",
|
||
duration_seconds: int = 0,
|
||
youtube_key_suffix: str = "",
|
||
) -> dict[str, Any]:
|
||
anchor = (anchor_name or "").strip()
|
||
title = (stream_title or "").strip()
|
||
if not push_date:
|
||
_, push_date = _parse_stream_title(title)
|
||
if not push_date and started_at:
|
||
push_date = _push_date_from_ts(started_at)
|
||
return {
|
||
"process": process,
|
||
"anchor_name": anchor,
|
||
"stream_title": title,
|
||
"started_at": started_at,
|
||
"push_date": push_date,
|
||
"source_url": source_url,
|
||
"source_room_id": source_room_id,
|
||
"duration_seconds": duration_seconds,
|
||
"youtube_key_suffix": youtube_key_suffix,
|
||
"ended_at": None,
|
||
}
|
||
|
||
|
||
def _load_process_config_texts(process: str, root: Path) -> tuple[str, str, str]:
|
||
from src.youtube_config_paths import resolve_youtube_style_config_paths
|
||
|
||
youtube_ini, url_config = resolve_youtube_style_config_paths(root, process)
|
||
youtube_ini_text = ""
|
||
url_lines = ""
|
||
youtube_key_suffix = ""
|
||
youtube_path = Path(youtube_ini)
|
||
if youtube_path.is_file():
|
||
youtube_ini_text = youtube_path.read_text(encoding="utf-8-sig", errors="replace")
|
||
youtube_key_suffix = extract_youtube_key_suffix(youtube_ini_text)
|
||
url_path = Path(url_config)
|
||
if url_path.is_file():
|
||
url_lines = url_path.read_text(encoding="utf-8-sig", errors="replace")
|
||
return url_lines, youtube_ini_text, youtube_key_suffix
|
||
|
||
|
||
def import_relay_sessions_from_log(
|
||
log_path: str | Path,
|
||
*,
|
||
process: str = "youtube",
|
||
url_lines: str = "",
|
||
youtube_key_suffix: str = "",
|
||
replace_imported: bool = False,
|
||
db_path: Path | None = None,
|
||
) -> dict[str, Any]:
|
||
path = Path(log_path)
|
||
if not path.is_file():
|
||
return {"imported": 0, "closed": 0, "error": "log file not found"}
|
||
text = path.read_text(encoding="utf-8", errors="replace")
|
||
proc = _normalize_process(process)
|
||
if replace_imported:
|
||
removed = clear_imported_relay_sessions(proc, db_path=db_path)
|
||
else:
|
||
removed = 0
|
||
url_index = _build_anchor_url_index(url_lines)
|
||
log_url_index: dict[str, tuple[str, str]] = {}
|
||
for raw_line in text.splitlines():
|
||
fail_match = _FAIL_ADDR_RE.search(raw_line)
|
||
if fail_match:
|
||
url = _clean_douyin_url(fail_match.group(1))
|
||
anchor = fail_match.group(2).strip()
|
||
if url and anchor:
|
||
log_url_index[anchor] = (url, extract_source_room_id(url))
|
||
incoming = _INCOMING_URL_RE.search(raw_line)
|
||
if incoming:
|
||
url = _clean_douyin_url(incoming.group(1))
|
||
if url:
|
||
log_url_index.setdefault("__last_incoming__", (url, extract_source_room_id(url)))
|
||
imported = 0
|
||
closed = 0
|
||
active: dict[str, Any] | None = None
|
||
sessions: list[dict[str, Any]] = []
|
||
conn = _connect_relay(db_path)
|
||
try:
|
||
for raw_line in text.splitlines():
|
||
line = raw_line.strip()
|
||
if not line:
|
||
continue
|
||
log_ts = _parse_log_line_ts(line)
|
||
event_ts = _parse_local_wall_time(line, log_ts) or log_ts
|
||
|
||
incoming = _INCOMING_URL_RE.search(line)
|
||
if incoming:
|
||
url = _clean_douyin_url(incoming.group(1))
|
||
room_id = extract_source_room_id(url)
|
||
log_url_index["__last_incoming__"] = (url, room_id)
|
||
label = _ANCHOR_LABEL_RE.search(line)
|
||
if label:
|
||
log_url_index[label.group(1).strip()] = (url, room_id)
|
||
elif active and not active.get("source_url"):
|
||
active["source_url"] = url
|
||
active["source_room_id"] = room_id
|
||
continue
|
||
|
||
fail_match = _FAIL_ADDR_RE.search(line)
|
||
if fail_match:
|
||
url = _clean_douyin_url(fail_match.group(1))
|
||
anchor = fail_match.group(2).strip()
|
||
if url and anchor:
|
||
log_url_index[anchor] = (url, extract_source_room_id(url))
|
||
continue
|
||
|
||
push_match = _PUSH_START_RE.search(line)
|
||
if push_match:
|
||
stream_title = push_match.group(1).strip()
|
||
anchor, push_date = _parse_stream_title(stream_title)
|
||
started_at = _timestamp_from_stream_title(stream_title) or event_ts or time.time()
|
||
if active:
|
||
sessions.append(_finalize_import_payload(active))
|
||
closed += 1
|
||
source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index)
|
||
active = _new_import_payload(
|
||
process=proc,
|
||
anchor_name=anchor,
|
||
stream_title=stream_title,
|
||
started_at=started_at,
|
||
push_date=push_date,
|
||
source_url=source_url,
|
||
source_room_id=source_room_id,
|
||
youtube_key_suffix=youtube_key_suffix,
|
||
)
|
||
continue
|
||
|
||
rec_match = _RECORDING_LINE_RE.search(line)
|
||
if rec_match:
|
||
anchor = rec_match.group(1).strip(" :?")
|
||
duration = _parse_duration_token(rec_match.group(2).strip())
|
||
if active and str(active.get("anchor_name") or "") == anchor:
|
||
active["duration_seconds"] = max(int(active.get("duration_seconds") or 0), duration)
|
||
if not active.get("source_url"):
|
||
source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index)
|
||
active["source_url"] = source_url
|
||
active["source_room_id"] = source_room_id
|
||
elif active and str(active.get("anchor_name") or "") != anchor:
|
||
sessions.append(_finalize_import_payload(active))
|
||
closed += 1
|
||
started_at = (event_ts or time.time()) - duration if duration else (event_ts or time.time())
|
||
source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index)
|
||
active = _new_import_payload(
|
||
process=proc,
|
||
anchor_name=anchor,
|
||
started_at=started_at,
|
||
source_url=source_url,
|
||
source_room_id=source_room_id,
|
||
duration_seconds=duration,
|
||
youtube_key_suffix=youtube_key_suffix,
|
||
)
|
||
else:
|
||
started_at = (event_ts or time.time()) - duration if duration else (event_ts or time.time())
|
||
source_url, source_room_id = _resolve_anchor_url(anchor, url_index, url_lines, log_url_index)
|
||
active = _new_import_payload(
|
||
process=proc,
|
||
anchor_name=anchor,
|
||
started_at=started_at,
|
||
source_url=source_url,
|
||
source_room_id=source_room_id,
|
||
duration_seconds=duration,
|
||
youtube_key_suffix=youtube_key_suffix,
|
||
)
|
||
continue
|
||
|
||
if "推流已彻底停止" in line and active:
|
||
if event_ts and int(active.get("duration_seconds") or 0) > 0:
|
||
active["ended_at"] = float(active["started_at"]) + int(active["duration_seconds"])
|
||
elif event_ts:
|
||
active["ended_at"] = event_ts
|
||
sessions.append(_finalize_import_payload(active))
|
||
active = None
|
||
closed += 1
|
||
|
||
if active:
|
||
sessions.append(_finalize_import_payload(active))
|
||
|
||
for payload in sessions:
|
||
if not payload.get("anchor_name"):
|
||
continue
|
||
if not payload.get("source_url"):
|
||
source_url, source_room_id = _resolve_anchor_url(
|
||
str(payload.get("anchor_name") or ""),
|
||
url_index,
|
||
url_lines,
|
||
log_url_index,
|
||
)
|
||
payload["source_url"] = source_url
|
||
payload["source_room_id"] = source_room_id or payload.get("source_room_id") or ""
|
||
_persist_import_row(
|
||
conn,
|
||
payload,
|
||
started_at=float(payload["started_at"]),
|
||
ended_at=payload.get("ended_at"),
|
||
duration_seconds=int(payload.get("duration_seconds") or 0),
|
||
)
|
||
imported += 1
|
||
if youtube_key_suffix:
|
||
conn.execute(
|
||
f"""
|
||
UPDATE {_RELAY_SESSIONS_TABLE}
|
||
SET youtube_key_suffix = ?, updated_at = ?
|
||
WHERE process = ? AND COALESCE(youtube_key_suffix, '') = ''
|
||
""",
|
||
(youtube_key_suffix, time.time(), proc),
|
||
)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
return {
|
||
"imported": imported,
|
||
"closed": closed,
|
||
"removed": removed,
|
||
"process": proc,
|
||
"log_path": str(path),
|
||
}
|
||
|
||
|
||
def _persist_import_close(conn, payload: dict[str, Any], ended_at: float) -> None:
|
||
started_at = float(payload.get("started_at") or ended_at)
|
||
duration = payload.get("duration_seconds")
|
||
if duration is None or int(duration) <= 0:
|
||
duration = int(max(0, ended_at - started_at))
|
||
else:
|
||
ended_at = started_at + int(duration)
|
||
_persist_import_row(conn, payload, started_at=started_at, ended_at=ended_at, duration_seconds=int(duration))
|
||
|
||
|
||
def _persist_import_open(conn, payload: dict[str, Any]) -> None:
|
||
started_at = float(payload.get("started_at") or time.time())
|
||
duration = int(payload.get("duration_seconds") or 0)
|
||
_persist_import_row(conn, payload, started_at=started_at, ended_at=None, duration_seconds=duration)
|
||
|
||
|
||
def _persist_import_row(
|
||
conn,
|
||
payload: dict[str, Any],
|
||
*,
|
||
started_at: float,
|
||
ended_at: float | None,
|
||
duration_seconds: int,
|
||
) -> None:
|
||
anchor = str(payload.get("anchor_name") or "").strip()
|
||
stream_title = str(payload.get("stream_title") or "")
|
||
if not anchor and not stream_title:
|
||
return
|
||
if duration_seconds > 0 and started_at > 0:
|
||
computed_end = started_at + duration_seconds
|
||
if ended_at is None or ended_at < started_at:
|
||
ended_at = computed_end
|
||
dedupe_started = _timestamp_from_stream_title(stream_title) or started_at
|
||
existing = conn.execute(
|
||
f"""
|
||
SELECT id FROM {_RELAY_SESSIONS_TABLE}
|
||
WHERE process = ? AND anchor_name = ? AND stream_title = ? AND ABS(started_at - ?) < 180
|
||
LIMIT 1
|
||
""",
|
||
(payload.get("process") or "youtube", anchor, stream_title, dedupe_started),
|
||
).fetchone()
|
||
if not existing and stream_title:
|
||
existing = conn.execute(
|
||
f"""
|
||
SELECT id FROM {_RELAY_SESSIONS_TABLE}
|
||
WHERE process = ? AND anchor_name = ? AND stream_title = ?
|
||
LIMIT 1
|
||
""",
|
||
(payload.get("process") or "youtube", anchor, stream_title),
|
||
).fetchone()
|
||
if existing:
|
||
return
|
||
now = time.time()
|
||
source_url = _clean_douyin_url(str(payload.get("source_url") or ""))
|
||
source_room_id = str(payload.get("source_room_id") or extract_source_room_id(source_url, stream_title, anchor))
|
||
conn.execute(
|
||
f"""
|
||
INSERT INTO {_RELAY_SESSIONS_TABLE}(
|
||
session_uuid, process, channel_name, anchor_name, source_url, source_room_id,
|
||
stream_title, youtube_key_suffix, started_at, ended_at, duration_seconds, push_date,
|
||
cover_path, status, end_reason, metadata_json, created_at, updated_at
|
||
) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?)
|
||
""",
|
||
(
|
||
str(uuid.uuid4()),
|
||
payload.get("process") or "youtube",
|
||
anchor,
|
||
source_url,
|
||
source_room_id,
|
||
stream_title,
|
||
str(payload.get("youtube_key_suffix") or ""),
|
||
started_at,
|
||
ended_at,
|
||
duration_seconds,
|
||
str(payload.get("push_date") or _push_date_from_ts(started_at)),
|
||
"ended" if ended_at else "active",
|
||
"imported_from_log",
|
||
_json_dumps({"imported": True, "stream_title": stream_title}),
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
|
||
|
||
def import_relay_sessions_for_process(
|
||
process: str,
|
||
*,
|
||
out_path: str | Path | None = None,
|
||
db_path: Path | None = None,
|
||
replace_imported: bool = False,
|
||
url_lines: str = "",
|
||
) -> dict[str, Any]:
|
||
proc = _normalize_process(process)
|
||
root = Path(os.environ.get("LIVE_PROJECT_ROOT") or Path(__file__).resolve().parent.parent)
|
||
loaded_url_lines, _youtube_ini_text, youtube_key_suffix = _load_process_config_texts(proc, root)
|
||
if not url_lines:
|
||
url_lines = loaded_url_lines
|
||
elif not youtube_key_suffix:
|
||
youtube_key_suffix = extract_youtube_key_suffix(_youtube_ini_text)
|
||
if out_path:
|
||
return import_relay_sessions_from_log(
|
||
out_path,
|
||
process=proc,
|
||
url_lines=url_lines,
|
||
youtube_key_suffix=youtube_key_suffix,
|
||
replace_imported=replace_imported,
|
||
db_path=db_path,
|
||
)
|
||
candidates = [
|
||
Path("/root/.pm2/logs") / f"{proc}-out.log",
|
||
Path(os.environ.get("PM2_HOME") or "") / "logs" / f"{proc}-out.log",
|
||
root / ".pm2" / "logs" / f"{proc}-out.log",
|
||
]
|
||
for candidate in candidates:
|
||
if candidate.is_file() and candidate.stat().st_size > 0:
|
||
return import_relay_sessions_from_log(
|
||
candidate,
|
||
process=proc,
|
||
url_lines=url_lines,
|
||
youtube_key_suffix=youtube_key_suffix,
|
||
replace_imported=replace_imported,
|
||
db_path=db_path,
|
||
)
|
||
return {"imported": 0, "closed": 0, "error": "pm2 log not found", "process": proc}
|