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
+4
View File
@@ -0,0 +1,4 @@
node_modules
.next
.git
*.log
+12
View File
@@ -0,0 +1,12 @@
# Firebase — get these from your Firebase project settings
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
# Named Firestore database (omit or set to "(default)" if using the default database)
NEXT_PUBLIC_FIRESTORE_DATABASE=
# C2 API — must be reachable from the browser (or a server-side proxy)
NEXT_PUBLIC_C2_URL=http://localhost:8888
+17
View File
@@ -0,0 +1,17 @@
FROM node:20-slim AS builder
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build
FROM node:20-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]
+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>
);
}
+57
View File
@@ -0,0 +1,57 @@
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { onAuthStateChanged, signOut as firebaseSignOut, User } from "firebase/auth";
import { auth } from "@/lib/firebase";
interface AuthContextType {
user: User | null;
loading: boolean;
isAdmin: boolean;
signOut: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType>({
user: null,
loading: true,
isAdmin: false,
signOut: async () => {},
});
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
return onAuthStateChanged(auth, async (u) => {
setUser(u);
setLoading(false);
if (u) {
document.cookie = "drb_session=1; path=/; SameSite=Strict";
// Read custom claims to determine admin status
const result = await u.getIdTokenResult(true);
setIsAdmin(!!result.claims.admin);
} else {
document.cookie = "drb_session=; path=/; max-age=0";
setIsAdmin(false);
}
});
}, []);
async function signOut() {
await firebaseSignOut(auth);
document.cookie = "drb_session=; path=/; max-age=0";
}
return (
<AuthContext.Provider value={{ user, loading, isAdmin, signOut }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
return useContext(AuthContext);
}
+51
View File
@@ -0,0 +1,51 @@
import type { CallRecord } from "@/lib/types";
interface Props {
call: CallRecord;
systemName?: string;
}
function duration(started: string, ended: string | null): string {
if (!ended) return "active";
const ms = new Date(ended).getTime() - new Date(started).getTime();
const s = Math.floor(ms / 1000);
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
}
export function CallRow({ call, systemName }: Props) {
const isActive = call.status === "active";
return (
<tr className="border-b border-gray-800 hover:bg-gray-900/50 font-mono text-sm">
<td className="px-4 py-2 text-gray-400 text-xs">
{new Date(call.started_at).toLocaleTimeString()}
</td>
<td className="px-4 py-2 text-gray-300">
{call.talkgroup_name || call.talkgroup_id || "—"}
</td>
<td className="px-4 py-2 text-gray-400">{systemName ?? call.system_id ?? "—"}</td>
<td className="px-4 py-2 text-gray-400">{call.node_id}</td>
<td className="px-4 py-2">
{isActive ? (
<span className="text-orange-400 animate-pulse"> live</span>
) : (
<span className="text-gray-500">{duration(call.started_at, call.ended_at)}</span>
)}
</td>
<td className="px-4 py-2">
{call.audio_url ? (
<a
href={call.audio_url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-400 hover:text-blue-300 text-xs"
>
audio
</a>
) : (
<span className="text-gray-700 text-xs"></span>
)}
</td>
</tr>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import { useEffect } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
import L from "leaflet";
import type { NodeRecord, CallRecord } from "@/lib/types";
import "leaflet/dist/leaflet.css";
// Fix Leaflet default icon paths broken by webpack
delete (L.Icon.Default.prototype as unknown as Record<string, unknown>)._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
});
const nodeIcon = (status: string) =>
L.divIcon({
className: "",
html: `<div style="
width:14px;height:14px;border-radius:50%;
background:${status === "online" || status === "recording" ? "#4ade80" : status === "unconfigured" ? "#818cf8" : "#6b7280"};
border:2px solid #111827;
box-shadow:0 0 6px ${status === "recording" ? "#fb923c" : "transparent"};
"></div>`,
iconSize: [14, 14],
iconAnchor: [7, 7],
});
interface Props {
nodes: NodeRecord[];
activeCalls: CallRecord[];
}
export default function MapView({ nodes, activeCalls }: Props) {
const activeByNode = Object.fromEntries(
activeCalls.map((c) => [c.node_id, c])
);
const center: [number, number] =
nodes.length > 0 ? [nodes[0].lat, nodes[0].lon] : [39.5, -98.35];
return (
<MapContainer
center={center}
zoom={nodes.length > 0 ? 10 : 4}
className="w-full h-full rounded-lg"
style={{ background: "#111827" }}
>
<TileLayer
url="https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
attribution='&copy; <a href="https://carto.com/">CARTO</a>'
/>
{nodes.map((node) => (
<Marker
key={node.node_id}
position={[node.lat, node.lon]}
icon={nodeIcon(node.status)}
>
<Popup className="font-mono">
<div className="text-gray-900">
<p className="font-bold">{node.name}</p>
<p className="text-xs text-gray-500">{node.node_id}</p>
<p className="text-xs mt-1 capitalize">{node.status}</p>
{activeByNode[node.node_id] && (
<p className="text-xs text-orange-600 mt-1">
TG {activeByNode[node.node_id].talkgroup_id ?? "—"}{" "}
{activeByNode[node.node_id].talkgroup_name}
</p>
)}
</div>
</Popup>
</Marker>
))}
</MapContainer>
);
}
+58
View File
@@ -0,0 +1,58 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useUnconfiguredNodes } from "@/lib/useNodes";
import { useAuth } from "@/components/AuthProvider";
const links = [
{ href: "/dashboard", label: "Dashboard" },
{ href: "/nodes", label: "Nodes" },
{ href: "/systems", label: "Systems" },
{ href: "/calls", label: "Calls" },
{ href: "/map", label: "Map" },
];
const adminLinks = [
{ href: "/tokens", label: "Tokens" },
];
export function Nav() {
const { user, isAdmin, signOut } = useAuth();
const pathname = usePathname();
const { nodes: pending } = useUnconfiguredNodes();
if (!user) return null;
return (
<nav className="border-b border-gray-800 bg-gray-950 px-6 py-3 flex items-center gap-6">
<span className="font-mono font-bold text-white tracking-tight mr-4">DRB</span>
{[...links, ...(isAdmin ? adminLinks : [])].map(({ href, label }) => (
<Link
key={href}
href={href}
className={`text-sm font-mono transition-colors ${
pathname.startsWith(href)
? "text-white"
: "text-gray-500 hover:text-gray-300"
}`}
>
{label}
{label === "Nodes" && pending.length > 0 && (
<span className="ml-1.5 inline-flex items-center justify-center w-4 h-4 rounded-full bg-yellow-500 text-gray-950 text-xs font-bold">
{pending.length}
</span>
)}
</Link>
))}
<div className="ml-auto">
<button
onClick={signOut}
className="text-sm font-mono text-gray-500 hover:text-gray-300 transition-colors"
>
Sign out
</button>
</div>
</nav>
);
}
+51
View File
@@ -0,0 +1,51 @@
import Link from "next/link";
import { StatusBadge } from "@/components/StatusBadge";
import type { NodeRecord, SystemRecord } from "@/lib/types";
interface Props {
node: NodeRecord;
system?: SystemRecord;
}
export function NodeCard({ node, system }: Props) {
const lastSeen = node.last_seen
? new Date(node.last_seen).toLocaleTimeString()
: "never";
return (
<Link href={`/nodes/${node.node_id}`}>
<div className="bg-gray-900 border border-gray-800 rounded-lg p-4 hover:border-gray-600 transition-colors cursor-pointer">
<div className="flex items-start justify-between mb-3">
<div>
<p className="font-mono font-semibold text-white">{node.name}</p>
<p className="text-xs text-gray-500 font-mono">{node.node_id}</p>
</div>
<StatusBadge status={node.status} />
</div>
<div className="space-y-1 text-xs font-mono text-gray-400">
<div className="flex justify-between">
<span>System</span>
<span className="text-gray-300">{system?.name ?? "Unassigned"}</span>
</div>
<div className="flex justify-between">
<span>Location</span>
<span className="text-gray-300">
{node.lat != null && node.lon != null
? `${node.lat.toFixed(4)}, ${node.lon.toFixed(4)}`
: "Unknown"}
</span>
</div>
<div className="flex justify-between">
<span>Last seen</span>
<span className="text-gray-300">{lastSeen}</span>
</div>
</div>
{!node.configured && (
<div className="mt-3 text-xs text-indigo-400 font-mono border-t border-gray-800 pt-2">
Needs configuration
</div>
)}
</div>
</Link>
);
}
@@ -0,0 +1,82 @@
"use client";
import { useState } from "react";
import { c2api } from "@/lib/c2api";
import type { NodeRecord, SystemRecord } from "@/lib/types";
interface Props {
node: NodeRecord;
systems: SystemRecord[];
onClose: () => void;
}
export function NodeConfigModal({ node, systems, onClose }: Props) {
const [systemId, setSystemId] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!systemId) return;
setSaving(true);
setError(null);
try {
await c2api.assignSystem(node.node_id, systemId);
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to assign system.");
} finally {
setSaving(false);
}
}
return (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-6 w-full max-w-md font-mono">
<h2 className="text-white font-semibold mb-1">Configure Node</h2>
<p className="text-gray-400 text-sm mb-5">
<span className="text-indigo-400">{node.node_id}</span> connected for the first time.
Assign it a radio system to begin monitoring.
</p>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs text-gray-400 mb-1">Radio System</label>
<select
value={systemId}
onChange={(e) => setSystemId(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"
required
>
<option value="">Select a system</option>
{systems.map((s) => (
<option key={s.system_id} value={s.system_id}>
{s.name} ({s.type})
</option>
))}
</select>
</div>
{error && <p className="text-red-400 text-xs">{error}</p>}
<div className="flex gap-3 pt-1">
<button
type="submit"
disabled={saving || !systemId}
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…" : "Assign & Configure"}
</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>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import type { NodeStatus } from "@/lib/types";
const styles: Record<NodeStatus, string> = {
online: "bg-green-950 text-green-400 border border-green-800",
recording: "bg-orange-950 text-orange-400 border border-orange-800 animate-pulse",
offline: "bg-gray-900 text-gray-500 border border-gray-700",
unconfigured: "bg-indigo-950 text-indigo-400 border border-indigo-800",
};
export function StatusBadge({ status }: { status: NodeStatus }) {
return (
<span className={`inline-block px-2 py-0.5 rounded-full text-xs font-semibold uppercase tracking-wide ${styles[status] ?? styles.offline}`}>
{status}
</span>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { auth } from "@/lib/firebase";
const BASE = process.env.NEXT_PUBLIC_C2_URL ?? "http://localhost:8000";
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const user = auth.currentUser;
const token = user ? await user.getIdToken() : null;
const res = await fetch(`${BASE}${path}`, {
...options,
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(options?.headers as Record<string, string> | undefined),
},
});
if (!res.ok) throw new Error(`C2 API error ${res.status}: ${await res.text()}`);
if (res.status === 204) return undefined as T;
return res.json();
}
export const c2api = {
// Nodes
getNodes: () => request<unknown[]>("/nodes"),
getNode: (id: string) => request<unknown>(`/nodes/${id}`),
sendCommand: (nodeId: string, payload: object) =>
request(`/nodes/${nodeId}/command`, { method: "POST", body: JSON.stringify(payload) }),
assignSystem: (nodeId: string, systemId: string) =>
request(`/nodes/${nodeId}/config/${systemId}`, { method: "POST" }),
// Systems
getSystems: () => request<unknown[]>("/systems"),
createSystem: (body: object) =>
request("/systems", { method: "POST", body: JSON.stringify(body) }),
updateSystem: (id: string, body: object) =>
request(`/systems/${id}`, { method: "PUT", body: JSON.stringify(body) }),
deleteSystem: (id: string) =>
request(`/systems/${id}`, { method: "DELETE" }),
// Tokens
getTokens: () => request<unknown[]>("/tokens"),
addToken: (body: { name: string; token: string }) =>
request("/tokens", { method: "POST", body: JSON.stringify(body) }),
deleteToken: (id: string) =>
request(`/tokens/${id}`, { method: "DELETE" }),
// Node approval
approveNode: (id: string) =>
request(`/nodes/${id}/approve`, { method: "POST" }),
rejectNode: (id: string) =>
request(`/nodes/${id}/reject`, { method: "POST" }),
// Calls
getCalls: (params?: Record<string, string>) => {
const qs = params ? "?" + new URLSearchParams(params).toString() : "";
return request<unknown[]>(`/calls${qs}`);
},
};
+18
View File
@@ -0,0 +1,18 @@
import { initializeApp, getApps, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
const app = getApps().length ? getApp() : initializeApp(firebaseConfig);
const databaseId = process.env.NEXT_PUBLIC_FIRESTORE_DATABASE || "(default)";
export const db = getFirestore(app, databaseId);
export const auth = getAuth(app);
export { app };
+51
View File
@@ -0,0 +1,51 @@
export type NodeStatus = "online" | "offline" | "recording" | "unconfigured";
export type ApprovalStatus = "pending" | "approved" | "rejected";
export interface NodeRecord {
node_id: string;
name: string;
lat: number;
lon: number;
status: NodeStatus;
configured: boolean;
last_seen: string | null;
assigned_system_id: string | null;
approval_status: ApprovalStatus | null;
}
export interface SystemRecord {
system_id: string;
name: string;
type: string; // P25 | DMR | NBFM
config: Record<string, unknown>;
}
export interface CallRecord {
call_id: string;
node_id: string;
system_id: string | null;
talkgroup_id: number | null;
talkgroup_name: string | null;
freq: number | null;
started_at: string;
ended_at: string | null;
audio_url: string | null;
transcript: string | null;
incident_id: string | null;
location: { lat: number; lng: number } | null;
tags: string[];
status: "active" | "ended";
}
export interface IncidentRecord {
incident_id: string;
title: string | null;
type: string | null;
status: "active" | "resolved";
location: { lat: number; lng: number } | null;
call_ids: string[];
started_at: string;
updated_at: string;
summary: string | null;
tags: string[];
}
+73
View File
@@ -0,0 +1,73 @@
"use client";
import { useEffect, useState } from "react";
import { collection, onSnapshot, query, orderBy, limit, where, FirestoreError } from "firebase/firestore";
import { onAuthStateChanged } from "firebase/auth";
import { db, auth } from "@/lib/firebase";
import type { CallRecord } from "@/lib/types";
export function useCalls(limitCount = 50) {
const [calls, setCalls] = useState<CallRecord[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let unsubFirestore: (() => void) | undefined;
const unsubAuth = onAuthStateChanged(auth, (user) => {
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
if (!user) {
setCalls([]);
setLoading(false);
return;
}
const q = query(
collection(db, "calls"),
orderBy("started_at", "desc"),
limit(limitCount)
);
unsubFirestore = onSnapshot(q, (snap) => {
setCalls(snap.docs.map((d) => d.data() as CallRecord));
setLoading(false);
}, (err: FirestoreError) => { console.error("useCalls:", err); setError(err.message); setLoading(false); });
});
return () => {
unsubAuth();
if (unsubFirestore) unsubFirestore();
};
}, [limitCount]);
return { calls, loading, error };
}
export function useActiveCalls() {
const [calls, setCalls] = useState<CallRecord[]>([]);
useEffect(() => {
let unsubFirestore: (() => void) | undefined;
const unsubAuth = onAuthStateChanged(auth, (user) => {
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
if (!user) {
setCalls([]);
return;
}
const q = query(collection(db, "calls"), where("status", "==", "active"));
unsubFirestore = onSnapshot(q, (snap) => {
setCalls(snap.docs.map((d) => d.data() as CallRecord));
}, (err: FirestoreError) => { console.error("useActiveCalls:", err); });
});
return () => {
unsubAuth();
if (unsubFirestore) unsubFirestore();
};
}, []);
return calls;
}
+48
View File
@@ -0,0 +1,48 @@
"use client";
import { useEffect, useState } from "react";
import { collection, onSnapshot, query, FirestoreError } from "firebase/firestore";
import { onAuthStateChanged } from "firebase/auth";
import { db, auth } from "@/lib/firebase";
import type { NodeRecord } from "@/lib/types";
export function useNodes() {
const [nodes, setNodes] = useState<NodeRecord[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let unsubFirestore: (() => void) | undefined;
const unsubAuth = onAuthStateChanged(auth, (user) => {
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
if (!user) {
setNodes([]);
setLoading(false);
return;
}
const q = query(collection(db, "nodes"));
unsubFirestore = onSnapshot(q, (snap) => {
setNodes(snap.docs.map((d) => d.data() as NodeRecord));
setLoading(false);
}, (err: FirestoreError) => { console.error("useNodes:", err); setError(err.message); setLoading(false); });
});
return () => {
unsubAuth();
if (unsubFirestore) unsubFirestore();
};
}, []);
return { nodes, loading, error };
}
export function useUnconfiguredNodes() {
const { nodes, loading } = useNodes();
return {
nodes: nodes.filter((n) => !n.configured),
loading,
};
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { useEffect, useState } from "react";
import { collection, onSnapshot, FirestoreError } from "firebase/firestore";
import { onAuthStateChanged } from "firebase/auth";
import { db, auth } from "@/lib/firebase";
import type { SystemRecord } from "@/lib/types";
export function useSystems() {
const [systems, setSystems] = useState<SystemRecord[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let unsubFirestore: (() => void) | undefined;
const unsubAuth = onAuthStateChanged(auth, (user) => {
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
if (!user) {
setSystems([]);
setLoading(false);
return;
}
unsubFirestore = onSnapshot(collection(db, "systems"), (snap) => {
setSystems(snap.docs.map((d) => d.data() as SystemRecord));
setLoading(false);
}, (err: FirestoreError) => { console.error("useSystems:", err); setError(err.message); setLoading(false); });
});
return () => {
unsubAuth();
if (unsubFirestore) unsubFirestore();
};
}, []);
return { systems, loading, error };
}
+20
View File
@@ -0,0 +1,20 @@
import { NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) {
const session = request.cookies.get("drb_session");
const { pathname } = request.nextUrl;
if (pathname === "/login") {
if (session) return NextResponse.redirect(new URL("/dashboard", request.url));
return NextResponse.next();
}
if (!session) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon\\.ico).*)"],
};
+6
View File
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
};
export default nextConfig;
+28
View File
@@ -0,0 +1,28 @@
{
"name": "drb-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^15",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"firebase": "^10.12.0",
"leaflet": "^1.9.4",
"react-leaflet": "^4.2.1"
},
"devDependencies": {
"typescript": "^5.4.0",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@types/node": "^20.12.0",
"@types/leaflet": "^1.9.12",
"tailwindcss": "^3.4.0",
"postcss": "^8.4.0",
"autoprefixer": "^10.4.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+18
View File
@@ -0,0 +1,18 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./app/**/*.{ts,tsx}",
"./components/**/*.{ts,tsx}",
],
theme: {
extend: {
fontFamily: {
mono: ["ui-monospace", "Cascadia Code", "Source Code Pro", "monospace"],
},
},
},
plugins: [],
};
export default config;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}