# -*- coding: utf-8 -*-
"""Relay business/process status — adapted from sh2 process_runtime_status (cloud, no PM2)."""
from __future__ import annotations
import re
import time
from typing import Any
_FFMPEG_PROGRESS_RE = re.compile(
r"frame=\s*(?P\d+).*?"
r"(?:fps=\s*(?P[\d.]+)\s*)?"
r"(?:time=(?P\d+):(?P\d+):(?P\d+(?:\.\d+)?).*?)?"
r"bitrate=\s*(?P[\d.]+\s*kbits/s)?.*?"
r"speed=\s*(?P\d+(?:\.\d+)?)x",
re.IGNORECASE,
)
_ERROR_HINTS = (
"error",
"failed",
"403 forbidden",
"404 not found",
"unauthorized",
"forbidden",
"io error",
"error opening output",
)
def _norm_log(text: str) -> str:
return (text or "").replace("\r\n", "\n").replace("\r", "\n")
def _has_any(text: str, patterns: tuple[str, ...]) -> bool:
low = text.lower()
return any(p in low for p in patterns)
def _looks_like_youtube_key_rejected(tail: str) -> bool:
if not _has_any(tail, ("rtmps://a.rtmps.youtube.com/live2/", "rtmp://a.rtmp.youtube.com/live2/")):
return False
if not _has_any(tail, ("error opening output", "error opening output file")):
return False
return _has_any(tail, ("io error", "401", "403", "unauthorized", "forbidden", "input/output error"))
def _ffmpeg_progress_samples(tail: str) -> list[dict[str, float | int]]:
samples: list[dict[str, float | int]] = []
for match in _FFMPEG_PROGRESS_RE.finditer(tail or ""):
try:
frame = int(match.group("frame"))
speed = float(match.group("speed"))
media_time = 0.0
if match.group("h") is not None:
media_time = (
int(match.group("h")) * 3600
+ int(match.group("m")) * 60
+ float(match.group("s") or 0)
)
row: dict[str, float | int] = {"frame": frame, "time": media_time, "speed": speed}
if match.group("fps"):
row["fps"] = float(match.group("fps"))
br = match.group("bitrate") or ""
m = re.search(r"([\d.]+)", br)
if m:
row["bitrate"] = float(m.group(1))
samples.append(row)
except (TypeError, ValueError):
continue
return samples[-8:]
def _progress_stalled(samples: list[dict[str, float | int]]) -> bool:
if len(samples) < 3:
return False
tail = samples[-3:]
frames = {int(r["frame"]) for r in tail}
times = {round(float(r["time"]), 2) for r in tail}
return len(frames) == 1 and len(times) == 1
def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.90) -> bool:
if len(samples) < 4:
return False
tail = samples[-4:]
if not all(float(r["speed"]) < threshold for r in tail):
return False
return int(tail[-1]["frame"]) > int(tail[0]["frame"]) or float(tail[-1]["time"]) > float(tail[0]["time"])
def _speed_healthy(samples: list[dict[str, float | int]], st: dict[str, Any]) -> bool:
if samples:
try:
if float(samples[-1]["speed"]) >= 0.95:
return True
except (TypeError, ValueError, KeyError):
pass
try:
return float(st.get("speed") or 0) >= 0.95
except (TypeError, ValueError):
return False
def split_relay_logs(lines: list[str] | None) -> tuple[str, str]:
out: list[str] = []
err: list[str] = []
for line in lines or []:
low = line.lower()
if any(h in low for h in _ERROR_HINTS):
err.append(line)
else:
out.append(line)
return "\n".join(out), "\n".join(err)
def summarize_relay_group(
*,
group: dict[str, Any],
st: dict[str, Any],
session_running: bool,
pipeline_enabled: bool,
log_age_seconds: float | None = None,
lane_armed: bool = False,
time_slot_mode: bool = False,
) -> dict[str, Any]:
"""Build process_monitor-style row for one assign group."""
gid = str(group.get("id") or st.get("group_id") or "")
has_key = bool(group.get("has_stream_key") or str(group.get("stream_key") or "").strip())
enabled = bool(group.get("enabled", True))
featured = group.get("featured") or []
featured_urls = [str(x.get("url") or "").strip() for x in featured if str(x.get("url") or "").strip()]
douyin_count = sum(1 for u in featured_urls if "douyin" in u.lower())
recent_log_lines = st.get("recent_log") if isinstance(st.get("recent_log"), list) else []
if not recent_log_lines and isinstance(st.get("recent_log"), str):
recent_log_lines = [st["recent_log"]]
recent_log, recent_error = split_relay_logs(recent_log_lines)
# FFmpeg progress often uses \r — normalize before matching.
tail = _norm_log(f"{recent_log}\n{recent_error}")[-8000:].lower().replace("\r", "\n")
raw_status = str(st.get("status") or "idle").lower()
armed = bool(lane_armed or pipeline_enabled)
if session_running:
process_status = "online"
elif raw_status in {"waiting", "reconnecting", "starting"} and armed:
# sh2: monitor thread still online while「等待直播」
process_status = "online"
elif not enabled:
process_status = "stopped"
elif has_key and armed:
process_status = "configured" if raw_status in {"idle", "stopped"} else raw_status
elif has_key:
process_status = "configured"
else:
process_status = "stopped"
pids: list[int] = []
pid = int(st.get("ffmpeg_pid") or 0)
if pid > 0:
pids = [pid]
progress_samples = _ffmpeg_progress_samples(tail)
latest = progress_samples[-1] if progress_samples else {}
progress_stalled = _progress_stalled(progress_samples)
speed_low = _speed_low(progress_samples)
has_progress = ("frame=" in tail and "speed=" in tail) or bool(progress_samples)
# Poll may be 3–10s; keep heartbeat window generous so UI doesn't flap.
log_recent = log_age_seconds is None or log_age_seconds <= 60
has_worker = bool(pids) or session_running
healthy_speed = _speed_healthy(progress_samples, st)
business_status = "inactive"
business_note = "未运行"
if not has_key:
business_status = "misconfigured"
business_note = "缺少 YouTube 直播 KEY"
elif not enabled:
business_status = "inactive"
business_note = "频道已停用"
elif not featured_urls and not time_slot_mode:
business_status = "misconfigured"
business_note = "直播地址列表(精选)为空"
elif _looks_like_youtube_key_rejected(tail):
business_status = "youtube_key_rejected"
business_note = "YouTube 拒绝了 RTMPS 推流,请检查直播 KEY 或网络"
elif session_running and has_progress and log_recent and progress_stalled:
business_status = "source_stalled"
business_note = "FFmpeg 在运行但帧/时间进度停滞"
elif session_running and has_progress and log_recent and speed_low and not healthy_speed:
business_status = "relay_slow"
business_note = "推流速度低于实时"
elif session_running and (has_progress or healthy_speed) and (log_recent or healthy_speed):
business_status = "streaming"
business_note = "正在推流到 YouTube"
elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://", "starting ffmpeg", "quality=")):
business_status = "relay_starting"
business_note = "FFmpeg 已启动,等待进度上报"
elif session_running:
business_status = "relay_starting"
business_note = "推流进程运行中"
elif raw_status == "waiting" and armed:
# Exact sh2 wording path: offline → keep polling
business_status = "waiting_source"
business_note = str(st.get("error") or "等待直播...").strip() or "等待直播..."
elif raw_status == "starting" and armed:
business_status = "relay_starting"
business_note = str(st.get("error") or "正在启动推流(解析源 / Neko / FFmpeg)").strip()
elif raw_status == "error" and st.get("error") and not armed:
business_status = "error"
business_note = str(st.get("error") or "")[:240]
elif raw_status == "reconnecting" and armed:
business_status = "relay_starting"
business_note = "推流中断,正在重连"
elif armed and enabled and has_key and not session_running:
if log_age_seconds is not None and log_age_seconds > 180 and has_worker:
business_status = "stale"
business_note = "进程在线但日志心跳过期"
else:
business_status = "monitoring"
business_note = "监听中,等待开播后自动推流"
elif has_key and featured_urls and pipeline_enabled:
business_status = "ready"
business_note = "已配置,等待自动推流"
elif process_status == "configured":
business_status = "ready"
business_note = "已配置(未推流)"
is_pushing = business_status in {"streaming", "relay_slow"} or (
business_status == "source_stalled" and has_progress and has_worker
)
speed = latest.get("speed")
if speed is None and st.get("speed"):
try:
speed = float(st.get("speed"))
except (TypeError, ValueError):
speed = None
frame = latest.get("frame")
if frame is None and st.get("frame"):
try:
frame = int(st.get("frame"))
except (TypeError, ValueError):
frame = None
# Never leak live metrics when not actually pushing — UI must stay consistent.
if not is_pushing:
speed = None
frame = None
latest = {}
progress_stalled = False
speed_low = False
return {
"group_id": gid,
"label": group.get("name") or gid,
"process_status": process_status,
"business_status": business_status,
"business_note": business_note,
"is_pushing": is_pushing,
"ffmpeg_active": bool(is_pushing and has_worker),
"ffmpeg_pids": pids if is_pushing else [],
"ffmpeg_pid": (pids[0] if pids and is_pushing else 0),
"ffmpeg_speed": speed if is_pushing else None,
"ffmpeg_frame": frame if is_pushing else None,
"ffmpeg_fps": latest.get("fps") if is_pushing else None,
"ffmpeg_bitrate_kbps": latest.get("bitrate") if is_pushing else None,
"ffmpeg_time_seconds": latest.get("time") if is_pushing else None,
"ffmpeg_progress_stalled": progress_stalled if is_pushing else False,
"ffmpeg_speed_low": speed_low if is_pushing else False,
"log_age_seconds": log_age_seconds,
"recent_log": recent_log,
"recent_error": recent_error,
"source_title": st.get("anchor_name") or "",
"source_room_id": st.get("source_room_id") or st.get("room_id") or "",
"source_url": st.get("source_url") or "",
"source_display": st.get("anchor_name") or "",
"url_count": len(featured_urls),
"douyin_count": douyin_count,
"has_stream_key": has_key,
"stream_key_suffix": _key_suffix(group),
"push_seconds": float(st.get("push_seconds") or 0) if is_pushing else 0.0,
"started_at": float(st.get("started_at") or 0),
"updated_at": float(st.get("updated_at") or 0),
}
def _key_suffix(group: dict[str, Any]) -> str:
sk = str(group.get("stream_key") or "").strip()
if len(sk) >= 4:
return sk[-4:]
masked = str(group.get("stream_key_masked") or "")
if masked.startswith("***") and len(masked) > 3:
return masked[3:]
return ""
def log_age_seconds(st: dict[str, Any], now: float | None = None) -> float | None:
updated = float(st.get("updated_at") or 0)
if updated <= 0:
return None
return max(0.0, (now or time.time()) - updated)