Files
luminary/src/components/AdminPanel.tsx
T
bhursey 158dccddf1 Add an admin action that rebuilds preview proxies
A library imported by an older pipeline keeps whatever proxy it was given, and
the editor can only show those bytes. The Storage tab now re-decodes every
camera raw from its original, writing a fresh JPEG proxy, thumbnail, 16-bit
sidecar and denoise prune, then stamps previewVersion so browsers refetch.

The decode loop runs one photo at a time on the server behind a status route:
an hour of LibRaw work would time out as a request, and parallel decodes would
starve the editor. The single-photo reprocess route shares the same helper.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:20:44 +00:00

1313 lines
52 KiB
TypeScript

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<AdminInvite['status'], string> = {
pending: 'Pending',
accepted: 'Used',
expired: 'Expired',
revoked: 'Revoked',
};
export default function AdminPanel({ user, onClose, onChanged, onRestored }: Props) {
const [tab, setTab] = useState<Tab>('users');
const [overview, setOverview] = useState<AdminOverview | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [note, setNote] = useState<string | null>(null);
const [newEmail, setNewEmail] = useState('');
const [newName, setNewName] = useState('');
const [newPassword, setNewPassword] = useState('');
const [newRole, setNewRole] = useState('member');
const [resetFor, setResetFor] = useState<string | null>(null);
const [resetValue, setResetValue] = useState('');
const [confirmUser, setConfirmUser] = useState<string | null>(null);
const [newInviteEmail, setNewInviteEmail] = useState('');
const [newInviteRole, setNewInviteRole] = useState('member');
const [newInviteDays, setNewInviteDays] = useState(7);
const [createdInvite, setCreatedInvite] = useState<AdminInvite | null>(null);
const [copiedInvite, setCopiedInvite] = useState<string | null>(null);
const [editEvent, setEditEvent] = useState<{ id: string; name: string } | null>(null);
const [confirmEvent, setConfirmEvent] = useState<string | null>(null);
const [rootInput, setRootInput] = useState('');
const [change, setChange] = useState<StorageChange | null>(null);
const [rebuild, setRebuild] = useState<PreviewRebuildStatus>(idleRebuild);
const [rebuildBusy, setRebuildBusy] = useState(false);
const restoreInput = useRef<HTMLInputElement>(null);
const [restoreNote, setRestoreNote] = useState<string | null>(null);
const [quotaDrafts, setQuotaDrafts] = useState<Record<string, string>>({});
const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' });
const [mail, setMail] = useState<MailStatus | null>(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<void>) => {
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<typeof adminUpdateUser>[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 (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal admin-modal">
<header className="modal-head">
<h2>Administration</h2>
<button className="icon-btn" onClick={onClose} title="Close (Esc)">
✕
</button>
</header>
<div className="tabs admin-tabs">
<button className={`tab ${tab === 'users' ? 'on' : ''}`} onClick={() => setTab('users')}>
Users {overview ? `(${overview.totals.users})` : ''}
</button>
<button className={`tab ${tab === 'invites' ? 'on' : ''}`} onClick={() => setTab('invites')}>
Invites {overview ? `(${overview.totals.pendingInvites ?? 0})` : ''}
</button>
<button className={`tab ${tab === 'content' ? 'on' : ''}`} onClick={() => setTab('content')}>
Content {overview ? `(${overview.totals.photos})` : ''}
</button>
<button className={`tab ${tab === 'storage' ? 'on' : ''}`} onClick={() => setTab('storage')}>
Storage
</button>
<button className={`tab ${tab === 'quotas' ? 'on' : ''}`} onClick={() => setTab('quotas')}>
Quotas
</button>
<button className={`tab ${tab === 'immich' ? 'on' : ''}`} onClick={() => setTab('immich')}>
Immich
</button>
<button className={`tab ${tab === 'backup' ? 'on' : ''}`} onClick={() => setTab('backup')}>
Backup
</button>
</div>
<div className="modal-body">
{!overview ? (
<p className="muted small">{error ?? 'Loading…'}</p>
) : tab === 'users' ? (
<section className="admin-section">
<div className="admin-create">
<h3>Add an account</h3>
<div className="admin-create-grid">
<input
type="email"
placeholder="email@studio.com"
value={newEmail}
onChange={(e) => setNewEmail(e.target.value)}
/>
<input
placeholder="Display name (optional)"
value={newName}
onChange={(e) => setNewName(e.target.value)}
/>
<input
type="password"
placeholder="Password (8+ characters)"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
/>
<select value={newRole} onChange={(e) => setNewRole(e.target.value)}>
<option value="member">Member</option>
<option value="admin">Administrator</option>
</select>
<button
className="btn primary"
onClick={createAccount}
disabled={busy || !newEmail.trim() || newPassword.length < 8}
>
{busy ? 'Saving…' : 'Add account'}
</button>
</div>
</div>
<div className="admin-table">
<div className="admin-row admin-row-head">
<span>Account</span>
<span>Role</span>
<span>Status</span>
<span>Actions</span>
</div>
{overview.users.map((row) => {
const self = row.id === user.id;
return (
<div className={`admin-row ${row.disabled ? 'is-off' : ''}`} key={row.id}>
<div className="admin-who">
<span className="cloud-avatar small">{(row.name || row.email).slice(0, 1).toUpperCase()}</span>
<div>
<strong>
{row.name || row.email}
{self && <span className="admin-badge">you</span>}
</strong>
<div className="muted small">
{row.email} · joined {fmtDate(row.createdAt)}
</div>
</div>
</div>
<select
className="admin-select"
value={row.role}
disabled={busy || self}
onChange={(e) => void patchUser(row, { role: e.target.value })}
>
<option value="member">Member</option>
<option value="admin">Administrator</option>
</select>
<button
className={`admin-toggle ${row.disabled ? 'off' : 'on'}`}
disabled={busy || self}
onClick={() => void patchUser(row, { disabled: !row.disabled })}
>
{row.disabled ? 'Disabled' : 'Active'}
</button>
<div className="admin-actions">
<button
className="btn ghost small"
disabled={busy}
onClick={() => {
setResetFor(resetFor === row.id ? null : row.id);
setResetValue('');
}}
>
Password
</button>
{confirmUser === row.id ? (
<>
<button className="btn danger small" disabled={busy} onClick={() => void removeUser(row)}>
Confirm delete
</button>
<button className="btn ghost small" onClick={() => setConfirmUser(null)}>
Cancel
</button>
</>
) : (
<button
className="btn ghost small"
disabled={busy || self}
onClick={() => setConfirmUser(row.id)}
>
Delete
</button>
)}
</div>
{resetFor === row.id && (
<div className="admin-inline">
<input
type="password"
autoFocus
placeholder="New password (8+ characters)"
value={resetValue}
onChange={(e) => setResetValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') resetPassword(row);
if (e.key === 'Escape') {
e.stopPropagation();
setResetFor(null);
}
}}
/>
<button
className="btn small"
disabled={busy || resetValue.length < 8}
onClick={() => resetPassword(row)}
>
Set password
</button>
<button className="btn ghost small" onClick={() => setResetFor(null)}>
Cancel
</button>
<span className="muted small">Signs that account out everywhere.</span>
</div>
)}
</div>
);
})}
</div>
</section>
) : tab === 'invites' ? (
<section className="admin-section">
<div className="admin-create">
<h3>Create an invite link</h3>
<div className="admin-create-grid invite-create-grid">
<input
type="email"
placeholder="Email (optional)"
value={newInviteEmail}
onChange={(e) => setNewInviteEmail(e.target.value)}
/>
<select value={newInviteRole} onChange={(e) => setNewInviteRole(e.target.value)}>
<option value="member">Member</option>
<option value="admin">Administrator</option>
</select>
<select value={newInviteDays} onChange={(e) => setNewInviteDays(Number(e.target.value))}>
<option value={1}>Expires in 1 day</option>
<option value={7}>Expires in 7 days</option>
<option value={30}>Expires in 30 days</option>
</select>
<button className="btn primary" onClick={createInvite} disabled={busy}>
{busy ? 'Creating…' : 'Create invite link'}
</button>
</div>
<p className="muted small invite-hint">
{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.
</p>
</div>
{createdInvite && (
<div className="invite-created">
<div className="invite-created-head">
<strong>Invite link ready</strong>
<span className="muted small">Expires {fmtDate(createdInvite.expiresAt)}</span>
</div>
<div className="invite-link-row">
<input
readOnly
value={inviteUrl(createdInvite.token)}
onFocus={(e) => e.currentTarget.select()}
/>
<button className="btn primary small" onClick={() => void copyInvite(createdInvite)}>
{copiedInvite === createdInvite.token ? 'Copied' : 'Copy link'}
</button>
</div>
<p className="muted small">
Send this link to {createdInvite.email || 'the person you want to invite'}. They create
their own account and get their own workspace.
</p>
</div>
)}
<div className="admin-table">
<div className="admin-row admin-row-head invite-row">
<span>Invite</span>
<span>Role</span>
<span>Status</span>
<span>Actions</span>
</div>
{(overview.invites ?? []).length === 0 && (
<p className="muted small invite-empty">No invite links yet.</p>
)}
{(overview.invites ?? []).map((invite) => {
const joined = invite.acceptedBy
? overview.users.find((row) => row.id === invite.acceptedBy)
: null;
return (
<div
className={`admin-row invite-row ${invite.status === 'pending' ? '' : 'is-off'}`}
key={invite.token}
>
<div className="admin-who">
<span className="cloud-avatar small">
{invite.email ? invite.email.slice(0, 1).toUpperCase() : '↗'}
</span>
<div>
<strong>{invite.email || 'Anyone with the link'}</strong>
<div className="muted small">
{invite.status === 'accepted'
? `Joined ${fmtDate(invite.acceptedAt)}${joined ? ` as ${joined.email}` : ''}`
: `Created ${fmtDate(invite.createdAt)} · expires ${fmtDate(invite.expiresAt)}`}
</div>
</div>
</div>
<span className="admin-role">{invite.role === 'admin' ? 'Admin' : 'Member'}</span>
<span className={`invite-status ${invite.status}`}>
{inviteStatusLabel[invite.status] ?? invite.status}
</span>
<div className="admin-actions">
{invite.status === 'pending' ? (
<>
<button className="btn ghost small" onClick={() => void copyInvite(invite)}>
{copiedInvite === invite.token ? 'Copied' : 'Copy link'}
</button>
<button
className="btn ghost small"
disabled={busy}
onClick={() => void revokeInviteLink(invite)}
>
Revoke
</button>
</>
) : (
<span className="muted small">—</span>
)}
</div>
</div>
);
})}
</div>
<p className="muted small">
Invite links are single-use and expire automatically. Revoking a link stops it immediately.
</p>
</section>
) : tab === 'content' ? (
<section className="admin-section">
<div className="admin-summary">
<div>
<dt>Photos</dt>
<dd>{overview.totals.photos}</dd>
</div>
<div>
<dt>Photo size</dt>
<dd>{fmtBytes(overview.totals.bytes)}</dd>
</div>
<div>
<dt>Events</dt>
<dd>{overview.events.length}</dd>
</div>
</div>
<div className="admin-table">
<div className="admin-row admin-row-head content-row">
<span>Event</span>
<span>Photos</span>
<span>Size</span>
<span>Actions</span>
</div>
{overview.events.length === 0 && <p className="muted small">No events yet.</p>}
{overview.events.map((event) => (
<div className="admin-row content-row" key={event.id}>
{editEvent?.id === event.id ? (
<div className="admin-inline tight">
<input
autoFocus
value={editEvent.name}
onChange={(e) => setEditEvent({ id: event.id, name: e.target.value })}
onKeyDown={(e) => {
if (e.key === 'Enter') renameEvent();
if (e.key === 'Escape') {
e.stopPropagation();
setEditEvent(null);
}
}}
/>
<button className="btn small" onClick={renameEvent} disabled={busy}>
Save
</button>
<button className="btn ghost small" onClick={() => setEditEvent(null)}>
Cancel
</button>
</div>
) : (
<div className="admin-event-name">
<strong>{event.name}</strong>
<div className="muted small">
{event.ownerEmail || 'unassigned'} · created {fmtDate(event.createdAt)}
</div>
</div>
)}
<span className="admin-num">{event.photos}</span>
<span className="admin-num">{fmtBytes(event.bytes)}</span>
<div className="admin-actions">
<button
className="btn ghost small"
disabled={busy}
onClick={() => setEditEvent({ id: event.id, name: event.name })}
>
Rename
</button>
{confirmEvent === event.id ? (
<>
<button
className="btn danger small"
disabled={busy}
onClick={() => void removeEvent(event.id, event.name)}
>
Confirm delete
</button>
<button className="btn ghost small" onClick={() => setConfirmEvent(null)}>
Cancel
</button>
</>
) : (
<button className="btn ghost small" disabled={busy} onClick={() => setConfirmEvent(event.id)}>
Delete
</button>
)}
</div>
</div>
))}
</div>
<p className="muted small">
Deleting an event removes its photos and the files on disk. Accounts are unaffected.
</p>
</section>
) : tab === 'quotas' ? (
<section className="admin-section">
<div className="admin-summary">
<div>
<dt>Default per account</dt>
<dd>{fmtBytes(overview.quotas[0]?.limit ?? 100 * GIB)}</dd>
</div>
<div>
<dt>Near their limit</dt>
<dd>{overview.quotas.filter((quota) => quota.warn).length}</dd>
</div>
<div>
<dt>Scheduled prunes</dt>
<dd>{overview.quotas.filter((quota) => quota.pruneAt).length}</dd>
</div>
</div>
<div className="admin-create">
<h3>Gmail notifications</h3>
<div className="admin-create-grid mail-grid">
<input
type="email"
placeholder="studio@gmail.com"
value={mailDraft.user}
onChange={(e) => setMailDraft((current) => ({ ...current, user: e.target.value }))}
/>
<input
type="password"
placeholder={mail?.hasPassword ? 'App password saved' : 'Google app password'}
value={mailDraft.appPassword}
onChange={(e) =>
setMailDraft((current) => ({ ...current, appPassword: e.target.value }))
}
/>
<input
type="email"
placeholder="From address (optional)"
value={mailDraft.from}
onChange={(e) => setMailDraft((current) => ({ ...current, from: e.target.value }))}
/>
<button
className="btn primary"
disabled={busy || !mailDraft.user.trim() || (!mailDraft.appPassword && !mail?.hasPassword)}
onClick={saveEmail}
>
Save email
</button>
<button className="btn ghost" disabled={busy || !mail?.configured} onClick={testEmail}>
Send test
</button>
</div>
<p className="muted small">
{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.'}
</p>
</div>
<div className="admin-table">
<div className="admin-row admin-row-head quota-row">
<span>Account</span>
<span>Usage</span>
<span>Quota</span>
<span>Actions</span>
</div>
{overview.quotas.map((quota) => (
<div className={`admin-row quota-row ${quota.over ? 'quota-over' : ''}`} key={quota.user.id}>
<div className="admin-who">
<span className="cloud-avatar small">
{(quota.user.name || quota.user.email).slice(0, 1).toUpperCase()}
</span>
<div>
<strong>{quota.user.name || quota.user.email}</strong>
<div className="muted small">{quota.user.email}</div>
</div>
</div>
<div className="quota-usage">
<div className="quota-numbers">
<strong>{fmtBytes(quota.used)}</strong>
<span className="muted"> / {fmtBytes(quota.limit)} · {quota.percent}%</span>
</div>
<div className="quota-meter" aria-label={`${quota.percent}% of quota used`}>
<span
className={quota.over ? 'over' : quota.warn ? 'warn' : ''}
style={{ width: `${Math.min(100, quota.percent)}%` }}
/>
</div>
<div className="muted small">
{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`}
</div>
</div>
<div className="quota-limit">
<input
type="number"
min={1}
step={1}
value={quotaDrafts[quota.user.id] ?? String(Math.round(quota.limit / GIB))}
onChange={(e) =>
setQuotaDrafts((current) => ({ ...current, [quota.user.id]: e.target.value }))
}
aria-label={`Quota in GB for ${quota.user.email}`}
/>
<span className="muted small">GB</span>
<button className="btn ghost small" disabled={busy} onClick={() => saveQuota(quota)}>
Set
</button>
</div>
<div className="admin-actions quota-actions">
{quota.pruneAt ? (
<button className="btn danger small" disabled={busy} onClick={() => cancelQuotaPrune(quota)}>
Cancel prune
</button>
) : (
<button
className="btn small"
disabled={busy || !overview.mail.configured || quota.plan.freedBytes <= 0}
title={
!overview.mail.configured
? 'Configure Gmail notifications first'
: quota.plan.freedBytes <= 0
? 'Nothing is old enough to reach the cleanup target'
: `Oldest content to remove: ${planSummary(quota)}`
}
onClick={() => scheduleQuotaPrune(quota)}
>
Schedule prune
</button>
)}
<button
className="btn ghost small"
disabled={busy || !quota.warn || !overview.mail.configured}
onClick={() => warnQuotaUser(quota)}
>
Email warning
</button>
</div>
</div>
))}
</div>
<div className="admin-note">
<p>
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.
</p>
<p className="muted small">
Prune candidates: {planSummary(overview.quotas.find((quota) => quota.warn) ?? overview.quotas[0])}
</p>
</div>
</section>
) : tab === 'immich' ? (
<section className="admin-section">
<h3>Immich connection</h3>
<p className="muted small">
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.
</p>
<label className="field">
<span>Immich server address</span>
<input
value={immichDraft.url}
spellCheck={false}
placeholder="http://192.168.1.10:2283"
onChange={(e) =>
setImmichDraft((current) => ({ ...current, url: e.target.value }))
}
onKeyDown={(e) => e.key === 'Enter' && saveImmich()}
/>
</label>
<label className="field">
<span>API key</span>
<input
type="password"
autoComplete="off"
value={immichDraft.apiKey}
placeholder={overview.immich.hasKey ? 'Saved — type to replace' : 'Immich API key'}
onChange={(e) =>
setImmichDraft((current) => ({ ...current, apiKey: e.target.value }))
}
onKeyDown={(e) => e.key === 'Enter' && saveImmich()}
/>
</label>
<label className="check-row">
<input
type="checkbox"
checked={immichDraft.enabled}
disabled={busy}
onChange={(e) =>
setImmichDraft((current) => ({ ...current, enabled: e.target.checked }))
}
/>
Automatically publish event photos and edits
</label>
<div className="btn-row">
<button
className="btn primary"
onClick={saveImmich}
disabled={
busy ||
!immichDraft.url.trim() ||
(!immichDraft.apiKey && !overview.immich.hasKey)
}
>
Save connection
</button>
<button
className="btn ghost"
onClick={testImmich}
disabled={busy || !overview.immich.hasKey}
>
Test connection
</button>
{overview.immich.hasKey && (
<button
className="btn ghost"
onClick={disconnectImmichConnection}
disabled={busy}
>
Disconnect
</button>
)}
</div>
{overview.immich.configured ? (
<div className={`banner ${overview.immich.enabled ? 'ok' : 'info'}`}>
{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.'}
</div>
) : (
<div className="banner info">
Add the server address and API key to enable Immich publishing.
</div>
)}
<div className="admin-note">
<p>
The key needs <code>album.read</code>, <code>album.create</code>,{' '}
<code>albumAsset.create</code>, <code>asset.read</code>,{' '}
<code>asset.download</code>, <code>asset.upload</code> and{' '}
<code>asset.update</code>. Add <code>asset.delete</code> only if originals should
move to the Immich trash after an edited version is uploaded.
</p>
<p className="muted small">
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.
</p>
</div>
</section>
) : tab === 'backup' ? (
<section className="admin-section">
<h3>Catalog backup</h3>
<p className="muted small">
Save events, photo records, edits, ratings, keywords, presets, collections and export
recipes as one JSON file. Image files and account passwords are not included.
</p>
<div className="btn-row">
<a className="btn primary" href="/api/admin/catalog" download>
Download catalog backup
</a>
</div>
<div className="admin-note">
<p>
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.
</p>
<p className="muted small">
Originals, previews and thumbnails stay in the image folder. Keep those backed up
separately if you need a complete restore after a disk loss.
</p>
</div>
<label className="field">
<span>Restore a catalog backup</span>
<input
ref={restoreInput}
type="file"
accept="application/json,.json"
disabled={busy}
onChange={(e) => void restoreCatalog(e.target.files?.[0])}
/>
</label>
{restoreNote && <div className="banner ok">{restoreNote}</div>}
</section>
) : (
<section className="admin-section">
<dl className="admin-summary">
<div>
<dt>Image folder</dt>
<dd className="admin-path">{overview.storage.root}</dd>
</div>
<div>
<dt>On disk</dt>
<dd>{fmtBytes(overview.storage.diskBytes ?? overview.totals.bytes)}</dd>
</div>
<div>
<dt>Photos</dt>
<dd>{overview.totals.photos}</dd>
</div>
</dl>
<label className="field admin-storage-field">
<span>Save images to</span>
<input
value={rootInput}
spellCheck={false}
onChange={(e) => setRootInput(e.target.value)}
placeholder="/srv/luminary-photos"
onKeyDown={(e) => e.key === 'Enter' && changeStorage()}
/>
</label>
<div className="btn-row">
<button
className="btn primary"
onClick={changeStorage}
disabled={busy || !rootInput.trim() || rootInput.trim() === overview.storage.root}
>
{busy ? 'Moving images…' : 'Use this folder'}
</button>
<button className="btn ghost" onClick={() => setRootInput(overview.storage.root)}>
Reset
</button>
{overview.storage.root !== overview.storage.defaultRoot && (
<button className="btn ghost" onClick={() => setRootInput(overview.storage.defaultRoot)}>
Default location
</button>
)}
</div>
{change?.moved && (
<div className="banner ok">
Moved {change.files} file{change.files === 1 ? '' : 's'} ({fmtBytes(change.bytes)}) from{' '}
<code>{change.previous}</code> to <code>{change.root}</code>.
</div>
)}
<div className="admin-note">
<p>
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.
</p>
<p className="muted small">
Default: <code>{overview.storage.defaultRoot}</code> — also settable with{' '}
<code>LUMINARY_DATA</code> before first start.
</p>
<p className="muted small">
The server must be able to write to this path. In Docker, mount the host folder into the
container first (for example <code>-v /photos:/photos</code>), then use that container path.
</p>
</div>
<h3>Preview proxies</h3>
<p className="muted small">
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.
</p>
<div className="btn-row">
<button
className="btn primary"
onClick={() => void rebuildPreviews()}
disabled={busy || rebuildBusy || rebuildRunning || rebuild.total === 0}
title={
rebuild.total === 0 && rebuild.state === 'done'
? 'The last rebuild found no camera raws to process'
: undefined
}
>
{rebuildRunning
? `Rebuilding ${rebuild.done} / ${rebuild.total}…`
: rebuildBusy
? 'Starting…'
: 'Rebuild previews'}
</button>
</div>
{rebuildRunning && (
<p className="muted small">
{rebuild.done} of {rebuild.total} raws rebuilt
{rebuild.failed ? ` · ${rebuild.failed} failed` : ''} · the server keeps going when
this panel closes.
</p>
)}
{rebuild.state === 'done' && (
<p className="muted small">
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]}` : ''}
</p>
)}
</section>
)}
{note && <div className="banner ok">{note}</div>}
{error && <div className="banner error">{error}</div>}
</div>
<footer className="modal-foot">
<span className="muted small">
Signed in as {user.email} · {user.role}
</span>
<button className="btn" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}