feat: Einstellungen, Verwaltung und öffentliches Profil

Nach einem Passwortwechsel fliegen alle anderen Geräte raus; ein gesperrtes
Konto wird sofort abgemeldet. Die letzte Administration lässt sich nicht
entmachten, und sich selbst kann niemand sperren.

Das öffentliche Profil zeigt Zahlen und zuletzt Gesehenes — keine Notizen,
keine Watchlist, keine E-Mail-Adresse. Was privat gemeint ist, bleibt privat.
Es braucht die Freigabe des Nutzers und die des Betreibers.
This commit is contained in:
Florian Wilde
2026-09-01 20:25:11 +02:00
parent bb63827bf7
commit a9314acbb4
10 changed files with 1649 additions and 0 deletions
+306
View File
@@ -0,0 +1,306 @@
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import {
checkPasswordStrength,
createApiKey,
destroyAllSessions,
getSessionUser,
hashPassword,
verifyPassword,
} from "@/lib/auth";
import { prisma } from "@/lib/db";
import { setSetting } from "@/lib/settings";
import { sendTestNotification } from "@/lib/notify";
import { importCsv, importTrakt, type ImportSummary } from "@/lib/transfer";
import { runSync } from "@/lib/sync";
/** Server-Aktionen für Einstellungen, Kanäle, API-Schlüssel und Verwaltung. */
export type SettingsResult = { ok: boolean; message?: string; secret?: string };
async function run(
fn: (userId: string) => Promise<{ message?: string; secret?: string } | void>,
): Promise<SettingsResult> {
const user = await getSessionUser();
if (!user) return { ok: false, message: "Bitte melde dich an." };
try {
const result = (await fn(user.id)) ?? {};
revalidatePath("/einstellungen", "layout");
revalidatePath("/", "layout");
return { ok: true, ...result };
} catch (error) {
console.error("Einstellungs-Aktion fehlgeschlagen:", error);
return {
ok: false,
message: error instanceof Error ? error.message : "Das hat nicht geklappt.",
};
}
}
async function requireAdminUser() {
const user = await getSessionUser();
if (!user || user.role !== "ADMIN") {
throw new Error("Dafür fehlen dir die Rechte.");
}
return user;
}
// ---------------------------------------------------------------------------
// Profil
// ---------------------------------------------------------------------------
const profileSchema = z.object({
name: z.string().trim().min(1).max(80),
region: z.string().trim().length(2).toUpperCase(),
publicProfile: z.boolean(),
profileSlug: z
.string()
.trim()
.toLowerCase()
.regex(/^[a-z0-9-]{3,40}$/, "Nur Kleinbuchstaben, Ziffern und Bindestriche, 3 bis 40 Zeichen.")
.nullable(),
notifyNewEpisode: z.boolean(),
notifyRelease: z.boolean(),
notifyAvailability: z.boolean(),
});
export async function updateProfileAction(data: unknown) {
return run(async (userId) => {
const parsed = profileSchema.parse(data);
if (parsed.publicProfile && !parsed.profileSlug) {
throw new Error("Für ein öffentliches Profil braucht es eine Adresse.");
}
if (parsed.profileSlug) {
const taken = await prisma.user.findFirst({
where: { profileSlug: parsed.profileSlug, id: { not: userId } },
select: { id: true },
});
if (taken) throw new Error("Diese Profiladresse ist schon vergeben.");
}
await prisma.user.update({ where: { id: userId }, data: parsed });
return { message: "Gespeichert" };
});
}
const passwordSchema = z.object({
current: z.string().min(1),
next: z.string().min(1),
repeat: z.string().min(1),
});
export async function changePasswordAction(data: unknown) {
return run(async (userId) => {
const parsed = passwordSchema.parse(data);
if (parsed.next !== parsed.repeat) throw new Error("Die neuen Passwörter stimmen nicht überein.");
const weak = checkPasswordStrength(parsed.next);
if (weak) throw new Error(weak);
const user = await prisma.user.findUniqueOrThrow({
where: { id: userId },
select: { passwordHash: true },
});
if (!user.passwordHash) {
throw new Error("Dieses Konto meldet sich über SSO an und hat kein Passwort.");
}
if (!(await verifyPassword(parsed.current, user.passwordHash))) {
throw new Error("Das bisherige Passwort stimmt nicht.");
}
await prisma.user.update({
where: { id: userId },
data: { passwordHash: await hashPassword(parsed.next) },
});
// Nach einem Passwortwechsel fliegen alle anderen Geräte raus.
await destroyAllSessions(userId);
return { message: "Passwort geändert — bitte neu anmelden." };
});
}
// ---------------------------------------------------------------------------
// API-Schlüssel
// ---------------------------------------------------------------------------
export async function createApiKeyAction(name: string) {
return run(async (userId) => {
const clean = z.string().trim().min(1).max(60).parse(name);
const { plain } = await createApiKey(userId, clean);
// Der Klartext existiert nur hier — danach steht in der Datenbank nur der Hash.
return { message: "Schlüssel angelegt", secret: plain };
});
}
export async function revokeApiKeyAction(keyId: string) {
return run(async (userId) => {
await prisma.apiKey.updateMany({
where: { id: keyId, userId },
data: { revokedAt: new Date() },
});
return { message: "Schlüssel zurückgezogen" };
});
}
// ---------------------------------------------------------------------------
// Benachrichtigungskanäle
// ---------------------------------------------------------------------------
const channelSchema = z.object({
kind: z.enum(["EMAIL", "NTFY", "GOTIFY", "WEBHOOK"]),
name: z.string().trim().min(1).max(60),
config: z.record(z.string(), z.string().max(500)).default({}),
});
export async function saveChannelAction(data: unknown, channelId?: string) {
return run(async (userId) => {
const parsed = channelSchema.parse(data);
if (channelId) {
await prisma.notificationChannel.updateMany({
where: { id: channelId, userId },
data: { kind: parsed.kind, name: parsed.name, config: parsed.config },
});
return { message: "Kanal gespeichert" };
}
await prisma.notificationChannel.create({
data: { userId, kind: parsed.kind, name: parsed.name, config: parsed.config },
});
return { message: "Kanal angelegt" };
});
}
export async function toggleChannelAction(channelId: string, enabled: boolean) {
return run(async (userId) => {
await prisma.notificationChannel.updateMany({
where: { id: channelId, userId },
data: { enabled },
});
return { message: enabled ? "Kanal aktiv" : "Kanal ruht" };
});
}
export async function deleteChannelAction(channelId: string) {
return run(async (userId) => {
await prisma.notificationChannel.deleteMany({ where: { id: channelId, userId } });
return { message: "Kanal entfernt" };
});
}
export async function testChannelAction(channelId: string) {
return run(async (userId) => {
await sendTestNotification(userId, channelId);
return { message: "Testnachricht verschickt" };
});
}
// ---------------------------------------------------------------------------
// Import
// ---------------------------------------------------------------------------
export type ImportResult = { ok: boolean; message?: string; summary?: ImportSummary };
export async function importDataAction(
format: "csv" | "trakt",
content: string,
): Promise<ImportResult> {
const user = await getSessionUser();
if (!user) return { ok: false, message: "Bitte melde dich an." };
if (content.length > 8_000_000) {
return { ok: false, message: "Die Datei ist zu groß (mehr als 8 MB)." };
}
try {
const summary = format === "csv" ? await importCsv(user.id, content) : await importTrakt(user.id, content);
revalidatePath("/bibliothek", "layout");
revalidatePath("/", "layout");
return {
ok: true,
message: `${summary.added} aufgenommen, ${summary.skipped} übersprungen`,
summary,
};
} catch (error) {
console.error("Import fehlgeschlagen:", error);
return { ok: false, message: error instanceof Error ? error.message : "Import fehlgeschlagen." };
}
}
// ---------------------------------------------------------------------------
// Verwaltung
// ---------------------------------------------------------------------------
export async function setRegistrationAction(enabled: boolean) {
return run(async () => {
await requireAdminUser();
await setSetting("registrationEnabled", enabled);
return { message: enabled ? "Registrierung offen" : "Registrierung geschlossen" };
});
}
export async function setInstanceNameAction(name: string) {
return run(async () => {
await requireAdminUser();
await setSetting("instanceName", z.string().trim().min(1).max(60).parse(name));
return { message: "Name gespeichert" };
});
}
export async function setPublicProfilesAction(enabled: boolean) {
return run(async () => {
await requireAdminUser();
await setSetting("publicProfilesEnabled", enabled);
return { message: enabled ? "Öffentliche Profile erlaubt" : "Öffentliche Profile abgeschaltet" };
});
}
export async function setUserActiveAction(targetId: string, active: boolean) {
return run(async (userId) => {
await requireAdminUser();
if (targetId === userId) throw new Error("Dich selbst kannst du nicht sperren.");
await prisma.user.update({ where: { id: targetId }, data: { isActive: active } });
if (!active) await destroyAllSessions(targetId);
revalidatePath("/verwaltung", "layout");
return { message: active ? "Konto freigegeben" : "Konto gesperrt" };
});
}
export async function setUserRoleAction(targetId: string, role: "ADMIN" | "USER") {
return run(async (userId) => {
await requireAdminUser();
if (targetId === userId) throw new Error("Deine eigene Rolle kannst du nicht ändern.");
if (role === "USER") {
const admins = await prisma.user.count({ where: { role: "ADMIN", isActive: true } });
if (admins <= 1) throw new Error("Es muss mindestens eine Administration geben.");
}
await prisma.user.update({ where: { id: targetId }, data: { role } });
revalidatePath("/verwaltung", "layout");
return { message: role === "ADMIN" ? "Zur Administration ernannt" : "Rechte entzogen" };
});
}
export async function runSyncAction() {
return run(async () => {
await requireAdminUser();
const stats = await runSync({ limit: 40 });
revalidatePath("/verwaltung", "layout");
return {
message:
stats.errors.length === 0
? `${stats.titlesUpdated} Titel aufgefrischt, ${stats.newEpisodes} neue Episoden, ${stats.notificationsSent} Benachrichtigungen`
: `Mit ${stats.errors.length} Fehlern beendet: ${stats.errors[0]}`,
};
});
}
+52
View File
@@ -0,0 +1,52 @@
import type { Metadata } from "next";
import { requireUser } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { env } from "@/lib/env";
import { ApiKeys } from "@/components/settings/Forms";
export const metadata: Metadata = { title: "API-Schlüssel" };
export default async function ApiPage() {
const user = await requireUser("/einstellungen/api");
const keys = await prisma.apiKey.findMany({
where: { userId: user.id, revokedAt: null },
orderBy: { createdAt: "desc" },
select: { id: true, name: true, prefix: true, lastUsedAt: true, createdAt: true },
});
const example = [
'curl -H "Authorization: Bearer <dein-schlüssel>" \\',
` ${env.appUrl}/api/v1/bibliothek?status=WATCHING`,
].join("\n");
return (
<div className="space-y-6">
<section className="fl-card p-5">
<h2 className="text-lg font-semibold">API-Schlüssel</h2>
<p className="mb-4 mt-1 text-sm text-[var(--fl-muted)]">
Für Skripte und eigene Anwendungen. Ein Schlüssel hat dieselben Rechte wie dein Konto —
gib ihn nicht weiter und zieh ihn zurück, sobald du ihn nicht mehr brauchst.
</p>
<ApiKeys keys={keys} />
</section>
<section className="fl-card p-5">
<h2 className="mb-3 text-lg font-semibold">So wird er benutzt</h2>
<pre className="overflow-x-auto rounded-xl bg-[var(--fl-surface-2)] p-3 text-xs leading-relaxed">
{example}
</pre>
<p className="mt-3 text-sm text-[var(--fl-muted)]">
Die vollständige Beschreibung steht in{" "}
<a
href="/api/v1/openapi.json"
className="text-[var(--fl-accent)] underline-offset-4 hover:underline"
>
openapi.json
</a>{" "}
und in <code>docs/API.md</code> im Repository.
</p>
</section>
</div>
);
}
@@ -0,0 +1,63 @@
import type { Metadata } from "next";
import { requireUser } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { env } from "@/lib/env";
import { ChannelList } from "@/components/settings/Forms";
export const metadata: Metadata = { title: "Benachrichtigungen" };
export default async function NotificationsPage() {
const user = await requireUser("/einstellungen/benachrichtigungen");
const [channels, recent] = await Promise.all([
prisma.notificationChannel.findMany({
where: { userId: user.id },
orderBy: { createdAt: "asc" },
}),
prisma.notificationLog.findMany({
where: { userId: user.id },
orderBy: { sentAt: "desc" },
take: 10,
}),
]);
return (
<div className="space-y-6">
<section className="fl-card p-5">
<h2 className="text-lg font-semibold">Kanäle</h2>
<p className="mb-4 mt-1 text-sm text-[var(--fl-muted)]">
Wohin Flimmer dir Bescheid gibt. Was gemeldet wird, stellst du im Profil ein.
</p>
<ChannelList
channels={channels.map((channel) => ({
id: channel.id,
kind: channel.kind,
name: channel.name,
config: (channel.config ?? {}) as Record<string, string>,
enabled: channel.enabled,
}))}
smtpReady={env.smtp.isConfigured}
/>
</section>
<section className="fl-card p-5">
<h2 className="mb-4 text-lg font-semibold">Zuletzt verschickt</h2>
{recent.length === 0 ? (
<p className="text-sm text-[var(--fl-faint)]">Noch nichts verschickt.</p>
) : (
<ul className="divide-y divide-[var(--fl-border)] text-sm">
{recent.map((entry) => (
<li key={entry.id} className="py-2.5">
<p className="font-medium">{entry.subject}</p>
<p className="text-xs text-[var(--fl-faint)]">
{entry.sentAt.toLocaleString("de-DE")}
{entry.ok ? "" : ` · fehlgeschlagen: ${entry.error ?? "unbekannt"}`}
</p>
</li>
))}
</ul>
)}
</section>
</div>
);
}
+46
View File
@@ -0,0 +1,46 @@
import type { Metadata } from "next";
import { requireUser } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { ImportForm } from "@/components/settings/Forms";
export const metadata: Metadata = { title: "Import und Export" };
export default async function DataPage() {
const user = await requireUser("/einstellungen/daten");
const [entries, watches] = await Promise.all([
prisma.libraryEntry.count({ where: { userId: user.id, deletedAt: null } }),
prisma.watch.count({ where: { userId: user.id } }),
]);
return (
<div className="space-y-6">
<section className="fl-card p-5">
<h2 className="text-lg font-semibold">Import</h2>
<p className="mb-4 mt-1 text-sm text-[var(--fl-muted)]">
Bringt Titel aus einem anderen Werkzeug mit.
</p>
<ImportForm />
</section>
<section className="fl-card p-5">
<h2 className="text-lg font-semibold">Export</h2>
<p className="mb-4 mt-1 text-sm text-[var(--fl-muted)]">
Deine Daten gehören dir: {entries} Einträge und {watches} Sichtungen zum Mitnehmen.
</p>
<div className="flex flex-wrap gap-2">
<a href="/api/v1/export?format=json" className="fl-btn fl-btn-primary" download>
Als JSON
</a>
<a href="/api/v1/export?format=csv" className="fl-btn fl-btn-ghost" download>
Als CSV
</a>
</div>
<p className="mt-3 text-xs text-[var(--fl-faint)]">
JSON enthält zusätzlich alle Sichtungen und Universen, CSV ist die schlanke Tabellenform
für Tabellenkalkulationen.
</p>
</section>
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { requireUser } from "@/lib/auth";
import { getSettings } from "@/lib/settings";
import { AppShell } from "@/components/AppShell";
import { SettingsNav } from "@/components/settings/SettingsNav";
/** Rahmen der Einstellungen: Seitennavigation links, Inhalt rechts. */
export default async function SettingsLayout({ children }: { children: React.ReactNode }) {
const user = await requireUser("/einstellungen");
const settings = await getSettings();
return (
<AppShell user={user} instanceName={settings.instanceName}>
<header className="mb-6">
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">Einstellungen</h1>
</header>
<div className="grid gap-6 lg:grid-cols-[14rem_minmax(0,1fr)]">
<SettingsNav isAdmin={user.role === "ADMIN"} />
<div className="min-w-0">{children}</div>
</div>
</AppShell>
);
}
+50
View File
@@ -0,0 +1,50 @@
import type { Metadata } from "next";
import { requireUser } from "@/lib/auth";
import { getSettings } from "@/lib/settings";
import { prisma } from "@/lib/db";
import { PasswordForm, ProfileForm } from "@/components/settings/Forms";
import pkg from "../../../package.json";
export const metadata: Metadata = { title: "Einstellungen" };
export default async function SettingsPage() {
const session = await requireUser("/einstellungen");
const settings = await getSettings();
const user = await prisma.user.findUniqueOrThrow({
where: { id: session.id },
select: {
name: true,
email: true,
region: true,
publicProfile: true,
profileSlug: true,
notifyNewEpisode: true,
notifyRelease: true,
notifyAvailability: true,
passwordHash: true,
},
});
const { passwordHash, ...profile } = user;
return (
<div className="space-y-6">
<section className="fl-card p-5">
<h2 className="mb-4 text-lg font-semibold">Profil</h2>
<ProfileForm user={profile} publicProfilesEnabled={settings.publicProfilesEnabled} />
</section>
{passwordHash && (
<section className="fl-card p-5">
<h2 className="mb-4 text-lg font-semibold">Passwort</h2>
<PasswordForm />
</section>
)}
<p className="text-xs text-[var(--fl-faint)]">
Flimmer {pkg.version} · Instanz {settings.instanceName}
</p>
</div>
);
}
+171
View File
@@ -0,0 +1,171 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { prisma } from "@/lib/db";
import { getSettings } from "@/lib/settings";
import { getMostWatched, getTopRated, getTotals } from "@/lib/stats";
import { formatMinutes, formatRelative } from "@/lib/labels";
import { FlimmerLogo } from "@/components/brand/FlimmerLogo";
import { Poster } from "@/components/Poster";
import { ThemeToggle } from "@/components/ThemeToggle";
type Params = Promise<{ slug: string }>;
/**
* Öffentliche Profilseite.
*
* Zeigt Zahlen und zuletzt Gesehenes — **keine** Notizen, keine Watchlist,
* keine E-Mail-Adresse. Was privat gemeint ist, bleibt privat. Die Seite ist
* nur erreichbar, wenn der Nutzer sie freigeschaltet hat *und* der Betreiber
* öffentliche Profile instanzweit erlaubt.
*/
export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
const { slug } = await params;
const user = await prisma.user.findFirst({
where: { profileSlug: slug, publicProfile: true, isActive: true },
select: { name: true },
});
return user ? { title: `${user.name} · Profil` } : { title: "Profil" };
}
export default async function PublicProfilePage({ params }: { params: Params }) {
const { slug } = await params;
const settings = await getSettings();
if (!settings.publicProfilesEnabled) notFound();
const user = await prisma.user.findFirst({
where: { profileSlug: slug, publicProfile: true, isActive: true },
select: { id: true, name: true, createdAt: true },
});
if (!user) notFound();
const [totals, mostWatched, topRated, recent] = await Promise.all([
getTotals(user.id),
getMostWatched(user.id, 6),
getTopRated(user.id, 6),
prisma.watch.findMany({
where: { userId: user.id },
orderBy: { watchedAt: "desc" },
take: 8,
distinct: ["titleId"],
include: {
title: { select: { id: true, title: true, posterPath: true, type: true } },
episode: { select: { seasonNumber: true, episodeNumber: true } },
},
}),
]);
return (
<div className="flex min-h-dvh flex-col">
<div className="mx-auto flex w-full max-w-5xl items-center justify-between px-4 py-4 sm:px-6">
<Link href="/" aria-label="Flimmer">
<FlimmerLogo />
</Link>
<ThemeToggle />
</div>
<main id="inhalt" className="mx-auto w-full max-w-5xl flex-1 px-4 py-6 sm:px-6">
<header className="fl-card relative overflow-hidden p-6 sm:p-8">
<div
aria-hidden
className="pointer-events-none absolute -right-20 -top-28 h-64 w-64 rounded-full opacity-25 blur-3xl"
style={{ backgroundImage: "var(--fl-gradient)" }}
/>
<div className="relative">
<p className="text-xs font-semibold uppercase tracking-wide text-[var(--fl-faint)]">
Öffentliches Profil
</p>
<h1 className="mt-1 text-3xl font-semibold tracking-tight">{user.name}</h1>
<p className="mt-1 text-sm text-[var(--fl-muted)]">
Dabei seit {user.createdAt.toLocaleDateString("de-DE", { month: "long", year: "numeric" })}
</p>
<dl className="mt-6 grid grid-cols-2 gap-4 sm:grid-cols-4">
<Stat label="Schauzeit" value={formatMinutes(totals.minutes)} />
<Stat label="Episoden" value={totals.episodes.toLocaleString("de-DE")} />
<Stat label="Filme" value={totals.movies.toLocaleString("de-DE")} />
<Stat label="Abgeschlossen" value={totals.titlesCompleted.toLocaleString("de-DE")} />
</dl>
</div>
</header>
{recent.length > 0 && (
<section className="mt-6">
<h2 className="mb-3 text-lg font-semibold">Zuletzt gesehen</h2>
<ul className="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-8">
{recent.map((watch) => (
<li key={watch.id}>
<Poster path={watch.title.posterPath} alt={watch.title.title} size="w185" />
<p className="mt-1.5 line-clamp-2 text-xs font-medium leading-snug">
{watch.title.title}
</p>
<p className="text-xs text-[var(--fl-faint)]">
{formatRelative(watch.watchedAt)}
</p>
</li>
))}
</ul>
</section>
)}
<div className="mt-6 grid gap-6 sm:grid-cols-2">
<TitleList heading="Die meiste Zeit" items={mostWatched} showMinutes />
<TitleList heading="Bestbewertet" items={topRated} />
</div>
{totals.minutes === 0 && (
<p className="fl-card mt-6 p-6 text-center text-sm text-[var(--fl-muted)]">
Hier ist noch nichts zu sehen.
</p>
)}
</main>
<footer className="mx-auto w-full max-w-5xl px-4 pb-10 pt-6 text-center text-xs text-[var(--fl-faint)] sm:px-6">
Erstellt mit Flimmer · Metadaten von TMDB
</footer>
</div>
);
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div>
<dt className="text-xs uppercase tracking-wide text-[var(--fl-faint)]">{label}</dt>
<dd className="mt-0.5 text-lg font-semibold tabular-nums">{value}</dd>
</div>
);
}
function TitleList({
heading,
items,
showMinutes = false,
}: {
heading: string;
items: { titleId: string; title: string; posterPath: string | null; rating: number | null; minutes: number }[];
showMinutes?: boolean;
}) {
if (items.length === 0) return null;
return (
<section className="fl-card p-5">
<h2 className="mb-4 text-lg font-semibold">{heading}</h2>
<ol className="space-y-3">
{items.map((item, index) => (
<li key={item.titleId} className="flex items-center gap-3">
<span className="w-4 shrink-0 text-right font-mono text-sm text-[var(--fl-faint)]">
{index + 1}
</span>
<span className="w-10 shrink-0">
<Poster path={item.posterPath} alt={item.title} size="w154" />
</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{item.title}</span>
<span className="shrink-0 text-sm tabular-nums text-[var(--fl-muted)]">
{showMinutes ? formatMinutes(item.minutes) : item.rating ? `${item.rating}/10` : "—"}
</span>
</li>
))}
</ol>
</section>
);
}
+129
View File
@@ -0,0 +1,129 @@
import type { Metadata } from "next";
import { requireAdmin } from "@/lib/auth";
import { getSettings } from "@/lib/settings";
import { prisma } from "@/lib/db";
import { env } from "@/lib/env";
import { AppShell } from "@/components/AppShell";
import { AdminSettings, UserRow } from "@/components/settings/Forms";
import { formatRelative } from "@/lib/labels";
export const metadata: Metadata = { title: "Verwaltung" };
export default async function AdminPage() {
const admin = await requireAdmin();
const settings = await getSettings();
const [users, lastRun, catalog] = await Promise.all([
prisma.user.findMany({
orderBy: { createdAt: "asc" },
select: {
id: true,
name: true,
email: true,
role: true,
isActive: true,
_count: { select: { entries: true } },
},
}),
prisma.syncRun.findFirst({ orderBy: { startedAt: "desc" } }),
Promise.all([
prisma.title.count(),
prisma.episode.count(),
prisma.watch.count(),
]),
]);
const [titleCount, episodeCount, watchCount] = catalog;
return (
<AppShell user={admin} instanceName={settings.instanceName}>
<header className="mb-6">
<h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">Verwaltung</h1>
<p className="mt-1 text-sm text-[var(--fl-muted)]">
Einstellungen der Instanz, Konten und Hintergrundlauf.
</p>
</header>
<div className="grid gap-6 lg:grid-cols-2">
<section className="fl-card p-5">
<h2 className="mb-4 text-lg font-semibold">Instanz</h2>
<AdminSettings
registrationEnabled={settings.registrationEnabled}
publicProfilesEnabled={settings.publicProfilesEnabled}
instanceName={settings.instanceName}
/>
</section>
<div className="space-y-6">
<section className="fl-card p-5">
<h2 className="mb-4 text-lg font-semibold">Zustand</h2>
<dl className="grid grid-cols-2 gap-4 text-sm">
<Fact label="Konten" value={String(users.length)} />
<Fact label="Titel im Katalog" value={titleCount.toLocaleString("de-DE")} />
<Fact label="Episoden" value={episodeCount.toLocaleString("de-DE")} />
<Fact label="Sichtungen" value={watchCount.toLocaleString("de-DE")} />
<Fact
label="TMDB"
value={env.tmdb.isConfigured ? "eingerichtet" : "kein Schlüssel"}
/>
<Fact label="SMTP" value={env.smtp.isConfigured ? "eingerichtet" : "nicht gesetzt"} />
<Fact
label="Zeitplan"
value={
env.scheduler.enabled
? `täglich ${String(env.scheduler.hour).padStart(2, "0")}:05 Uhr`
: "abgeschaltet"
}
/>
<Fact label="OIDC" value={env.oidc.isConfigured ? "eingerichtet" : "nicht gesetzt"} />
</dl>
</section>
<section className="fl-card p-5">
<h2 className="mb-3 text-lg font-semibold">Letzter Abgleich</h2>
{lastRun ? (
<p className="text-sm text-[var(--fl-muted)]">
{formatRelative(lastRun.startedAt)} ·{" "}
<span style={{ color: lastRun.ok ? "var(--fl-success)" : "var(--fl-danger)" }}>
{lastRun.ok ? "erfolgreich" : "mit Fehlern"}
</span>
{lastRun.message ? ` · ${lastRun.message}` : ""}
</p>
) : (
<p className="text-sm text-[var(--fl-faint)]">Noch kein Abgleich gelaufen.</p>
)}
</section>
</div>
</div>
<section className="fl-card mt-6 p-5">
<h2 className="mb-2 text-lg font-semibold">Konten</h2>
<ul className="divide-y divide-[var(--fl-border)]">
{users.map((user) => (
<UserRow
key={user.id}
user={{
id: user.id,
name: user.name,
email: user.email,
role: user.role,
isActive: user.isActive,
entries: user._count.entries,
}}
isSelf={user.id === admin.id}
/>
))}
</ul>
</section>
</AppShell>
);
}
function Fact({ label, value }: { label: string; value: string }) {
return (
<div>
<dt className="text-xs uppercase tracking-wide text-[var(--fl-faint)]">{label}</dt>
<dd className="mt-0.5 font-medium">{value}</dd>
</div>
);
}