"use client"; import { AlertTriangle, ExternalLink, Pause, Play, RefreshCw } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { formatPollBadge } from "@/lib/adaptivePoll"; import { formatBitrateLabel, formatFfmpegMetricValue, formatFfmpegStatsBrief, mergeFfmpegMetrics, } from "@/lib/ffmpegMetrics"; import { douyinSourceDisplayFrom, extractDouyinCurrentRoomFromLog, extractDouyinLiveUrls, extractDouyinRoomHints, } from "@/lib/youtubeConfigUtils"; type TFn = (zh: string, en: string) => string; type StatusPayload = { process_status?: string; recent_log?: string; recent_error?: string; business_status?: string; business_note?: string; ffmpeg_pids?: number[]; log_age_seconds?: number | null; is_pushing?: boolean; ffmpeg_speed?: number | null; ffmpeg_frame?: number | null; ffmpeg_time_seconds?: number | null; ffmpeg_speed_low?: boolean; ffmpeg_progress_stalled?: boolean; source_title?: string; source_room_id?: string; source_url?: string; source_display?: string; source_ambiguous?: boolean; source_current?: boolean; }; function fmtDuration(sec: number): string { if (sec < 60) return `${sec}s`; const m = Math.floor(sec / 60); const s = sec % 60; if (m < 60) return `${m}m ${s}s`; const h = Math.floor(m / 60); const mm = m % 60; return `${h}h ${mm}m`; } function statusLine(t: TFn, raw: string | undefined): string { const s = (raw || "unknown").toLowerCase(); if (s === "online" || s === "running") return t("运行中(PM2/进程在线)", "Running (process online)"); if (s === "stopped" || s === "stopping") return t("已停止", "Stopped"); if (s === "configured") return t("已配置(未启动)", "Configured (not running)"); if (s === "not_found" || s === "errored") return t("未运行或未找到", "Not running / not found"); if (s === "invalid") return t("无效进程名", "Invalid process"); return raw || "—"; } type MonitorRowHint = { ffmpeg_active?: boolean; ffmpeg_speed?: number | null; ffmpeg_frame?: number | null; ffmpeg_speed_low?: boolean; ffmpeg_progress_stalled?: boolean; is_pushing?: boolean; }; type Props = { t: TFn; currentProc: string; fetchJson: (path: string, init?: RequestInit) => Promise; /** 用于源站房间线索(与 Electron 一致) */ urlListText: string; /** YouTube 密钥尾码;非 YouTube 进程可传空并关 showKeyRow */ keySuffixUi: string; showKeyRow?: boolean; pollMs?: number; refreshToken?: number; /** process_monitor 行:补全 light status 缺失的 FFmpeg 指标 */ monitorRow?: MonitorRowHint; /** Pro 线路名:推流中时固定显示频道名 */ preferredTitle?: string; }; function businessLine(t: TFn, raw: string | undefined, note: string | undefined): string { const s = (raw || "").toLowerCase(); if (s === "ready" || s === "configured") return t("已配置,等待启动", "Configured and ready to start"); if (s === "inactive") return t("未运行", "Inactive"); if (s === "streaming") return t("正在推流到 YouTube", "Pushing to YouTube"); if (s === "relay_slow") return t("推流速度偏低", "Relay running slowly"); if (s === "relay_starting") return t("转推 Worker 启动中,等待 FFmpeg 进度", "Relay worker starting; waiting for FFmpeg progress"); if (s === "waiting_source") return t("等待上游直播源开播", "Waiting for the upstream live source"); if (s === "source_live") return t("源站已开播,转推 Worker 未启动", "Source live detected, but no active FFmpeg relay worker"); if (s === "monitoring") return t("进程在线,监控源站中", "Process online and monitoring the source"); if (s === "misconfigured") return t("YouTube 密钥缺失或无效", "YouTube key missing or invalid"); if (s === "youtube_key_rejected") return t( "YouTube 推流失败:串流密钥无效、过期或不属于当前直播间", "YouTube rejected the stream key", ); if (s === "source_stalled") return t("上游源站卡住", "Upstream source stalled"); if (s === "stale") return t("进程在线但日志心跳过期", "Process online but the log heartbeat is stale"); if (s === "error") return t("检测到近期进程错误", "Recent process error detected"); if (note?.trim()) return note.trim(); return t("暂无业务状态", "No business-state hint yet"); } function businessShortLine(t: TFn, raw: string | undefined, pushing = false): string { if (pushing) return t("推流中", "Pushing"); const s = (raw || "").toLowerCase(); if (s === "ready" || s === "configured") return t("已配置", "Ready"); if (s === "inactive") return t("未运行", "Inactive"); if (s === "streaming") return t("推流中", "Pushing"); if (s === "relay_slow") return t("低速", "Slow"); if (s === "relay_starting") return t("启动中", "Starting"); if (s === "waiting_source") return t("等源", "Wait source"); if (s === "source_live") return t("源开播", "Source live"); if (s === "monitoring") return t("监控中", "Monitoring"); if (s === "misconfigured") return t("密钥异常", "Key invalid"); if (s === "youtube_key_rejected") return t("密钥被拒", "Key rejected"); if (s === "source_stalled") return t("源卡住", "Stalled"); if (s === "stale") return t("心跳过期", "Stale"); if (s === "error") return t("异常", "Error"); return t("未知", "Unknown"); } function businessBadgeClass(raw: string | undefined): string { const s = (raw || "").trim().toLowerCase(); if (s === "ready" || s === "configured") return "bg-sky-500/15 text-sky-100 ring-sky-500/25"; if (s === "streaming" || s === "relay_slow") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30"; if (s === "waiting_source" || s === "monitoring" || s === "source_live" || s === "relay_starting") { return "bg-amber-500/15 text-amber-100 ring-amber-500/25"; } if (s === "misconfigured" || s === "youtube_key_rejected" || s === "error" || s === "stale" || s === "source_stalled") { return "bg-rose-500/15 text-rose-100 ring-rose-500/30"; } return "bg-zinc-600/20 text-zinc-300 ring-zinc-500/25"; } function processBadgeClass(raw: string | undefined): string { const s = (raw || "").trim().toLowerCase(); if (s === "online" || s === "running") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30"; if (s === "stopped" || s === "stopping") return "bg-zinc-600/20 text-zinc-300 ring-zinc-500/25"; if (s === "not_found" || s === "errored" || s === "error") return "bg-rose-500/15 text-rose-100 ring-rose-500/30"; return "bg-zinc-600/20 text-zinc-300 ring-zinc-500/25"; } export function LiveProcessLiveLogCard({ t, currentProc, fetchJson, urlListText, keySuffixUi, showKeyRow = true, pollMs = 1000, refreshToken = 0, monitorRow, preferredTitle, }: Props) { const [processStatus, setProcessStatus] = useState(""); const [recentLog, setRecentLog] = useState(""); const [recentError, setRecentError] = useState(""); const [businessStatus, setBusinessStatus] = useState(""); const [businessNote, setBusinessNote] = useState(""); const [ffmpegPids, setFfmpegPids] = useState([]); const [logAgeSeconds, setLogAgeSeconds] = useState(null); const [sourceTitle, setSourceTitle] = useState(""); const [sourceRoomId, setSourceRoomId] = useState(""); const [sourceUrl, setSourceUrl] = useState(""); const [sourceDisplay, setSourceDisplay] = useState(""); const [sourceAmbiguous, setSourceAmbiguous] = useState(false); const [sourceCurrent, setSourceCurrent] = useState(false); const [isPushing, setIsPushing] = useState(false); const [statusFfmpegSpeed, setStatusFfmpegSpeed] = useState(null); const [statusFfmpegFrame, setStatusFfmpegFrame] = useState(null); const [statusFfmpegTime, setStatusFfmpegTime] = useState(null); const [statusSpeedLow, setStatusSpeedLow] = useState(false); const [statusProgressStalled, setStatusProgressStalled] = useState(false); const [paused, setPaused] = useState(false); const [liveSince, setLiveSince] = useState(null); const [nowTick, setNowTick] = useState(0); const [pageVisible, setPageVisible] = useState(true); const outRef = useRef(null); const errRef = useRef(null); const prevPushingRef = useRef(false); const pullInFlightRef = useRef(false); const pullQueuedRef = useRef(false); const currentProcRef = useRef(currentProc); const requestSeqRef = useRef(0); const douyinHints = extractDouyinRoomHints(urlListText); const roomFromLog = extractDouyinCurrentRoomFromLog(recentLog); const fallbackUrls = extractDouyinLiveUrls(urlListText); const fallbackUrl = fallbackUrls[0] ?? ""; const pushingNow = isPushing || ["streaming", "relay_slow"].includes(businessStatus.trim().toLowerCase()); const liveMetrics = mergeFfmpegMetrics( { ffmpeg_speed: statusFfmpegSpeed ?? monitorRow?.ffmpeg_speed, ffmpeg_frame: statusFfmpegFrame ?? monitorRow?.ffmpeg_frame, ffmpeg_active: monitorRow?.ffmpeg_active, is_pushing: pushingNow, ffmpeg_speed_low: statusSpeedLow || monitorRow?.ffmpeg_speed_low, ffmpeg_progress_stalled: statusProgressStalled || monitorRow?.ffmpeg_progress_stalled, }, undefined, `${recentLog}\n${recentError}`, ); const encodedDurationLabel = typeof statusFfmpegTime === "number" && statusFfmpegTime > 0 ? fmtDuration(Math.max(0, Math.floor(statusFfmpegTime))) : null; const liveStatsText = formatFfmpegStatsBrief(liveMetrics, { live: pushingNow, }); const ffmpegWorkerLabel = ffmpegPids.length ? ffmpegPids.join(", ") : pushingNow ? t("转推活跃(PID 未采集)", "Relay active (PID n/a)") : t("无", "none"); const suppressAmbiguousBackend = sourceAmbiguous && pushingNow && !sourceCurrent; const backendRoomId = suppressAmbiguousBackend ? "" : sourceRoomId; const backendUrl = suppressAmbiguousBackend ? "" : sourceUrl; const suppressAmbiguousFallback = fallbackUrls.length > 1 && pushingNow && !backendUrl && !backendRoomId && !roomFromLog && (sourceAmbiguous || !!sourceDisplay || !!sourceTitle); const primaryRoomId = backendRoomId || roomFromLog || (!suppressAmbiguousFallback ? fallbackUrl.match(/live\.douyin\.com\/([a-zA-Z0-9_-]+)/i)?.[1] ?? null : null); const primaryUrl = backendUrl || (backendRoomId ? `https://live.douyin.com/${backendRoomId}` : "") || (roomFromLog ? `https://live.douyin.com/${roomFromLog}` : "") || (!suppressAmbiguousFallback ? fallbackUrl || null : null); const localSourceLabel = suppressAmbiguousBackend ? douyinSourceDisplayFrom("", recentLog) : douyinSourceDisplayFrom(urlListText, recentLog); const primarySourceLabel = (suppressAmbiguousBackend ? "" : sourceDisplay) || (suppressAmbiguousBackend ? "" : sourceTitle) || localSourceLabel || preferredTitle?.trim() || (primaryRoomId ? `抖音直播间 ${primaryRoomId}` : ""); const douyinSourceSubtitle = preferredTitle?.trim() && primarySourceLabel && preferredTitle.trim() !== primarySourceLabel ? preferredTitle.trim() : ""; const youtubeKeyRejected = businessStatus.trim().toLowerCase() === "youtube_key_rejected"; const pull = useCallback(async () => { const targetProc = currentProcRef.current.trim(); if (!targetProc) return; if (pullInFlightRef.current) { pullQueuedRef.current = true; return; } pullInFlightRef.current = true; const requestId = ++requestSeqRef.current; try { const data = await fetchJson( `/status?process=${encodeURIComponent(targetProc)}&light=1`, ); if (requestId !== requestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; const ps = data.process_status || "unknown"; setProcessStatus(ps); setRecentLog(data.recent_log || ""); setRecentError(data.recent_error || ""); setBusinessStatus(data.business_status || ""); setBusinessNote(data.business_note || ""); setFfmpegPids(Array.isArray(data.ffmpeg_pids) ? data.ffmpeg_pids : []); setLogAgeSeconds(typeof data.log_age_seconds === "number" ? data.log_age_seconds : null); setSourceTitle(data.source_title || ""); setSourceRoomId(data.source_room_id || ""); setSourceUrl(data.source_url || ""); setSourceDisplay(data.source_display || ""); setSourceAmbiguous(!!data.source_ambiguous); setSourceCurrent(!!data.source_current); setIsPushing(!!data.is_pushing); setStatusFfmpegSpeed(typeof data.ffmpeg_speed === "number" ? data.ffmpeg_speed : null); setStatusFfmpegFrame(typeof data.ffmpeg_frame === "number" ? data.ffmpeg_frame : null); setStatusFfmpegTime(typeof data.ffmpeg_time_seconds === "number" ? data.ffmpeg_time_seconds : null); setStatusSpeedLow(!!data.ffmpeg_speed_low); setStatusProgressStalled(!!data.ffmpeg_progress_stalled); const pushing = !!( data.is_pushing || ["streaming", "relay_slow"].includes((data.business_status || "").trim().toLowerCase()) ); if (pushing && !prevPushingRef.current) { setLiveSince(Date.now()); } if (!pushing) { setLiveSince(null); } prevPushingRef.current = pushing; } catch { if (requestId !== requestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; setProcessStatus("error"); setBusinessStatus("error"); setBusinessNote(""); setFfmpegPids([]); setLogAgeSeconds(null); setSourceTitle(""); setSourceRoomId(""); setSourceUrl(""); setSourceDisplay(""); setSourceAmbiguous(false); setSourceCurrent(false); setIsPushing(false); setStatusFfmpegSpeed(null); setStatusFfmpegFrame(null); setStatusFfmpegTime(null); setStatusSpeedLow(false); setStatusProgressStalled(false); prevPushingRef.current = false; } finally { pullInFlightRef.current = false; if (pullQueuedRef.current) { pullQueuedRef.current = false; window.setTimeout(() => void pull(), 0); } } }, [fetchJson]); useEffect(() => { currentProcRef.current = currentProc; requestSeqRef.current += 1; pullQueuedRef.current = false; if (!currentProc) { setProcessStatus(""); setRecentLog(""); setRecentError(""); setBusinessStatus(""); setBusinessNote(""); setFfmpegPids([]); setLogAgeSeconds(null); setSourceTitle(""); setSourceRoomId(""); setSourceUrl(""); setSourceDisplay(""); setSourceAmbiguous(false); setSourceCurrent(false); setIsPushing(false); setStatusFfmpegSpeed(null); setStatusFfmpegFrame(null); setStatusFfmpegTime(null); setStatusSpeedLow(false); setStatusProgressStalled(false); setLiveSince(null); prevPushingRef.current = false; return; } setProcessStatus(""); setRecentLog(""); setRecentError(""); setBusinessStatus(""); setBusinessNote(""); setFfmpegPids([]); setLogAgeSeconds(null); setSourceTitle(""); setSourceRoomId(""); setSourceUrl(""); setSourceDisplay(""); setSourceAmbiguous(false); setSourceCurrent(false); setIsPushing(false); setStatusFfmpegSpeed(null); setStatusFfmpegFrame(null); setStatusFfmpegTime(null); setStatusSpeedLow(false); setStatusProgressStalled(false); setLiveSince(null); prevPushingRef.current = false; void pull(); }, [currentProc, pull]); useEffect(() => { const onVis = () => setPageVisible(document.visibilityState === "visible"); onVis(); document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, []); useEffect(() => { if (!currentProc) return; void pull(); }, [currentProc, pull, refreshToken]); useEffect(() => { if (paused || !currentProc || pollMs <= 0) return; const id = window.setInterval(() => void pull(), pollMs); return () => clearInterval(id); }, [paused, currentProc, pull, pollMs]); useEffect(() => { const onVis = () => { if (document.visibilityState === "visible") void pull(); }; document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, [pull]); useEffect(() => { if (!liveSince) return; const id = window.setInterval(() => setNowTick((n) => n + 1), 1000); return () => clearInterval(id); }, [liveSince]); useEffect(() => { if (paused || !pageVisible) return; const el = outRef.current; if (el) el.scrollTop = el.scrollHeight; }, [recentLog, paused, pageVisible]); useEffect(() => { if (paused || !pageVisible) return; const el = errRef.current; if (el) el.scrollTop = el.scrollHeight; }, [recentError, paused, pageVisible]); const durationLabel = liveSince == null ? t("—(未检测到在线)", "— (not online)") : fmtDuration(Math.max(0, Math.floor((Date.now() - liveSince) / 1000))); const refreshBadgeLabel = paused ? t("已暂停刷新", "Paused") : formatPollBadge(pollMs, t); const refreshBadgeClass = paused ? "bg-amber-500/20 text-amber-100 ring-amber-500/35" : pollMs >= 30_000 ? "bg-sky-500/15 text-sky-100 ring-sky-500/25" : pollMs >= 4000 ? "bg-zinc-500/15 text-zinc-200/90 ring-zinc-500/25" : "bg-emerald-500/15 text-emerald-200/90 ring-emerald-500/25"; return (
{nowTick}

{t("当前直播日志", "Live process log")}

{pushingNow ? ( {t("推流中", "Pushing")} ) : null} {currentProc || "—"} {refreshBadgeLabel}

{t("进程状态", "Process")}

{statusLine(t, processStatus)}

{t("业务状态", "Business")}

{businessShortLine(t, businessStatus, pushingNow)}

{pushingNow ? t("推流时长(估算)", "Relay duration (est.)") : t("进程在线时长(估算)", "Process uptime (est.)")}

{durationLabel}

{encodedDurationLabel ? (

{t("已编码", "Encoded")} {encodedDurationLabel}

) : null}

{t("FFmpeg workers", "FFmpeg workers")}

{ffmpegWorkerLabel}

{logAgeSeconds != null ? (

{t("日志心跳", "Log heartbeat")} {fmtDuration(Math.max(0, Math.floor(logAgeSeconds)))}

) : null}

{t("实时转推指标", "Live relay metrics")}

{liveStatsText || t("等待 FFmpeg 上报 fps / speed / frame", "Waiting for FFmpeg fps / speed / frame")}

fps {formatFfmpegMetricValue(liveMetrics.fps)}

speed {formatFfmpegMetricValue(liveMetrics.speed, "x")}

frame {formatFfmpegMetricValue(liveMetrics.frame, "", 0)}

{t("码率", "Bitrate")} {formatBitrateLabel(liveMetrics.bitrate) ?? "—"}

{primarySourceLabel ? (

{pushingNow && preferredTitle?.trim() ? t("当前转播线路", "Current relay lane") : t("当前转播源", "Current relay source")}

{primarySourceLabel}

{douyinSourceSubtitle ? (

{t("抖音源", "Douyin")}: {douyinSourceSubtitle}

) : null}
) : null} {showKeyRow ? (
{t("YouTube key 尾码(参考)", "YT key suffix")} {keySuffixUi || "—"}
) : null} {youtubeKeyRejected ? (

{t( "YouTube 已拒绝本次 RTMPS 推流。请从 YouTube Studio 当前直播间复制完整串流密钥,保存到当前线路后重新开始;如果密钥确认无误,再检查到 YouTube RTMPS 的网络/代理。", "YouTube rejected this RTMPS publish. Copy the full stream key for the current live event from YouTube Studio, save it to this lane, then start again; if the key is correct, check network/proxy access to YouTube RTMPS.", )}

) : null} {primaryUrl ? (
{roomFromLog ? t("当前直播源站(日志)", "Current source (from log)") : pushingNow ? t("配置中的源站地址", "Configured source URL") : t("源站快捷入口", "Source quick link")} {primarySourceLabel || t("打开抖音直播页", "Open Douyin live")}
{primaryRoomId && primarySourceLabel && !primarySourceLabel.includes(primaryRoomId) ? (

room:{primaryRoomId}

) : null} {douyinHints.length > 1 && roomFromLog ? (

{t("配置中还有", "Also in config:")}{" "} {douyinHints .filter((id) => id !== primaryRoomId) .slice(0, 3) .map((id) => ( {id} ))} {douyinHints.length > 4 ? "…" : null}

) : null}
) : (

{t("(日志与地址列表中暂无抖音房间)", "(No Douyin room in log or URL list)")}

)}
{processStatus !== "not_found" && processStatus !== "invalid" ? (
{t("进程输出(stdout / 合并日志)", "Process output")}
              {recentLog.trim() || t("(暂无)", "(empty)")}
            
{t("异常信息(stderr)", "Stderr")}
              {recentError.trim() || t("(暂无)", "(empty)")}
            
) : (

{t("进程未在 PM2 / 本地注册表中运行,日志区域已隐藏。", "Process not running — log panes hidden.")}

)}
); }