Owner-reported on live: adding a radio channel for a server + voice channel that already had one (different label, system, even bot) overwrote the existing stream and made its bot leave, because stream_id was guild:channel. - New streams get guild:channel:<12 hex> ids (leases.new_stream_id); old guild:channel docs keep working for read/stop/remove/node reports. Route validators accept both (leases.STREAM_ID_PATTERN). - start_stream: no stream_id = ADD. Same system already on in that channel is idempotent (already_on, label/mode untouched); a stopped one of that system is restarted; anything else is a new doc. stream_id = explicit restart/edit (admin Start button, reconciler), incl. moving to another bot. - preferred_token_id is strict: bot already in this server -> 409 preferred_busy naming the stream; on another node -> preferred_other_node; unusable -> preferred_unavailable. No silent swap. pool_exhausted now says one-bot-per-server and to add + invite another bot. - One-token-per-guild was already enforced inside the lease transaction; now covered by race tests. Per-guild asyncio lock serialises the already-on / server-cap check with the create (guild half of #223). - Stop by stream_id (POST /discord/guilds/{id}/stop {stream_id}); admin UI Stop/Start/Remove act on the row's stream; node picker lists every stream in a channel and adds beside other systems. - Bot: /leave stream: (autocomplete) stops one; /leave channel: with several streams asks which unless all:True; bare /leave still stops the server. /status and /join name each stream's bot. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
506 lines
21 KiB
TypeScript
506 lines
21 KiB
TypeScript
"use client";
|
|
|
|
// Node page "Discord radio" panel + picker (server-26#213 item 3, #109 item 13).
|
|
// Replaces the raw Guild ID / Voice Channel ID modal. The picker lists only
|
|
// the Discord servers linked to this node's org and the voice channels the
|
|
// DRB bot reported in them; a pick becomes a radio channel pinned to this node
|
|
// (desired state — the node reconciles and reports back, shown per row).
|
|
// A voice channel can carry several radio streams, each its own bot playing
|
|
// its own system (server-26#213 follow-up): picking a channel that already
|
|
// plays another system ADDS this node's system beside it; only a stream of
|
|
// this node's own system there is restarted / moved here.
|
|
// Layout follows design-canvas/discord-system-mockup.html "Radio channels".
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { c2api } from "@/lib/c2api";
|
|
import {
|
|
parseC2Error,
|
|
type DiscordGuildOption,
|
|
type DiscordInvite,
|
|
type DiscordJoinOptions,
|
|
type DiscordStreamView,
|
|
type StreamState,
|
|
} from "@/lib/discordPicker";
|
|
|
|
const POLL_MS = 10_000;
|
|
|
|
const STATE: Record<StreamState, { label: string; dot: string }> = {
|
|
pending: { label: "on → waiting for node", dot: "bg-sev-moderate" },
|
|
connecting: { label: "on → connecting", dot: "bg-sev-moderate" },
|
|
connected: { label: "on → connected", dot: "bg-green-500" },
|
|
error: { label: "on → error", dot: "bg-sev-major" },
|
|
stopping: { label: "off → stopping", dot: "bg-ink-muted" },
|
|
stopped: { label: "off", dot: "bg-ink-muted" },
|
|
node_offline: { label: "on → node offline", dot: "bg-sev-major" },
|
|
paused_locally: { label: "on → paused on node", dot: "bg-sev-moderate" },
|
|
};
|
|
|
|
function StatePill({ s }: { s: DiscordStreamView }) {
|
|
const st = STATE[s.actual?.state ?? "pending"] ?? STATE.pending;
|
|
return (
|
|
<span className="inline-flex items-center gap-1.5 text-xs font-medium whitespace-nowrap text-ink">
|
|
<i className={`inline-block w-2 h-2 rounded-full ${st.dot}`} />
|
|
{st.label}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function InviteLinks({ invite }: { invite: DiscordInvite[] }) {
|
|
if (!invite.length) return null;
|
|
return (
|
|
<span className="flex flex-wrap gap-x-3 gap-y-1 mt-1">
|
|
{invite.map((i) => (
|
|
<a
|
|
key={i.invite_url}
|
|
href={i.invite_url}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="text-accent hover:underline"
|
|
>
|
|
Invite {i.name}
|
|
</a>
|
|
))}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function modeLabel(mode: DiscordStreamView["mode"]) {
|
|
return mode === "persistent" ? "persistent" : "ad-hoc";
|
|
}
|
|
|
|
function streamLabel(s: DiscordStreamView) {
|
|
const sys = s.system_name ?? "radio";
|
|
return s.token_name ? `${sys} (${s.token_name})` : sys;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Picker
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function DiscordPicker({
|
|
nodeId,
|
|
options,
|
|
onClose,
|
|
onStarted,
|
|
}: {
|
|
nodeId: string;
|
|
options: DiscordJoinOptions;
|
|
onClose: () => void;
|
|
onStarted: () => void;
|
|
}) {
|
|
const usable = options.guilds;
|
|
const [guildId, setGuildId] = useState<string>(usable.length === 1 ? usable[0].guild_id : "");
|
|
const [channelId, setChannelId] = useState("");
|
|
const [mode, setMode] = useState<"adhoc" | "persistent">("adhoc");
|
|
const [sending, setSending] = useState(false);
|
|
const [error, setError] = useState<{ message: string; invite: DiscordInvite[] } | null>(null);
|
|
|
|
const guild: DiscordGuildOption | undefined = usable.find((g) => g.guild_id === guildId);
|
|
const channel = guild?.voice_channels.find((c) => c.channel_id === channelId);
|
|
const atNodeCap = options.limits.node_used >= options.limits.node_max;
|
|
const channelOnHere = channel?.stream?.node_id === nodeId;
|
|
|
|
const grouped = useMemo(() => {
|
|
const out: { category: string | null; channels: DiscordGuildOption["voice_channels"] }[] = [];
|
|
for (const c of guild?.voice_channels ?? []) {
|
|
const last = out[out.length - 1];
|
|
if (last && last.category === c.category) last.channels.push(c);
|
|
else out.push({ category: c.category, channels: [c] });
|
|
}
|
|
return out;
|
|
}, [guild]);
|
|
|
|
async function start() {
|
|
if (!guild || !channel) return;
|
|
setSending(true);
|
|
setError(null);
|
|
try {
|
|
await c2api.startNodeDiscordStream(nodeId, { guild_id: guild.guild_id, channel_id: channel.channel_id, mode });
|
|
onStarted();
|
|
onClose();
|
|
} catch (err) {
|
|
setError(parseC2Error(err));
|
|
} finally {
|
|
setSending(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4" role="dialog" aria-modal="true" aria-labelledby="discord-picker-title">
|
|
<div className="bg-surface border border-line rounded-xl w-full max-w-lg max-h-[90vh] flex flex-col text-sm">
|
|
<div className="px-5 pt-5 pb-3 border-b border-line">
|
|
<h3 id="discord-picker-title" className="text-ink font-semibold text-base">Add radio channel</h3>
|
|
<p className="text-ink-muted text-xs mt-1">
|
|
Source: <span className="text-ink-2">{options.system_name ?? "no system"}</span> ·{" "}
|
|
<span className="text-ink-2">{options.node_name ?? nodeId}</span>. Audio comes from this node's
|
|
PulseAudio monitor.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="px-5 py-4 space-y-4 overflow-y-auto">
|
|
{/* 1 — server */}
|
|
<fieldset>
|
|
<legend className="text-xs text-ink-muted mb-2">Discord server</legend>
|
|
{usable.length === 0 ? (
|
|
<p className="text-xs text-ink-2 bg-raised border border-line rounded-lg px-3 py-2">
|
|
No Discord server is linked to your organization yet. Add the DRB bot to your Discord server and
|
|
link it to your organization; it shows up here once the bot reports its channels.
|
|
</p>
|
|
) : (
|
|
<div className="space-y-1.5">
|
|
{usable.map((g) => (
|
|
<label
|
|
key={g.guild_id}
|
|
className={`flex items-start gap-3 rounded-lg border px-3 py-2 cursor-pointer ${
|
|
g.guild_id === guildId ? "border-accent bg-accent/10" : "border-line bg-raised hover:border-line-strong"
|
|
}`}
|
|
>
|
|
<input
|
|
type="radio"
|
|
name="guild"
|
|
className="mt-1 accent-[var(--accent)]"
|
|
checked={g.guild_id === guildId}
|
|
onChange={() => {
|
|
setGuildId(g.guild_id);
|
|
setChannelId("");
|
|
setError(null);
|
|
}}
|
|
/>
|
|
<span className="flex-1 min-w-0">
|
|
<span className="text-ink font-medium block truncate">{g.name ?? `Server ${g.guild_id}`}</span>
|
|
<span className="text-xs text-ink-muted block">
|
|
{g.linked ? "Linked" : "Default organization (not linked yet)"} · {g.streams_on} /{" "}
|
|
{options.limits.guild_max} radio channels on
|
|
</span>
|
|
{!g.bot.ok && (
|
|
<span className="text-xs text-sev-moderate block mt-1">
|
|
{g.bot.message}
|
|
<InviteLinks invite={g.bot.invite} />
|
|
</span>
|
|
)}
|
|
</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
)}
|
|
</fieldset>
|
|
|
|
{/* 2 — voice channel */}
|
|
{guild && (
|
|
<fieldset>
|
|
<legend className="text-xs text-ink-muted mb-2">Voice channel</legend>
|
|
{!guild.synced ? (
|
|
<p className="text-xs text-ink-2 bg-raised border border-line rounded-lg px-3 py-2">
|
|
The DRB bot has not reported this server's channels yet. It does when it starts and every 15
|
|
minutes — check back shortly.
|
|
</p>
|
|
) : guild.voice_channels.length === 0 ? (
|
|
<p className="text-xs text-ink-2 bg-raised border border-line rounded-lg px-3 py-2">
|
|
This server has no voice channels the DRB bot can see.
|
|
</p>
|
|
) : (
|
|
<div className="space-y-2">
|
|
{grouped.map((grp, gi) => (
|
|
<div key={`${grp.category ?? ""}-${gi}`}>
|
|
{grp.category && (
|
|
<div className="text-[11px] uppercase tracking-wider text-ink-muted mb-1">{grp.category}</div>
|
|
)}
|
|
<div className="space-y-1">
|
|
{grp.channels.map((c) => {
|
|
const here = c.stream?.node_id === nodeId;
|
|
const others = (c.streams ?? []).filter((x) => x.stream_id !== c.stream?.stream_id);
|
|
return (
|
|
<label
|
|
key={c.channel_id}
|
|
className={`flex items-start gap-3 rounded-lg border px-3 py-1.5 cursor-pointer ${
|
|
c.channel_id === channelId ? "border-accent bg-accent/10" : "border-line bg-raised hover:border-line-strong"
|
|
}`}
|
|
>
|
|
<input
|
|
type="radio"
|
|
name="channel"
|
|
className="mt-1 accent-[var(--accent)]"
|
|
checked={c.channel_id === channelId}
|
|
onChange={() => {
|
|
setChannelId(c.channel_id);
|
|
setError(null);
|
|
}}
|
|
/>
|
|
<span className="flex-1 min-w-0">
|
|
<span className="text-ink block truncate">🔊 {c.name}</span>
|
|
{c.stream && (
|
|
<span className="text-xs text-ink-muted block">
|
|
{here
|
|
? `${options.system_name ?? "This system"} is already on this node here`
|
|
: `${options.system_name ?? "This system"} is carried by ${c.stream.node_name ?? "another node"} — picking it moves it to this node`}
|
|
</span>
|
|
)}
|
|
{others.length > 0 && (
|
|
<span className="text-xs text-ink-muted block">
|
|
Also playing: {others.map(streamLabel).join(", ")}
|
|
{!c.stream && ` — this adds ${options.system_name ?? "this node's system"} beside it with another bot`}
|
|
</span>
|
|
)}
|
|
</span>
|
|
</label>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</fieldset>
|
|
)}
|
|
|
|
{/* 3 — mode */}
|
|
{channel && (
|
|
<fieldset>
|
|
<legend className="text-xs text-ink-muted mb-2">Mode</legend>
|
|
<div className="grid grid-cols-2 gap-2">
|
|
{(
|
|
[
|
|
["adhoc", "Ad-hoc", "Stops if this node goes offline or switches system."],
|
|
["persistent", "Persistent", `Stays up: if this node drops, DRB moves it to another node on ${options.system_name ?? "this system"}.`],
|
|
] as const
|
|
).map(([value, label, hint]) => (
|
|
<label
|
|
key={value}
|
|
className={`rounded-lg border px-3 py-2 cursor-pointer ${
|
|
mode === value ? "border-accent bg-accent/10" : "border-line bg-raised hover:border-line-strong"
|
|
}`}
|
|
>
|
|
<span className="flex items-center gap-2">
|
|
<input
|
|
type="radio"
|
|
name="mode"
|
|
className="accent-[var(--accent)]"
|
|
checked={mode === value}
|
|
onChange={() => setMode(value)}
|
|
/>
|
|
<span className="text-ink font-medium">{label}</span>
|
|
</span>
|
|
<span className="text-xs text-ink-muted block mt-1">{hint}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
</fieldset>
|
|
)}
|
|
|
|
{!options.system_id && (
|
|
<p className="text-xs text-sev-moderate">
|
|
This node is not listening to a system yet. Assign it one before adding a radio channel.
|
|
</p>
|
|
)}
|
|
{atNodeCap && !channelOnHere && (
|
|
<p className="text-xs text-sev-moderate">
|
|
This node already carries {options.limits.node_used} of {options.limits.node_max} radio channels. Stop one
|
|
first.
|
|
</p>
|
|
)}
|
|
{error && (
|
|
<p role="alert" className="text-xs text-sev-major">
|
|
{error.message}
|
|
<InviteLinks invite={error.invite} />
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="flex gap-3 px-5 py-4 border-t border-line">
|
|
<button
|
|
type="button"
|
|
onClick={start}
|
|
disabled={sending || !channel || !options.system_id || (atNodeCap && !channelOnHere)}
|
|
className="flex-1 bg-accent hover:brightness-110 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg py-2 text-sm font-semibold"
|
|
>
|
|
{sending ? "Starting…" : channelOnHere ? "Update" : "Start radio"}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
className="flex-1 bg-raised border border-line hover:brightness-110 text-ink-2 rounded-lg py-2 text-sm"
|
|
>
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Panel
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export function NodeDiscordRadio({ nodeId }: { nodeId: string }) {
|
|
const [options, setOptions] = useState<DiscordJoinOptions | null>(null);
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
const [picking, setPicking] = useState(false);
|
|
const [busy, setBusy] = useState<string | null>(null);
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
|
|
const load = useCallback(async () => {
|
|
try {
|
|
setOptions(await c2api.getNodeDiscordOptions(nodeId));
|
|
setLoadError(null);
|
|
} catch (err) {
|
|
setLoadError(parseC2Error(err).message);
|
|
}
|
|
}, [nodeId]);
|
|
|
|
useEffect(() => {
|
|
load();
|
|
const t = setInterval(() => {
|
|
if (document.visibilityState === "visible") load();
|
|
}, POLL_MS);
|
|
return () => clearInterval(t);
|
|
}, [load]);
|
|
|
|
async function stop(streamId?: string) {
|
|
if (!streamId && !confirm("Stop every Discord radio channel this node carries?")) return;
|
|
setBusy(streamId ?? "all");
|
|
setActionError(null);
|
|
try {
|
|
await c2api.stopNodeDiscordStreams(nodeId, streamId);
|
|
await load();
|
|
} catch (err) {
|
|
setActionError(parseC2Error(err).message);
|
|
} finally {
|
|
setBusy(null);
|
|
}
|
|
}
|
|
|
|
async function remove(s: DiscordStreamView) {
|
|
const name = s.channel_name ?? "this channel";
|
|
if (!confirm(`Remove ${streamLabel(s)} from ${name} permanently? It is stopped first (the node logs its radio bot out), then deleted from DRB. Other streams in that voice channel keep playing.`)) return;
|
|
setBusy(`rm:${s.stream_id}`);
|
|
setActionError(null);
|
|
try {
|
|
await c2api.removeNodeDiscordStream(nodeId, s.stream_id);
|
|
await load();
|
|
} catch (err) {
|
|
setActionError(parseC2Error(err).message);
|
|
} finally {
|
|
setBusy(null);
|
|
}
|
|
}
|
|
|
|
const streams = options?.streams ?? [];
|
|
const canControl = options?.can_control ?? false;
|
|
const canRemove = options?.can_remove ?? false;
|
|
|
|
return (
|
|
<section className="bg-surface border border-line rounded-lg overflow-hidden">
|
|
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-3 border-b border-line">
|
|
<h2 className="text-sm font-semibold text-ink">Discord radio</h2>
|
|
<span className="text-xs text-ink-muted">
|
|
Voice channels this node streams into. They reconnect by themselves; state is reported by the node.
|
|
</span>
|
|
{canControl && (
|
|
<span className="ml-auto flex gap-2">
|
|
{streams.length > 1 && (
|
|
<button
|
|
type="button"
|
|
disabled={busy !== null}
|
|
onClick={() => stop()}
|
|
className="bg-raised border border-line hover:brightness-110 disabled:opacity-50 text-ink-2 rounded-md px-2.5 py-1 text-xs"
|
|
>
|
|
{busy === "all" ? "Stopping…" : "Stop all"}
|
|
</button>
|
|
)}
|
|
<button
|
|
type="button"
|
|
disabled={!options}
|
|
onClick={() => setPicking(true)}
|
|
className="bg-accent hover:brightness-110 disabled:opacity-50 text-white rounded-md px-2.5 py-1 text-xs font-semibold"
|
|
>
|
|
+ Add radio channel
|
|
</button>
|
|
</span>
|
|
)}
|
|
</div>
|
|
|
|
{loadError ? (
|
|
<p role="alert" className="px-4 py-3 text-xs text-sev-major">Couldn't load Discord radio: {loadError}</p>
|
|
) : !options ? (
|
|
<p className="px-4 py-3 text-xs text-ink-muted">Loading…</p>
|
|
) : streams.length === 0 ? (
|
|
<p className="px-4 py-3 text-xs text-ink-muted">
|
|
Not streaming into any Discord voice channel.
|
|
{!canControl && " The organization owner or this node's operator can add one."}
|
|
</p>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-sm">
|
|
<thead>
|
|
<tr className="text-xs text-ink-muted border-b border-line">
|
|
<th className="px-4 py-2 text-left font-medium">Server · channel</th>
|
|
<th className="px-4 py-2 text-left font-medium">Mode</th>
|
|
<th className="px-4 py-2 text-left font-medium">Desired → actual</th>
|
|
{(canControl || canRemove) && <th className="px-4 py-2" />}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{streams.map((s) => (
|
|
<tr key={s.stream_id} className="border-b border-line last:border-0 align-top">
|
|
<td className="px-4 py-2.5">
|
|
<div className="text-ink font-medium">🔊 {s.channel_name ?? s.channel_id}</div>
|
|
<div className="text-xs text-ink-muted">
|
|
{s.guild_name ?? s.guild_id} · {streamLabel(s)}
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-2.5 text-ink-2">{modeLabel(s.mode)}</td>
|
|
<td className="px-4 py-2.5">
|
|
<StatePill s={s} />
|
|
{s.actual?.error && (
|
|
<div className="text-xs text-ink-muted mt-1 max-w-xs">
|
|
{s.actual.error}
|
|
{s.actual.code && <span className="font-mono"> [{s.actual.code}]</span>}
|
|
</div>
|
|
)}
|
|
</td>
|
|
{(canControl || canRemove) && (
|
|
<td className="px-4 py-2.5 text-right whitespace-nowrap">
|
|
{canControl && (
|
|
<button
|
|
type="button"
|
|
disabled={busy !== null}
|
|
onClick={() => stop(s.stream_id)}
|
|
className="bg-raised border border-line hover:brightness-110 disabled:opacity-50 text-ink-2 rounded-md px-2 py-0.5 text-xs"
|
|
>
|
|
{busy === s.stream_id ? "Stopping…" : "Stop"}
|
|
</button>
|
|
)}
|
|
{canRemove && (
|
|
<button
|
|
type="button"
|
|
disabled={busy !== null}
|
|
onClick={() => remove(s)}
|
|
className="ml-1 bg-sev-major hover:brightness-110 disabled:opacity-50 text-white rounded-md px-2 py-0.5 text-xs"
|
|
>
|
|
{busy === `rm:${s.stream_id}` ? "Removing…" : "Remove"}
|
|
</button>
|
|
)}
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
|
|
{actionError && <p role="alert" className="px-4 py-2 text-xs text-sev-major border-t border-line">{actionError}</p>}
|
|
{options && !options.node_online && streams.length > 0 && (
|
|
<p className="px-4 py-2 text-xs text-ink-muted bg-raised border-t border-line">
|
|
This node is offline — its channels resume if it reconnects shortly. If it stays down, ad-hoc ones stop and persistent ones move to another node on the same system.
|
|
</p>
|
|
)}
|
|
|
|
{picking && options && (
|
|
<DiscordPicker nodeId={nodeId} options={options} onClose={() => setPicking(false)} onStarted={load} />
|
|
)}
|
|
</section>
|
|
);
|
|
}
|