sh2/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx
eric 9888f1daad Harden YouTube unmanned live stack and hide advanced console panels.
Fix Pro config SSOT, event FSM, FFmpeg error tiers, relay heartbeat, and ingest auth while keeping relay snapshot, quality guard, and event hub hidden in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-23 06:31:31 -05:00

3781 lines
161 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { Activity, AlertTriangle, Ban, Clock, Database, ExternalLink, Eye, History, Loader2, MonitorPlay, Play, Plus, Radio, RefreshCw, 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;
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<string, ProLaneDraft> {
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_slow" ||
business === "source_stalled"
);
}
function proLaneStatusLabel(row: LiveProcRow | undefined, t: TFn): string {
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 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 (
<div className="group relative overflow-hidden rounded-xl border border-white/[0.06] bg-black/25 p-3 min-w-0 transition hover:border-white/12">
<div className={`pointer-events-none absolute inset-0 bg-gradient-to-br ${ring} opacity-70`} />
<div className="relative">
<p className="text-[11px] text-zinc-500">{label}</p>
<p className={`mt-1 text-xl font-semibold tracking-tight ${warn ? "text-amber-200" : "text-white"}`}>
<span className={warn ? "inline-flex animate-pulse" : ""}>{value}</span>
</p>
<p className="mt-1 text-[10px] text-zinc-600">{helper}</p>
</div>
</div>
);
}
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,
label,
className,
baseLock,
onRun,
notify,
t,
compact,
}: {
kind: "start" | "stop" | "restart";
busyKind?: "start" | "stop" | "restart";
targetPm2: string;
busy: string | null;
online: 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" && online;
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 live"));
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 (
<button
type="button"
onClick={onClick}
className={`relative overflow-hidden rounded-xl ring-1 transition ${sizeCls} ${className} ${
blocked || hardLock ? "cursor-not-allowed" : ""
} ${blocked && !loading ? "opacity-45" : ""} ${siblingBusy ? "opacity-35" : ""} ${loading ? "ring-violet-400/40" : ""}`}
>
{loading ? (
<span className="absolute inset-0 flex items-center justify-center bg-black/25 backdrop-blur-[2px]">
<Loader2 className={`${compact ? "h-4 w-4" : "h-6 w-6"} animate-spin text-white`} />
</span>
) : null}
<span className={`inline-flex items-center justify-center gap-1.5 ${loading ? "invisible" : ""}`}>
{blocked ? <Ban className={`${compact ? "h-3 w-3" : "h-4 w-4"} shrink-0 opacity-90`} aria-hidden /> : null}
{label}
</span>
</button>
);
}
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<void>;
fetchJson: <T,>(path: string, init?: RequestInit) => Promise<T>;
liveProcesses: LiveProcRow[];
notify: (msg: string) => void;
onNavigate?: (target: PortalNavTarget) => void;
onRefresh?: () => void | Promise<void>;
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<YoutubeProChannel[]>([]);
const [activeCh, setActiveCh] = useState<string>("");
const [singleUrlDraft, setSingleUrlDraft] = useState(urlConfig);
const [youtubeIniText, setYoutubeIniText] = useState("");
const [ytFields, setYtFields] = useState<YoutubeIniFields>({
key: "",
rtmps: true,
bitrate: "",
fastAudio: true,
});
const [ytIniStatus, setYtIniStatus] = useState<string | null>(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<string | null>(null);
const [laneDrafts, setLaneDrafts] = useState<Record<string, ProLaneDraft>>({});
const [laneSaving, setLaneSaving] = useState(false);
const [laneStatus, setLaneStatus] = useState<string | null>(null);
const [activeViewRefreshToken, setActiveViewRefreshToken] = useState(0);
const [liveEventSummary, setLiveEventSummary] = useState<YoutubeLiveSummary | null>(null);
const [selectedLiveEvent, setSelectedLiveEvent] = useState<YoutubeLiveEvent | null>(null);
const [liveEventLoading, setLiveEventLoading] = useState(false);
const [qualityGuard, setQualityGuard] = useState<YoutubeQualityGuard | null>(null);
const [qualityGuardLoading, setQualityGuardLoading] = useState(false);
const [pageVisible, setPageVisible] = useState(true);
const [nekoBusy, setNekoBusy] = useState<string | null>(null);
const [nekoActionNote, setNekoActionNote] = useState<string | null>(null);
const urlListDirtyRef = useRef(false);
const singleUrlDraftRef = useRef(urlConfig);
const proUrlDraftRef = useRef(proUrlDraft);
const channelsRef = useRef<YoutubeProChannel[]>([]);
const currentProcRef = useRef(currentProc);
const urlRequestSeqRef = useRef(0);
const ytIniRequestSeqRef = useRef(0);
const urlLoadingSeqRef = useRef(0);
const ytIniLoadingSeqRef = useRef(0);
const urlConfigReadInFlightRef = useRef<Record<string, Promise<string>>>({});
const ytIniReadInFlightRef = useRef<Record<string, Promise<string>>>({});
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<YoutubeProChannel>) => {
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<NekoActionResult>("/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<YoutubeLiveSummary>("/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(() => {
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<YoutubeQualityGuard>("/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(() => {
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 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 (
<div
key={link.key}
className={`flex min-h-[2.5rem] items-stretch overflow-hidden rounded-lg border text-xs ring-1 ${
activeNeko
? "border-emerald-400/30 bg-emerald-500/15 text-emerald-50 ring-emerald-400/25"
: "border-white/10 bg-white/5 text-zinc-200 ring-white/10"
}`}
>
<a
href={normalizeBrowserReachableHttpUrl(link.url)}
target="_blank"
rel="noreferrer"
className="flex items-center gap-2 px-3 py-2 hover:bg-white/[0.04]"
>
<span className="font-semibold">{link.label}</span>
<span className="rounded-full bg-emerald-500/15 px-1.5 py-0.5 text-[10px] text-emerald-100">
{link.accessLabel}
</span>
<span className="font-mono text-white/70">
{link.host || ""}
{link.port ? `:${link.port}` : ""}
</span>
</a>
<div className="flex border-l border-white/10">
<button
type="button"
disabled={disabled}
title={t("\u542f\u52a8 Neko \u5bb9\u5668", "Start Neko container")}
onClick={() => void runNekoAction(link, "start")}
className="inline-flex min-w-[3.75rem] items-center justify-center gap-1 px-2 text-emerald-100 hover:bg-emerald-500/15 disabled:cursor-not-allowed disabled:opacity-45"
>
{startBusy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}
{t("\u542f\u52a8", "Start")}
</button>
<button
type="button"
disabled={disabled}
title={t("\u505c\u6b62 Neko \u5bb9\u5668", "Stop Neko container")}
onClick={() => void runNekoAction(link, "stop")}
className="inline-flex min-w-[3.75rem] items-center justify-center gap-1 border-l border-white/10 px-2 text-amber-100 hover:bg-amber-500/15 disabled:cursor-not-allowed disabled:opacity-45"
>
{stopBusy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Square className="h-3.5 w-3.5" />}
{t("\u505c\u6b62", "Stop")}
</button>
<button
type="button"
disabled={deleteDisabled}
title={
canDelete
? t("\u5220\u9664\u6700\u540e\u4e00\u4e2a Neko \u5b9e\u4f8b\uff0c\u4fdd\u7559\u6d4f\u89c8\u5668\u914d\u7f6e\u6570\u636e", "Delete the last Neko instance and keep browser profile data")
: t("\u53ea\u80fd\u5220\u9664\u6700\u540e\u4e00\u4e2a Neko \u5b9e\u4f8b", "Only the last Neko instance can be deleted")
}
onClick={() => void runNekoAction(link, "delete")}
className="inline-flex min-w-[3.75rem] items-center justify-center gap-1 border-l border-white/10 px-2 text-rose-100 hover:bg-rose-500/15 disabled:cursor-not-allowed disabled:opacity-45"
>
{deleteBusy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
{t("\u5220\u9664", "Delete")}
</button>
</div>
</div>
);
};
const urlToolbar = (
<div className="mt-2 flex flex-wrap items-center gap-4 text-xs text-zinc-400">
<label className="flex cursor-pointer items-center gap-2">
<input
type="checkbox"
className="rounded border-white/20 bg-black/40"
checked={urlAutoRefresh}
onChange={(e) => setUrlAutoRefresh(e.target.checked)}
/>
{t("后台自动从服务器刷新(空闲约 12 秒)", "Auto-refresh from server (~12s when idle)")}
</label>
<button
type="button"
disabled={lock}
onClick={() => void reloadUrlManual()}
className="rounded-lg border border-white/10 px-3 py-1.5 text-zinc-200 hover:bg-white/5"
>
{t("手动重新读取", "Reload from server")}
</button>
<button
type="button"
disabled={lock}
onClick={() => void dedupeUrlDraft()}
className="rounded-lg border border-cyan-500/20 bg-cyan-500/10 px-3 py-1.5 text-cyan-100 hover:bg-cyan-500/15"
>
{urlOptimizing ? t("去重中...", "Deduplicating...") : t("智能去重", "Deduplicate")}
</button>
</div>
);
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 = (
<section className="rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.08] via-zinc-950/80 to-emerald-500/[0.05] p-6 ring-1 ring-white/[0.04]">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 className="flex items-center gap-2 text-sm font-semibold text-white">
<Database className="h-4 w-4 text-cyan-300" />
{t("直播事件中枢", "Live event center")}
</h3>
<p className="mt-1 text-xs text-zinc-500">
{t("事件、转播对象、时长、页面采集、弹窗和告警全部写入本地 SQLite,可追溯。", "Events, source rooms, duration, browser telemetry, popups, and alerts are stored locally.")}
</p>
</div>
<button
type="button"
onClick={() => void refreshLiveEvents()}
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.05] px-3 py-2 text-xs text-zinc-200 hover:bg-white/[0.08]"
>
<RefreshCw className={`h-3.5 w-3.5 ${liveEventLoading ? "animate-spin" : ""}`} />
{t("刷新事件", "Refresh events")}
</button>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
{liveEventStatCards.map(({ label, value, Icon }) => (
<div key={label} className="rounded-xl border border-white/[0.06] bg-black/25 p-3">
<div className="flex items-center gap-2 text-[11px] text-zinc-500">
<Icon className="h-3.5 w-3.5 text-cyan-300" />
{label}
</div>
<p className="mt-2 font-mono text-lg font-semibold text-white">{String(value)}</p>
</div>
))}
</div>
<div className="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(22rem,0.9fr)]">
<div className="space-y-4">
<div className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
<div className="flex items-center justify-between gap-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-cyan-200/90">{t("正在转播", "Active relay")}</h4>
<span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-[10px] text-emerald-100 ring-1 ring-emerald-500/25">
{activeEvents.length}
</span>
</div>
<div className="mt-3 space-y-2">
{(activeEvents.length ? activeEvents : latestEvents.slice(0, 1)).map((event) => (
<button
key={event.id}
type="button"
onClick={() => void openLiveEventDetail(event.id)}
className="block w-full rounded-lg border border-white/[0.06] bg-white/[0.03] px-3 py-2 text-left transition hover:bg-white/[0.06]"
>
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="truncate text-sm font-medium text-white">
{event.source_title || event.channel_name || event.source_room_id || event.process || `#${event.id}`}
</span>
<span className={`rounded-full px-2 py-0.5 text-[10px] ring-1 ${eventStatusClass(event.status)}`}>
{event.status || "event"}
</span>
</div>
<div className="mt-1 flex flex-wrap gap-2 font-mono text-[10px] text-zinc-500">
<span>{event.process || "-"}</span>
<span>{event.source_room_id ? `room:${event.source_room_id}` : t("未知来源", "unknown source")}</span>
<span>{fmtEventDuration(event.duration_seconds)}</span>
<span>{event.last_viewer_count != null ? `${event.last_viewer_count} online` : ""}</span>
</div>
</button>
))}
{!activeEvents.length && !latestEvents.length ? (
<p className="text-xs text-zinc-600">{t("暂无事件;开始直播或打开 Neko 中的 YouTube Studio 后会自动生成。", "No events yet. Start a relay or open YouTube Studio in Neko.")}</p>
) : null}
</div>
</div>
<div className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
<h4 className="text-xs font-semibold uppercase tracking-wider text-zinc-400">{t("最近事件", "Recent events")}</h4>
<div className="mt-3 divide-y divide-white/[0.06]">
{latestEvents.slice(0, 8).map((event) => (
<button
key={event.id}
type="button"
onClick={() => void openLiveEventDetail(event.id)}
className="flex w-full items-center justify-between gap-3 py-2 text-left"
>
<div className="min-w-0">
<p className="truncate text-xs font-medium text-zinc-200">
{event.source_title || event.source_room_id || event.channel_name || event.process || `#${event.id}`}
</p>
<p className="mt-0.5 font-mono text-[10px] text-zinc-600">
{fmtEventTime(event.started_at)} · {fmtEventDuration(event.duration_seconds)}
</p>
</div>
<span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] ring-1 ${eventStatusClass(event.status)}`}>
{event.quality_score ?? 0}/100
</span>
</button>
))}
</div>
</div>
</div>
<div className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
<div className="flex items-center justify-between gap-3">
<h4 className="text-xs font-semibold uppercase tracking-wider text-cyan-200/90">{t("事件详情页", "Event detail")}</h4>
{selectedLiveEvent ? (
<button type="button" onClick={() => setSelectedLiveEvent(null)} className="text-[11px] text-zinc-500 hover:text-zinc-300">
{t("收起", "Close")}
</button>
) : null}
</div>
{selectedLiveEvent ? (
<div className="mt-3 space-y-3">
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="truncate text-sm font-semibold text-white">
{selectedLiveEvent.source_title || selectedLiveEvent.source_room_id || selectedLiveEvent.process}
</p>
<span className={`rounded-full px-2 py-0.5 text-[10px] ring-1 ${eventStatusClass(selectedLiveEvent.status)}`}>
{selectedLiveEvent.status}
</span>
</div>
<div className="mt-2 grid gap-2 text-[11px] text-zinc-400 sm:grid-cols-2">
<p><span className="text-zinc-600">Process:</span> {selectedLiveEvent.process || "-"}</p>
<p><span className="text-zinc-600">Room:</span> {selectedLiveEvent.source_room_id || "-"}</p>
<p><span className="text-zinc-600">Started:</span> {fmtEventTime(selectedLiveEvent.started_at)}</p>
<p><span className="text-zinc-600">Duration:</span> {fmtEventDuration(selectedLiveEvent.duration_seconds)}</p>
<p><span className="text-zinc-600">Viewers:</span> {selectedLiveEvent.last_viewer_count ?? "-"} / peak {selectedLiveEvent.viewer_peak ?? 0}</p>
<p><span className="text-zinc-600">Health:</span> {selectedLiveEvent.last_health || selectedLiveEvent.last_live_status || "-"}</p>
</div>
<div className="mt-2 flex flex-wrap gap-2">
{selectedLiveEvent.source_url ? (
<a href={selectedLiveEvent.source_url} target="_blank" rel="noreferrer" className="rounded-lg bg-violet-500/15 px-2.5 py-1.5 text-[11px] text-violet-100 ring-1 ring-violet-500/25">
{t("打开源直播间", "Open source")}
</a>
) : null}
{selectedLiveEvent.last_page_url ? (
<a href={selectedLiveEvent.last_page_url} target="_blank" rel="noreferrer" className="rounded-lg bg-cyan-500/15 px-2.5 py-1.5 text-[11px] text-cyan-100 ring-1 ring-cyan-500/25">
{t("打开 Studio 页面", "Open Studio page")}
</a>
) : null}
</div>
</div>
{(selectedLiveEvent.alerts || latestAlerts).slice(0, 4).length ? (
<div className="rounded-lg border border-amber-500/20 bg-amber-500/[0.06] p-3">
<h5 className="flex items-center gap-2 text-xs font-semibold text-amber-100">
<AlertTriangle className="h-3.5 w-3.5" />
{t("弹窗 / 告警", "Popups / alerts")}
</h5>
<div className="mt-2 space-y-1">
{(selectedLiveEvent.alerts || latestAlerts).slice(0, 4).map((alert, idx) => (
<p key={`${alert.id || idx}`} className="text-[11px] text-amber-100/85">
{alert.title || alert.severity || "alert"}: {alert.message || "-"}
</p>
))}
</div>
</div>
) : null}
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<h5 className="text-xs font-semibold text-zinc-300">{t("采样时间线", "Sample timeline")}</h5>
<div className="mt-2 max-h-52 space-y-2 overflow-auto pr-1">
{(selectedLiveEvent.samples || []).slice(0, 12).map((sample) => (
<div key={sample.id} className="rounded-md border border-white/[0.05] bg-black/25 px-2 py-1.5">
<div className="flex flex-wrap items-center justify-between gap-2 font-mono text-[10px] text-zinc-500">
<span>{fmtEventTime(sample.ts)}</span>
<span>{sample.source || "sample"}</span>
</div>
<p className="mt-1 text-[11px] text-zinc-300">
{sample.live_status || "-"} · {sample.health || "-"} · {sample.viewer_count ?? "-"} online
</p>
{sample.popup_text ? <p className="mt-1 text-[10px] text-amber-100/80">{sample.popup_text}</p> : null}
</div>
))}
{!(selectedLiveEvent.samples || []).length ? (
<p className="text-[11px] text-zinc-600">{t("暂无采样;Chrome 扩展或状态接口会自动写入。", "No samples yet. The Chrome extension or status API will fill this.")}</p>
) : null}
</div>
</div>
</div>
) : (
<p className="mt-3 text-xs text-zinc-600">{t("选择左侧事件查看完整详情。", "Select an event to see details.")}</p>
)}
</div>
</div>
</section>
);
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 = (
<section className="rounded-2xl border border-white/[0.08] bg-zinc-950/90 p-6 ring-1 ring-cyan-500/10">
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h3 className="flex items-center gap-2 text-base font-semibold text-white">
<Database className="h-5 w-5 text-cyan-300" />
{t("直播事件中枢", "Live event center")}
</h3>
<p className="mt-1 max-w-3xl text-sm text-zinc-400">
{t(
"这里按运营视角展示:谁在播、转播哪个直播间、播了多久、观众多少、Studio 是否弹窗、有没有异常。机器编号只放在详情底部。",
"Built for operators: what is live, source room, duration, viewers, Studio popups, and issues. Technical ids stay in the detail footer.",
)}
</p>
</div>
<button
type="button"
onClick={() => void refreshLiveEvents()}
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.05] px-3 py-2 text-xs text-zinc-200 hover:bg-white/[0.08]"
>
<RefreshCw className={`h-3.5 w-3.5 ${liveEventLoading ? "animate-spin" : ""}`} />
{t("刷新", "Refresh")}
</button>
</div>
<div className="mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{humanLiveEventStats.map(({ label, value, helper, Icon, tone }) => (
<div key={label} className="rounded-xl border border-white/[0.06] bg-white/[0.035] p-4">
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-zinc-500">{label}</p>
<Icon className={`h-4 w-4 ${tone}`} />
</div>
<p className="mt-2 text-2xl font-semibold tracking-tight text-white">{value}</p>
<p className="mt-1 text-[11px] text-zinc-600">{helper}</p>
</div>
))}
</div>
<div className="mt-6 grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(25rem,0.9fr)]">
<div className="rounded-xl border border-white/[0.06] bg-black/25">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-white/[0.06] px-4 py-3">
<div>
<h4 className="text-sm font-semibold text-white">{activeEvents.length ? t("正在直播", "Live now") : t("最近直播记录", "Recent live events")}</h4>
<p className="mt-0.5 text-xs text-zinc-500">
{activeEvents.length
? t("优先显示还在推流的场次。", "Active relays are listed first.")
: t("当前没有正在直播的场次,下方是最近历史。", "Nothing is live now; showing recent history.")}
</p>
</div>
<span className="rounded-full bg-cyan-500/10 px-2.5 py-1 text-xs text-cyan-100 ring-1 ring-cyan-500/20">
{humanEventRows.length} {t("条记录", "records")}
</span>
</div>
<div className="divide-y divide-white/[0.06]">
{humanEventRows.map((event) => {
const selected = focusedLiveEvent?.id === event.id;
return (
<button
key={event.id}
type="button"
onClick={() => void openLiveEventDetail(event.id)}
className={`grid w-full gap-3 px-4 py-4 text-left transition md:grid-cols-[minmax(0,1fr)_8rem_7rem_7rem] ${
selected ? "bg-cyan-500/[0.08]" : "hover:bg-white/[0.04]"
}`}
>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className={`rounded-full px-2 py-0.5 text-[11px] ring-1 ${eventStatusClass(event.status)}`}>
{eventStatusText(event.status, t)}
</span>
<span className={`rounded-full px-2 py-0.5 text-[11px] ring-1 ${eventRiskClass(event)}`}>
{eventRiskText(event, t)}
</span>
</div>
<p className="mt-2 truncate text-sm font-semibold text-white">{eventTitleText(event, t)}</p>
<p className="mt-1 truncate text-xs text-zinc-500">
{eventSourceText(event, t)} {"->"} YouTube
</p>
</div>
<div className="self-center">
<p className="text-[11px] text-zinc-600">{t("开始", "Started")}</p>
<p className="mt-1 text-xs text-zinc-300">{fmtShortTime(event.started_at)}</p>
</div>
<div className="self-center">
<p className="text-[11px] text-zinc-600">{t("时长", "Duration")}</p>
<p className="mt-1 text-xs text-zinc-300">{fmtDurationHuman(event.duration_seconds, t)}</p>
</div>
<div className="self-center">
<p className="text-[11px] text-zinc-600">{t("在线/峰值", "Viewers")}</p>
<p className="mt-1 text-xs text-zinc-300">
{viewerText(event.last_viewer_count, t)} / {viewerText(event.viewer_peak ?? 0, t)}
</p>
</div>
</button>
);
})}
{!humanEventRows.length ? (
<div className="px-4 py-10 text-center">
<MonitorPlay className="mx-auto h-8 w-8 text-zinc-700" />
<p className="mt-3 text-sm font-medium text-zinc-300">{t("还没有直播记录", "No live events yet")}</p>
<p className="mt-1 text-xs text-zinc-600">
{t("启动转播或在 Neko 打开 YouTube Studio 后,这里会自动生成可追溯记录。", "Start a relay or open YouTube Studio in Neko to create traceable records.")}
</p>
</div>
) : null}
</div>
</div>
<div className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
{focusedLiveEvent ? (
<div className="space-y-4">
<div>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<p className="text-xs text-cyan-300">{t("这场直播", "Selected event")}</p>
<h4 className="mt-1 truncate text-lg font-semibold text-white">{eventTitleText(focusedLiveEvent, t)}</h4>
<p className="mt-1 text-sm text-zinc-500">{eventSourceText(focusedLiveEvent, t)} {"->"} YouTube</p>
</div>
<span className={`rounded-full px-2.5 py-1 text-xs ring-1 ${eventStatusClass(focusedLiveEvent.status)}`}>
{eventStatusText(focusedLiveEvent.status, t)}
</span>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<p className="text-[11px] text-zinc-600">{t("直播时长", "Duration")}</p>
<p className="mt-1 text-lg font-semibold text-white">{fmtDurationHuman(focusedLiveEvent.duration_seconds, t)}</p>
<p className="mt-1 text-[11px] text-zinc-500">{fmtEventTime(focusedLiveEvent.started_at)}</p>
</div>
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<p className="text-[11px] text-zinc-600">{t("观众", "Viewers")}</p>
<p className="mt-1 text-lg font-semibold text-white">
{viewerText(focusedLiveEvent.last_viewer_count, t)}
<span className="ml-2 text-xs font-normal text-zinc-500">
{t("峰值", "peak")} {viewerText(focusedLiveEvent.viewer_peak ?? 0, t)}
</span>
</p>
<p className="mt-1 text-[11px] text-zinc-500">{t("来自 Chrome 插件/Studio 页面采集", "Captured from Studio")}</p>
</div>
</div>
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h5 className="text-sm font-semibold text-white">{t("Studio 状态", "Studio status")}</h5>
<span className={`rounded-full px-2 py-0.5 text-[11px] ring-1 ${eventRiskClass(focusedLiveEvent)}`}>
{eventRiskText(focusedLiveEvent, t)}
</span>
</div>
<div className="mt-3 space-y-2 text-sm text-zinc-300">
<p>{focusedLiveEvent.last_live_status || focusedLiveEvent.last_health || t("暂未采集到 Studio 状态", "No Studio status captured yet")}</p>
{focusedLiveEvent.last_popup_text ? (
<p className="rounded-md border border-amber-500/20 bg-amber-500/[0.08] px-3 py-2 text-xs text-amber-100">
{focusedLiveEvent.last_popup_text}
</p>
) : (
<p className="text-xs text-zinc-600">{t("没有记录到弹窗。", "No popup recorded.")}</p>
)}
{focusedLiveEvent.last_page_title || focusedLiveEvent.last_page_url ? (
<p className="truncate text-xs text-zinc-500">
{focusedLiveEvent.last_page_title || focusedLiveEvent.last_page_url}
</p>
) : null}
</div>
<div className="mt-3 flex flex-wrap gap-2">
{focusedLiveEvent.source_url ? (
<a href={focusedLiveEvent.source_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 rounded-lg bg-violet-500/15 px-2.5 py-1.5 text-xs text-violet-100 ring-1 ring-violet-500/25">
{t("打开源直播间", "Open source")} <ExternalLink className="h-3 w-3" />
</a>
) : null}
{focusedLiveEvent.last_page_url ? (
<a href={focusedLiveEvent.last_page_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 rounded-lg bg-cyan-500/15 px-2.5 py-1.5 text-xs text-cyan-100 ring-1 ring-cyan-500/25">
{t("打开 Studio", "Open Studio")} <ExternalLink className="h-3 w-3" />
</a>
) : null}
</div>
</div>
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<h5 className="text-sm font-semibold text-white">{t("采样时间线", "Telemetry timeline")}</h5>
<div className="mt-3 max-h-64 space-y-2 overflow-auto pr-1">
{focusedSamples.slice(0, 10).map((sample) => (
<div key={sample.id} className="rounded-md border border-white/[0.05] bg-black/25 px-3 py-2">
<div className="flex flex-wrap items-center justify-between gap-2 text-xs">
<span className="text-zinc-400">{fmtShortTime(sample.ts)}</span>
<span className="text-zinc-600">{sample.source || t("采样", "sample")}</span>
</div>
<p className="mt-1 text-sm text-zinc-200">
{(sample.live_status || sample.health || t("状态未识别", "Unknown status"))}
<span className="ml-2 text-xs text-zinc-500">
{t("在线", "online")} {viewerText(sample.viewer_count, t)}
</span>
</p>
{sample.popup_text ? <p className="mt-1 text-xs text-amber-100">{sample.popup_text}</p> : null}
</div>
))}
{!focusedSamples.length ? (
<p className="rounded-md border border-white/[0.05] bg-black/20 px-3 py-3 text-xs text-zinc-500">
{selectedLiveEvent
? t("这场直播暂时没有采样明细。", "No telemetry samples for this event yet.")
: t("点击左侧记录后加载完整采样明细。", "Click a record on the left to load full telemetry samples.")}
</p>
) : null}
</div>
</div>
<div className="rounded-lg border border-white/[0.06] bg-white/[0.03] p-3">
<h5 className="flex items-center gap-2 text-sm font-semibold text-white">
<AlertTriangle className="h-4 w-4 text-amber-300" />
{t("告警和弹窗", "Alerts and popups")}
</h5>
<div className="mt-3 space-y-2">
{focusedAlerts.slice(0, 4).map((alert, idx) => (
<p key={`${alert.id || idx}`} className="rounded-md border border-amber-500/15 bg-amber-500/[0.06] px-3 py-2 text-xs text-amber-100">
{(alert.title || alert.severity || t("提示", "Notice"))}: {alert.message || "-"}
</p>
))}
{!focusedAlerts.length ? <p className="text-xs text-zinc-600">{t("没有告警。", "No alerts.")}</p> : null}
</div>
</div>
<p className="truncate text-[11px] text-zinc-700">
{t("技术标识", "Technical id")}: #{focusedLiveEvent.id} · {focusedLiveEvent.process || "-"} · {focusedLiveEvent.event_uuid || "-"}
</p>
</div>
) : (
<div className="flex min-h-[24rem] flex-col items-center justify-center text-center">
<Database className="h-10 w-10 text-zinc-700" />
<p className="mt-3 text-sm font-medium text-zinc-300">{t("等待第一场直播", "Waiting for the first live event")}</p>
<p className="mt-1 max-w-sm text-xs text-zinc-600">
{t("开始转播后,这里会变成这场直播的详情页。", "After a relay starts, this panel becomes the event detail page.")}
</p>
</div>
)}
</div>
</div>
</section>
);
const qualitySummary = qualityGuard?.summary || {};
const qualityLanes = qualityGuard?.lanes || [];
const qualityRecommendations = qualityGuard?.recommendations || [];
const qualityGuardPanel = (
<section className="rounded-2xl border border-emerald-500/20 bg-gradient-to-br from-emerald-500/[0.08] via-zinc-950/90 to-cyan-500/[0.06] p-6 ring-1 ring-white/[0.04]">
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h3 className="flex items-center gap-2 text-base font-semibold text-white">
<Activity className="h-5 w-5 text-emerald-300" />
{t("算法友好质量守护", "Algorithm-friendly quality guard")}
</h3>
<p className="mt-1 max-w-3xl text-sm text-zinc-400">
{t(
"目标不是刷数据,而是让直播信号长期稳定:不断流、不卡顿、Studio 状态可见、异常能追踪。",
"The goal is stable, policy-safe signal quality: no drops, no stalls, visible Studio state, and traceable issues.",
)}
</p>
</div>
<button
type="button"
onClick={() => void refreshQualityGuard()}
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.05] px-3 py-2 text-xs text-zinc-200 hover:bg-white/[0.08]"
>
<RefreshCw className={`h-3.5 w-3.5 ${qualityGuardLoading ? "animate-spin" : ""}`} />
{t("重新检测", "Check now")}
</button>
</div>
<div className="mt-5 grid gap-3 md:grid-cols-[12rem_minmax(0,1fr)]">
<div className="rounded-xl border border-white/[0.06] bg-black/30 p-4">
<p className="text-xs text-zinc-500">{t("综合分", "Score")}</p>
<p className={`mt-2 text-5xl font-semibold tracking-tight ${qualityScoreClass(qualityGuard?.score)}`}>
{qualityGuard?.score ?? 0}
</p>
<p className="mt-2 text-[11px] text-zinc-600">
{t("80 以上适合长时间无人值守", "80+ is suitable for long unattended runs")}
</p>
</div>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{[
[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]) => (
<div key={label} className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
<p className="text-xs text-zinc-500">{label}</p>
<p className="mt-2 text-2xl font-semibold text-white">{value}</p>
</div>
))}
</div>
</div>
<div className="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(20rem,0.8fr)]">
<div className="rounded-xl border border-white/[0.06] bg-black/25">
<div className="border-b border-white/[0.06] px-4 py-3">
<h4 className="text-sm font-semibold text-white">{t("线路质量", "Lane quality")}</h4>
<p className="mt-0.5 text-xs text-zinc-500">{t("从进程、FFmpeg 日志、配置和事件采样综合判断。", "Combined from process state, FFmpeg logs, config, and event telemetry.")}</p>
</div>
<div className="divide-y divide-white/[0.06]">
{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 (
<div key={lane.process || lane.label} className="grid gap-3 px-4 py-4 md:grid-cols-[minmax(0,1fr)_6rem_14rem]">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<p className="truncate text-sm font-semibold text-white">{laneDisplay}</p>
<span className={`rounded-full px-2 py-0.5 text-[11px] ring-1 ${lane.is_pushing ? "bg-emerald-500/15 text-emerald-100 ring-emerald-500/25" : "bg-zinc-600/20 text-zinc-300 ring-zinc-500/25"}`}>
{lane.is_pushing ? t("推流中", "Pushing") : t("未推流", "Idle")}
</span>
<span className={`rounded-full px-2 py-0.5 text-[11px] ring-1 ${lane.rtmps ? "bg-cyan-500/15 text-cyan-100 ring-cyan-500/25" : "bg-amber-500/15 text-amber-100 ring-amber-500/25"}`}>
{lane.rtmps ? "RTMPS" : t("非 RTMPS", "No RTMPS")}
</span>
</div>
{laneDouyinSubtitle && laneDouyinSubtitle !== laneDisplay ? (
<p className="mt-0.5 truncate text-xs text-zinc-500">{laneDouyinSubtitle}</p>
) : null}
<p className="mt-1 truncate text-xs text-zinc-600">{laneTech || "-"}</p>
<div className="mt-2 flex flex-wrap gap-1.5">
{(lane.issues || []).slice(0, 3).map((issue, idx) => (
<span key={`${issue.text || idx}`} className={`rounded-full px-2 py-0.5 text-[10px] ring-1 ${qualityPillClass(issue.level)}`}>
{issue.text || issue.level}
</span>
))}
</div>
</div>
<div>
<p className="text-[11px] text-zinc-600">{t("分数", "Score")}</p>
<p className={`mt-1 text-2xl font-semibold ${qualityScoreClass(lane.score)}`}>{lane.score ?? 0}</p>
</div>
<div className="grid grid-cols-3 gap-2 font-mono text-[11px] text-zinc-300">
<p><span className="block text-zinc-600">fps</span>{formatFfmpegMetricValue(laneLiveMetrics.fps)}</p>
<p>
<span className="block text-zinc-600">speed</span>
<span className={laneLiveMetrics.speedLow ? "text-amber-300" : ""}>
{formatFfmpegMetricValue(laneLiveMetrics.speed, "x")}
</span>
</p>
<p>
<span className="block text-zinc-600">{t("码率", "Bitrate")}</span>
{lane.is_pushing ? formatBitrateLabel(laneLiveMetrics.bitrate) ?? "—" : "—"}
</p>
<p>
<span className="block text-zinc-600">frame</span>
<span className={laneLiveMetrics.progressStalled ? "text-rose-300" : ""}>
{formatFfmpegMetricValue(laneLiveMetrics.frame, "", 0)}
</span>
</p>
<p><span className="block text-zinc-600">drop</span>{lane.metrics?.drop ?? "-"}</p>
<p><span className="block text-zinc-600">urls</span>{lane.url_count ?? 0}</p>
<p><span className="block text-zinc-600">err</span>{lane.metrics?.error_count ?? 0}</p>
</div>
</div>
);
})}
{!qualityLanes.length ? (
<div className="px-4 py-8 text-center text-sm text-zinc-500">
{t("没有发现 YouTube 线路。", "No YouTube lanes found.")}
</div>
) : null}
</div>
</div>
<div className="space-y-4">
<div className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
<h4 className="text-sm font-semibold text-white">{t("下一步建议", "Next actions")}</h4>
<div className="mt-3 space-y-2">
{qualityRecommendations.slice(0, 6).map((item, idx) => (
<p key={`${item.text || idx}`} className={`rounded-lg px-3 py-2 text-xs ring-1 ${qualityPillClass(item.level)}`}>
{item.text || "-"}
</p>
))}
{!qualityRecommendations.length ? <p className="text-xs text-zinc-600">{t("暂无建议。", "No recommendations.")}</p> : null}
</div>
</div>
<div className="rounded-xl border border-white/[0.06] bg-black/25 p-4">
<h4 className="text-sm font-semibold text-white">FFmpeg</h4>
<p className="mt-2 text-xs text-zinc-400">{qualityGuard?.ffmpeg_profile?.target || "720p30 H.264 CBR / RTMPS / AAC 128k"}</p>
<ul className="mt-3 space-y-1.5 text-xs text-zinc-500">
{(qualityGuard?.ffmpeg_profile?.guardrails || []).slice(0, 4).map((item) => (
<li key={item}>- {item}</li>
))}
</ul>
</div>
</div>
</div>
</section>
);
const statusOverviewPanel = (
<section className="rounded-2xl border border-white/[0.08] bg-gradient-to-br from-zinc-950/95 via-zinc-950/80 to-violet-500/[0.06] p-5 ring-1 ring-white/[0.04]">
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 items-start gap-3">
<div className="relative mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-black/40 ring-1 ring-white/10">
<Radio className={`h-5 w-5 ${overviewPushing ? "text-emerald-300" : "text-zinc-500"}`} />
{overviewPushing ? (
<span className="absolute -right-0.5 -top-0.5 flex h-3 w-3">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-60" />
<span className="relative inline-flex h-3 w-3 rounded-full bg-emerald-400" />
</span>
) : null}
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-sm font-semibold text-white">{t("转播实况", "Relay snapshot")}</h3>
<span
className={`rounded-full px-2.5 py-0.5 text-[11px] font-medium ring-1 ${businessStatusBadgeClass(overviewRow)}`}
>
{overviewStatusLabel}
</span>
</div>
<p className="mt-1 truncate text-sm text-zinc-300">
{overviewSource || t("未配置抖音直播源", "No Douyin source configured")}
</p>
{overviewDouyinSubtitle && overviewDouyinSubtitle !== overviewSource ? (
<p className="mt-0.5 truncate text-xs text-zinc-500">
{t("抖音源", "Douyin")}: {overviewDouyinSubtitle}
</p>
) : null}
<p className="mt-1 font-mono text-[11px] text-zinc-600">
{runtimeLogProc || "—"}
{mode === "pro" && overviewPushingLanes > 0
? ` · ${overviewPushingLanes}/${channels.length} ${t("路推流中", "lanes pushing")}`
: ""}
</p>
</div>
</div>
<div className="flex flex-wrap gap-2">
{overviewSourceUrl ? (
<a
href={overviewSourceUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 rounded-lg border border-violet-500/25 bg-violet-500/10 px-3 py-1.5 text-xs text-violet-100 ring-1 ring-violet-500/20 hover:bg-violet-500/15"
>
<ExternalLink className="h-3.5 w-3.5" />
{t("打开源站", "Open source")}
</a>
) : null}
{selectedNeko.link ? (
<a
href={selectedNekoUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 rounded-lg border border-emerald-500/25 bg-emerald-500/10 px-3 py-1.5 text-xs text-emerald-100 ring-1 ring-emerald-500/20 hover:bg-emerald-500/15"
>
<ExternalLink className="h-3.5 w-3.5" />
{t("Studio", "Studio")}
</a>
) : null}
<button
type="button"
onClick={() => void onRefresh?.()}
className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.05] px-3 py-1.5 text-xs text-zinc-300 hover:bg-white/[0.08]"
>
<RefreshCw className="h-3.5 w-3.5" />
{t("刷新全局", "Refresh")}
</button>
</div>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-7">
{[
{
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 }) => (
<MetricPulseCard key={label} label={label} value={value} warn={warn} helper={helper} accent={accent} />
))}
</div>
{overviewActiveEvent && overviewPushing ? (
<div className="mt-4 flex flex-wrap items-center gap-3 rounded-xl border border-cyan-500/20 bg-cyan-500/[0.06] px-4 py-3 text-xs">
<span className="font-medium text-cyan-100">{t("本场直播", "This event")}</span>
<span className={`rounded-full px-2 py-0.5 ring-1 ${eventStatusClass(overviewActiveEvent.status)}`}>
{eventStatusText(overviewActiveEvent.status, t)}
</span>
<span className={`rounded-full px-2 py-0.5 ring-1 ${eventRiskClass(overviewActiveEvent)}`}>
{eventRiskText(overviewActiveEvent, t)}
</span>
<span className="text-zinc-400">
{t("观众", "Viewers")} {viewerText(overviewActiveEvent.last_viewer_count, t)}
{" · "}
{fmtDurationHuman(overviewActiveEvent.duration_seconds, t)}
</span>
{overviewActiveEvent.last_popup_text ? (
<span className="text-amber-200">{t("弹窗", "Popup")}: {overviewActiveEvent.last_popup_text}</span>
) : null}
</div>
) : null}
</section>
);
return (
<div className="mx-auto max-w-6xl space-y-6">
{onNavigate ? (
<LivePipelineStrip
t={t}
title={t("YouTube 转播链路", "YouTube relay chain")}
subtitle={t(
"与「网络」页相同风格的链路示意:代理 → 编码推流 → 浏览器侧操作工作室。",
"Same visual language as Network: proxy → encode → browser studio.",
)}
onNavigate={onNavigate}
steps={[
{
label: "ShellCrash",
sub: t("透明代理", "Proxy"),
gradient: "from-violet-500 to-fuchsia-500",
target: "network",
},
{
label: "FFmpeg",
sub: t("推流 / 转码", "Stream"),
gradient: "from-cyan-400 to-blue-500",
target: "live_youtube",
},
{
label: "Neko",
sub: selectedNeko.link
? `${t("Chromium 工作室", "Chromium studio")} · ${selectedNeko.link.label}`
: t("Chromium 工作室", "Chromium studio"),
gradient: "from-emerald-400 to-teal-500",
openUrl: selectedNekoUrl,
},
]}
/>
) : null}
<div className="rounded-2xl border border-violet-500/25 bg-gradient-to-br from-violet-500/[0.12] via-zinc-950/80 to-cyan-500/5 p-6 shadow-xl shadow-violet-900/10">
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex items-center gap-3">
<div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-red-500/30 to-violet-600/30 ring-1 ring-white/10">
<MonitorPlay className="h-5 w-5 text-red-200" />
</div>
<div>
<h2 className="text-lg font-semibold tracking-tight text-white">
{t("YouTube 无人直播", "YouTube unmanned live")}
</h2>
<p className="mt-0.5 text-xs text-zinc-500">
{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.",
)}
</p>
</div>
</div>
<div
className={`ml-auto flex shrink-0 self-start rounded-xl border border-white/10 bg-black/30 p-1 ${
HIDE_YOUTUBE_MULTI_PRO_TOGGLE ? "hidden" : ""
}`}
aria-hidden={HIDE_YOUTUBE_MULTI_PRO_TOGGLE}
>
<button
type="button"
onClick={() => setModePersist("single")}
className={`rounded-lg px-4 py-2 text-xs font-medium transition ${
mode === "single" ? "bg-violet-500/25 text-white" : "text-zinc-500 hover:text-zinc-300"
}`}
>
{t("单频道", "Single")}
</button>
<button
type="button"
onClick={() => setModePersist("pro")}
className={`rounded-lg px-4 py-2 text-xs font-medium transition ${
mode === "pro" ? "bg-violet-500/25 text-white" : "text-zinc-500 hover:text-zinc-300"
}`}
>
{t("多频道 Pro", "Multi Pro")}
</button>
</div>
</div>
</div>
{!HIDE_YOUTUBE_RELAY_SNAPSHOT ? statusOverviewPanel : null}
{laneQuickLinks.length ? (
<div className="space-y-2">
{nekoActionNote ? <p className="text-xs text-zinc-400">{nekoActionNote}</p> : null}
<div className="flex flex-wrap gap-2">
{selectedNeko.link ? (
<a
href={selectedNekoUrl}
target="_blank"
rel="noreferrer"
className="rounded-lg border border-emerald-500/20 bg-emerald-500/10 px-3 py-2 text-xs text-emerald-100 ring-1 ring-emerald-500/20"
>
{t("打开当前线路 Neko 工作室", "Open lane Neko studio")}
</a>
) : null}
{nekoLinks.length ? (
<div className="flex flex-wrap gap-2">
{nekoLinks.map((link) => renderNekoLinkControl(link))}
</div>
) : null}
{quickLinks?.chromium_remote_debug ? (
<a
href={normalizeBrowserReachableHttpUrl(quickLinks.chromium_remote_debug)}
target="_blank"
rel="noreferrer"
className="rounded-lg border border-cyan-500/20 bg-cyan-500/10 px-3 py-2 text-xs text-cyan-100 ring-1 ring-cyan-500/20"
>
{t("打开 Chromium 调试", "Open Chromium debug")}
</a>
) : null}
{quickLinks?.srs_api ? (
<a
href={normalizeBrowserReachableHttpUrl(quickLinks.srs_api)}
target="_blank"
rel="noreferrer"
className="rounded-lg border border-violet-500/20 bg-violet-500/10 px-3 py-2 text-xs text-violet-100 ring-1 ring-violet-500/20"
>
{t("打开 SRS API", "Open SRS API")}
</a>
) : null}
</div>
</div>
) : null}
<div className="rounded-2xl border border-amber-500/20 bg-zinc-950/60 p-6 ring-1 ring-white/[0.04]">
<div className="flex items-center gap-2 text-amber-200/90">
<Radio className="h-4 w-4" />
<h3 className="text-sm font-semibold text-white">{t("直播开关", "Live control")}</h3>
</div>
{mode === "single" ? (
<>
<label className="mt-4 block text-xs font-semibold uppercase tracking-wider text-zinc-500">
{t("转播任务", "Relay task")}
</label>
<select
className="mt-2 w-full rounded-xl border border-white/10 bg-black/40 px-4 py-3 text-sm text-white"
value={currentProc}
onChange={(e) => {
const next = e.target.value;
currentProcRef.current = next;
setCurrentProc(next);
void refreshSingleProcessFromServer(next);
}}
>
{currentProc && !singleProcessOptions.some((entry) => entry.pm2 === currentProc) ? (
<option value={currentProc}>
{currentProcChannel ? `${currentProcChannel.name || currentProcChannel.id} (${currentProc})` : currentProc}
{currentProcRow ? ` (${businessStatusLabel(currentProcRow, t)})` : ""}
</option>
) : null}
{singleProcessOptions.map((e) => (
<option key={e.pm2} value={e.pm2}>
{singleModeProcessLabel(e, t)} ({e.pm2})
</option>
))}
</select>
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-3">
<LiveStreamActionBtn
kind="start"
targetPm2={singleRuntimeProc}
busy={busy}
online={singleOnline}
label={t("开始直播", "Start")}
className="bg-emerald-500/20 text-emerald-200 ring-emerald-500/30"
baseLock={false}
onRun={() => onRunProcess("start", singleRuntimeProc)}
notify={notify}
t={t}
/>
<LiveStreamActionBtn
kind="stop"
targetPm2={singleRuntimeProc}
busy={busy}
online={singleOnline}
label={t("停止直播", "Stop")}
className="bg-rose-500/15 text-rose-200 ring-rose-500/25"
baseLock={false}
onRun={() => onRunProcess("stop", singleRuntimeProc)}
notify={notify}
t={t}
/>
<LiveStreamActionBtn
kind="restart"
targetPm2={singleRuntimeProc}
busy={busy}
online={singleOnline}
label={t("重新开始", "Restart")}
className="bg-amber-500/15 text-amber-200 ring-amber-500/25"
baseLock={false}
onRun={() => onRunProcess("restart", singleRuntimeProc)}
notify={notify}
t={t}
/>
</div>
<div className="mt-3 flex flex-wrap items-center justify-center gap-2 text-xs">
<span className={`rounded-full px-2.5 py-0.5 font-medium ring-1 ${businessStatusBadgeClass(singleRow)}`}>
{businessStatusLabel(singleRow, t)}
</span>
{typeof singleRow?.ffmpeg_speed === "number" ? (
<span className={`font-mono text-zinc-400 ${singleRow.ffmpeg_speed_low ? "text-amber-300" : ""}`}>
speed {singleRow.ffmpeg_speed.toFixed(2)}x
</span>
) : null}
{typeof singleRow?.ffmpeg_frame === "number" ? (
<span className={`font-mono text-zinc-400 ${singleRow.ffmpeg_progress_stalled ? "text-rose-300" : ""}`}>
frame {singleRow.ffmpeg_frame}
</span>
) : null}
</div>
</>
) : (
<>
<div className="mt-4 rounded-xl border border-cyan-500/25 bg-gradient-to-br from-cyan-500/[0.1] via-zinc-950/50 to-violet-500/[0.06] p-4 ring-1 ring-white/[0.04]">
<h4 className="text-xs font-semibold uppercase tracking-wider text-cyan-200/90">
{t("Pro 转播实况", "Pro relay status")}
</h4>
<p className="mt-1 text-[11px] text-zinc-500">
{t("对齐桌面端:每路独立 URL / youtube 配置文件;点左侧信息切换编辑,右侧控制进程。", "Per-lane config files like desktop; click row info to edit, use right-side controls for PM2.")}
</p>
{nekoPortsLabel ? (
<p className="mt-2 text-[11px] text-zinc-500">
{t("Neko 实例", "Neko instances")}: {nekoPortsLabel}
</p>
) : null}
<div className="mt-3 max-h-[min(24rem,55vh)] space-y-2 overflow-y-auto pr-1">
{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 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 (
<div
key={c.id}
className={`flex flex-wrap items-center gap-2 rounded-lg border px-3 py-2.5 text-left text-xs transition sm:flex-nowrap ${
sel ? "border-violet-500/45 bg-violet-500/[0.1]" : "border-white/10 bg-black/30 hover:border-white/18"
}`}
>
<button
type="button"
className="min-w-0 flex-1 text-left"
onClick={() => {
currentProcRef.current = resolveChannelPm2(c);
selectProChannel(c);
}}
>
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-zinc-100">
<span className="mr-1.5" aria-hidden>{laneStatusEmoji(row)}</span>
{laneDisplay || t("未配置抖音直播源", "No Douyin source")}
</span>
<span
className={`shrink-0 rounded-md px-2 py-0.5 text-[10px] font-medium ring-1 ${
businessStatusBadgeClass(row)
}`}
>
{laneStatusLabel}
</span>
{laneNeko ? (
<span className="shrink-0 rounded-md bg-emerald-500/15 px-2 py-0.5 text-[10px] font-medium text-emerald-100 ring-1 ring-emerald-500/25">
{laneNeko.label} · {laneNeko.accessLabel}
</span>
) : null}
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 font-mono text-[10px] text-zinc-500">
{laneDouyinSubtitle && laneDouyinSubtitle !== laneDisplay ? (
<>
<span className="truncate text-zinc-400" title={laneDouyinSubtitle}>
{t("抖音源", "Douyin")} {laneDouyinSubtitle}
</span>
<span className="text-zinc-600">·</span>
</>
) : null}
<span title={laneName}>
{t("线路", "Lane")} {laneName}
</span>
<span className="text-zinc-600">·</span>
<span>
key …{suf || "—"}
</span>
<span className="text-zinc-600">·</span>
<span className="truncate" title={pm}>
{pm}
</span>
<span className="text-zinc-600">·</span>
<span>
URL {laneUrls.length}
</span>
<span className="text-zinc-600">·</span>
<span>
DY {douyinUrls.length}
</span>
{laneStatsText ? (
<>
<span className="text-zinc-600">·</span>
<span
className={speedToneClass(
laneLiveMetrics.speed,
laneLiveMetrics.speedLow,
laneLiveMetrics.progressStalled,
)}
>
{laneStatsText}
</span>
</>
) : null}
</div>
{dUrl ? (
<a
href={dUrl}
target="_blank"
rel="noreferrer"
className="mt-1 block max-w-full truncate text-cyan-300/90 underline-offset-2 hover:underline"
onClick={(e) => e.stopPropagation()}
title={dUrl}
>
{laneDisplay ? `${t("打开源站", "Open source")} · ${dUrl.replace(/^https?:\/\//, "")}` : dUrl.replace(/^https?:\/\//, "")}
</a>
) : (
<span className="mt-1 block text-zinc-600">—</span>
)}
</button>
<div
className="flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
<LiveStreamActionBtn
kind="start"
targetPm2={pm}
busy={busy}
online={rowOnline}
label={t("开始", "Start")}
className="rounded-lg bg-emerald-500/20 text-emerald-100 ring-emerald-500/30"
baseLock={false}
onRun={() => void runProProcess("start", pm)}
notify={notify}
t={t}
compact
/>
<LiveStreamActionBtn
kind="stop"
targetPm2={pm}
busy={busy}
online={rowOnline}
label={t("停止", "Stop")}
className="rounded-lg bg-rose-500/15 text-rose-100 ring-rose-500/25"
baseLock={false}
onRun={() => void runProProcess("stop", pm)}
notify={notify}
t={t}
compact
/>
<LiveStreamActionBtn
kind="restart"
targetPm2={pm}
busy={busy}
online={rowOnline}
label={t("重新开始", "Restart")}
className="rounded-lg bg-amber-500/15 text-amber-100 ring-amber-500/25"
baseLock={false}
onRun={() => void runProProcess("restart", pm)}
notify={notify}
t={t}
compact
/>
{laneNeko ? (
<button
type="button"
onClick={() => {
window.open(normalizeBrowserReachableHttpUrl(laneNeko.url), "_blank", "noopener,noreferrer");
}}
className="inline-flex min-h-[2rem] items-center justify-center rounded-lg border border-emerald-500/25 bg-emerald-500/10 px-2.5 py-1.5 text-emerald-100 ring-1 ring-emerald-500/20 transition hover:bg-emerald-500/20"
title={`${t("打开该线路 Neko 工作室", "Open this lane's Neko studio")} · ${laneNeko.label}${laneNeko.port ? ` :${laneNeko.port}` : ""}`}
aria-label={`${t("打开该线路 Neko 工作室", "Open this lane's Neko studio")} · ${laneNeko.label}`}
>
<span className="sr-only">{t("打开该线路 Neko 工作室", "Open this lane's Neko studio")}</span>
<span aria-hidden className="text-sm leading-none">
🐱
</span>
<ExternalLink className="ml-1 h-3.5 w-3.5 shrink-0" aria-hidden />
</button>
) : null}
</div>
</div>
);
})}
</div>
</div>
</>
)}
</div>
<LiveProcessLiveLogCard
t={t}
currentProc={runtimeLogProc}
fetchJson={fetchJson}
urlListText={monitorUrlDraft}
keySuffixUi={keySuffixUi}
showKeyRow
pollMs={statusCardPollMs}
refreshToken={activeViewRefreshToken}
monitorRow={overviewRow ?? undefined}
preferredTitle={mode === "pro" ? overviewLaneName : undefined}
/>
{!HIDE_YOUTUBE_QUALITY_GUARD ? qualityGuardPanel : null}
{!HIDE_YOUTUBE_LIVE_EVENT_HUB ? humanLiveEventPanel || liveEventPanel : null}
<section className="rounded-2xl border border-white/[0.08] bg-zinc-950/50 ring-1 ring-white/[0.03]">
<div className="border-b border-white/[0.06] px-6 py-4">
<h3 className="text-sm font-semibold text-white">
{t("配置与地址", "Config and URLs")}
{configNeedsAttention ? (
<span className="ml-2 rounded-md bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-100 ring-1 ring-amber-500/25">
{t("待完善", "Needs setup")}
</span>
) : null}
</h3>
<p className="mt-1 text-xs text-zinc-500">
{t("密钥、youtube.ini、URL 列表", "Keys, youtube.ini, URL list")}
</p>
</div>
<div className="space-y-6 p-6 pt-4">
{mode === "single" ? (
<div>
<h3 className="text-sm font-semibold text-white">{t("YouTube 相关设置", "YouTube settings")}</h3>
<p className="mt-1 text-xs text-zinc-500">
{t("串流参数写进 youtube.ini,无需 Google 登录。", "Stream settings go to youtube.ini — no Google login.")}
</p>
<div className="mt-4 space-y-3">
<label className="block text-xs text-zinc-400">{t("串流密钥", "Stream key")}</label>
<input
className="w-full rounded-xl border border-white/10 bg-black/40 px-4 py-3 text-sm font-mono text-zinc-200"
spellCheck={false}
autoComplete="off"
value={ytFields.key}
onChange={(e) => setYtFields((f) => ({ ...f, key: e.target.value }))}
placeholder="xxxx-xxxx-xxxx-xxxx-xxxx"
/>
<div className="grid gap-3 sm:grid-cols-3">
<label className="flex flex-col gap-1 text-xs text-zinc-400">
RTMPS
<select
className="rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
value={ytFields.rtmps ? "1" : "0"}
onChange={(e) => setYtFields((f) => ({ ...f, rtmps: e.target.value === "1" }))}
>
<option value="1">{t("是(默认)", "Yes")}</option>
<option value="0">{t("否 → RTMP", "No")}</option>
</select>
</label>
<label className="flex flex-col gap-1 text-xs text-zinc-400">
{t("比特率 kbps", "Bitrate kbps")}
<input
className="rounded-lg border border-white/10 bg-black/40 px-3 py-2 font-mono text-sm"
value={ytFields.bitrate}
onChange={(e) => setYtFields((f) => ({ ...f, bitrate: e.target.value }))}
placeholder="4000"
/>
</label>
<label className="flex cursor-pointer items-center gap-2 pt-6 text-xs text-zinc-300">
<input
type="checkbox"
className="rounded border-white/20 bg-black/40"
checked={ytFields.fastAudio}
onChange={(e) => setYtFields((f) => ({ ...f, fastAudio: e.target.checked }))}
/>
fast_audio({t("轻量音频", "lighter audio")})
</label>
</div>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<button
type="button"
disabled={lock}
onClick={() => void loadYoutubeIni()}
className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-zinc-200"
>
<RefreshCw className={`h-3.5 w-3.5 ${ytIniLoading ? "animate-spin" : ""}`} />
{t("重新读取", "Reload")}
</button>
<button
type="button"
disabled={lock}
onClick={() => void applyFieldsAndSave()}
className="inline-flex items-center gap-2 rounded-xl bg-violet-500/25 px-4 py-2 text-sm font-medium text-violet-100 ring-1 ring-violet-500/35"
>
{ytIniLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
{t("保存 youtube.ini", "Save youtube.ini")}
</button>
<button
type="button"
disabled={lock}
onClick={() => void applyYoutubeBalancedPreset()}
className="rounded-xl border border-cyan-500/20 bg-cyan-500/10 px-4 py-2 text-sm text-cyan-100"
>
{t("平衡预设", "Balanced preset")}
</button>
<button
type="button"
disabled={lock}
onClick={syncFieldsFromText}
className="rounded-xl border border-white/10 px-4 py-2 text-sm text-zinc-400"
>
{t("从原文同步表单", "Parse raw")}
</button>
</div>
<details className="mt-4 rounded-xl border border-white/5 bg-black/20 p-3">
<summary className="cursor-pointer text-xs text-zinc-500">{t("高级:youtube.ini 原文", "Raw youtube.ini")}</summary>
<textarea
className="mt-2 h-36 w-full resize-y rounded-lg border border-white/10 bg-black/50 p-3 font-mono text-[11px] text-zinc-400"
value={youtubeIniText}
onChange={(e) => setYoutubeIniText(e.target.value)}
spellCheck={false}
/>
<button
type="button"
disabled={lock}
className="mt-2 rounded-lg bg-cyan-500/15 px-3 py-1.5 text-xs text-cyan-200"
onClick={() => void saveYoutubeIniToServer(youtubeIniText)}
>
{t("保存原文", "Save raw")}
</button>
</details>
{ytIniStatus ? <p className="mt-2 font-mono text-xs text-zinc-500">{ytIniStatus}</p> : null}
</div>
) : (
<div className="space-y-6">
<div>
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h3 className="text-sm font-semibold text-white">
{t("当前线路", "Current lane")}
{active ? (
<span className="ml-2 font-normal text-zinc-400">
· {activeSourceDisplay || t("未配置抖音直播源", "No Douyin source")}
</span>
) : null}
{activeLaneDirty ? (
<span className="ml-2 rounded-md bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-100 ring-1 ring-amber-500/25">
{t("有未保存修改", "Unsaved")}
</span>
) : null}
</h3>
{active ? (
<p className="mt-0.5 font-mono text-[11px] text-zinc-500">
{t("配置名", "Config")}: {cleanLaneName(active.name, Math.max(0, channels.findIndex((row) => row.id === active.id)))} · PM2: {activeSavedPm2}
{activePm2PreviewChanged ? ` → ${activeDraftPm2}` : ""}
{" · "}
key {t("尾码", "suffix")}: {keySuffixDisplay}
</p>
) : null}
</div>
<button
type="button"
disabled={proLaneActionLock}
className="inline-flex items-center gap-1 rounded-lg bg-violet-500/20 px-3 py-1.5 text-xs text-violet-100 ring-1 ring-violet-500/30"
onClick={() => {
const id = newChannelId();
const nc: YoutubeProChannel = {
id,
name: `${t("线路", "Ch")} ${channels.length + 1}`,
streamKey: "",
urlLines: "",
pm2Name: defaultPm2NameForChannel(id),
notes: "",
};
setLaneDrafts((prev) => ({
...prev,
[id]: laneDraftFromChannel(nc),
}));
persistChannels([...channels, nc], { force: true });
setActiveCh(id);
currentProcRef.current = resolveChannelPm2(nc);
setCurrentProc(currentProcRef.current);
applyProUrlDraft("");
urlRequestSeqRef.current += 1;
ytIniRequestSeqRef.current += 1;
urlListDirtyRef.current = false;
setYoutubeIniText("");
setYtFields(parseYoutubeIniFields(""));
setUrlFetchNote(t("新线路已切换,地址列表为空", "New lane selected with an empty URL list"));
}}
>
<Plus className="h-3.5 w-3.5" />
{t("新增线路", "Add lane")}
</button>
</div>
{active ? (
<div className="mt-4 space-y-3 border-t border-white/5 pt-4">
<input
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm"
value={activeLaneDraft?.name ?? ""}
onChange={(e) => setLaneDraftField("name", e.target.value)}
placeholder={t("线路名称", "Lane name")}
/>
<label className="block text-xs text-zinc-500">{t("串流密钥", "Stream key")}</label>
<input
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-sm"
spellCheck={false}
value={activeLaneDraft?.streamKey ?? ""}
onChange={(e) => setLaneDraftField("streamKey", e.target.value)}
placeholder="xxxx-xxxx… / rtmp(s)://…"
/>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={proLaneActionLock}
onClick={() => void saveProLaneSettings()}
className="rounded-xl border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-zinc-100"
>
{laneSaving ? t("保存中...", "Saving...") : t("保存线路设置", "Save lane")}
</button>
<button
type="button"
disabled={proLaneActionLock}
onClick={() => void pushProStreamKeyToServer()}
className="rounded-xl bg-violet-500/25 px-4 py-2 text-sm font-medium text-violet-100 ring-1 ring-violet-500/35"
>
{t("写入 youtube.ini", "Write youtube.ini")}
</button>
</div>
{!activeLaneValidation.ok ? (
<p className="text-xs text-rose-300">{activeLaneValidation.message}</p>
) : null}
<details className="rounded-xl border border-white/5 bg-black/20 p-3">
<summary className="cursor-pointer text-xs text-zinc-500">{t("高级:进程名", "Advanced: process name")}</summary>
<input
className="mt-2 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 font-mono text-xs"
value={activeLaneDraft?.pm2Name ?? defaultPm2NameForChannel(active.id)}
onChange={(e) => setLaneDraftField("pm2Name", e.target.value)}
spellCheck={false}
placeholder="youtube2__…"
/>
<p className="mt-2 font-mono text-[11px] text-zinc-500">
{t("实际生效", "Effective")}: {activeDraftPm2 || "—"}
</p>
{activeLaneValidation.message && !activeLaneValidation.ok ? (
<p className="mt-2 text-[11px] text-rose-300">{activeLaneValidation.message}</p>
) : null}
</details>
<textarea
className="h-16 w-full resize-y rounded-xl border border-white/10 bg-black/40 p-3 text-xs text-zinc-300"
value={activeLaneDraft?.notes ?? ""}
onChange={(e) => setLaneDraftField("notes", e.target.value)}
placeholder={t("备注(可选)", "Notes (optional)")}
/>
{laneStatus ? <p className="text-xs text-zinc-400">{laneStatus}</p> : null}
<button
type="button"
disabled={lock || channels.length < 2}
className="inline-flex items-center gap-1 text-xs text-rose-300 hover:text-rose-200 disabled:opacity-30"
onClick={() => {
const next = channels.filter((c) => c.id !== active.id);
const nextActive = next[0] ?? null;
setLaneDrafts((prev) => {
const clone = { ...prev };
delete clone[active.id];
return clone;
});
persistChannels(next, { force: true });
setActiveCh(nextActive?.id || "");
if (nextActive) {
const pm2 = resolveChannelPm2(nextActive);
currentProcRef.current = pm2;
setCurrentProc(pm2);
applyProUrlDraft((nextActive.urlLines ?? "").trim());
void refreshProLaneFromServer(nextActive);
} else {
currentProcRef.current = "";
setCurrentProc("");
applyProUrlDraft("");
}
}}
>
<Trash2 className="h-3.5 w-3.5" />
{t("删除此线路", "Delete lane")}
</button>
</div>
) : null}
</div>
<div>
<h3 className="text-sm font-semibold text-white">{t("直播地址列表", "URL list")}</h3>
<p className="mt-1 text-xs text-zinc-500">
{t(
"每条线路独立写入自己的 URL_config.<pm2>.ini,不再复用或回填所谓“全局地址”。",
"Each lane writes to its own URL_config.<pm2>.ini with no shared global URL draft.",
)}
</p>
<p className="mt-1 font-mono text-[10px] text-zinc-600">
{currentProc
? managedUrlConfigRelPathForPm2(currentProc)
: "URL_config.ini"}
</p>
<div className="mt-3 flex flex-wrap gap-2 text-[11px]">
<span className="rounded-full border border-cyan-500/20 bg-cyan-500/10 px-2.5 py-1 text-cyan-100">
{t("有效地址", "Valid URLs")}: {currentUrlCount}
</span>
<span className="rounded-full border border-violet-500/20 bg-violet-500/10 px-2.5 py-1 text-violet-100">
Douyin: {currentDouyinCount}
</span>
</div>
{urlToolbar}
{urlFetchNote ? <p className="mt-2 text-xs text-zinc-500">{urlFetchNote}</p> : null}
<textarea
className="mt-4 min-h-[160px] w-full resize-y rounded-xl border border-white/10 bg-black/50 p-4 font-mono text-xs text-zinc-300"
value={proUrlDraft}
onChange={(e) => {
urlListDirtyRef.current = true;
applyProUrlDraft(e.target.value);
}}
spellCheck={false}
placeholder="https://live.douyin.com/..."
/>
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
disabled={laneSaving}
title={urlSaveBlockedReason || undefined}
onClick={() => void saveProUrlAndServer()}
className="rounded-xl bg-cyan-500/20 px-4 py-2 text-sm text-cyan-100 ring-1 ring-cyan-500/30"
>
{t("保存地址", "Save URLs")}
</button>
</div>
</div>
</div>
)}
{mode === "single" ? (
<div>
<h3 className="text-sm font-semibold text-white">{t("直播地址列表 · URL_config.ini", "URL_config.ini")}</h3>
<p className="mt-1 text-xs text-zinc-500">
{t("一行一个地址;可自动刷新或手动重新读取。", "One URL per line; auto-refresh or reload.")}
</p>
<p className="mt-1 font-mono text-[10px] text-zinc-600">
{currentProc ? managedUrlConfigRelPathForPm2(currentProc) : "URL_config.ini"}
</p>
<div className="mt-3 flex flex-wrap gap-2 text-[11px]">
<span className="rounded-full border border-cyan-500/20 bg-cyan-500/10 px-2.5 py-1 text-cyan-100">
{t("有效地址", "Valid URLs")}: {currentUrlCount}
</span>
<span className="rounded-full border border-violet-500/20 bg-violet-500/10 px-2.5 py-1 text-violet-100">
Douyin: {currentDouyinCount}
</span>
</div>
{urlToolbar}
{urlFetchNote ? <p className="mt-2 text-xs text-zinc-500">{urlFetchNote}</p> : null}
<textarea
className="mt-4 min-h-[200px] w-full resize-y rounded-xl border border-white/10 bg-black/50 p-4 font-mono text-xs text-zinc-300"
value={singleUrlDraft}
onChange={(e) => {
urlListDirtyRef.current = true;
applySingleUrlDraft(e.target.value);
}}
spellCheck={false}
/>
<button
type="button"
disabled={laneSaving}
title={urlSaveBlockedReason || undefined}
onClick={() => void saveSingleUrlAndClearDirty()}
className="mt-3 rounded-xl bg-cyan-500/20 px-4 py-2 text-sm text-cyan-100 ring-1 ring-cyan-500/30"
>
{t("保存 URL 配置", "Save URL config")}
</button>
</div>
) : null}
</div>
</section>
</div>
);
}