- Fix device rename input collapsing on mobile (fixed width vs w-full inside an auto-layout table column). - Add cascade-delete confirmation for sessions with a saved recording. - Fix header connection LED: derive state from scanning/device-count/ recording instead of the Buttplug client's raw connected flag; drop the label text and hide the indicator entirely when idle. - Add a per-device disconnect button (stop + remove from store, the closest equivalent Buttplug's protocol allows per device). - Fix replay ending early: duration now comes from the recording's actual durationMs, not the last event's timestamp. - Replay robustness: show which devices are being replayed to, reset actuators to zero on start/play/pause, fully disconnect devices and the whole client on stop/unmount, surface command failures via toast. - Stop flagging the header LED red during replay - recording is only for live sessions. - Add page-number pagination to recordings/sessions/devices lists. - Wordmark SEXY -> Sexy; add proper per-page <title>s including dynamic titles for recording/session detail and replay pages. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
299 lines
12 KiB
TypeScript
299 lines
12 KiB
TypeScript
"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 { disconnectAll, getButtplugClientHandle, getDevice, 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 setActuatorValue = useButtplugStore((s) => s.setActuatorValue);
|
|
const removeDevice = useButtplugStore((s) => s.removeDevice);
|
|
const connectedDevices = useMemo(() => Object.values(devices), [devices]);
|
|
|
|
const [data, setData] = useState<RecordingResponse | null>(null);
|
|
const [showRemap, setShowRemap] = useState(false);
|
|
const [starting, setStarting] = useState(false);
|
|
const [player, setPlayer] = useState<RecordingPlayer | null>(null);
|
|
const [playing, setPlaying] = useState(false);
|
|
const [elapsedMs, setElapsedMs] = useState(0);
|
|
const [replayTargets, setReplayTargets] = useState<{ slotLabel: string; deviceName: string }[]>([]);
|
|
const [replayDeviceIndexes, setReplayDeviceIndexes] = useState<number[]>([]);
|
|
const [activeSessionId, setActiveSessionId] = useState<number | null>(null);
|
|
|
|
useEffect(() => {
|
|
fetch(`/api/recordings/${recordingId}`)
|
|
.then((r) => r.json())
|
|
.then(setData)
|
|
.catch(() => toast.error("Could not load recording"));
|
|
}, [recordingId]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
void disconnectAll();
|
|
};
|
|
}, []);
|
|
|
|
async function resetReplayDevices() {
|
|
await Promise.all(
|
|
replayDeviceIndexes.map(async (deviceIndex) => {
|
|
const liveDevice = await getDevice(deviceIndex);
|
|
await liveDevice?.stop().catch(() => {});
|
|
devices[deviceIndex]?.actuators.forEach((a) => setActuatorValue(deviceIndex, a.featureIndex, 0));
|
|
}),
|
|
);
|
|
}
|
|
|
|
async function handleConfirmRemap(mapping: Map<number, number>) {
|
|
if (!data) return;
|
|
setShowRemap(false);
|
|
setStarting(true);
|
|
|
|
try {
|
|
const orderedSlots = data.recording.deviceSlots.filter((s) => mapping.has(s.sourceSessionDeviceId));
|
|
const targets = orderedSlots.map((slot) => {
|
|
const deviceIndex = mapping.get(slot.sourceSessionDeviceId)!;
|
|
const device = connectedDevices.find((d) => d.index === deviceIndex)!;
|
|
return { slotLabel: slot.slotLabel, deviceName: device.displayName ?? device.name };
|
|
});
|
|
|
|
const body = {
|
|
kind: "replay" as const,
|
|
replayedRecordingId: data.recording.id,
|
|
devices: orderedSlots.map((slot, i) => ({ slotLabel: slot.slotLabel, bleName: targets[i].deviceName })),
|
|
};
|
|
|
|
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]),
|
|
);
|
|
|
|
// Reset every actuator on every device that will take part in this replay before
|
|
// the first scheduled event fires, so playback always starts from a known-zero
|
|
// state rather than whatever intensity was left over from manual control.
|
|
const deviceIndexes = new Set(sessionDeviceIdToDeviceIndex.values());
|
|
await Promise.all(
|
|
[...deviceIndexes].map(async (deviceIndex) => {
|
|
const liveDevice = await getDevice(deviceIndex);
|
|
await liveDevice?.stop().catch(() => {});
|
|
actuatorsByDeviceIndex.get(deviceIndex)?.forEach((a) => setActuatorValue(deviceIndex, a.featureIndex, 0));
|
|
}),
|
|
);
|
|
|
|
const { runtime } = await getButtplugClientHandle();
|
|
const instance = new RecordingPlayer({
|
|
events: data.events,
|
|
durationMs: data.recording.durationMs,
|
|
sessionDeviceIdToDeviceIndex,
|
|
actuatorsByDeviceIndex,
|
|
runtime,
|
|
onProgress: (elapsed) => setElapsedMs(elapsed),
|
|
onError: (message) => toast.error(`Replay command failed: ${message}`),
|
|
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" }),
|
|
}).catch(() => {});
|
|
toast.success("Replay finished");
|
|
},
|
|
});
|
|
setReplayTargets(targets);
|
|
setReplayDeviceIndexes([...deviceIndexes]);
|
|
setActiveSessionId(result.session.id);
|
|
setPlayer(instance);
|
|
instance.play();
|
|
setPlaying(true);
|
|
} catch {
|
|
toast.error("Could not start replay");
|
|
} finally {
|
|
setStarting(false);
|
|
}
|
|
}
|
|
|
|
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 () => {
|
|
try {
|
|
await getButtplugClientHandle();
|
|
setShowRemap(true);
|
|
} catch {
|
|
toast.error("Could not connect to Buttplug client");
|
|
}
|
|
}}
|
|
disabled={connectedDevices.length === 0 || starting}
|
|
>
|
|
{starting ? "Starting..." : "Match devices & replay"}
|
|
</Button>
|
|
</div>
|
|
</>
|
|
) : (
|
|
<div className="flex flex-col gap-3">
|
|
{replayTargets.length > 0 && (
|
|
<div className="flex flex-wrap gap-2">
|
|
{replayTargets.map((t) => (
|
|
<span
|
|
key={t.slotLabel}
|
|
className="bp-readout rounded-md border border-border bg-card/60 px-2 py-1 text-xs text-muted-foreground"
|
|
>
|
|
{t.slotLabel} → {t.deviceName}
|
|
</span>
|
|
))}
|
|
</div>
|
|
)}
|
|
<Slider
|
|
value={[elapsedMs]}
|
|
max={data.recording.durationMs}
|
|
onValueChange={([v]) => player.seek(v)}
|
|
/>
|
|
<div className="flex items-center justify-between">
|
|
<span className="bp-readout text-xs text-muted-foreground">
|
|
{formatTime(elapsedMs)} / {formatTime(data.recording.durationMs)}
|
|
</span>
|
|
<div className="flex items-center gap-2">
|
|
<Button
|
|
size="icon"
|
|
variant="outline"
|
|
onClick={async () => {
|
|
if (playing) {
|
|
player.pause();
|
|
setPlaying(false);
|
|
} else {
|
|
player.play();
|
|
setPlaying(true);
|
|
}
|
|
// Toggling either way leaves the toy holding whatever intensity was
|
|
// last sent - zero it out so pause always actually stops the device,
|
|
// and resume always starts from a clean, known state.
|
|
await resetReplayDevices();
|
|
}}
|
|
aria-label={playing ? "Pause" : "Play"}
|
|
>
|
|
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="ghost"
|
|
onClick={async () => {
|
|
player.stop();
|
|
setPlaying(false);
|
|
setElapsedMs(0);
|
|
eventBuffer.stop();
|
|
if (activeSessionId !== null) {
|
|
await fetch(`/api/play-sessions/${activeSessionId}`, {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ status: "aborted" }),
|
|
}).catch(() => {});
|
|
}
|
|
// Fully disconnect every device that took part in this replay,
|
|
// not just stop the player - see handleDisconnectDevice in
|
|
// ButtplugConsole for why "stop + remove from store" is the
|
|
// closest equivalent Buttplug's protocol allows per-device.
|
|
await Promise.all(
|
|
replayDeviceIndexes.map(async (deviceIndex) => {
|
|
const liveDevice = await getDevice(deviceIndex);
|
|
await liveDevice?.stop().catch(() => {});
|
|
removeDevice(deviceIndex);
|
|
}),
|
|
);
|
|
setPlayer(null);
|
|
setReplayTargets([]);
|
|
setReplayDeviceIndexes([]);
|
|
setActiveSessionId(null);
|
|
}}
|
|
>
|
|
Stop
|
|
</Button>
|
|
</div>
|
|
</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>
|
|
);
|
|
}
|