Initial commit — DRB server stack

Includes c2-core (FastAPI/MQTT/Firestore), discord-bot (slash commands),
frontend (Next.js admin UI), and mosquitto config.
This commit is contained in:
Logan
2026-04-05 19:01:39 -04:00
commit 2f0597c81b
77 changed files with 4126 additions and 0 deletions
+93
View File
@@ -0,0 +1,93 @@
"use client";
import { useState } from "react";
import { useCalls } from "@/lib/useCalls";
import { useSystems } from "@/lib/useSystems";
import { CallRow } from "@/components/CallRow";
export default function CallsPage() {
const [limitCount, setLimitCount] = useState(100);
const { calls, loading } = useCalls(limitCount);
const { systems } = useSystems();
const systemMap = Object.fromEntries(systems.map((s) => [s.system_id, s]));
const active = calls.filter((c) => c.status === "active");
const ended = calls.filter((c) => c.status === "ended");
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-xl font-bold text-white font-mono">Calls</h1>
<span className="text-xs text-gray-500 font-mono">{calls.length} loaded</span>
</div>
{active.length > 0 && (
<section>
<h2 className="text-sm font-semibold text-orange-400 uppercase tracking-wider mb-3">
Live ({active.length})
</h2>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-gray-500 uppercase tracking-wider border-b border-gray-800">
<th className="px-4 py-2 text-left">Time</th>
<th className="px-4 py-2 text-left">Talkgroup</th>
<th className="px-4 py-2 text-left">System</th>
<th className="px-4 py-2 text-left">Node</th>
<th className="px-4 py-2 text-left">Duration</th>
<th className="px-4 py-2 text-left">Audio</th>
</tr>
</thead>
<tbody>
{active.map((c) => (
<CallRow key={c.call_id} call={c} systemName={systemMap[c.system_id ?? ""]?.name} />
))}
</tbody>
</table>
</div>
</section>
)}
<section>
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">
History
</h2>
{loading ? (
<p className="text-gray-600 text-sm font-mono">Loading</p>
) : ended.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No calls recorded yet.</p>
) : (
<>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-gray-500 uppercase tracking-wider border-b border-gray-800">
<th className="px-4 py-2 text-left">Time</th>
<th className="px-4 py-2 text-left">Talkgroup</th>
<th className="px-4 py-2 text-left">System</th>
<th className="px-4 py-2 text-left">Node</th>
<th className="px-4 py-2 text-left">Duration</th>
<th className="px-4 py-2 text-left">Audio</th>
</tr>
</thead>
<tbody>
{ended.map((c) => (
<CallRow key={c.call_id} call={c} systemName={systemMap[c.system_id ?? ""]?.name} />
))}
</tbody>
</table>
</div>
{ended.length >= limitCount && (
<button
onClick={() => setLimitCount((n) => n + 100)}
className="mt-4 text-sm text-indigo-400 hover:text-indigo-300 font-mono transition-colors"
>
Load more
</button>
)}
</>
)}
</section>
</div>
);
}
+118
View File
@@ -0,0 +1,118 @@
"use client";
import { useNodes, useUnconfiguredNodes } from "@/lib/useNodes";
import { useCalls, useActiveCalls } from "@/lib/useCalls";
import { useSystems } from "@/lib/useSystems";
import { NodeCard } from "@/components/NodeCard";
import { CallRow } from "@/components/CallRow";
import { NodeConfigModal } from "@/components/NodeConfigModal";
import { useState } from "react";
import type { NodeRecord } from "@/lib/types";
function StatCard({ label, value, accent }: { label: string; value: string | number; accent?: string }) {
return (
<div className="bg-gray-900 border border-gray-800 rounded-lg p-4">
<p className="text-xs text-gray-500 uppercase tracking-wider mb-1">{label}</p>
<p className={`text-3xl font-bold font-mono ${accent ?? "text-white"}`}>{value}</p>
</div>
);
}
export default function DashboardPage() {
const { nodes, error: nodesError } = useNodes();
const { nodes: pending } = useUnconfiguredNodes();
const { calls, error: callsError } = useCalls(20);
const activeCalls = useActiveCalls();
const { systems, error: systemsError } = useSystems();
const [configNode, setConfigNode] = useState<NodeRecord | null>(null);
const systemMap = Object.fromEntries(systems.map((s) => [s.system_id, s]));
const onlineCount = nodes.filter((n) => n.status !== "offline").length;
const fsError = nodesError ?? callsError ?? systemsError;
return (
<div className="space-y-6">
<h1 className="text-xl font-bold text-white font-mono">Dashboard</h1>
{fsError && (
<div className="bg-red-950 border border-red-800 rounded-lg p-4">
<p className="text-red-400 text-sm font-mono">Firestore error: {fsError}</p>
</div>
)}
{/* Pending config banner */}
{pending.length > 0 && (
<div className="bg-indigo-950 border border-indigo-800 rounded-lg p-4 flex items-center justify-between">
<p className="text-indigo-300 text-sm font-mono">
{pending.length} new node{pending.length > 1 ? "s" : ""} connected and need{pending.length === 1 ? "s" : ""} configuration.
</p>
<button
onClick={() => setConfigNode(pending[0])}
className="text-xs bg-indigo-700 hover:bg-indigo-600 text-white px-3 py-1.5 rounded-lg transition-colors"
>
Configure now
</button>
</div>
)}
{/* Stats */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<StatCard label="Nodes Online" value={onlineCount} accent="text-green-400" />
<StatCard label="Active Calls" value={activeCalls.length} accent={activeCalls.length > 0 ? "text-orange-400" : undefined} />
<StatCard label="Total Nodes" value={nodes.length} />
<StatCard label="Systems" value={systems.length} />
</div>
{/* Nodes */}
<section>
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Nodes</h2>
{nodes.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No nodes registered yet.</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{nodes.map((n) => (
<NodeCard key={n.node_id} node={n} system={systemMap[n.assigned_system_id ?? ""]} />
))}
</div>
)}
</section>
{/* Recent calls */}
<section>
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Recent Calls</h2>
{calls.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No calls recorded yet.</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-gray-500 uppercase tracking-wider border-b border-gray-800">
<th className="px-4 py-2 text-left">Time</th>
<th className="px-4 py-2 text-left">Talkgroup</th>
<th className="px-4 py-2 text-left">System</th>
<th className="px-4 py-2 text-left">Node</th>
<th className="px-4 py-2 text-left">Duration</th>
<th className="px-4 py-2 text-left">Audio</th>
</tr>
</thead>
<tbody>
{calls.map((c) => (
<CallRow key={c.call_id} call={c} systemName={systemMap[c.system_id ?? ""]?.name} />
))}
</tbody>
</table>
</div>
)}
</section>
{configNode && (
<NodeConfigModal
node={configNode}
systems={systems}
onClose={() => setConfigNode(null)}
/>
)}
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html, body {
@apply bg-gray-950 text-gray-100 font-mono;
}
+22
View File
@@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { Nav } from "@/components/Nav";
import { AuthProvider } from "@/components/AuthProvider";
import "./globals.css";
export const metadata: Metadata = {
title: "DRB Portal",
description: "Distributed Radio Bot — Control & Monitoring",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className="dark">
<body className="min-h-screen bg-gray-950">
<AuthProvider>
<Nav />
<main className="p-6">{children}</main>
</AuthProvider>
</body>
</html>
);
}
+69
View File
@@ -0,0 +1,69 @@
"use client";
import { useState } from "react";
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "@/lib/firebase";
import { useRouter } from "next/navigation";
export default function LoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const router = useRouter();
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
try {
await signInWithEmailAndPassword(auth, email, password);
router.push("/dashboard");
} catch {
setError("Invalid email or password.");
} finally {
setLoading(false);
}
}
return (
<div className="max-w-sm mx-auto pt-16">
<form
onSubmit={handleSubmit}
className="bg-gray-900 border border-gray-700 rounded-xl p-8 space-y-5 font-mono"
>
<h1 className="text-white text-lg font-bold">DRB Portal</h1>
<div>
<label className="text-xs text-gray-400 block mb-1">Email</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoComplete="email"
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
autoComplete="current-password"
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
{error && <p className="text-red-400 text-xs">{error}</p>}
<button
type="submit"
disabled={loading}
className="w-full bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg py-2 text-sm font-semibold transition-colors"
>
{loading ? "Signing in…" : "Sign in"}
</button>
</form>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
"use client";
import dynamic from "next/dynamic";
import { useNodes } from "@/lib/useNodes";
import { useActiveCalls } from "@/lib/useCalls";
// Leaflet is browser-only — must be dynamically imported with no SSR
const MapView = dynamic(() => import("@/components/MapView"), { ssr: false });
export default function MapPage() {
const { nodes, loading } = useNodes();
const activeCalls = useActiveCalls();
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-bold text-white font-mono">Map</h1>
<div className="flex items-center gap-4 text-xs font-mono text-gray-400">
<span><span className="text-green-400"></span> Online</span>
<span><span className="text-orange-400 animate-pulse"></span> Recording</span>
<span><span className="text-indigo-400"></span> Unconfigured</span>
<span><span className="text-gray-600"></span> Offline</span>
</div>
</div>
{loading ? (
<div className="flex items-center justify-center h-96 text-gray-600 font-mono text-sm">
Loading map
</div>
) : (
<div style={{ height: "calc(100vh - 160px)" }}>
<MapView nodes={nodes} activeCalls={activeCalls} />
</div>
)}
</div>
);
}
+295
View File
@@ -0,0 +1,295 @@
"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { doc, onSnapshot } from "firebase/firestore";
import { db } from "@/lib/firebase";
import { useSystems } from "@/lib/useSystems";
import { useCalls } from "@/lib/useCalls";
import { StatusBadge } from "@/components/StatusBadge";
import { NodeConfigModal } from "@/components/NodeConfigModal";
import { CallRow } from "@/components/CallRow";
import { useAuth } from "@/components/AuthProvider";
import { c2api } from "@/lib/c2api";
import type { NodeRecord } from "@/lib/types";
function ApprovalBadge({ status }: { status: string | null }) {
if (status === "approved") return (
<span className="text-xs text-green-400 bg-green-400/10 px-2 py-0.5 rounded font-mono">Approved</span>
);
if (status === "rejected") return (
<span className="text-xs text-red-400 bg-red-400/10 px-2 py-0.5 rounded font-mono">Rejected</span>
);
return (
<span className="text-xs text-yellow-400 bg-yellow-400/10 px-2 py-0.5 rounded font-mono">Pending approval</span>
);
}
function DiscordJoinModal({
nodeId,
onClose,
}: {
nodeId: string;
onClose: () => void;
}) {
const [guildId, setGuildId] = useState("");
const [channelId, setChannelId] = useState("");
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setSending(true);
setError(null);
try {
await c2api.sendCommand(nodeId, {
action: "discord_join",
guild_id: guildId,
channel_id: channelId,
});
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to send join command.");
} finally {
setSending(false);
}
}
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
<form
onSubmit={handleSubmit}
className="bg-gray-900 border border-gray-700 rounded-xl p-6 space-y-4 font-mono w-full max-w-sm"
>
<h3 className="text-white font-semibold">Join Discord Voice</h3>
<div>
<label className="text-xs text-gray-400 block mb-1">Server ID (Guild)</label>
<input
value={guildId}
onChange={(e) => setGuildId(e.target.value)}
required
pattern="[0-9]+"
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="123456789012345678"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">Voice Channel ID</label>
<input
value={channelId}
onChange={(e) => setChannelId(e.target.value)}
required
pattern="[0-9]+"
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="123456789012345678"
/>
</div>
<p className="text-xs text-gray-600">
A token will be drawn from the pool automatically. Make sure the bot is a member of the server.
</p>
{error && <p className="text-red-400 text-xs">{error}</p>}
<div className="flex gap-3">
<button
type="submit"
disabled={sending}
className="flex-1 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg py-2 text-sm font-semibold transition-colors"
>
{sending ? "Joining…" : "Join"}
</button>
<button
type="button"
onClick={onClose}
className="flex-1 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg py-2 text-sm transition-colors"
>
Cancel
</button>
</div>
</form>
</div>
);
}
export default function NodeDetailPage() {
const { id } = useParams<{ id: string }>();
const [node, setNode] = useState<NodeRecord | null>(null);
const [showConfig, setShowConfig] = useState(false);
const [showDiscordJoin, setShowDiscordJoin] = useState(false);
const [sending, setSending] = useState(false);
const [approving, setApproving] = useState(false);
const { systems } = useSystems();
const { calls } = useCalls(20);
const { isAdmin } = useAuth();
const systemMap = Object.fromEntries(systems.map((s) => [s.system_id, s]));
const nodeCalls = calls.filter((c) => c.node_id === id);
useEffect(() => {
const unsub = onSnapshot(doc(db, "nodes", id), (snap) => {
setNode(snap.exists() ? (snap.data() as NodeRecord) : null);
});
return unsub;
}, [id]);
async function sendCommand(action: string) {
setSending(true);
try {
await c2api.sendCommand(id, { action });
} finally {
setSending(false);
}
}
async function handleApprove() {
setApproving(true);
try {
await c2api.approveNode(id);
} catch (err) {
alert(err instanceof Error ? err.message : "Approval failed.");
} finally {
setApproving(false);
}
}
async function handleReject() {
if (!confirm("Reject this node? It will not be able to upload recordings.")) return;
setApproving(true);
try {
await c2api.rejectNode(id);
} catch (err) {
alert(err instanceof Error ? err.message : "Rejection failed.");
} finally {
setApproving(false);
}
}
if (!node) {
return <p className="text-gray-500 font-mono text-sm">Loading node</p>;
}
const system = systemMap[node.assigned_system_id ?? ""];
return (
<div className="space-y-6 max-w-3xl">
<div className="flex items-start justify-between">
<div>
<h1 className="text-xl font-bold text-white font-mono">{node.name}</h1>
<p className="text-gray-500 text-sm font-mono">{node.node_id}</p>
</div>
<StatusBadge status={node.status} />
</div>
{/* Info */}
<div className="bg-gray-900 border border-gray-800 rounded-lg divide-y divide-gray-800 font-mono text-sm">
{[
["System", system?.name ?? "Unassigned"],
["Location", `${node.lat}, ${node.lon}`],
["Last Seen", node.last_seen ? new Date(node.last_seen).toLocaleString() : "never"],
["Configured", node.configured ? "Yes" : "No"],
].map(([label, value]) => (
<div key={label} className="flex justify-between px-4 py-2.5">
<span className="text-gray-500">{label}</span>
<span className="text-gray-200">{value}</span>
</div>
))}
<div className="flex justify-between px-4 py-2.5">
<span className="text-gray-500">Approval</span>
<ApprovalBadge status={node.approval_status ?? null} />
</div>
</div>
{/* Admin approval actions */}
{isAdmin && node.approval_status === "pending" && (
<div className="flex gap-3 items-center">
<span className="text-sm text-yellow-400 font-mono">This node is awaiting approval.</span>
<button
onClick={handleApprove}
disabled={approving}
className="px-4 py-2 bg-green-700 hover:bg-green-600 disabled:opacity-50 text-white rounded-lg text-sm font-mono transition-colors"
>
{approving ? "…" : "Approve"}
</button>
<button
onClick={handleReject}
disabled={approving}
className="px-4 py-2 bg-red-900 hover:bg-red-800 disabled:opacity-50 text-gray-300 rounded-lg text-sm font-mono transition-colors"
>
Reject
</button>
</div>
)}
{/* Actions */}
<div className="flex flex-wrap gap-3">
<button
onClick={() => setShowConfig(true)}
className="px-4 py-2 bg-indigo-700 hover:bg-indigo-600 text-white rounded-lg text-sm font-mono transition-colors"
>
{node.configured ? "Reassign System" : "Configure"}
</button>
<button
disabled={sending}
onClick={() => sendCommand("op25_restart")}
className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors disabled:opacity-50"
>
Restart OP25
</button>
<button
onClick={() => setShowDiscordJoin(true)}
className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors"
>
Join Discord
</button>
<button
disabled={sending}
onClick={() => sendCommand("discord_leave")}
className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors disabled:opacity-50"
>
Leave Discord
</button>
</div>
{/* Recent calls */}
<section>
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Recent Calls</h2>
{nodeCalls.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No calls recorded from this node.</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-gray-500 uppercase tracking-wider border-b border-gray-800">
<th className="px-4 py-2 text-left">Time</th>
<th className="px-4 py-2 text-left">Talkgroup</th>
<th className="px-4 py-2 text-left">System</th>
<th className="px-4 py-2 text-left">Node</th>
<th className="px-4 py-2 text-left">Duration</th>
<th className="px-4 py-2 text-left">Audio</th>
</tr>
</thead>
<tbody>
{nodeCalls.map((c) => (
<CallRow key={c.call_id} call={c} systemName={system?.name} />
))}
</tbody>
</table>
</div>
)}
</section>
{showConfig && (
<NodeConfigModal
node={node}
systems={systems}
onClose={() => setShowConfig(false)}
/>
)}
{showDiscordJoin && (
<DiscordJoinModal
nodeId={id}
onClose={() => setShowDiscordJoin(false)}
/>
)}
</div>
);
}
+63
View File
@@ -0,0 +1,63 @@
"use client";
import { useState } from "react";
import { useNodes } from "@/lib/useNodes";
import { useSystems } from "@/lib/useSystems";
import { NodeCard } from "@/components/NodeCard";
import { NodeConfigModal } from "@/components/NodeConfigModal";
import type { NodeRecord } from "@/lib/types";
export default function NodesPage() {
const { nodes, loading } = useNodes();
const { systems } = useSystems();
const [configNode, setConfigNode] = useState<NodeRecord | null>(null);
const systemMap = Object.fromEntries(systems.map((s) => [s.system_id, s]));
const pending = nodes.filter((n) => !n.configured);
return (
<div className="space-y-6">
<h1 className="text-xl font-bold text-white font-mono">Nodes</h1>
{pending.length > 0 && (
<div className="space-y-2">
<h2 className="text-sm font-semibold text-indigo-400 uppercase tracking-wider">
Needs Configuration ({pending.length})
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{pending.map((n) => (
<div key={n.node_id} onClick={() => setConfigNode(n)} className="cursor-pointer">
<NodeCard node={n} system={systemMap[n.assigned_system_id ?? ""]} />
</div>
))}
</div>
</div>
)}
<div className="space-y-2">
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">
All Nodes ({nodes.length})
</h2>
{loading ? (
<p className="text-gray-600 text-sm font-mono">Loading</p>
) : nodes.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No nodes registered yet. Boot a Pi to get started.</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{nodes.map((n) => (
<NodeCard key={n.node_id} node={n} system={systemMap[n.assigned_system_id ?? ""]} />
))}
</div>
)}
</div>
{configNode && (
<NodeConfigModal
node={configNode}
systems={systems}
onClose={() => setConfigNode(null)}
/>
)}
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function Home() {
redirect("/dashboard");
}
+519
View File
@@ -0,0 +1,519 @@
"use client";
import { useState } from "react";
import { useSystems } from "@/lib/useSystems";
import { c2api } from "@/lib/c2api";
import type { SystemRecord } from "@/lib/types";
// ── P25 structured config types ──────────────────────────────────────────────
interface TalkgroupEntry {
id: string;
name: string;
tag: string;
}
interface P25Config {
nac: string;
system_id: string;
wacn: string;
control_channels: string;
voice_channels: string;
talkgroups: TalkgroupEntry[];
}
const DEFAULT_P25: P25Config = {
nac: "",
system_id: "",
wacn: "",
control_channels: "",
voice_channels: "",
talkgroups: [],
};
const TG_TAGS = ["fire", "police", "ems", "transit", "public works", "other"];
function recordToP25Config(c: Record<string, unknown>): P25Config {
return {
nac: String(c.nac ?? ""),
system_id: String(c.system_id ?? ""),
wacn: String(c.wacn ?? ""),
control_channels: Array.isArray(c.control_channels)
? (c.control_channels as number[]).join(", ")
: "",
voice_channels: Array.isArray(c.voice_channels)
? (c.voice_channels as number[]).join(", ")
: "",
talkgroups: Array.isArray(c.talkgroups)
? (c.talkgroups as Array<{ id: number; name: string; tag: string }>).map((tg) => ({
id: String(tg.id),
name: tg.name,
tag: tg.tag ?? "other",
}))
: [],
};
}
function p25ConfigToRecord(p: P25Config): Record<string, unknown> {
const parseFreqs = (s: string) =>
s
.split(",")
.map((f) => parseFloat(f.trim()))
.filter((f) => !isNaN(f));
return {
nac: p.nac,
system_id: p.system_id ? parseInt(p.system_id, 10) : undefined,
wacn: p.wacn,
control_channels: parseFreqs(p.control_channels),
voice_channels: parseFreqs(p.voice_channels),
talkgroups: p.talkgroups
.filter((tg) => tg.id && tg.name)
.map((tg) => ({ id: parseInt(tg.id, 10), name: tg.name, tag: tg.tag })),
};
}
// ── Talkgroup table editor ────────────────────────────────────────────────────
function TalkgroupEditor({
talkgroups,
onChange,
}: {
talkgroups: TalkgroupEntry[];
onChange: (tgs: TalkgroupEntry[]) => void;
}) {
const [showPaste, setShowPaste] = useState(false);
const [pasteText, setPasteText] = useState("");
function addRow() {
onChange([...talkgroups, { id: "", name: "", tag: "other" }]);
}
function removeRow(i: number) {
onChange(talkgroups.filter((_, idx) => idx !== i));
}
function updateRow(i: number, field: keyof TalkgroupEntry, value: string) {
const updated = [...talkgroups];
updated[i] = { ...updated[i], [field]: value };
onChange(updated);
}
function handlePasteImport() {
const lines = pasteText.trim().split("\n");
const parsed: TalkgroupEntry[] = lines
.map((line) => {
const parts = line.includes("\t") ? line.split("\t") : line.split(",");
const id = parts[0]?.trim() ?? "";
const name = parts[1]?.trim() ?? "";
const rawTag = parts[2]?.trim()?.toLowerCase() ?? "other";
const tag = TG_TAGS.includes(rawTag) ? rawTag : "other";
return { id, name, tag };
})
.filter((e) => e.id && e.name);
onChange([...talkgroups, ...parsed]);
setPasteText("");
setShowPaste(false);
}
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-xs text-gray-400">
Talkgroups{talkgroups.length > 0 && <span className="text-gray-600 ml-1">({talkgroups.length})</span>}
</label>
<div className="flex gap-3">
<button
type="button"
onClick={() => setShowPaste(!showPaste)}
className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"
>
{showPaste ? "Cancel paste" : "Paste import"}
</button>
<button
type="button"
onClick={addRow}
className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"
>
+ Add row
</button>
</div>
</div>
{showPaste && (
<div className="space-y-2 p-3 bg-gray-800 rounded-lg border border-gray-700">
<p className="text-xs text-gray-500">
Paste rows from RadioReference tab- or comma-separated: <span className="text-gray-400">ID, Name, Tag</span>
<br />Tags: fire · police · ems · transit · public works · other
</p>
<textarea
value={pasteText}
onChange={(e) => setPasteText(e.target.value)}
rows={6}
placeholder={"1234\tFire Dispatch\tfire\n5678\tPolice Zone 1\tpolice\n9012\tEMS\tems"}
className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-white text-xs font-mono focus:outline-none focus:border-indigo-500"
/>
<button
type="button"
onClick={handlePasteImport}
disabled={!pasteText.trim()}
className="bg-indigo-700 hover:bg-indigo-600 disabled:opacity-50 text-white px-3 py-1.5 rounded text-xs font-semibold transition-colors"
>
Import rows
</button>
</div>
)}
{talkgroups.length > 0 ? (
<div className="border border-gray-800 rounded-lg overflow-hidden">
<table className="w-full text-xs font-mono">
<thead>
<tr className="bg-gray-800 text-gray-400">
<th className="px-3 py-1.5 text-left w-20">Dec ID</th>
<th className="px-3 py-1.5 text-left">Name</th>
<th className="px-3 py-1.5 text-left w-28">Tag</th>
<th className="px-3 py-1.5 w-8"></th>
</tr>
</thead>
<tbody>
{talkgroups.map((tg, i) => (
<tr key={i} className="border-t border-gray-800 hover:bg-gray-800/30">
<td className="px-2 py-1">
<input
value={tg.id}
onChange={(e) => updateRow(i, "id", e.target.value)}
className="w-full bg-transparent text-white focus:outline-none"
placeholder="1234"
/>
</td>
<td className="px-2 py-1">
<input
value={tg.name}
onChange={(e) => updateRow(i, "name", e.target.value)}
className="w-full bg-transparent text-white focus:outline-none"
placeholder="Fire Dispatch"
/>
</td>
<td className="px-2 py-1">
<select
value={tg.tag}
onChange={(e) => updateRow(i, "tag", e.target.value)}
className="w-full bg-gray-900 text-gray-300 focus:outline-none rounded px-1"
>
{TG_TAGS.map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
</td>
<td className="px-2 py-1 text-center">
<button
type="button"
onClick={() => removeRow(i)}
className="text-gray-600 hover:text-red-400 transition-colors font-bold"
>
×
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="text-xs text-gray-600 italic py-1">No talkgroups add rows or paste from RadioReference.</p>
)}
</div>
);
}
// ── P25 structured form ───────────────────────────────────────────────────────
function P25Form({ value, onChange }: { value: P25Config; onChange: (v: P25Config) => void }) {
return (
<div className="space-y-4">
<div className="grid grid-cols-3 gap-3">
<div>
<label className="text-xs text-gray-400 block mb-1">NAC (hex)</label>
<input
value={value.nac}
onChange={(e) => onChange({ ...value, nac: e.target.value })}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="0x293"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">System ID</label>
<input
value={value.system_id}
onChange={(e) => onChange({ ...value, system_id: e.target.value })}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="50513"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">WACN (hex)</label>
<input
value={value.wacn}
onChange={(e) => onChange({ ...value, wacn: e.target.value })}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="0xBEE00"
/>
</div>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">
Control Channels <span className="text-gray-600">(MHz, comma-separated)</span>
</label>
<input
value={value.control_channels}
onChange={(e) => onChange({ ...value, control_channels: e.target.value })}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="851.0125, 851.5125, 852.0125"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">
Voice Channels <span className="text-gray-600">(MHz, comma-separated leave blank for auto-discovery)</span>
</label>
<input
value={value.voice_channels}
onChange={(e) => onChange({ ...value, voice_channels: e.target.value })}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="Optional"
/>
</div>
<TalkgroupEditor
talkgroups={value.talkgroups}
onChange={(tgs) => onChange({ ...value, talkgroups: tgs })}
/>
</div>
);
}
// ── Main system form ──────────────────────────────────────────────────────────
function SystemForm({
initial,
onSave,
onCancel,
}: {
initial?: SystemRecord;
onSave: () => void;
onCancel: () => void;
}) {
const [name, setName] = useState(initial?.name ?? "");
const [type, setType] = useState(initial?.type ?? "P25");
const [p25, setP25] = useState<P25Config>(
initial?.type === "P25" && initial.config
? recordToP25Config(initial.config)
: DEFAULT_P25
);
const [rawJson, setRawJson] = useState(
initial?.type !== "P25" && initial?.config
? JSON.stringify(initial.config, null, 2)
: "{}"
);
const [showRaw, setShowRaw] = useState(initial?.type !== "P25");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
function handleTypeChange(t: string) {
setType(t);
setShowRaw(t !== "P25");
}
function toggleRaw() {
if (!showRaw) {
setRawJson(JSON.stringify(p25ConfigToRecord(p25), null, 2));
} else {
try {
setP25(recordToP25Config(JSON.parse(rawJson)));
} catch {
// keep current p25 state if parse fails
}
}
setShowRaw(!showRaw);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
setError(null);
try {
let config: Record<string, unknown>;
if (type === "P25" && !showRaw) {
config = p25ConfigToRecord(p25);
} else {
config = JSON.parse(rawJson);
}
if (initial) {
await c2api.updateSystem(initial.system_id, { name, type, config });
} else {
await c2api.createSystem({ name, type, config });
}
onSave();
} catch (err) {
setError(err instanceof Error ? err.message : "Invalid config or save failed.");
} finally {
setSaving(false);
}
}
return (
<form onSubmit={handleSubmit} className="bg-gray-900 border border-gray-700 rounded-xl p-5 space-y-4 font-mono">
<h3 className="text-white font-semibold">{initial ? "Edit System" : "New System"}</h3>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs text-gray-400 block mb-1">Name</label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
placeholder="Westchester County P25"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">Type</label>
<select
value={type}
onChange={(e) => handleTypeChange(e.target.value)}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
>
<option>P25</option>
<option>DMR</option>
<option>NBFM</option>
</select>
</div>
</div>
{type === "P25" && !showRaw ? (
<P25Form value={p25} onChange={setP25} />
) : (
<div>
<label className="text-xs text-gray-400 block mb-1">Config (JSON)</label>
<textarea
value={rawJson}
onChange={(e) => setRawJson(e.target.value)}
rows={10}
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-xs font-mono focus:outline-none focus:border-indigo-500"
/>
</div>
)}
{type === "P25" && (
<button
type="button"
onClick={toggleRaw}
className="text-xs text-gray-600 hover:text-gray-400 transition-colors"
>
{showRaw ? "← Use structured form" : "Edit raw JSON →"}
</button>
)}
{error && <p className="text-red-400 text-xs">{error}</p>}
<div className="flex gap-3">
<button
type="submit"
disabled={saving}
className="flex-1 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg py-2 text-sm font-semibold transition-colors"
>
{saving ? "Saving…" : "Save"}
</button>
<button
type="button"
onClick={onCancel}
className="flex-1 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg py-2 text-sm transition-colors"
>
Cancel
</button>
</div>
</form>
);
}
// ── Systems list page ─────────────────────────────────────────────────────────
export default function SystemsPage() {
const { systems, loading } = useSystems();
const [editing, setEditing] = useState<SystemRecord | null | "new">(null);
async function handleDelete(id: string) {
if (!confirm("Delete this system?")) return;
await c2api.deleteSystem(id);
}
return (
<div className="space-y-6 max-w-3xl">
<div className="flex items-center justify-between">
<h1 className="text-xl font-bold text-white font-mono">Systems</h1>
<button
onClick={() => setEditing("new")}
className="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded-lg text-sm font-mono transition-colors"
>
+ New System
</button>
</div>
{editing && (
<SystemForm
initial={editing === "new" ? undefined : editing}
onSave={() => setEditing(null)}
onCancel={() => setEditing(null)}
/>
)}
{loading ? (
<p className="text-gray-600 text-sm font-mono">Loading</p>
) : systems.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No systems defined yet.</p>
) : (
<div className="space-y-3">
{systems.map((s) => {
const tgCount = Array.isArray(s.config.talkgroups)
? (s.config.talkgroups as unknown[]).length
: null;
const ccCount = Array.isArray(s.config.control_channels)
? (s.config.control_channels as unknown[]).length
: null;
return (
<div key={s.system_id} className="bg-gray-900 border border-gray-800 rounded-lg p-4 font-mono">
<div className="flex items-start justify-between">
<div>
<p className="text-white font-semibold">{s.name}</p>
<p className="text-xs text-gray-500">{s.system_id}</p>
{(s.config.nac || ccCount !== null || tgCount !== null) && (
<p className="text-xs text-gray-600 mt-0.5 space-x-2">
{!!s.config.nac && <span>NAC {String(s.config.nac)}</span>}
{ccCount !== null && <span>· {ccCount} CC</span>}
{tgCount !== null && <span>· {tgCount} TGs</span>}
</p>
)}
</div>
<span className="text-xs bg-gray-800 border border-gray-700 text-gray-400 px-2 py-0.5 rounded">
{s.type}
</span>
</div>
<div className="mt-3 flex gap-3">
<button
onClick={() => setEditing(s)}
className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"
>
Edit
</button>
<button
onClick={() => handleDelete(s.system_id)}
className="text-xs text-red-500 hover:text-red-400 transition-colors"
>
Delete
</button>
</div>
</div>
);
})}
</div>
)}
</div>
);
}
+181
View File
@@ -0,0 +1,181 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { c2api } from "@/lib/c2api";
import { useAuth } from "@/components/AuthProvider";
interface TokenRecord {
token_id: string;
name: string;
token: string; // masked server-side
in_use: boolean;
assigned_node_id: string | null;
assigned_at: string | null;
}
export default function TokensPage() {
const { isAdmin, loading: authLoading } = useAuth();
const router = useRouter();
const [tokens, setTokens] = useState<TokenRecord[]>([]);
const [loading, setLoading] = useState(true);
const [showAdd, setShowAdd] = useState(false);
const [name, setName] = useState("");
const [token, setToken] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!authLoading && !isAdmin) router.replace("/dashboard");
}, [authLoading, isAdmin, router]);
const refresh = useCallback(async () => {
try {
const data = await c2api.getTokens();
setTokens(data as TokenRecord[]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => { refresh(); }, [refresh]);
async function handleAdd(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
setError(null);
try {
await c2api.addToken({ name, token });
setName("");
setToken("");
setShowAdd(false);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to add token.");
} finally {
setSaving(false);
}
}
async function handleDelete(id: string) {
if (!confirm("Remove this token from the pool?")) return;
try {
await c2api.deleteToken(id);
await refresh();
} catch (err) {
alert(err instanceof Error ? err.message : "Delete failed.");
}
}
if (authLoading || !isAdmin) return null;
return (
<div className="space-y-6 max-w-2xl">
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-bold text-white font-mono">Bot Token Pool</h1>
<p className="text-xs text-gray-500 font-mono mt-0.5">
Discord bot tokens assigned to nodes when they join a voice channel.
</p>
</div>
<button
onClick={() => setShowAdd(!showAdd)}
className="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded-lg text-sm font-mono transition-colors"
>
+ Add Token
</button>
</div>
{showAdd && (
<form onSubmit={handleAdd} className="bg-gray-900 border border-gray-700 rounded-xl p-5 space-y-4 font-mono">
<h3 className="text-white font-semibold text-sm">Add Token</h3>
<div>
<label className="text-xs text-gray-400 block mb-1">Label</label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
placeholder="DRB Bot 1"
/>
</div>
<div>
<label className="text-xs text-gray-400 block mb-1">Discord Bot Token</label>
<input
value={token}
onChange={(e) => setToken(e.target.value)}
required
type="password"
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
placeholder="MTxxxxxxxxxx.Gxxxxx.xxxxxxxxxx"
/>
</div>
{error && <p className="text-red-400 text-xs">{error}</p>}
<div className="flex gap-3">
<button
type="submit"
disabled={saving}
className="flex-1 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg py-2 text-sm font-semibold transition-colors"
>
{saving ? "Saving…" : "Save"}
</button>
<button
type="button"
onClick={() => setShowAdd(false)}
className="flex-1 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg py-2 text-sm transition-colors"
>
Cancel
</button>
</div>
</form>
)}
{loading ? (
<p className="text-gray-600 text-sm font-mono">Loading</p>
) : tokens.length === 0 ? (
<p className="text-gray-600 text-sm font-mono">No tokens in the pool. Add one to enable Discord voice streaming.</p>
) : (
<div className="border border-gray-800 rounded-lg overflow-hidden font-mono">
<table className="w-full text-sm">
<thead>
<tr className="bg-gray-900 text-xs text-gray-500 uppercase tracking-wider">
<th className="px-4 py-2.5 text-left">Label</th>
<th className="px-4 py-2.5 text-left">Token</th>
<th className="px-4 py-2.5 text-left">Status</th>
<th className="px-4 py-2.5 text-left">Node</th>
<th className="px-4 py-2.5 w-16"></th>
</tr>
</thead>
<tbody>
{tokens.map((t) => (
<tr key={t.token_id} className="border-t border-gray-800 hover:bg-gray-900/50">
<td className="px-4 py-2.5 text-white">{t.name}</td>
<td className="px-4 py-2.5 text-gray-500 text-xs">{t.token}</td>
<td className="px-4 py-2.5">
{t.in_use ? (
<span className="text-xs text-green-400 bg-green-400/10 px-2 py-0.5 rounded">In use</span>
) : (
<span className="text-xs text-gray-500 bg-gray-800 px-2 py-0.5 rounded">Free</span>
)}
</td>
<td className="px-4 py-2.5 text-gray-500 text-xs">
{t.assigned_node_id ?? "—"}
</td>
<td className="px-4 py-2.5 text-right">
<button
onClick={() => handleDelete(t.token_id)}
disabled={t.in_use}
className="text-xs text-red-600 hover:text-red-400 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
>
Remove
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}