diff --git a/.env.example b/.env.example index 4c22ebd..57065a5 100644 --- a/.env.example +++ b/.env.example @@ -94,12 +94,16 @@ NFS_ADDR= NFS_EXPORT= NFS_VERSION=4 -# Advanced editor bridge (optional). LUMENROOM_URL is the base URL of the -# separate Lumenroom deployment, e.g. http://edit.local:8787. BRIDGE_SECRET is a -# long random string shared with that deployment; without both the "Advanced" -# button reports that the editor is not configured. +# Advanced editor bridge (optional). LUMENROOM_URL is the browser-facing base +# URL of Lumenroom, e.g. http://:8787 or https://edit.example.org. +# BRIDGE_SECRET is a long random string shared by both containers; without both +# the "Advanced" button reports that the editor is not configured. LUMENROOM_URL= BRIDGE_SECRET= +# Compose-only host publishing for the Lumenroom container. Bind it to loopback +# when a reverse proxy in front of it terminates TLS. +LUMENROOM_PORT=8787 +LUMENROOM_BIND=0.0.0.0 # Observability (declared; no Sentry integration is wired yet) SENTRY_DSN= diff --git a/Dockerfile b/Dockerfile index e2fe3bc..ab922ba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ ENV NODE_ENV=production # ImageMagick's LibRaw delegate decodes camera RAW files for the in-app editor; # sharp does the tone rendering and JPEG encode. The Postgres client provides # pg_dump/psql for admin backups and restores; unzip reads restore packages. -RUN apk add --no-cache imagemagick libraw ffmpeg postgresql16-client unzip +RUN apk add --no-cache imagemagick libraw ffmpeg exiv2 postgresql16-client unzip # pnpm is how this project is built (see package.json scripts). RUN npm install -g pnpm@9.15.0 diff --git a/README.md b/README.md index dd28deb..4c3b894 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It - [Features](#features) - [Stack](#stack) - [Quick start (Docker)](#quick-start-docker) +- [Deploying the combined stack on another system](#deploying-the-combined-stack-on-another-system) - [Local development](#local-development) - [Configuration](#configuration) - [Email delivery](#email-delivery) @@ -108,10 +109,19 @@ cp .env.example .env docker compose up -d db docker compose --profile tools build migrate docker compose --profile tools run --rm migrate # migrations + seed -docker compose up -d --build app +docker compose up -d --build app lumenroom ``` -Open . The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it). +Open . The advanced photo editor (Lumenroom) is the +vendored second container and publishes on ; it is +optional, and the **Advanced** button stays disabled until `BRIDGE_SECRET` and +`LUMENROOM_URL` are set in `.env` (see [step 15](#15-advanced-photo-editor-bridge-optional)). +The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it). + +```bash +curl -fsS http://localhost:3000/api/health # dashboard +curl -fsS http://localhost:8787/api/health # advanced editor +``` With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link shows it in the browser and prints it in the app log: @@ -123,6 +133,93 @@ Sign in with the seeded admin, `admin@glenloch.local`. Other seeded accounts: `c Migrations are **not** run automatically by `docker compose up`. Re-run the `migrate` command after pulling schema changes. The seed is idempotent. +## Deploying the combined stack on another system + +One clone deploys everything: the dashboard (`app`), the advanced photo editor +(`lumenroom`, vendored under `lumenroom/`) and PostgreSQL (`db`). The detailed +Ubuntu walkthrough below covers each step; this is the short version for moving +the stack to a new host. + +**What the target host needs** + +- Docker Engine 24+ with Compose v2, and sudo access. +- A DNS name per app (for example `media.example.org` and `edit.example.org`), + or the host's LAN IP if it is not exposed to the internet. +- Inbound TCP 80 and 443 only. Ports 3000, 5433 and 8787 stay on the private + interface (`APP_BIND`, `POSTGRES_BIND`, `LUMENROOM_BIND` = `127.0.0.1`). +- The media export mounted on the host for original photos and videos + ([step 9](#9-media-storage-on-nfs-or-a-local-path-required-for-event-media)). + +**Get the code and secrets** + +```bash +git clone /opt/glenloch-media +cd /opt/glenloch-media +cp .env.example .env +chmod 600 .env + +openssl rand -base64 32 # NEXTAUTH_SECRET +openssl rand -hex 32 # CRON_SECRET +openssl rand -hex 24 # POSTGRES_PASSWORD (hex avoids URL encoding) +openssl rand -hex 32 # BRIDGE_SECRET, shared by app and lumenroom +``` + +Minimum `.env` for both containers: + +```dotenv +NEXTAUTH_URL=https://media.example.org +NEXTAUTH_SECRET= +PUBLIC_ORIGIN=https://media.example.org +APP_ORIGIN=https://media.example.org +APP_BIND=127.0.0.1 +POSTGRES_BIND=127.0.0.1 +POSTGRES_USER=media +POSTGRES_PASSWORD= +POSTGRES_DB=media +DATABASE_URL=postgres://media:@localhost:5433/media +CRON_SECRET= +MEDIA_ARCHIVE_DIR=/mnt/glenloch-media + +# Advanced editor bridge +LUMENROOM_URL=https://edit.example.org +LUMENROOM_BIND=127.0.0.1 +BRIDGE_SECRET= +``` + +`BRIDGE_SECRET` is passed to both services from this one value; they must match. +`LUMENROOM_URL` is the browser-facing editor address, while the app reaches +Lumenroom inside the Compose network by service name. + +**Build, migrate, start** + +```bash +docker compose config --quiet +docker compose up -d db +docker compose --profile tools build migrate +docker compose --profile tools run --rm migrate +docker compose up -d --build app lumenroom +docker compose ps +curl -fsS http://127.0.0.1:3000/api/health +curl -fsS http://127.0.0.1:8787/api/health +``` + +Both `app` and `lumenroom` must be `healthy`. `docker compose up -d --build` +without a service name also works and builds both images; naming them is just an +explicit version of the same command. + +**Finish and verify** + +1. Complete first sign-in and admin bootstrap ([step 5](#5-first-sign-in-and-admin-bootstrap)). +2. Save the media share in Settings → Media storage ([step 9](#9-media-storage-on-nfs-or-a-local-path-required-for-event-media)). +3. Put both hostnames in the reverse proxy ([step 6](#6-reverse-proxy-and-tls-with-caddy)) and reload Caddy. +4. Open an event photo and click **Advanced**: the editor should open in a new tab, already signed in, with a banner showing **Save to event**. If it reports the editor is not configured, `BRIDGE_SECRET` or `LUMENROOM_URL` is missing or the two secrets differ. + +**Moving an existing installation.** Run Admin → Backup & restore on the old +host, copy the ZIP and `.env` (especially `NEXTAUTH_SECRET`) to the new host, +bring the stack up as above, then restore through the same admin panel. Original +media comes from the ZIP or the share itself. The `lumenroom-data` volume holds +only temporary bridge data and does not need to move. + ## Local development ```bash @@ -176,6 +273,8 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `. | `UPLOAD_DIR` | Training attachments only (`/tmp/uploads` in compose). Event photos and videos never live here. | | `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Mount path inside the container, the reported share, and the default folder. This is the primary storage for original event photos and videos; a named share plus a writable path is required or uploads and photo editing stay disabled. | | `MEDIA_ARCHIVE_DIR` | **Compose-only host path** mounted at `/archive` for the NFS export. | +| `LUMENROOM_URL`, `BRIDGE_SECRET` | Advanced editor bridge: the browser-facing address of the Lumenroom container and the shared token secret. Both are required for the **Advanced** button; leave empty to run without the editor. | +| `LUMENROOM_PORT`, `LUMENROOM_BIND` | **Compose-only** host publishing for Lumenroom. Default `8787` on all interfaces; set `127.0.0.1` behind a reverse proxy. | | `SENTRY_DSN` | Declared but not wired to any integration. | Volumes in Compose: `pgdata`, `outbox-data`, `uploads-data`, and either `archive-data` or the host `MEDIA_ARCHIVE_DIR` bind mount (the latter is what holds original photos and videos). Back these up together. @@ -327,6 +426,11 @@ MAGIC_LINK_DEV_TRANSPORT=true CRON_SECRET= POSTMARK_FROM=media@example.org # POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead + +# Advanced photo editor (optional; omit to run without it) +LUMENROOM_URL=https://edit.example.org +LUMENROOM_BIND=127.0.0.1 +BRIDGE_SECRET= ``` Notes: @@ -348,9 +452,10 @@ docker compose config --quiet docker compose up -d db docker compose --profile tools build migrate docker compose --profile tools run --rm migrate -docker compose up -d --build app +docker compose up -d --build app lumenroom docker compose ps curl -fsS http://127.0.0.1:3000/api/health +curl -fsS http://127.0.0.1:8787/api/health ``` Rebuild `migrate` as shown; `docker compose run` reuses the last built tools image, so without the build step an update can run stale seed code against a newer schema. @@ -401,8 +506,18 @@ media.example.org { encode zstd gzip reverse_proxy 127.0.0.1:3000 } + +edit.example.org { + reverse_proxy 127.0.0.1:8787 +} ``` +The second site is the advanced editor. Give it the same pattern as the app: +set `LUMENROOM_BIND=127.0.0.1` and `LUMENROOM_URL=https://edit.example.org`, and +point DNS for that hostname at the server too. If you leave the editor out, +remove its site block and set no `BRIDGE_SECRET`; the **Advanced** button then +reports that the editor is not configured. + ```bash sudo caddy validate --config /etc/caddy/Caddyfile sudo systemctl reload caddy @@ -421,7 +536,7 @@ sudo ufw enable sudo ufw status ``` -`APP_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app and database off the public interface. +`APP_BIND=127.0.0.1`, `LUMENROOM_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app, the editor and the database off the public interface; only Caddy listens on 80/443. ### 8. Background jobs (cron) @@ -541,6 +656,10 @@ Use Admin → Backup & restore to download a ZIP of the database dump, uploads, At minimum, back up after every schedule/training/media milestone and before every upgrade. The database, uploads, and archive volumes live under Docker's volume directory; the application-level ZIP is the supported portable backup. +The `lumenroom-data` volume is different: it holds only Lumenroom's temporary +bridge catalog, cached previews and thumbnails, so it can be left out of backups +and rebuilt by opening events again. + ### 12. Updating the deployment Take a backup, then: @@ -550,9 +669,10 @@ cd /opt/glenloch-media git pull --ff-only docker compose --profile tools build migrate docker compose --profile tools run --rm migrate -docker compose up -d --build app +docker compose up -d --build app lumenroom docker compose ps curl -fsS http://127.0.0.1:3000/api/health +curl -fsS http://127.0.0.1:8787/api/health ``` `migrate` is idempotent and also runs the seed, which does not duplicate authored lessons or existing rows. If a release is bad, rebuild the previous commit: @@ -560,7 +680,7 @@ curl -fsS http://127.0.0.1:3000/api/health ```bash git log --oneline -5 git checkout -docker compose up -d --build app +docker compose up -d --build app lumenroom # after fixing: git switch main ``` @@ -578,6 +698,8 @@ git switch main | Uploads/editing are disabled | Settings → Media storage needs a share name and a mounted path that UID 100 can write to; the banner states the exact failure. | | Uploads are blocked with "not a network mount" | The export is not actually mounted: either add `docker-compose.nfs.yml` (`NFS_ADDR`/`NFS_EXPORT`) or mount it on the host and point `MEDIA_ARCHIVE_DIR` at that mount. `docker compose exec app grep ' /archive ' /proc/self/mounts` shows what the container really has. | | Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. | +| **Advanced** reports the editor is not configured | `LUMENROOM_URL` and `BRIDGE_SECRET` are set in the app's environment, and Lumenroom has the same `BRIDGE_SECRET`. Restart both: `docker compose up -d app lumenroom`. | +| Advanced opens but the editor fails to load or is blank | `docker compose ps` should show `lumenroom` as `healthy`; `curl -fsS http://127.0.0.1:8787/api/health`; check `LUMENROOM_URL` is reachable from users' browsers and the proxy forwards `edit.example.org` to `127.0.0.1:8787`. | | Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. | ### 14. Production checklist @@ -592,6 +714,8 @@ git switch main - [ ] Cron jobs installed and returning success. - [ ] Backup downloaded, stored off-host, and restore tested once. - [ ] Media storage share configured in Settings → Media storage and writable (required for event photos and videos). +- [ ] `LUMENROOM_BIND=127.0.0.1`, `LUMENROOM_URL` set to the editor's HTTPS origin, and `BRIDGE_SECRET` identical in both containers. +- [ ] `edit.example.org` (or the chosen editor hostname) proxies to `127.0.0.1:8787`, and **Advanced** opens the editor signed in. - [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary. ### 15. Advanced photo editor bridge (optional) @@ -610,12 +734,16 @@ that bridge session expires (12 hours by default). **One deployment.** Lumenroom is vendored under `lumenroom/`, and `docker-compose.yml` builds it as a second service next to the app. One clone -and one command deploy both: +and one command deploy both (add `--build` when the sources changed): ```bash -docker compose up -d --build +docker compose up -d --build app lumenroom ``` +Deployment steps are in [Deploying the combined stack on another +system](#deploying-the-combined-stack-on-another-system); the editor only needs +the extra `LUMENROOM_*` and `BRIDGE_SECRET` values shown there. + Values in `.env` (all optional except the secret): ```dotenv @@ -692,7 +820,7 @@ that the gallery shows. │ ├── domain/ Pure, unit-tested business rules │ └── lib/ Timezone, tokens, email, storage, media, backup helpers ├── Dockerfile Multi-stage build; tools stage for migrations -├── docker-compose.yml App + Postgres + one-shot migrate/seed +├── docker-compose.yml App + Lumenroom + Postgres + one-shot migrate/seed ├── drizzle.config.ts ├── next.config.ts ├── playwright.config.ts diff --git a/lumenroom/server/bridge.mjs b/lumenroom/server/bridge.mjs index 4256b07..ac77b75 100644 --- a/lumenroom/server/bridge.mjs +++ b/lumenroom/server/bridge.mjs @@ -9,7 +9,7 @@ import crypto from 'node:crypto'; import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs'; -import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs'; +import { db, getPhoto, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs'; import { removeAsset } from './storage.mjs'; const VERSION = 'g1'; @@ -173,11 +173,17 @@ function photoRecordFrom(photo, eventId, sessionId, index) { meta: {}, thumb: '', thumbUrl: `/api/photos/${id}/thumb`, + // Thumbnail of the saved edit; the timestamp keeps the browser from reusing + // a thumbnail rendered before the edit was saved. + thumbVersion: photo.editedAt ? Date.parse(photo.editedAt) || undefined : undefined, rating: 0, flag: 'none', color: '', keywords: [], - edits: {}, + // The dashboard sends back the recipe saved for this photo, so reopening + // the advanced editor starts from the sliders the user left it with. + edits: + photo.edits && typeof photo.edits === 'object' ? photo.edits : {}, history: [], raw, previewUrl: raw ? `/api/photos/${id}/preview` : undefined, @@ -189,7 +195,7 @@ function photoRecordFrom(photo, eventId, sessionId, index) { * Mirrors one event into the local catalog. The photo bytes stay on the * dashboard; only metadata, previews and thumbnails are temporary here. */ -export async function importBridgeEvent({ serviceToken, sessionId }) { +export async function importBridgeEvent({ serviceToken, sessionId, returnUrl }) { const expiresAt = Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000; @@ -198,12 +204,35 @@ export async function importBridgeEvent({ serviceToken, sessionId }) { serviceToken, ); const eventId = bridgeEventId(listing.event.id); + // Preserve anything still unsaved locally before the import replaces rows, so + // reopening the editor never discards work in progress. + const localEdits = new Map(); + for (const row of photosForEvent.all(eventId)) { + const record = getPhoto(row.id); + if (record?.edits && Object.keys(record.edits).length > 0) { + localEdits.set(row.id, record); + } + } dropBridgeEvent(eventId); - const returnUrl = listing.editor?.returnUrl ?? null; - saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0); + // The exchange hands back the dashboard address the browser actually used; + // the listing's value is a fallback derived from server configuration and may + // point at localhost in a LAN deployment. + const dashboardReturn = + typeof returnUrl === 'string' && /^https?:\/\//i.test(returnUrl) + ? returnUrl + : listing.editor?.returnUrl ?? null; + saveEvent(eventRecordFrom(listing, eventId, sessionId, dashboardReturn, expiresAt), 0); listing.photos.forEach((photo, index) => { - savePhoto(photoRecordFrom(photo, eventId, sessionId, index)); + const record = photoRecordFrom(photo, eventId, sessionId, index); + const local = localEdits.get(record.id); + if (local) { + record.edits = local.edits; + if (Array.isArray(local.history) && local.history.length > 0) { + record.history = local.history; + } + } + savePhoto(record); }); bridgeInsert.run( eventId, @@ -211,7 +240,7 @@ export async function importBridgeEvent({ serviceToken, sessionId }) { serviceToken, GLENLOCH_URL, listing.event.id, - returnUrl, + dashboardReturn, expiresAt, Date.now(), ); diff --git a/lumenroom/server/index.mjs b/lumenroom/server/index.mjs index c280634..077ebc8 100644 --- a/lumenroom/server/index.mjs +++ b/lumenroom/server/index.mjs @@ -39,6 +39,7 @@ import { findPreview, findThumb, removeAsset, + removeThumb, storageBytes, writeOriginal, writePreview, @@ -302,6 +303,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => { const imported = await importBridgeEvent({ serviceToken: service.token, sessionId: payload.sid, + returnUrl: service.returnUrl, }); const sessionToken = createSession(row.id); res.writeHead(302, { @@ -459,7 +461,17 @@ route('POST', '/api/bridge/export', async ({ req, res }) => { if (result.status >= 400) { return error(res, result.status, result.body?.error || 'The edit could not be saved to the event'); } - return json(res, 200, result.body ?? { ok: true }); + + // The grid now shows the dashboard's thumbnail of this render, so drop the + // cached copy and bump the URL the browser asks for. + await removeThumb(body.photoId).catch(() => undefined); + const thumbVersion = Date.now(); + const stored = getPhoto(body.photoId); + if (stored) { + stored.thumbVersion = thumbVersion; + savePhoto(stored); + } + return json(res, 200, { ...(result.body ?? { ok: true }), thumbVersion }); }); route('PUT', '/api/photos/:id', async ({ req, res, params }) => { diff --git a/lumenroom/server/storage.mjs b/lumenroom/server/storage.mjs index 5a106bb..a6682c5 100644 --- a/lumenroom/server/storage.mjs +++ b/lumenroom/server/storage.mjs @@ -70,6 +70,12 @@ export function findThumb(id) { return fs.existsSync(p) ? p : null; } +/** Drops the cached grid thumbnail so the next request refetches it. */ +export async function removeThumb(id) { + const thumb = findThumb(id); + if (thumb) await fsp.rm(thumb, { force: true }); +} + export async function removeAsset(id) { const files = [findOriginal(id), findPreview(id), findThumb(id)]; await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve()))); diff --git a/lumenroom/src/App.tsx b/lumenroom/src/App.tsx index 61825b1..035743c 100644 --- a/lumenroom/src/App.tsx +++ b/lumenroom/src/App.tsx @@ -653,15 +653,22 @@ export default function App() { height: activePhoto.height, }), }); - const data = (await res.json().catch(() => ({}))) as { error?: string }; + const data = (await res.json().catch(() => ({}))) as { + error?: string; + thumbVersion?: number; + }; if (!res.ok) throw new Error(data.error || 'The photo could not be saved'); + if (typeof data.thumbVersion === 'number') { + // Refresh the grid thumbnail so it shows this render, not the original. + updatePhoto(activePhoto.id, { thumbVersion: data.thumbVersion }); + } setToast(`Saved ${activePhoto.name} to the event`); } catch (err) { setToast(err instanceof Error ? err.message : 'The photo could not be saved'); } finally { setBridgeBusy(false); } - }, [activePhoto, bridgeEvent]); + }, [activePhoto, bridgeEvent, updatePhoto]); const handleCloudLogin = useCallback( async (email: string, password: string) => { diff --git a/lumenroom/src/components/Develop.tsx b/lumenroom/src/components/Develop.tsx index 9b7f3fd..b121055 100644 --- a/lumenroom/src/components/Develop.tsx +++ b/lumenroom/src/components/Develop.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits'; -import { getBitmap } from '../lib/images'; +import { getBitmap, thumbSrc } from '../lib/images'; import { rotatedBounds, Renderer } from '../gl/renderer'; import type { Edits, EventRecord, PhotoRecord, Preset } from '../types'; import ContextMenu, { type MenuEntry } from './ContextMenu'; @@ -703,7 +703,7 @@ export default function Develop({ title={p.name} > {p.name}
{p.name}
{photo.name} diff --git a/lumenroom/src/lib/edits.ts b/lumenroom/src/lib/edits.ts index 41444c8..0a33827 100644 --- a/lumenroom/src/lib/edits.ts +++ b/lumenroom/src/lib/edits.ts @@ -266,6 +266,7 @@ export function normalizePhoto(input: Partial & { id: string }): Ph decode: input.decode, previewUrl: input.previewUrl, thumbUrl: input.thumbUrl, + thumbVersion: input.thumbVersion, name: input.name ?? 'Untitled', width: input.width ?? 0, height: input.height ?? 0, diff --git a/lumenroom/src/lib/images.ts b/lumenroom/src/lib/images.ts index a064b7f..114beec 100644 --- a/lumenroom/src/lib/images.ts +++ b/lumenroom/src/lib/images.ts @@ -4,6 +4,17 @@ import { getAsset, putAsset } from './db'; const CACHE_LIMIT = 6; const cache = new Map(); +/** + * Grid/filmstrip thumbnail URL. The version stamp changes when the saved edit is + * re-rendered, so the browser does not keep showing the pre-edit thumbnail. + */ +export function thumbSrc(photo: PhotoRecord): string { + if (!photo.thumbUrl) return photo.thumb; + return photo.thumbVersion + ? `${photo.thumbUrl}?v=${photo.thumbVersion}` + : photo.thumbUrl; +} + /** Where to fetch the original (or raw proxy) when it is not cached on this device. */ export function remoteAssetUrl(photo: PhotoRecord): string { if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`; diff --git a/lumenroom/src/styles.css b/lumenroom/src/styles.css index 17a5062..00d22b4 100644 --- a/lumenroom/src/styles.css +++ b/lumenroom/src/styles.css @@ -562,6 +562,9 @@ img { overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + /* Keep every row at its natural height. Without this, a large library makes + the auto rows shrink to fit the viewport and the thumbnails collapse. */ + grid-auto-rows: max-content; gap: 12px; padding: 14px; align-content: start; diff --git a/lumenroom/src/types.ts b/lumenroom/src/types.ts index c0adc8c..4e19a48 100644 --- a/lumenroom/src/types.ts +++ b/lumenroom/src/types.ts @@ -103,6 +103,8 @@ export interface PhotoRecord { previewUrl?: string; /** server URL for the grid thumbnail */ thumbUrl?: string; + /** bumps the thumbnail URL whenever the saved edit is re-rendered */ + thumbVersion?: number; /** Set when the photo is proxied from a dashboard bridge session. */ bridgeSource?: { sessionId: string; sourceId: string }; } diff --git a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx index 028cbdd..7f6d418 100644 --- a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx +++ b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx @@ -10,6 +10,7 @@ import { } from "@/lib/event-photos"; import { mediaStorage } from "@/lib/media-storage"; import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments"; +import { advancedEditViewFor } from "@/lib/advanced-edit"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { @@ -64,9 +65,12 @@ export default async function EventFolderPage({ previewable: isBrowserRenderablePhoto(photo.filename), editable: isEditableEventPhoto(photo.filename), adjustments: parseStoredPhotoAdjustments(photo.editJson), + advancedEdit: Boolean(photo.advancedEditJson), + advancedSummary: advancedEditViewFor(photo.advancedEditJson), editedAt: photo.editedAt ? photo.editedAt.toISOString() : null, editedSizeBytes: photo.editedSizeBytes, })); + const editedCount = photos.filter((photo) => photo.editedAt).length; return (
@@ -104,6 +108,17 @@ export default async function EventFolderPage({ )} + {editedCount > 0 && ( + + )}
diff --git a/src/app/(app)/events/[id]/page.tsx b/src/app/(app)/events/[id]/page.tsx index fb38c90..9c87409 100644 --- a/src/app/(app)/events/[id]/page.tsx +++ b/src/app/(app)/events/[id]/page.tsx @@ -5,6 +5,7 @@ import { auth } from "@/auth/config"; import type { SystemRole } from "@/auth/roles"; import { getEventDetail, listAssignableUsers } from "@/db/events"; import { listEventVideos } from "@/db/videos"; +import { bridgeConfigured } from "@/lib/bridge"; import { formatVideoDuration } from "@/lib/event-videos"; import { getStorageSettings } from "@/db/storage-settings"; import { mediaStorage } from "@/lib/media-storage"; @@ -17,6 +18,7 @@ import { } from "@/components/app/events/photographer-panel"; import { FolderCreateForm } from "@/components/app/events/folder-create-form"; import { DeleteEventButton } from "@/components/app/events/delete-event-button"; +import { AdvancedEditorButton } from "@/components/app/events/advanced-editor-button"; import { ArchiveEventButton } from "@/components/app/events/archive-event-button"; import { VideoUploadForm } from "@/components/app/media/video-upload-form"; import { Button } from "@/components/ui/button"; @@ -99,6 +101,9 @@ export default async function EventDetailPage({ {event.event.eventType}
+ {bridgeConfigured() && ( + + )} {event.event.photoCount > 0 && ( + {error && ( + + {error} + + )} + + ); +} diff --git a/src/components/app/events/photo-gallery.tsx b/src/components/app/events/photo-gallery.tsx index 7c1fa75..2bb6492 100644 --- a/src/components/app/events/photo-gallery.tsx +++ b/src/components/app/events/photo-gallery.tsx @@ -8,6 +8,40 @@ import { Badge } from "@/components/ui/badge"; import { Input } from "@/components/ui/input"; import { PhotoViewer, type ViewerPhoto } from "./photo-viewer"; import type { PhotoAdjustments } from "@/lib/photo-adjustments"; +import type { AdvancedEditView } from "@/lib/advanced-edit"; + +/** + * Grid image that degrades to a readable tile instead of a blank square when + * the thumbnail cannot be produced (damaged or unsupported RAW, missing file). + */ +function GalleryImage({ src, alt }: { src: string; alt: string }) { + const [failed, setFailed] = useState(false); + + if (failed) { + return ( +
+
+ ); + } + + return ( + // Frames are private; the serving route sets the cache policy. + // eslint-disable-next-line @next/next/no-img-element + {alt} setFailed(true)} + className="h-full w-full object-cover" + /> + ); +} export interface GalleryPhoto { id: string; @@ -19,6 +53,10 @@ export interface GalleryPhoto { previewable: boolean; editable: boolean; adjustments: PhotoAdjustments; + /** The saved edit was produced by the advanced (Lumenroom) editor. */ + advancedEdit: boolean; + /** Read-only view of the advanced recipe and a quick-editor seed. */ + advancedSummary: AdvancedEditView | null; editedAt: string | null; editedSizeBytes: number | null; } @@ -303,15 +341,7 @@ export function PhotoGallery({ onClick={() => setViewing(photo)} > {photo.previewable || photo.editedAt || photo.kind === "raw" ? ( - // Frames are private; the serving route sets the cache policy. - // eslint-disable-next-line @next/next/no-img-element - {photo.filename} + ) : (
- - + {photo.editedAt ? ( + <> + + + + Original + + + ) : ( + + + )} {editable && ( +

+ Loads these values into the sliders. Saving then retires + the advanced recipe and renders from the original file. +

+ + )} +
+ + )} +
{TABS.map((item) => (
)} + {takeOverMessage && !saveError && ( +

+ {takeOverMessage} +

+ )} + + {saveResult && + (saveResult.unchanged ? ( +

+ No changes to apply — the saved version is already the + advanced editor's render. Move a slider to save your own + adjustments on top of it. +

+ ) : ( +
+

Full-resolution JPEG saved.

+

+ {saveResult.width > 0 && saveResult.height > 0 + ? `${saveResult.width} × ${saveResult.height} · ` + : ""} + {formatBytes(saveResult.editedSizeBytes)} +

+
+ ))} + {hasSavedEdit && (

Download JPEG

diff --git a/src/db/bridge.ts b/src/db/bridge.ts index 38d6769..32adab0 100644 --- a/src/db/bridge.ts +++ b/src/db/bridge.ts @@ -112,6 +112,12 @@ export interface BridgePhotoRow { sizeBytes: number; storedName: string; editedStoredName: string | null; + /** Recipe saved by the advanced editor, so a reopen can restore its sliders. */ + advancedEditJson: string | null; + /** Recipe from the simple editor, layered on top of the advanced render. */ + editJson: string | null; + /** When the saved edit was rendered; stamps the thumbnail cache. */ + editedAt: Date | null; createdAt: Date; folderName: string; } @@ -128,6 +134,9 @@ export async function listBridgePhotos( sizeBytes: eventPhotos.sizeBytes, storedName: eventPhotos.storedName, editedStoredName: eventPhotos.editedStoredName, + advancedEditJson: eventPhotos.advancedEditJson, + editJson: eventPhotos.editJson, + editedAt: eventPhotos.editedAt, createdAt: eventPhotos.createdAt, folderName: eventFolders.name, }) @@ -150,6 +159,9 @@ export async function getBridgePhoto( sizeBytes: eventPhotos.sizeBytes, storedName: eventPhotos.storedName, editedStoredName: eventPhotos.editedStoredName, + advancedEditJson: eventPhotos.advancedEditJson, + editJson: eventPhotos.editJson, + editedAt: eventPhotos.editedAt, createdAt: eventPhotos.createdAt, folderName: eventFolders.name, }) diff --git a/src/db/events.ts b/src/db/events.ts index f833639..2b75589 100644 --- a/src/db/events.ts +++ b/src/db/events.ts @@ -73,6 +73,7 @@ export interface EventPhotoRow { checksumSha256: string; kind: "raw" | "image"; editJson: string | null; + advancedEditJson: string | null; editedStoredName: string | null; editedSizeBytes: number | null; editedAt: Date | null; @@ -374,6 +375,7 @@ export async function getFolderDetail( checksumSha256: eventPhotos.checksumSha256, kind: eventPhotos.kind, editJson: eventPhotos.editJson, + advancedEditJson: eventPhotos.advancedEditJson, editedStoredName: eventPhotos.editedStoredName, editedSizeBytes: eventPhotos.editedSizeBytes, editedAt: eventPhotos.editedAt, @@ -672,11 +674,16 @@ export async function updateEventPhotoEdit(input: { editedStoredName: string; editedSizeBytes: number; editedBy: string; + /** True when the quick editor takes the look over from the advanced render. */ + clearAdvancedEdit?: boolean; }) { const [row] = await db .update(eventPhotos) .set({ + // The simple recipe is applied on top of any advanced render, so the + // advanced recipe is kept and both editors stay in sync. editJson: input.editJson, + ...(input.clearAdvancedEdit ? { advancedEditJson: null } : {}), editedStoredName: input.editedStoredName, editedSizeBytes: input.editedSizeBytes, editedAt: new Date(), diff --git a/src/lib/advanced-edit.test.ts b/src/lib/advanced-edit.test.ts new file mode 100644 index 0000000..0132e5d --- /dev/null +++ b/src/lib/advanced-edit.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from "vitest"; +import { + advancedEditViewFor, + advancedToQuickAdjustments, + parseAdvancedRecipe, +} from "./advanced-edit"; +import { defaultPhotoAdjustments } from "./photo-adjustments"; + +const ADVANCED = { + exposure: 0.4, + contrast: 26, + highlights: -12, + shadows: 8, + whites: 10, + blacks: -14, + texture: 20, + clarity: 16, + dehaze: 0, + vibrance: 0, + saturation: 0, + temp: 6, + tint: -3, + bw: true, + bwFilter: "red", + bwFilterAmount: 100, + curve: { + rgb: [ + { x: 0, y: 0 }, + { x: 0.35, y: 0.42 }, + { x: 1, y: 1 }, + ], + red: [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, + ], + green: [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, + ], + blue: [ + { x: 0, y: 0 }, + { x: 1, y: 0.9 }, + ], + }, + hsl: { hue: [0, 0, 0, 0, 0, 0, 0, 0], sat: [0, 0, 0, 0, 0, 0, 0, 0], lum: [0, 0, 0, 0, 0, 0, 0, 0] }, + grading: { shadows: { h: 210, s: 0 }, highlights: { h: 45, s: 0 }, balance: 0 }, + sharpen: { amount: 40, radius: 1.4, detail: 30 }, + noise: { luminance: 12, detail: 50 }, + vignette: { amount: -18, midpoint: 50, feather: 50 }, + grain: { amount: 14, size: 30, roughness: 50 }, + crop: { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: "original", flipH: false, flipV: false }, +}; + +describe("advanced edit view", () => { + it("ignores photos without an advanced recipe", () => { + expect(advancedEditViewFor(null)).toBeNull(); + expect(advancedEditViewFor("")).toBeNull(); + expect(advancedEditViewFor("{}")).toBeNull(); + expect(advancedEditViewFor("not json")).toBeNull(); + }); + + it("maps the tone and colour sliders onto the quick recipe", () => { + const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify(ADVANCED))!); + expect(seed.exposure).toBe(0.4); + expect(seed.contrast).toBe(26); + expect(seed.highlights).toBe(-12); + expect(seed.whites).toBe(10); + expect(seed.blacks).toBe(-14); + expect(seed.clarity).toBe(16); + expect(seed.temperature).toBe(6); + expect(seed.tint).toBe(-3); + expect(seed.sharpen).toBe(40); + expect(seed.noiseReduction).toBe(12); + expect(seed.vignette).toBe(-18); + expect(seed.grain).toBe(14); + // A black-and-white advanced edit becomes the quick grey conversion. + expect(seed.saturation).toBe(-100); + }); + + it("samples the advanced master curve with anchors for the quick curve", () => { + const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify(ADVANCED))!); + expect(seed.curves[0].x).toBe(0); + expect(seed.curves[seed.curves.length - 1].x).toBe(1); + // The lifted midtone survives in the sampled curve. + const atMid = seed.curves.reduce((best, point) => + Math.abs(point.x - 0.5) < Math.abs(best.x - 0.5) ? point : best, + ); + expect(atMid.y).toBeGreaterThan(atMid.x); + }); + + it("lists the settings the quick editor cannot hold", () => { + const view = advancedEditViewFor(JSON.stringify(ADVANCED))!; + expect(view.onlyAdvanced).toEqual( + expect.arrayContaining([ + "Texture", + "red black & white filter", + "Sharpening radius and detail", + "Per-channel curves", + ]), + ); + const flat = view.sections.flatMap((section) => section.items.map((item) => item.label)); + expect(flat).toContain("Contrast"); + expect(flat).toContain("Black & white"); + expect(flat).not.toContain("Dehaze"); + }); + + it("converts rotation and a crop into the quick geometry", () => { + const view = advancedEditViewFor( + JSON.stringify({ + crop: { x: 0.1, y: 0, w: 0.8, h: 0.8, angle: 3, quarter: 1, aspect: "1:1", flipH: false, flipV: true }, + }), + )!; + expect(view.seed.rotation).toBe(90); + expect(view.seed.straighten).toBe(3); + expect(view.seed.crop.aspect).toBe("1:1"); + expect(view.seed.crop.zoom).toBeCloseTo(1.25, 3); + expect(view.onlyAdvanced).toContain("Flip"); + expect(view.caveats.length).toBeGreaterThan(0); + }); + + it("leaves a neutral recipe with the neutral quick adjustments", () => { + const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify({ exposure: 0 }))!); + expect(seed).toEqual(defaultPhotoAdjustments()); + }); +}); diff --git a/src/lib/advanced-edit.ts b/src/lib/advanced-edit.ts new file mode 100644 index 0000000..23dad02 --- /dev/null +++ b/src/lib/advanced-edit.ts @@ -0,0 +1,571 @@ +/** + * Read the advanced (Lumenroom) recipe stored on an event photo. + * + * The two editors are separate applications with separate recipes. This module + * translates the advanced recipe into the quick editor's controls so the photo + * page can show what the advanced editor did, and so a photographer can hand + * the look over to the quick sliders. The translation is deliberately lossy: + * controls the quick editor has no equivalent for are reported instead of being + * silently dropped. + */ + +import { + MAX_CURVE_POINTS, + PHOTO_ADJUSTMENT_LIMITS, + createCurveEvaluator, + defaultPhotoAdjustments, + normalizePhotoAdjustments, + type CurvePoint, + type PhotoAdjustments, + type PhotoCropAspect, + type PhotoRotation, +} from "./photo-adjustments"; + +export interface AdvancedRecipe { + temp: number; + tint: number; + exposure: number; + contrast: number; + highlights: number; + shadows: number; + whites: number; + blacks: number; + texture: number; + clarity: number; + dehaze: number; + vibrance: number; + saturation: number; + bw: boolean; + bwFilter: string; + curve: { rgb: CurvePoint[]; red: CurvePoint[]; green: CurvePoint[]; blue: CurvePoint[] }; + hsl: { hue: number[]; sat: number[]; lum: number[] }; + grading: { shadows: number; highlights: number }; + sharpen: { amount: number; radius: number; detail: number }; + noise: { luminance: number; detail: number }; + vignette: { amount: number; midpoint: number; feather: number }; + grain: { amount: number; size: number; roughness: number }; + crop: { + x: number; + y: number; + w: number; + h: number; + angle: number; + quarter: number; + aspect: string; + flipH: boolean; + flipV: boolean; + }; +} + +/** Quick-editor controls that take a single number. */ +export type QuickNumericSetting = Exclude< + keyof PhotoAdjustments, + "curves" | "crop" | "rotation" +>; + +export interface AdvancedEditItem { + label: string; + value: string; + /** The quick-editor control that shows this setting on its own. */ + preview?: { key: QuickNumericSetting; amount: number }; +} + +export interface AdvancedEditView { + /** Non-neutral settings, grouped for display. */ + sections: { title: string; items: AdvancedEditItem[] }[]; + /** Settings the quick editor has no control for. */ + onlyAdvanced: string[]; + /** Notes about values that were mapped approximately. */ + caveats: string[]; + /** Quick-editor recipe that reproduces the advanced look as closely as possible. */ + seed: PhotoAdjustments; +} + +const IDENTITY: CurvePoint[] = [ + { x: 0, y: 0 }, + { x: 1, y: 1 }, +]; + +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)); +} + +function round(value: number, places = 2): number { + const factor = 10 ** places; + return Math.round(value * factor) / factor; +} + +function num(value: unknown, fallback: number, min: number, max: number): number { + return typeof value === "number" && Number.isFinite(value) + ? clamp(value, min, max) + : fallback; +} + +function record(value: unknown): Record { + return value && typeof value === "object" ? (value as Record) : {}; +} + +function curvePoints(value: unknown): CurvePoint[] { + if (!Array.isArray(value)) return IDENTITY; + const points = value + .map((entry) => record(entry)) + .filter((entry) => typeof entry.x === "number" && typeof entry.y === "number") + .map((entry) => ({ + x: clamp(entry.x as number, 0, 1), + y: clamp(entry.y as number, 0, 1), + })) + .sort((a, b) => a.x - b.x); + return points.length >= 2 ? points : IDENTITY; +} + +function bands(value: unknown): number[] { + if (!Array.isArray(value)) return []; + return value + .filter((entry): entry is number => typeof entry === "number" && Number.isFinite(entry)) + .map((entry) => round(entry, 1)); +} + +function isNeutralBandList(values: number[]): boolean { + return values.every((value) => value === 0); +} + +export function isIdentityCurve(points: readonly CurvePoint[]): boolean { + if (points.length !== 2) return false; + return ( + Math.abs(points[0].x) < 1e-6 && + Math.abs(points[0].y) < 1e-6 && + Math.abs(points[1].x - 1) < 1e-6 && + Math.abs(points[1].y - 1) < 1e-6 + ); +} + +/** Parse the advanced recipe JSON; null when no recipe was saved. */ +export function parseAdvancedRecipe(json: string | null | undefined): AdvancedRecipe | null { + if (!json) return null; + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch { + return null; + } + if (!parsed || typeof parsed !== "object" || Object.keys(parsed).length === 0) { + return null; + } + + const raw = parsed as Record; + const curve = record(raw.curve); + const hsl = record(raw.hsl); + const grading = record(raw.grading); + const gradingShadows = record(grading.shadows); + const gradingHighlights = record(grading.highlights); + const sharpen = record(raw.sharpen); + const noise = record(raw.noise); + const vignette = record(raw.vignette); + const grain = record(raw.grain); + const crop = record(raw.crop); + + return { + temp: num(raw.temp, 0, -100, 100), + tint: num(raw.tint, 0, -100, 100), + exposure: num(raw.exposure, 0, -5, 5), + contrast: num(raw.contrast, 0, -100, 100), + highlights: num(raw.highlights, 0, -100, 100), + shadows: num(raw.shadows, 0, -100, 100), + whites: num(raw.whites, 0, -100, 100), + blacks: num(raw.blacks, 0, -100, 100), + texture: num(raw.texture, 0, -100, 100), + clarity: num(raw.clarity, 0, -100, 100), + dehaze: num(raw.dehaze, 0, -100, 100), + vibrance: num(raw.vibrance, 0, -100, 100), + saturation: num(raw.saturation, 0, -100, 100), + bw: raw.bw === true, + bwFilter: typeof raw.bwFilter === "string" ? raw.bwFilter : "none", + curve: { + rgb: curvePoints(curve.rgb), + red: curvePoints(curve.red), + green: curvePoints(curve.green), + blue: curvePoints(curve.blue), + }, + hsl: { + hue: bands(hsl.hue), + sat: bands(hsl.sat), + lum: bands(hsl.lum), + }, + grading: { + shadows: num(gradingShadows.s, 0, 0, 100), + highlights: num(gradingHighlights.s, 0, 0, 100), + }, + sharpen: { + amount: num(sharpen.amount, 0, 0, 150), + radius: num(sharpen.radius, 1, 0.5, 3), + detail: num(sharpen.detail, 25, 0, 100), + }, + noise: { + luminance: num(noise.luminance, 0, 0, 100), + detail: num(noise.detail, 50, 0, 100), + }, + vignette: { + amount: num(vignette.amount, 0, -100, 100), + midpoint: num(vignette.midpoint, 50, 0, 100), + feather: num(vignette.feather, 50, 0, 100), + }, + grain: { + amount: num(grain.amount, 0, 0, 100), + size: num(grain.size, 25, 10, 100), + roughness: num(grain.roughness, 50, 0, 100), + }, + crop: { + x: num(crop.x, 0, 0, 1), + y: num(crop.y, 0, 0, 1), + w: num(crop.w, 1, 0.02, 1), + h: num(crop.h, 1, 0.02, 1), + angle: num(crop.angle, 0, -45, 45), + quarter: num(crop.quarter, 0, 0, 3), + aspect: typeof crop.aspect === "string" ? crop.aspect : "original", + flipH: crop.flipH === true, + flipV: crop.flipV === true, + }, + }; +} + +/** + * Sample the advanced master curve into the quick editor's format. The quick + * curve requires points at 0 and 1, and the advanced curve may not have them. + */ +function toQuickCurve(points: CurvePoint[]): CurvePoint[] { + if (isIdentityCurve(points)) return IDENTITY; + const padded = [...points]; + if (padded[0].x > 1e-6) padded.unshift({ x: 0, y: padded[0].y }); + if (padded[padded.length - 1].x < 1 - 1e-6) { + padded.push({ x: 1, y: padded[padded.length - 1].y }); + } + const evaluate = createCurveEvaluator(padded); + const count = Math.min(MAX_CURVE_POINTS, Math.max(2, padded.length)); + return Array.from({ length: count }, (_, index) => { + const x = count === 1 ? 0 : index / (count - 1); + return { x: round(x, 4), y: round(evaluate(x), 4) }; + }); +} + +const CROP_ASPECT_RATIOS: { aspect: PhotoCropAspect; ratio: number }[] = [ + { aspect: "1:1", ratio: 1 }, + { aspect: "4:5", ratio: 4 / 5 }, + { aspect: "5:4", ratio: 5 / 4 }, + { aspect: "4:3", ratio: 4 / 3 }, + { aspect: "3:4", ratio: 3 / 4 }, + { aspect: "16:9", ratio: 16 / 9 }, + { aspect: "9:16", ratio: 9 / 16 }, +]; + +function closestAspect(width: number, height: number): PhotoCropAspect { + if (width >= 0.999 && height >= 0.999) return "original"; + const ratio = width / Math.max(1e-6, height); + let best: PhotoCropAspect = "original"; + let bestDelta = Infinity; + for (const option of CROP_ASPECT_RATIOS) { + const delta = Math.abs(ratio - option.ratio) / option.ratio; + if (delta < bestDelta) { + best = option.aspect; + bestDelta = delta; + } + } + return bestDelta <= 0.03 ? best : "original"; +} + +function isDefaultCrop(crop: AdvancedRecipe["crop"]): boolean { + return ( + crop.x === 0 && + crop.y === 0 && + crop.w >= 0.999 && + crop.h >= 0.999 && + crop.angle === 0 && + crop.quarter === 0 + ); +} + +/** Map the advanced look onto the quick editor's recipe. */ +export function advancedToQuickAdjustments(recipe: AdvancedRecipe): PhotoAdjustments { + const limits = PHOTO_ADJUSTMENT_LIMITS; + const base = defaultPhotoAdjustments(); + const quarter = ((Math.round(recipe.crop.quarter) % 4) + 4) % 4; + const zoom = clamp(1 / Math.max(0.02, Math.max(recipe.crop.w, recipe.crop.h)), 1, limits.cropZoom); + const offsetX = clamp( + (recipe.crop.x + recipe.crop.w / 2 - 0.5) / Math.max(1e-6, (1 - recipe.crop.w) / 2), + -1, + 1, + ); + const offsetY = clamp( + (recipe.crop.y + recipe.crop.h / 2 - 0.5) / Math.max(1e-6, (1 - recipe.crop.h) / 2), + -1, + 1, + ); + + const adjustments: PhotoAdjustments = { + ...base, + exposure: round(clamp(recipe.exposure, -limits.exposure, limits.exposure), 2), + contrast: Math.round(recipe.contrast), + shadows: Math.round(recipe.shadows), + highlights: Math.round(recipe.highlights), + whites: Math.round(recipe.whites), + blacks: Math.round(recipe.blacks), + brightness: 0, + clarity: Math.round(recipe.clarity), + dehaze: Math.round(recipe.dehaze), + temperature: Math.round(recipe.temp), + tint: Math.round(recipe.tint), + vibrance: Math.round(recipe.vibrance), + saturation: recipe.bw ? -100 : Math.round(recipe.saturation), + sharpen: Math.round(clamp(recipe.sharpen.amount, 0, limits.sharpen)), + noiseReduction: Math.round(clamp(recipe.noise.luminance, 0, limits.noiseReduction)), + vignette: Math.round(recipe.vignette.amount), + grain: Math.round(clamp(recipe.grain.amount, 0, limits.grain)), + curves: toQuickCurve(recipe.curve.rgb), + rotation: ((quarter * 90) % 360) as PhotoRotation, + straighten: round(clamp(recipe.crop.angle, -limits.straighten, limits.straighten), 2), + crop: { + aspect: closestAspect(recipe.crop.w, recipe.crop.h), + zoom: round(zoom, 3), + offsetX: round(offsetX, 3), + offsetY: round(offsetY, 3), + }, + }; + + return normalizePhotoAdjustments(adjustments) ?? base; +} + +function signed(value: number, suffix = ""): string { + return `${value > 0 ? "+" : ""}${value}${suffix}`; +} + +function identityAll(curves: AdvancedRecipe["curve"]): boolean { + return ( + isIdentityCurve(curves.rgb) && + isIdentityCurve(curves.red) && + isIdentityCurve(curves.green) && + isIdentityCurve(curves.blue) + ); +} + +const BW_FILTER_NAMES: Record = { + yellow: "yellow", + orange: "orange", + red: "red", + green: "green", + blue: "blue", +}; + +/** Build the read-only summary and the quick-editor seed for a stored recipe. */ +export function advancedEditViewFor( + json: string | null | undefined, +): AdvancedEditView | null { + const recipe = parseAdvancedRecipe(json); + if (!recipe) return null; + + const light: AdvancedEditItem[] = []; + const color: AdvancedEditItem[] = []; + const detail: AdvancedEditItem[] = []; + const geometry: AdvancedEditItem[] = []; + + if (recipe.exposure !== 0) { + light.push({ + label: "Exposure", + value: signed(recipe.exposure, " EV"), + preview: { key: "exposure", amount: recipe.exposure }, + }); + } + if (recipe.contrast !== 0) { + light.push({ + label: "Contrast", + value: signed(recipe.contrast), + preview: { key: "contrast", amount: recipe.contrast }, + }); + } + if (recipe.highlights !== 0) { + light.push({ + label: "Highlights", + value: signed(recipe.highlights), + preview: { key: "highlights", amount: recipe.highlights }, + }); + } + if (recipe.shadows !== 0) { + light.push({ + label: "Shadows", + value: signed(recipe.shadows), + preview: { key: "shadows", amount: recipe.shadows }, + }); + } + if (recipe.whites !== 0) { + light.push({ + label: "Whites", + value: signed(recipe.whites), + preview: { key: "whites", amount: recipe.whites }, + }); + } + if (recipe.blacks !== 0) { + light.push({ + label: "Blacks", + value: signed(recipe.blacks), + preview: { key: "blacks", amount: recipe.blacks }, + }); + } + if (recipe.texture !== 0) light.push({ label: "Texture", value: signed(recipe.texture) }); + if (recipe.clarity !== 0) { + light.push({ + label: "Clarity", + value: signed(recipe.clarity), + preview: { key: "clarity", amount: recipe.clarity }, + }); + } + if (recipe.dehaze !== 0) { + light.push({ + label: "Dehaze", + value: signed(recipe.dehaze), + preview: { key: "dehaze", amount: recipe.dehaze }, + }); + } + + if (recipe.temp !== 0) { + color.push({ + label: "Temperature", + value: signed(recipe.temp), + preview: { key: "temperature", amount: recipe.temp }, + }); + } + if (recipe.tint !== 0) { + color.push({ + label: "Tint", + value: signed(recipe.tint), + preview: { key: "tint", amount: recipe.tint }, + }); + } + if (recipe.bw) { + color.push({ + label: "Black & white", + value: "On", + preview: { key: "saturation", amount: -100 }, + }); + } + if (recipe.vibrance !== 0) { + color.push({ + label: "Vibrance", + value: signed(recipe.vibrance), + preview: { key: "vibrance", amount: recipe.vibrance }, + }); + } + if (recipe.saturation !== 0) { + color.push({ + label: "Saturation", + value: signed(recipe.saturation), + preview: { key: "saturation", amount: recipe.saturation }, + }); + } + if (!identityAll(recipe.curve)) color.push({ label: "Curve", value: "Edited" }); + if (!isNeutralBandList(recipe.hsl.hue) || !isNeutralBandList(recipe.hsl.sat) || !isNeutralBandList(recipe.hsl.lum)) { + color.push({ label: "Colour mixer", value: "Edited" }); + } + if (recipe.grading.shadows > 0 || recipe.grading.highlights > 0) { + color.push({ label: "Colour grading", value: "On" }); + } + + if (recipe.sharpen.amount !== 0) { + detail.push({ + label: "Sharpen", + value: String(recipe.sharpen.amount), + preview: { key: "sharpen", amount: recipe.sharpen.amount }, + }); + } + if (recipe.noise.luminance !== 0) { + detail.push({ + label: "Noise reduction", + value: String(recipe.noise.luminance), + preview: { key: "noiseReduction", amount: recipe.noise.luminance }, + }); + } + if (recipe.vignette.amount !== 0) { + detail.push({ + label: "Vignette", + value: signed(recipe.vignette.amount), + preview: { key: "vignette", amount: recipe.vignette.amount }, + }); + } + if (recipe.grain.amount !== 0) { + detail.push({ + label: "Grain", + value: String(recipe.grain.amount), + preview: { key: "grain", amount: recipe.grain.amount }, + }); + } + + if (!isDefaultCrop(recipe.crop)) { + if (recipe.crop.quarter !== 0) { + geometry.push({ label: "Rotate", value: `${Math.round(recipe.crop.quarter) * 90}°` }); + } + if (recipe.crop.angle !== 0) { + geometry.push({ label: "Straighten", value: signed(round(recipe.crop.angle, 1), "°") }); + } + if (recipe.crop.w < 0.999 || recipe.crop.h < 0.999) { + geometry.push({ + label: "Crop", + value: `${Math.round(recipe.crop.w * 100)}% × ${Math.round(recipe.crop.h * 100)}%`, + }); + } + if (recipe.crop.flipH || recipe.crop.flipV) { + geometry.push({ + label: "Flip", + value: recipe.crop.flipH && recipe.crop.flipV ? "Both" : recipe.crop.flipH ? "Horizontal" : "Vertical", + }); + } + } + + const onlyAdvanced: string[] = []; + if (recipe.texture !== 0) onlyAdvanced.push("Texture"); + if (recipe.bw && recipe.bwFilter !== "none") { + onlyAdvanced.push(`${BW_FILTER_NAMES[recipe.bwFilter] ?? "Coloured"} black & white filter`); + } + if (recipe.sharpen.radius !== 1 || recipe.sharpen.detail !== 25) { + onlyAdvanced.push("Sharpening radius and detail"); + } + if (recipe.noise.detail !== 50) onlyAdvanced.push("Noise detail"); + if (recipe.vignette.midpoint !== 50 || recipe.vignette.feather !== 50) { + onlyAdvanced.push("Vignette midpoint and feather"); + } + if (recipe.grain.size !== 25 || recipe.grain.roughness !== 50) { + onlyAdvanced.push("Grain size and roughness"); + } + if (!isNeutralBandList(recipe.hsl.hue) || !isNeutralBandList(recipe.hsl.sat) || !isNeutralBandList(recipe.hsl.lum)) { + onlyAdvanced.push("Colour mixer"); + } + if (recipe.grading.shadows > 0 || recipe.grading.highlights > 0) { + onlyAdvanced.push("Colour grading"); + } + if ( + !isIdentityCurve(recipe.curve.red) || + !isIdentityCurve(recipe.curve.green) || + !isIdentityCurve(recipe.curve.blue) + ) { + onlyAdvanced.push("Per-channel curves"); + } + if (recipe.crop.flipH || recipe.crop.flipV) onlyAdvanced.push("Flip"); + + const caveats: string[] = []; + if (recipe.crop.w < 0.999 || recipe.crop.h < 0.999) { + caveats.push("The crop becomes the closest quick-editor aspect and zoom; nudge it to match exactly."); + } + if (Math.abs(recipe.crop.angle) > PHOTO_ADJUSTMENT_LIMITS.straighten) { + caveats.push(`Straighten is limited to ±${PHOTO_ADJUSTMENT_LIMITS.straighten}° here.`); + } + + const sections = [ + { title: "Light", items: light }, + { title: "Colour", items: color }, + { title: "Detail", items: detail }, + { title: "Crop", items: geometry }, + ].filter((section) => section.items.length > 0); + + return { + sections, + onlyAdvanced, + caveats, + seed: advancedToQuickAdjustments(recipe), + }; +} diff --git a/src/lib/bridge.ts b/src/lib/bridge.ts index 3beb96e..cdcc653 100644 --- a/src/lib/bridge.ts +++ b/src/lib/bridge.ts @@ -24,6 +24,12 @@ export interface BridgeTokenPayload { kind: "login" | "service"; /** Unix seconds. */ exp: number; + /** + * Browser-facing URL to return to after editing. Captured from the request + * that opened the editor, because the server-to-server origin is not the + * address the user's browser used. + */ + ret?: string; } export const BRIDGE_LOGIN_TTL_SECONDS = 10 * 60; @@ -108,9 +114,15 @@ export function verifyBridgeToken( return payload as BridgeTokenPayload; } -/** Where the advanced editor sends a user back to after finishing. */ +/** + * Where the advanced editor sends a user back to after finishing. Prefer the + * configured public origin; `NEXTAUTH_URL` is only a fallback because compose + * defaults it to localhost. + */ export function bridgeReturnUrl(eventId: string): string | null { - const origin = process.env.NEXTAUTH_URL?.trim(); + const origin = ( + process.env.PUBLIC_ORIGIN?.trim() || process.env.NEXTAUTH_URL?.trim() + ); if (!origin) return null; return `${origin.replace(/\/+$/, "")}/events/${eventId}`; } diff --git a/src/lib/event-photos.ts b/src/lib/event-photos.ts index 72d02a3..ca4c3ca 100644 --- a/src/lib/event-photos.ts +++ b/src/lib/event-photos.ts @@ -160,6 +160,19 @@ export function editedStoredNameForEventPhoto( return `events/${eventId}/edits/${photoId}.jpg`; } +/** + * The advanced editor's own render. Kept apart from the final edited JPEG so + * the simple editor can layer its adjustments on top without compounding + * renders, and so re-saving in either editor keeps the other's work. + */ +export function advancedStoredNameForEventPhoto( + eventId: string, + photoId: string, +): string { + assertEventPhotoIds(eventId, photoId); + return `events/${eventId}/edits/${photoId}-advanced.jpg`; +} + /** Lazily generated small grid thumbnail of the untouched original. */ export function thumbStoredNameForEventPhoto( eventId: string, @@ -196,6 +209,19 @@ export function bridgeThumbStoredNameForEventPhoto( return `events/${eventId}/previews/${photoId}-bridge-thumb.jpg`; } +/** + * Cached grid thumbnail of a photo's saved edit. Kept apart from the original + * thumbnail so the editor can reopen either, and refreshed whenever the edited + * JPEG is re-rendered. + */ +export function bridgeEditedThumbStoredNameForEventPhoto( + eventId: string, + photoId: string, +): string { + assertEventPhotoIds(eventId, photoId); + return `events/${eventId}/previews/${photoId}-bridge-thumb-edited.jpg`; +} + function assertEventPhotoIds(eventId: string, photoId: string): void { const safeId = /^[A-Za-z0-9_-]+$/; if (!safeId.test(eventId) || !safeId.test(photoId)) { diff --git a/src/lib/photo-render.ts b/src/lib/photo-render.ts index 04aab7a..eebb3fb 100644 --- a/src/lib/photo-render.ts +++ b/src/lib/photo-render.ts @@ -10,13 +10,14 @@ */ import { execFile } from "node:child_process"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readdir, rm, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import sharp from "sharp"; import { applyPhotoAdjustmentsToRgba, + defaultPhotoAdjustments, type PhotoAdjustments, } from "./photo-adjustments"; import { cropInterleavedRgb, cropRectForCanvas } from "./photo-geometry"; @@ -90,6 +91,119 @@ export interface RenderedPhoto { height: number; } +/** + * Cameras store one or more JPEG previews inside every RAW file; a full-size + * NEF preview is a ~1 MB JPEG written next to the symlink by exiv2 in about + * 10 ms. That is roughly seventy times faster than demosaicing the sensor data + * for a 640 px tile, so thumbnails try the preview first and only fall back to + * LibRaw when the camera embedded nothing big enough. + */ +async function extractEmbeddedPreview( + filePath: string, + minDimension: number, +): Promise<{ path: string; cleanup: () => Promise } | null> { + const directory = await mkdtemp(path.join(tmpdir(), "glenloch-preview-")); + const cleanup = () => rm(directory, { recursive: true, force: true }); + const link = path.join( + directory, + `source${path.extname(filePath) || ".raw"}`, + ); + + try { + // exiv2 writes the previews beside the file it is given. A symlink keeps + // the original (read-only) untouched and the output in the temp directory. + await symlink(filePath, link); + // A non-zero exit is normal when some embedded preview cannot be re-encoded + // (for example a TIFF thumbnail); the files that did land are inspected. + await execFileAsync("exiv2", ["-ep", link], { timeout: 30_000 }).catch( + () => undefined, + ); + + let best: { path: string; longEdge: number } | undefined; + for (const entry of await readdir(directory)) { + if (!/-preview\d+\.jpe?g$/i.test(entry)) continue; + const candidate = path.join(directory, entry); + try { + const metadata = await sharp(candidate, { failOn: "none" }).metadata(); + const longEdge = Math.max(metadata.width ?? 0, metadata.height ?? 0); + if (longEdge < minDimension) continue; + if (!best || longEdge > best.longEdge) best = { path: candidate, longEdge }; + } catch { + // Not a readable JPEG; try the next preview. + } + } + + if (!best) { + await cleanup().catch(() => undefined); + return null; + } + return { path: best.path, cleanup }; + } catch { + await cleanup().catch(() => undefined); + return null; + } +} + +/** + * Small grid thumbnail. RAW files use the camera's embedded preview when it is + * large enough; everything else (and RAW files without one) goes through the + * regular render pipeline. + */ +export async function renderPhotoThumbnail(input: { + filePath: string; + kind: "raw" | "image"; + maxDimension: number; + quality?: number; +}): Promise { + if (input.kind === "raw") { + const preview = await extractEmbeddedPreview( + input.filePath, + input.maxDimension, + ); + if (preview) { + try { + return await sharp(preview.path, { + failOn: "none", + limitInputPixels: 500_000_000, + }) + .autoOrient() + .toColourspace("srgb") + .resize({ + width: input.maxDimension, + height: input.maxDimension, + fit: "inside", + withoutEnlargement: true, + }) + .jpeg({ quality: input.quality ?? 72, mozjpeg: true }) + .toBuffer(); + } finally { + await preview.cleanup().catch(() => undefined); + } + } + } + + if (input.kind === "image") { + return sharp(input.filePath, { failOn: "none", limitInputPixels: 500_000_000 }) + .autoOrient() + .resize({ + width: input.maxDimension, + height: input.maxDimension, + fit: "inside", + withoutEnlargement: true, + }) + .jpeg({ quality: input.quality ?? 72 }) + .toBuffer(); + } + + const rendered = await renderPhotoJpeg({ + filePath: input.filePath, + kind: input.kind, + adjustments: defaultPhotoAdjustments(), + maxDimension: input.maxDimension, + }); + return rendered.data; +} + /** Source dimensions after applying the EXIF orientation the browser sees. */ async function orientedDimensions( filePath: string,