Files
shared/media-webui/src/lib/features/ModeratorWorkspace.svelte
T
Gabriel20xx 7b5a4e6c2c Merge media-webui/media-backend into the general shared component/backend system
Extracts a new backend/authproxy package for the AuthGuard-proxy helper
functions (session cookie handling, input normalization, error
translation) that Bitmagnet/GameStream/media-backend/AutoCode/
CollabTable/PubliSafe/SimpleCollection/SyncServer/UnraidMonitor/
OutdoorGames were each independently reimplementing, and repoints all
of them onto it.

Extends packages/web-ui's Button/Badge with the variants media-webui
needed (outline, icon size, primary badge) and promotes EmptyState/
SectionTitle/Metric/StatusWidget/StatusDialog into the shared library,
then migrates media-webui off its own diverged ui/{button,card,badge,
metric} components and local duplicates of the promoted components
onto @gabriel20xx/web-ui, so media-webui is a proper consumer of the
same design system every other project already uses instead of a
parallel fork.

Also removes the dead `desktop`/MediaDesktop service variant from
media-backend and media-webui (MediaDesktop is an Electron client that
never actually runs this stack).
2026-09-03 00:14:01 +02:00

497 lines
21 KiB
Svelte

<script lang="ts">
import { BarChart3, Check, Pencil, ShieldCheck, Trash2, UserCheck, Users } from '@lucide/svelte'
import { onMount } from 'svelte'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post, put } from '$lib/api'
interface UserRow {
id: string | number
email?: string
username?: string
role?: string
disabled?: boolean
mfaEnabled?: boolean
createdAt?: string
}
interface UserForm {
email: string
username: string
password: string
role: string
}
interface MediaRow {
id: string | number
mediaKey?: string
title?: string
active?: boolean
source?: string
mediaType?: string
createdAt?: string
generatorUsername?: string
}
let { panel = 'dashboard' }: { panel?: string } = $props()
let users = $state<UserRow[]>([])
let media = $state<MediaRow[]>([])
let selectedUsers = $state<string[]>([])
let selectedMedia = $state<string[]>([])
let search = $state('')
let loading = $state(true)
let error = $state('')
let editingUser = $state<UserRow | null>(null)
let savingUser = $state(false)
let createForm = $state<UserForm>({ email: '', username: '', password: '', role: 'user' })
let editForm = $state<UserForm>({ email: '', username: '', password: '', role: 'user' })
async function load() {
loading = true
error = ''
try {
const [usersResponse, mediaResponse] = await Promise.all([
get<{ users?: UserRow[] }>(`/api/admin/users?search=${encodeURIComponent(search)}`).catch(() => ({
users: [],
})),
get<{ media?: MediaRow[] }>(`/api/admin/media?search=${encodeURIComponent(search)}`).catch(() => ({
media: [],
})),
])
users = Array.isArray(usersResponse.users) ? usersResponse.users : []
media = Array.isArray(mediaResponse.media) ? mediaResponse.media : []
} catch (reason) {
error = reason instanceof Error ? reason.message : 'Unable to load moderation data.'
} finally {
loading = false
}
}
function toggle(list: string[], id: string, kind: 'users' | 'media') {
const next = list.includes(id) ? list.filter((value) => value !== id) : [...list, id]
if (kind === 'users') selectedUsers = next
else selectedMedia = next
}
async function userAction(action: string) {
if (!selectedUsers.length) return
try {
await post('/api/admin/users/actions', { action, ids: selectedUsers })
notify.success(`${action} applied to ${selectedUsers.length} user(s).`)
selectedUsers = []
await load()
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'User action failed.')
}
}
async function createUser() {
if (!createForm.email.trim() || !createForm.password) {
notify.error('Email and password are required.')
return
}
if (createForm.password.length < 8) {
notify.error('Password must be at least 8 characters.')
return
}
savingUser = true
try {
await post('/api/admin/users', {
email: createForm.email.trim(),
username: createForm.username.trim(),
password: createForm.password,
role: createForm.role,
})
notify.success('User created.')
createForm = { email: '', username: '', password: '', role: 'user' }
await load()
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to create user.')
} finally {
savingUser = false
}
}
function openUserEditor(user: UserRow) {
editingUser = user
editForm = {
email: user.email || '',
username: user.username || '',
password: '',
role: user.role || 'user',
}
}
function closeUserEditor() {
if (!savingUser) editingUser = null
}
async function saveUser() {
if (!editingUser) return
if (!editForm.email.trim()) {
notify.error('Email is required.')
return
}
if (editForm.password && editForm.password.length < 8) {
notify.error('Password must be at least 8 characters.')
return
}
savingUser = true
try {
const body: Record<string, string> = {
email: editForm.email.trim(),
username: editForm.username.trim(),
role: editForm.role,
}
if (editForm.password) body.password = editForm.password
await put(`/api/admin/users/${encodeURIComponent(String(editingUser.id))}`, body)
notify.success('User updated.')
editingUser = null
await load()
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Unable to update user.')
} finally {
savingUser = false
}
}
async function mediaAction(action: string) {
if (!selectedMedia.length) return
try {
await post('/api/admin/media/actions', { action, ids: selectedMedia })
notify.success(`${action} applied to ${selectedMedia.length} media item(s).`)
selectedMedia = []
await load()
} catch (reason) {
notify.error(reason instanceof Error ? reason.message : 'Media action failed.')
}
}
onMount(() => void load())
</script>
<div class="space-y-4">
{#if error}<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
{error}
</div>{/if}
{#if panel === 'dashboard'}
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Metric label="Users" value={users.length} detail="Loaded from admin catalog" /><Metric
label="Active users"
value={users.filter((user) => !user.disabled).length}
variant="success"
/><Metric label="Media records" value={media.length} detail="Catalog window" /><Metric
label="Flagged / inactive"
value={media.filter((item) => item.active === false).length}
variant="warning"
/>
</div>
<div class="grid gap-4 lg:grid-cols-2">
<Card class="space-y-4"
><SectionTitle title="Access posture" description="Account state at a glance." />
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-4">
<ShieldCheck class="size-6 text-success" />
<div>
<p class="text-sm font-medium text-fg">Moderation controls available</p>
<p class="mt-1 text-xs text-muted-fg">
Use Users and Media for scoped actions; every write remains protected by the existing admin API.
</p>
</div>
</div></Card
><Card class="space-y-4"
><SectionTitle title="Next actions" />
<div class="grid gap-3 sm:grid-cols-2">
<a href="/users" class="rounded-md border border-border bg-bg p-4 transition hover:border-primary/60"
><Users class="size-5 text-primary" />
<p class="mt-3 text-sm font-medium text-fg">Review users</p>
<p class="mt-1 text-xs text-muted-fg">Disable, enable, reset, or change roles.</p></a
><a href="/media" class="rounded-md border border-border bg-bg p-4 transition hover:border-primary/60"
><BarChart3 class="size-5 text-primary" />
<p class="mt-3 text-sm font-medium text-fg">Moderate media</p>
<p class="mt-1 text-xs text-muted-fg">Hide, restore, delete, or rename catalog items.</p></a
>
</div></Card
>
</div>
{:else if panel === 'users'}
<Card class="space-y-5"
><div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<SectionTitle title="Users" description="Create accounts, edit account details, or apply a bulk action." />
<div class="flex gap-2">
<input
bind:value={search}
onkeydown={(event) => event.key === 'Enter' && void load()}
placeholder="Search users"
class="h-9 w-48 rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/><Button size="sm" variant="secondary" onclick={() => void load()}>Search</Button>
</div>
</div>
<div class="flex flex-wrap gap-2 border-y border-border py-3">
<Badge variant="primary">{selectedUsers.length} selected</Badge><Button
size="sm"
variant="secondary"
disabled={!selectedUsers.length}
onclick={() => void userAction('enable')}><UserCheck class="size-4" />Enable</Button
><Button
size="sm"
variant="secondary"
disabled={!selectedUsers.length}
onclick={() => void userAction('disable')}>Disable</Button
><Button size="sm" variant="danger" disabled={!selectedUsers.length} onclick={() => void userAction('delete')}
><Trash2 class="size-4" />Delete</Button
>
</div>
<form
class="grid gap-3 rounded-md border border-border bg-bg p-4 sm:grid-cols-2 lg:grid-cols-5"
onsubmit={(event) => {
event.preventDefault()
void createUser()
}}
>
<div class="sm:col-span-2 lg:col-span-1">
<label for="new-user-email" class="mb-1 block text-xs font-medium text-muted-fg">Email</label>
<input
id="new-user-email"
type="email"
required
bind:value={createForm.email}
autocomplete="email"
placeholder="user@example.com"
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
<div>
<label for="new-user-username" class="mb-1 block text-xs font-medium text-muted-fg">Username</label>
<input
id="new-user-username"
bind:value={createForm.username}
autocomplete="username"
placeholder="Optional"
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
<div>
<label for="new-user-password" class="mb-1 block text-xs font-medium text-muted-fg">Password</label>
<input
id="new-user-password"
type="password"
required
minlength="8"
bind:value={createForm.password}
autocomplete="new-password"
placeholder="At least 8 characters"
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
<div>
<label for="new-user-role" class="mb-1 block text-xs font-medium text-muted-fg">Role</label>
<select
id="new-user-role"
bind:value={createForm.role}
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<option value="user">user</option>
<option value="moderator">moderator</option>
<option value="admin">admin</option>
</select>
</div>
<div class="flex items-end">
<Button type="submit" class="w-full" disabled={savingUser}>Create user</Button>
</div>
</form>
{#if loading}<p class="py-8 text-center text-sm text-muted-fg">
Loading users…
</p>{:else if users.length === 0}<EmptyState
title="No users found"
message="Try a different search or create a user above."
/>{:else}<div class="overflow-x-auto">
<table class="w-full min-w-[760px] text-left">
<thead
><tr class="border-b border-border text-xs uppercase tracking-wider text-muted-fg"
><th class="w-10 py-3"></th><th class="py-3">User</th><th class="py-3">Role</th><th class="py-3"
>Status</th
><th class="py-3">Security</th><th class="py-3 text-right">Actions</th></tr
></thead
><tbody class="divide-y divide-border"
>{#each users as user (user.id)}<tr class="hover:bg-surface-hover/50"
><td class="py-3"
><input
type="checkbox"
checked={selectedUsers.includes(String(user.id))}
onchange={() => toggle(selectedUsers, String(user.id), 'users')}
class="size-4 accent-primary"
/></td
><td class="py-3"
><p class="text-sm font-medium text-fg">{user.username || user.email || `User ${user.id}`}</p>
<p class="mt-1 text-xs text-muted-fg">{user.email || 'No email'}</p></td
><td class="py-3"
><Badge variant={user.role === 'admin' || user.role === 'superadmin' ? 'primary' : 'default'}
>{user.role || 'user'}</Badge
></td
><td class="py-3"
><Badge variant={user.disabled ? 'danger' : 'success'}>{user.disabled ? 'Disabled' : 'Active'}</Badge
></td
><td class="py-3 text-xs text-muted-fg">{user.mfaEnabled ? 'MFA enabled' : 'MFA not enabled'}</td><td
class="py-3 text-right"
>
<Button size="sm" variant="secondary" onclick={() => openUserEditor(user)}
><Pencil class="size-4" />Edit</Button
></td
></tr
>{/each}</tbody
>
</table>
</div>{/if}</Card
>
{#if editingUser}
<div
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
role="presentation"
onclick={(event) => event.target === event.currentTarget && closeUserEditor()}
>
<div
role="dialog"
aria-modal="true"
aria-labelledby="edit-user-title"
class="w-full max-w-xl rounded-lg border border-border bg-surface p-5 shadow-xl"
>
<div class="flex items-start justify-between gap-4">
<div>
<h2 id="edit-user-title" class="text-lg font-semibold text-fg">Edit user</h2>
<p class="mt-1 text-xs text-muted-fg">
Update the account details for {editingUser.username || editingUser.email || `User ${editingUser.id}`}.
</p>
</div>
<Button variant="ghost" size="sm" onclick={closeUserEditor} disabled={savingUser}>Close</Button>
</div>
<form
class="mt-5 space-y-4"
onsubmit={(event) => {
event.preventDefault()
void saveUser()
}}
>
<div class="grid gap-4 sm:grid-cols-2">
<div>
<label for="edit-user-email" class="mb-1 block text-xs font-medium text-muted-fg">Email</label>
<input
id="edit-user-email"
type="email"
required
bind:value={editForm.email}
autocomplete="email"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
<div>
<label for="edit-user-username" class="mb-1 block text-xs font-medium text-muted-fg">Username</label>
<input
id="edit-user-username"
bind:value={editForm.username}
autocomplete="username"
placeholder="Optional"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
</div>
<div>
<label for="edit-user-password" class="mb-1 block text-xs font-medium text-muted-fg">New password</label>
<input
id="edit-user-password"
type="password"
minlength="8"
bind:value={editForm.password}
autocomplete="new-password"
placeholder="Leave blank to keep the current password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</div>
<div>
<label for="edit-user-role" class="mb-1 block text-xs font-medium text-muted-fg">Role</label>
<select
id="edit-user-role"
bind:value={editForm.role}
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<option value="user">user</option>
<option value="moderator">moderator</option>
<option value="admin">admin</option>
<option value="superadmin">superadmin</option>
</select>
</div>
<div class="flex justify-end gap-2">
<Button type="button" variant="secondary" onclick={closeUserEditor} disabled={savingUser}>Cancel</Button>
<Button type="submit" disabled={savingUser}>{savingUser ? 'Saving…' : 'Save changes'}</Button>
</div>
</form>
</div>
</div>
{/if}
{:else}
<Card class="space-y-5"
><div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<SectionTitle title="Media catalog" description="Select catalog rows and apply visibility actions." />
<div class="flex gap-2">
<input
bind:value={search}
onkeydown={(event) => event.key === 'Enter' && void load()}
placeholder="Search media"
class="h-9 w-48 rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
/><Button size="sm" variant="secondary" onclick={() => void load()}>Search</Button>
</div>
</div>
<div class="flex flex-wrap gap-2 border-y border-border py-3">
<Badge variant="primary">{selectedMedia.length} selected</Badge><Button
size="sm"
variant="secondary"
disabled={!selectedMedia.length}
onclick={() => void mediaAction('activate')}><Check class="size-4" />Show</Button
><Button
size="sm"
variant="secondary"
disabled={!selectedMedia.length}
onclick={() => void mediaAction('deactivate')}>Hide</Button
><Button size="sm" variant="danger" disabled={!selectedMedia.length} onclick={() => void mediaAction('delete')}
><Trash2 class="size-4" />Delete</Button
>
</div>
{#if loading}<p class="py-8 text-center text-sm text-muted-fg">
Loading media…
</p>{:else if media.length === 0}<EmptyState
title="No catalog media found"
message="MediaAnalyzer outputs will appear once the catalog synchronization has data."
/>{:else}<div class="overflow-x-auto">
<table class="w-full min-w-[720px] text-left">
<thead
><tr class="border-b border-border text-xs uppercase tracking-wider text-muted-fg"
><th class="w-10 py-3"></th><th class="py-3">Media</th><th class="py-3">Source</th><th class="py-3"
>Owner</th
><th class="py-3">Visibility</th></tr
></thead
><tbody class="divide-y divide-border"
>{#each media as item (item.id)}<tr class="hover:bg-surface-hover/50"
><td class="py-3"
><input
type="checkbox"
checked={selectedMedia.includes(String(item.id))}
onchange={() => toggle(selectedMedia, String(item.id), 'media')}
class="size-4 accent-primary"
/></td
><td class="py-3"
><p class="max-w-md truncate text-sm font-medium text-fg">
{item.title || item.mediaKey || `Media ${item.id}`}
</p>
<p class="mt-1 max-w-md truncate text-xs text-muted-fg">{item.mediaKey || 'No media key'}</p></td
><td class="py-3 text-xs text-muted-fg">{item.source || '—'}</td><td
class="py-3 text-xs text-muted-fg">{item.generatorUsername || '—'}</td
><td class="py-3"
><Badge variant={item.active === false ? 'danger' : 'success'}
>{item.active === false ? 'Hidden' : 'Visible'}</Badge
></td
></tr
>{/each}</tbody
>
</table>
</div>{/if}</Card
>
{/if}
</div>