Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5484d3cefe | ||
|
|
f97ed6da04 | ||
|
|
0bd36b08c9 | ||
|
|
db507bfe3b |
@@ -1,5 +1,8 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { ButtplugConsoleLoader as ButtplugConsole } from "@/components/control/ButtplugConsoleLoader";
|
import { ButtplugConsoleLoader as ButtplugConsole } from "@/components/control/ButtplugConsoleLoader";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: "Control" };
|
||||||
|
|
||||||
export default function ControlPage() {
|
export default function ControlPage() {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
|
|||||||
@@ -1,11 +1,20 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { DevicesTable } from "@/components/devices/DevicesTable";
|
import { DevicesTable } from "@/components/devices/DevicesTable";
|
||||||
import { listDevices } from "@/lib/db/queries/devices";
|
import { PageNav } from "@/components/shared/PageNav";
|
||||||
|
import { listDevicesPage } from "@/lib/db/queries/devices";
|
||||||
|
import { parsePage } from "@/lib/pagination";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
export const metadata: Metadata = { title: "Devices" };
|
||||||
|
|
||||||
export default async function DevicesPage() {
|
export default async function DevicesPage({
|
||||||
const devices = await listDevices();
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ page?: string }>;
|
||||||
|
}) {
|
||||||
|
const page = parsePage((await searchParams).page);
|
||||||
|
const { items: devices, pageSize, total } = await listDevicesPage(page);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
@@ -17,8 +26,9 @@ export default async function DevicesPage() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-base">Known devices</CardTitle>
|
<CardTitle className="text-base">Known devices</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent className="flex flex-col gap-3">
|
||||||
<DevicesTable devices={devices} />
|
<DevicesTable devices={devices} />
|
||||||
|
<PageNav basePath="/devices" page={page} pageSize={pageSize} total={total} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
import type { Metadata } from "next";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { getRecording } from "@/lib/db/queries/recordings";
|
import { getRecording, getRecordingName } from "@/lib/db/queries/recordings";
|
||||||
import { Play } from "lucide-react";
|
import { Play } from "lucide-react";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
|
||||||
|
const { id } = await params;
|
||||||
|
const name = await getRecordingName(Number(id));
|
||||||
|
return { title: name ?? "Recording" };
|
||||||
|
}
|
||||||
|
|
||||||
function formatDuration(ms: number): string {
|
function formatDuration(ms: number): string {
|
||||||
const totalSeconds = Math.round(ms / 1000);
|
const totalSeconds = Math.round(ms / 1000);
|
||||||
return `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, "0")}`;
|
return `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, "0")}`;
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { ReplayPlayerLoader } from "@/components/recordings/ReplayPlayerLoader";
|
import { ReplayPlayerLoader } from "@/components/recordings/ReplayPlayerLoader";
|
||||||
|
import { getRecordingName } from "@/lib/db/queries/recordings";
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
|
||||||
|
const { id } = await params;
|
||||||
|
const name = await getRecordingName(Number(id));
|
||||||
|
return { title: name ? `Replay ${name}` : "Replay" };
|
||||||
|
}
|
||||||
|
|
||||||
export default async function ReplayPage({ params }: { params: Promise<{ id: string }> }) {
|
export default async function ReplayPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
|||||||
@@ -1,11 +1,20 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { RecordingsTable } from "@/components/recordings/RecordingsTable";
|
import { RecordingsTable } from "@/components/recordings/RecordingsTable";
|
||||||
import { listRecordings } from "@/lib/db/queries/recordings";
|
import { PageNav } from "@/components/shared/PageNav";
|
||||||
|
import { listRecordingsPage } from "@/lib/db/queries/recordings";
|
||||||
|
import { parsePage } from "@/lib/pagination";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
export const metadata: Metadata = { title: "Recordings" };
|
||||||
|
|
||||||
export default async function RecordingsPage() {
|
export default async function RecordingsPage({
|
||||||
const recordings = await listRecordings();
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ page?: string }>;
|
||||||
|
}) {
|
||||||
|
const page = parsePage((await searchParams).page);
|
||||||
|
const { items: recordings, pageSize, total } = await listRecordingsPage(page);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
@@ -17,8 +26,9 @@ export default async function RecordingsPage() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-base">Library</CardTitle>
|
<CardTitle className="text-base">Library</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent className="flex flex-col gap-3">
|
||||||
<RecordingsTable recordings={recordings} />
|
<RecordingsTable recordings={recordings} />
|
||||||
|
<PageNav basePath="/recordings" page={page} pageSize={pageSize} total={total} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,11 +1,18 @@
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
import type { Metadata } from "next";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { SessionTimelineChart } from "@/components/sessions/SessionTimelineChart";
|
import { SessionTimelineChart } from "@/components/sessions/SessionTimelineChart";
|
||||||
import { getPlaySessionDetail } from "@/lib/db/queries/play-sessions";
|
import { getPlaySessionDetail, getPlaySessionName } from "@/lib/db/queries/play-sessions";
|
||||||
import { getSessionTimeline } from "@/lib/db/queries/stats";
|
import { getSessionTimeline } from "@/lib/db/queries/stats";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
|
||||||
|
const { id } = await params;
|
||||||
|
const name = await getPlaySessionName(Number(id));
|
||||||
|
return { title: name ?? `Session #${id}` };
|
||||||
|
}
|
||||||
|
|
||||||
function formatDuration(ms: number | null): string {
|
function formatDuration(ms: number | null): string {
|
||||||
if (ms === null) return "-";
|
if (ms === null) return "-";
|
||||||
const totalSeconds = Math.round(ms / 1000);
|
const totalSeconds = Math.round(ms / 1000);
|
||||||
|
|||||||
@@ -1,11 +1,20 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { SessionsTable } from "@/components/sessions/SessionsTable";
|
import { SessionsTable } from "@/components/sessions/SessionsTable";
|
||||||
import { listPlaySessions } from "@/lib/db/queries/play-sessions";
|
import { PageNav } from "@/components/shared/PageNav";
|
||||||
|
import { listPlaySessionsPage } from "@/lib/db/queries/play-sessions";
|
||||||
|
import { parsePage } from "@/lib/pagination";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
export const metadata: Metadata = { title: "Sessions" };
|
||||||
|
|
||||||
export default async function SessionsPage() {
|
export default async function SessionsPage({
|
||||||
const sessions = [...(await listPlaySessions())].reverse();
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ page?: string }>;
|
||||||
|
}) {
|
||||||
|
const page = parsePage((await searchParams).page);
|
||||||
|
const { items: sessions, pageSize, total } = await listPlaySessionsPage(page);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
@@ -17,8 +26,9 @@ export default async function SessionsPage() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-base">History</CardTitle>
|
<CardTitle className="text-base">History</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent className="flex flex-col gap-3">
|
||||||
<SessionsTable sessions={sessions} />
|
<SessionsTable sessions={sessions} />
|
||||||
|
<PageNav basePath="/sessions" page={page} pageSize={pageSize} total={total} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { SessionsSummaryCards } from "@/components/stats/SessionsSummaryCards";
|
import { SessionsSummaryCards } from "@/components/stats/SessionsSummaryCards";
|
||||||
import { DeviceUsageTable } from "@/components/stats/DeviceUsageTable";
|
import { DeviceUsageTable } from "@/components/stats/DeviceUsageTable";
|
||||||
@@ -5,6 +6,7 @@ import { RecordingLibraryStats } from "@/components/stats/RecordingLibraryStats"
|
|||||||
import { getDeviceCommandCounts, getDeviceUsageStats, getRecordingLibraryStats, getSessionsSummary } from "@/lib/db/queries/stats";
|
import { getDeviceCommandCounts, getDeviceUsageStats, getRecordingLibraryStats, getSessionsSummary } from "@/lib/db/queries/stats";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
export const metadata: Metadata = { title: "Stats" };
|
||||||
|
|
||||||
export default async function StatsPage() {
|
export default async function StatsPage() {
|
||||||
const [sessionsSummary, deviceUsage, commandCounts, recordingStats] = await Promise.all([
|
const [sessionsSummary, deviceUsage, commandCounts, recordingStats] = await Promise.all([
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { deletePlaySession, endPlaySession, getPlaySessionDetail } from "@/lib/db/queries/play-sessions";
|
import { deletePlaySession, endPlaySession, getPlaySessionDetail } from "@/lib/db/queries/play-sessions";
|
||||||
|
import { getRecordingsForSession } from "@/lib/db/queries/recordings";
|
||||||
|
|
||||||
const patchSchema = z.object({ status: z.enum(["completed", "aborted"]) });
|
const patchSchema = z.object({ status: z.enum(["completed", "aborted"]) });
|
||||||
|
|
||||||
@@ -22,16 +23,18 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
|
|||||||
return NextResponse.json({ playSession: updated });
|
return NextResponse.json({ playSession: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
export async function DELETE(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
|
const cascade = new URL(req.url).searchParams.get("cascade") === "true";
|
||||||
try {
|
try {
|
||||||
await deletePlaySession(Number(id));
|
await deletePlaySession(Number(id), { cascade });
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : String(err);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
if (message.includes("FOREIGN KEY") || message.includes("SQLITE_CONSTRAINT")) {
|
if (message.includes("FOREIGN KEY") || message.includes("SQLITE_CONSTRAINT")) {
|
||||||
|
const blockingRecordings = await getRecordingsForSession(Number(id));
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "cannot delete a session that a saved recording still references" },
|
{ error: "cannot delete a session that a saved recording still references", recordings: blockingRecordings },
|
||||||
{ status: 409 },
|
{ status: 409 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-2
@@ -176,6 +176,17 @@
|
|||||||
.bp-led[data-on="true"] {
|
.bp-led[data-on="true"] {
|
||||||
background: var(--primary);
|
background: var(--primary);
|
||||||
}
|
}
|
||||||
|
/* Header connection indicator: state-driven color, distinct from the
|
||||||
|
transmit-dot's boolean data-on above. */
|
||||||
|
.bp-led[data-state="scanning"] {
|
||||||
|
background: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
.bp-led[data-state="connected"] {
|
||||||
|
background: var(--primary);
|
||||||
|
}
|
||||||
|
.bp-led[data-state="recording"] {
|
||||||
|
background: var(--destructive);
|
||||||
|
}
|
||||||
|
|
||||||
/* Thin panel seam - a hardware "trim line," not a plain UI divider. */
|
/* Thin panel seam - a hardware "trim line," not a plain UI divider. */
|
||||||
.bp-hairline {
|
.bp-hairline {
|
||||||
@@ -193,15 +204,21 @@
|
|||||||
@keyframes bp-pulse-glow {
|
@keyframes bp-pulse-glow {
|
||||||
0%,
|
0%,
|
||||||
100% {
|
100% {
|
||||||
box-shadow: 0 0 0 0 color-mix(in srgb, var(--primary) 55%, transparent);
|
box-shadow: 0 0 0 0 color-mix(in srgb, var(--bp-pulse-color, var(--primary)) 55%, transparent);
|
||||||
}
|
}
|
||||||
50% {
|
50% {
|
||||||
box-shadow: 0 0 0 6px color-mix(in srgb, var(--primary) 0%, transparent);
|
box-shadow: 0 0 0 6px color-mix(in srgb, var(--bp-pulse-color, var(--primary)) 0%, transparent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.bp-pulse {
|
.bp-pulse {
|
||||||
animation: bp-pulse-glow 2s ease-in-out infinite;
|
animation: bp-pulse-glow 2s ease-in-out infinite;
|
||||||
}
|
}
|
||||||
|
.bp-led[data-state="scanning"] {
|
||||||
|
--bp-pulse-color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
.bp-led[data-state="recording"] {
|
||||||
|
--bp-pulse-color: var(--destructive);
|
||||||
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.bp-pulse {
|
.bp-pulse {
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ const spaceGrotesk = Space_Grotesk({ subsets: ["latin"], variable: "--font-displ
|
|||||||
const jetbrainsMono = JetBrains_Mono({ subsets: ["latin"], variable: "--font-mono" });
|
const jetbrainsMono = JetBrains_Mono({ subsets: ["latin"], variable: "--font-mono" });
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "SEXY",
|
title: { default: "Sexy", template: "%s · Sexy" },
|
||||||
description: "Bluetooth toy control console",
|
description: "Bluetooth toy control console",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -1,8 +1,11 @@
|
|||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
|
import type { Metadata } from "next";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { LoginForm } from "@/components/auth/LoginForm";
|
import { LoginForm } from "@/components/auth/LoginForm";
|
||||||
import { BrandMark } from "@/components/layout/BrandMark";
|
import { BrandMark } from "@/components/layout/BrandMark";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: "Log in" };
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-dvh items-center justify-center p-4">
|
<div className="flex min-h-dvh items-center justify-center p-4">
|
||||||
@@ -10,7 +13,7 @@ export default function LoginPage() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<BrandMark size={32} />
|
<BrandMark size={32} />
|
||||||
<CardTitle className="font-heading bp-gradient-text text-2xl">SEXY</CardTitle>
|
<CardTitle className="font-heading bp-gradient-text text-2xl">Sexy</CardTitle>
|
||||||
</div>
|
</div>
|
||||||
<CardDescription>Enter the shared access secret to continue.</CardDescription>
|
<CardDescription>Enter the shared access secret to continue.</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
|
export default function manifest(): MetadataRoute.Manifest {
|
||||||
|
return {
|
||||||
|
name: "Sexy",
|
||||||
|
short_name: "Sexy",
|
||||||
|
description: "Bluetooth toy control console",
|
||||||
|
start_url: "/",
|
||||||
|
display: "standalone",
|
||||||
|
background_color: "#15131f",
|
||||||
|
theme_color: "#15131f",
|
||||||
|
icons: [
|
||||||
|
{
|
||||||
|
src: "/icon.svg",
|
||||||
|
sizes: "any",
|
||||||
|
type: "image/svg+xml",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
disconnectAll,
|
disconnectAll,
|
||||||
|
getBatteryLevel,
|
||||||
getButtplugClientHandle,
|
getButtplugClientHandle,
|
||||||
getDevice,
|
getDevice,
|
||||||
isWebBluetoothSupported,
|
isWebBluetoothSupported,
|
||||||
@@ -42,6 +43,10 @@ export function ButtplugConsole() {
|
|||||||
const devices = useButtplugStore((s) => s.devices);
|
const devices = useButtplugStore((s) => s.devices);
|
||||||
const actuatorValues = useButtplugStore((s) => s.actuatorValues);
|
const actuatorValues = useButtplugStore((s) => s.actuatorValues);
|
||||||
const setActuatorValue = useButtplugStore((s) => s.setActuatorValue);
|
const setActuatorValue = useButtplugStore((s) => s.setActuatorValue);
|
||||||
|
const batteryLevels = useButtplugStore((s) => s.batteryLevels);
|
||||||
|
const setBatteryLevel = useButtplugStore((s) => s.setBatteryLevel);
|
||||||
|
const removeDevice = useButtplugStore((s) => s.removeDevice);
|
||||||
|
const setRecording = useButtplugStore((s) => s.setRecording);
|
||||||
const storeError = useButtplugStore((s) => s.error);
|
const storeError = useButtplugStore((s) => s.error);
|
||||||
|
|
||||||
const [activeSession, setActiveSession] = useState<ActivePlaySession | null>(null);
|
const [activeSession, setActiveSession] = useState<ActivePlaySession | null>(null);
|
||||||
@@ -64,6 +69,21 @@ export function ButtplugConsole() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const devicesWithBattery = Object.values(devices).filter((d) => d.hasBattery);
|
||||||
|
if (devicesWithBattery.length === 0) return;
|
||||||
|
|
||||||
|
function refresh() {
|
||||||
|
for (const device of devicesWithBattery) {
|
||||||
|
void getBatteryLevel(device.index).then((level) => setBatteryLevel(device.index, level));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
refresh();
|
||||||
|
const interval = setInterval(refresh, 60_000);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, [devices, setBatteryLevel]);
|
||||||
|
|
||||||
async function ensureRuntime(): Promise<ButtplugRuntime> {
|
async function ensureRuntime(): Promise<ButtplugRuntime> {
|
||||||
if (runtimeRef.current) return runtimeRef.current;
|
if (runtimeRef.current) return runtimeRef.current;
|
||||||
const { runtime } = await getButtplugClientHandle();
|
const { runtime } = await getButtplugClientHandle();
|
||||||
@@ -118,6 +138,7 @@ export function ButtplugConsole() {
|
|||||||
sessionDeviceIdByDeviceIndex,
|
sessionDeviceIdByDeviceIndex,
|
||||||
});
|
});
|
||||||
setElapsedMs(0);
|
setElapsedMs(0);
|
||||||
|
setRecording(true);
|
||||||
} catch {
|
} catch {
|
||||||
toast.error("Could not start session.");
|
toast.error("Could not start session.");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -129,6 +150,7 @@ export function ButtplugConsole() {
|
|||||||
if (!activeSession) return;
|
if (!activeSession) return;
|
||||||
setSessionBusy(true);
|
setSessionBusy(true);
|
||||||
eventBuffer.stop();
|
eventBuffer.stop();
|
||||||
|
setRecording(false);
|
||||||
await fetch(`/api/play-sessions/${activeSession.id}`, {
|
await fetch(`/api/play-sessions/${activeSession.id}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -153,11 +175,17 @@ export function ButtplugConsole() {
|
|||||||
const runtime = await ensureRuntime();
|
const runtime = await ensureRuntime();
|
||||||
const liveDevice = await getDevice(device.index);
|
const liveDevice = await getDevice(device.index);
|
||||||
const feature = liveDevice && findFeature(liveDevice, featureIndex);
|
const feature = liveDevice && findFeature(liveDevice, featureIndex);
|
||||||
if (!liveDevice || !feature) return;
|
if (!liveDevice || !feature) {
|
||||||
|
toast.error(`${device.name}: device not found - try reconnecting.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
setTransmittingKey(key);
|
setTransmittingKey(key);
|
||||||
const cmd = buildOutputCommand(runtime, actuator, v);
|
const cmd = buildOutputCommand(runtime, actuator, v);
|
||||||
await feature.runOutput(cmd);
|
await feature.runOutput(cmd);
|
||||||
eventBuffer.record({ deviceIndex: device.index, commandType: actuator.outputType, featureIndex, value: v });
|
eventBuffer.record({ deviceIndex: device.index, commandType: actuator.outputType, featureIndex, value: v });
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
toast.error(`${device.name}: command failed - ${message}`);
|
||||||
} finally {
|
} finally {
|
||||||
setTransmittingKey((k) => (k === key ? null : k));
|
setTransmittingKey((k) => (k === key ? null : k));
|
||||||
}
|
}
|
||||||
@@ -173,6 +201,17 @@ export function ButtplugConsole() {
|
|||||||
device.actuators.forEach((a) => setActuatorValue(device.index, a.featureIndex, 0));
|
device.actuators.forEach((a) => setActuatorValue(device.index, a.featureIndex, 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleDisconnectDevice(device: ConnectedDeviceInfo) {
|
||||||
|
// Buttplug's protocol has no per-device disconnect message - only a
|
||||||
|
// whole-client disconnect() and stop() (halts actuators). Stopping it and
|
||||||
|
// removing it from local state is the closest equivalent: the card
|
||||||
|
// disappears and it stops receiving commands, though the underlying BLE
|
||||||
|
// link may persist until the whole client disconnects.
|
||||||
|
const liveDevice = await getDevice(device.index);
|
||||||
|
await liveDevice?.stop().catch(() => {});
|
||||||
|
removeDevice(device.index);
|
||||||
|
}
|
||||||
|
|
||||||
if (!supported) {
|
if (!supported) {
|
||||||
return (
|
return (
|
||||||
<Card className="bp-glass">
|
<Card className="bp-glass">
|
||||||
@@ -214,6 +253,7 @@ export function ButtplugConsole() {
|
|||||||
<DeviceCard
|
<DeviceCard
|
||||||
key={device.index}
|
key={device.index}
|
||||||
device={device}
|
device={device}
|
||||||
|
batteryLevel={batteryLevels[device.index] ?? null}
|
||||||
actuatorValues={Object.fromEntries(
|
actuatorValues={Object.fromEntries(
|
||||||
device.actuators.map((a) => [a.featureIndex, actuatorValues[actuatorKey(device.index, a.featureIndex)] ?? 0]),
|
device.actuators.map((a) => [a.featureIndex, actuatorValues[actuatorKey(device.index, a.featureIndex)] ?? 0]),
|
||||||
)}
|
)}
|
||||||
@@ -224,6 +264,7 @@ export function ButtplugConsole() {
|
|||||||
}
|
}
|
||||||
onActuatorChange={(featureIndex, value) => void handleActuatorChange(device, featureIndex, value)}
|
onActuatorChange={(featureIndex, value) => void handleActuatorChange(device, featureIndex, value)}
|
||||||
onStop={() => void handleStopDevice(device)}
|
onStop={() => void handleStopDevice(device)}
|
||||||
|
onDisconnect={() => void handleDisconnectDevice(device)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,29 +4,55 @@ import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { ActuatorSlider } from "./ActuatorSlider";
|
import { ActuatorSlider } from "./ActuatorSlider";
|
||||||
import type { ConnectedDeviceInfo } from "@/lib/buttplug/types";
|
import type { ConnectedDeviceInfo } from "@/lib/buttplug/types";
|
||||||
|
import { Battery, BatteryFull, BatteryLow, BatteryMedium, BatteryWarning, Unlink } from "lucide-react";
|
||||||
|
|
||||||
interface DeviceCardProps {
|
interface DeviceCardProps {
|
||||||
device: ConnectedDeviceInfo;
|
device: ConnectedDeviceInfo;
|
||||||
|
batteryLevel: number | null;
|
||||||
actuatorValues: Record<number, number>;
|
actuatorValues: Record<number, number>;
|
||||||
transmittingFeatureIndex: number | null;
|
transmittingFeatureIndex: number | null;
|
||||||
onActuatorChange: (featureIndex: number, value: number) => void;
|
onActuatorChange: (featureIndex: number, value: number) => void;
|
||||||
onStop: () => void;
|
onStop: () => void;
|
||||||
|
onDisconnect: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function BatteryIndicator({ level }: { level: number }) {
|
||||||
|
const Icon = level < 0.15 ? BatteryWarning : level < 0.4 ? BatteryLow : level < 0.8 ? BatteryMedium : BatteryFull;
|
||||||
|
return (
|
||||||
|
<span className={`flex items-center gap-1 ${level < 0.15 ? "text-destructive" : "text-muted-foreground"}`}>
|
||||||
|
<Icon className="size-3.5" />
|
||||||
|
<span className="bp-readout text-xs">{Math.round(level * 100)}%</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DeviceCard({
|
export function DeviceCard({
|
||||||
device,
|
device,
|
||||||
|
batteryLevel,
|
||||||
actuatorValues,
|
actuatorValues,
|
||||||
transmittingFeatureIndex,
|
transmittingFeatureIndex,
|
||||||
onActuatorChange,
|
onActuatorChange,
|
||||||
onStop,
|
onStop,
|
||||||
|
onDisconnect,
|
||||||
}: DeviceCardProps) {
|
}: DeviceCardProps) {
|
||||||
return (
|
return (
|
||||||
<Card className="bp-glass">
|
<Card className="bp-glass">
|
||||||
<CardHeader className="flex flex-row items-center justify-between pb-3">
|
<CardHeader className="flex flex-row items-center justify-between pb-3">
|
||||||
<span className="text-sm font-medium text-foreground">{device.displayName ?? device.name}</span>
|
<span className="text-sm font-medium text-foreground">{device.displayName ?? device.name}</span>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{device.hasBattery &&
|
||||||
|
(batteryLevel !== null ? (
|
||||||
|
<BatteryIndicator level={batteryLevel} />
|
||||||
|
) : (
|
||||||
|
<Battery className="size-3.5 text-muted-foreground" aria-label="Reading battery level" />
|
||||||
|
))}
|
||||||
<Button variant="outline" size="sm" onClick={onStop}>
|
<Button variant="outline" size="sm" onClick={onStop}>
|
||||||
Stop
|
Stop
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon-sm" onClick={onDisconnect} aria-label="Disconnect device">
|
||||||
|
<Unlink className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<div className="bp-hairline mx-4" />
|
<div className="bp-hairline mx-4" />
|
||||||
<CardContent className="flex flex-col gap-3 pt-3">
|
<CardContent className="flex flex-col gap-3 pt-3">
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ function DeviceNameCell({ device }: { device: DeviceRow }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input value={value} onChange={(e) => setValue(e.target.value)} className="h-8 max-w-48" />
|
<Input value={value} onChange={(e) => setValue(e.target.value)} className="h-8 w-40 min-w-40" />
|
||||||
<Button size="sm" variant="outline" onClick={handleSave} disabled={saving}>
|
<Button size="sm" variant="outline" onClick={handleSave} disabled={saving} className="shrink-0">
|
||||||
Save
|
Save
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,18 +1,28 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useButtplugStore } from "@/lib/buttplug/store";
|
import { useButtplugStore } from "@/lib/buttplug/store";
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
type IndicatorState = "scanning" | "connected" | "recording";
|
||||||
|
|
||||||
export function ConnectionStatus() {
|
export function ConnectionStatus() {
|
||||||
const connected = useButtplugStore((s) => s.connected);
|
const scanning = useButtplugStore((s) => s.scanning);
|
||||||
|
const recording = useButtplugStore((s) => s.recording);
|
||||||
const deviceCount = useButtplugStore((s) => Object.keys(s.devices).length);
|
const deviceCount = useButtplugStore((s) => Object.keys(s.devices).length);
|
||||||
|
|
||||||
return (
|
// Priority: an active recording is the most important thing to surface,
|
||||||
<div className="flex items-center gap-2 rounded-md border border-border bg-card/60 px-3 py-1 text-xs">
|
// then whether toys are actually connected, then a bare scan-in-progress -
|
||||||
<span className={cn("bp-led", connected && "bp-pulse")} data-on={connected} aria-hidden />
|
// this is deliberately independent of the Buttplug client's own `connected`
|
||||||
<span className="bp-readout text-muted-foreground">
|
// flag, which goes true as soon as the embedded server initializes (i.e. as
|
||||||
{connected ? `${deviceCount} device${deviceCount === 1 ? "" : "s"} connected` : "not connected"}
|
// soon as scanning starts), not when a device is actually paired.
|
||||||
</span>
|
const state: IndicatorState | null = recording
|
||||||
</div>
|
? "recording"
|
||||||
);
|
: deviceCount > 0
|
||||||
|
? "connected"
|
||||||
|
: scanning
|
||||||
|
? "scanning"
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (!state) return null;
|
||||||
|
|
||||||
|
return <span className="bp-led bp-pulse" data-state={state} aria-hidden />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export function NavBar() {
|
|||||||
<div className="mx-auto flex h-14 max-w-6xl items-center gap-3 px-4">
|
<div className="mx-auto flex h-14 max-w-6xl items-center gap-3 px-4">
|
||||||
<Link href="/" className="mr-2 flex items-center gap-2">
|
<Link href="/" className="mr-2 flex items-center gap-2">
|
||||||
<BrandMark size={26} />
|
<BrandMark size={26} />
|
||||||
<span className="font-heading bp-gradient-text text-lg font-semibold">SEXY</span>
|
<span className="font-heading bp-gradient-text text-lg font-semibold">Sexy</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<nav className="hidden items-center gap-1 md:flex">
|
<nav className="hidden items-center gap-1 md:flex">
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Slider } from "@/components/ui/slider";
|
import { Slider } from "@/components/ui/slider";
|
||||||
import { DeviceScanPanel } from "@/components/control/DeviceScanPanel";
|
import { DeviceScanPanel } from "@/components/control/DeviceScanPanel";
|
||||||
import { DeviceRemapDialog } from "./DeviceRemapDialog";
|
import { DeviceRemapDialog } from "./DeviceRemapDialog";
|
||||||
import { getButtplugClientHandle, startScanning, stopScanning } from "@/lib/buttplug/client";
|
import { disconnectAll, getButtplugClientHandle, getDevice, startScanning, stopScanning } from "@/lib/buttplug/client";
|
||||||
import { eventBuffer } from "@/lib/buttplug/event-buffer";
|
import { eventBuffer } from "@/lib/buttplug/event-buffer";
|
||||||
import { RecordingPlayer, type RecordingEventRow } from "@/lib/buttplug/player";
|
import { RecordingPlayer, type RecordingEventRow } from "@/lib/buttplug/player";
|
||||||
import { useButtplugStore } from "@/lib/buttplug/store";
|
import { useButtplugStore } from "@/lib/buttplug/store";
|
||||||
@@ -35,13 +35,19 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const scanning = useButtplugStore((s) => s.scanning);
|
const scanning = useButtplugStore((s) => s.scanning);
|
||||||
const devices = useButtplugStore((s) => s.devices);
|
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 connectedDevices = useMemo(() => Object.values(devices), [devices]);
|
||||||
|
|
||||||
const [data, setData] = useState<RecordingResponse | null>(null);
|
const [data, setData] = useState<RecordingResponse | null>(null);
|
||||||
const [showRemap, setShowRemap] = useState(false);
|
const [showRemap, setShowRemap] = useState(false);
|
||||||
|
const [starting, setStarting] = useState(false);
|
||||||
const [player, setPlayer] = useState<RecordingPlayer | null>(null);
|
const [player, setPlayer] = useState<RecordingPlayer | null>(null);
|
||||||
const [playing, setPlaying] = useState(false);
|
const [playing, setPlaying] = useState(false);
|
||||||
const [elapsedMs, setElapsedMs] = useState(0);
|
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(() => {
|
useEffect(() => {
|
||||||
fetch(`/api/recordings/${recordingId}`)
|
fetch(`/api/recordings/${recordingId}`)
|
||||||
@@ -50,19 +56,39 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
|||||||
.catch(() => toast.error("Could not load recording"));
|
.catch(() => toast.error("Could not load recording"));
|
||||||
}, [recordingId]);
|
}, [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>) {
|
async function handleConfirmRemap(mapping: Map<number, number>) {
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
setShowRemap(false);
|
setShowRemap(false);
|
||||||
|
setStarting(true);
|
||||||
|
|
||||||
|
try {
|
||||||
const orderedSlots = data.recording.deviceSlots.filter((s) => mapping.has(s.sourceSessionDeviceId));
|
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 = {
|
const body = {
|
||||||
kind: "replay" as const,
|
kind: "replay" as const,
|
||||||
replayedRecordingId: data.recording.id,
|
replayedRecordingId: data.recording.id,
|
||||||
devices: orderedSlots.map((slot) => {
|
devices: orderedSlots.map((slot, i) => ({ slotLabel: slot.slotLabel, bleName: targets[i].deviceName })),
|
||||||
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", {
|
const res = await fetch("/api/play-sessions", {
|
||||||
@@ -92,13 +118,27 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
|||||||
connectedDevices.map((d) => [d.index, d.actuators]),
|
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 { runtime } = await getButtplugClientHandle();
|
||||||
const instance = new RecordingPlayer({
|
const instance = new RecordingPlayer({
|
||||||
events: data.events,
|
events: data.events,
|
||||||
|
durationMs: data.recording.durationMs,
|
||||||
sessionDeviceIdToDeviceIndex,
|
sessionDeviceIdToDeviceIndex,
|
||||||
actuatorsByDeviceIndex,
|
actuatorsByDeviceIndex,
|
||||||
runtime,
|
runtime,
|
||||||
onProgress: (elapsed) => setElapsedMs(elapsed),
|
onProgress: (elapsed) => setElapsedMs(elapsed),
|
||||||
|
onError: (message) => toast.error(`Replay command failed: ${message}`),
|
||||||
onComplete: async () => {
|
onComplete: async () => {
|
||||||
setPlaying(false);
|
setPlaying(false);
|
||||||
eventBuffer.stop();
|
eventBuffer.stop();
|
||||||
@@ -106,13 +146,21 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
|||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ status: "completed" }),
|
body: JSON.stringify({ status: "completed" }),
|
||||||
});
|
}).catch(() => {});
|
||||||
toast.success("Replay finished");
|
toast.success("Replay finished");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
setReplayTargets(targets);
|
||||||
|
setReplayDeviceIndexes([...deviceIndexes]);
|
||||||
|
setActiveSessionId(result.session.id);
|
||||||
setPlayer(instance);
|
setPlayer(instance);
|
||||||
instance.play();
|
instance.play();
|
||||||
setPlaying(true);
|
setPlaying(true);
|
||||||
|
} catch {
|
||||||
|
toast.error("Could not start replay");
|
||||||
|
} finally {
|
||||||
|
setStarting(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!data) {
|
if (!data) {
|
||||||
@@ -136,30 +184,47 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
|||||||
<DeviceScanPanel scanning={scanning} onScan={() => void startScanning()} onStopScan={() => void stopScanning()} />
|
<DeviceScanPanel scanning={scanning} onScan={() => void startScanning()} onStopScan={() => void stopScanning()} />
|
||||||
<Button
|
<Button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
|
try {
|
||||||
await getButtplugClientHandle();
|
await getButtplugClientHandle();
|
||||||
setShowRemap(true);
|
setShowRemap(true);
|
||||||
|
} catch {
|
||||||
|
toast.error("Could not connect to Buttplug client");
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
disabled={connectedDevices.length === 0}
|
disabled={connectedDevices.length === 0 || starting}
|
||||||
>
|
>
|
||||||
Match devices & replay
|
{starting ? "Starting..." : "Match devices & replay"}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-3">
|
<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
|
<Slider
|
||||||
value={[elapsedMs]}
|
value={[elapsedMs]}
|
||||||
max={data.recording.durationMs}
|
max={data.recording.durationMs}
|
||||||
onValueChange={([v]) => player.seek(v)}
|
onValueChange={([v]) => player.seek(v)}
|
||||||
/>
|
/>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="bp-readout text-xs text-muted-foreground">
|
||||||
{formatTime(elapsedMs)} / {formatTime(data.recording.durationMs)}
|
{formatTime(elapsedMs)} / {formatTime(data.recording.durationMs)}
|
||||||
</span>
|
</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<Button
|
<Button
|
||||||
size="icon"
|
size="icon"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => {
|
onClick={async () => {
|
||||||
if (playing) {
|
if (playing) {
|
||||||
player.pause();
|
player.pause();
|
||||||
setPlaying(false);
|
setPlaying(false);
|
||||||
@@ -167,10 +232,50 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
|||||||
player.play();
|
player.play();
|
||||||
setPlaying(true);
|
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" />}
|
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
|
||||||
</Button>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,13 +1,27 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
import { Trash2 } from "lucide-react";
|
import { Trash2 } from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
interface BlockingRecording {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SessionRow {
|
export interface SessionRow {
|
||||||
id: number;
|
id: number;
|
||||||
name: string | null;
|
name: string | null;
|
||||||
@@ -27,6 +41,8 @@ function formatDuration(ms: number | null): string {
|
|||||||
|
|
||||||
export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const [conflict, setConflict] = useState<{ id: number; recordings: BlockingRecording[] } | null>(null);
|
||||||
|
const [deleting, setDeleting] = useState(false);
|
||||||
|
|
||||||
async function handleDelete(id: number) {
|
async function handleDelete(id: number) {
|
||||||
const res = await fetch(`/api/play-sessions/${id}`, { method: "DELETE" });
|
const res = await fetch(`/api/play-sessions/${id}`, { method: "DELETE" });
|
||||||
@@ -34,7 +50,22 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
|||||||
toast.success("Session deleted");
|
toast.success("Session deleted");
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} else if (res.status === 409) {
|
} else if (res.status === 409) {
|
||||||
toast.error("A saved recording still references this session");
|
const body: { recordings?: BlockingRecording[] } = await res.json().catch(() => ({}));
|
||||||
|
setConflict({ id, recordings: body.recordings ?? [] });
|
||||||
|
} else {
|
||||||
|
toast.error("Could not delete session");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCascadeDelete() {
|
||||||
|
if (!conflict) return;
|
||||||
|
setDeleting(true);
|
||||||
|
const res = await fetch(`/api/play-sessions/${conflict.id}?cascade=true`, { method: "DELETE" });
|
||||||
|
setDeleting(false);
|
||||||
|
if (res.ok) {
|
||||||
|
toast.success("Session and recording deleted");
|
||||||
|
setConflict(null);
|
||||||
|
router.refresh();
|
||||||
} else {
|
} else {
|
||||||
toast.error("Could not delete session");
|
toast.error("Could not delete session");
|
||||||
}
|
}
|
||||||
@@ -45,6 +76,7 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
@@ -81,5 +113,29 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
|||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
|
|
||||||
|
<Dialog open={conflict !== null} onOpenChange={(open) => !open && setConflict(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Delete session and recording?</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
This session has a saved recording
|
||||||
|
{conflict && conflict.recordings.length > 0
|
||||||
|
? ` (${conflict.recordings.map((r) => r.name).join(", ")})`
|
||||||
|
: ""}{" "}
|
||||||
|
that still points to it. Deleting the session will also delete that recording.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="ghost" onClick={() => setConflict(null)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={() => void handleCascadeDelete()} disabled={deleting}>
|
||||||
|
{deleting ? "Deleting..." : "Delete both"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||||
|
|
||||||
|
interface PageNavProps {
|
||||||
|
basePath: string;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PageNav({ basePath, page, pageSize, total }: PageNavProps) {
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||||
|
if (totalPages <= 1) return null;
|
||||||
|
|
||||||
|
const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
|
||||||
|
const to = Math.min(page * pageSize, total);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between gap-4 pt-2">
|
||||||
|
<span className="bp-readout text-xs text-muted-foreground">
|
||||||
|
{from}-{to} of {total}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{page > 1 ? (
|
||||||
|
<Button asChild variant="outline" size="icon-sm">
|
||||||
|
<Link href={`${basePath}?page=${page - 1}`} aria-label="Previous page">
|
||||||
|
<ChevronLeft className="size-3.5" />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button variant="outline" size="icon-sm" disabled aria-label="Previous page">
|
||||||
|
<ChevronLeft className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<span className="bp-readout text-xs text-muted-foreground">
|
||||||
|
{page} / {totalPages}
|
||||||
|
</span>
|
||||||
|
{page < totalPages ? (
|
||||||
|
<Button asChild variant="outline" size="icon-sm">
|
||||||
|
<Link href={`${basePath}?page=${page + 1}`} aria-label="Next page">
|
||||||
|
<ChevronRight className="size-3.5" />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button variant="outline" size="icon-sm" disabled aria-label="Next page">
|
||||||
|
<ChevronRight className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+23
-2
@@ -1,4 +1,4 @@
|
|||||||
import type { ButtplugClient, ButtplugClientDevice } from "buttplug";
|
import type { ButtplugClient, ButtplugClientDevice, InputType } from "buttplug";
|
||||||
import { deriveActuators, type ButtplugRuntime } from "./commands";
|
import { deriveActuators, type ButtplugRuntime } from "./commands";
|
||||||
import { useButtplugStore } from "./store";
|
import { useButtplugStore } from "./store";
|
||||||
import type { ConnectedDeviceInfo } from "./types";
|
import type { ConnectedDeviceInfo } from "./types";
|
||||||
@@ -20,6 +20,9 @@ function toDeviceInfo(device: ButtplugClientDevice): ConnectedDeviceInfo {
|
|||||||
name: device.name,
|
name: device.name,
|
||||||
displayName: device.displayName,
|
displayName: device.displayName,
|
||||||
actuators: deriveActuators(device),
|
actuators: deriveActuators(device),
|
||||||
|
// "Battery" is a string enum value - passing the literal avoids needing
|
||||||
|
// InputType as a runtime import here (see commands.ts for the same trick).
|
||||||
|
hasBattery: device.hasInput("Battery" as InputType),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +48,14 @@ async function initClient(): Promise<ClientHandle> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const connector = new ButtplugWasmClientConnector();
|
const connector = new ButtplugWasmClientConnector();
|
||||||
await client.connect(connector);
|
// EXPERIMENTAL: buttplug-wasm@3.0.0's embedded server was built against
|
||||||
|
// buttplug@^4.0.2's wire format; buttplug@5's OutputCmd message shape
|
||||||
|
// changed (`Value` went from number[] to a bare number), which is a real
|
||||||
|
// protocol break, not just a type mismatch - the cast below silences that
|
||||||
|
// signal rather than fixing it. Scanning/pairing may still work since
|
||||||
|
// DeviceAdded's shape didn't change; device *commands* may be silently
|
||||||
|
// rejected or mis-parsed server-side. Revert to buttplug@^4.0.2 if so.
|
||||||
|
await client.connect(connector as unknown as Parameters<typeof client.connect>[0]);
|
||||||
|
|
||||||
useButtplugStore.getState().setConnected(true);
|
useButtplugStore.getState().setConnected(true);
|
||||||
for (const device of client.devices.values()) {
|
for (const device of client.devices.values()) {
|
||||||
@@ -94,3 +104,14 @@ export async function getDevice(deviceIndex: number): Promise<ButtplugClientDevi
|
|||||||
const { client } = await getButtplugClientHandle();
|
const { client } = await getButtplugClientHandle();
|
||||||
return client.devices.get(deviceIndex);
|
return client.devices.get(deviceIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Reads the current battery level (0-1), or null if unsupported/unreadable. */
|
||||||
|
export async function getBatteryLevel(deviceIndex: number): Promise<number | null> {
|
||||||
|
const device = await getDevice(deviceIndex);
|
||||||
|
if (!device || !device.hasInput("Battery" as InputType)) return null;
|
||||||
|
try {
|
||||||
|
return await device.battery();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import type { ButtplugClientDevice, DeviceOutputCommand, OutputType } from "butt
|
|||||||
import type { ActuatorInfo, NormalizedOutputType } from "./types";
|
import type { ActuatorInfo, NormalizedOutputType } from "./types";
|
||||||
|
|
||||||
// buttplug@4's barrel doesn't re-export `ButtplugClientDeviceFeature` itself,
|
// buttplug@4's barrel doesn't re-export `ButtplugClientDeviceFeature` itself,
|
||||||
// so its type is recovered from the `features` map it's stored in.
|
// so its type is recovered from the `features` map it's stored in. Matched
|
||||||
type DeviceFeature = ButtplugClientDevice["features"] extends Map<number, infer F> ? F : never;
|
// against ReadonlyMap (not Map) so this works whether `.features` returns a
|
||||||
|
// mutable Map (v4) or a ReadonlyMap (v5) - Map structurally extends ReadonlyMap.
|
||||||
|
type DeviceFeature = ButtplugClientDevice["features"] extends ReadonlyMap<number, infer F> ? F : never;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The pieces of the dynamically-imported `buttplug` module namespace this
|
* The pieces of the dynamically-imported `buttplug` module namespace this
|
||||||
|
|||||||
+21
-12
@@ -14,6 +14,11 @@ export interface RecordingEventRow {
|
|||||||
|
|
||||||
export interface PlayerOptions {
|
export interface PlayerOptions {
|
||||||
events: RecordingEventRow[];
|
events: RecordingEventRow[];
|
||||||
|
/** The recording's actual duration (recordings.durationMs from the DB) - this is the source
|
||||||
|
* of truth for playback length, NOT the last event's timestamp: a recording can run for a
|
||||||
|
* while after its last command (e.g. the user stopped the toy but let the session continue),
|
||||||
|
* so deriving duration from events would end playback early and misreport it as "finished". */
|
||||||
|
durationMs: number;
|
||||||
/** Recording's session_device_id -> currently-connected device index, from the remap step. */
|
/** Recording's session_device_id -> currently-connected device index, from the remap step. */
|
||||||
sessionDeviceIdToDeviceIndex: Map<number, number>;
|
sessionDeviceIdToDeviceIndex: Map<number, number>;
|
||||||
actuatorsByDeviceIndex: Map<number, ActuatorInfo[]>;
|
actuatorsByDeviceIndex: Map<number, ActuatorInfo[]>;
|
||||||
@@ -21,6 +26,7 @@ export interface PlayerOptions {
|
|||||||
speed?: number;
|
speed?: number;
|
||||||
onProgress?: (elapsedMs: number, durationMs: number) => void;
|
onProgress?: (elapsedMs: number, durationMs: number) => void;
|
||||||
onComplete?: () => void;
|
onComplete?: () => void;
|
||||||
|
onError?: (message: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,7 +43,7 @@ export class RecordingPlayer {
|
|||||||
private playing = false;
|
private playing = false;
|
||||||
|
|
||||||
constructor(private readonly options: PlayerOptions) {
|
constructor(private readonly options: PlayerOptions) {
|
||||||
this.durationMs = options.events.at(-1)?.tsMs ?? 0;
|
this.durationMs = options.durationMs;
|
||||||
}
|
}
|
||||||
|
|
||||||
get isPlaying(): boolean {
|
get isPlaying(): boolean {
|
||||||
@@ -108,22 +114,13 @@ export class RecordingPlayer {
|
|||||||
const deviceIndex = this.options.sessionDeviceIdToDeviceIndex.get(event.sessionDeviceId);
|
const deviceIndex = this.options.sessionDeviceIdToDeviceIndex.get(event.sessionDeviceId);
|
||||||
if (deviceIndex === undefined) return;
|
if (deviceIndex === undefined) return;
|
||||||
|
|
||||||
|
try {
|
||||||
const device = await getDevice(deviceIndex);
|
const device = await getDevice(deviceIndex);
|
||||||
if (!device) return;
|
if (!device) return;
|
||||||
|
|
||||||
eventBuffer.record({
|
|
||||||
deviceIndex,
|
|
||||||
commandType: event.commandType,
|
|
||||||
featureIndex: event.featureIndex,
|
|
||||||
value: event.value,
|
|
||||||
durationMs: event.durationMs ?? undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (event.commandType === "stop") {
|
if (event.commandType === "stop") {
|
||||||
await device.stop();
|
await device.stop();
|
||||||
return;
|
} else {
|
||||||
}
|
|
||||||
|
|
||||||
const actuator = this.options.actuatorsByDeviceIndex
|
const actuator = this.options.actuatorsByDeviceIndex
|
||||||
.get(deviceIndex)
|
.get(deviceIndex)
|
||||||
?.find((a) => a.featureIndex === event.featureIndex);
|
?.find((a) => a.featureIndex === event.featureIndex);
|
||||||
@@ -133,4 +130,16 @@ export class RecordingPlayer {
|
|||||||
const cmd = buildOutputCommand(this.options.runtime, actuator, event.value, event.durationMs ?? undefined);
|
const cmd = buildOutputCommand(this.options.runtime, actuator, event.value, event.durationMs ?? undefined);
|
||||||
await feature.runOutput(cmd);
|
await feature.runOutput(cmd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
eventBuffer.record({
|
||||||
|
deviceIndex,
|
||||||
|
commandType: event.commandType,
|
||||||
|
featureIndex: event.featureIndex,
|
||||||
|
value: event.value,
|
||||||
|
durationMs: event.durationMs ?? undefined,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
this.options.onError?.(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-2
@@ -7,15 +7,21 @@ export const actuatorKey = (deviceIndex: number, featureIndex: number): string =
|
|||||||
interface ButtplugStoreState {
|
interface ButtplugStoreState {
|
||||||
connected: boolean;
|
connected: boolean;
|
||||||
scanning: boolean;
|
scanning: boolean;
|
||||||
|
/** Whether a play session is actively being recorded (see ButtplugConsole's session lifecycle). */
|
||||||
|
recording: boolean;
|
||||||
devices: Record<number, ConnectedDeviceInfo>;
|
devices: Record<number, ConnectedDeviceInfo>;
|
||||||
/** Last-known slider value per `${deviceIndex}:${featureIndex}`, for UI display only. */
|
/** Last-known slider value per `${deviceIndex}:${featureIndex}`, for UI display only. */
|
||||||
actuatorValues: Record<string, number>;
|
actuatorValues: Record<string, number>;
|
||||||
|
/** Last-known battery reading (0-1) per device index; absent until first read completes. */
|
||||||
|
batteryLevels: Record<number, number | null>;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
setConnected: (connected: boolean) => void;
|
setConnected: (connected: boolean) => void;
|
||||||
setScanning: (scanning: boolean) => void;
|
setScanning: (scanning: boolean) => void;
|
||||||
|
setRecording: (recording: boolean) => void;
|
||||||
upsertDevice: (device: ConnectedDeviceInfo) => void;
|
upsertDevice: (device: ConnectedDeviceInfo) => void;
|
||||||
removeDevice: (index: number) => void;
|
removeDevice: (index: number) => void;
|
||||||
setActuatorValue: (deviceIndex: number, featureIndex: number, value: number) => void;
|
setActuatorValue: (deviceIndex: number, featureIndex: number, value: number) => void;
|
||||||
|
setBatteryLevel: (deviceIndex: number, level: number | null) => void;
|
||||||
setError: (message: string | null) => void;
|
setError: (message: string | null) => void;
|
||||||
reset: () => void;
|
reset: () => void;
|
||||||
}
|
}
|
||||||
@@ -23,22 +29,30 @@ interface ButtplugStoreState {
|
|||||||
export const useButtplugStore = create<ButtplugStoreState>((set) => ({
|
export const useButtplugStore = create<ButtplugStoreState>((set) => ({
|
||||||
connected: false,
|
connected: false,
|
||||||
scanning: false,
|
scanning: false,
|
||||||
|
recording: false,
|
||||||
devices: {},
|
devices: {},
|
||||||
actuatorValues: {},
|
actuatorValues: {},
|
||||||
|
batteryLevels: {},
|
||||||
error: null,
|
error: null,
|
||||||
setConnected: (connected) => set({ connected }),
|
setConnected: (connected) => set({ connected }),
|
||||||
setScanning: (scanning) => set({ scanning }),
|
setScanning: (scanning) => set({ scanning }),
|
||||||
|
setRecording: (recording) => set({ recording }),
|
||||||
upsertDevice: (device) => set((s) => ({ devices: { ...s.devices, [device.index]: device } })),
|
upsertDevice: (device) => set((s) => ({ devices: { ...s.devices, [device.index]: device } })),
|
||||||
removeDevice: (index) =>
|
removeDevice: (index) =>
|
||||||
set((s) => {
|
set((s) => {
|
||||||
const devices = { ...s.devices };
|
const devices = { ...s.devices };
|
||||||
delete devices[index];
|
delete devices[index];
|
||||||
return { devices };
|
const batteryLevels = { ...s.batteryLevels };
|
||||||
|
delete batteryLevels[index];
|
||||||
|
return { devices, batteryLevels };
|
||||||
}),
|
}),
|
||||||
setActuatorValue: (deviceIndex, featureIndex, value) =>
|
setActuatorValue: (deviceIndex, featureIndex, value) =>
|
||||||
set((s) => ({
|
set((s) => ({
|
||||||
actuatorValues: { ...s.actuatorValues, [actuatorKey(deviceIndex, featureIndex)]: value },
|
actuatorValues: { ...s.actuatorValues, [actuatorKey(deviceIndex, featureIndex)]: value },
|
||||||
})),
|
})),
|
||||||
|
setBatteryLevel: (deviceIndex, level) =>
|
||||||
|
set((s) => ({ batteryLevels: { ...s.batteryLevels, [deviceIndex]: level } })),
|
||||||
setError: (message) => set({ error: message }),
|
setError: (message) => set({ error: message }),
|
||||||
reset: () => set({ connected: false, scanning: false, devices: {}, actuatorValues: {} }),
|
reset: () =>
|
||||||
|
set({ connected: false, scanning: false, recording: false, devices: {}, actuatorValues: {}, batteryLevels: {} }),
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export interface ConnectedDeviceInfo {
|
|||||||
name: string;
|
name: string;
|
||||||
displayName?: string;
|
displayName?: string;
|
||||||
actuators: ActuatorInfo[];
|
actuators: ActuatorInfo[];
|
||||||
|
hasBattery: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A single dispatched command, timestamped relative to session start. */
|
/** A single dispatched command, timestamped relative to session start. */
|
||||||
|
|||||||
@@ -1,11 +1,23 @@
|
|||||||
import { eq } from "drizzle-orm";
|
import { desc, eq, sql } from "drizzle-orm";
|
||||||
import { db } from "@/lib/db/client";
|
import { db } from "@/lib/db/client";
|
||||||
import { devices, type DeviceCapabilities } from "@/lib/db/schema";
|
import { devices, type DeviceCapabilities } from "@/lib/db/schema";
|
||||||
|
import { PAGE_SIZE, type Page } from "@/lib/pagination";
|
||||||
|
|
||||||
export async function listDevices() {
|
export async function listDevices() {
|
||||||
return db.select().from(devices).orderBy(devices.lastConnectedAt);
|
return db.select().from(devices).orderBy(devices.lastConnectedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listDevicesPage(page: number, pageSize = PAGE_SIZE): Promise<Page<typeof devices.$inferSelect>> {
|
||||||
|
const [{ count }] = await db.select({ count: sql<number>`count(*)` }).from(devices);
|
||||||
|
const items = await db
|
||||||
|
.select()
|
||||||
|
.from(devices)
|
||||||
|
.orderBy(desc(devices.lastConnectedAt))
|
||||||
|
.limit(pageSize)
|
||||||
|
.offset((page - 1) * pageSize);
|
||||||
|
return { items, page, pageSize, total: count };
|
||||||
|
}
|
||||||
|
|
||||||
export async function getDevice(id: number) {
|
export async function getDevice(id: number) {
|
||||||
const [row] = await db.select().from(devices).where(eq(devices.id, id));
|
const [row] = await db.select().from(devices).where(eq(devices.id, id));
|
||||||
return row;
|
return row;
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { eq } from "drizzle-orm";
|
import { desc, eq, sql } from "drizzle-orm";
|
||||||
import { db } from "@/lib/db/client";
|
import { db } from "@/lib/db/client";
|
||||||
import { playSessions, sessionDevices, devices } from "@/lib/db/schema";
|
import { playSessions, sessionDevices, devices, recordings } from "@/lib/db/schema";
|
||||||
import { upsertDeviceByBleName } from "./devices";
|
import { upsertDeviceByBleName } from "./devices";
|
||||||
import { incrementPlayCount } from "./recordings";
|
import { incrementPlayCount } from "./recordings";
|
||||||
import type { DeviceCapabilities } from "@/lib/db/schema";
|
import type { DeviceCapabilities } from "@/lib/db/schema";
|
||||||
|
import { PAGE_SIZE, type Page } from "@/lib/pagination";
|
||||||
|
|
||||||
export interface StartSessionDeviceInput {
|
export interface StartSessionDeviceInput {
|
||||||
slotLabel: string;
|
slotLabel: string;
|
||||||
@@ -86,6 +87,23 @@ export async function listPlaySessions() {
|
|||||||
return db.select().from(playSessions).orderBy(playSessions.startedAt);
|
return db.select().from(playSessions).orderBy(playSessions.startedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listPlaySessionsPage(page: number, pageSize = PAGE_SIZE): Promise<Page<typeof playSessions.$inferSelect>> {
|
||||||
|
const [{ count }] = await db.select({ count: sql<number>`count(*)` }).from(playSessions);
|
||||||
|
const items = await db
|
||||||
|
.select()
|
||||||
|
.from(playSessions)
|
||||||
|
.orderBy(desc(playSessions.startedAt))
|
||||||
|
.limit(pageSize)
|
||||||
|
.offset((page - 1) * pageSize);
|
||||||
|
return { items, page, pageSize, total: count };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lightweight name-only lookup for page titles - avoids getPlaySessionDetail's device join. */
|
||||||
|
export async function getPlaySessionName(id: number): Promise<string | null | undefined> {
|
||||||
|
const [row] = await db.select({ name: playSessions.name }).from(playSessions).where(eq(playSessions.id, id));
|
||||||
|
return row?.name;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getPlaySessionDetail(id: number) {
|
export async function getPlaySessionDetail(id: number) {
|
||||||
const [session] = await db.select().from(playSessions).where(eq(playSessions.id, id));
|
const [session] = await db.select().from(playSessions).where(eq(playSessions.id, id));
|
||||||
if (!session) return undefined;
|
if (!session) return undefined;
|
||||||
@@ -107,6 +125,9 @@ export async function getPlaySessionDetail(id: number) {
|
|||||||
return { session, devices: sessionDeviceRows };
|
return { session, devices: sessionDeviceRows };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deletePlaySession(id: number) {
|
export async function deletePlaySession(id: number, options?: { cascade?: boolean }) {
|
||||||
|
if (options?.cascade) {
|
||||||
|
await db.delete(recordings).where(eq(recordings.sourcePlaySessionId, id));
|
||||||
|
}
|
||||||
await db.delete(playSessions).where(eq(playSessions.id, id));
|
await db.delete(playSessions).where(eq(playSessions.id, id));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { desc, eq } from "drizzle-orm";
|
import { desc, eq, sql } from "drizzle-orm";
|
||||||
import { db } from "@/lib/db/client";
|
import { db } from "@/lib/db/client";
|
||||||
import { recordings, sessionDevices, devices, playSessions, type RecordingDeviceSlot } from "@/lib/db/schema";
|
import { recordings, sessionDevices, devices, playSessions, type RecordingDeviceSlot } from "@/lib/db/schema";
|
||||||
import { getEventsForSession } from "./session-events";
|
import { getEventsForSession } from "./session-events";
|
||||||
|
import { PAGE_SIZE, type Page } from "@/lib/pagination";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A recording is a thin pointer over an already-captured play_session, not a
|
* A recording is a thin pointer over an already-captured play_session, not a
|
||||||
@@ -60,6 +61,30 @@ export async function listRecordings() {
|
|||||||
return db.select().from(recordings).orderBy(desc(recordings.createdAt));
|
return db.select().from(recordings).orderBy(desc(recordings.createdAt));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listRecordingsPage(page: number, pageSize = PAGE_SIZE): Promise<Page<typeof recordings.$inferSelect>> {
|
||||||
|
const [{ count }] = await db.select({ count: sql<number>`count(*)` }).from(recordings);
|
||||||
|
const items = await db
|
||||||
|
.select()
|
||||||
|
.from(recordings)
|
||||||
|
.orderBy(desc(recordings.createdAt))
|
||||||
|
.limit(pageSize)
|
||||||
|
.offset((page - 1) * pageSize);
|
||||||
|
return { items, page, pageSize, total: count };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRecordingsForSession(playSessionId: number) {
|
||||||
|
return db
|
||||||
|
.select({ id: recordings.id, name: recordings.name })
|
||||||
|
.from(recordings)
|
||||||
|
.where(eq(recordings.sourcePlaySessionId, playSessionId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lightweight name-only lookup for page titles - avoids getRecording's event-table join. */
|
||||||
|
export async function getRecordingName(id: number): Promise<string | undefined> {
|
||||||
|
const [row] = await db.select({ name: recordings.name }).from(recordings).where(eq(recordings.id, id));
|
||||||
|
return row?.name;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getRecording(id: number) {
|
export async function getRecording(id: number) {
|
||||||
const [recording] = await db.select().from(recordings).where(eq(recordings.id, id));
|
const [recording] = await db.select().from(recordings).where(eq(recordings.id, id));
|
||||||
if (!recording) return undefined;
|
if (!recording) return undefined;
|
||||||
|
|||||||
@@ -37,9 +37,15 @@ export async function getSessionsSummary() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getSessionTimeline(playSessionId: number, bucketMs = 1000) {
|
export async function getSessionTimeline(playSessionId: number, bucketMs = 1000) {
|
||||||
|
// Reuse the same expression object (not a `sql`bucket`` alias reference)
|
||||||
|
// in groupBy/orderBy - drizzle doesn't emit a literal `AS bucket` that
|
||||||
|
// SQLite's GROUP BY/ORDER BY could resolve a bare "bucket" identifier
|
||||||
|
// against, so referencing it by name causes "no such column: bucket".
|
||||||
|
const bucket = sql<number>`(${sessionEvents.tsMs} / ${bucketMs}) * ${bucketMs}`;
|
||||||
|
|
||||||
return db
|
return db
|
||||||
.select({
|
.select({
|
||||||
bucket: sql<number>`(${sessionEvents.tsMs} / ${bucketMs}) * ${bucketMs}`,
|
bucket,
|
||||||
sessionDeviceId: sessionEvents.sessionDeviceId,
|
sessionDeviceId: sessionEvents.sessionDeviceId,
|
||||||
slotLabel: sessionDevices.slotLabel,
|
slotLabel: sessionDevices.slotLabel,
|
||||||
avgValue: sql<number>`avg(${sessionEvents.value})`,
|
avgValue: sql<number>`avg(${sessionEvents.value})`,
|
||||||
@@ -48,8 +54,8 @@ export async function getSessionTimeline(playSessionId: number, bucketMs = 1000)
|
|||||||
.from(sessionEvents)
|
.from(sessionEvents)
|
||||||
.innerJoin(sessionDevices, eq(sessionEvents.sessionDeviceId, sessionDevices.id))
|
.innerJoin(sessionDevices, eq(sessionEvents.sessionDeviceId, sessionDevices.id))
|
||||||
.where(and(eq(sessionEvents.playSessionId, playSessionId), ne(sessionEvents.commandType, "stop")))
|
.where(and(eq(sessionEvents.playSessionId, playSessionId), ne(sessionEvents.commandType, "stop")))
|
||||||
.groupBy(sql`bucket`, sessionEvents.sessionDeviceId)
|
.groupBy(bucket, sessionEvents.sessionDeviceId)
|
||||||
.orderBy(sql`bucket`);
|
.orderBy(bucket);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getDeviceUsageStats() {
|
export async function getDeviceUsageStats() {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export const PAGE_SIZE = 20;
|
||||||
|
|
||||||
|
export function parsePage(value: string | string[] | undefined): number {
|
||||||
|
const n = Number(Array.isArray(value) ? value[0] : value);
|
||||||
|
return Number.isInteger(n) && n > 0 ? n : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Page<T> {
|
||||||
|
items: T[];
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sexy",
|
"name": "sexy",
|
||||||
"version": "0.1.0",
|
"version": "0.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"better-sqlite3": "^13.0.3",
|
"better-sqlite3": "^13.0.3",
|
||||||
"buttplug": "^4.0.2",
|
"buttplug": "^5.0.1",
|
||||||
"buttplug-wasm": "^3.0.0",
|
"buttplug-wasm": "^3.0.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
|||||||
Generated
+13
-2
@@ -12,8 +12,8 @@ importers:
|
|||||||
specifier: ^13.0.3
|
specifier: ^13.0.3
|
||||||
version: 13.0.3
|
version: 13.0.3
|
||||||
buttplug:
|
buttplug:
|
||||||
specifier: ^4.0.2
|
specifier: ^5.0.1
|
||||||
version: 4.0.2
|
version: 5.0.1
|
||||||
buttplug-wasm:
|
buttplug-wasm:
|
||||||
specifier: ^3.0.0
|
specifier: ^3.0.0
|
||||||
version: 3.0.0
|
version: 3.0.0
|
||||||
@@ -2292,6 +2292,9 @@ packages:
|
|||||||
buttplug@4.0.2:
|
buttplug@4.0.2:
|
||||||
resolution: {integrity: sha512-PciEJEoBkHjeA0UFfdymr5+jHXukzF0T8Pg7TaAxxWFb/0Ynfy1dWaGt1c7O5E1sfJSVyWxrvBQQCSeNWzprbg==}
|
resolution: {integrity: sha512-PciEJEoBkHjeA0UFfdymr5+jHXukzF0T8Pg7TaAxxWFb/0Ynfy1dWaGt1c7O5E1sfJSVyWxrvBQQCSeNWzprbg==}
|
||||||
|
|
||||||
|
buttplug@5.0.1:
|
||||||
|
resolution: {integrity: sha512-m7Qzoi6TEsr0DkqqXc3Gun/wikWiHziQeXu73Oxzd1ETqj2y1P0VdJ9QxAT811bLcTIYvyf0VkuHlXbEGcEXCw==}
|
||||||
|
|
||||||
bytes@3.1.2:
|
bytes@3.1.2:
|
||||||
resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}
|
resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
@@ -6531,6 +6534,14 @@ snapshots:
|
|||||||
- bufferutil
|
- bufferutil
|
||||||
- utf-8-validate
|
- utf-8-validate
|
||||||
|
|
||||||
|
buttplug@5.0.1:
|
||||||
|
dependencies:
|
||||||
|
eventemitter3: 5.0.4
|
||||||
|
ws: 8.21.3
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- bufferutil
|
||||||
|
- utf-8-validate
|
||||||
|
|
||||||
bytes@3.1.2: {}
|
bytes@3.1.2: {}
|
||||||
|
|
||||||
call-bind-apply-helpers@1.0.2:
|
call-bind-apply-helpers@1.0.2:
|
||||||
|
|||||||
@@ -22,5 +22,7 @@ export default async function proxy(req: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ["/((?!_next/static|_next/image|favicon.ico|icon.svg|login|api/auth/login|api/health).*)"],
|
matcher: [
|
||||||
|
"/((?!_next/static|_next/image|favicon.ico|icon.svg|manifest.webmanifest|login|api/auth/login|api/health).*)",
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user