import { useCallback, useEffect, useRef, useState } from 'react'; import type { AdminInvite, AdminOverview, AdminQuota, AdminUser, CatalogBackup, MailStatus, PreviewRebuildStatus, SessionUser, StorageChange, } from '../lib/api'; import { adminCancelPrune, adminCreateInvite, adminCreateUser, adminDeleteEvent, adminDeleteUser, adminDisconnectImmich, adminRestoreCatalog, adminRevokeInvite, adminOverview, adminPreviewRebuildStatus, adminRebuildPreviews, adminRenameEvent, adminSaveImmich, adminSaveMail, adminSchedulePrune, adminSetQuota, adminSetStorage, adminTestImmich, adminTestMail, adminUpdateUser, adminWarnUser, } from '../lib/api'; interface Props { user: SessionUser; onClose: () => void; onChanged: () => void; onRestored?: () => void; } const fmtBytes = (bytes: number) => { if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`; if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`; if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`; return `${bytes} B`; }; const fmtDate = (ms: number | null) => ms ? new Date(ms).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '—'; const fmtDateTime = (ms: number | null) => ms ? new Date(ms).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', }) : '—'; const GIB = 1024 ** 3; const planSummary = (quota: AdminQuota) => { const parts: string[] = []; for (const event of quota.plan.events) { parts.push(`${event.name} (${event.photos.length} photos, ${fmtBytes(event.bytes)})`); } if (quota.plan.photos.length) { parts.push(`${quota.plan.photos.length} unassigned photos`); } return parts.length ? parts.join(', ') : 'nothing'; }; type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'immich' | 'backup'; /** No rebuild has run in this process yet. */ const idleRebuild: PreviewRebuildStatus = { state: 'idle', total: 0, done: 0, failed: 0, sidecars: 0, startedAt: null, finishedAt: null, errors: [], }; const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`; const inviteStatusLabel: Record = { pending: 'Pending', accepted: 'Used', expired: 'Expired', revoked: 'Revoked', }; export default function AdminPanel({ user, onClose, onChanged, onRestored }: Props) { const [tab, setTab] = useState('users'); const [overview, setOverview] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [note, setNote] = useState(null); const [newEmail, setNewEmail] = useState(''); const [newName, setNewName] = useState(''); const [newPassword, setNewPassword] = useState(''); const [newRole, setNewRole] = useState('member'); const [resetFor, setResetFor] = useState(null); const [resetValue, setResetValue] = useState(''); const [confirmUser, setConfirmUser] = useState(null); const [newInviteEmail, setNewInviteEmail] = useState(''); const [newInviteRole, setNewInviteRole] = useState('member'); const [newInviteDays, setNewInviteDays] = useState(7); const [createdInvite, setCreatedInvite] = useState(null); const [copiedInvite, setCopiedInvite] = useState(null); const [editEvent, setEditEvent] = useState<{ id: string; name: string } | null>(null); const [confirmEvent, setConfirmEvent] = useState(null); const [rootInput, setRootInput] = useState(''); const [change, setChange] = useState(null); const [rebuild, setRebuild] = useState(idleRebuild); const [rebuildBusy, setRebuildBusy] = useState(false); const restoreInput = useRef(null); const [restoreNote, setRestoreNote] = useState(null); const [quotaDrafts, setQuotaDrafts] = useState>({}); const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' }); const [mail, setMail] = useState(null); const [immichDraft, setImmichDraft] = useState({ url: '', apiKey: '', enabled: true }); // The rebuild runs inside the server, so the panel reads its progress instead // of holding the work: closing the modal does not stop it, and reopening the // tab picks up a run that is already in flight. useEffect(() => { if (tab !== 'storage') return; let alive = true; adminPreviewRebuildStatus() .then((next) => { if (alive) setRebuild(next); }) .catch(() => undefined); return () => { alive = false; }; }, [tab]); const rebuildRunning = rebuild.state === 'running'; useEffect(() => { if (tab !== 'storage' || !rebuildRunning) return; const timer = setInterval(() => { adminPreviewRebuildStatus() .then(setRebuild) .catch(() => undefined); }, 2000); return () => clearInterval(timer); }, [tab, rebuildRunning]); const rebuildPreviews = async () => { setRebuildBusy(true); setError(null); setNote(null); try { const started = await adminRebuildPreviews(); setRebuild(started); setNote( started.state === 'done' ? 'Nothing to rebuild: every camera raw is a JPEG-only import' : `Rebuilding ${started.total} preview proxies`, ); } catch (err) { setError(err instanceof Error ? err.message : 'Could not rebuild the previews'); } finally { setRebuildBusy(false); } }; const restoreCatalog = async (file: File | undefined) => { if (!file || busy) return; setBusy(true); setError(null); setNote(null); setRestoreNote(null); try { const parsed = JSON.parse(await file.text()) as CatalogBackup; if (parsed?.kind !== 'lumenroom-catalog') throw new Error('That file is not a Luminary catalog backup'); const count = parsed.photos?.length ?? 0; if (!window.confirm(`Restore ${parsed.events?.length ?? 0} events and ${count} photo records? Existing records with the same ids will be replaced. This does not restore image files.`)) { return; } const result = await adminRestoreCatalog(parsed); setRestoreNote(`Restored ${result.events} events and ${result.photos} photo records.`); await reload(); onRestored?.(); } catch (err) { setError(err instanceof Error ? err.message : 'Could not restore the catalog'); } finally { setBusy(false); if (restoreInput.current) restoreInput.current.value = ''; } }; useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key !== 'Escape') return; // Inline editors (event rename, password reset) own Escape: cancel the // field first instead of tearing down the whole panel. if ((e.target as HTMLElement | null)?.closest?.('.admin-inline')) return; e.preventDefault(); e.stopImmediatePropagation(); if (!busy) onClose(); }; window.addEventListener('keydown', onKey, true); return () => window.removeEventListener('keydown', onKey, true); }, [busy, onClose]); const reload = useCallback(async () => { const next = await adminOverview(); setOverview(next); setMail(next.mail); setMailDraft((current) => ({ ...current, user: current.user || next.mail.user, from: current.from || next.mail.from, })); setImmichDraft((current) => ({ url: next.immich.hasKey ? current.url || next.immich.url : next.immich.url, apiKey: '', enabled: next.immich.hasKey ? (current.url ? current.enabled : next.immich.enabled) : true, })); setRootInput((current) => (current ? current : next.storage.root)); onChanged(); }, [onChanged]); useEffect(() => { let alive = true; (async () => { try { const next = await adminOverview(); if (!alive) return; setOverview(next); setMail(next.mail); setMailDraft({ user: next.mail.user, appPassword: '', from: next.mail.from }); // A connection being set up for the first time defaults to on; the box // would otherwise be unchecked and silently save publishing as off. setImmichDraft({ url: next.immich.url, apiKey: '', enabled: next.immich.hasKey ? next.immich.enabled : true, }); setRootInput(next.storage.root); setQuotaDrafts( Object.fromEntries( next.quotas.map((quota) => [quota.user.id, String(Math.round(quota.limit / GIB))]), ), ); } catch (err) { if (alive) setError(err instanceof Error ? err.message : 'Could not load administration'); } })(); return () => { alive = false; }; }, []); const run = async (action: () => Promise) => { if (busy) return; setBusy(true); setError(null); setNote(null); try { await action(); await reload(); } catch (err) { setError(err instanceof Error ? err.message : 'That change could not be saved'); } finally { setBusy(false); } }; const createAccount = () => run(async () => { const created = await adminCreateUser({ email: newEmail.trim(), name: newName.trim(), password: newPassword, role: newRole, }); setNewEmail(''); setNewName(''); setNewPassword(''); setNewRole('member'); setNote(`Created ${created.email} as ${created.role}`); }); const createInvite = () => run(async () => { const invite = await adminCreateInvite({ email: newInviteEmail.trim(), role: newInviteRole, days: newInviteDays, }); setCreatedInvite(invite); setNewInviteEmail(''); setNote(`Invite link created${invite.email ? ` for ${invite.email}` : ''}`); }); const copyInvite = async (invite: AdminInvite) => { try { await navigator.clipboard.writeText(inviteUrl(invite.token)); setCopiedInvite(invite.token); setTimeout(() => setCopiedInvite((current) => (current === invite.token ? null : current)), 1800); setNote('Invite link copied'); } catch { // Clipboard access needs a secure context and permission. Fall back to // showing the link in the selectable field so it can still be copied. setCreatedInvite(invite); setError('Clipboard is unavailable here — select the link above and copy it'); } }; const revokeInviteLink = (invite: AdminInvite) => run(async () => { await adminRevokeInvite(invite.token); if (createdInvite?.token === invite.token) setCreatedInvite(null); setCopiedInvite(null); setNote('Invite link revoked'); }); const patchUser = (target: AdminUser, patch: Parameters[1]) => run(async () => { await adminUpdateUser(target.id, patch); setNote(`Updated ${target.email}`); }); const resetPassword = (target: AdminUser) => { if (resetValue.length < 8) { setError('Use at least 8 characters for the password'); return; } void run(async () => { await adminUpdateUser(target.id, { password: resetValue }); setResetFor(null); setResetValue(''); setNote(`Password reset for ${target.email}`); }); }; const removeUser = (target: AdminUser) => run(async () => { await adminDeleteUser(target.id); setConfirmUser(null); setNote(`Deleted ${target.email}`); }); const saveQuota = (quota: AdminQuota) => { const gigabytes = Number(quotaDrafts[quota.user.id]); if (!Number.isFinite(gigabytes) || gigabytes < 1) { setError('Enter a quota of at least 1 GB'); return; } void run(async () => { await adminSetQuota(quota.user.id, Math.round(gigabytes * GIB)); setNote(`Quota for ${quota.user.email} set to ${gigabytes} GB`); }); }; const scheduleQuotaPrune = (quota: AdminQuota) => { if (quota.plan.freedBytes <= 0) { setError('There is nothing old enough to prune. The account is already below the cleanup target'); return; } if (!overview?.mail.configured) { setError('Set up Gmail email notifications before scheduling a prune'); return; } const freed = fmtBytes(quota.plan.freedBytes); const proceed = window.confirm( `Email ${quota.user.email} a 24-hour warning, then permanently remove the oldest content?\n\n${planSummary(quota)}\n\nThis will free about ${freed}.`, ); if (!proceed) return; void run(async () => { const result = await adminSchedulePrune(quota.user.id); setNote( `Warning sent to ${quota.user.email} · prune runs ${fmtDateTime(result.pruneAt)}`, ); }); }; const cancelQuotaPrune = (quota: AdminQuota) => { if (!window.confirm(`Cancel the scheduled prune for ${quota.user.email}?`)) return; void run(async () => { await adminCancelPrune(quota.user.id); setNote(`Scheduled prune cancelled for ${quota.user.email}`); }); }; const warnQuotaUser = (quota: AdminQuota) => run(async () => { await adminWarnUser(quota.user.id); setNote(`Quota warning emailed to ${quota.user.email}`); }); const saveEmail = () => run(async () => { const next = await adminSaveMail({ user: mailDraft.user.trim(), appPassword: mailDraft.appPassword, from: mailDraft.from.trim(), }); setMail(next); setMailDraft((current) => ({ ...current, appPassword: '' })); setNote('Gmail notification settings saved'); }); const testEmail = () => run(async () => { await adminTestMail(user.email); setNote(`Test email sent to ${user.email}`); }); const saveImmich = () => run(async () => { const next = await adminSaveImmich({ url: immichDraft.url.trim(), apiKey: immichDraft.apiKey, enabled: immichDraft.enabled, }); setImmichDraft({ url: next.url, apiKey: '', enabled: next.enabled }); setNote( next.enabled ? 'Immich connection saved for every account' : 'Immich connection saved; automatic publishing is off', ); }); const testImmich = () => run(async () => { const result = await adminTestImmich(); setNote( `Connected to Immich ${result.version} · ${result.albumCount} album${ result.albumCount === 1 ? '' : 's' }`, ); }); const disconnectImmichConnection = () => { if (!window.confirm('Remove the server-wide Immich connection? Existing albums and photos stay in Immich.')) { return; } void run(async () => { const next = await adminDisconnectImmich(); setImmichDraft({ url: next.url, apiKey: '', enabled: next.enabled }); setNote('Immich connection removed'); }); }; const renameEvent = () => { if (!editEvent) return; const name = editEvent.name.trim(); if (!name) { setError('Enter an event name'); return; } void run(async () => { await adminRenameEvent(editEvent.id, name); setEditEvent(null); setNote(`Renamed event to “${name}”`); }); }; const removeEvent = (id: string, name: string) => run(async () => { const result = await adminDeleteEvent(id); setConfirmEvent(null); setNote(`Deleted “${name}” and ${result.photos} photo${result.photos === 1 ? '' : 's'}`); }); const changeStorage = () => run(async () => { const result = await adminSetStorage(rootInput.trim()); setChange(result); setRootInput(result.root); setNote( result.moved ? `Images now save to ${result.root} · moved ${result.files} file${result.files === 1 ? '' : 's'} (${fmtBytes(result.bytes)})` : 'That is already the active image folder', ); }); return (
e.target === e.currentTarget && onClose()}>

Administration

{!overview ? (

{error ?? 'Loading…'}

) : tab === 'users' ? (

Add an account

setNewEmail(e.target.value)} /> setNewName(e.target.value)} /> setNewPassword(e.target.value)} />
Account Role Status Actions
{overview.users.map((row) => { const self = row.id === user.id; return (
{(row.name || row.email).slice(0, 1).toUpperCase()}
{row.name || row.email} {self && you}
{row.email} · joined {fmtDate(row.createdAt)}
{confirmUser === row.id ? ( <> ) : ( )}
{resetFor === row.id && (
setResetValue(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') resetPassword(row); if (e.key === 'Escape') { e.stopPropagation(); setResetFor(null); } }} /> Signs that account out everywhere.
)}
); })}
) : tab === 'invites' ? (

Create an invite link

setNewInviteEmail(e.target.value)} />

{newInviteEmail.trim() ? `Only ${newInviteEmail.trim()} can use this link.` : 'Anyone with the link can create one account.'}{' '} Each link is single-use and can be revoked.

{createdInvite && (
Invite link ready Expires {fmtDate(createdInvite.expiresAt)}
e.currentTarget.select()} />

Send this link to {createdInvite.email || 'the person you want to invite'}. They create their own account and get their own workspace.

)}
Invite Role Status Actions
{(overview.invites ?? []).length === 0 && (

No invite links yet.

)} {(overview.invites ?? []).map((invite) => { const joined = invite.acceptedBy ? overview.users.find((row) => row.id === invite.acceptedBy) : null; return (
{invite.email ? invite.email.slice(0, 1).toUpperCase() : '↗'}
{invite.email || 'Anyone with the link'}
{invite.status === 'accepted' ? `Joined ${fmtDate(invite.acceptedAt)}${joined ? ` as ${joined.email}` : ''}` : `Created ${fmtDate(invite.createdAt)} · expires ${fmtDate(invite.expiresAt)}`}
{invite.role === 'admin' ? 'Admin' : 'Member'} {inviteStatusLabel[invite.status] ?? invite.status}
{invite.status === 'pending' ? ( <> ) : ( — )}
); })}

Invite links are single-use and expire automatically. Revoking a link stops it immediately.

) : tab === 'content' ? (
Photos
{overview.totals.photos}
Photo size
{fmtBytes(overview.totals.bytes)}
Events
{overview.events.length}
Event Photos Size Actions
{overview.events.length === 0 &&

No events yet.

} {overview.events.map((event) => (
{editEvent?.id === event.id ? (
setEditEvent({ id: event.id, name: e.target.value })} onKeyDown={(e) => { if (e.key === 'Enter') renameEvent(); if (e.key === 'Escape') { e.stopPropagation(); setEditEvent(null); } }} />
) : (
{event.name}
{event.ownerEmail || 'unassigned'} · created {fmtDate(event.createdAt)}
)} {event.photos} {fmtBytes(event.bytes)}
{confirmEvent === event.id ? ( <> ) : ( )}
))}

Deleting an event removes its photos and the files on disk. Accounts are unaffected.

) : tab === 'quotas' ? (
Default per account
{fmtBytes(overview.quotas[0]?.limit ?? 100 * GIB)}
Near their limit
{overview.quotas.filter((quota) => quota.warn).length}
Scheduled prunes
{overview.quotas.filter((quota) => quota.pruneAt).length}

Gmail notifications

setMailDraft((current) => ({ ...current, user: e.target.value }))} /> setMailDraft((current) => ({ ...current, appPassword: e.target.value })) } /> setMailDraft((current) => ({ ...current, from: e.target.value }))} />

{mail?.configured ? `Sending through ${mail.host}:${mail.port} as ${mail.user}. A Google app password is required, not the normal Gmail password.` : 'Add a Gmail address and its Google app password to send 24-hour prune warnings. The password is stored only on this server.'}

Account Usage Quota Actions
{overview.quotas.map((quota) => (
{(quota.user.name || quota.user.email).slice(0, 1).toUpperCase()}
{quota.user.name || quota.user.email}
{quota.user.email}
{fmtBytes(quota.used)} / {fmtBytes(quota.limit)} · {quota.percent}%
{quota.pruneAt ? `Prune scheduled ${fmtDateTime(quota.pruneAt)} · warning ${fmtDateTime(quota.pruneNotifiedAt)}` : quota.warn ? `Warning threshold ${fmtBytes(quota.warnAt)} · ${fmtBytes(quota.remaining)} free` : `${fmtBytes(quota.remaining)} free`}
setQuotaDrafts((current) => ({ ...current, [quota.user.id]: e.target.value })) } aria-label={`Quota in GB for ${quota.user.email}`} /> GB
{quota.pruneAt ? ( ) : ( )}
))}

When an account reaches 90% of its quota, the user sees an in-app warning and is emailed at most once a day. A scheduled prune always sends a warning first and waits 24 hours. At that time the oldest events listed in the warning are removed; photos uploaded after the warning are not touched.

Prune candidates: {planSummary(overview.quotas.find((quota) => quota.warn) ?? overview.quotas[0])}

) : tab === 'immich' ? (

Immich connection

One connection is shared by every account. When it is enabled, importing into a Luminary event creates a matching Immich album, publishes the originals there, and saves edited versions to the same album.

{overview.immich.hasKey && ( )}
{overview.immich.configured ? (
{overview.immich.enabled ? 'Connected and automatic publishing is on.' : 'Connection saved; automatic publishing is off.'}{' '} {overview.immich.version ? `Immich ${overview.immich.version}.` : 'Test it to verify access.'}
) : (
Add the server address and API key to enable Immich publishing.
)}

The key needs album.read, album.create,{' '} albumAsset.create, asset.read,{' '} asset.download, asset.upload and{' '} asset.update. Add asset.delete only if originals should move to the Immich trash after an edited version is uploaded.

The key is encrypted on the server and never sent back to a browser. Existing albums already in Immich stay untouched if the connection is removed.

) : tab === 'backup' ? (

Catalog backup

Save events, photo records, edits, ratings, keywords, presets, collections and export recipes as one JSON file. Image files and account passwords are not included.

Restore merges records by id into this account. Existing records with the same ids are replaced; records that are not in the backup are left alone.

Originals, previews and thumbnails stay in the image folder. Keep those backed up separately if you need a complete restore after a disk loss.

{restoreNote &&
{restoreNote}
}
) : (
Image folder
{overview.storage.root}
On disk
{fmtBytes(overview.storage.diskBytes ?? overview.totals.bytes)}
Photos
{overview.totals.photos}
{overview.storage.root !== overview.storage.defaultRoot && ( )}
{change?.moved && (
Moved {change.files} file{change.files === 1 ? '' : 's'} ({fmtBytes(change.bytes)}) from{' '} {change.previous} to {change.root}.
)}

Originals, previews and thumbnails are stored here. Changing the folder moves the existing images so the library keeps working; the database stays in the server data folder.

Default: {overview.storage.defaultRoot} — also settable with{' '} LUMINARY_DATA before first start.

The server must be able to write to this path. In Docker, mount the host folder into the container first (for example -v /photos:/photos), then use that container path.

Preview proxies

Re-decode every camera raw from its original and replace its JPEG proxy, grid thumbnail and 16-bit sidecar. Run this after a change to the raw pipeline: edits, ratings and events are kept, and the originals are never modified.

{rebuildRunning && (

{rebuild.done} of {rebuild.total} raws rebuilt {rebuild.failed ? ` · ${rebuild.failed} failed` : ''} · the server keeps going when this panel closes.

)} {rebuild.state === 'done' && (

Rebuilt {rebuild.done - rebuild.failed} of {rebuild.total} raws {rebuild.sidecars ? `, ${rebuild.sidecars} with a 16-bit sidecar` : ''} {rebuild.failed ? ` · ${rebuild.failed} failed` : ''}. {rebuild.errors.length > 0 ? ` First failure: ${rebuild.errors[0]}` : ''}

)}
)} {note &&
{note}
} {error &&
{error}
}
); }