"use client"; import { Activity, AlertTriangle, Ban, Clock, Database, ExternalLink, Eye, History, Loader2, MonitorPlay, Play, Plus, Radio, RefreshCw, ScrollText, Square, Trash2 } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buildYoutubeIniFromFields, douyinSourceDisplayFrom, extractDouyinLiveUrls, managedUrlConfigRelPathForPm2, managedYoutubeIniRelPathForPm2, parseYoutubeIniFields, parseYoutubeStreamKeySuffix, type YoutubeIniFields, } from "@/lib/youtubeConfigUtils"; import { extractNekoBrowserLinks, formatNekoPorts, resolveNekoBrowserLink, type NekoBrowserLink, type QuickLinkMap, } from "@/lib/nekoLinks"; import type { PortalNavTarget } from "@/components/live-product/LivePipelineStrip"; import { LivePipelineStrip } from "@/components/live-product/LivePipelineStrip"; import { LiveProcessLiveLogCard } from "@/components/live-product/LiveProcessLiveLogCard"; import { cleanYoutubeProChannelNames, cleanYoutubeProLaneName, defaultPm2NameForChannel, fetchYoutubeProChannelsRemote, loadYoutubeProChannels, newChannelId, pushYoutubeProChannelsRemote, resolveYoutubeProChannelPm2, saveYoutubeProChannels, sanitizeYoutubePm2Name, type YoutubeProChannel, type YoutubeProChannelsSyncOptions, } from "@/lib/youtubeProChannels"; import { classifyProcessMonitorActivity, classifyRowActivity, liveEventsPollMs, qualityGuardPollMs, statusPollMs, urlConfigPollMs, } from "@/lib/adaptivePoll"; import { normalizeBrowserReachableHttpUrl } from "@/lib/panelUrls"; import { formatBitrateLabel, formatFfmpegMetricValue, formatFfmpegStatsBrief, mergeFfmpegMetrics, type FfmpegMetrics, } from "@/lib/ffmpegMetrics"; type ProcessEntry = { pm2: string; script: string; label: string }; type TFn = (zh: string, en: string) => string; type NekoAction = "start" | "stop" | "delete"; type NekoActionResult = { id?: number; action?: string; container?: string; configured_count?: number; exists?: boolean; running?: boolean; status?: string; message?: string; }; const YOUTUBE_PRO_PM2_PREFIX = "youtube2__"; function isYoutubeProcess(e: ProcessEntry) { return /youtube/i.test(e.script) || /youtube/i.test(e.pm2); } function isYoutubeProPm2(pm2: string): boolean { return pm2.trim().toLowerCase().startsWith(YOUTUBE_PRO_PM2_PREFIX); } function isYoutubeProProcess(e: ProcessEntry): boolean { return isYoutubeProPm2(e.pm2); } function scriptStem(script: string): string { const base = script.split("/").pop() || script; return base.replace(/\.[^.]+$/, ""); } function isStaticYoutubeControlEntry(entry: ProcessEntry): boolean { return isYoutubeProcess(entry) && entry.pm2.trim() === scriptStem(entry.script).trim(); } function singleModeProcessLabel(entry: ProcessEntry, t: TFn): string { const stem = scriptStem(entry.script).toLowerCase(); if (stem.startsWith("douyin_youtube")) return t("抖音→YouTube", "Douyin → YouTube"); if (stem.startsWith("youtube")) return t("YouTube", "YouTube"); return entry.label; } function preferredSingleProcessPm2(entries: ProcessEntry[]): string { const exact = entries.find((entry) => entry.pm2.trim().toLowerCase() === "youtube"); if (exact) return exact.pm2; const byScript = entries.find((entry) => scriptStem(entry.script).trim().toLowerCase() === "youtube"); if (byScript) return byScript.pm2; return entries[0]?.pm2 ?? ""; } function isYoutubeRow(row: LiveProcRow | undefined): boolean { if (!row) return false; return /youtube/i.test(row.pm2) || /youtube/i.test(row.script ?? ""); } function singleProcessPriority(entry: ProcessEntry, row: LiveProcRow | undefined): number { const business = (row?.business_status || "").trim().toLowerCase(); if (row?.is_pushing || business === "streaming") return 0; if (pm2StatusOnline(row?.process_status)) return 1; if (entry.pm2.trim().toLowerCase() === "youtube") return 2; if (scriptStem(entry.script).trim().toLowerCase() === "youtube") return 3; return 10; } function buildSingleProcessOptions(entries: ProcessEntry[], liveRows: LiveProcRow[]): ProcessEntry[] { const youtubeEntries = entries.filter((entry) => isYoutubeProcess(entry) && !isYoutubeProProcess(entry)); const staticYoutubeEntries = youtubeEntries.filter((entry) => isStaticYoutubeControlEntry(entry)); const base = staticYoutubeEntries.length ? [...staticYoutubeEntries] : youtubeEntries.length ? [...youtubeEntries] : [...entries]; const seen = new Set(base.map((entry) => entry.pm2.trim())); for (const row of liveRows.filter((row) => isYoutubeRow(row) && !isYoutubeProPm2(row.pm2))) { const pm2 = row.pm2.trim(); if (!pm2 || seen.has(pm2)) continue; const business = (row.business_status || "").trim().toLowerCase(); if (!row.is_pushing && business !== "streaming" && !pm2StatusOnline(row.process_status)) continue; const matched = youtubeEntries.find((entry) => entry.pm2.trim() === pm2); base.push( matched ?? { pm2, script: row.script ?? youtubeEntries[0]?.script ?? "youtube.py", label: row.label ?? pm2, }, ); seen.add(pm2); } return base; } function preferredSingleProcessPm2FromRuntime(entries: ProcessEntry[], liveRows: LiveProcRow[]): string { if (!entries.length) return ""; const rowMap = new Map( liveRows .filter(isYoutubeRow) .map((row) => [row.pm2.trim(), row] as const), ); let best = entries[0]; let bestScore = singleProcessPriority(best, rowMap.get(best.pm2.trim())); for (const entry of entries.slice(1)) { const score = singleProcessPriority(entry, rowMap.get(entry.pm2.trim())); if (score < bestScore) { best = entry; bestScore = score; } } return best.pm2; } function resolveChannelPm2(channel: YoutubeProChannel): string { return resolveYoutubeProChannelPm2(channel); } const MODE_KEY = "live-hub-youtube-mode-v1"; const PRO_PM2_RESERVED = new Set(["douyin_youtube", "tiktok", "obs", "web"]); /** UI 暂时隐藏「多频道 Pro」切换(DOM 与逻辑保留,改 false 即可恢复) */ const HIDE_YOUTUBE_MULTI_PRO_TOGGLE = false; /** UI 隐藏顶部「转播实况」概览卡(状态、指标网格、打开源站等) */ const HIDE_YOUTUBE_RELAY_SNAPSHOT = true; /** UI 隐藏「算法友好质量守护」板块 */ const HIDE_YOUTUBE_QUALITY_GUARD = true; /** UI 隐藏「直播事件中枢」板块 */ const HIDE_YOUTUBE_LIVE_EVENT_HUB = true; /** UI 隐藏「当前直播日志」整张卡片(改 false 可恢复) */ const HIDE_YOUTUBE_LIVE_PROCESS_LOG = false; type ProLaneDraft = { name: string; streamKey: string; pm2Name: string; notes: string; }; function laneDraftFromChannel(channel: YoutubeProChannel): ProLaneDraft { return { name: channel.name, streamKey: channel.streamKey ?? "", pm2Name: channel.pm2Name ?? defaultPm2NameForChannel(channel.id), notes: channel.notes ?? "", }; } function cleanLaneName(value: string | undefined, index: number): string { return cleanYoutubeProLaneName(value, index); } function laneDraftsFromChannels(channels: YoutubeProChannel[]): Record { return Object.fromEntries(channels.map((channel) => [channel.id, laneDraftFromChannel(channel)])); } function isLivePushingRow(row?: LiveProcRow): boolean { const business = (row?.business_status || "").trim().toLowerCase(); return !!row?.is_pushing || business === "streaming" || business === "relay_starting"; } function procStartBlocked(row?: LiveProcRow): boolean { return isLivePushingRow(row); } function proLaneStatusLabel(row: LiveProcRow | undefined, t: TFn): string { const business = (row?.business_status || "").trim().toLowerCase(); if ( business === "source_stalled" || business === "relay_slow" || business === "waiting_source" || business === "source_live" ) { return businessStatusLabel(row, t); } if (isLivePushingRow(row)) return t("推流中", "Pushing"); return businessStatusLabel(row, t); } function proLanePrimaryTitle( laneName: string, row?: LiveProcRow, urlLines = "", qualityLane?: YoutubeQualityLane, ): string { const fromQuality = (qualityLane?.source_display || qualityLane?.source_title || "").trim(); if (fromQuality) return fromQuality; return douyinSourceDisplayFor(row, urlLines) || laneName.trim(); } function proLaneDouyinSubtitle(row?: LiveProcRow, urlLines = "", laneName = ""): string { const source = douyinSourceDisplayFor(row, urlLines).trim(); const lane = laneName.trim(); if (isLivePushingRow(row) && lane && source && lane !== source) return lane; return ""; } function douyinSourceDisplayFor(row?: LiveProcRow, urlLines = "", logText = ""): string { const suppressAmbiguousBackend = !!row?.source_ambiguous && isLivePushingRow(row) && !row?.source_current; if (!suppressAmbiguousBackend) { const fromBackend = (row?.source_display || row?.source_title || "").trim(); if (fromBackend) return fromBackend; } else { const fromLogOnly = logText ? douyinSourceDisplayFrom("", logText).trim() : ""; if (fromLogOnly) return fromLogOnly; return ""; } const fromLocal = douyinSourceDisplayFrom(urlLines, logText).trim(); if (fromLocal) return fromLocal; const roomId = (row?.source_room_id || "").trim(); return roomId ? `抖音直播间 ${roomId}` : ""; } function douyinSourceUrlFor(row?: LiveProcRow, urlLines = ""): string { const backendUrl = (row?.source_url || "").trim(); if (backendUrl) return backendUrl; const urls = extractDouyinLiveUrls(urlLines); const suppressAmbiguousLocal = isLivePushingRow(row) && (row?.source_ambiguous || !!row?.source_display || !!row?.source_title) && urls.length > 1; if (suppressAmbiguousLocal) return ""; return urls[0] ?? ""; } type LiveProcRow = { pm2: string; script?: string; label?: string; process_status?: string; business_status?: string; business_note?: string; ffmpeg_active?: boolean; ffmpeg_speed?: number | null; ffmpeg_frame?: number | null; ffmpeg_time_seconds?: number | null; ffmpeg_progress_stalled?: boolean; ffmpeg_speed_low?: boolean; is_pushing?: boolean; source_title?: string; source_room_id?: string; source_url?: string; source_display?: string; source_ambiguous?: boolean; source_current?: boolean; }; type YoutubeLiveAlert = { id?: number; ts?: number; severity?: string; title?: string; message?: string; source?: string; }; type YoutubeLiveSample = { id?: number; ts?: number; source?: string; live_status?: string; viewer_count?: number | null; health?: string; popup_text?: string; page_url?: string; page_title?: string; }; type YoutubeLiveEvent = { id: number; event_uuid?: string; process?: string; mode?: string; channel_name?: string; source_url?: string; source_room_id?: string; source_title?: string; status?: string; started_at?: number; ended_at?: number | null; duration_seconds?: number; last_seen_at?: number; quality_score?: number; viewer_peak?: number; last_viewer_count?: number | null; last_live_status?: string; last_health?: string; last_popup_text?: string; last_page_url?: string; last_page_title?: string; control_actions?: Array<{ action?: string; ts?: number; note?: string }>; samples?: YoutubeLiveSample[]; alerts?: YoutubeLiveAlert[]; sample_count?: number; }; type YoutubeLiveSummary = { active?: YoutubeLiveEvent[]; latest?: YoutubeLiveEvent[]; alerts?: YoutubeLiveAlert[]; stats?: { total_events?: number; ended_events?: number; active_events?: number; sample_count?: number; total_duration_seconds?: number; viewer_peak?: number; }; capabilities?: string[]; }; type YoutubeQualityIssue = { level?: string; text?: string; }; type YoutubeQualityLane = { process?: string; label?: string; source_title?: string; source_room_id?: string; source_url?: string; source_display?: string; status?: string; is_pushing?: boolean; ffmpeg_active?: boolean; score?: number; metrics?: { fps?: number; bitrate?: number; speed?: number; frame?: number; drop?: number; dup?: number; error_count?: number; reconnect_count?: number; encoded_time?: string; }; url_count?: number; rtmps?: boolean; has_stream_key?: boolean; issues?: YoutubeQualityIssue[]; }; type YoutubeQualityGuard = { generated_at?: number; score?: number; summary?: { lanes?: number; pushing_lanes?: number; active_events?: number; sample_count?: number; viewer_peak?: number; }; lanes?: YoutubeQualityLane[]; recommendations?: YoutubeQualityIssue[]; ffmpeg_profile?: { target?: string; guardrails?: string[]; }; }; function pm2StatusOnline(st?: string) { return /^(online|running)$/i.test((st || "").trim()); } function openRelayLogPage(process: string) { const proc = (process || "youtube").trim() || "youtube"; const url = `/youtube-relay-log?process=${encodeURIComponent(proc)}`; window.open(url, "_blank", "noopener,noreferrer"); } function businessStatusLabel(row: LiveProcRow | undefined, t: TFn): string { const business = (row?.business_status || "").trim().toLowerCase(); if (business === "ready") return t("已配置", "Ready"); if (business === "streaming") return t("推流中", "Pushing"); if (business === "source_stalled") return t("源卡住", "Source stalled"); if (business === "relay_slow") return t("低速推流", "Relay slow"); if (business === "relay_starting") return t("转推启动中", "Relay starting"); if (business === "waiting_source") return t("等待上游", "Waiting source"); if (business === "source_live") return t("源已开播,转推未起", "Source live, relay down"); if (business === "monitoring") return t("监控中", "Monitoring"); if (business === "misconfigured") return t("密钥异常", "Key invalid"); if (business === "youtube_key_rejected") return t("密钥被 YouTube 拒绝", "Key rejected"); if (business === "stale") return t("心跳过期", "Stale"); if (business === "error") return t("异常", "Error"); if (pm2StatusOnline(row?.process_status)) return t("运行中", "Running"); return (row?.process_status || "").trim() || t("未运行", "Idle"); } function businessStatusBadgeClass(row: LiveProcRow | undefined): string { const business = (row?.business_status || "").trim().toLowerCase(); if (business === "ready") return "bg-sky-500/15 text-sky-100 ring-sky-500/25"; if (business === "streaming") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30"; if (business === "relay_slow") return "bg-amber-500/15 text-amber-100 ring-amber-500/25"; if (business === "source_stalled") return "bg-rose-500/15 text-rose-100 ring-rose-500/25"; if (business === "waiting_source" || business === "monitoring" || business === "relay_starting") { return "bg-amber-500/15 text-amber-100 ring-amber-500/25"; } if (business === "source_live") return "bg-sky-500/15 text-sky-100 ring-sky-500/25"; if (business === "misconfigured" || business === "youtube_key_rejected" || business === "error" || business === "stale") { return "bg-rose-500/15 text-rose-100 ring-rose-500/25"; } if (pm2StatusOnline(row?.process_status)) return "bg-zinc-500/15 text-zinc-200 ring-zinc-500/25"; return "bg-zinc-600/20 text-zinc-400 ring-zinc-500/25"; } function fmtEventDuration(seconds?: number | null): string { const sec = Math.max(0, Math.floor(seconds || 0)); if (sec < 60) return `${sec}s`; const min = Math.floor(sec / 60); if (min < 60) return `${min}m ${sec % 60}s`; const h = Math.floor(min / 60); const m = min % 60; return `${h}h ${m}m`; } function fmtEventTime(ts?: number | null): string { if (!ts) return "-"; try { return new Date(ts * 1000).toLocaleString(); } catch { return "-"; } } function eventStatusClass(status?: string): string { const s = (status || "").toLowerCase(); if (s === "active") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30"; if (s === "error") return "bg-rose-500/15 text-rose-100 ring-rose-500/30"; if (s === "ended") return "bg-zinc-600/20 text-zinc-300 ring-zinc-500/25"; return "bg-cyan-500/15 text-cyan-100 ring-cyan-500/25"; } function eventStatusText(status: string | undefined, t: TFn): string { const s = (status || "").toLowerCase(); if (s === "active") return t("直播中", "Live"); if (s === "ended") return t("已结束", "Ended"); if (s === "error") return t("异常", "Problem"); if (s === "idle") return t("等待中", "Waiting"); return t("记录", "Record"); } function viewerText(value?: number | null, t?: TFn): string { if (value == null) return t ? t("未知", "Unknown") : "-"; return value.toLocaleString(); } function eventTitleText(event: YoutubeLiveEvent | null | undefined, t: TFn): string { if (!event) return t("未选择直播", "No event selected"); const title = (event.source_title || event.channel_name || "").trim(); if (title) return title; if (event.source_room_id) return t(`抖音直播间 ${event.source_room_id}`, `Douyin room ${event.source_room_id}`); if (event.process) return t(`直播线路 ${event.process}`, `Relay lane ${event.process}`); return t(`直播事件 #${event.id}`, `Live event #${event.id}`); } function eventSourceText(event: YoutubeLiveEvent | null | undefined, t: TFn): string { if (!event) return "-"; if (event.source_room_id) return t(`抖音房间 ${event.source_room_id}`, `Douyin room ${event.source_room_id}`); if (event.source_url) return event.source_url.replace(/^https?:\/\//, ""); return t("来源未识别", "Unknown source"); } function fmtDurationHuman(seconds: number | null | undefined, t: TFn): string { const sec = Math.max(0, Math.floor(seconds || 0)); if (sec < 60) return t(`${sec} 秒`, `${sec}s`); const min = Math.floor(sec / 60); if (min < 60) return t(`${min} 分 ${sec % 60} 秒`, `${min}m ${sec % 60}s`); const h = Math.floor(min / 60); const m = min % 60; return t(`${h} 小时 ${m} 分`, `${h}h ${m}m`); } function fmtShortTime(ts?: number | null): string { if (!ts) return "-"; try { return new Date(ts * 1000).toLocaleString(undefined, { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false, }); } catch { return "-"; } } function eventRiskText(event: YoutubeLiveEvent | null | undefined, t: TFn): string { if (!event) return "-"; const status = (event.status || "").toLowerCase(); const health = `${event.last_health || ""} ${event.last_live_status || ""} ${event.last_popup_text || ""}`.toLowerCase(); if (status === "error" || /error|failed|poor|unstable|异常|错误|失败/.test(health)) return t("需要处理", "Needs attention"); if (event.last_popup_text) return t("有弹窗", "Popup seen"); if ((event.quality_score ?? 100) < 50) return t("质量偏低", "Low quality"); return t("正常", "Normal"); } function eventRiskClass(event: YoutubeLiveEvent | null | undefined): string { const risk = eventRiskText(event, (zh) => zh); if (risk === "需要处理" || risk === "质量偏低") return "bg-rose-500/15 text-rose-100 ring-rose-500/30"; if (risk === "有弹窗") return "bg-amber-500/15 text-amber-100 ring-amber-500/30"; return "bg-emerald-500/15 text-emerald-100 ring-emerald-500/25"; } function qualityScoreClass(score?: number): string { const value = Number(score || 0); if (value >= 80) return "text-emerald-200"; if (value >= 55) return "text-amber-200"; return "text-rose-200"; } function qualityPillClass(level?: string): string { const value = (level || "").toLowerCase(); if (value === "critical") return "bg-rose-500/15 text-rose-100 ring-rose-500/30"; if (value === "warning") return "bg-amber-500/15 text-amber-100 ring-amber-500/30"; if (value === "ok") return "bg-emerald-500/15 text-emerald-100 ring-emerald-500/25"; return "bg-cyan-500/15 text-cyan-100 ring-cyan-500/25"; } function laneStatusEmoji(row?: LiveProcRow): string { const business = (row?.business_status || "").trim().toLowerCase(); if (business === "streaming") return "🟢"; if (business === "relay_slow") return "🟡"; if (business === "source_stalled") return "🟠"; if (business === "relay_starting") return "🔵"; if (business === "youtube_key_rejected" || business === "error") return "🔴"; if (business === "source_live") return "🔵"; if (business === "waiting_source") return "⚪"; return "⚫"; } function speedToneClass(speed?: number, speedLow?: boolean, progressStalled?: boolean): string { if (progressStalled) return "text-rose-300"; if (speedLow || (typeof speed === "number" && speed > 0 && speed < 0.95)) return "text-amber-200"; if (typeof speed === "number" && speed >= 0.95) return "text-emerald-200"; return "text-cyan-100"; } function MetricPulseCard({ label, value, helper, warn = false, accent = "cyan", }: { label: string; value: string; helper: string; warn?: boolean; accent?: "cyan" | "emerald" | "amber" | "violet"; }) { const ring = accent === "emerald" ? "from-emerald-500/20 via-transparent to-cyan-500/10" : accent === "amber" ? "from-amber-500/20 via-transparent to-rose-500/10" : accent === "violet" ? "from-violet-500/20 via-transparent to-cyan-500/10" : "from-cyan-500/20 via-transparent to-violet-500/10"; return (

{label}

{value}

{helper}

); } function qualityLaneMetrics( row: LiveProcRow | undefined, qualityLane: YoutubeQualityLane | undefined, ): FfmpegMetrics & { speedLow?: boolean; progressStalled?: boolean; live: boolean } { return mergeFfmpegMetrics(row, qualityLane?.metrics, ""); } function nonCommentUrlLinesOf(text: string): string[] { return text .split(/\r?\n/) .map((line) => line.trim()) .filter((line) => line && !line.startsWith("#")); } function shouldPreserveLocalUrlDraft(localText: string, remoteText: string): boolean { return nonCommentUrlLinesOf(localText).length > 0 && nonCommentUrlLinesOf(remoteText).length === 0; } function parseProcBusy(busy: string | null): { action: string; pm2: string } | null { if (!busy?.startsWith("proc:")) return null; const rest = busy.slice(5); const idx = rest.indexOf(":"); if (idx <= 0) return null; const action = rest.slice(0, idx); const pm2 = rest.slice(idx + 1); if (!pm2 || !["start", "stop", "restart"].includes(action)) return null; return { action, pm2 }; } function LiveStreamActionBtn({ kind, busyKind, targetPm2, busy, online, pushing, label, className, baseLock, onRun, notify, t, compact, }: { kind: "start" | "stop" | "restart"; busyKind?: "start" | "stop" | "restart"; targetPm2: string; busy: string | null; online: boolean; pushing: boolean; label: string; className: string; baseLock: boolean; onRun: () => void; notify: (s: string) => void; t: TFn; compact?: boolean; }) { const pb = parseProcBusy(busy); const forThisProc = pb && pb.pm2 === targetPm2; const actionForBusy = busyKind ?? kind; const loading = !!(forThisProc && pb.action === actionForBusy); const siblingBusy = !!(forThisProc && pb.action !== actionForBusy); const blockStart = kind === "start" && pushing; const blockStop = kind === "stop" && !online; const blockRestart = kind === "restart" && !online; const blocked = blockStart || blockStop || blockRestart; const hardLock = baseLock || loading || siblingBusy; const onClick = () => { if (loading) return; if (siblingBusy) { notify(t("请等待当前操作完成", "Wait for the current action to finish")); return; } if (blockStart) { notify(t("已在推流中,无需重复开始", "Already pushing")); return; } if (blockStop) { notify(t("当前未在直播,无法停止", "Not live — cannot stop")); return; } if (blockRestart) { notify(t("进程未运行时请使用「开始直播」", "Use Start when the process is not running")); return; } if (baseLock) return; onRun(); }; const sizeCls = compact ? "min-h-[2rem] px-3 py-1.5 text-xs font-medium" : "min-h-[2.75rem] px-4 py-3 text-sm font-medium"; return ( ); } type Props = { t: TFn; busy: string | null; entries: ProcessEntry[]; currentProc: string; setCurrentProc: (v: string) => void; urlConfig: string; setUrlConfig: (v: string) => void; onRunProcess: (a: "start" | "stop" | "restart", processPm2?: string) => void; onSaveUrlConfig: (content?: string, processPm2?: string) => void | Promise; fetchJson: (path: string, init?: RequestInit) => Promise; liveProcesses: LiveProcRow[]; notify: (msg: string) => void; onNavigate?: (target: PortalNavTarget) => void; onRefresh?: () => void | Promise; quickLinks?: QuickLinkMap; }; export function LiveYoutubeUnmannedView({ t, busy, entries, currentProc, setCurrentProc, urlConfig, setUrlConfig, onRunProcess, onSaveUrlConfig, fetchJson, liveProcesses, notify, onNavigate, onRefresh, quickLinks, }: Props) { const ytEntries = useMemo(() => entries.filter(isYoutubeProcess), [entries]); const singleProcessOptions = useMemo( () => buildSingleProcessOptions(ytEntries.length ? ytEntries : entries, liveProcesses), [entries, liveProcesses, ytEntries], ); const preferredSingleProc = useMemo( () => preferredSingleProcessPm2FromRuntime(singleProcessOptions, liveProcesses) || preferredSingleProcessPm2(singleProcessOptions), [liveProcesses, singleProcessOptions], ); const [mode, setMode] = useState<"single" | "pro">("single"); const [channels, setChannels] = useState([]); const [activeCh, setActiveCh] = useState(""); const [singleUrlDraft, setSingleUrlDraft] = useState(urlConfig); const [youtubeIniText, setYoutubeIniText] = useState(""); const [ytFields, setYtFields] = useState({ key: "", rtmps: true, bitrate: "", fastAudio: true, }); const [ytIniStatus, setYtIniStatus] = useState(null); const [ytIniLoading, setYtIniLoading] = useState(false); const [proUrlDraft, setProUrlDraft] = useState(""); const [urlAutoRefresh, setUrlAutoRefresh] = useState(true); const [urlReloading, setUrlReloading] = useState(false); const [urlOptimizing, setUrlOptimizing] = useState(false); const [urlFetchNote, setUrlFetchNote] = useState(null); const [laneDrafts, setLaneDrafts] = useState>({}); const [laneSaving, setLaneSaving] = useState(false); const [laneStatus, setLaneStatus] = useState(null); const [activeViewRefreshToken, setActiveViewRefreshToken] = useState(0); const [liveEventSummary, setLiveEventSummary] = useState(null); const [selectedLiveEvent, setSelectedLiveEvent] = useState(null); const [liveEventLoading, setLiveEventLoading] = useState(false); const [qualityGuard, setQualityGuard] = useState(null); const [qualityGuardLoading, setQualityGuardLoading] = useState(false); const [pageVisible, setPageVisible] = useState(true); const [nekoBusy, setNekoBusy] = useState(null); const [nekoActionNote, setNekoActionNote] = useState(null); const urlListDirtyRef = useRef(false); const singleUrlDraftRef = useRef(urlConfig); const proUrlDraftRef = useRef(proUrlDraft); const channelsRef = useRef([]); const currentProcRef = useRef(currentProc); const urlRequestSeqRef = useRef(0); const ytIniRequestSeqRef = useRef(0); const urlLoadingSeqRef = useRef(0); const ytIniLoadingSeqRef = useRef(0); const urlConfigReadInFlightRef = useRef>>({}); const ytIniReadInFlightRef = useRef>>({}); const applySingleUrlDraft = useCallback( (next: string) => { singleUrlDraftRef.current = next; setSingleUrlDraft(next); setUrlConfig(next); }, [setUrlConfig], ); const applyProUrlDraft = useCallback((next: string) => { proUrlDraftRef.current = next; setProUrlDraft(next); }, []); const readUrlConfigContent = useCallback( (targetPm2: string) => { const target = targetPm2.trim(); if (!target) return Promise.resolve(""); const existing = urlConfigReadInFlightRef.current[target]; if (existing) return existing; const params = new URLSearchParams({ process: target, _ts: String(Date.now()) }); const promise = fetchJson<{ content?: string }>(`/get_url_config?${params}`).then((data) => data.content ?? ""); urlConfigReadInFlightRef.current[target] = promise; promise.then( () => { if (urlConfigReadInFlightRef.current[target] === promise) delete urlConfigReadInFlightRef.current[target]; }, () => { if (urlConfigReadInFlightRef.current[target] === promise) delete urlConfigReadInFlightRef.current[target]; }, ); return promise; }, [fetchJson], ); const readYoutubeIniContent = useCallback( (targetPm2: string) => { const target = targetPm2.trim(); if (!target) return Promise.resolve(""); const existing = ytIniReadInFlightRef.current[target]; if (existing) return existing; const params = new URLSearchParams({ process: target, _ts: String(Date.now()) }); const promise = fetchJson<{ content?: string }>(`/get_config?${params}`).then((data) => data.content ?? ""); ytIniReadInFlightRef.current[target] = promise; promise.then( () => { if (ytIniReadInFlightRef.current[target] === promise) delete ytIniReadInFlightRef.current[target]; }, () => { if (ytIniReadInFlightRef.current[target] === promise) delete ytIniReadInFlightRef.current[target]; }, ); return promise; }, [fetchJson], ); const beginUrlLoading = useCallback(() => { const id = ++urlLoadingSeqRef.current; setUrlReloading(true); return id; }, []); const finishUrlLoading = useCallback((id: number) => { if (id === urlLoadingSeqRef.current) setUrlReloading(false); }, []); const beginYtIniLoading = useCallback(() => { const id = ++ytIniLoadingSeqRef.current; setYtIniLoading(true); return id; }, []); const finishYtIniLoading = useCallback((id: number) => { if (id === ytIniLoadingSeqRef.current) setYtIniLoading(false); }, []); useEffect(() => { const onVis = () => setPageVisible(document.visibilityState === "visible"); onVis(); document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, []); useEffect(() => { urlListDirtyRef.current = false; }, [currentProc]); useEffect(() => { currentProcRef.current = currentProc; }, [currentProc]); useEffect(() => { if (mode !== "single") return; singleUrlDraftRef.current = urlConfig; setSingleUrlDraft(urlConfig); }, [mode, urlConfig]); useEffect(() => { proUrlDraftRef.current = proUrlDraft; }, [proUrlDraft]); useEffect(() => { channelsRef.current = channels; }, [channels]); useEffect(() => { urlRequestSeqRef.current += 1; ytIniRequestSeqRef.current += 1; urlListDirtyRef.current = false; setUrlFetchNote(null); }, [mode, activeCh]); const pullUrlConfigFromServer = useCallback(async () => { const targetProc = currentProcRef.current.trim(); if (!targetProc) return; if (mode === "pro") { const activePm2 = channelsRef.current.find((row) => row.id === activeCh); if (!activePm2 || resolveChannelPm2(activePm2) !== targetProc) return; } const requestId = ++urlRequestSeqRef.current; try { const c = await readUrlConfigContent(targetProc); if (requestId !== urlRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; if (urlListDirtyRef.current) return; if (mode === "single") applySingleUrlDraft(c); else { const localDraft = channelsRef.current.find((row) => row.id === activeCh)?.urlLines ?? ""; if (shouldPreserveLocalUrlDraft(localDraft, c)) { applyProUrlDraft(localDraft); return; } applyProUrlDraft(c); } } catch { /* ignore */ } }, [activeCh, applyProUrlDraft, applySingleUrlDraft, mode, readUrlConfigContent]); const urlConfigPollIntervalMs = useMemo( () => urlConfigPollMs({ pageVisible }), [pageVisible], ); useEffect(() => { if (!currentProc || !urlAutoRefresh || urlConfigPollIntervalMs <= 0) return; const id = window.setInterval(() => { if (urlListDirtyRef.current) return; void pullUrlConfigFromServer(); }, urlConfigPollIntervalMs); return () => clearInterval(id); }, [currentProc, urlAutoRefresh, pullUrlConfigFromServer, urlConfigPollIntervalMs]); const reloadUrlManual = async () => { const targetProc = currentProcRef.current.trim(); if (!targetProc) return; if (mode === "pro") { const activePm2 = channelsRef.current.find((row) => row.id === activeCh); if (!activePm2 || resolveChannelPm2(activePm2) !== targetProc) return; } const urlLoadingId = beginUrlLoading(); setUrlFetchNote(null); urlListDirtyRef.current = false; const requestId = ++urlRequestSeqRef.current; try { const c = await readUrlConfigContent(targetProc); if (requestId !== urlRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; if (urlListDirtyRef.current) { setUrlFetchNote(t("检测到本地未保存修改,已保留当前草稿", "Kept the local unsaved draft")); return; } if (mode === "single") applySingleUrlDraft(c); else { const localDraft = channelsRef.current.find((row) => row.id === activeCh)?.urlLines ?? ""; if (shouldPreserveLocalUrlDraft(localDraft, c)) { applyProUrlDraft(localDraft); setUrlFetchNote(t("服务器暂无已保存 URL,已保留本地草稿", "Server has no saved URLs, kept the local draft")); return; } applyProUrlDraft(c); } setUrlFetchNote(t("已从服务器读取 URL_config", "Reloaded URL_config from server")); } catch (e) { if (requestId !== urlRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; setUrlFetchNote((e as Error).message); } finally { finishUrlLoading(urlLoadingId); } }; useEffect(() => { try { if (HIDE_YOUTUBE_MULTI_PRO_TOGGLE) { setMode("single"); return; } const m = window.localStorage.getItem(MODE_KEY); if (m === "pro" || m === "single") setMode(m); } catch { /* ignore */ } }, []); useEffect(() => { let cancelled = false; void (async () => { try { const remote = await fetchYoutubeProChannelsRemote(fetchJson); if (remote.fetched && remote.channels.length && !cancelled) { const nextChannels = cleanYoutubeProChannelNames(remote.channels); channelsRef.current = nextChannels; setChannels(nextChannels); setLaneDrafts(laneDraftsFromChannels(nextChannels)); saveYoutubeProChannels(nextChannels); return; } } catch { /* 使用本机缓存 */ } if (cancelled) return; const list = loadYoutubeProChannels(); const initial = list.length > 0 ? list : (() => { const id = newChannelId(); return [ { id, name: "线路 1", streamKey: "", urlLines: "", pm2Name: defaultPm2NameForChannel(id), notes: "", }, ]; })(); const nextInitial = cleanYoutubeProChannelNames(initial); channelsRef.current = nextInitial; setChannels(nextInitial); setLaneDrafts(laneDraftsFromChannels(nextInitial)); saveYoutubeProChannels(nextInitial); })(); return () => { cancelled = true; }; }, [fetchJson]); useEffect(() => { if (!channels.length) { if (activeCh) setActiveCh(""); return; } if (!activeCh || !channels.some((row) => row.id === activeCh)) { setActiveCh(channels[0].id); } }, [channels, activeCh]); const active = channels.find((c) => c.id === activeCh) || channels[0]; const currentProcChannel = useMemo( () => channels.find((c) => resolveChannelPm2(c) === currentProc), [channels, currentProc], ); const rowForPm2 = useCallback((pm2: string) => liveProcesses.find((p) => p.pm2 === pm2), [liveProcesses]); const statusForPm2 = useCallback( (pm2: string) => rowForPm2(pm2)?.process_status, [rowForPm2], ); const currentProcRow = rowForPm2(currentProc); const singleRuntimeProc = currentProc; const runtimeLogProc = currentProc; const runtimeLogRow = rowForPm2(runtimeLogProc); useEffect(() => { if (mode !== "single" || !preferredSingleProc) return; if (!currentProc) { currentProcRef.current = preferredSingleProc; setCurrentProc(preferredSingleProc); } }, [currentProc, mode, preferredSingleProc, setCurrentProc]); const applyChannelsLocal = useCallback((next: YoutubeProChannel[]) => { const cleaned = cleanYoutubeProChannelNames(next); channelsRef.current = cleaned; setChannels(cleaned); saveYoutubeProChannels(cleaned); }, []); const patchChannelLocalForPm2 = useCallback( (pm2: string, patch: Partial) => { const target = pm2.trim(); if (!target) return; let changed = false; const next = channelsRef.current.map((row) => { if (resolveChannelPm2(row) !== target) return row; changed = true; return { ...row, ...patch }; }); if (changed) applyChannelsLocal(next); }, [applyChannelsLocal], ); const syncChannelsRemote = useCallback( async (next: YoutubeProChannel[], options: YoutubeProChannelsSyncOptions = {}) => { await pushYoutubeProChannelsRemote(fetchJson, next, options); }, [fetchJson], ); const persistChannels = useCallback( (next: YoutubeProChannel[], options: YoutubeProChannelsSyncOptions = {}) => { applyChannelsLocal(next); void syncChannelsRemote(next, options).catch((e) => { notify( `${t("多频道列表未同步到服务器", "Channel list not saved on server")}: ${(e as Error).message}`, ); }); }, [applyChannelsLocal, notify, syncChannelsRemote, t], ); const activeLaneDraft = useMemo( () => (active ? laneDrafts[active.id] ?? laneDraftFromChannel(active) : null), [active, laneDrafts], ); useEffect(() => { if (!active) return; setLaneDrafts((prev) => { if (prev[active.id]) return prev; return { ...prev, [active.id]: laneDraftFromChannel(active) }; }); }, [active]); useEffect(() => { if (!active || resolveChannelPm2(active) !== "youtube") return; const key = ytFields.key.trim(); if (!key) return; setLaneDrafts((prev) => { const draft = prev[active.id] ?? laneDraftFromChannel(active); if (draft.streamKey.trim() === key && draft.pm2Name === "youtube") return prev; if (draft.streamKey.trim()) return prev; return { ...prev, [active.id]: { ...draft, streamKey: key, pm2Name: "youtube", }, }; }); }, [active, ytFields.key]); useEffect(() => { setLaneStatus(null); }, [activeCh]); const setLaneDraftField = useCallback( (key: keyof ProLaneDraft, value: string) => { if (!active) return; setLaneDrafts((prev) => ({ ...prev, [active.id]: { ...(prev[active.id] ?? laneDraftFromChannel(active)), [key]: value, }, })); setLaneStatus(null); }, [active], ); const activeSavedPm2 = active ? resolveChannelPm2(active) : ""; const activeDraftPm2 = active && activeLaneDraft ? resolveYoutubeProChannelPm2({ id: active.id, pm2Name: activeLaneDraft.pm2Name }) : ""; const activePm2PreviewChanged = !!active && !!activeLaneDraft && activeDraftPm2 !== activeSavedPm2; const activeLaneValidation = useMemo(() => { if (!active || !activeLaneDraft) { return { ok: false, message: t("请选择线路", "Pick a lane"), normalizedName: "", normalizedPm2: "", normalizedStreamKey: "", normalizedNotes: "", }; } const activeIndex = channels.findIndex((row) => row.id === active.id); const normalizedName = cleanLaneName(activeLaneDraft.name, activeIndex >= 0 ? activeIndex : 0); const normalizedPm2 = resolveYoutubeProChannelPm2({ id: active.id, pm2Name: activeLaneDraft.pm2Name }); if (!normalizedPm2) { return { ok: false, message: t("进程名不能为空", "PM2 name is required"), normalizedName, normalizedPm2, normalizedStreamKey: activeLaneDraft.streamKey.trim(), normalizedNotes: activeLaneDraft.notes.trim(), }; } if (PRO_PM2_RESERVED.has(normalizedPm2)) { return { ok: false, message: t("该进程名保留给系统模块,请换一个", "This PM2 name is reserved"), normalizedName, normalizedPm2, normalizedStreamKey: activeLaneDraft.streamKey.trim(), normalizedNotes: activeLaneDraft.notes.trim(), }; } const duplicate = channels.find((row) => row.id !== active.id && resolveChannelPm2(row) === normalizedPm2); if (duplicate) { return { ok: false, message: t("该进程名已被其它线路占用", "Another lane already uses this PM2 name"), normalizedName, normalizedPm2, normalizedStreamKey: activeLaneDraft.streamKey.trim(), normalizedNotes: activeLaneDraft.notes.trim(), }; } return { ok: true, message: "", normalizedName, normalizedPm2, normalizedStreamKey: activeLaneDraft.streamKey.trim(), normalizedNotes: activeLaneDraft.notes.trim(), }; }, [active, activeLaneDraft, channels, t]); const activeLaneDirty = useMemo(() => { if (!active || !activeLaneDraft) return false; const savedDraft = laneDraftFromChannel(active); return ( activeLaneDraft.name !== savedDraft.name || activeLaneDraft.streamKey !== savedDraft.streamKey || sanitizeYoutubePm2Name(activeLaneDraft.pm2Name) !== sanitizeYoutubePm2Name(savedDraft.pm2Name) || activeLaneDraft.notes !== savedDraft.notes ); }, [active, activeLaneDraft]); const refreshSingleProcessFromServer = useCallback( async (targetPm2: string) => { const target = targetPm2.trim(); if (!target) return; const urlRequestId = ++urlRequestSeqRef.current; const iniRequestId = ++ytIniRequestSeqRef.current; urlListDirtyRef.current = false; const urlLoadingId = beginUrlLoading(); const iniLoadingId = beginYtIniLoading(); setUrlFetchNote(t("正在同步单频道配置...", "Syncing single-channel config...")); setYtIniStatus(null); try { const [urlResult, iniResult] = await Promise.allSettled([ readUrlConfigContent(target), readYoutubeIniContent(target), ]); if (urlRequestId === urlRequestSeqRef.current && target === currentProcRef.current.trim()) { if (urlResult.status === "fulfilled") { applySingleUrlDraft(urlResult.value); setUrlFetchNote(t("单频道配置已实时同步", "Single-channel config synced")); } else { setUrlFetchNote(urlResult.reason instanceof Error ? urlResult.reason.message : String(urlResult.reason)); } } if (iniRequestId === ytIniRequestSeqRef.current && target === currentProcRef.current.trim()) { if (iniResult.status === "fulfilled") { const text = iniResult.value; setYoutubeIniText(text); setYtFields(parseYoutubeIniFields(text)); } else { setYtIniStatus(iniResult.reason instanceof Error ? iniResult.reason.message : String(iniResult.reason)); } } } finally { finishUrlLoading(urlLoadingId); finishYtIniLoading(iniLoadingId); if (target === currentProcRef.current.trim()) { setActiveViewRefreshToken((prev) => prev + 1); } } }, [ applySingleUrlDraft, beginUrlLoading, beginYtIniLoading, finishUrlLoading, finishYtIniLoading, readUrlConfigContent, readYoutubeIniContent, t, ], ); const refreshProLaneFromServer = useCallback( async (channel: YoutubeProChannel) => { const target = resolveChannelPm2(channel).trim(); if (!target) return; const urlRequestId = ++urlRequestSeqRef.current; const iniRequestId = ++ytIniRequestSeqRef.current; urlListDirtyRef.current = false; const urlLoadingId = beginUrlLoading(); const iniLoadingId = beginYtIniLoading(); setUrlFetchNote(t("正在同步当前线路配置...", "Syncing current lane config...")); setYtIniStatus(null); try { const [urlResult, iniResult] = await Promise.allSettled([ readUrlConfigContent(target), readYoutubeIniContent(target), ]); if (urlRequestId === urlRequestSeqRef.current && target === currentProcRef.current.trim()) { if (urlResult.status === "fulfilled") { const remoteText = urlResult.value; const localDraft = channel.urlLines ?? ""; if (shouldPreserveLocalUrlDraft(localDraft, remoteText)) { applyProUrlDraft(localDraft); patchChannelLocalForPm2(target, { urlLines: localDraft }); setUrlFetchNote(t("服务器暂无已保存 URL,已保留当前线路草稿", "Server has no saved URLs, kept this lane draft")); } else { applyProUrlDraft(remoteText); patchChannelLocalForPm2(target, { urlLines: remoteText }); setUrlFetchNote(t("当前线路地址已实时同步", "Current lane URLs synced")); } } else { setUrlFetchNote(urlResult.reason instanceof Error ? urlResult.reason.message : String(urlResult.reason)); } } if (iniRequestId === ytIniRequestSeqRef.current && target === currentProcRef.current.trim()) { if (iniResult.status === "fulfilled") { const text = iniResult.value; const fields = parseYoutubeIniFields(text); setYoutubeIniText(text); setYtFields(fields); if (fields.key.trim()) { setLaneDrafts((prev) => { const draft = prev[channel.id] ?? laneDraftFromChannel(channel); if (draft.streamKey.trim() && draft.streamKey.trim() !== (channel.streamKey ?? "").trim()) return prev; if (draft.streamKey.trim() === fields.key.trim()) return prev; return { ...prev, [channel.id]: { ...draft, streamKey: fields.key.trim(), }, }; }); } } else { setYtIniStatus(iniResult.reason instanceof Error ? iniResult.reason.message : String(iniResult.reason)); } } } finally { finishUrlLoading(urlLoadingId); finishYtIniLoading(iniLoadingId); if (target === currentProcRef.current.trim()) { setActiveViewRefreshToken((prev) => prev + 1); } } }, [ applyProUrlDraft, beginUrlLoading, beginYtIniLoading, finishUrlLoading, finishYtIniLoading, patchChannelLocalForPm2, readUrlConfigContent, readYoutubeIniContent, t, ], ); const refreshProChannelsFromServer = useCallback(async () => { try { const remote = await fetchYoutubeProChannelsRemote(fetchJson); if (!remote.fetched || !remote.channels.length) return; const nextChannels = cleanYoutubeProChannelNames(remote.channels); channelsRef.current = nextChannels; setChannels(nextChannels); setLaneDrafts(laneDraftsFromChannels(nextChannels)); saveYoutubeProChannels(nextChannels); const ch = nextChannels.find((row) => row.id === activeCh) ?? nextChannels[0]; if (!ch) return; setActiveCh(ch.id); applyProUrlDraft((ch.urlLines ?? "").trim()); const pm2 = resolveChannelPm2(ch); currentProcRef.current = pm2; setCurrentProc(pm2); void refreshProLaneFromServer(ch); } catch { /* keep current local channels when the server is temporarily unreachable */ } }, [activeCh, applyProUrlDraft, fetchJson, refreshProLaneFromServer, setCurrentProc]); void refreshSingleProcessFromServer; void refreshProChannelsFromServer; const setModePersist = useCallback( (m: "single" | "pro") => { if (m === "pro" && mode === "single" && !ytFields.key.trim()) { notify(t("请先填写并保存 YouTube 推流 key,再切换到多频道 Pro", "Fill and save the YouTube stream key before switching to Multi Pro")); return; } if (m === "single") { const current = currentProcRef.current.trim(); const activePm2 = active ? resolveChannelPm2(active) : ""; const target = mode === "pro" ? activePm2 || current : current || preferredSingleProc || singleProcessOptions[0]?.pm2 || ""; if (target) { currentProcRef.current = target; setCurrentProc(target); void refreshSingleProcessFromServer(target); } } if (m === "pro" && channels.length) { const current = currentProcRef.current.trim(); const ch = channels.find((c) => resolveChannelPm2(c) === current) ?? channels.find((c) => c.id === activeCh) ?? channels[0]; applyProUrlDraft((ch?.urlLines ?? "").trim()); if (ch) { setActiveCh(ch.id); const pm2 = resolveChannelPm2(ch); currentProcRef.current = pm2; setCurrentProc(pm2); void refreshProLaneFromServer(ch); } } setMode(m); try { window.localStorage.setItem(MODE_KEY, m); } catch { /* ignore */ } }, [ channels, applyProUrlDraft, active, activeCh, mode, notify, preferredSingleProc, refreshProLaneFromServer, refreshSingleProcessFromServer, setCurrentProc, singleProcessOptions, t, ytFields.key, ], ); const selectProChannel = useCallback( (c: YoutubeProChannel) => { const u = (c.urlLines ?? "").trim(); applyProUrlDraft(u); setActiveCh(c.id); const pm2 = resolveChannelPm2(c); currentProcRef.current = pm2; setCurrentProc(pm2); void refreshProLaneFromServer(c); }, [applyProUrlDraft, refreshProLaneFromServer, setCurrentProc], ); useEffect(() => { if (mode !== "pro" || !activeCh) return; const ch = channels.find((x) => x.id === activeCh); if (!ch) return; const want = resolveChannelPm2(ch); currentProcRef.current = want; setCurrentProc(want); }, [mode, activeCh, channels, setCurrentProc]); const loadYoutubeIni = useCallback(async () => { const targetProc = currentProcRef.current.trim(); if (!targetProc) return; const requestId = ++ytIniRequestSeqRef.current; const iniLoadingId = beginYtIniLoading(); setYtIniStatus(null); try { const text = await readYoutubeIniContent(targetProc); if (requestId !== ytIniRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; setYoutubeIniText(text); setYtFields(parseYoutubeIniFields(text)); } catch (e) { if (requestId !== ytIniRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return; setYtIniStatus((e as Error).message); } finally { finishYtIniLoading(iniLoadingId); } }, [beginYtIniLoading, finishYtIniLoading, readYoutubeIniContent]); useEffect(() => { if (!currentProc) return; if (mode === "pro") { if (!active || currentProc !== resolveChannelPm2(active)) return; void pullUrlConfigFromServer(); void loadYoutubeIni(); setActiveViewRefreshToken((prev) => prev + 1); return; } void refreshSingleProcessFromServer(currentProc); }, [active, activeCh, currentProc, loadYoutubeIni, mode, pullUrlConfigFromServer, refreshSingleProcessFromServer]); const persistActiveLaneDraft = useCallback( async () => { if (!active || !activeLaneDraft) { throw new Error(t("请选择线路", "Pick a lane")); } if (!activeLaneValidation.ok) { throw new Error(activeLaneValidation.message); } const latestProUrlDraft = proUrlDraftRef.current; const next = channels.map((row) => row.id === active.id ? { ...row, name: activeLaneValidation.normalizedName, streamKey: activeLaneValidation.normalizedStreamKey, pm2Name: activeLaneValidation.normalizedPm2, notes: activeLaneValidation.normalizedNotes, urlLines: latestProUrlDraft, } : row, ); await syncChannelsRemote(next, { force: true }); applyChannelsLocal(next); setLaneDrafts((prev) => ({ ...prev, [active.id]: { name: activeLaneValidation.normalizedName, streamKey: activeLaneValidation.normalizedStreamKey, pm2Name: activeLaneValidation.normalizedPm2, notes: activeLaneValidation.normalizedNotes, }, })); return { next, savedLane: next.find((row) => row.id === active.id) ?? ({ ...active, name: activeLaneValidation.normalizedName, streamKey: activeLaneValidation.normalizedStreamKey, pm2Name: activeLaneValidation.normalizedPm2, notes: activeLaneValidation.normalizedNotes, urlLines: latestProUrlDraft, } satisfies YoutubeProChannel), pm2: activeLaneValidation.normalizedPm2, }; }, [ active, activeLaneDraft, activeLaneValidation, applyChannelsLocal, channels, syncChannelsRemote, t, ], ); const saveYoutubeIniToServer = async (content: string, processPm2 = currentProcRef.current) => { const targetPm2 = processPm2.trim(); if (!targetPm2) { setYtIniStatus(t("请选择进程", "Pick a process")); return; } ytIniRequestSeqRef.current += 1; const iniLoadingId = beginYtIniLoading(); setYtIniStatus(null); try { const params = new URLSearchParams({ process: targetPm2 }); await fetchJson(`/save_config?${params}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content }), }); setYoutubeIniText(content); patchChannelLocalForPm2(targetPm2, { streamKey: parseYoutubeIniFields(content).key }); setYtIniStatus(t("youtube.ini 已保存", "youtube.ini saved")); } catch (e) { setYtIniStatus((e as Error).message); } finally { finishYtIniLoading(iniLoadingId); } }; const saveProLaneSettings = useCallback(async () => { if (!active) return; setLaneSaving(true); setLaneStatus(null); try { const saved = await persistActiveLaneDraft(); currentProcRef.current = saved.pm2; setCurrentProc(saved.pm2); const base = parseYoutubeIniFields(youtubeIniText || buildYoutubeIniFromFields(ytFields)); const draft = laneDrafts[active.id] ?? laneDraftFromChannel(active); const body = buildYoutubeIniFromFields({ key: (draft.streamKey || activeLaneValidation.normalizedStreamKey || "").trim(), rtmps: base.rtmps, bitrate: base.bitrate, fastAudio: base.fastAudio, }); await saveYoutubeIniToServer(body, saved.pm2); setLaneStatus(t("线路设置与推流配置已保存", "Lane settings and stream config saved")); } catch (e) { const message = (e as Error).message; setLaneStatus(message); notify(message); } finally { setLaneSaving(false); } }, [ active, activeLaneValidation.normalizedStreamKey, laneDrafts, notify, persistActiveLaneDraft, setCurrentProc, t, youtubeIniText, ytFields, ]); const applyFieldsAndSave = async () => { const body = buildYoutubeIniFromFields(ytFields); await saveYoutubeIniToServer(body); }; const applyYoutubeBalancedPreset = async () => { ytIniRequestSeqRef.current += 1; const iniLoadingId = beginYtIniLoading(); setYtIniStatus(null); try { const source = youtubeIniText || buildYoutubeIniFromFields(ytFields); const data = await fetchJson<{ message?: string; content?: string }>("/config_optimize", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ root: "app-config", path: managedYoutubeIniRelPathForPm2(currentProcRef.current), content: source, action: "youtube_balanced_preset", }), }); const next = data.content ?? source; setYoutubeIniText(next); setYtFields(parseYoutubeIniFields(next)); setYtIniStatus(data.message || t("已应用 YouTube 预设", "Applied YouTube preset")); } catch (e) { setYtIniStatus((e as Error).message); } finally { finishYtIniLoading(iniLoadingId); } }; const syncFieldsFromText = () => { setYtFields(parseYoutubeIniFields(youtubeIniText)); setYtIniStatus(t("已从下方原文同步到表单", "Synced from raw")); }; const keySuffixUi = useMemo(() => { if (mode === "single") { return parseYoutubeStreamKeySuffix(`key = ${ytFields.key}`); } const k = activeLaneDraft?.streamKey ?? active?.streamKey ?? ""; return parseYoutubeStreamKeySuffix(`key = ${k}`); }, [mode, active?.streamKey, ytFields.key, activeLaneDraft?.streamKey]); const keySuffixDisplay = keySuffixUi ? `…${keySuffixUi}` : "—"; const saveProUrlAndServer = async () => { if (!active) { const message = t("请选择线路后再保存地址", "Pick a lane before saving URLs"); setLaneStatus(message); notify(message); return; } if (urlSaveBlockedReason) { setLaneStatus(urlSaveBlockedReason); notify(urlSaveBlockedReason); return; } try { setLaneSaving(true); setLaneStatus(null); urlRequestSeqRef.current += 1; const latestProUrlDraft = proUrlDraftRef.current; const saved = await persistActiveLaneDraft(); currentProcRef.current = saved.pm2; setCurrentProc(saved.pm2); await Promise.resolve(onSaveUrlConfig(latestProUrlDraft, saved.pm2)); urlListDirtyRef.current = false; setLaneStatus(t("线路与地址已保存", "Lane settings and URLs saved")); } catch (e) { const message = e instanceof Error ? e.message : String(e); setLaneStatus(message); notify(message); } finally { setLaneSaving(false); } }; const saveSingleUrlAndClearDirty = async () => { if (urlSaveBlockedReason) { notify(urlSaveBlockedReason); return; } const targetPm2 = currentProcRef.current.trim(); if (!targetPm2) { notify(t("请选择进程", "Pick a process")); return; } try { urlRequestSeqRef.current += 1; await Promise.resolve(onSaveUrlConfig(singleUrlDraftRef.current, targetPm2)); patchChannelLocalForPm2(targetPm2, { urlLines: singleUrlDraftRef.current }); urlListDirtyRef.current = false; } catch { /* parent 已 toast */ } }; const dedupeUrlDraft = async () => { const source = mode === "single" ? singleUrlDraftRef.current : proUrlDraftRef.current; setUrlOptimizing(true); setUrlFetchNote(null); try { const data = await fetchJson<{ message?: string; content?: string }>("/config_optimize", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ root: "app-config", path: managedUrlConfigRelPathForPm2(currentProcRef.current), content: source, action: "dedupe_urls", }), }); const next = data.content ?? source; if (mode === "single") applySingleUrlDraft(next); else { applyProUrlDraft(next); } urlListDirtyRef.current = true; setUrlFetchNote(data.message || t("已去重当前 URL 列表", "Deduplicated current URL list")); } catch (e) { setUrlFetchNote((e as Error).message); } finally { setUrlOptimizing(false); } }; const pushProStreamKeyToServer = async () => { if (!active || !activeLaneDraft) return; const base = parseYoutubeIniFields(youtubeIniText || buildYoutubeIniFromFields(ytFields)); const f: YoutubeIniFields = { key: activeLaneDraft.streamKey.trim(), rtmps: base.rtmps, bitrate: base.bitrate, fastAudio: base.fastAudio, }; const body = buildYoutubeIniFromFields(f); setLaneSaving(true); setLaneStatus(null); try { const saved = await persistActiveLaneDraft(); currentProcRef.current = saved.pm2; setCurrentProc(saved.pm2); await saveYoutubeIniToServer(body, saved.pm2); setLaneStatus(t("线路设置与 youtube.ini 已保存", "Lane settings and youtube.ini saved")); } catch (e) { const message = (e as Error).message; setLaneStatus(message); notify(message); } finally { setLaneSaving(false); } }; const currentUrlDraft = mode === "single" ? singleUrlDraft : proUrlDraft; const currentUrlCount = useMemo(() => nonCommentUrlLinesOf(currentUrlDraft).length, [currentUrlDraft]); const currentDouyinCount = useMemo(() => extractDouyinLiveUrls(currentUrlDraft).length, [currentUrlDraft]); const nekoLinks = useMemo(() => extractNekoBrowserLinks(quickLinks), [quickLinks]); const selectedNeko = useMemo( () => resolveNekoBrowserLink(nekoLinks, mode === "pro" && active ? channels.findIndex((row) => row.id === active.id) : 0), [active, channels, mode, nekoLinks], ); const selectedNekoUrl = selectedNeko.link ? normalizeBrowserReachableHttpUrl(selectedNeko.link.url) : normalizeBrowserReachableHttpUrl("http://live.local:9200/"); const nekoPortsLabel = useMemo(() => formatNekoPorts(nekoLinks), [nekoLinks]); const laneQuickLinks = useMemo( () => [selectedNeko.link?.url, quickLinks?.chromium_remote_debug, quickLinks?.srs_api].filter((value): value is string => !!value), [quickLinks, selectedNeko.link?.url], ); const runNekoAction = useCallback( async (link: NekoBrowserLink, action: NekoAction) => { if (nekoBusy) return; if (action === "delete") { const ok = window.confirm(`${link.label}: 删除容器?浏览器配置和登录数据会保留,之后点“启动”会自动重建。`); if (!ok) return; } const busyKey = `${link.id}:${action}`; setNekoBusy(busyKey); setNekoActionNote(null); try { const result = await fetchJson("/neko/instance_action", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: link.id, action }), }); const state = result.running ? t("运行中", "running") : result.exists ? t("已停止", "stopped") : t("容器不存在", "missing"); const message = result.message || `${link.label}: ${state}`; setNekoActionNote(`${message} · ${state}`); await onRefresh?.(); } catch (e) { const message = (e as Error).message; setNekoActionNote(message); notify(message); } finally { setNekoBusy(null); } }, [fetchJson, nekoBusy, notify, onRefresh, t], ); const flushProChannelsBeforeRun = useCallback( async (targetPm2: string) => { const next = channels; const activePm2 = active ? resolveChannelPm2(active) : ""; if (active && targetPm2 === activePm2) { const saved = await persistActiveLaneDraft(); return saved; } applyChannelsLocal(next); await syncChannelsRemote(next, { force: true }); return { next, savedLane: active ?? null, pm2: targetPm2, }; }, [active, applyChannelsLocal, channels, persistActiveLaneDraft, syncChannelsRemote], ); const runProProcess = useCallback( async (action: "start" | "stop" | "restart", targetPm2: string) => { const targetMatchesActiveLane = !!active && resolveChannelPm2(active) === targetPm2; if (action !== "stop") { let next = channels; let effectivePm2 = targetPm2; try { const saved = await flushProChannelsBeforeRun(targetPm2); next = saved.next; effectivePm2 = saved.pm2; } catch (e) { notify( `${t("当前线路保存失败", "Failed to save the active lane")}: ${(e as Error).message}`, ); return; } const target = next.find( (row) => resolveChannelPm2(row) === effectivePm2, ); const urlText = target?.urlLines ?? ""; if (!((target?.streamKey ?? "").trim())) { notify(t("请先填写当前线路的推流密钥", "Fill the stream key before starting")); return; } if (!nonCommentUrlLinesOf(urlText).length) { notify(t("请先填写当前线路的直播地址", "Fill the source URLs before starting")); return; } targetPm2 = effectivePm2; } if (targetMatchesActiveLane) { setCurrentProc(targetPm2); } onRunProcess(action, targetPm2); }, [active, channels, flushProChannelsBeforeRun, notify, onRunProcess, setCurrentProc, t], ); const refreshLiveEvents = useCallback( async (detailId?: number | null) => { setLiveEventLoading(true); try { const summary = await fetchJson("/hub/youtube/live/summary"); setLiveEventSummary(summary); const active = summary.active || []; const selectedPm2 = currentProcRef.current.trim(); const autoPick = detailId ?? (selectedPm2 ? active.find((event) => event.process === selectedPm2)?.id : undefined) ?? active[0]?.id ?? selectedLiveEvent?.id; if (autoPick) { const detail = await fetchJson<{ event?: YoutubeLiveEvent }>( `/hub/youtube/live/events/${encodeURIComponent(String(autoPick))}`, ); if (detail.event) setSelectedLiveEvent(detail.event); } } catch { /* keep last known event state */ } finally { setLiveEventLoading(false); } }, [fetchJson, selectedLiveEvent?.id], ); const openLiveEventDetail = useCallback( async (eventId: number) => { setLiveEventLoading(true); try { const detail = await fetchJson<{ event?: YoutubeLiveEvent }>(`/hub/youtube/live/events/${encodeURIComponent(String(eventId))}`); setSelectedLiveEvent(detail.event || null); } catch (e) { notify((e as Error).message); } finally { setLiveEventLoading(false); } }, [fetchJson, notify], ); const activeLiveEventCount = liveEventSummary?.active?.length ?? 0; const liveEventsPollIntervalMs = useMemo( () => liveEventsPollMs({ activeEvents: activeLiveEventCount, pageVisible }), [activeLiveEventCount, pageVisible], ); useEffect(() => { if (HIDE_YOUTUBE_LIVE_EVENT_HUB) return; void refreshLiveEvents(null); if (liveEventsPollIntervalMs <= 0) return; const id = window.setInterval(() => void refreshLiveEvents(), liveEventsPollIntervalMs); return () => window.clearInterval(id); }, [liveEventsPollIntervalMs, refreshLiveEvents]); useEffect(() => { const onVis = () => { if (document.visibilityState !== "visible") return; void refreshLiveEvents(null); }; document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, [refreshLiveEvents]); const refreshQualityGuard = useCallback(async () => { setQualityGuardLoading(true); try { const report = await fetchJson("/hub/youtube/quality_guard"); setQualityGuard(report); } catch { /* keep last known guard state */ } finally { setQualityGuardLoading(false); } }, [fetchJson]); const qualityGuardPushCount = qualityGuard?.summary?.pushing_lanes ?? 0; const qualityGuardPollIntervalMs = useMemo( () => qualityGuardPollMs({ pushingLanes: qualityGuardPushCount, pageVisible }), [qualityGuardPushCount, pageVisible], ); useEffect(() => { if (HIDE_YOUTUBE_QUALITY_GUARD) return; void refreshQualityGuard(); if (qualityGuardPollIntervalMs <= 0) return; const id = window.setInterval(() => void refreshQualityGuard(), qualityGuardPollIntervalMs); return () => window.clearInterval(id); }, [qualityGuardPollIntervalMs, refreshQualityGuard]); useEffect(() => { const onVis = () => { if (document.visibilityState !== "visible") return; void refreshQualityGuard(); }; document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, [refreshQualityGuard]); const lock = !!busy || ytIniLoading || urlReloading || urlOptimizing || laneSaving; const proLaneActionLock = !!busy || laneSaving; const urlSaveBlockedReason = ytIniLoading ? t("正在读取 youtube.ini,稍后再保存地址", "youtube.ini is loading; save URLs after it finishes") : urlReloading ? t("正在重新读取地址列表,稍后再保存", "URL list is reloading; save after it finishes") : urlOptimizing ? t("正在整理地址列表,稍后再保存", "URL list is being optimized; save after it finishes") : busy ? t("正在执行其他操作,稍后再保存地址", "Another operation is running; save URLs after it finishes") : ""; const singleRow = mode === "single" ? runtimeLogRow : currentProcRow; const statusLogActivity = useMemo(() => { if (mode === "pro") { return classifyProcessMonitorActivity(liveProcesses.filter((row) => isYoutubeRow(row))); } return classifyRowActivity(runtimeLogRow); }, [mode, liveProcesses, runtimeLogRow]); const statusCardPollMs = useMemo( () => statusPollMs({ activity: statusLogActivity, pageVisible }), [statusLogActivity, pageVisible], ); const singleOnline = pm2StatusOnline(statusForPm2(singleRuntimeProc)); const singlePushing = procStartBlocked(singleRow); const activeSourceDisplay = active ? douyinSourceDisplayFor(rowForPm2(resolveChannelPm2(active)), proUrlDraft || active.urlLines || "") : ""; const overviewRow = runtimeLogRow; const overviewPushing = isLivePushingRow(overviewRow); const overviewActiveEvent = useMemo(() => { const active = liveEventSummary?.active || []; const selectedPm2 = currentProc.trim(); if (!selectedPm2) return active[0] ?? null; return active.find((event) => event.process === selectedPm2) ?? active[0] ?? null; }, [currentProc, liveEventSummary?.active]); const monitorUrlDraft = useMemo(() => { if (mode === "single") return singleUrlDraft; const ch = channels.find((c) => resolveChannelPm2(c) === runtimeLogProc); if (ch && ch.id === active?.id) return proUrlDraft; return (ch?.urlLines ?? "").trim() || proUrlDraft; }, [active?.id, channels, mode, proUrlDraft, runtimeLogProc, singleUrlDraft]); const overviewChannel = mode === "pro" ? channels.find((channel) => resolveChannelPm2(channel) === runtimeLogProc) : null; const overviewLaneIndex = overviewChannel ? channels.findIndex((channel) => channel.id === overviewChannel.id) : -1; const overviewLaneName = overviewChannel ? cleanLaneName(overviewChannel.name, overviewLaneIndex >= 0 ? overviewLaneIndex : 0) : ""; const overviewSource = proLanePrimaryTitle(overviewLaneName, overviewRow, monitorUrlDraft); const overviewDouyinSubtitle = proLaneDouyinSubtitle(overviewRow, monitorUrlDraft, overviewLaneName); const overviewStatusLabel = proLaneStatusLabel(overviewRow, t); const overviewSourceUrl = douyinSourceUrlFor(overviewRow, monitorUrlDraft); const overviewQualityLane = qualityGuard?.lanes?.find((lane) => lane.process === runtimeLogProc); const overviewLiveMetrics = qualityLaneMetrics(overviewRow, overviewQualityLane); const overviewQualityScore = overviewQualityLane?.score ?? null; const overviewPushingLanes = mode === "pro" ? liveProcesses.filter((row) => isYoutubeRow(row) && isLivePushingRow(row)).length : overviewPushing ? 1 : 0; const overviewFfmpegSpeed = formatFfmpegMetricValue(overviewLiveMetrics.speed, "x"); const overviewFfmpegFrame = formatFfmpegMetricValue(overviewLiveMetrics.frame, "", 0); const overviewFfmpegFps = formatFfmpegMetricValue(overviewLiveMetrics.fps); const overviewBitrate = overviewLiveMetrics.live ? formatBitrateLabel(overviewLiveMetrics.bitrate) : null; const overviewEncodedDuration = typeof overviewRow?.ffmpeg_time_seconds === "number" ? fmtDurationHuman(overviewRow.ffmpeg_time_seconds, t) : null; const configNeedsAttention = !keySuffixUi || currentDouyinCount === 0; const overviewKeyHelper = !keySuffixUi ? t("检查密钥", "Check key") : ytFields.rtmps ? "RTMPS" : "RTMP"; const renderNekoLinkControl = (link: NekoBrowserLink) => { const activeNeko = selectedNeko.link?.id === link.id; const startBusy = nekoBusy === `${link.id}:start`; const stopBusy = nekoBusy === `${link.id}:stop`; const deleteBusy = nekoBusy === `${link.id}:delete`; const disabled = !!nekoBusy; const canDelete = link.id === nekoLinks.length && nekoLinks.length > 1; const deleteDisabled = disabled || !canDelete; return (
{link.label} {link.accessLabel} {link.host || ""} {link.port ? `:${link.port}` : ""}
); }; const urlToolbar = (
); const activeEvents = liveEventSummary?.active || []; const latestEvents = liveEventSummary?.latest || []; const latestAlerts = liveEventSummary?.alerts || []; const liveEventStats = liveEventSummary?.stats || {}; const liveEventStatCards = [ { label: t("活动事件", "Active"), value: liveEventStats.active_events ?? activeEvents.length, Icon: Activity }, { label: t("历史事件", "History"), value: liveEventStats.total_events ?? latestEvents.length, Icon: History }, { label: t("采样点", "Samples"), value: liveEventStats.sample_count ?? 0, Icon: Database }, { label: t("峰值在线", "Viewer peak"), value: liveEventStats.viewer_peak ?? 0, Icon: Eye }, { label: t("累计时长", "Total duration"), value: fmtEventDuration(liveEventStats.total_duration_seconds), Icon: Clock }, ]; const liveEventPanel = (

{t("直播事件中枢", "Live event center")}

{t("事件、转播对象、时长、页面采集、弹窗和告警全部写入本地 SQLite,可追溯。", "Events, source rooms, duration, browser telemetry, popups, and alerts are stored locally.")}

{liveEventStatCards.map(({ label, value, Icon }) => (
{label}

{String(value)}

))}

{t("正在转播", "Active relay")}

{activeEvents.length}
{(activeEvents.length ? activeEvents : latestEvents.slice(0, 1)).map((event) => ( ))} {!activeEvents.length && !latestEvents.length ? (

{t("暂无事件;开始直播或打开 Neko 中的 YouTube Studio 后会自动生成。", "No events yet. Start a relay or open YouTube Studio in Neko.")}

) : null}

{t("最近事件", "Recent events")}

{latestEvents.slice(0, 8).map((event) => ( ))}

{t("事件详情页", "Event detail")}

{selectedLiveEvent ? ( ) : null}
{selectedLiveEvent ? (

{selectedLiveEvent.source_title || selectedLiveEvent.source_room_id || selectedLiveEvent.process}

{selectedLiveEvent.status}

Process: {selectedLiveEvent.process || "-"}

Room: {selectedLiveEvent.source_room_id || "-"}

Started: {fmtEventTime(selectedLiveEvent.started_at)}

Duration: {fmtEventDuration(selectedLiveEvent.duration_seconds)}

Viewers: {selectedLiveEvent.last_viewer_count ?? "-"} / peak {selectedLiveEvent.viewer_peak ?? 0}

Health: {selectedLiveEvent.last_health || selectedLiveEvent.last_live_status || "-"}

{selectedLiveEvent.source_url ? ( {t("打开源直播间", "Open source")} ) : null} {selectedLiveEvent.last_page_url ? ( {t("打开 Studio 页面", "Open Studio page")} ) : null}
{(selectedLiveEvent.alerts || latestAlerts).slice(0, 4).length ? (
{t("弹窗 / 告警", "Popups / alerts")}
{(selectedLiveEvent.alerts || latestAlerts).slice(0, 4).map((alert, idx) => (

{alert.title || alert.severity || "alert"}: {alert.message || "-"}

))}
) : null}
{t("采样时间线", "Sample timeline")}
{(selectedLiveEvent.samples || []).slice(0, 12).map((sample) => (
{fmtEventTime(sample.ts)} {sample.source || "sample"}

{sample.live_status || "-"} · {sample.health || "-"} · {sample.viewer_count ?? "-"} online

{sample.popup_text ?

{sample.popup_text}

: null}
))} {!(selectedLiveEvent.samples || []).length ? (

{t("暂无采样;Chrome 扩展或状态接口会自动写入。", "No samples yet. The Chrome extension or status API will fill this.")}

) : null}
) : (

{t("选择左侧事件查看完整详情。", "Select an event to see details.")}

)}
); const humanEventRows = [ ...activeEvents, ...latestEvents.filter((event) => !activeEvents.some((activeEvent) => activeEvent.id === event.id)), ].slice(0, 12); const focusedLiveEvent = selectedLiveEvent || humanEventRows[0] || null; const focusedSamples = focusedLiveEvent?.samples || []; const focusedAlerts = focusedLiveEvent?.alerts?.length ? focusedLiveEvent.alerts : latestAlerts; const humanLiveEventStats = [ { label: t("正在直播", "Live now"), value: String(liveEventStats.active_events ?? activeEvents.length), helper: t("当前仍在推流的场次", "Events still pushing"), Icon: Radio, tone: "text-emerald-200", }, { label: t("总场次", "Total events"), value: String(liveEventStats.total_events ?? latestEvents.length), helper: t("本机数据库里的直播记录", "Stored locally"), Icon: History, tone: "text-cyan-200", }, { label: t("累计时长", "Total duration"), value: fmtDurationHuman(liveEventStats.total_duration_seconds, t), helper: t("已结束场次累计", "Ended events total"), Icon: Clock, tone: "text-violet-200", }, { label: t("最高在线", "Peak viewers"), value: viewerText(liveEventStats.viewer_peak ?? 0, t), helper: t("Chrome/Studio 采集峰值", "Captured from Studio"), Icon: Eye, tone: "text-amber-200", }, ]; const humanLiveEventPanel = (

{t("直播事件中枢", "Live event center")}

{t( "这里按运营视角展示:谁在播、转播哪个直播间、播了多久、观众多少、Studio 是否弹窗、有没有异常。机器编号只放在详情底部。", "Built for operators: what is live, source room, duration, viewers, Studio popups, and issues. Technical ids stay in the detail footer.", )}

{humanLiveEventStats.map(({ label, value, helper, Icon, tone }) => (

{label}

{value}

{helper}

))}

{activeEvents.length ? t("正在直播", "Live now") : t("最近直播记录", "Recent live events")}

{activeEvents.length ? t("优先显示还在推流的场次。", "Active relays are listed first.") : t("当前没有正在直播的场次,下方是最近历史。", "Nothing is live now; showing recent history.")}

{humanEventRows.length} {t("条记录", "records")}
{humanEventRows.map((event) => { const selected = focusedLiveEvent?.id === event.id; return ( ); })} {!humanEventRows.length ? (

{t("还没有直播记录", "No live events yet")}

{t("启动转播或在 Neko 打开 YouTube Studio 后,这里会自动生成可追溯记录。", "Start a relay or open YouTube Studio in Neko to create traceable records.")}

) : null}
{focusedLiveEvent ? (

{t("这场直播", "Selected event")}

{eventTitleText(focusedLiveEvent, t)}

{eventSourceText(focusedLiveEvent, t)} {"->"} YouTube

{eventStatusText(focusedLiveEvent.status, t)}

{t("直播时长", "Duration")}

{fmtDurationHuman(focusedLiveEvent.duration_seconds, t)}

{fmtEventTime(focusedLiveEvent.started_at)}

{t("观众", "Viewers")}

{viewerText(focusedLiveEvent.last_viewer_count, t)} {t("峰值", "peak")} {viewerText(focusedLiveEvent.viewer_peak ?? 0, t)}

{t("来自 Chrome 插件/Studio 页面采集", "Captured from Studio")}

{t("Studio 状态", "Studio status")}
{eventRiskText(focusedLiveEvent, t)}

{focusedLiveEvent.last_live_status || focusedLiveEvent.last_health || t("暂未采集到 Studio 状态", "No Studio status captured yet")}

{focusedLiveEvent.last_popup_text ? (

{focusedLiveEvent.last_popup_text}

) : (

{t("没有记录到弹窗。", "No popup recorded.")}

)} {focusedLiveEvent.last_page_title || focusedLiveEvent.last_page_url ? (

{focusedLiveEvent.last_page_title || focusedLiveEvent.last_page_url}

) : null}
{focusedLiveEvent.source_url ? ( {t("打开源直播间", "Open source")} ) : null} {focusedLiveEvent.last_page_url ? ( {t("打开 Studio", "Open Studio")} ) : null}
{t("采样时间线", "Telemetry timeline")}
{focusedSamples.slice(0, 10).map((sample) => (
{fmtShortTime(sample.ts)} {sample.source || t("采样", "sample")}

{(sample.live_status || sample.health || t("状态未识别", "Unknown status"))} {t("在线", "online")} {viewerText(sample.viewer_count, t)}

{sample.popup_text ?

{sample.popup_text}

: null}
))} {!focusedSamples.length ? (

{selectedLiveEvent ? t("这场直播暂时没有采样明细。", "No telemetry samples for this event yet.") : t("点击左侧记录后加载完整采样明细。", "Click a record on the left to load full telemetry samples.")}

) : null}
{t("告警和弹窗", "Alerts and popups")}
{focusedAlerts.slice(0, 4).map((alert, idx) => (

{(alert.title || alert.severity || t("提示", "Notice"))}: {alert.message || "-"}

))} {!focusedAlerts.length ?

{t("没有告警。", "No alerts.")}

: null}

{t("技术标识", "Technical id")}: #{focusedLiveEvent.id} · {focusedLiveEvent.process || "-"} · {focusedLiveEvent.event_uuid || "-"}

) : (

{t("等待第一场直播", "Waiting for the first live event")}

{t("开始转播后,这里会变成这场直播的详情页。", "After a relay starts, this panel becomes the event detail page.")}

)}
); const qualitySummary = qualityGuard?.summary || {}; const qualityLanes = qualityGuard?.lanes || []; const qualityRecommendations = qualityGuard?.recommendations || []; const qualityGuardPanel = (

{t("算法友好质量守护", "Algorithm-friendly quality guard")}

{t( "目标不是刷数据,而是让直播信号长期稳定:不断流、不卡顿、Studio 状态可见、异常能追踪。", "The goal is stable, policy-safe signal quality: no drops, no stalls, visible Studio state, and traceable issues.", )}

{t("综合分", "Score")}

{qualityGuard?.score ?? 0}

{t("80 以上适合长时间无人值守", "80+ is suitable for long unattended runs")}

{[ [t("推流线路", "Lanes"), `${qualitySummary.pushing_lanes ?? 0}/${qualitySummary.lanes ?? 0}`], [t("活动事件", "Active events"), String(qualitySummary.active_events ?? 0)], [t("Studio 采样", "Studio samples"), String(qualitySummary.sample_count ?? 0)], [t("最高在线", "Viewer peak"), viewerText(qualitySummary.viewer_peak ?? 0, t)], ].map(([label, value]) => (

{label}

{value}

))}

{t("线路质量", "Lane quality")}

{t("从进程、FFmpeg 日志、配置和事件采样综合判断。", "Combined from process state, FFmpeg logs, config, and event telemetry.")}

{qualityLanes.map((lane) => { const laneLabelName = (lane.label || "").replace(/^YouTube Pro\s*·\s*/i, "").trim(); const laneRow = rowForPm2(String(lane.process || "")); const laneLiveMetrics = qualityLaneMetrics(laneRow, lane); const laneDisplay = (lane.source_display || lane.source_title || "").trim() || laneLabelName || lane.label || lane.process || "-"; const laneDouyinSubtitle = lane.is_pushing && laneLabelName && laneDisplay !== laneLabelName ? laneLabelName : ""; const laneTech = [lane.label, lane.process].filter(Boolean).join(" · "); return (

{laneDisplay}

{lane.is_pushing ? t("推流中", "Pushing") : t("未推流", "Idle")} {lane.rtmps ? "RTMPS" : t("非 RTMPS", "No RTMPS")}
{laneDouyinSubtitle && laneDouyinSubtitle !== laneDisplay ? (

{laneDouyinSubtitle}

) : null}

{laneTech || "-"}

{(lane.issues || []).slice(0, 3).map((issue, idx) => ( {issue.text || issue.level} ))}

{t("分数", "Score")}

{lane.score ?? 0}

fps{formatFfmpegMetricValue(laneLiveMetrics.fps)}

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

{t("码率", "Bitrate")} {lane.is_pushing ? formatBitrateLabel(laneLiveMetrics.bitrate) ?? "—" : "—"}

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

drop{lane.metrics?.drop ?? "-"}

urls{lane.url_count ?? 0}

err{lane.metrics?.error_count ?? 0}

); })} {!qualityLanes.length ? (
{t("没有发现 YouTube 线路。", "No YouTube lanes found.")}
) : null}

{t("下一步建议", "Next actions")}

{qualityRecommendations.slice(0, 6).map((item, idx) => (

{item.text || "-"}

))} {!qualityRecommendations.length ?

{t("暂无建议。", "No recommendations.")}

: null}

FFmpeg

{qualityGuard?.ffmpeg_profile?.target || "720p30 H.264 CBR / RTMPS / AAC 128k"}

    {(qualityGuard?.ffmpeg_profile?.guardrails || []).slice(0, 4).map((item) => (
  • - {item}
  • ))}
); const statusOverviewPanel = (
{overviewPushing ? ( ) : null}

{t("转播实况", "Relay snapshot")}

{overviewStatusLabel}

{overviewSource || t("未配置抖音直播源", "No Douyin source configured")}

{overviewDouyinSubtitle && overviewDouyinSubtitle !== overviewSource ? (

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

) : null}

{runtimeLogProc || "—"} {mode === "pro" && overviewPushingLanes > 0 ? ` · ${overviewPushingLanes}/${channels.length} ${t("路推流中", "lanes pushing")}` : ""}

{overviewSourceUrl ? ( {t("打开源站", "Open source")} ) : null} {selectedNeko.link ? ( {t("Studio", "Studio")} ) : null}
{[ { label: t("FFmpeg 速度", "FFmpeg speed"), value: overviewFfmpegSpeed, warn: overviewLiveMetrics.speedLow, helper: overviewLiveMetrics.live ? overviewEncodedDuration ? `${t("已编码", "Encoded")} ${overviewEncodedDuration}` : t("实时倍速", "Realtime multiplier") : t("等待进程上报", "Waiting for metrics"), accent: overviewLiveMetrics.speedLow ? "amber" as const : "emerald" as const, }, { label: t("实时 FPS", "Live FPS"), value: overviewFfmpegFps, warn: typeof overviewLiveMetrics.fps === "number" && overviewLiveMetrics.fps > 0 && overviewLiveMetrics.fps < 24, helper: overviewLiveMetrics.live ? t("FFmpeg 输出帧率", "FFmpeg output fps") : t("未推流", "Not pushing"), accent: "cyan" as const, }, { label: t("编码帧", "Encoded frame"), value: overviewFfmpegFrame, warn: overviewLiveMetrics.progressStalled, helper: overviewRow?.ffmpeg_active ? t("Worker 活跃", "Worker active") : t("无活跃 Worker", "No active worker"), accent: overviewLiveMetrics.progressStalled ? "amber" as const : "violet" as const, }, { label: t("码率", "Bitrate"), value: overviewBitrate ?? "—", warn: false, helper: overviewLiveMetrics.live ? t("实时输出码率", "Live output bitrate") : t("停推后不显示", "Hidden when idle"), accent: "cyan" as const, }, { label: t("质量分", "Quality score"), value: overviewQualityScore != null ? String(overviewQualityScore) : "—", warn: overviewQualityScore != null && overviewQualityScore < 55, helper: t("当前线路综合评估", "Current lane score"), accent: "violet" as const, }, { label: t("活动场次", "Active events"), value: String(activeLiveEventCount), warn: false, helper: t("本地事件库", "Local event store"), accent: "cyan" as const, }, { label: t("抖音地址", "Douyin URLs"), value: String(currentDouyinCount), warn: currentDouyinCount === 0, helper: `${currentUrlCount} ${t("条有效地址", "valid URLs")}`, accent: "cyan" as const, }, { label: t("密钥尾码", "Key suffix"), value: keySuffixDisplay, warn: !keySuffixUi, helper: overviewKeyHelper, accent: "violet" as const, }, ].map(({ label, value, warn, helper, accent }) => ( ))}
{overviewActiveEvent && overviewPushing ? (
{t("本场直播", "This event")} {eventStatusText(overviewActiveEvent.status, t)} {eventRiskText(overviewActiveEvent, t)} {t("观众", "Viewers")} {viewerText(overviewActiveEvent.last_viewer_count, t)} {" · "} {fmtDurationHuman(overviewActiveEvent.duration_seconds, t)} {overviewActiveEvent.last_popup_text ? ( {t("弹窗", "Popup")}: {overviewActiveEvent.last_popup_text} ) : null}
) : null}
); return (
{onNavigate ? ( ) : null}

{t("YouTube 无人直播", "YouTube unmanned live")}

{t( "单路一条流;多路时每条线路独立保存自己的密钥、URL 列表和 PM2 任务。填好后保存,再点「开始」。Neko 浏览器仅作辅助工作室,不再阻塞推流。", "Single lane or multi-lane: every lane keeps its own key, URL list, and PM2 task. Save, then Start. Neko is optional browser tooling and no longer blocks streaming.", )}

{!HIDE_YOUTUBE_RELAY_SNAPSHOT ? statusOverviewPanel : null} {laneQuickLinks.length ? (
{nekoActionNote ?

{nekoActionNote}

: null}
{selectedNeko.link ? ( {t("打开当前线路 Neko 工作室", "Open lane Neko studio")} ) : null} {nekoLinks.length ? (
{nekoLinks.map((link) => renderNekoLinkControl(link))}
) : null} {quickLinks?.chromium_remote_debug ? ( {t("打开 Chromium 调试", "Open Chromium debug")} ) : null} {quickLinks?.srs_api ? ( {t("打开 SRS API", "Open SRS API")} ) : null}
) : null}

{t("直播开关", "Live control")}

{mode === "single" ? ( <>
onRunProcess("start", singleRuntimeProc)} notify={notify} t={t} /> onRunProcess("stop", singleRuntimeProc)} notify={notify} t={t} /> onRunProcess("restart", singleRuntimeProc)} notify={notify} t={t} />
{businessStatusLabel(singleRow, t)} {typeof singleRow?.ffmpeg_speed === "number" ? ( speed {singleRow.ffmpeg_speed.toFixed(2)}x ) : null} {typeof singleRow?.ffmpeg_frame === "number" ? ( frame {singleRow.ffmpeg_frame} ) : null}
) : ( <>

{t("Pro 转播实况", "Pro relay status")}

{t("对齐桌面端:每路独立 URL / youtube 配置文件;点左侧信息切换编辑,右侧控制进程。", "Per-lane config files like desktop; click row info to edit, use right-side controls for PM2.")}

{nekoPortsLabel ? (

{t("Neko 实例", "Neko instances")}: {nekoPortsLabel}

) : null}
{channels.map((c) => { const pm = resolveChannelPm2(c); const row = rowForPm2(pm); const st = statusForPm2(pm); const sel = activeCh === c.id; const laneUrlText = sel ? proUrlDraft : (c.urlLines ?? "").trim(); const laneKeyText = sel ? activeLaneDraft?.streamKey ?? c.streamKey ?? "" : c.streamKey ?? ""; const laneUrls = nonCommentUrlLinesOf(laneUrlText); const douyinUrls = extractDouyinLiveUrls(laneUrlText); const dUrl = douyinSourceUrlFor(row, laneUrlText); const suf = parseYoutubeStreamKeySuffix(`key = ${laneKeyText}`); const rowOnline = pm2StatusOnline(st); const rowPushing = procStartBlocked(row); const laneIndex = channels.findIndex((row) => row.id === c.id); const laneNeko = resolveNekoBrowserLink(nekoLinks, laneIndex).link; const laneName = cleanLaneName(c.name, laneIndex >= 0 ? laneIndex : 0); const laneQuality = qualityGuard?.lanes?.find((lane) => lane.process === pm); const laneDisplay = proLanePrimaryTitle(laneName, row, laneUrlText, laneQuality); const laneDouyinSubtitle = proLaneDouyinSubtitle(row, laneUrlText, laneName); const laneStatusLabel = proLaneStatusLabel(row, t); const laneLiveMetrics = qualityLaneMetrics(row, laneQuality); const laneStatsText = formatFfmpegStatsBrief(laneLiveMetrics, { live: laneLiveMetrics.live || isLivePushingRow(row), }); return (
e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} > void runProProcess("start", pm)} notify={notify} t={t} compact /> void runProProcess("stop", pm)} notify={notify} t={t} compact /> void runProProcess("restart", pm)} notify={notify} t={t} compact /> {laneNeko ? ( ) : null}
); })}
)}
{!HIDE_YOUTUBE_LIVE_PROCESS_LOG ? ( ) : null} {!HIDE_YOUTUBE_QUALITY_GUARD ? qualityGuardPanel : null} {!HIDE_YOUTUBE_LIVE_EVENT_HUB ? humanLiveEventPanel || liveEventPanel : null}

{t("配置与地址", "Config and URLs")} {configNeedsAttention ? ( {t("待完善", "Needs setup")} ) : null}

{t("密钥、youtube.ini、URL 列表", "Keys, youtube.ini, URL list")}

{mode === "single" ? (

{t("YouTube 相关设置", "YouTube settings")}

{t("串流参数写进 youtube.ini,无需 Google 登录。", "Stream settings go to youtube.ini — no Google login.")}

setYtFields((f) => ({ ...f, key: e.target.value }))} placeholder="xxxx-xxxx-xxxx-xxxx-xxxx" />
{t("高级:youtube.ini 原文", "Raw youtube.ini")}