Convert settings page to server component with server actions

Replace client-side data fetching with server-side queries and server
actions, eliminating 3 API route files. Extract page into granular
client components (account, integrations, server, webhook card) with
optimistic updates. Rename sections: Media Servers → Integrations,
Administration → Server. Add admin badge to account section.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-03 09:32:18 -05:00
co-authored by Claude Opus 4.6
parent 83e2bc5143
commit 8487c3d7b1
11 changed files with 864 additions and 800 deletions
@@ -0,0 +1,71 @@
"use client";
import { IconLogout, IconUser } from "@tabler/icons-react";
import { useRouter } from "next/navigation";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import { signOut } from "@/lib/auth/client";
export function AccountSection({
user,
}: {
user: { name: string; email: string; createdAt: string; role?: string };
}) {
const router = useRouter();
const memberSince = new Date(user.createdAt).toLocaleDateString(undefined, {
year: "numeric",
month: "long",
});
const initial = user.name?.charAt(0).toUpperCase() ?? "?";
return (
<div>
<div className="mb-3 flex items-center gap-2">
<IconUser size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Account
</h2>
</div>
<Card>
<CardContent className="flex items-center gap-4">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-primary/10 font-display text-lg text-primary">
{initial}
</div>
<div className="min-w-0 flex-1">
<CardTitle>
{user.name}
{user.role === "admin" && (
<span className="ml-2 inline-flex items-center rounded-md bg-primary/10 px-1.5 py-0.5 align-middle text-[10px] font-medium text-primary">
Admin
</span>
)}
</CardTitle>
<CardDescription>{user.email}</CardDescription>
<p className="mt-0.5 text-xs text-muted-foreground/60">
Member since {memberSince}
</p>
</div>
</CardContent>
<CardContent className="pt-0">
<button
type="button"
onClick={async () => {
await signOut();
router.push("/");
router.refresh();
}}
className="inline-flex h-9 items-center gap-2 rounded-lg border border-border/50 px-4 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<IconLogout size={14} />
Sign out
</button>
</CardContent>
</Card>
</div>
);
}
+140
View File
@@ -0,0 +1,140 @@
"use server";
import crypto from "node:crypto";
import { and, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db } from "@/lib/db/client";
import { webhookConnections } from "@/lib/db/schema";
import { setSetting } from "@/lib/services/settings";
async function getSession() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) throw new Error("Unauthorized");
return session;
}
export async function saveWebhookConnection(
provider: "plex" | "jellyfin",
mediaServerUsername: string,
enabled?: boolean,
) {
const session = await getSession();
if (!["plex", "jellyfin"].includes(provider)) {
throw new Error("Invalid provider");
}
if (!mediaServerUsername?.trim()) {
throw new Error("Media server username is required");
}
const existing = await db
.select()
.from(webhookConnections)
.where(
and(
eq(webhookConnections.userId, session.user.id),
eq(webhookConnections.provider, provider),
),
)
.get();
if (existing) {
const connection = await db
.update(webhookConnections)
.set({
mediaServerUsername: mediaServerUsername.trim(),
enabled: typeof enabled === "boolean" ? enabled : existing.enabled,
})
.where(eq(webhookConnections.id, existing.id))
.returning()
.get();
return {
...connection,
lastEventAt: connection.lastEventAt?.toISOString() ?? null,
createdAt: connection.createdAt.toISOString(),
};
}
const token = crypto.randomBytes(32).toString("hex");
const now = new Date();
const connection = await db
.insert(webhookConnections)
.values({
userId: session.user.id,
provider,
token,
mediaServerUsername: mediaServerUsername.trim(),
enabled: true,
createdAt: now,
})
.returning()
.get();
return {
...connection,
lastEventAt: connection.lastEventAt?.toISOString() ?? null,
createdAt: connection.createdAt.toISOString(),
};
}
export async function deleteWebhookConnection(provider: "plex" | "jellyfin") {
const session = await getSession();
if (!["plex", "jellyfin"].includes(provider)) {
throw new Error("Invalid provider");
}
await db
.delete(webhookConnections)
.where(
and(
eq(webhookConnections.userId, session.user.id),
eq(webhookConnections.provider, provider),
),
)
.run();
}
export async function regenerateWebhookToken(provider: "plex" | "jellyfin") {
const session = await getSession();
if (!["plex", "jellyfin"].includes(provider)) {
throw new Error("Invalid provider");
}
const newToken = crypto.randomBytes(32).toString("hex");
const connection = await db
.update(webhookConnections)
.set({ token: newToken })
.where(
and(
eq(webhookConnections.userId, session.user.id),
eq(webhookConnections.provider, provider),
),
)
.returning()
.get();
if (!connection) {
throw new Error("Connection not found");
}
return {
...connection,
lastEventAt: connection.lastEventAt?.toISOString() ?? null,
createdAt: connection.createdAt.toISOString(),
};
}
export async function toggleRegistration(open: boolean) {
const session = await getSession();
if (session.user.role !== "admin") {
throw new Error("Forbidden");
}
await setSetting("registrationOpen", String(open));
}
@@ -0,0 +1,103 @@
"use client";
import { IconWebhook } from "@tabler/icons-react";
import { useState } from "react";
import {
deleteWebhookConnection,
regenerateWebhookToken,
saveWebhookConnection,
} from "./actions";
import { WebhookCard, type WebhookConnection } from "./webhook-card";
export function IntegrationsSection({
initialConnections,
}: {
initialConnections: WebhookConnection[];
}) {
const [connections, setConnections] =
useState<WebhookConnection[]>(initialConnections);
const plexConnection = connections.find((c) => c.provider === "plex") ?? null;
const jellyfinConnection =
connections.find((c) => c.provider === "jellyfin") ?? null;
async function handleSave(provider: "plex" | "jellyfin", username: string) {
const result = await saveWebhookConnection(provider, username);
setConnections((prev) => {
const existing = prev.find((c) => c.provider === provider);
if (existing) {
return prev.map((c) =>
c.provider === provider
? { ...result, recentEvents: existing.recentEvents }
: c,
);
}
return [...prev, { ...result, recentEvents: [] }];
});
}
async function handleDelete(provider: "plex" | "jellyfin") {
const previous = connections;
setConnections((prev) => prev.filter((c) => c.provider !== provider));
try {
await deleteWebhookConnection(provider);
} catch {
setConnections(previous);
}
}
async function handleRegenerateToken(provider: "plex" | "jellyfin") {
const result = await regenerateWebhookToken(provider);
setConnections((prev) =>
prev.map((c) =>
c.provider === provider ? { ...c, token: result.token } : c,
),
);
}
async function handleToggle(provider: "plex" | "jellyfin", enabled: boolean) {
const previous = connections;
setConnections((prev) =>
prev.map((c) => (c.provider === provider ? { ...c, enabled } : c)),
);
try {
const conn = connections.find((c) => c.provider === provider);
await saveWebhookConnection(
provider,
conn?.mediaServerUsername ?? "",
enabled,
);
} catch {
setConnections(previous);
}
}
return (
<div>
<div className="mb-3 flex items-center gap-2">
<IconWebhook size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Integrations
</h2>
</div>
<div className="space-y-3">
<WebhookCard
provider="plex"
connection={plexConnection}
onSave={handleSave}
onDelete={handleDelete}
onRegenerateToken={handleRegenerateToken}
onToggle={handleToggle}
/>
<WebhookCard
provider="jellyfin"
connection={jellyfinConnection}
onSave={handleSave}
onDelete={handleDelete}
onRegenerateToken={handleRegenerateToken}
onToggle={handleToggle}
/>
</div>
</div>
);
}
@@ -0,0 +1,73 @@
"use client";
import { IconShieldLock, IconUserPlus } from "@tabler/icons-react";
import { useState } from "react";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { toggleRegistration } from "./actions";
export function ServerSection({
initialRegistrationOpen,
}: {
initialRegistrationOpen: boolean;
}) {
const [registrationOpen, setRegistrationOpen] = useState(
initialRegistrationOpen,
);
const [toggling, setToggling] = useState(false);
async function handleToggle(checked: boolean) {
const previous = registrationOpen;
setRegistrationOpen(checked);
setToggling(true);
try {
await toggleRegistration(checked);
} catch {
setRegistrationOpen(previous);
} finally {
setToggling(false);
}
}
return (
<div>
<div className="mb-3 flex items-center gap-2">
<IconShieldLock size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Server
</h2>
<span className="rounded-md bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
Admin
</span>
</div>
<Card className="border-l-2 border-l-primary/30">
<CardContent>
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconUserPlus size={16} className="text-primary" />
</div>
<div>
<CardTitle>Open registration</CardTitle>
<CardDescription>
Allow new users to create accounts. Useful for adding
household members.
</CardDescription>
</div>
</div>
<Switch
checked={registrationOpen}
onCheckedChange={handleToggle}
disabled={toggling}
/>
</div>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,42 @@
"use client";
import { IconSettings } from "@tabler/icons-react";
import { motion } from "motion/react";
import { Children, type ReactNode } from "react";
const sectionVariants = {
hidden: { opacity: 0, y: 20 },
visible: {
opacity: 1,
y: 0,
transition: { type: "spring" as const, stiffness: 200, damping: 24 },
},
};
export function SettingsShell({ children }: { children: ReactNode }) {
return (
<motion.div
className="mx-auto max-w-2xl space-y-8"
initial="hidden"
animate="visible"
variants={{
hidden: {},
visible: { transition: { staggerChildren: 0.15 } },
}}
>
<motion.div variants={sectionVariants}>
<div className="flex items-center gap-2">
<IconSettings size={20} className="text-primary" />
<h1 className="font-display text-3xl tracking-tight">Settings</h1>
</div>
<p className="mt-1 text-sm text-muted-foreground">
Manage your account and preferences
</p>
</motion.div>
{Children.map(children, (child) => (
<motion.div variants={sectionVariants}>{child}</motion.div>
))}
</motion.div>
);
}
@@ -0,0 +1,343 @@
"use client";
import {
IconCheck,
IconChevronDown,
IconCopy,
IconInfoCircle,
IconRefresh,
IconTrash,
} from "@tabler/icons-react";
import { AnimatePresence, motion } from "motion/react";
import { useState } from "react";
import { JellyfinIcon, PlexIcon } from "@/components/icons/media-servers";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
export interface WebhookConnection {
id: string;
provider: "plex" | "jellyfin";
token: string;
mediaServerUsername: string;
enabled: boolean;
lastEventAt: string | null;
recentEvents: {
id: string;
eventType: string | null;
mediaType: string | null;
mediaTitle: string | null;
status: "success" | "ignored" | "error";
receivedAt: string;
}[];
}
export function timeAgo(dateStr: string): string {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
export function WebhookCard({
provider,
connection,
onSave,
onDelete,
onRegenerateToken,
onToggle,
}: {
provider: "plex" | "jellyfin";
connection: WebhookConnection | null;
onSave: (provider: "plex" | "jellyfin", username: string) => Promise<void>;
onDelete: (provider: "plex" | "jellyfin") => Promise<void>;
onRegenerateToken: (provider: "plex" | "jellyfin") => Promise<void>;
onToggle: (provider: "plex" | "jellyfin", enabled: boolean) => Promise<void>;
}) {
const [username, setUsername] = useState(
connection?.mediaServerUsername ?? "",
);
const [saving, setSaving] = useState(false);
const [copied, setCopied] = useState(false);
const [setupOpen, setSetupOpen] = useState(false);
const [cardOpen, setCardOpen] = useState(false);
const isPlex = provider === "plex";
const label = isPlex ? "Plex" : "Jellyfin";
const Icon = isPlex ? PlexIcon : JellyfinIcon;
const webhookUrl = connection
? `${window.location.origin}/api/webhooks/${connection.token}`
: null;
async function handleSave() {
if (!username.trim()) return;
setSaving(true);
try {
await onSave(provider, username.trim());
} finally {
setSaving(false);
}
}
async function handleCopy() {
if (!webhookUrl) return;
await navigator.clipboard.writeText(webhookUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
return (
<Card>
<Collapsible open={cardOpen} onOpenChange={setCardOpen}>
<CardContent>
<CollapsibleTrigger className="flex w-full cursor-pointer items-center justify-between gap-4">
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<Icon className="size-4 text-primary" />
</div>
<div className="text-left">
<CardTitle>{label}</CardTitle>
<CardDescription>
{connection
? connection.lastEventAt
? `Last event ${timeAgo(connection.lastEventAt)}`
: "Connected — no events yet"
: "Not configured"}
</CardDescription>
</div>
</div>
<IconChevronDown
size={16}
className={`text-muted-foreground transition-transform duration-200 ${cardOpen ? "rotate-180" : ""}`}
/>
</CollapsibleTrigger>
</CardContent>
<CollapsibleContent>
<CardContent className="space-y-3 pt-0">
{connection && (
<div className="flex items-center justify-between rounded-lg bg-muted/30 px-3 py-2">
<span className="text-xs text-muted-foreground">
Webhook {connection.enabled ? "enabled" : "disabled"}
</span>
<Switch
checked={connection.enabled}
onCheckedChange={(checked) => onToggle(provider, checked)}
/>
</div>
)}
{isPlex && (
<div className="flex gap-2.5 rounded-lg border border-primary/20 bg-primary/5 px-3 py-2.5">
<IconInfoCircle
size={14}
className="mt-0.5 shrink-0 text-primary"
/>
<p className="text-xs leading-relaxed text-muted-foreground">
Plex webhooks require an active{" "}
<span className="font-medium text-foreground">Plex Pass</span>{" "}
subscription.
</p>
</div>
)}
<div>
<label
htmlFor={`${provider}-username`}
className="mb-1 block text-xs text-muted-foreground"
>
{label} username
</label>
<div className="flex gap-2">
<Input
id={`${provider}-username`}
placeholder={`Your ${label} username`}
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSave()}
/>
{!connection ? (
<Button
onClick={handleSave}
disabled={saving || !username.trim()}
>
{saving ? "Saving..." : "Connect"}
</Button>
) : (
username.trim() !== connection.mediaServerUsername && (
<Button
onClick={handleSave}
disabled={saving || !username.trim()}
variant="outline"
>
Update
</Button>
)
)}
</div>
</div>
<AnimatePresence>
{webhookUrl && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
className="space-y-3 overflow-hidden"
>
<div>
<label
htmlFor={`${provider}-webhook-url`}
className="mb-1 block text-xs text-muted-foreground"
>
Webhook URL
</label>
<div className="flex gap-2">
<Input
id={`${provider}-webhook-url`}
readOnly
value={webhookUrl}
className="font-mono text-[10px] text-muted-foreground"
/>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="icon"
onClick={handleCopy}
/>
}
>
{copied ? (
<IconCheck size={14} className="text-green-400" />
) : (
<IconCopy size={14} />
)}
</TooltipTrigger>
<TooltipContent>Copy URL</TooltipContent>
</Tooltip>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => onRegenerateToken(provider)}
>
<IconRefresh size={12} />
Regenerate URL
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => onDelete(provider)}
>
<IconTrash size={12} />
Disconnect
</Button>
</div>
</motion.div>
)}
</AnimatePresence>
<Collapsible open={setupOpen} onOpenChange={setSetupOpen}>
<CollapsibleTrigger className="flex w-full items-center gap-1.5 rounded-md py-1 text-xs text-muted-foreground transition-colors hover:text-foreground">
<IconChevronDown
size={12}
className={`transition-transform ${setupOpen ? "rotate-0" : "-rotate-90"}`}
/>
Setup instructions
</CollapsibleTrigger>
<CollapsibleContent>
<div className="mt-2 rounded-lg bg-muted/30 p-3 text-xs leading-relaxed text-muted-foreground">
{isPlex ? (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Open Plex, go to{" "}
<span className="font-medium text-foreground">
Settings &gt; Webhooks
</span>
</li>
<li>
Click{" "}
<span className="font-medium text-foreground">
Add Webhook
</span>{" "}
and paste the URL above
</li>
<li>
Sofa will automatically log movies and episodes when you
finish watching them
</li>
<li>
Make sure the username above matches your Plex account
name
</li>
</ol>
) : (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Install the{" "}
<span className="font-medium text-foreground">
Webhook plugin
</span>{" "}
from Jellyfin&apos;s plugin catalog
</li>
<li>
Go to{" "}
<span className="font-medium text-foreground">
Dashboard &gt; Plugins &gt; Webhook
</span>
</li>
<li>
Add a{" "}
<span className="font-medium text-foreground">
Generic Destination
</span>{" "}
and paste the URL above
</li>
<li>
Enable the{" "}
<span className="font-medium text-foreground">
Playback Stop
</span>{" "}
notification type
</li>
<li>
Make sure the username above matches your Jellyfin
username
</li>
</ol>
)}
</div>
</CollapsibleContent>
</Collapsible>
</CardContent>
</CollapsibleContent>
</Collapsible>
</Card>
);
}
+26
View File
@@ -0,0 +1,26 @@
import { Skeleton } from "@/components/ui/skeleton";
export default function SettingsLoading() {
return (
<div className="mx-auto max-w-2xl space-y-8">
{/* Header */}
<div>
<Skeleton className="h-9 w-40" />
<Skeleton className="mt-2 h-4 w-64" />
</div>
{/* Account card */}
<div className="space-y-3">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-28 w-full rounded-xl" />
</div>
{/* Media server cards */}
<div className="space-y-3">
<Skeleton className="h-4 w-28" />
<Skeleton className="h-16 w-full rounded-xl" />
<Skeleton className="h-16 w-full rounded-xl" />
</div>
</div>
);
}
+66 -603
View File
@@ -1,612 +1,75 @@
"use client";
import { desc, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth/server";
import { db } from "@/lib/db/client";
import { webhookConnections, webhookEventLog } from "@/lib/db/schema";
import { getSetting } from "@/lib/services/settings";
import { AccountSection } from "./_components/account-section";
import { IntegrationsSection } from "./_components/integrations-section";
import { ServerSection } from "./_components/server-section";
import { SettingsShell } from "./_components/settings-shell";
import {
IconCheck,
IconChevronDown,
IconCopy,
IconInfoCircle,
IconLogout,
IconRefresh,
IconSettings,
IconShieldLock,
IconTrash,
IconUser,
IconUserPlus,
IconWebhook,
} from "@tabler/icons-react";
import { AnimatePresence, motion } from "motion/react";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { JellyfinIcon, PlexIcon } from "@/components/icons/media-servers";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { signOut, useSession } from "@/lib/auth/client";
export default async function SettingsPage() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session?.user) redirect("/login");
const sectionVariants = {
hidden: { opacity: 0, y: 20 },
visible: {
opacity: 1,
y: 0,
transition: { type: "spring" as const, stiffness: 200, damping: 24 },
},
};
const isAdmin = session.user.role === "admin";
interface WebhookConnection {
id: string;
provider: "plex" | "jellyfin";
token: string;
mediaServerUsername: string;
enabled: boolean;
lastEventAt: string | null;
recentEvents: {
id: string;
eventType: string | null;
mediaType: string | null;
mediaTitle: string | null;
status: "success" | "ignored" | "error";
receivedAt: string;
}[];
}
const [connections, registrationOpen] = await Promise.all([
(async () => {
const rows = await db
.select()
.from(webhookConnections)
.where(eq(webhookConnections.userId, session.user.id))
.all();
function timeAgo(dateStr: string): string {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
return Promise.all(
rows.map(async (conn) => {
const events = await db
.select()
.from(webhookEventLog)
.where(eq(webhookEventLog.connectionId, conn.id))
.orderBy(desc(webhookEventLog.receivedAt))
.limit(10)
.all();
function WebhookCard({
provider,
connection,
onSave,
onDelete,
onRegenerateToken,
onToggle,
}: {
provider: "plex" | "jellyfin";
connection: WebhookConnection | null;
onSave: (provider: "plex" | "jellyfin", username: string) => Promise<void>;
onDelete: (provider: "plex" | "jellyfin") => Promise<void>;
onRegenerateToken: (provider: "plex" | "jellyfin") => Promise<void>;
onToggle: (provider: "plex" | "jellyfin", enabled: boolean) => Promise<void>;
}) {
const [username, setUsername] = useState(
connection?.mediaServerUsername ?? "",
);
const [saving, setSaving] = useState(false);
const [copied, setCopied] = useState(false);
const [setupOpen, setSetupOpen] = useState(false);
const [cardOpen, setCardOpen] = useState(false);
const isPlex = provider === "plex";
const label = isPlex ? "Plex" : "Jellyfin";
const Icon = isPlex ? PlexIcon : JellyfinIcon;
const webhookUrl = connection
? `${window.location.origin}/api/webhooks/${connection.token}`
: null;
async function handleSave() {
if (!username.trim()) return;
setSaving(true);
try {
await onSave(provider, username.trim());
} finally {
setSaving(false);
}
}
async function handleCopy() {
if (!webhookUrl) return;
await navigator.clipboard.writeText(webhookUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
return {
id: conn.id,
provider: conn.provider,
token: conn.token,
mediaServerUsername: conn.mediaServerUsername,
enabled: conn.enabled,
lastEventAt: conn.lastEventAt?.toISOString() ?? null,
recentEvents: events.map((e) => ({
id: e.id,
eventType: e.eventType,
mediaType: e.mediaType,
mediaTitle: e.mediaTitle,
status: e.status,
receivedAt: e.receivedAt.toISOString(),
})),
};
}),
);
})(),
isAdmin
? getSetting("registrationOpen").then((v) => v === "true")
: Promise.resolve(false),
]);
return (
<Card>
<Collapsible open={cardOpen} onOpenChange={setCardOpen}>
<CardContent>
<CollapsibleTrigger className="flex w-full cursor-pointer items-center justify-between gap-4">
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<Icon className="size-4 text-primary" />
</div>
<div className="text-left">
<CardTitle>{label}</CardTitle>
<CardDescription>
{connection
? connection.lastEventAt
? `Last event ${timeAgo(connection.lastEventAt)}`
: "Connected — no events yet"
: "Not configured"}
</CardDescription>
</div>
</div>
<IconChevronDown
size={16}
className={`text-muted-foreground transition-transform duration-200 ${cardOpen ? "rotate-180" : ""}`}
/>
</CollapsibleTrigger>
</CardContent>
<CollapsibleContent>
<CardContent className="space-y-3 pt-0">
{connection && (
<div className="flex items-center justify-between rounded-lg bg-muted/30 px-3 py-2">
<span className="text-xs text-muted-foreground">
Webhook {connection.enabled ? "enabled" : "disabled"}
</span>
<Switch
checked={connection.enabled}
onCheckedChange={(checked) => onToggle(provider, checked)}
/>
</div>
)}
{isPlex && (
<div className="flex gap-2.5 rounded-lg border border-primary/20 bg-primary/5 px-3 py-2.5">
<IconInfoCircle
size={14}
className="mt-0.5 shrink-0 text-primary"
/>
<p className="text-xs leading-relaxed text-muted-foreground">
Plex webhooks require an active{" "}
<span className="font-medium text-foreground">Plex Pass</span>{" "}
subscription.
</p>
</div>
)}
<div>
<label
htmlFor={`${provider}-username`}
className="mb-1 block text-xs text-muted-foreground"
>
{label} username
</label>
<div className="flex gap-2">
<Input
id={`${provider}-username`}
placeholder={`Your ${label} username`}
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSave()}
/>
{!connection ? (
<Button
onClick={handleSave}
disabled={saving || !username.trim()}
>
{saving ? "Saving..." : "Connect"}
</Button>
) : (
username.trim() !== connection.mediaServerUsername && (
<Button
onClick={handleSave}
disabled={saving || !username.trim()}
variant="outline"
>
Update
</Button>
)
)}
</div>
</div>
<AnimatePresence>
{webhookUrl && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
className="space-y-3 overflow-hidden"
>
<div>
<label
htmlFor={`${provider}-webhook-url`}
className="mb-1 block text-xs text-muted-foreground"
>
Webhook URL
</label>
<div className="flex gap-2">
<Input
id={`${provider}-webhook-url`}
readOnly
value={webhookUrl}
className="font-mono text-[10px] text-muted-foreground"
/>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="icon"
onClick={handleCopy}
/>
}
>
{copied ? (
<IconCheck size={14} className="text-green-400" />
) : (
<IconCopy size={14} />
)}
</TooltipTrigger>
<TooltipContent>Copy URL</TooltipContent>
</Tooltip>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => onRegenerateToken(provider)}
>
<IconRefresh size={12} />
Regenerate URL
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => onDelete(provider)}
>
<IconTrash size={12} />
Disconnect
</Button>
</div>
</motion.div>
)}
</AnimatePresence>
<Collapsible open={setupOpen} onOpenChange={setSetupOpen}>
<CollapsibleTrigger className="flex w-full items-center gap-1.5 rounded-md py-1 text-xs text-muted-foreground transition-colors hover:text-foreground">
<IconChevronDown
size={12}
className={`transition-transform ${setupOpen ? "rotate-0" : "-rotate-90"}`}
/>
Setup instructions
</CollapsibleTrigger>
<CollapsibleContent>
<div className="mt-2 rounded-lg bg-muted/30 p-3 text-xs leading-relaxed text-muted-foreground">
{isPlex ? (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Open Plex, go to{" "}
<span className="font-medium text-foreground">
Settings &gt; Webhooks
</span>
</li>
<li>
Click{" "}
<span className="font-medium text-foreground">
Add Webhook
</span>{" "}
and paste the URL above
</li>
<li>
Sofa will automatically log movies and episodes when you
finish watching them
</li>
<li>
Make sure the username above matches your Plex account
name
</li>
</ol>
) : (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Install the{" "}
<span className="font-medium text-foreground">
Webhook plugin
</span>{" "}
from Jellyfin&apos;s plugin catalog
</li>
<li>
Go to{" "}
<span className="font-medium text-foreground">
Dashboard &gt; Plugins &gt; Webhook
</span>
</li>
<li>
Add a{" "}
<span className="font-medium text-foreground">
Generic Destination
</span>{" "}
and paste the URL above
</li>
<li>
Enable the{" "}
<span className="font-medium text-foreground">
Playback Stop
</span>{" "}
notification type
</li>
<li>
Make sure the username above matches your Jellyfin
username
</li>
</ol>
)}
</div>
</CollapsibleContent>
</Collapsible>
</CardContent>
</CollapsibleContent>
</Collapsible>
</Card>
);
}
export default function SettingsPage() {
const { data: session, isPending } = useSession();
const router = useRouter();
const [registrationOpen, setRegistrationOpen] = useState(false);
const [loadingSettings, setLoadingSettings] = useState(true);
const [toggling, setToggling] = useState(false);
const [webhookConnections, setWebhookConnections] = useState<
WebhookConnection[]
>([]);
const isAdmin = session?.user?.role === "admin";
const fetchSettings = useCallback(async () => {
try {
const res = await fetch("/api/admin/settings");
if (res.ok) {
const data = await res.json();
setRegistrationOpen(data.registrationOpen);
}
} finally {
setLoadingSettings(false);
}
}, []);
const fetchWebhooks = useCallback(async () => {
try {
const res = await fetch("/api/settings/webhooks");
if (res.ok) {
const data = await res.json();
setWebhookConnections(data.connections);
}
} catch {}
}, []);
useEffect(() => {
if (isPending) return;
fetchWebhooks();
if (session?.user?.role === "admin") {
fetchSettings();
} else {
setLoadingSettings(false);
}
}, [session, isPending, fetchSettings, fetchWebhooks]);
async function handleToggleRegistration(checked: boolean) {
setToggling(true);
try {
const res = await fetch("/api/admin/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ registrationOpen: checked }),
});
if (res.ok) {
setRegistrationOpen(checked);
}
} finally {
setToggling(false);
}
}
async function handleSaveWebhook(
provider: "plex" | "jellyfin",
mediaServerUsername: string,
) {
const res = await fetch("/api/settings/webhooks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ provider, mediaServerUsername }),
});
if (res.ok) await fetchWebhooks();
}
async function handleDeleteWebhook(provider: "plex" | "jellyfin") {
const res = await fetch("/api/settings/webhooks", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ provider }),
});
if (res.ok) await fetchWebhooks();
}
async function handleRegenerateToken(provider: "plex" | "jellyfin") {
const res = await fetch("/api/settings/webhooks/regenerate-token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ provider }),
});
if (res.ok) await fetchWebhooks();
}
async function handleToggleWebhook(
provider: "plex" | "jellyfin",
enabled: boolean,
) {
await fetch("/api/settings/webhooks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
provider,
mediaServerUsername:
webhookConnections.find((c) => c.provider === provider)
?.mediaServerUsername ?? "",
enabled,
}),
});
await fetchWebhooks();
}
if (isPending || loadingSettings) {
return <div className="min-h-[60vh]" />;
}
if (!session?.user) return null;
const memberSince = new Date(session.user.createdAt).toLocaleDateString(
undefined,
{ year: "numeric", month: "long" },
);
const initial = session.user.name?.charAt(0).toUpperCase() ?? "?";
const plexConnection =
webhookConnections.find((c) => c.provider === "plex") ?? null;
const jellyfinConnection =
webhookConnections.find((c) => c.provider === "jellyfin") ?? null;
return (
<motion.div
className="mx-auto max-w-2xl space-y-8"
initial="hidden"
animate="visible"
variants={{
hidden: {},
visible: { transition: { staggerChildren: 0.15 } },
}}
>
<motion.div variants={sectionVariants}>
<div className="flex items-center gap-2">
<IconSettings size={20} className="text-primary" />
<h1 className="font-display text-3xl tracking-tight">Settings</h1>
</div>
<p className="mt-1 text-sm text-muted-foreground">
Manage your account and preferences
</p>
</motion.div>
{/* Account section */}
<motion.div variants={sectionVariants}>
<div className="mb-3 flex items-center gap-2">
<IconUser size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Account
</h2>
</div>
<Card>
<CardContent className="flex items-center gap-4">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-primary/10 font-display text-lg text-primary">
{initial}
</div>
<div className="min-w-0 flex-1">
<CardTitle>{session.user.name}</CardTitle>
<CardDescription>{session.user.email}</CardDescription>
<p className="mt-0.5 text-xs text-muted-foreground/60">
Member since {memberSince}
</p>
</div>
</CardContent>
<CardContent className="pt-0">
<button
type="button"
onClick={async () => {
await signOut();
router.push("/");
router.refresh();
}}
className="inline-flex h-9 items-center gap-2 rounded-lg border border-border/50 px-4 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<IconLogout size={14} />
Sign out
</button>
</CardContent>
</Card>
</motion.div>
{/* Media Servers section */}
<motion.div variants={sectionVariants}>
<div className="mb-3 flex items-center gap-2">
<IconWebhook size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Media Servers
</h2>
</div>
<div className="space-y-3">
<WebhookCard
provider="plex"
connection={plexConnection}
onSave={handleSaveWebhook}
onDelete={handleDeleteWebhook}
onRegenerateToken={handleRegenerateToken}
onToggle={handleToggleWebhook}
/>
<WebhookCard
provider="jellyfin"
connection={jellyfinConnection}
onSave={handleSaveWebhook}
onDelete={handleDeleteWebhook}
onRegenerateToken={handleRegenerateToken}
onToggle={handleToggleWebhook}
/>
</div>
</motion.div>
{/* Administration section — admin only */}
{isAdmin && (
<motion.div variants={sectionVariants}>
<div className="mb-3 flex items-center gap-2">
<IconShieldLock size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Administration
</h2>
<span className="rounded-md bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
Admin
</span>
</div>
<Card className="border-l-2 border-l-primary/30">
<CardContent>
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconUserPlus size={16} className="text-primary" />
</div>
<div>
<CardTitle>Open registration</CardTitle>
<CardDescription>
Allow new users to create accounts. Useful for adding
household members.
</CardDescription>
</div>
</div>
<Switch
checked={registrationOpen}
onCheckedChange={handleToggleRegistration}
disabled={toggling}
/>
</div>
</CardContent>
</Card>
</motion.div>
)}
</motion.div>
<SettingsShell>
<AccountSection
user={{
name: session.user.name,
email: session.user.email,
createdAt: session.user.createdAt.toISOString(),
role: session.user.role ?? undefined,
}}
/>
<IntegrationsSection initialConnections={connections} />
{isAdmin && <ServerSection initialRegistrationOpen={registrationOpen} />}
</SettingsShell>
);
}
-30
View File
@@ -1,30 +0,0 @@
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth/server";
import { getSetting, setSetting } from "@/lib/services/settings";
export async function GET() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (session.user.role !== "admin")
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const registrationOpen = (await getSetting("registrationOpen")) === "true";
return NextResponse.json({ registrationOpen });
}
export async function POST(request: Request) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (session.user.role !== "admin")
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await request.json();
if (typeof body.registrationOpen === "boolean") {
await setSetting("registrationOpen", String(body.registrationOpen));
}
return NextResponse.json({ success: true });
}
@@ -1,43 +0,0 @@
import crypto from "node:crypto";
import { and, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth/server";
import { db } from "@/lib/db/client";
import { webhookConnections } from "@/lib/db/schema";
export async function POST(request: Request) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const body = await request.json();
const { provider } = body;
if (!provider || !["plex", "jellyfin"].includes(provider)) {
return NextResponse.json({ error: "Invalid provider" }, { status: 400 });
}
const newToken = crypto.randomBytes(32).toString("hex");
const connection = await db
.update(webhookConnections)
.set({ token: newToken })
.where(
and(
eq(webhookConnections.userId, session.user.id),
eq(webhookConnections.provider, provider),
),
)
.returning()
.get();
if (!connection) {
return NextResponse.json(
{ error: "Connection not found" },
{ status: 404 },
);
}
return NextResponse.json({ connection });
}
-124
View File
@@ -1,124 +0,0 @@
import crypto from "node:crypto";
import { and, desc, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth/server";
import { db } from "@/lib/db/client";
import { webhookConnections, webhookEventLog } from "@/lib/db/schema";
export async function GET() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const connections = await db
.select()
.from(webhookConnections)
.where(eq(webhookConnections.userId, session.user.id))
.all();
// Fetch recent events for each connection
const connectionsWithEvents = await Promise.all(
connections.map(async (conn) => {
const events = await db
.select()
.from(webhookEventLog)
.where(eq(webhookEventLog.connectionId, conn.id))
.orderBy(desc(webhookEventLog.receivedAt))
.limit(10)
.all();
return { ...conn, recentEvents: events };
}),
);
return NextResponse.json({ connections: connectionsWithEvents });
}
export async function POST(request: Request) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const body = await request.json();
const { provider, mediaServerUsername, enabled } = body;
if (!provider || !["plex", "jellyfin"].includes(provider)) {
return NextResponse.json({ error: "Invalid provider" }, { status: 400 });
}
if (!mediaServerUsername || typeof mediaServerUsername !== "string") {
return NextResponse.json(
{ error: "Media server username is required" },
{ status: 400 },
);
}
// Check if connection already exists
const existing = await db
.select()
.from(webhookConnections)
.where(
and(
eq(webhookConnections.userId, session.user.id),
eq(webhookConnections.provider, provider),
),
)
.get();
if (existing) {
// Update existing — preserve token, update username and enabled
const connection = await db
.update(webhookConnections)
.set({
mediaServerUsername: mediaServerUsername.trim(),
enabled: typeof enabled === "boolean" ? enabled : existing.enabled,
})
.where(eq(webhookConnections.id, existing.id))
.returning()
.get();
return NextResponse.json({ connection });
}
// Create new connection
const token = crypto.randomBytes(32).toString("hex");
const now = new Date();
const connection = await db
.insert(webhookConnections)
.values({
userId: session.user.id,
provider,
token,
mediaServerUsername: mediaServerUsername.trim(),
enabled: true,
createdAt: now,
})
.returning()
.get();
return NextResponse.json({ connection });
}
export async function DELETE(request: Request) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const body = await request.json();
const { provider } = body;
if (!provider || !["plex", "jellyfin"].includes(provider)) {
return NextResponse.json({ error: "Invalid provider" }, { status: 400 });
}
await db
.delete(webhookConnections)
.where(
and(
eq(webhookConnections.userId, session.user.id),
eq(webhookConnections.provider, provider),
),
)
.run();
return NextResponse.json({ ok: true });
}