import type { EventRecord, Flag, PhotoRecord, Preset } from '../types'; export interface Health { ok: boolean; app: string; version: string; needsSetup: boolean; registrationOpen: boolean; photos: number; bytes: number; storage?: { root: string; custom: boolean }; raw: { libraw: boolean; sharp: boolean; formats: string[] }; } export interface SessionUser { id: string; email: string; name: string; role: string; } export interface UploadResult { raw: boolean; engine?: 'libraw' | 'embedded'; width?: number; height?: number; mime?: string; size?: number; previewUrl?: string; thumbUrl?: string; note?: string | null; } export class ApiError extends Error { status: number; constructor(message: string, status: number) { super(message); this.status = status; } } export async function request(path: string, init?: RequestInit): Promise { let res: Response; try { res = await fetch(path, { credentials: 'same-origin', ...init }); } catch { throw new ApiError('Cannot reach the Luminary server', 0); } if (!res.ok) { let message = `Request failed (${res.status})`; try { const body = (await res.json()) as { error?: string }; if (body?.error) message = body.error; } catch { /* non-JSON error body */ } throw new ApiError(message, res.status); } if (res.status === 204) return undefined as T; return (await res.json()) as T; } function jsonBody(payload: unknown): RequestInit { return { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }; } /** Returns null when the app is running without a server (pure browser library). */ export async function getHealth(): Promise { try { const res = await fetch('/api/health', { credentials: 'same-origin' }); if (!res.ok) return null; const body = (await res.json()) as Health; return body?.ok ? body : null; } catch { return null; } } export async function register(input: { email: string; password: string; name?: string; invite?: string; inviteToken?: string; }): Promise { const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input)); return res.user; } export async function login(email: string, password: string): Promise { const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password })); return res.user; } export async function logout(): Promise { await request('/api/auth/logout', { method: 'POST' }); } export async function currentUser(): Promise { try { const res = await request<{ user: SessionUser }>('/api/auth/me'); return res.user; } catch (err) { if (err instanceof ApiError && err.status === 401) return null; return null; } } export interface ProofSummary { photoId: string; eventId: string; count: number; clients: string[]; comments?: number; approved?: number; changes?: number; } export interface SyncPayload { user: SessionUser; events: EventRecord[]; photos: PhotoRecord[]; presets: Preset[]; proofs?: ProofSummary[]; } export function pullAll(): Promise { return request('/api/sync'); } export function pullProofs(): Promise { return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []); } export function uploadOriginal(id: string, file: File | Blob, name: string): Promise { const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' }); return request(`/api/photos/${encodeURIComponent(id)}/original?${query}`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file, }); } /** Re-decode a stored RAW with the server's current pipeline settings. */ export function reprocessRawPhoto( id: string, ): Promise<{ width: number; height: number; engine?: 'libraw' | 'embedded'; note?: string | null; previewVersion?: number; previewUrl?: string; thumbUrl?: string; }> { return request(`/api/photos/${encodeURIComponent(id)}/reprocess`, { method: 'POST' }); } export function pushPhoto(photo: PhotoRecord): Promise { return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(photo), }).then((res) => res.photo); } export interface ProofUpload { proofAt: number; width: number | null; height: number | null; thumbUrl: string; } /** Upload a rendered (edited) proof for the client gallery and owner grid. */ export interface DenoiseJob { id: string; key: string; state: 'running' | 'done' | 'error'; ms: number | null; error: string | null; url: string | null; /** Reported by a job that found the render already on disk. */ cached?: boolean; stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null; } /** Starts a server-side denoise job; the work runs off the request thread. */ export function startDenoise(photoId: string): Promise<{ jobId: string }> { return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' }); } /** Drops the rendered files for a photo; the next run renders from scratch. */ export function clearDenoised(photoId: string): Promise { return request(`/api/photos/${encodeURIComponent(photoId)}/denoised`, { method: 'DELETE' }); } export function getDenoiseJob(jobId: string): Promise { return request(`/api/denoise/jobs/${encodeURIComponent(jobId)}`); } export function pushProof(id: string, jpegBase64: string): Promise { return request(`/api/photos/${encodeURIComponent(id)}/proof`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jpeg: jpegBase64 }), }); } export function deletePhotoRemote(id: string): Promise { return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' }); } export function pushEvent(event: EventRecord): Promise { return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(event), }).then((res) => res.event); } export function deleteEventRemote(id: string): Promise { return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' }); } /* ------------------------------------------------------------ proofing api */ export interface ShareFeedback { kind: 'comment' | 'approved' | 'changes'; photoId: string; clientName: string; body?: string; createdAt: number; } export interface ShareSettings { passwordSet: boolean; expiresAt: number | null; watermark: string; allowDownloads: boolean; downloadCap: number; downloadCount: number; } export interface ShareState { token: string | null; picks: { photoId: string; clientName: string }[]; feedback?: ShareFeedback[]; settings?: ShareSettings | null; } export interface GalleryStatus { locked: boolean; expiresAt: number | null; allowDownloads: boolean; } export interface GalleryComment { id: string; clientName: string; body: string; createdAt: number; } export interface GalleryPhoto { id: string; name: string; width: number; height: number; takenAt: number | null; thumbUrl: string; previewUrl: string; pickCount: number; mine: boolean; comments: GalleryComment[]; reviewStatus: 'approved' | 'changes' | null; } export interface GalleryPayload { event: { name: string; date: number | null; notes: string }; photographer: string; photos: GalleryPhoto[]; picks: { total: number; clients: number }; downloads?: { allowed: boolean; remaining: number | null }; watermark?: string; } export function getShare(eventId: string): Promise { return request(`/api/events/${encodeURIComponent(eventId)}/share`); } export function createShare(eventId: string): Promise { return request<{ token: string }>(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'POST', }).then((res) => res.token); } export function galleryDownloadUrl(token: string, photoId: string): string { return `/api/galleries/${encodeURIComponent(token)}/photos/${encodeURIComponent(photoId)}/download`; } export function galleryDownloadAllUrl(token: string, clientId: string): string { const query = new URLSearchParams({ client: clientId }); return `/api/galleries/${encodeURIComponent(token)}/download-all?${query}`; } export interface ShareSettingsInput { password?: string; expiresAt?: number | null; watermark?: string; allowDownloads?: boolean; downloadCap?: number; } export function saveShareSettings( eventId: string, input: ShareSettingsInput, ): Promise { return request<{ settings: ShareSettings }>( `/api/events/${encodeURIComponent(eventId)}/share/settings`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }, ).then((res) => res.settings); } /* ------------------------------------------------------------ tether api */ export interface TetherFile { name: string; size: number; mtime: number; } export interface TetherState { folder: string; files: TetherFile[]; } export function listTether(eventId: string): Promise { return request(`/api/events/${encodeURIComponent(eventId)}/tether`); } export function tetherFileUrl(eventId: string, name: string): string { const query = new URLSearchParams({ name }); return `/api/events/${encodeURIComponent(eventId)}/tether/file?${query}`; } export function removeTetherFile(eventId: string, name: string): Promise { const query = new URLSearchParams({ name }); return request(`/api/events/${encodeURIComponent(eventId)}/tether/file?${query}`, { method: 'DELETE', }); } /** Public check for the link's lock and expiry, before loading the gallery. */ export function getGalleryStatus(token: string): Promise { return request(`/api/galleries/${encodeURIComponent(token)}/status`); } /** Exchanges the gallery password for the unlock cookie the routes require. */ export function unlockGallery(token: string, password: string): Promise { return request(`/api/galleries/${encodeURIComponent(token)}/unlock`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }), }); } export function revokeShare(eventId: string): Promise { return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' }); } /** Public, session-free gallery load. */ export function loadGallery(token: string, clientId: string): Promise { const query = new URLSearchParams({ client: clientId }); return request(`/api/galleries/${encodeURIComponent(token)}?${query}`); } export function setGalleryPick( token: string, input: { photoId: string; picked: boolean; clientId: string; clientName: string }, ): Promise { return request(`/api/galleries/${encodeURIComponent(token)}/picks`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }); } export function addGalleryComment( token: string, input: { photoId: string; clientId: string; clientName: string; body: string }, ): Promise { return request<{ comment: GalleryComment }>(`/api/galleries/${encodeURIComponent(token)}/comments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }).then((res) => res.comment); } export function setGalleryReview( token: string, input: { photoId: string; clientId: string; clientName: string; status: 'approved' | 'changes' | 'none'; }, ): Promise { return request(`/api/galleries/${encodeURIComponent(token)}/reviews`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }); } /* --------------------------------------------------------------- admin api */ export interface AdminUser { id: string; email: string; name: string; role: string; disabled: boolean; createdAt: number | null; } export interface AdminEvent { id: string; name: string; createdAt: number | null; photos: number; bytes: number; ownerId: string; ownerEmail: string; } export interface AdminInvite { token: string; email: string; role: string; status: 'pending' | 'accepted' | 'expired' | 'revoked'; createdAt: number | null; expiresAt: number | null; acceptedAt: number | null; acceptedBy: string | null; revokedAt: number | null; } export interface InviteInfo { status: AdminInvite['status']; email: string; role: string; expiresAt: number | null; } export interface QuotaPlanEvent { id: string; name: string; createdAt: number; photos: string[]; bytes: number; } export interface QuotaPlanPhoto { id: string; name: string; bytes: number; } export interface QuotaPlan { targetBytes: number; usedBytes: number; projectedBytes: number; freedBytes: number; events: QuotaPlanEvent[]; photos: QuotaPlanPhoto[]; } export interface QuotaState { userId: string; limit: number; used: number; remaining: number; ratio: number; percent: number; warn: boolean; over: boolean; warnAt: number; pruneAt: number | null; prunePlan: QuotaPlan | null; pruneNotifiedAt: number | null; lastWarningAt: number | null; } export interface AdminQuota extends QuotaState { user: AdminUser; plan: QuotaPlan; } export interface MailStatus { configured: boolean; source: 'admin' | 'environment' | 'none'; host: string; port: number; secure: boolean; user: string; from: string; hasPassword: boolean; gmail: boolean; } export interface ImmichStatus { configured: boolean; enabled: boolean; /** The connection is configured server-wide by an administrator. */ managed?: boolean; url: string; hasKey: boolean; autoSync: boolean; syncMinutes: number; trashOriginal: boolean; syncMetadata: boolean; lastSyncAt: number | null; lastError: string | null; version: string | null; albumCount: number; } export interface ImmichAlbum { id: string; name: string; assetCount: number; /** A gallery created from a Luminary event is an upload destination, not an import source. */ kind?: 'import' | 'gallery'; updatedAt: number | null; startDate: number | null; endDate: number | null; thumbnailAssetId: string | null; /** Set when this account already imported the album. */ eventId?: string | null; lastSyncAt?: number | null; } export interface ImmichImportJob { id: string; albumId: string; albumName: string; eventId: string | null; state: 'running' | 'done' | 'error'; scheduled?: boolean; total: number; done: number; skipped: number; failed: number; bytes: number; message: string; errors: string[]; startedAt: number; finishedAt: number | null; } export interface ImmichTestResult { ok: boolean; url: string; version: string; major: number; albumCount: number; } export interface ImmichPushResult { ok: boolean; assetId: string; alreadyPushed: boolean; /** True when the photo already existed in Immich and no upload was made. */ skipped?: boolean; trashed: boolean; associations: Partial>; warning: string; } export interface AdminOverview { users: AdminUser[]; events: AdminEvent[]; invites: AdminInvite[]; totals: { users: number; photos: number; bytes: number; pendingInvites: number }; storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number }; quotas: AdminQuota[]; mail: MailStatus; immich: ImmichStatus; } export interface StorageChange { root: string; previous: string; files: number; bytes: number; moved: boolean; photos: number; } export function loadInvite(token: string): Promise { return request(`/api/invites/${encodeURIComponent(token)}`); } export function adminCreateInvite(input: { email: string; role: string; days: number; }): Promise { return request<{ invite: AdminInvite }>('/api/admin/invites', jsonBody(input)).then( (res) => res.invite, ); } export function adminRevokeInvite(token: string): Promise { return request(`/api/admin/invites/${encodeURIComponent(token)}`, { method: 'DELETE' }); } export function adminOverview(): Promise { return request('/api/admin/overview'); } export function adminCreateUser(input: { email: string; name: string; password: string; role: string; }): Promise { return request<{ user: AdminUser }>('/api/admin/users', jsonBody(input)).then((res) => res.user); } export function adminUpdateUser( id: string, patch: { name?: string; role?: string; disabled?: boolean; password?: string }, ): Promise { return request<{ user: AdminUser }>(`/api/admin/users/${encodeURIComponent(id)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch), }).then((res) => res.user); } export function adminDeleteUser(id: string): Promise { return request(`/api/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' }); } export function adminRenameEvent(id: string, name: string): Promise { return request(`/api/admin/events/${encodeURIComponent(id)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }), }); } export function adminDeleteEvent(id: string): Promise<{ photos: number }> { return request<{ photos: number }>(`/api/admin/events/${encodeURIComponent(id)}`, { method: 'DELETE', }); } export interface CatalogBackup { kind: 'lumenroom-catalog'; version: number; generatedAt: number; events: EventRecord[]; photos: PhotoRecord[]; kv: Record; } export function adminRestoreCatalog( catalog: CatalogBackup, ): Promise<{ ok: boolean; events: number; photos: number }> { return request('/api/admin/catalog', jsonBody(catalog)); } export function adminStorage(): Promise { return request('/api/admin/storage'); } export function getQuota(): Promise { return request('/api/quota'); } export function adminSetQuota(userId: string, bytes: number): Promise { return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ bytes }), }).then((res) => res.quota); } export function adminSchedulePrune( userId: string, ): Promise<{ pruneAt: number; plan: QuotaPlan; warningSent: boolean }> { return request(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, { method: 'POST' }); } export function adminCancelPrune(userId: string): Promise { return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, { method: 'DELETE', }).then((res) => res.quota); } export function adminWarnUser(userId: string): Promise { return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/warn`, { method: 'POST', }).then((res) => res.quota); } export function adminGetMail(): Promise { return request<{ mail: MailStatus }>('/api/admin/mail').then((res) => res.mail); } export function adminSaveMail(input: { user: string; appPassword: string; from: string; host?: string; port?: number; }): Promise { return request<{ mail: MailStatus }>('/api/admin/mail', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }).then((res) => res.mail); } export function adminTestMail(to?: string): Promise<{ ok: boolean; to: string }> { return request('/api/admin/mail/test', jsonBody(to ? { to } : {})); } export function adminSetStorage(root: string): Promise { return request('/api/admin/storage', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ root }), }); } export function adminSaveImmich(input: { url: string; apiKey?: string; enabled?: boolean; }): Promise { return request<{ immich: ImmichStatus }>('/api/admin/immich', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }).then((res) => res.immich); } export function adminTestImmich(): Promise { return request('/api/admin/immich/test', { method: 'POST' }); } export function adminDisconnectImmich(): Promise { return request<{ immich: ImmichStatus }>('/api/admin/immich', { method: 'DELETE' }).then( (res) => res.immich, ); } export function getImmichStatus(): Promise { return request<{ immich: ImmichStatus }>('/api/immich').then((res) => res.immich); } export function saveImmichSettings(input: { url: string; apiKey?: string; enabled?: boolean; autoSync?: boolean; syncMinutes?: number; trashOriginal?: boolean; syncMetadata?: boolean; }): Promise { return request<{ immich: ImmichStatus }>('/api/immich', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }).then((res) => res.immich); } export function disconnectImmich(): Promise { return request<{ immich: ImmichStatus }>('/api/immich', { method: 'DELETE' }).then( (res) => res.immich, ); } export function testImmich(): Promise { return request('/api/immich/test', { method: 'POST' }); } export function pushImmichPhoto(photoId: string, jpegBase64: string): Promise { return request( `/api/immich/photos/${encodeURIComponent(photoId)}/push`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jpeg: jpegBase64 }), }, ); } export interface ImmichQueueEntry { photoId: string; name: string; /** Upload the untouched original, or the current rendered edit. */ mode: 'original' | 'edit'; } /** The manual push plan for an event: originals and edits changed since last push. */ export function immichEventQueue( eventId: string, ): Promise<{ queue: ImmichQueueEntry[]; total: number }> { return request(`/api/immich/events/${encodeURIComponent(eventId)}/queue`); } export function publishImmichOriginal(photoId: string): Promise { return request( `/api/immich/photos/${encodeURIComponent(photoId)}/publish`, { method: 'POST' }, ); } export function createImmichEventAlbum( eventId: string, name: string, ): Promise<{ album: ImmichAlbum; event: EventRecord }> { return request('/api/immich/albums', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ eventId, name }), }); } export function immichAlbums(): Promise { return request<{ albums: ImmichAlbum[] }>('/api/immich/albums').then((res) => res.albums ?? []); } export function immichImportAlbum(albumId: string): Promise { return request<{ job: ImmichImportJob }>( `/api/immich/albums/${encodeURIComponent(albumId)}/import`, { method: 'POST' }, ).then((res) => res.job); } export function getImmichJob(jobId: string): Promise { return request<{ job: ImmichImportJob }>( `/api/immich/jobs/${encodeURIComponent(jobId)}`, ).then((res) => res.job); } export function pushPresets(presets: Preset[]): Promise { return request('/api/presets', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ presets }), }); }