Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a3c4ff1f2 | ||
|
|
c46adf788f | ||
|
|
9e0380ec75 | ||
|
|
5484d3cefe |
@@ -1,5 +1,8 @@
|
||||
import type { Metadata } from "next";
|
||||
import { ButtplugConsoleLoader as ButtplugConsole } from "@/components/control/ButtplugConsoleLoader";
|
||||
|
||||
export const metadata: Metadata = { title: "Control" };
|
||||
|
||||
export default function ControlPage() {
|
||||
return (
|
||||
<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 { 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 metadata: Metadata = { title: "Devices" };
|
||||
|
||||
export default async function DevicesPage() {
|
||||
const devices = await listDevices();
|
||||
export default async function DevicesPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}) {
|
||||
const page = parsePage((await searchParams).page);
|
||||
const { items: devices, pageSize, total } = await listDevicesPage(page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
@@ -17,8 +26,9 @@ export default async function DevicesPage() {
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Known devices</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<DevicesTable devices={devices} />
|
||||
<PageNav basePath="/devices" page={page} pageSize={pageSize} total={total} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { NavBar } from "@/components/layout/NavBar";
|
||||
import { Breadcrumbs } from "@/components/layout/Breadcrumbs";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
|
||||
export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="min-h-dvh">
|
||||
<div className="flex min-h-dvh flex-col">
|
||||
<NavBar />
|
||||
<main className="mx-auto max-w-6xl px-4 py-8">{children}</main>
|
||||
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-8">
|
||||
<Breadcrumbs />
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@ export default async function DashboardPage() {
|
||||
<div className="flex flex-col gap-8">
|
||||
<Card className="bp-glass overflow-hidden">
|
||||
<CardContent className="flex flex-col items-start gap-4 py-8">
|
||||
<BrandMark size={40} className="bp-pulse rounded-[9px]" />
|
||||
<h1 className="font-heading bp-gradient-text text-3xl font-semibold">Welcome back</h1>
|
||||
<BrandMark size={48} animated className="rounded-[9px]" />
|
||||
<h1 className="font-heading text-3xl font-semibold">Welcome back</h1>
|
||||
<p className="max-w-xl text-sm text-muted-foreground">
|
||||
Scan for nearby devices, take control, and record sessions to replay later - all running
|
||||
directly from your browser over Web Bluetooth.
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import type { Metadata } from "next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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";
|
||||
|
||||
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 {
|
||||
const totalSeconds = Math.round(ms / 1000);
|
||||
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 { 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 }> }) {
|
||||
const { id } = await params;
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
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 metadata: Metadata = { title: "Recordings" };
|
||||
|
||||
export default async function RecordingsPage() {
|
||||
const recordings = await listRecordings();
|
||||
export default async function RecordingsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}) {
|
||||
const page = parsePage((await searchParams).page);
|
||||
const { items: recordings, pageSize, total } = await listRecordingsPage(page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
@@ -17,8 +26,9 @@ export default async function RecordingsPage() {
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Library</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<RecordingsTable recordings={recordings} />
|
||||
<PageNav basePath="/recordings" page={page} pageSize={pageSize} total={total} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import type { Metadata } from "next";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
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";
|
||||
|
||||
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 {
|
||||
if (ms === null) return "-";
|
||||
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 { 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 metadata: Metadata = { title: "Sessions" };
|
||||
|
||||
export default async function SessionsPage() {
|
||||
const sessions = [...(await listPlaySessions())].reverse();
|
||||
export default async function SessionsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}) {
|
||||
const page = parsePage((await searchParams).page);
|
||||
const { items: sessions, pageSize, total } = await listPlaySessionsPage(page);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
@@ -17,8 +26,9 @@ export default async function SessionsPage() {
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">History</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<SessionsTable sessions={sessions} />
|
||||
<PageNav basePath="/sessions" page={page} pageSize={pageSize} total={total} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { SessionsSummaryCards } from "@/components/stats/SessionsSummaryCards";
|
||||
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";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Stats" };
|
||||
|
||||
export default async function StatsPage() {
|
||||
const [sessionsSummary, deviceUsage, commandCounts, recordingStats] = await Promise.all([
|
||||
@@ -25,7 +27,7 @@ export default async function StatsPage() {
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="sessions">
|
||||
<TabsList>
|
||||
<TabsList className="bp-glass">
|
||||
<TabsTrigger value="sessions">Sessions</TabsTrigger>
|
||||
<TabsTrigger value="devices">Devices</TabsTrigger>
|
||||
<TabsTrigger value="recordings">Recordings</TabsTrigger>
|
||||
|
||||
@@ -3,21 +3,26 @@ import { z } from "zod";
|
||||
import { getEnv } from "@/lib/env";
|
||||
import { timingSafeStringEqual } from "@/lib/auth/timing-safe-compare";
|
||||
import { createSessionToken, sessionCookieOptions } from "@/lib/auth/session";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const log = createLogger("auth");
|
||||
const bodySchema = z.object({ secret: z.string().min(1) });
|
||||
|
||||
export async function POST(req: Request) {
|
||||
export const POST = withRouteLogging("auth.login", async (req: Request) => {
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "secret is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!timingSafeStringEqual(parsed.data.secret, getEnv().ACCESS_PASSWORD)) {
|
||||
log.warn("login attempt with invalid secret");
|
||||
return NextResponse.json({ error: "invalid secret" }, { status: 401 });
|
||||
}
|
||||
|
||||
log.info("login succeeded");
|
||||
const token = await createSessionToken();
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set({ ...sessionCookieOptions, value: token });
|
||||
return res;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { SESSION_COOKIE_NAME } from "@/lib/auth/session";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
export async function POST() {
|
||||
export const POST = withRouteLogging("auth.logout", async () => {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.delete(SESSION_COOKIE_NAME);
|
||||
return res;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { renameDevice } from "@/lib/db/queries/devices";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
const bodySchema = z.object({ displayName: z.string().min(1).max(120) });
|
||||
|
||||
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const PATCH = withRouteLogging(
|
||||
"devices.rename",
|
||||
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
@@ -13,4 +16,5 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
|
||||
const updated = await renameDevice(Number(id), parsed.data.displayName);
|
||||
if (!updated) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
return NextResponse.json({ device: updated });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { listDevices } from "@/lib/db/queries/devices";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
export async function GET() {
|
||||
export const GET = withRouteLogging("devices.list", async () => {
|
||||
const rows = await listDevices();
|
||||
return NextResponse.json({ devices: rows });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { sqlite } from "@/lib/db/client";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
export async function GET() {
|
||||
const log = createLogger("health");
|
||||
|
||||
export const GET = withRouteLogging("health.check", async () => {
|
||||
try {
|
||||
sqlite.prepare("select 1").get();
|
||||
return NextResponse.json({ status: "ok" });
|
||||
} catch {
|
||||
} catch (err) {
|
||||
log.error("health check failed", { error: err instanceof Error ? err.message : String(err) });
|
||||
return NextResponse.json({ status: "error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { insertEvents } from "@/lib/db/queries/session-events";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
const eventSchema = z.object({
|
||||
sessionDeviceId: z.number().int().positive(),
|
||||
@@ -13,7 +14,9 @@ const eventSchema = z.object({
|
||||
|
||||
const bodySchema = z.object({ events: z.array(eventSchema).max(2000) });
|
||||
|
||||
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const POST = withRouteLogging(
|
||||
"play-sessions.events.append",
|
||||
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
@@ -21,4 +24,5 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
|
||||
}
|
||||
await insertEvents(Number(id), parsed.data.events);
|
||||
return NextResponse.json({ inserted: parsed.data.events.length });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { deletePlaySession, endPlaySession, getPlaySessionDetail } from "@/lib/db/queries/play-sessions";
|
||||
import { getRecordingsForSession } from "@/lib/db/queries/recordings";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const log = createLogger("play-sessions");
|
||||
const patchSchema = z.object({ status: z.enum(["completed", "aborted"]) });
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const GET = withRouteLogging(
|
||||
"play-sessions.get",
|
||||
async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const detail = await getPlaySessionDetail(Number(id));
|
||||
if (!detail) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
return NextResponse.json(detail);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const PATCH = withRouteLogging(
|
||||
"play-sessions.end",
|
||||
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const parsed = patchSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
@@ -20,21 +29,28 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
|
||||
const updated = await endPlaySession(Number(id), parsed.data);
|
||||
if (!updated) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
return NextResponse.json({ playSession: updated });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const DELETE = withRouteLogging(
|
||||
"play-sessions.delete",
|
||||
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const cascade = new URL(req.url).searchParams.get("cascade") === "true";
|
||||
try {
|
||||
await deletePlaySession(Number(id));
|
||||
await deletePlaySession(Number(id), { cascade });
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (message.includes("FOREIGN KEY") || message.includes("SQLITE_CONSTRAINT")) {
|
||||
log.warn("blocked session delete due to referencing recording", { sessionId: id, cascade });
|
||||
const blockingRecordings = await getRecordingsForSession(Number(id));
|
||||
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 },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { listPlaySessions, startPlaySession } from "@/lib/db/queries/play-sessions";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
const deviceInputSchema = z.object({
|
||||
slotLabel: z.string().min(1),
|
||||
@@ -16,16 +17,16 @@ const bodySchema = z.object({
|
||||
devices: z.array(deviceInputSchema).min(1),
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
export const GET = withRouteLogging("play-sessions.list", async () => {
|
||||
const rows = await listPlaySessions();
|
||||
return NextResponse.json({ playSessions: rows });
|
||||
}
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
export const POST = withRouteLogging("play-sessions.start", async (req: Request) => {
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.message }, { status: 400 });
|
||||
}
|
||||
const result = await startPlaySession(parsed.data);
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { deleteRecording, getRecording, renameRecording } from "@/lib/db/queries/recordings";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
const patchSchema = z.object({
|
||||
name: z.string().min(1).max(160).optional(),
|
||||
description: z.string().max(2000).optional(),
|
||||
});
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const GET = withRouteLogging(
|
||||
"recordings.get",
|
||||
async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const result = await getRecording(Number(id));
|
||||
if (!result) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const PATCH = withRouteLogging(
|
||||
"recordings.update",
|
||||
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const parsed = patchSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
@@ -23,10 +29,14 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
|
||||
const updated = await renameRecording(Number(id), parsed.data);
|
||||
if (!updated) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
return NextResponse.json({ recording: updated });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const DELETE = withRouteLogging(
|
||||
"recordings.delete",
|
||||
async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
await deleteRecording(Number(id));
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { createRecording, listRecordings } from "@/lib/db/queries/recordings";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
const bodySchema = z.object({
|
||||
sourcePlaySessionId: z.number().int().positive(),
|
||||
@@ -8,16 +9,16 @@ const bodySchema = z.object({
|
||||
description: z.string().max(2000).optional(),
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
export const GET = withRouteLogging("recordings.list", async () => {
|
||||
const rows = await listRecordings();
|
||||
return NextResponse.json({ recordings: rows });
|
||||
}
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
export const POST = withRouteLogging("recordings.create", async (req: Request) => {
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.message }, { status: 400 });
|
||||
}
|
||||
const recording = await createRecording(parsed.data);
|
||||
return NextResponse.json({ recording }, { status: 201 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getDeviceCommandCounts, getDeviceUsageStats } from "@/lib/db/queries/stats";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
export async function GET() {
|
||||
export const GET = withRouteLogging("stats.devices", async () => {
|
||||
const [usage, commandCounts] = await Promise.all([getDeviceUsageStats(), getDeviceCommandCounts()]);
|
||||
const commandCountByDevice = new Map(commandCounts.map((c) => [c.deviceId, c.commandCount]));
|
||||
const devices = usage.map((d) => ({ ...d, commandCount: commandCountByDevice.get(d.deviceId) ?? 0 }));
|
||||
return NextResponse.json({ devices });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getRecordingLibraryStats } from "@/lib/db/queries/stats";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
export async function GET() {
|
||||
export const GET = withRouteLogging("stats.recordings", async () => {
|
||||
const stats = await getRecordingLibraryStats();
|
||||
return NextResponse.json(stats);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getSessionTimeline } from "@/lib/db/queries/stats";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
export const GET = withRouteLogging(
|
||||
"stats.session-timeline",
|
||||
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const bucketMs = Number(new URL(req.url).searchParams.get("bucketMs") ?? 1000);
|
||||
const timeline = await getSessionTimeline(Number(id), bucketMs);
|
||||
return NextResponse.json({ timeline });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getSessionsSummary } from "@/lib/db/queries/stats";
|
||||
import { withRouteLogging } from "@/lib/api/with-route-logging";
|
||||
|
||||
export async function GET() {
|
||||
export const GET = withRouteLogging("stats.sessions", async () => {
|
||||
const summary = await getSessionsSummary();
|
||||
return NextResponse.json(summary);
|
||||
}
|
||||
});
|
||||
|
||||
+101
-7
@@ -127,13 +127,46 @@
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
@apply text-foreground;
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
}
|
||||
|
||||
/* Animated signature-sweep background - sits behind everything; cards use
|
||||
.bp-glass (translucent + blurred) so it shines through instead of being
|
||||
fully hidden behind an opaque card surface. */
|
||||
body {
|
||||
background-color: var(--background);
|
||||
background-image:
|
||||
radial-gradient(ellipse 80% 60% at 15% 10%, color-mix(in srgb, #ff6fb0 32%, transparent), transparent 60%),
|
||||
radial-gradient(ellipse 70% 60% at 85% 25%, color-mix(in srgb, #4f7fe0 28%, transparent), transparent 60%),
|
||||
radial-gradient(ellipse 75% 65% at 50% 100%, color-mix(in srgb, #b34bde 30%, transparent), transparent 60%);
|
||||
background-repeat: no-repeat;
|
||||
background-size: 140% 140%;
|
||||
background-attachment: fixed;
|
||||
animation: bp-bg-drift 24s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes bp-bg-drift {
|
||||
0% {
|
||||
background-position: 0% 0%, 100% 0%, 50% 100%;
|
||||
}
|
||||
50% {
|
||||
background-position: 20% 20%, 80% 30%, 60% 80%;
|
||||
}
|
||||
100% {
|
||||
background-position: 0% 0%, 100% 0%, 50% 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
body {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Signature pink -> purple -> blue sweep (matches app/icon.svg), used for
|
||||
the wordmark and one hero moment - not smeared across every surface. */
|
||||
.bp-gradient-text {
|
||||
@@ -147,17 +180,20 @@
|
||||
background: linear-gradient(135deg, #ff6fb0, #b34bde 50%, #4f7fe0);
|
||||
}
|
||||
|
||||
/* Console-module surface: hairline border + a soft inset top highlight,
|
||||
standing in for backdrop-blur glassmorphism. */
|
||||
/* Console-module surface: translucent + blurred so the animated background
|
||||
sweep shines through, with a hairline border and soft inset top highlight. */
|
||||
.bp-glass {
|
||||
background: var(--card);
|
||||
background: color-mix(in srgb, var(--card) 55%, transparent);
|
||||
backdrop-filter: blur(20px) saturate(150%);
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, var(--foreground) 8%, transparent);
|
||||
transition:
|
||||
border-color 0.2s ease,
|
||||
box-shadow 0.2s ease;
|
||||
box-shadow 0.2s ease,
|
||||
background-color 0.2s ease;
|
||||
}
|
||||
.bp-glass:hover {
|
||||
background: color-mix(in srgb, var(--card) 62%, transparent);
|
||||
border-color: color-mix(in srgb, var(--primary) 45%, var(--border));
|
||||
box-shadow:
|
||||
inset 0 1px 0 color-mix(in srgb, var(--foreground) 10%, transparent),
|
||||
@@ -176,6 +212,17 @@
|
||||
.bp-led[data-on="true"] {
|
||||
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. */
|
||||
.bp-hairline {
|
||||
@@ -190,18 +237,65 @@
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
/* BrandMark's animated variant (dashboard hero): the heart glyph beats, the
|
||||
EKG-style curve glows in the primary accent instead of plain white. */
|
||||
@keyframes bp-mark-heartbeat {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.22;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.75;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
.bp-mark-heart {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
animation: bp-mark-heartbeat 1.8s ease-in-out infinite;
|
||||
}
|
||||
@keyframes bp-mark-curve-glow {
|
||||
0%,
|
||||
100% {
|
||||
filter: drop-shadow(0 0 1px color-mix(in srgb, var(--primary) 50%, transparent));
|
||||
}
|
||||
50% {
|
||||
filter:
|
||||
drop-shadow(0 0 5px color-mix(in srgb, var(--primary) 100%, transparent))
|
||||
drop-shadow(0 0 10px color-mix(in srgb, var(--primary) 70%, transparent));
|
||||
}
|
||||
}
|
||||
.bp-mark-curve {
|
||||
stroke: #fff;
|
||||
animation: bp-mark-curve-glow 1.8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bp-mark-heart,
|
||||
.bp-mark-curve {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes bp-pulse-glow {
|
||||
0%,
|
||||
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% {
|
||||
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 {
|
||||
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) {
|
||||
.bp-pulse {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="30" height="30" rx="9" fill="url(#bpGrad)" />
|
||||
<g transform="translate(0 0.7)">
|
||||
<path
|
||||
d="M16 22.6c-.3 0-.5-.1-.7-.3C11.7 19 8 15.6 8 12.3 8 9.9 9.9 8 12.3 8c1.3 0 2.6.6 3.4 1.7.1.1.2.1.3 0 .8-1.1 2.1-1.7 3.4-1.7C21.8 8 23.7 9.9 23.7 12.3c0 3.3-3.7 6.7-7.3 10-.2.2-.4.3-.7.3z"
|
||||
fill="rgba(255,255,255,0.22)"
|
||||
@@ -19,4 +20,5 @@
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 884 B After Width: | Height: | Size: 950 B |
+4
-4
@@ -1,16 +1,16 @@
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
import { Inter, Space_Grotesk, JetBrains_Mono } from "next/font/google";
|
||||
import { Inter, Sora, JetBrains_Mono } from "next/font/google";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ThemeProvider } from "@/components/layout/ThemeProvider";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" });
|
||||
const spaceGrotesk = Space_Grotesk({ subsets: ["latin"], variable: "--font-display" });
|
||||
const sora = Sora({ subsets: ["latin"], variable: "--font-display" });
|
||||
const jetbrainsMono = JetBrains_Mono({ subsets: ["latin"], variable: "--font-mono" });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "SEXY",
|
||||
title: { default: "Sexy", template: "%s · Sexy" },
|
||||
description: "Bluetooth toy control console",
|
||||
};
|
||||
|
||||
@@ -19,7 +19,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
||||
<html
|
||||
lang="en"
|
||||
suppressHydrationWarning
|
||||
className={cn("font-sans", inter.variable, spaceGrotesk.variable, jetbrainsMono.variable)}
|
||||
className={cn("font-sans", inter.variable, sora.variable, jetbrainsMono.variable)}
|
||||
>
|
||||
<body>
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange>
|
||||
|
||||
+4
-1
@@ -1,8 +1,11 @@
|
||||
import { Suspense } from "react";
|
||||
import type { Metadata } from "next";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { LoginForm } from "@/components/auth/LoginForm";
|
||||
import { BrandMark } from "@/components/layout/BrandMark";
|
||||
|
||||
export const metadata: Metadata = { title: "Log in" };
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center p-4">
|
||||
@@ -10,7 +13,7 @@ export default function LoginPage() {
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<BrandMark size={32} />
|
||||
<CardTitle className="font-heading bp-gradient-text text-2xl">SEXY</CardTitle>
|
||||
<CardTitle className="font-heading text-2xl">Sexy</CardTitle>
|
||||
</div>
|
||||
<CardDescription>Enter the shared access secret to continue.</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ import type { MetadataRoute } from "next";
|
||||
|
||||
export default function manifest(): MetadataRoute.Manifest {
|
||||
return {
|
||||
name: "SEXY",
|
||||
short_name: "SEXY",
|
||||
name: "Sexy",
|
||||
short_name: "Sexy",
|
||||
description: "Bluetooth toy control console",
|
||||
start_url: "/",
|
||||
display: "standalone",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import Link from "next/link";
|
||||
import type { Metadata } from "next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { BrandMark } from "@/components/layout/BrandMark";
|
||||
|
||||
export const metadata: Metadata = { title: "Not found" };
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center p-4">
|
||||
<Card className="bp-glass w-full max-w-sm">
|
||||
<CardContent className="flex flex-col items-center gap-4 py-4 text-center">
|
||||
<BrandMark size={32} />
|
||||
<div className="space-y-1">
|
||||
<p className="bp-readout bp-gradient-text text-4xl font-semibold">404</p>
|
||||
<p className="text-sm text-muted-foreground">This page doesn't exist.</p>
|
||||
</div>
|
||||
<Button asChild size="sm">
|
||||
<Link href="/">Back to dashboard</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -45,6 +45,8 @@ export function ButtplugConsole() {
|
||||
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 [activeSession, setActiveSession] = useState<ActivePlaySession | null>(null);
|
||||
@@ -136,6 +138,7 @@ export function ButtplugConsole() {
|
||||
sessionDeviceIdByDeviceIndex,
|
||||
});
|
||||
setElapsedMs(0);
|
||||
setRecording(true);
|
||||
} catch {
|
||||
toast.error("Could not start session.");
|
||||
} finally {
|
||||
@@ -147,6 +150,7 @@ export function ButtplugConsole() {
|
||||
if (!activeSession) return;
|
||||
setSessionBusy(true);
|
||||
eventBuffer.stop();
|
||||
setRecording(false);
|
||||
await fetch(`/api/play-sessions/${activeSession.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -197,6 +201,17 @@ export function ButtplugConsole() {
|
||||
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) {
|
||||
return (
|
||||
<Card className="bp-glass">
|
||||
@@ -249,6 +264,7 @@ export function ButtplugConsole() {
|
||||
}
|
||||
onActuatorChange={(featureIndex, value) => void handleActuatorChange(device, featureIndex, value)}
|
||||
onStop={() => void handleStopDevice(device)}
|
||||
onDisconnect={() => void handleDisconnectDevice(device)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ActuatorSlider } from "./ActuatorSlider";
|
||||
import type { ConnectedDeviceInfo } from "@/lib/buttplug/types";
|
||||
import { Battery, BatteryFull, BatteryLow, BatteryMedium, BatteryWarning } from "lucide-react";
|
||||
import { Battery, BatteryFull, BatteryLow, BatteryMedium, BatteryWarning, Unlink } from "lucide-react";
|
||||
|
||||
interface DeviceCardProps {
|
||||
device: ConnectedDeviceInfo;
|
||||
@@ -13,6 +13,7 @@ interface DeviceCardProps {
|
||||
transmittingFeatureIndex: number | null;
|
||||
onActuatorChange: (featureIndex: number, value: number) => void;
|
||||
onStop: () => void;
|
||||
onDisconnect: () => void;
|
||||
}
|
||||
|
||||
function BatteryIndicator({ level }: { level: number }) {
|
||||
@@ -32,6 +33,7 @@ export function DeviceCard({
|
||||
transmittingFeatureIndex,
|
||||
onActuatorChange,
|
||||
onStop,
|
||||
onDisconnect,
|
||||
}: DeviceCardProps) {
|
||||
return (
|
||||
<Card className="bp-glass">
|
||||
@@ -47,6 +49,9 @@ export function DeviceCard({
|
||||
<Button variant="outline" size="sm" onClick={onStop}>
|
||||
Stop
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onDisconnect} aria-label="Disconnect device">
|
||||
<Unlink className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<div className="bp-hairline mx-4" />
|
||||
|
||||
@@ -28,7 +28,7 @@ export function RecordControls({ active, elapsedLabel, disabled, busy, onStart,
|
||||
}
|
||||
|
||||
return (
|
||||
<Button onClick={onStart} disabled={disabled || busy} size="sm">
|
||||
<Button onClick={onStart} disabled={disabled || busy}>
|
||||
<Circle className="size-3.5" /> Start session
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -38,8 +38,8 @@ function DeviceNameCell({ device }: { device: DeviceRow }) {
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input value={value} onChange={(e) => setValue(e.target.value)} className="h-8 max-w-48" />
|
||||
<Button size="sm" variant="outline" onClick={handleSave} disabled={saving}>
|
||||
<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} className="shrink-0">
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -3,10 +3,12 @@ import { cn } from "@/lib/utils";
|
||||
interface BrandMarkProps {
|
||||
size?: number;
|
||||
className?: string;
|
||||
/** Beats the heart glyph and makes the curve glow - used for the dashboard hero mark. */
|
||||
animated?: boolean;
|
||||
}
|
||||
|
||||
/** Inline twin of app/icon.svg (the favicon) - kept as markup, not an <img>, so it can be sized/animated with CSS. */
|
||||
export function BrandMark({ size = 28, className }: BrandMarkProps) {
|
||||
export function BrandMark({ size = 28, className, animated = false }: BrandMarkProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
@@ -25,9 +27,11 @@ export function BrandMark({ size = 28, className }: BrandMarkProps) {
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="30" height="30" rx="9" fill="url(#bpGradMark)" />
|
||||
<g transform="translate(0 0.7)">
|
||||
<path
|
||||
d="M16 22.6c-.3 0-.5-.1-.7-.3C11.7 19 8 15.6 8 12.3 8 9.9 9.9 8 12.3 8c1.3 0 2.6.6 3.4 1.7.1.1.2.1.3 0 .8-1.1 2.1-1.7 3.4-1.7C21.8 8 23.7 9.9 23.7 12.3c0 3.3-3.7 6.7-7.3 10-.2.2-.4.3-.7.3z"
|
||||
fill="rgba(255,255,255,0.22)"
|
||||
className={cn(animated && "bp-mark-heart")}
|
||||
/>
|
||||
<polyline
|
||||
points="6,15 10,15 12,9 15,21 18,13 20,15 26,15"
|
||||
@@ -36,7 +40,9 @@ export function BrandMark({ size = 28, className }: BrandMarkProps) {
|
||||
strokeWidth={1.7}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={cn(animated && "bp-mark-curve")}
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { ChevronRight, House } from "lucide-react";
|
||||
|
||||
const SECTION_LABELS: Record<string, string> = {
|
||||
control: "Control",
|
||||
recordings: "Recordings",
|
||||
sessions: "Sessions",
|
||||
stats: "Stats",
|
||||
devices: "Devices",
|
||||
};
|
||||
|
||||
const LEAF_LABELS: Record<string, string> = {
|
||||
replay: "Replay",
|
||||
};
|
||||
|
||||
export function Breadcrumbs() {
|
||||
const pathname = usePathname();
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
|
||||
if (segments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const crumbs = segments.reduce<{ label: string; href: string }[]>((acc, segment) => {
|
||||
const href = `${acc.at(-1)?.href ?? ""}/${segment}`;
|
||||
const label = /^\d+$/.test(segment) ? `#${segment}` : (LEAF_LABELS[segment] ?? SECTION_LABELS[segment] ?? segment);
|
||||
return [...acc, { label, href }];
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<nav aria-label="Breadcrumb" className="bp-glass mb-6 flex w-fit items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm text-muted-foreground">
|
||||
<Link href="/" className="flex items-center hover:text-foreground" aria-label="Dashboard">
|
||||
<House className="size-3.5" />
|
||||
</Link>
|
||||
{crumbs.map((crumb, i) => {
|
||||
const isLast = i === crumbs.length - 1;
|
||||
return (
|
||||
<span key={crumb.href} className="flex items-center gap-1.5">
|
||||
<ChevronRight className="size-3.5 text-muted-foreground/50" />
|
||||
{isLast ? (
|
||||
<span className="font-medium text-foreground">{crumb.label}</span>
|
||||
) : (
|
||||
<Link href={crumb.href} className="hover:text-foreground">
|
||||
{crumb.label}
|
||||
</Link>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useButtplugStore } from "@/lib/buttplug/store";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type IndicatorState = "scanning" | "connected" | "recording";
|
||||
|
||||
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);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-md border border-border bg-card/60 px-3 py-1 text-xs">
|
||||
<span className={cn("bp-led", connected && "bp-pulse")} data-on={connected} aria-hidden />
|
||||
<span className="bp-readout text-muted-foreground">
|
||||
{connected ? `${deviceCount} device${deviceCount === 1 ? "" : "s"} connected` : "not connected"}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
// Priority: an active recording is the most important thing to surface,
|
||||
// then whether toys are actually connected, then a bare scan-in-progress -
|
||||
// this is deliberately independent of the Buttplug client's own `connected`
|
||||
// flag, which goes true as soon as the embedded server initializes (i.e. as
|
||||
// soon as scanning starts), not when a device is actually paired.
|
||||
const state: IndicatorState | null = recording
|
||||
? "recording"
|
||||
: deviceCount > 0
|
||||
? "connected"
|
||||
: scanning
|
||||
? "scanning"
|
||||
: null;
|
||||
|
||||
if (!state) return null;
|
||||
|
||||
return <span className="bp-led bp-pulse" data-state={state} aria-hidden />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
export function Footer() {
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
return (
|
||||
<footer className="mx-auto w-full max-w-6xl px-4 py-6">
|
||||
<div className="flex flex-col items-center gap-1 text-center text-xs text-muted-foreground">
|
||||
<p>
|
||||
Made with <span aria-hidden="true">💜</span> by{" "}
|
||||
<a
|
||||
href="https://dev.pivoine.art/valknar/sexy"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
Valknar
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
© {year} Sexy · Powered by{" "}
|
||||
<a
|
||||
href="https://buttplug.io/"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
Buttplug.io
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTheme } from "next-themes";
|
||||
@@ -45,6 +46,7 @@ function NavLinks({ onNavigate }: { onNavigate?: () => void }) {
|
||||
export function NavBar() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const router = useRouter();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
async function handleLogout() {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
@@ -57,7 +59,7 @@ export function NavBar() {
|
||||
<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">
|
||||
<BrandMark size={26} />
|
||||
<span className="font-heading bp-gradient-text text-lg font-semibold">SEXY</span>
|
||||
<span className="font-heading text-lg font-semibold">Sexy</span>
|
||||
</Link>
|
||||
|
||||
<nav className="hidden items-center gap-1 md:flex">
|
||||
@@ -79,7 +81,7 @@ export function NavBar() {
|
||||
<LogOut className="size-4" />
|
||||
</Button>
|
||||
|
||||
<Sheet>
|
||||
<Sheet open={menuOpen} onOpenChange={setMenuOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="md:hidden" aria-label="Open menu">
|
||||
<Menu className="size-4" />
|
||||
@@ -88,7 +90,7 @@ export function NavBar() {
|
||||
<SheetContent side="right" className="w-64">
|
||||
<SheetTitle className="px-4 pt-4">Menu</SheetTitle>
|
||||
<nav className="flex flex-col gap-1 p-4">
|
||||
<NavLinks />
|
||||
<NavLinks onNavigate={() => setMenuOpen(false)} />
|
||||
</nav>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
"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 { 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";
|
||||
@@ -32,16 +31,21 @@ function formatTime(ms: number): string {
|
||||
}
|
||||
|
||||
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}`)
|
||||
@@ -50,19 +54,39 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
.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) => {
|
||||
const deviceIndex = mapping.get(slot.sourceSessionDeviceId)!;
|
||||
const device = connectedDevices.find((d) => d.index === deviceIndex)!;
|
||||
return { slotLabel: slot.slotLabel, bleName: device.name };
|
||||
}),
|
||||
devices: orderedSlots.map((slot, i) => ({ slotLabel: slot.slotLabel, bleName: targets[i].deviceName })),
|
||||
};
|
||||
|
||||
const res = await fetch("/api/play-sessions", {
|
||||
@@ -92,13 +116,27 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
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();
|
||||
@@ -106,13 +144,21 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
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) {
|
||||
@@ -136,30 +182,47 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
<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}
|
||||
disabled={connectedDevices.length === 0 || starting}
|
||||
>
|
||||
Match devices & replay
|
||||
{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="text-xs text-muted-foreground">
|
||||
<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={() => {
|
||||
onClick={async () => {
|
||||
if (playing) {
|
||||
player.pause();
|
||||
setPlaying(false);
|
||||
@@ -167,10 +230,50 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
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>
|
||||
)}
|
||||
@@ -184,10 +287,6 @@ export function ReplayPlayer({ recordingId }: { recordingId: number }) {
|
||||
onCancel={() => setShowRemap(false)}
|
||||
onConfirm={(mapping) => void handleConfirmRemap(mapping)}
|
||||
/>
|
||||
|
||||
<Button variant="ghost" size="sm" onClick={() => router.push("/recordings")}>
|
||||
Back to recordings
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface BlockingRecording {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface SessionRow {
|
||||
id: number;
|
||||
name: string | null;
|
||||
@@ -27,6 +41,8 @@ function formatDuration(ms: number | null): string {
|
||||
|
||||
export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
||||
const router = useRouter();
|
||||
const [conflict, setConflict] = useState<{ id: number; recordings: BlockingRecording[] } | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
async function handleDelete(id: number) {
|
||||
const res = await fetch(`/api/play-sessions/${id}`, { method: "DELETE" });
|
||||
@@ -34,7 +50,22 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
||||
toast.success("Session deleted");
|
||||
router.refresh();
|
||||
} 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 {
|
||||
toast.error("Could not delete session");
|
||||
}
|
||||
@@ -45,6 +76,7 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
@@ -81,5 +113,29 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
|
||||
))}
|
||||
</TableBody>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
|
||||
export interface DeviceUsageRow {
|
||||
@@ -12,10 +13,16 @@ export interface DeviceUsageRow {
|
||||
|
||||
export function DeviceUsageTable({ devices }: { devices: DeviceUsageRow[] }) {
|
||||
if (devices.length === 0) {
|
||||
return <p className="text-sm text-muted-foreground">No device activity yet.</p>;
|
||||
return (
|
||||
<Card className="bp-glass">
|
||||
<CardContent className="py-6 text-sm text-muted-foreground">No device activity yet.</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="bp-glass">
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
@@ -40,5 +47,7 @@ export function DeviceUsageTable({ devices }: { devices: DeviceUsageRow[] }) {
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,6 +35,8 @@ export function RecordingLibraryStats({ stats }: { stats: RecordingLibrarySummar
|
||||
</div>
|
||||
|
||||
{stats.list.length > 0 && (
|
||||
<Card className="bp-glass">
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
@@ -55,6 +57,8 @@ export function RecordingLibraryStats({ stats }: { stats: RecordingLibrarySummar
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -40,9 +40,11 @@ export function SessionsSummaryCards({ summary }: { summary: SessionsSummary })
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<Card className="bp-glass">
|
||||
<CardContent className="py-3 text-sm text-muted-foreground">
|
||||
{liveCount} live · {replayCount} replay
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{summary.durationPerDevice.length > 0 && (
|
||||
<Card className="bp-glass">
|
||||
<CardHeader>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
export async function register() {
|
||||
// Only the Node.js server runtime touches better-sqlite3; the Edge
|
||||
// middleware runtime must never import this module.
|
||||
@@ -6,3 +8,26 @@ export async function register() {
|
||||
runMigrations();
|
||||
}
|
||||
}
|
||||
|
||||
export async function onRequestError(
|
||||
error: unknown,
|
||||
request: { path: string; method: string; headers: Record<string, string | string[]> },
|
||||
context: { routerKind: string; routePath: string; routeType: string },
|
||||
) {
|
||||
const log = createLogger("uncaught");
|
||||
|
||||
// Safety net for errors that escape a route handler's own try/catch (e.g. a
|
||||
// bug in code that never reaches withRouteLogging, or a rendering error) -
|
||||
// route handlers wrapped in withRouteLogging already log and convert their
|
||||
// own errors to a JSON 500, so this rarely double-logs the same failure.
|
||||
const digest = typeof error === "object" && error !== null && "digest" in error ? String(error.digest) : undefined;
|
||||
log.error("unhandled error", {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
digest,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
path: request.path,
|
||||
method: request.method,
|
||||
routePath: context.routePath,
|
||||
routeType: context.routeType,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const log = createLogger("api");
|
||||
|
||||
type RouteHandler<Ctx> = (req: Request, ctx: Ctx) => Promise<Response> | Response;
|
||||
|
||||
/**
|
||||
* Wraps an App Router route handler with consistent request/response logging:
|
||||
* a reqId (also echoed as `x-request-id`), method/path, status, and duration on
|
||||
* every call, plus a logged stack trace and JSON 500 for anything the handler
|
||||
* doesn't catch itself. Every export in app/api/** goes through this so log
|
||||
* shape and error handling stay uniform across routes instead of being
|
||||
* reimplemented per file.
|
||||
*/
|
||||
export function withRouteLogging<Ctx = unknown>(routeName: string, handler: RouteHandler<Ctx>): RouteHandler<Ctx> {
|
||||
return async (req, ctx) => {
|
||||
const reqId = randomUUID();
|
||||
const start = performance.now();
|
||||
const { pathname, search } = new URL(req.url);
|
||||
const reqLog = log.child({ reqId, route: routeName, method: req.method });
|
||||
|
||||
reqLog.debug("request start", { path: pathname + search });
|
||||
|
||||
try {
|
||||
const res = await handler(req, ctx);
|
||||
const durationMs = Math.round(performance.now() - start);
|
||||
const level = res.status >= 500 ? "error" : res.status >= 400 ? "warn" : "info";
|
||||
reqLog[level]("request end", { status: res.status, durationMs });
|
||||
res.headers.set("x-request-id", reqId);
|
||||
return res;
|
||||
} catch (err) {
|
||||
const durationMs = Math.round(performance.now() - start);
|
||||
reqLog.error("request failed", {
|
||||
durationMs,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
return NextResponse.json({ error: "internal error", reqId }, { status: 500 });
|
||||
}
|
||||
};
|
||||
}
|
||||
+21
-12
@@ -14,6 +14,11 @@ export interface RecordingEventRow {
|
||||
|
||||
export interface PlayerOptions {
|
||||
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. */
|
||||
sessionDeviceIdToDeviceIndex: Map<number, number>;
|
||||
actuatorsByDeviceIndex: Map<number, ActuatorInfo[]>;
|
||||
@@ -21,6 +26,7 @@ export interface PlayerOptions {
|
||||
speed?: number;
|
||||
onProgress?: (elapsedMs: number, durationMs: number) => void;
|
||||
onComplete?: () => void;
|
||||
onError?: (message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,7 +43,7 @@ export class RecordingPlayer {
|
||||
private playing = false;
|
||||
|
||||
constructor(private readonly options: PlayerOptions) {
|
||||
this.durationMs = options.events.at(-1)?.tsMs ?? 0;
|
||||
this.durationMs = options.durationMs;
|
||||
}
|
||||
|
||||
get isPlaying(): boolean {
|
||||
@@ -108,22 +114,13 @@ export class RecordingPlayer {
|
||||
const deviceIndex = this.options.sessionDeviceIdToDeviceIndex.get(event.sessionDeviceId);
|
||||
if (deviceIndex === undefined) return;
|
||||
|
||||
try {
|
||||
const device = await getDevice(deviceIndex);
|
||||
if (!device) return;
|
||||
|
||||
eventBuffer.record({
|
||||
deviceIndex,
|
||||
commandType: event.commandType,
|
||||
featureIndex: event.featureIndex,
|
||||
value: event.value,
|
||||
durationMs: event.durationMs ?? undefined,
|
||||
});
|
||||
|
||||
if (event.commandType === "stop") {
|
||||
await device.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
} else {
|
||||
const actuator = this.options.actuatorsByDeviceIndex
|
||||
.get(deviceIndex)
|
||||
?.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);
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ export const actuatorKey = (deviceIndex: number, featureIndex: number): string =
|
||||
interface ButtplugStoreState {
|
||||
connected: boolean;
|
||||
scanning: boolean;
|
||||
/** Whether a play session is actively being recorded (see ButtplugConsole's session lifecycle). */
|
||||
recording: boolean;
|
||||
devices: Record<number, ConnectedDeviceInfo>;
|
||||
/** Last-known slider value per `${deviceIndex}:${featureIndex}`, for UI display only. */
|
||||
actuatorValues: Record<string, number>;
|
||||
@@ -15,6 +17,7 @@ interface ButtplugStoreState {
|
||||
error: string | null;
|
||||
setConnected: (connected: boolean) => void;
|
||||
setScanning: (scanning: boolean) => void;
|
||||
setRecording: (recording: boolean) => void;
|
||||
upsertDevice: (device: ConnectedDeviceInfo) => void;
|
||||
removeDevice: (index: number) => void;
|
||||
setActuatorValue: (deviceIndex: number, featureIndex: number, value: number) => void;
|
||||
@@ -26,12 +29,14 @@ interface ButtplugStoreState {
|
||||
export const useButtplugStore = create<ButtplugStoreState>((set) => ({
|
||||
connected: false,
|
||||
scanning: false,
|
||||
recording: false,
|
||||
devices: {},
|
||||
actuatorValues: {},
|
||||
batteryLevels: {},
|
||||
error: null,
|
||||
setConnected: (connected) => set({ connected }),
|
||||
setScanning: (scanning) => set({ scanning }),
|
||||
setRecording: (recording) => set({ recording }),
|
||||
upsertDevice: (device) => set((s) => ({ devices: { ...s.devices, [device.index]: device } })),
|
||||
removeDevice: (index) =>
|
||||
set((s) => {
|
||||
@@ -48,5 +53,6 @@ export const useButtplugStore = create<ButtplugStoreState>((set) => ({
|
||||
setBatteryLevel: (deviceIndex, level) =>
|
||||
set((s) => ({ batteryLevels: { ...s.batteryLevels, [deviceIndex]: level } })),
|
||||
setError: (message) => set({ error: message }),
|
||||
reset: () => set({ connected: false, scanning: false, devices: {}, actuatorValues: {}, batteryLevels: {} }),
|
||||
reset: () =>
|
||||
set({ connected: false, scanning: false, recording: false, devices: {}, actuatorValues: {}, batteryLevels: {} }),
|
||||
}));
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { devices, type DeviceCapabilities } from "@/lib/db/schema";
|
||||
import { PAGE_SIZE, type Page } from "@/lib/pagination";
|
||||
|
||||
export async function listDevices() {
|
||||
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) {
|
||||
const [row] = await db.select().from(devices).where(eq(devices.id, id));
|
||||
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 { playSessions, sessionDevices, devices } from "@/lib/db/schema";
|
||||
import { playSessions, sessionDevices, devices, recordings } from "@/lib/db/schema";
|
||||
import { upsertDeviceByBleName } from "./devices";
|
||||
import { incrementPlayCount } from "./recordings";
|
||||
import type { DeviceCapabilities } from "@/lib/db/schema";
|
||||
import { PAGE_SIZE, type Page } from "@/lib/pagination";
|
||||
|
||||
export interface StartSessionDeviceInput {
|
||||
slotLabel: string;
|
||||
@@ -86,6 +87,23 @@ export async function listPlaySessions() {
|
||||
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) {
|
||||
const [session] = await db.select().from(playSessions).where(eq(playSessions.id, id));
|
||||
if (!session) return undefined;
|
||||
@@ -107,6 +125,9 @@ export async function getPlaySessionDetail(id: number) {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { recordings, sessionDevices, devices, playSessions, type RecordingDeviceSlot } from "@/lib/db/schema";
|
||||
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
|
||||
@@ -60,6 +61,30 @@ export async function listRecordings() {
|
||||
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) {
|
||||
const [recording] = await db.select().from(recordings).where(eq(recordings.id, id));
|
||||
if (!recording) return undefined;
|
||||
|
||||
+12
-5
@@ -34,14 +34,21 @@ export interface Logger {
|
||||
info(message: string, fields?: LogFields): void;
|
||||
warn(message: string, fields?: LogFields): void;
|
||||
error(message: string, fields?: LogFields): void;
|
||||
/** Returns a logger that merges `bindings` into every call's fields - for attaching
|
||||
* per-request context (reqId, route) without threading it through every log call. */
|
||||
child(bindings: LogFields): Logger;
|
||||
}
|
||||
|
||||
/** Scoped logger. `scope` is the bracketed tag, e.g. createLogger("api") -> "[api]". */
|
||||
export function createLogger(scope: string): Logger {
|
||||
export function createLogger(scope: string, bindings?: LogFields): Logger {
|
||||
const log = (level: LogLevel, message: string, fields?: LogFields) =>
|
||||
write(level, scope, message, bindings || fields ? { ...bindings, ...fields } : undefined);
|
||||
|
||||
return {
|
||||
debug: (message, fields) => write("debug", scope, message, fields),
|
||||
info: (message, fields) => write("info", scope, message, fields),
|
||||
warn: (message, fields) => write("warn", scope, message, fields),
|
||||
error: (message, fields) => write("error", scope, message, fields),
|
||||
debug: (message, fields) => log("debug", message, fields),
|
||||
info: (message, fields) => log("info", message, fields),
|
||||
warn: (message, fields) => log("warn", message, fields),
|
||||
error: (message, fields) => log("error", message, fields),
|
||||
child: (extra) => createLogger(scope, { ...bindings, ...extra }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sexy",
|
||||
"version": "0.2.1",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { SESSION_COOKIE_NAME, verifySessionToken } from "@/lib/auth/session";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const log = createLogger("auth");
|
||||
|
||||
export default async function proxy(req: NextRequest) {
|
||||
const { pathname } = req.nextUrl;
|
||||
@@ -13,9 +16,11 @@ export default async function proxy(req: NextRequest) {
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/api/")) {
|
||||
log.warn("rejected unauthenticated request", { path: pathname, method: req.method });
|
||||
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
log.warn("redirecting unauthenticated request to login", { path: pathname });
|
||||
const loginUrl = new URL("/login", req.url);
|
||||
loginUrl.searchParams.set("from", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
|
||||
Reference in New Issue
Block a user