douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx
eric fa403d7b6a Promote Neko to top-level nav; always show remote Neko UX on assign cards.
Ops sub-tab renamed to 综合; /ops/neko redirects to /neko.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 02:42:42 -05:00

600 lines
25 KiB
TypeScript
Raw 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 Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { ExternalLink, Loader2, Monitor, RotateCw } from "lucide-react";
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
import { EnableSwitch } from "@/components/EnableSwitch";
import { StudioViewerChart } from "@/components/StudioViewerChart";
import { useToast } from "@/components/Toast";
import {
formatFfmpegStatsBrief,
mergeFfmpegMetrics,
speedToneClass,
} from "@/lib/ffmpegMetrics";
import { fetchJson } from "@/lib/api";
import {
businessStatusBadgeClass,
businessStatusLabel,
isLivePushingRow,
laneStatusEmoji,
procStartBlocked,
procStartBlockReason,
type RelayMonitorRow,
} from "@/lib/ytRelayStatus";
type GroupLike = {
id: string;
name?: string;
enabled?: boolean;
has_stream_key?: boolean;
featured?: Array<{ url?: string }>;
neko_instance_id?: number;
neko_enabled?: boolean;
/** Always native local /neko/N/ — never removed when remote is paired. */
neko_studio_url?: string;
neko_local_studio_url?: string;
ops_neko_open_url?: string;
ops_neko_bound?: boolean;
ops_neko_slot?: number;
ops_neko_edge_label?: string;
neko_open_prefer?: "local" | "remote";
neko_open_url?: string;
neko_open_source?: "local" | "remote";
};
type NekoState = {
running?: boolean;
ready?: boolean;
status?: string;
studio_url?: string;
detail?: string;
studio?: {
live_page_open?: boolean;
on_air?: boolean;
live_status?: string;
health?: string;
viewer_count?: number | null;
like_count?: number | null;
total_views?: number | null;
live_duration?: string;
live_duration_sec?: number | null;
stream_title?: string;
url?: string;
age_sec?: number | null;
detect_source?: string;
minute_reports?: Array<{
ts?: number;
on_air?: boolean;
live_status?: string;
health?: string;
viewer_count?: number | null;
total_views?: number | null;
live_duration?: string;
live_duration_sec?: number | null;
}>;
} | null;
};
type Props = {
group: GroupLike;
row?: RelayMonitorRow;
relayKickId: string;
onStart: (id: string) => void;
onStop: (id: string) => void;
onRestart: (id: string) => void;
onNekoChange?: () => void;
};
function nekoStatusLabel(st?: NekoState | null, instanceId?: number, pollErr?: string): string {
if (!instanceId || instanceId < 1) return "未配置";
if (pollErr) return "状态未知";
if (!st) return "检测中";
if (st.ready) return "运行中";
if (st.running) return "启动中";
if (st.status === "missing") return "容器缺失";
return "已停止";
}
/** Single-channel Pro relay status + per-channel Neko studio — embedded in 分配. */
export function YtRelayProStatusPanel({
group,
row,
relayKickId,
onStart,
onStop,
onRestart,
onNekoChange,
}: Props) {
const toast = useToast();
const laneName = group.name || "未命名频道";
const douyinSubtitle = row?.source_display || row?.source_title || "";
const dUrl = row?.source_url || "";
const suf = row?.stream_key_suffix || "—";
const urlCount = row?.url_count ?? (group.featured || []).length;
const dyCount = row?.douyin_count ?? urlCount;
const blocked = procStartBlocked(row);
const blockReason = procStartBlockReason(row);
const pushing = isLivePushingRow(row);
const starting = row?.business_status === "relay_starting";
const logText = typeof row?.recent_log === "string" ? row.recent_log : Array.isArray(row?.recent_log) ? (row?.recent_log as string[]).join("\n") : "";
const metrics = mergeFfmpegMetrics(row, logText);
const statsText = formatFfmpegStatsBrief(metrics, { live: pushing });
const busy = relayKickId === group.id;
const instanceId = Number(group.neko_instance_id || row?.neko_instance_id || 0);
const [nekoEnabled, setNekoEnabled] = useState(Boolean(group.neko_enabled ?? row?.neko_enabled));
const [nekoBusy, setNekoBusy] = useState(false);
const [nekoState, setNekoState] = useState<NekoState | null>((row?.neko as NekoState) || null);
const [nekoPollErr, setNekoPollErr] = useState("");
const [openPrefer, setOpenPrefer] = useState<"local" | "remote">(
group.neko_open_prefer === "remote" ? "remote" : "local",
);
const localStudioUrl = String(
group.neko_local_studio_url || group.neko_studio_url || nekoState?.studio_url || "",
).trim();
const remoteStudioUrl = String(group.ops_neko_open_url || "").trim();
const remoteBound = Boolean(group.ops_neko_bound || remoteStudioUrl);
const preferredUrl =
openPrefer === "remote" && remoteStudioUrl
? remoteStudioUrl
: localStudioUrl || String(nekoState?.studio_url || "").trim();
useEffect(() => {
setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled));
}, [group.id, group.neko_enabled, row?.neko_enabled]);
useEffect(() => {
setOpenPrefer(group.neko_open_prefer === "remote" ? "remote" : "local");
}, [group.id, group.neko_open_prefer]);
// Prefer Neko snapshot from relay/status (3.5s) — avoids a second docker poll loop.
useEffect(() => {
if (row?.neko) {
setNekoState(row.neko as NekoState);
setNekoPollErr("");
}
}, [row?.neko, row?.neko?.status, row?.neko?.ready, row?.neko?.running, row?.neko?.studio_url]);
const refreshNeko = useCallback(async () => {
if (instanceId < 1) return;
try {
const st = (await fetchJson("/api/youtube/neko/status")) as { instances?: NekoState[]; available?: boolean };
if (st.available === false) {
setNekoPollErr("Docker 不可用");
return;
}
const inst = (st.instances || []).find((x) => Number((x as { id?: number }).id) === instanceId);
if (inst) setNekoState(inst);
setNekoPollErr("");
} catch (e) {
setNekoPollErr((e as Error).message || "状态查询失败");
}
}, [instanceId]);
// Fallback only when relay payload has no neko field yet (old API / cold start).
useEffect(() => {
if (instanceId < 1) return;
if (row?.neko) return;
void refreshNeko();
}, [instanceId, row?.neko, refreshNeko]);
async function postNeko(body: Record<string, unknown>) {
setNekoBusy(true);
try {
const r = (await fetchJson(`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/neko`, {
method: "POST",
body: JSON.stringify(body),
})) as { group?: GroupLike; neko?: NekoState };
if (r.group) setNekoEnabled(Boolean(r.group.neko_enabled));
if (r.neko) setNekoState(r.neko);
onNekoChange?.();
await refreshNeko();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setNekoBusy(false);
}
}
async function setPrefer(prefer: "local" | "remote") {
if (prefer === "remote" && !remoteBound) {
toast.push("尚未配对远程 Neko(请先到一级 Tab「Neko」完成绑定)", "err");
return;
}
setNekoBusy(true);
try {
const r = (await fetchJson(
`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/neko-open-prefer`,
{ method: "POST", body: JSON.stringify({ prefer }) },
)) as { group?: GroupLike };
if (r.group?.neko_open_prefer === "remote" || r.group?.neko_open_prefer === "local") {
setOpenPrefer(r.group.neko_open_prefer);
} else {
setOpenPrefer(prefer);
}
toast.push(
prefer === "remote" ? "默认打开:远程 Neko(本机原生仍保留)" : "默认打开:本机原生 Neko",
"ok",
);
onNekoChange?.();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setNekoBusy(false);
}
}
return (
<div className="overflow-hidden rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.09] via-[#0a121c]/80 to-violet-500/[0.05] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] ring-1 ring-white/[0.03] transition duration-300 hover:border-cyan-400/30">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h4 className="text-[10px] font-semibold uppercase tracking-[0.18em] text-cyan-200/80">Pro 转播实况</h4>
<p className="mt-1 text-[11px] text-slate-500">
本频道 FFmpeg。精选列表 = 下方直播地址;顶部「自动推流」打开后由 Worker 调度。
</p>
</div>
{pushing ? (
<span className="inline-flex items-center gap-1.5 rounded-full border border-rose-400/30 bg-rose-500/15 px-2.5 py-1 text-[10px] font-medium text-rose-100">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-rose-400" />
LIVE
</span>
) : null}
</div>
<div className="mt-3 flex flex-wrap items-center gap-2 rounded-xl border border-white/10 bg-black/35 px-3 py-2.5 text-xs sm:flex-nowrap">
<div className="min-w-0 flex-1">
<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>
{laneName}
</span>
<span
className={`shrink-0 rounded-md px-2 py-0.5 text-[10px] font-medium ring-1 ${businessStatusBadgeClass(row)}`}
>
{businessStatusLabel(row)}
</span>
{row?.source_room_id ? <DouyinLiveBadge roomId={row.source_room_id} compact showOffline /> : null}
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 font-mono text-[10px] text-slate-500">
{douyinSubtitle && douyinSubtitle !== laneName ? (
<>
<span className="truncate text-slate-400" title={douyinSubtitle}>
抖音源 {douyinSubtitle}
</span>
<span className="text-slate-600">·</span>
</>
) : null}
<span>key …{suf}</span>
<span className="text-slate-600">·</span>
<span>URL {urlCount}</span>
<span className="text-slate-600">·</span>
<span>DY {dyCount}</span>
{statsText ? (
<>
<span className="text-slate-600">·</span>
<span className={speedToneClass(metrics.speed, metrics.speedLow, metrics.progressStalled)}>
{statsText}
</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"
title={dUrl}
>
打开源站 · {dUrl.replace(/^https?:\/\//, "")}
</a>
) : (
<span className="mt-1 block text-slate-600">—</span>
)}
</div>
<div className="flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto">
<Link
href={`/youtube-relay-log?group_id=${encodeURIComponent(group.id)}`}
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 hover:bg-white/10"
>
历史
</Link>
<button
type="button"
disabled={!group.enabled || !group.has_stream_key || blocked || busy}
onClick={() => onStart(group.id)}
className="rounded-lg bg-emerald-500/20 px-2.5 py-1.5 text-[11px] text-emerald-100 ring-1 ring-emerald-500/30 disabled:opacity-40"
>
{busy ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : pushing ? (
"推流中"
) : starting ? (
"启动中…"
) : (
"开始"
)}
</button>
<button
type="button"
disabled={busy}
onClick={() => onStop(group.id)}
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 ring-1 ring-rose-500/25 disabled:opacity-40"
>
停止
</button>
<button
type="button"
disabled={!group.enabled || !group.has_stream_key || busy}
onClick={() => onRestart(group.id)}
className="inline-flex items-center gap-1 rounded-lg bg-amber-500/15 px-2.5 py-1.5 text-[11px] text-amber-100 ring-1 ring-amber-500/25 disabled:opacity-40"
>
<RotateCw className="h-3 w-3" />
重新开始
</button>
</div>
</div>
{blockReason ? (
<p className="mt-2 text-[10px] text-amber-200/90">无法开始:{blockReason}</p>
) : null}
{!group.has_stream_key ? (
<p className="mt-2 text-[10px] text-rose-200/80">未配置推流密钥,无法启动 FFmpeg。</p>
) : null}
{instanceId > 0 ? (
<div className="mt-3 rounded-xl border border-violet-500/25 bg-violet-500/[0.07] px-3 py-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2 text-xs">
<span className="flex h-7 w-7 items-center justify-center rounded-lg bg-violet-500/15 text-violet-200 ring-1 ring-violet-400/20">
<Monitor className="h-3.5 w-3.5" />
</span>
<span className="font-medium text-violet-50">
Neko 工作室
<span className="ml-1.5 font-mono text-[10px] text-slate-500">#{instanceId}</span>
</span>
<span
className={`rounded-md px-1.5 py-0.5 text-[10px] font-medium ${
nekoState?.ready
? "bg-emerald-500/20 text-emerald-200 ring-1 ring-emerald-400/25"
: nekoState?.running
? "bg-amber-500/20 text-amber-100 ring-1 ring-amber-400/25"
: nekoPollErr
? "bg-rose-500/15 text-rose-200 ring-1 ring-rose-400/20"
: "bg-white/5 text-slate-400 ring-1 ring-white/10"
}`}
>
{nekoStatusLabel(nekoState, instanceId, nekoPollErr)}
</span>
</div>
<EnableSwitch
checked={nekoEnabled}
disabled={nekoBusy}
label="启用"
onChange={(v) => void postNeko({ enabled: v, action: v ? "start" : "stop" })}
/>
</div>
<p className="mt-2 text-[10px] leading-relaxed text-slate-500">
本机原生 Neko #{instanceId} 始终保留(默认停止)。密码{" "}
<span className="font-mono text-slate-400">douyinweb</span>
。地址须带尾斜杠。
{nekoPollErr ? <span className="ml-2 text-rose-300">({nekoPollErr})</span> : null}
</p>
{/* Remote Neko — always visible UX (paired or empty CTA) */}
<div className="mt-2 space-y-2 rounded-lg border border-teal-500/25 bg-teal-500/[0.07] px-2.5 py-2.5">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<p className="text-[11px] font-medium text-teal-50">远程 Neko</p>
<p className="mt-0.5 text-[10px] text-slate-400">
{remoteBound
? `已配对${group.ops_neko_slot ? ` slot #${group.ops_neko_slot}` : ""}${
group.ops_neko_edge_label ? ` · ${group.ops_neko_edge_label}` : ""
}`
: "尚未配对 — 在物理机一级「Neko」创建实例并登记到本频道"}
</p>
</div>
<Link
href="/neko"
className="shrink-0 rounded-lg border border-teal-400/30 bg-teal-500/10 px-2.5 py-1 text-[10px] text-teal-100 hover:bg-teal-500/20"
>
打开 Neko Tab
</Link>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="text-[10px] text-slate-400">默认打开</span>
<div className="inline-flex rounded-full border border-white/10 bg-black/30 p-0.5">
<button
type="button"
disabled={nekoBusy}
onClick={() => void setPrefer("local")}
className={`rounded-full px-2.5 py-1 text-[10px] ${
openPrefer === "local" ? "bg-violet-400/90 text-slate-900" : "text-slate-400"
}`}
>
本机原生
</button>
<button
type="button"
disabled={nekoBusy || !remoteBound}
title={remoteBound ? "打开物理机配对实例" : "请先完成远程配对"}
onClick={() => void setPrefer("remote")}
className={`rounded-full px-2.5 py-1 text-[10px] ${
openPrefer === "remote" && remoteBound
? "bg-teal-400/90 text-slate-900"
: "text-slate-500"
} disabled:cursor-not-allowed disabled:opacity-40`}
>
远程
{group.ops_neko_slot ? ` #${group.ops_neko_slot}` : ""}
</button>
</div>
</div>
{!remoteBound ? (
<p className="text-[10px] leading-relaxed text-slate-500">
流程:物理机 Neko Tab → edge + Token → 新建实例 → 拉取 VPS 分配卡 → 绑定本频道并登记。登记后此处可切「远程」。
</p>
) : null}
</div>
<div className="mt-2 flex flex-wrap gap-1.5">
{preferredUrl ? (
<a
href={preferredUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-violet-500/30 bg-violet-500/10 px-2.5 py-1.5 text-[11px] text-violet-100 hover:bg-violet-500/20"
>
<ExternalLink className="h-3 w-3" />
打开工作室
{openPrefer === "remote" && remoteBound ? "(远程)" : "(本机)"}
</a>
) : null}
{localStudioUrl ? (
<a
href={localStudioUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 hover:bg-white/10"
>
本机原生
</a>
) : null}
{remoteStudioUrl ? (
<a
href={remoteStudioUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-2.5 py-1.5 text-[11px] text-teal-100 hover:bg-teal-500/20"
>
远程 Neko
</a>
) : (
<Link
href="/neko"
className="inline-flex items-center gap-1 rounded-lg border border-dashed border-teal-500/30 bg-teal-500/[0.06] px-2.5 py-1.5 text-[11px] text-teal-200/80 hover:bg-teal-500/15"
>
去配对远程…
</Link>
)}
<button
type="button"
disabled={nekoBusy || !nekoEnabled}
onClick={() => void postNeko({ action: "start" })}
className="rounded-lg bg-emerald-500/15 px-2.5 py-1.5 text-[11px] text-emerald-100 disabled:opacity-40"
title="仅启停本机原生 Docker Neko,不影响物理机 Tab 实例"
>
启动本机 Neko
</button>
<button
type="button"
disabled={nekoBusy}
onClick={() => void postNeko({ enabled: false, action: "stop" })}
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 disabled:opacity-40"
>
停止本机 Neko
</button>
<button
type="button"
disabled={nekoBusy || !nekoEnabled}
onClick={() => void postNeko({ action: "restart" })}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 disabled:opacity-40"
>
<RotateCw className="h-3 w-3" />
重启本机
</button>
</div>
{(() => {
const st = nekoState?.studio;
if (!st && !nekoState?.ready && !nekoState?.running) return null;
const reports = st?.minute_reports || [];
const viewers =
st?.viewer_count != null && Number.isFinite(Number(st.viewer_count))
? Number(st.viewer_count).toLocaleString()
: "—";
const totalViews =
st?.total_views != null && Number.isFinite(Number(st.total_views))
? Number(st.total_views).toLocaleString()
: "—";
const liveDur = String(st?.live_duration || "").trim() || "—";
return (
<div className="mt-3 space-y-2 rounded-lg border border-white/10 bg-black/25 px-2.5 py-2">
<div className="flex flex-wrap items-center gap-1.5 text-[10px]">
{st?.live_status === "signed_out" ? (
<span className="rounded-md bg-amber-500/20 px-1.5 py-0.5 text-amber-100 ring-1 ring-amber-400/30">
Google 已登出 — 请打开工作室点选账号重新登录
</span>
) : null}
<span
className={`rounded-md px-1.5 py-0.5 ring-1 ${
st?.live_page_open
? "bg-sky-500/15 text-sky-100 ring-sky-400/25"
: "bg-white/5 text-slate-500 ring-white/10"
}`}
>
Live 页 {st?.live_page_open ? "已打开" : "未打开"}
</span>
<span
className={`rounded-md px-1.5 py-0.5 ring-1 ${
st?.on_air
? "bg-rose-500/20 text-rose-100 ring-rose-400/30"
: "bg-white/5 text-slate-500 ring-white/10"
}`}
>
{st?.on_air ? "开播中" : "未开播"}
</span>
{st?.on_air || liveDur !== "—" ? (
<span className="rounded-md bg-rose-500/15 px-1.5 py-0.5 font-mono text-rose-100 ring-1 ring-rose-400/25">
LIVE {liveDur}
</span>
) : null}
{st?.live_status ? (
<span className="rounded-md bg-white/5 px-1.5 py-0.5 text-slate-400 ring-1 ring-white/10">
{st.live_status}
</span>
) : null}
{st?.health ? (
<span className="rounded-md bg-emerald-500/10 px-1.5 py-0.5 text-emerald-200/90 ring-1 ring-emerald-400/20">
健康 {st.health}
</span>
) : null}
<span className="rounded-md bg-white/5 px-1.5 py-0.5 text-slate-400 ring-1 ring-white/10">
同时观看 {viewers}
</span>
<span className="rounded-md bg-violet-500/10 px-1.5 py-0.5 text-violet-100 ring-1 ring-violet-400/25">
总观看 {totalViews}
</span>
{st?.age_sec != null ? (
<span className="text-slate-600">{Math.round(Number(st.age_sec))}s 前</span>
) : null}
</div>
{st?.stream_title ? (
<p className="truncate text-[10px] text-slate-400" title={st.stream_title}>
{st.stream_title}
</p>
) : null}
{reports.length > 0 ? (
<StudioViewerChart
reports={reports}
currentViewers={st?.viewer_count}
currentTotalViews={st?.total_views}
currentDuration={st?.live_duration}
onAir={Boolean(st?.on_air)}
/>
) : (
<p className="text-[10px] text-slate-600">暂无分钟报告(开播后约 1 分钟开始汇总)</p>
)}
</div>
);
})()}
</div>
) : null}
</div>
);
}