Initial implementation of Bluetooth toy control app
Next.js app with a browser-side buttplug/buttplug-wasm control layer (server never touches real-time device commands), SQLite storage via Drizzle, single-secret auth, recordings/replay with device remapping, a usage stats dashboard, Docker deployment, and Gitea CI. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W8WkFF5ppURBAB918593Eb
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { autoMapDeviceSlots } from "@/lib/buttplug/device-remap";
|
||||
import type { RecordingDeviceSlot } from "@/lib/db/schema";
|
||||
import type { ConnectedDeviceInfo } from "@/lib/buttplug/types";
|
||||
|
||||
interface DeviceRemapDialogProps {
|
||||
open: boolean;
|
||||
deviceSlots: RecordingDeviceSlot[];
|
||||
connectedDevices: ConnectedDeviceInfo[];
|
||||
onCancel: () => void;
|
||||
onConfirm: (mapping: Map<number, number>) => void;
|
||||
}
|
||||
|
||||
export function DeviceRemapDialog({
|
||||
open,
|
||||
deviceSlots,
|
||||
connectedDevices,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: DeviceRemapDialogProps) {
|
||||
const autoMapped = autoMapDeviceSlots(deviceSlots, connectedDevices);
|
||||
const [assignments, setAssignments] = useState<Record<number, number | null>>(
|
||||
Object.fromEntries(deviceSlots.map((slot, i) => [slot.sourceSessionDeviceId, autoMapped[i]?.matchedDeviceIndex ?? null])),
|
||||
);
|
||||
|
||||
const allAssigned = deviceSlots.every((s) => assignments[s.sourceSessionDeviceId] !== null);
|
||||
|
||||
function handleConfirm() {
|
||||
const mapping = new Map<number, number>();
|
||||
for (const slot of deviceSlots) {
|
||||
const deviceIndex = assignments[slot.sourceSessionDeviceId];
|
||||
if (deviceIndex !== null && deviceIndex !== undefined) mapping.set(slot.sourceSessionDeviceId, deviceIndex);
|
||||
}
|
||||
onConfirm(mapping);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onCancel()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Match devices for replay</DialogTitle>
|
||||
<DialogDescription>
|
||||
Web Bluetooth doesn't expose a stable device id across sessions, so match each recorded
|
||||
device to a currently-connected one. Two identically-named devices can't be told apart
|
||||
automatically.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-3">
|
||||
{deviceSlots.map((slot) => (
|
||||
<div key={slot.sourceSessionDeviceId} className="flex items-center justify-between gap-3">
|
||||
<span className="text-sm font-medium">{slot.slotLabel}</span>
|
||||
<Select
|
||||
value={assignments[slot.sourceSessionDeviceId]?.toString() ?? undefined}
|
||||
onValueChange={(v) =>
|
||||
setAssignments((prev) => ({ ...prev, [slot.sourceSessionDeviceId]: Number(v) }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-48">
|
||||
<SelectValue placeholder="Unmatched" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{connectedDevices.map((d) => (
|
||||
<SelectItem key={d.index} value={d.index.toString()}>
|
||||
{d.displayName ?? d.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!allAssigned}>
|
||||
Start replay
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Play, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export interface RecordingRow {
|
||||
id: number;
|
||||
name: string;
|
||||
durationMs: number;
|
||||
playCount: number;
|
||||
lastPlayedAt: number | null;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
function formatDuration(ms: number): string {
|
||||
const totalSeconds = Math.round(ms / 1000);
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function RecordingsTable({ recordings }: { recordings: RecordingRow[] }) {
|
||||
const router = useRouter();
|
||||
|
||||
async function handleDelete(id: number) {
|
||||
const res = await fetch(`/api/recordings/${id}`, { method: "DELETE" });
|
||||
if (res.ok) {
|
||||
toast.success("Recording deleted");
|
||||
router.refresh();
|
||||
} else {
|
||||
toast.error("Could not delete recording");
|
||||
}
|
||||
}
|
||||
|
||||
if (recordings.length === 0) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No recordings yet - start a session on the Control page and save it when you're done.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Duration</TableHead>
|
||||
<TableHead>Plays</TableHead>
|
||||
<TableHead>Last played</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{recordings.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`/recordings/${r.id}`} className="hover:underline">
|
||||
{r.name}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>{formatDuration(r.durationMs)}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="secondary">{r.playCount}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{r.lastPlayedAt ? new Date(r.lastPlayedAt).toLocaleString() : "Never"}
|
||||
</TableCell>
|
||||
<TableCell className="flex justify-end gap-1">
|
||||
<Button asChild variant="ghost" size="icon-sm">
|
||||
<Link href={`/recordings/${r.id}/replay`} aria-label="Replay">
|
||||
<Play className="size-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" onClick={() => void handleDelete(r.id)} aria-label="Delete">
|
||||
<Trash2 className="size-3.5" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
import { DeviceScanPanel } from "@/components/control/DeviceScanPanel";
|
||||
import { DeviceRemapDialog } from "./DeviceRemapDialog";
|
||||
import { getButtplugClientHandle, startScanning, stopScanning } from "@/lib/buttplug/client";
|
||||
import { eventBuffer } from "@/lib/buttplug/event-buffer";
|
||||
import { RecordingPlayer, type RecordingEventRow } from "@/lib/buttplug/player";
|
||||
import { useButtplugStore } from "@/lib/buttplug/store";
|
||||
import type { ActuatorInfo } from "@/lib/buttplug/types";
|
||||
import type { RecordingDeviceSlot } from "@/lib/db/schema";
|
||||
import { Pause, Play } from "lucide-react";
|
||||
|
||||
interface RecordingResponse {
|
||||
recording: {
|
||||
id: number;
|
||||
name: string;
|
||||
durationMs: number;
|
||||
deviceSlots: RecordingDeviceSlot[];
|
||||
};
|
||||
events: RecordingEventRow[];
|
||||
}
|
||||
|
||||
function formatTime(ms: number): string {
|
||||
const totalSeconds = Math.floor(ms / 1000);
|
||||
return `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
const router = useRouter();
|
||||
const scanning = useButtplugStore((s) => s.scanning);
|
||||
const devices = useButtplugStore((s) => s.devices);
|
||||
const connectedDevices = useMemo(() => Object.values(devices), [devices]);
|
||||
|
||||
const [data, setData] = useState<RecordingResponse | null>(null);
|
||||
const [showRemap, setShowRemap] = useState(false);
|
||||
const [player, setPlayer] = useState<RecordingPlayer | null>(null);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [elapsedMs, setElapsedMs] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`/api/recordings/${recordingId}`)
|
||||
.then((r) => r.json())
|
||||
.then(setData)
|
||||
.catch(() => toast.error("Could not load recording"));
|
||||
}, [recordingId]);
|
||||
|
||||
async function handleConfirmRemap(mapping: Map<number, number>) {
|
||||
if (!data) return;
|
||||
setShowRemap(false);
|
||||
|
||||
const orderedSlots = data.recording.deviceSlots.filter((s) => mapping.has(s.sourceSessionDeviceId));
|
||||
const body = {
|
||||
kind: "replay" as const,
|
||||
replayedRecordingId: data.recording.id,
|
||||
devices: orderedSlots.map((slot) => {
|
||||
const deviceIndex = mapping.get(slot.sourceSessionDeviceId)!;
|
||||
const device = connectedDevices.find((d) => d.index === deviceIndex)!;
|
||||
return { slotLabel: slot.slotLabel, bleName: device.name };
|
||||
}),
|
||||
};
|
||||
|
||||
const res = await fetch("/api/play-sessions", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error("Could not start replay session");
|
||||
return;
|
||||
}
|
||||
const result: { session: { id: number; startedAt: number }; sessionDevices: { id: number }[] } =
|
||||
await res.json();
|
||||
|
||||
eventBuffer.start(result.session.id, result.session.startedAt);
|
||||
const sessionDeviceIdToDeviceIndex = new Map<number, number>();
|
||||
orderedSlots.forEach((slot, i) => {
|
||||
const deviceIndex = mapping.get(slot.sourceSessionDeviceId)!;
|
||||
const newSessionDeviceId = result.sessionDevices[i]?.id;
|
||||
if (newSessionDeviceId !== undefined) {
|
||||
eventBuffer.registerSessionDevice(deviceIndex, newSessionDeviceId);
|
||||
sessionDeviceIdToDeviceIndex.set(slot.sourceSessionDeviceId, deviceIndex);
|
||||
}
|
||||
});
|
||||
|
||||
const actuatorsByDeviceIndex = new Map<number, ActuatorInfo[]>(
|
||||
connectedDevices.map((d) => [d.index, d.actuators]),
|
||||
);
|
||||
|
||||
const { runtime } = await getButtplugClientHandle();
|
||||
const instance = new RecordingPlayer({
|
||||
events: data.events,
|
||||
sessionDeviceIdToDeviceIndex,
|
||||
actuatorsByDeviceIndex,
|
||||
runtime,
|
||||
onProgress: (elapsed) => setElapsedMs(elapsed),
|
||||
onComplete: async () => {
|
||||
setPlaying(false);
|
||||
eventBuffer.stop();
|
||||
await fetch(`/api/play-sessions/${result.session.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status: "completed" }),
|
||||
});
|
||||
toast.success("Replay finished");
|
||||
},
|
||||
});
|
||||
setPlayer(instance);
|
||||
instance.play();
|
||||
setPlaying(true);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return <p className="text-sm text-muted-foreground">Loading recording...</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<Card className="bp-glass">
|
||||
<CardHeader>
|
||||
<CardTitle>{data.recording.name}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{!player ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connect the devices you want to replay onto, then match them to the recording's
|
||||
original device slots.
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<DeviceScanPanel scanning={scanning} onScan={() => void startScanning()} onStopScan={() => void stopScanning()} />
|
||||
<Button
|
||||
onClick={async () => {
|
||||
await getButtplugClientHandle();
|
||||
setShowRemap(true);
|
||||
}}
|
||||
disabled={connectedDevices.length === 0}
|
||||
>
|
||||
Match devices & replay
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Slider
|
||||
value={[elapsedMs]}
|
||||
max={data.recording.durationMs}
|
||||
onValueChange={([v]) => player.seek(v)}
|
||||
/>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatTime(elapsedMs)} / {formatTime(data.recording.durationMs)}
|
||||
</span>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (playing) {
|
||||
player.pause();
|
||||
setPlaying(false);
|
||||
} else {
|
||||
player.play();
|
||||
setPlaying(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<DeviceRemapDialog
|
||||
open={showRemap}
|
||||
deviceSlots={data.recording.deviceSlots}
|
||||
connectedDevices={connectedDevices}
|
||||
onCancel={() => setShowRemap(false)}
|
||||
onConfirm={(mapping) => void handleConfirmRemap(mapping)}
|
||||
/>
|
||||
|
||||
<Button variant="ghost" size="sm" onClick={() => router.push("/recordings")}>
|
||||
Back to recordings
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
const ReplayPlayer = dynamic(() => import("./ReplayPlayer").then((m) => m.ReplayPlayer), {
|
||||
ssr: false,
|
||||
loading: () => <Skeleton className="h-64 w-full" />,
|
||||
});
|
||||
|
||||
export function ReplayPlayerLoader({ recordingId }: { recordingId: number }) {
|
||||
return <ReplayPlayer recordingId={recordingId} />;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface SaveRecordingDialogProps {
|
||||
playSessionId: number | null;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}
|
||||
|
||||
export function SaveRecordingDialog({ playSessionId, onClose, onSaved }: SaveRecordingDialogProps) {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function handleSave() {
|
||||
if (!playSessionId || name.trim().length === 0) return;
|
||||
setSaving(true);
|
||||
const res = await fetch("/api/recordings", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sourcePlaySessionId: playSessionId, name: name.trim(), description }),
|
||||
});
|
||||
setSaving(false);
|
||||
if (res.ok) {
|
||||
toast.success("Recording saved");
|
||||
onSaved();
|
||||
} else {
|
||||
toast.error("Could not save recording");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={playSessionId !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Save session as a recording</DialogTitle>
|
||||
<DialogDescription>Give it a name so you can find and replay it later.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="recording-name">Name</Label>
|
||||
<Input id="recording-name" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="recording-description">Description (optional)</Label>
|
||||
<Input
|
||||
id="recording-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Skip
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={saving || name.trim().length === 0}>
|
||||
{saving ? "Saving..." : "Save recording"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user