3 Commits

Author SHA1 Message Date
bhursey f75178de69 fix(auth): give invite links a lifetime that fits an inbox
CI / build (push) Has been cancelled
Invite and welcome emails signed a 10-minute sign-in token, so the link was
usually dead by the time someone opened the mail and could never reach the
set-password page. Invitations now use a 7-day single-use token, while
requested sign-in links stay at 10 minutes. Expired or already-used links also
explain themselves on the sign-in page and point at requesting a fresh one.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-22 17:38:15 +00:00
bhursey fac9b96cca feat(events): show every photo on the event page without folders
CI / build (push) Has been cancelled
Folders were an implementation detail leaking into the event workflow: every
upload needed a folder first and photos were split across pages. Uploads now
land in a single implicit "Photos" folder and the event page renders one
gallery with the uploader and an edited-only download.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 14:37:57 +00:00
bhursey ebe0c77f7e feat(editor): finish the quick/advanced editor handoff
CI / build (push) Has been cancelled
Reopen advanced edits from their saved recipe, seed or take over the quick
editor from them, refresh thumbnails after a save, and add an edited-only
download. Also fixes the Lumenroom library collapsing to slivers on large
shoots and documents deploying both containers on a new host.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 06:35:24 +00:00
50 changed files with 2322 additions and 607 deletions
+8 -4
View File
@@ -94,12 +94,16 @@ NFS_ADDR=
NFS_EXPORT= NFS_EXPORT=
NFS_VERSION=4 NFS_VERSION=4
# Advanced editor bridge (optional). LUMENROOM_URL is the base URL of the # Advanced editor bridge (optional). LUMENROOM_URL is the browser-facing base
# separate Lumenroom deployment, e.g. http://edit.local:8787. BRIDGE_SECRET is a # URL of Lumenroom, e.g. http://<lan-ip>:8787 or https://edit.example.org.
# long random string shared with that deployment; without both the "Advanced" # BRIDGE_SECRET is a long random string shared by both containers; without both
# button reports that the editor is not configured. # the "Advanced" button reports that the editor is not configured.
LUMENROOM_URL= LUMENROOM_URL=
BRIDGE_SECRET= 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) # Observability (declared; no Sentry integration is wired yet)
SENTRY_DSN= SENTRY_DSN=
+1 -1
View File
@@ -10,7 +10,7 @@ ENV NODE_ENV=production
# ImageMagick's LibRaw delegate decodes camera RAW files for the in-app editor; # 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 # sharp does the tone rendering and JPEG encode. The Postgres client provides
# pg_dump/psql for admin backups and restores; unzip reads restore packages. # 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). # pnpm is how this project is built (see package.json scripts).
RUN npm install -g pnpm@9.15.0 RUN npm install -g pnpm@9.15.0
+141 -13
View File
@@ -13,6 +13,7 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It
- [Features](#features) - [Features](#features)
- [Stack](#stack) - [Stack](#stack)
- [Quick start (Docker)](#quick-start-docker) - [Quick start (Docker)](#quick-start-docker)
- [Deploying the combined stack on another system](#deploying-the-combined-stack-on-another-system)
- [Local development](#local-development) - [Local development](#local-development)
- [Configuration](#configuration) - [Configuration](#configuration)
- [Email delivery](#email-delivery) - [Email delivery](#email-delivery)
@@ -67,9 +68,9 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It
### Events and media ### Events and media
- One-off events with a shot brief, location, times, photographer/editor assignments, and per-event shared folders. - One-off events with a shot brief, location, times, photographer/editor assignments, and a single shared photo gallery per event.
- RAW and JPEG uploads streamed to disk, SHA-256 dedupe per folder, authenticated downloads, and manager-only event deletion with file cleanup. - RAW and JPEG uploads streamed to disk, SHA-256 dedupe per event, authenticated downloads, and manager-only event deletion with file cleanup.
- Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, per-folder or whole-event ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share — never in container-local storage. - Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, whole-event or edited-only ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share — never in container-local storage.
- Video upload with FFmpeg probe/transcode to web H.264/AAC, generated poster, non-destructive trim re-render, and retry after a failed encode. - Video upload with FFmpeg probe/transcode to web H.264/AAC, generated poster, non-destructive trim re-render, and retry after a failed encode.
- Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/<id>`, a minimal `/embed/<id>` iframe, and an oEmbed endpoint. - Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/<id>`, a minimal `/embed/<id>` iframe, and an oEmbed endpoint.
- Announcements feed with draft/publish/delete for coordinators and admins. - Announcements feed with draft/publish/delete for coordinators and admins.
@@ -108,10 +109,19 @@ cp .env.example .env
docker compose up -d db docker compose up -d db
docker compose --profile tools build migrate docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate # migrations + seed docker compose --profile tools run --rm migrate # migrations + seed
docker compose up -d --build app docker compose up -d --build app lumenroom
``` ```
Open <http://localhost:3000>. 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 <http://localhost:3000>. The advanced photo editor (Lumenroom) is the
vendored second container and publishes on <http://localhost:8787>; 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: 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. 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 <repository-url> /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=<base64 value>
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=<hex value>
POSTGRES_DB=media
DATABASE_URL=postgres://media:<hex value>@localhost:5433/media
CRON_SECRET=<hex value>
MEDIA_ARCHIVE_DIR=/mnt/glenloch-media
# Advanced editor bridge
LUMENROOM_URL=https://edit.example.org
LUMENROOM_BIND=127.0.0.1
BRIDGE_SECRET=<hex value>
```
`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 ## Local development
```bash ```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. | | `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. | | `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. | | `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. | | `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. 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=<hex value> CRON_SECRET=<hex value>
POSTMARK_FROM=media@example.org POSTMARK_FROM=media@example.org
# POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead # 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=<hex value>
``` ```
Notes: Notes:
@@ -348,9 +452,10 @@ docker compose config --quiet
docker compose up -d db docker compose up -d db
docker compose --profile tools build migrate docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate docker compose --profile tools run --rm migrate
docker compose up -d --build app docker compose up -d --build app lumenroom
docker compose ps docker compose ps
curl -fsS http://127.0.0.1:3000/api/health 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. 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 encode zstd gzip
reverse_proxy 127.0.0.1:3000 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 ```bash
sudo caddy validate --config /etc/caddy/Caddyfile sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy sudo systemctl reload caddy
@@ -421,7 +536,7 @@ sudo ufw enable
sudo ufw status 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) ### 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. 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 ### 12. Updating the deployment
Take a backup, then: Take a backup, then:
@@ -550,9 +669,10 @@ cd /opt/glenloch-media
git pull --ff-only git pull --ff-only
docker compose --profile tools build migrate docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate docker compose --profile tools run --rm migrate
docker compose up -d --build app docker compose up -d --build app lumenroom
docker compose ps docker compose ps
curl -fsS http://127.0.0.1:3000/api/health 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: `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 ```bash
git log --oneline -5 git log --oneline -5
git checkout <previous-commit> git checkout <previous-commit>
docker compose up -d --build app docker compose up -d --build app lumenroom
# after fixing: # after fixing:
git switch main 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/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. | | 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`. | | 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. | | Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. |
### 14. Production checklist ### 14. Production checklist
@@ -592,6 +714,8 @@ git switch main
- [ ] Cron jobs installed and returning success. - [ ] Cron jobs installed and returning success.
- [ ] Backup downloaded, stored off-host, and restore tested once. - [ ] 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). - [ ] 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. - [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary.
### 15. Advanced photo editor bridge (optional) ### 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 **One deployment.** Lumenroom is vendored under `lumenroom/`, and
`docker-compose.yml` builds it as a second service next to the app. One clone `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 ```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): Values in `.env` (all optional except the secret):
```dotenv ```dotenv
@@ -692,7 +820,7 @@ that the gallery shows.
│ ├── domain/ Pure, unit-tested business rules │ ├── domain/ Pure, unit-tested business rules
│ └── lib/ Timezone, tokens, email, storage, media, backup helpers │ └── lib/ Timezone, tokens, email, storage, media, backup helpers
├── Dockerfile Multi-stage build; tools stage for migrations ├── 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 ├── drizzle.config.ts
├── next.config.ts ├── next.config.ts
├── playwright.config.ts ├── playwright.config.ts
@@ -709,7 +837,7 @@ that the gallery shows.
| `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet | | `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet |
| `/availability` | Personal and team blackout management | | `/availability` | Personal and team blackout management |
| `/coverage` | Swap/release requests and public intake | | `/coverage` | Swap/release requests and public intake |
| `/events`, `/events/[id]` | One-off events, briefs, photographers, folders | | `/events`, `/events/[id]` | One-off events, briefs, photographers, photo gallery |
| `/media`, `/media/[id]` | Photo/video library and public video page | | `/media`, `/media/[id]` | Photo/video library and public video page |
| `/training`, `/training/guides/*` | Lessons, attachments, role guides | | `/training`, `/training/guides/*` | Lessons, attachments, role guides |
| `/announcements` | Team feed | | `/announcements` | Team feed |
+7 -15
View File
@@ -4,8 +4,8 @@ import { signInAs, resetDb, BASE } from "./dev";
/** /**
* Event photography (J/K slice): a coordinator creates an event and assigns two * Event photography (J/K slice): a coordinator creates an event and assigns two
* photographers; the first creates a folder and uploads an edited JPEG plus a * photographers; the first uploads a JPEG and a RAW original straight onto the
* RAW original; the second — not the uploader — downloads the untouched bytes. * event page; the second — not the uploader — downloads the untouched bytes.
* An unassigned volunteer cannot open the event at all. * An unassigned volunteer cannot open the event at all.
*/ */
@@ -56,17 +56,13 @@ test.describe("event photo sharing", () => {
await expect(page.getByText("Sam Okafor").first()).toBeVisible(); await expect(page.getByText("Sam Okafor").first()).toBeVisible();
}); });
test("an assigned photographer creates a folder and uploads files", async ({ test("an assigned photographer uploads files on the event page", async ({
page, page,
}) => { }) => {
await page.setViewportSize({ width: 1200, height: 900 }); await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "avery@glenloch.local"); await signInAs(page, "avery@glenloch.local");
await page.goto(eventUrl); await page.goto(eventUrl);
await page.getByLabel("New folder").fill("Originals");
await page.getByRole("button", { name: "Create folder" }).click();
await page.getByRole("link", { name: /Originals/ }).click();
await page.getByLabel("Choose photos to upload").setInputFiles([ await page.getByLabel("Choose photos to upload").setInputFiles([
{ name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO }, { name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO },
{ name: "raw.CR3", mimeType: "application/octet-stream", buffer: RAW }, { name: "raw.CR3", mimeType: "application/octet-stream", buffer: RAW },
@@ -84,11 +80,9 @@ test.describe("event photo sharing", () => {
await page.setViewportSize({ width: 1200, height: 900 }); await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local"); await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl); await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
const [download] = await Promise.all([ const [download] = await Promise.all([
page.waitForEvent("download"), page.waitForEvent("download"),
// Exact: the folder header also offers "Download folder (n)".
page.getByRole("link", { name: "Download", exact: true }).first().click(), page.getByRole("link", { name: "Download", exact: true }).first().click(),
]); ]);
const downloadPath = await download.path(); const downloadPath = await download.path();
@@ -112,11 +106,11 @@ test.describe("event photo sharing", () => {
const zip = await readFile(downloadPath!); const zip = await readFile(downloadPath!);
expect(zip.subarray(0, 4).toString("binary")).toBe("PK\x03\x04"); expect(zip.subarray(0, 4).toString("binary")).toBe("PK\x03\x04");
// Store-only entries keep the original bytes and folder paths in the ZIP. // Store-only entries keep the original bytes; uploads share one folder.
expect(zip.includes(PHOTO)).toBe(true); expect(zip.includes(PHOTO)).toBe(true);
expect(zip.includes(RAW)).toBe(true); expect(zip.includes(RAW)).toBe(true);
expect(zip.includes(Buffer.from(`Originals/${PHOTO_NAME}`))).toBe(true); expect(zip.includes(Buffer.from(`Photos/${PHOTO_NAME}`))).toBe(true);
expect(zip.includes(Buffer.from("Originals/raw.CR3"))).toBe(true); expect(zip.includes(Buffer.from("Photos/raw.CR3"))).toBe(true);
}); });
test("a photographer views a photo and saves a full-resolution edited JPEG", async ({ test("a photographer views a photo and saves a full-resolution edited JPEG", async ({
@@ -125,7 +119,6 @@ test.describe("event photo sharing", () => {
await page.setViewportSize({ width: 1200, height: 900 }); await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local"); await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl); await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
await page await page
.getByRole("button", { name: `View and edit ${PHOTO_NAME}` }) .getByRole("button", { name: `View and edit ${PHOTO_NAME}` })
@@ -164,7 +157,7 @@ test.describe("event photo sharing", () => {
]); ]);
const zip = await readFile((await zipDownload.path())!); const zip = await readFile((await zipDownload.path())!);
expect(zip.includes(edited)).toBe(true); expect(zip.includes(edited)).toBe(true);
expect(zip.includes(Buffer.from("Originals/photo-edited.jpg"))).toBe(true); expect(zip.includes(Buffer.from("Photos/photo-edited.jpg"))).toBe(true);
}); });
test("an unassigned volunteer cannot open the event", async ({ page }) => { test("an unassigned volunteer cannot open the event", async ({ page }) => {
@@ -178,7 +171,6 @@ test.describe("event photo sharing", () => {
await page.setViewportSize({ width: 1200, height: 900 }); await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local"); await signInAs(page, "admin@glenloch.local");
await page.goto(eventUrl); await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
const photoHref = await page const photoHref = await page
.getByRole("link", { name: "Download", exact: true }) .getByRole("link", { name: "Download", exact: true })
.first() .first()
+4 -7
View File
@@ -158,14 +158,11 @@ test.describe("growth goals and maintenance", () => {
"No media storage share", "No media storage share",
); );
await page.goto(`${BASE}/events/${eventId}/folders/${folderId}`);
await expect(page.getByRole("alert").first()).toContainText(
"Photo uploads and editing are disabled",
);
await page.goto(`${BASE}/events/${eventId}`); await page.goto(`${BASE}/events/${eventId}`);
await expect(page.getByRole("alert").first()).toContainText( await expect(
"Photo and video uploads are disabled", page.getByText("Photo uploads and editing are disabled"),
); ).toBeVisible();
await expect(page.getByText("Photo and video uploads are disabled")).toBeVisible();
// A share name that reads like `host:/export` while the path is a local // A share name that reads like `host:/export` while the path is a local
// directory must block writes: media would silently land on local disk. // directory must block writes: media would silently land on local disk.
+36 -7
View File
@@ -9,7 +9,7 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs'; 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'; import { removeAsset } from './storage.mjs';
const VERSION = 'g1'; const VERSION = 'g1';
@@ -173,11 +173,17 @@ function photoRecordFrom(photo, eventId, sessionId, index) {
meta: {}, meta: {},
thumb: '', thumb: '',
thumbUrl: `/api/photos/${id}/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, rating: 0,
flag: 'none', flag: 'none',
color: '', color: '',
keywords: [], 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: [], history: [],
raw, raw,
previewUrl: raw ? `/api/photos/${id}/preview` : undefined, 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 * Mirrors one event into the local catalog. The photo bytes stay on the
* dashboard; only metadata, previews and thumbnails are temporary here. * dashboard; only metadata, previews and thumbnails are temporary here.
*/ */
export async function importBridgeEvent({ serviceToken, sessionId }) { export async function importBridgeEvent({ serviceToken, sessionId, returnUrl }) {
const expiresAt = const expiresAt =
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000; Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
@@ -198,12 +204,35 @@ export async function importBridgeEvent({ serviceToken, sessionId }) {
serviceToken, serviceToken,
); );
const eventId = bridgeEventId(listing.event.id); 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); dropBridgeEvent(eventId);
const returnUrl = listing.editor?.returnUrl ?? null; // The exchange hands back the dashboard address the browser actually used;
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0); // 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) => { 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( bridgeInsert.run(
eventId, eventId,
@@ -211,7 +240,7 @@ export async function importBridgeEvent({ serviceToken, sessionId }) {
serviceToken, serviceToken,
GLENLOCH_URL, GLENLOCH_URL,
listing.event.id, listing.event.id,
returnUrl, dashboardReturn,
expiresAt, expiresAt,
Date.now(), Date.now(),
); );
+13 -1
View File
@@ -39,6 +39,7 @@ import {
findPreview, findPreview,
findThumb, findThumb,
removeAsset, removeAsset,
removeThumb,
storageBytes, storageBytes,
writeOriginal, writeOriginal,
writePreview, writePreview,
@@ -302,6 +303,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => {
const imported = await importBridgeEvent({ const imported = await importBridgeEvent({
serviceToken: service.token, serviceToken: service.token,
sessionId: payload.sid, sessionId: payload.sid,
returnUrl: service.returnUrl,
}); });
const sessionToken = createSession(row.id); const sessionToken = createSession(row.id);
res.writeHead(302, { res.writeHead(302, {
@@ -459,7 +461,17 @@ route('POST', '/api/bridge/export', async ({ req, res }) => {
if (result.status >= 400) { if (result.status >= 400) {
return error(res, result.status, result.body?.error || 'The edit could not be saved to the event'); 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 }) => { route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
+6
View File
@@ -70,6 +70,12 @@ export function findThumb(id) {
return fs.existsSync(p) ? p : null; 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) { export async function removeAsset(id) {
const files = [findOriginal(id), findPreview(id), findThumb(id)]; const files = [findOriginal(id), findPreview(id), findThumb(id)];
await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve()))); await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve())));
+9 -2
View File
@@ -653,15 +653,22 @@ export default function App() {
height: activePhoto.height, 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 (!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`); setToast(`Saved ${activePhoto.name} to the event`);
} catch (err) { } catch (err) {
setToast(err instanceof Error ? err.message : 'The photo could not be saved'); setToast(err instanceof Error ? err.message : 'The photo could not be saved');
} finally { } finally {
setBridgeBusy(false); setBridgeBusy(false);
} }
}, [activePhoto, bridgeEvent]); }, [activePhoto, bridgeEvent, updatePhoto]);
const handleCloudLogin = useCallback( const handleCloudLogin = useCallback(
async (email: string, password: string) => { async (email: string, password: string) => {
+2 -2
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits'; 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 { rotatedBounds, Renderer } from '../gl/renderer';
import type { Edits, EventRecord, PhotoRecord, Preset } from '../types'; import type { Edits, EventRecord, PhotoRecord, Preset } from '../types';
import ContextMenu, { type MenuEntry } from './ContextMenu'; import ContextMenu, { type MenuEntry } from './ContextMenu';
@@ -703,7 +703,7 @@ export default function Develop({
title={p.name} title={p.name}
> >
<img <img
src={p.thumbUrl ?? p.thumb} src={thumbSrc(p)}
alt={p.name} alt={p.name}
loading="lazy" loading="lazy"
draggable={false} draggable={false}
+2 -1
View File
@@ -1,6 +1,7 @@
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits'; import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag'; import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
import { thumbSrc } from '../lib/images';
import type { ColorLabel, Flag, PhotoRecord } from '../types'; import type { ColorLabel, Flag, PhotoRecord } from '../types';
import Stars, { ColorSwatches, FlagButtons } from './Stars'; import Stars, { ColorSwatches, FlagButtons } from './Stars';
@@ -312,7 +313,7 @@ export default function LibraryGrid({
> >
<div className="card-thumb"> <div className="card-thumb">
<img <img
src={p.thumbUrl ?? p.thumb} src={thumbSrc(p)}
alt={p.name} alt={p.name}
loading="lazy" loading="lazy"
draggable={false} draggable={false}
+2 -2
View File
@@ -4,7 +4,7 @@ import { computeAutoEdits } from '../lib/auto';
import { clamp } from '../lib/curves'; import { clamp } from '../lib/curves';
import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types'; import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types';
import CurveEditor from './CurveEditor'; import CurveEditor from './CurveEditor';
import { getBitmap } from '../lib/images'; import { getBitmap, thumbSrc } from '../lib/images';
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer'; import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets'; import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets';
import { usePresetThumbs } from './PresetThumbs'; import { usePresetThumbs } from './PresetThumbs';
@@ -653,7 +653,7 @@ export function NavigatorPanel({ photo }: { photo: PhotoRecord }) {
</div> </div>
<div className="navigator-thumb"> <div className="navigator-thumb">
<img <img
src={photo.thumbUrl ?? photo.thumb} src={thumbSrc(photo)}
alt={photo.name} alt={photo.name}
style={{ transform: thumbTransform(photo) }} style={{ transform: thumbTransform(photo) }}
/> />
+1
View File
@@ -266,6 +266,7 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
decode: input.decode, decode: input.decode,
previewUrl: input.previewUrl, previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl, thumbUrl: input.thumbUrl,
thumbVersion: input.thumbVersion,
name: input.name ?? 'Untitled', name: input.name ?? 'Untitled',
width: input.width ?? 0, width: input.width ?? 0,
height: input.height ?? 0, height: input.height ?? 0,
+11
View File
@@ -4,6 +4,17 @@ import { getAsset, putAsset } from './db';
const CACHE_LIMIT = 6; const CACHE_LIMIT = 6;
const cache = new Map<string, ImageBitmap>(); const cache = new Map<string, ImageBitmap>();
/**
* 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. */ /** Where to fetch the original (or raw proxy) when it is not cached on this device. */
export function remoteAssetUrl(photo: PhotoRecord): string { export function remoteAssetUrl(photo: PhotoRecord): string {
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`; if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
+3
View File
@@ -562,6 +562,9 @@ img {
overflow-y: auto; overflow-y: auto;
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); 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; gap: 12px;
padding: 14px; padding: 14px;
align-content: start; align-content: start;
+2
View File
@@ -103,6 +103,8 @@ export interface PhotoRecord {
previewUrl?: string; previewUrl?: string;
/** server URL for the grid thumbnail */ /** server URL for the grid thumbnail */
thumbUrl?: string; 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. */ /** Set when the photo is proxied from a dashboard bridge session. */
bridgeSource?: { sessionId: string; sourceId: string }; bridgeSource?: { sessionId: string; sourceId: string };
} }
@@ -1,126 +0,0 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Download } from "lucide-react";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getFolderDetail } from "@/db/events";
import {
isBrowserRenderablePhoto,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { mediaStorage } from "@/lib/media-storage";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
PhotoGallery,
type GalleryPhoto,
} from "@/components/app/events/photo-gallery";
const KIND_LABELS: Record<string, string> = {
originals: "RAW / originals",
edited: "Edited exports",
mixed: "Mixed",
};
function sizeLabel(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
/**
* A folder's gallery. Every assigned photographer can see and download every
* file; only the uploader or an event manager can delete one.
*/
export default async function EventFolderPage({
params,
}: {
params: Promise<{ id: string; folderId: string }>;
}) {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) redirect("/login");
const { id, folderId } = await params;
const detail = await getFolderDetail(folderId, user.id, user.systemRole);
if (!detail || detail.event.id !== id) notFound();
// Photos live only on the configured media storage share, so the uploader and
// editor stay disabled (with the reason) until that destination is ready.
const storage = await mediaStorage();
const photos: GalleryPhoto[] = detail.photos.map((photo) => ({
id: photo.id,
filename: photo.filename,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
uploaderId: photo.uploaderId,
uploaderName: photo.uploaderName,
previewable: isBrowserRenderablePhoto(photo.filename),
editable: isEditableEventPhoto(photo.filename),
adjustments: parseStoredPhotoAdjustments(photo.editJson),
editedAt: photo.editedAt ? photo.editedAt.toISOString() : null,
editedSizeBytes: photo.editedSizeBytes,
}));
return (
<div className="space-y-5">
<div>
<Link
href={`/events/${detail.event.id}`}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
{detail.event.title}
</Link>
</div>
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">
{detail.folder.name}
</h1>
<p className="text-sm text-muted-foreground">
{detail.photos.length} photo{detail.photos.length === 1 ? "" : "s"}{" "}
· {sizeLabel(detail.folder.totalBytes)}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">
{KIND_LABELS[detail.folder.kind] ?? detail.folder.kind}
</Badge>
{detail.photos.length > 0 && (
<Button asChild variant="outline" size="sm">
<a
href={`/api/events/${detail.event.id}/download?folderId=${detail.folder.id}`}
>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download folder ({detail.photos.length})
</a>
</Button>
)}
</div>
</div>
<PhotoGallery
eventId={detail.event.id}
folderId={detail.folder.id}
photos={photos}
canContribute={detail.canContribute}
canManage={detail.canManage}
currentUserId={user.id}
storageReady={storage.ok}
storageMessage={
storage.ok
? ""
: storage.message
}
/>
</div>
);
}
+80 -54
View File
@@ -1,10 +1,23 @@
import Link from "next/link"; import Link from "next/link";
import { notFound, redirect } from "next/navigation"; import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Camera, Download, Film, FolderOpen, MapPin, Play } from "lucide-react"; import {
ArrowLeft,
Camera,
Download,
Film,
Image as ImageIcon,
MapPin,
Play,
} from "lucide-react";
import { auth } from "@/auth/config"; import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles"; import type { SystemRole } from "@/auth/roles";
import { getEventDetail, listAssignableUsers } from "@/db/events"; import {
getEventDetail,
listAssignableUsers,
listEventPhotos,
} from "@/db/events";
import { listEventVideos } from "@/db/videos"; import { listEventVideos } from "@/db/videos";
import { bridgeConfigured } from "@/lib/bridge";
import { formatVideoDuration } from "@/lib/event-videos"; import { formatVideoDuration } from "@/lib/event-videos";
import { getStorageSettings } from "@/db/storage-settings"; import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage"; import { mediaStorage } from "@/lib/media-storage";
@@ -15,17 +28,21 @@ import {
PhotographerPanel, PhotographerPanel,
type EventPhotographer, type EventPhotographer,
} from "@/components/app/events/photographer-panel"; } 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 { 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 { ArchiveEventButton } from "@/components/app/events/archive-event-button";
import { VideoUploadForm } from "@/components/app/media/video-upload-form"; import { VideoUploadForm } from "@/components/app/media/video-upload-form";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import {
const KIND_LABELS: Record<string, string> = { PhotoGallery,
originals: "RAW / originals", type GalleryPhoto,
edited: "Edited exports", } from "@/components/app/events/photo-gallery";
mixed: "Mixed", import {
}; isBrowserRenderablePhoto,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { advancedEditViewFor } from "@/lib/advanced-edit";
function when(date: Date): string { function when(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, { return formatInTimezone(date, CHURCH_TIMEZONE, {
@@ -48,9 +65,9 @@ function sizeLabel(bytes: number): string {
} }
/** /**
* One event: brief, assigned photographers, and the shared folders. Managers * One event: brief, assigned photographers, and every photo in a single
* assign people; any assignee can create folders. Folder pages own uploads; * gallery. Managers assign people; any assignee can upload here. The header
* the event header downloads every photo as one ZIP. * downloads every photo (or only the edited ones) as one ZIP.
*/ */
export default async function EventDetailPage({ export default async function EventDetailPage({
params, params,
@@ -79,6 +96,25 @@ export default async function EventDetailPage({
role: person.role, role: person.role,
}), }),
); );
const photos: GalleryPhoto[] = (await listEventPhotos(event.event.id)).map(
(photo) => ({
id: photo.id,
folderId: photo.folderId,
filename: photo.filename,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
uploaderId: photo.uploaderId,
uploaderName: photo.uploaderName,
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 ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -99,6 +135,9 @@ export default async function EventDetailPage({
</h1> </h1>
<Badge variant="outline">{event.event.eventType}</Badge> <Badge variant="outline">{event.event.eventType}</Badge>
<div className="ml-auto flex flex-wrap items-center justify-end gap-2"> <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
{bridgeConfigured() && (
<AdvancedEditorButton eventId={event.event.id} />
)}
{event.event.photoCount > 0 && ( {event.event.photoCount > 0 && (
<Button asChild variant="outline" size="sm"> <Button asChild variant="outline" size="sm">
<a href={`/api/events/${event.event.id}/download`}> <a href={`/api/events/${event.event.id}/download`}>
@@ -107,6 +146,17 @@ export default async function EventDetailPage({
</a> </a>
</Button> </Button>
)} )}
{editedCount > 0 && (
<Button asChild variant="outline" size="sm">
<a
href={`/api/events/${event.event.id}/download?edited=1`}
title="Download only the photos with a saved edit, as full-resolution JPEGs"
>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download edited ({editedCount})
</a>
</Button>
)}
{event.canManage && archiveStatus.ok && ( {event.canManage && archiveStatus.ok && (
<ArchiveEventButton <ArchiveEventButton
eventId={event.event.id} eventId={event.event.id}
@@ -175,50 +225,26 @@ export default async function EventDetailPage({
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base"> <CardTitle className="flex items-center gap-2 text-base">
<FolderOpen className="h-4 w-4" aria-hidden="true" /> <ImageIcon className="h-4 w-4" aria-hidden="true" />
Folders Photos
{photos.length > 0 && (
<span className="text-sm font-normal text-muted-foreground">
{photos.length}
{editedCount > 0 ? ` · ${editedCount} edited` : ""}
</span>
)}
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-3"> <CardContent>
{event.folders.length === 0 ? ( <PhotoGallery
<p className="text-sm text-muted-foreground"> eventId={event.event.id}
No folders yet. Create one for originals, dumps, or edited selects. photos={photos}
</p> canContribute={event.canContribute}
) : ( canManage={event.canManage}
<ul className="grid gap-3 sm:grid-cols-2"> currentUserId={user.id}
{event.folders.map((folder) => ( storageReady={archiveStatus.ok}
<li key={folder.id}> storageMessage={archiveStatus.ok ? "" : archiveStatus.message}
<Link />
href={`/events/${event.event.id}/folders/${folder.id}`}
className="block rounded-md border border-border p-3 transition-colors hover:border-primary/60 hover:bg-muted/30"
>
<div className="flex items-start justify-between gap-2">
<p className="truncate text-sm font-medium">
{folder.name}
</p>
<Badge variant="secondary">
{KIND_LABELS[folder.kind] ?? folder.kind}
</Badge>
</div>
<p className="mt-1 text-xs text-muted-foreground">
{folder.photoCount} photo
{folder.photoCount === 1 ? "" : "s"} ·{" "}
{sizeLabel(folder.totalBytes)}
</p>
</Link>
</li>
))}
</ul>
)}
{event.canContribute ? (
<FolderCreateForm eventId={event.event.id} />
) : (
<p className="text-xs text-muted-foreground">
Only assigned photographers, coordinators and admins can add
folders or upload.
</p>
)}
</CardContent> </CardContent>
</Card> </Card>
+4 -4
View File
@@ -235,8 +235,8 @@ export default async function MediaPage() {
Photos Photos
</h2> </h2>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Every photo in the event folders you can open. Download originals Every photo in the events you can open. Download originals from
from the event folder. the event page.
</p> </p>
</div> </div>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
@@ -264,7 +264,7 @@ export default async function MediaPage() {
return ( return (
<Link <Link
key={photo.id} key={photo.id}
href={`/events/${photo.eventId}/folders/${photo.folderId}`} href={`/events/${photo.eventId}`}
className="group overflow-hidden rounded-md border border-border bg-background transition-colors hover:border-primary/60" className="group overflow-hidden rounded-md border border-border bg-background transition-colors hover:border-primary/60"
> >
<div className="flex aspect-square items-center justify-center bg-muted/40"> <div className="flex aspect-square items-center justify-center bg-muted/40">
@@ -292,7 +292,7 @@ export default async function MediaPage() {
{photo.filename} {photo.filename}
</p> </p>
<p className="truncate text-[11px] text-muted-foreground"> <p className="truncate text-[11px] text-muted-foreground">
{photo.eventTitle} · {photo.folderName} {photo.eventTitle}
</p> </p>
<p className="text-[10px] text-muted-foreground"> <p className="text-[10px] text-muted-foreground">
{bytesLabel(photo.sizeBytes)} {bytesLabel(photo.sizeBytes)}
+1 -1
View File
@@ -450,7 +450,7 @@ export default function AdminGuidePage() {
rate-limited and appear under Coverage as new requests. Read the brief, rate-limited and appear under Coverage as new requests. Read the brief,
then either <strong>Create event</strong> (which opens an event with then either <strong>Create event</strong> (which opens an event with
the requester and ministry attached) or <strong>Decline</strong>. The the requester and ministry attached) or <strong>Decline</strong>. The
event is where you assign photographers and folders. event page is where you assign photographers and upload photos.
</p> </p>
</GuideSection> </GuideSection>
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
import { authenticateBridge } from "@/db/bridge"; import { authenticateBridge } from "@/db/bridge";
import { import {
BRIDGE_SESSION_TTL_SECONDS, BRIDGE_SESSION_TTL_SECONDS,
bridgeReturnUrl,
signBridgeToken, signBridgeToken,
} from "@/lib/bridge"; } from "@/lib/bridge";
import { errorResponse, jsonResponse } from "@/lib/http"; import { errorResponse, jsonResponse } from "@/lib/http";
@@ -36,5 +37,9 @@ export const POST = async (
sessionId: auth.session.id, sessionId: auth.session.id,
eventId: auth.session.eventId, eventId: auth.session.eventId,
expiresAt: auth.session.expiresAt, expiresAt: auth.session.expiresAt,
// Carried from the browser-facing request that opened the editor so the
// editor can link back to the address the user actually reached.
returnUrl:
auth.payload.ret ?? bridgeReturnUrl(auth.session.eventId) ?? null,
}); });
}; };
@@ -4,11 +4,17 @@ import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge"; import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge";
import { import {
advancedStoredNameForEventPhoto,
editedStoredNameForEventPhoto, editedStoredNameForEventPhoto,
eventPhotoPath, eventPhotoPath,
} from "@/lib/event-photos"; } from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http"; import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage"; import { mediaStorage } from "@/lib/media-storage";
import {
defaultPhotoAdjustments,
parseStoredPhotoAdjustments,
} from "@/lib/photo-adjustments";
import { renderPhotoJpeg } from "@/lib/photo-render";
const MAX_BODY_BYTES = 64 * 1024 * 1024; const MAX_BODY_BYTES = 64 * 1024 * 1024;
const MAX_RECIPE_BYTES = 512 * 1024; const MAX_RECIPE_BYTES = 512 * 1024;
@@ -19,9 +25,10 @@ const MAX_JPEG_BYTES = 48 * 1024 * 1024;
* Body: { jpeg: <base64>, edits: <advanced recipe>, width, height } * Body: { jpeg: <base64>, edits: <advanced recipe>, width, height }
* *
* The advanced editor renders in the browser, so the server only has to store * The advanced editor renders in the browser, so the server only has to store
* the result. The JPEG becomes the photo's edited version (used by the gallery, * the result. The JPEG is kept as the photo's advanced render (its own file, so
* thumbnails and delivery exports) and the recipe is kept so the editor can be * the simple editor can layer on top) and the recipe is kept so the editor can
* reopened with its sliders intact. * be reopened with its sliders intact. Any simple-editor layer is rebuilt on
* top of the new render, so the two editors never disagree.
*/ */
export const POST = async ( export const POST = async (
req: NextRequest, req: NextRequest,
@@ -70,11 +77,11 @@ export const POST = async (
const storage = await mediaStorage(); const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message); if (!storage.ok) return errorResponse(503, storage.message);
const storedName = editedStoredNameForEventPhoto( const advancedStoredName = advancedStoredNameForEventPhoto(
auth.session.eventId, auth.session.eventId,
photo.id, photo.id,
); );
const target = eventPhotoPath(storage.root, storedName); const target = eventPhotoPath(storage.root, advancedStoredName);
const temporary = `${target}.${randomUUID()}.tmp`; const temporary = `${target}.${randomUUID()}.tmp`;
try { try {
await mkdir(path.dirname(target), { recursive: true }); await mkdir(path.dirname(target), { recursive: true });
@@ -85,10 +92,40 @@ export const POST = async (
return errorResponse(500, "the edited image could not be saved"); return errorResponse(500, "the edited image could not be saved");
} }
// A photo the simple editor also adjusted keeps that layer: re-render it on
// the new advanced render so the saved JPEG still shows both recipes.
const quick = parseStoredPhotoAdjustments(photo.editJson);
const hasQuickLayer =
JSON.stringify(quick) !== JSON.stringify(defaultPhotoAdjustments());
let editedStoredName = advancedStoredName;
let editedSizeBytes = data.byteLength;
if (hasQuickLayer) {
editedStoredName = editedStoredNameForEventPhoto(auth.session.eventId, photo.id);
const layered = eventPhotoPath(storage.root, editedStoredName);
try {
const rendered = await renderPhotoJpeg({
filePath: target,
kind: "image",
adjustments: quick,
});
await mkdir(path.dirname(layered), { recursive: true });
const layeredTemporary = `${layered}.${randomUUID()}.tmp`;
await writeFile(layeredTemporary, rendered.data);
await rename(layeredTemporary, layered);
editedSizeBytes = rendered.data.byteLength;
} catch (error) {
console.error("simple edit layer rebuild failed", error);
return errorResponse(
500,
"the simple editor's adjustments could not be rebuilt on the new render",
);
}
}
const editedAt = await saveBridgeRender({ const editedAt = await saveBridgeRender({
photoId: photo.id, photoId: photo.id,
editedStoredName: storedName, editedStoredName,
editedSizeBytes: data.byteLength, editedSizeBytes,
advancedEditJson: recipe, advancedEditJson: recipe,
editedBy: auth.user.id, editedBy: auth.user.id,
}); });
@@ -100,6 +137,6 @@ export const POST = async (
return jsonResponse({ return jsonResponse({
ok: true, ok: true,
editedAt, editedAt,
editedSizeBytes: data.byteLength, editedSizeBytes,
}); });
}; };
@@ -4,9 +4,9 @@ import { createReadStream } from "node:fs";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { Readable } from "node:stream"; import { Readable } from "node:stream";
import sharp from "sharp";
import { authenticateBridge, getBridgePhoto } from "@/db/bridge"; import { authenticateBridge, getBridgePhoto } from "@/db/bridge";
import { import {
bridgeEditedThumbStoredNameForEventPhoto,
bridgeProxyStoredNameForEventPhoto, bridgeProxyStoredNameForEventPhoto,
bridgeThumbStoredNameForEventPhoto, bridgeThumbStoredNameForEventPhoto,
eventPhotoPath, eventPhotoPath,
@@ -14,7 +14,7 @@ import {
import { errorResponse } from "@/lib/http"; import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage"; import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments"; import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { renderPhotoJpeg } from "@/lib/photo-render"; import { renderPhotoJpeg, renderPhotoThumbnail } from "@/lib/photo-render";
const PROXY_MAX_EDGE = 4000; const PROXY_MAX_EDGE = 4000;
const THUMB_MAX_EDGE = 480; const THUMB_MAX_EDGE = 480;
@@ -31,14 +31,25 @@ function imageResponse(data: Buffer, contentType = "image/jpeg"): Response {
}); });
} }
/** Reads a cached derivative or writes it atomically on first use. */ /**
* Reads a cached derivative or writes it atomically on first use. When
* `newerThan` is given, a cache older than that timestamp is rebuilt, so a
* thumbnail of a re-rendered edit never goes stale.
*/
async function cached( async function cached(
filePath: string, filePath: string,
produce: () => Promise<Buffer>, produce: () => Promise<Buffer>,
newerThan?: number,
): Promise<Buffer> { ): Promise<Buffer> {
try { try {
const info = await stat(filePath); const info = await stat(filePath);
if (info.isFile() && info.size > 0) return readFile(filePath); if (
info.isFile() &&
info.size > 0 &&
(newerThan === undefined || info.mtimeMs >= newerThan)
) {
return readFile(filePath);
}
} catch { } catch {
// Not generated yet. // Not generated yet.
} }
@@ -51,24 +62,12 @@ async function cached(
} }
async function thumbFor(filePath: string, kind: "raw" | "image") { async function thumbFor(filePath: string, kind: "raw" | "image") {
if (kind === "raw") { return renderPhotoThumbnail({
const rendered = await renderPhotoJpeg({
filePath, filePath,
kind, kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: THUMB_MAX_EDGE, maxDimension: THUMB_MAX_EDGE,
quality: 82,
}); });
return rendered.data;
}
return sharp(filePath)
.resize({
width: THUMB_MAX_EDGE,
height: THUMB_MAX_EDGE,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: 82, mozjpeg: true })
.toBuffer();
} }
/** /**
@@ -126,13 +125,33 @@ export const GET = async (
} }
if (variant === "thumb") { if (variant === "thumb") {
try { // With a saved edit, the grid should show the photo as it was developed —
const thumbPath = eventPhotoPath( // the editor's own look — not the untouched original.
storage.root, let sourcePath = originalPath;
bridgeThumbStoredNameForEventPhoto(auth.session.eventId, photo.id), let sourceKind: "raw" | "image" = photo.kind;
let thumbName = bridgeThumbStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
); );
const data = await cached(thumbPath, () => let editedMtime: number | undefined;
thumbFor(originalPath, photo.kind), if (photo.editedStoredName) {
const editedPath = eventPhotoPath(storage.root, photo.editedStoredName);
const edited = await stat(editedPath).catch(() => null);
if (edited?.isFile()) {
sourcePath = editedPath;
sourceKind = "image";
editedMtime = edited.mtimeMs;
thumbName = bridgeEditedThumbStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
);
}
}
try {
const data = await cached(
eventPhotoPath(storage.root, thumbName),
() => thumbFor(sourcePath, sourceKind),
editedMtime,
); );
return imageResponse(data); return imageResponse(data);
} catch { } catch {
@@ -10,6 +10,17 @@ import { mediaStorage } from "@/lib/media-storage";
import { eventPhotoPath } from "@/lib/event-photos"; import { eventPhotoPath } from "@/lib/event-photos";
import sharp from "sharp"; import sharp from "sharp";
/** The advanced editor's saved slider recipe, or null when it cannot be read. */
function savedRecipe(json: string | null): unknown {
if (!json) return null;
try {
const parsed = JSON.parse(json) as unknown;
return parsed && typeof parsed === "object" ? parsed : null;
} catch {
return null;
}
}
/** Reads the header dimensions without decoding the whole file. */ /** Reads the header dimensions without decoding the whole file. */
async function imageSize( async function imageSize(
path: string, path: string,
@@ -77,6 +88,12 @@ export const GET = async (
width: sizes.get(row.id)?.width ?? 0, width: sizes.get(row.id)?.width ?? 0,
height: sizes.get(row.id)?.height ?? 0, height: sizes.get(row.id)?.height ?? 0,
takenAt: row.createdAt, takenAt: row.createdAt,
// Reopening the editor restores the sliders exactly as they were saved;
// the editor falls back to neutral when this is null.
edits: savedRecipe(row.advancedEditJson),
// Stamps the thumbnail URL so a newly saved edit is not masked by a
// cached grid thumbnail from before it was rendered.
editedAt: row.editedAt,
})), })),
editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) }, editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) },
}); });
+7 -2
View File
@@ -2,7 +2,12 @@ import { NextRequest } from "next/server";
import { z } from "zod"; import { z } from "zod";
import { gateOrUser } from "@/auth/api"; import { gateOrUser } from "@/auth/api";
import { approveUser } from "@/auth/invites"; import { approveUser } from "@/auth/invites";
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link"; import {
APP_ORIGIN,
INVITE_LINK_TTL,
requestOrigin,
signMagicToken,
} from "@/auth/magic-link";
import { getUserById } from "@/db/users"; import { getUserById } from "@/db/users";
import { sendWelcomeEmail } from "@/lib/welcome-email"; import { sendWelcomeEmail } from "@/lib/welcome-email";
@@ -48,7 +53,7 @@ export const POST = async (req: NextRequest) => {
const approved = await getUserById(user.id); const approved = await getUserById(user.id);
let welcome: { delivered: boolean; transport: string | null } | null = null; let welcome: { delivered: boolean; transport: string | null } | null = null;
if (approved) { if (approved) {
const token = await signMagicToken(approved.email); const token = await signMagicToken(approved.email, INVITE_LINK_TTL);
const origin = requestOrigin(req) || APP_ORIGIN; const origin = requestOrigin(req) || APP_ORIGIN;
const url = `${origin}/api/dev/complete?token=${encodeURIComponent( const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
token, token,
+9 -3
View File
@@ -1,7 +1,12 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { z } from "zod"; import { z } from "zod";
import { gateOrUser } from "@/auth/api"; import { gateOrUser } from "@/auth/api";
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link"; import {
APP_ORIGIN,
INVITE_LINK_TTL,
requestOrigin,
signMagicToken,
} from "@/auth/magic-link";
import { validateUsername } from "@/auth/password"; import { validateUsername } from "@/auth/password";
import { SYSTEM_ROLES } from "@/auth/roles"; import { SYSTEM_ROLES } from "@/auth/roles";
import { db } from "@/db"; import { db } from "@/db";
@@ -128,8 +133,9 @@ export const POST = async (req: NextRequest) => {
}); });
// Hand the admin a sign-in link, exactly like the invite flow does. The // Hand the admin a sign-in link, exactly like the invite flow does. The
// link only works once the account is active. // link only works once the account is active. It is an invite, not a
const token = await signMagicToken(user.email); // just-requested sign-in, so it gets the invite lifetime.
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
const origin = requestOrigin(req) || APP_ORIGIN; const origin = requestOrigin(req) || APP_ORIGIN;
const url = `${origin}/api/dev/complete?token=${encodeURIComponent( const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
token, token,
+10 -3
View File
@@ -1,5 +1,6 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { gateSession } from "@/auth/api"; import { gateSession } from "@/auth/api";
import { requestOrigin } from "@/auth/magic-link";
import { bridgeUser, createBridgeSession } from "@/db/bridge"; import { bridgeUser, createBridgeSession } from "@/db/bridge";
import { getEventAccess } from "@/db/events"; import { getEventAccess } from "@/db/events";
import { errorResponse, jsonResponse } from "@/lib/http"; import { errorResponse, jsonResponse } from "@/lib/http";
@@ -7,7 +8,6 @@ import {
BRIDGE_LOGIN_TTL_SECONDS, BRIDGE_LOGIN_TTL_SECONDS,
advancedEditorUrl, advancedEditorUrl,
bridgeConfigured, bridgeConfigured,
bridgeReturnUrl,
signBridgeToken, signBridgeToken,
} from "@/lib/bridge"; } from "@/lib/bridge";
@@ -19,7 +19,7 @@ import {
* dashboard session; the editor only ever sees the scoped token. * dashboard session; the editor only ever sees the scoped token.
*/ */
export const POST = async ( export const POST = async (
_req: NextRequest, req: NextRequest,
{ params }: { params: Promise<{ id: string }> }, { params }: { params: Promise<{ id: string }> },
) => { ) => {
const gate = await gateSession(); const gate = await gateSession();
@@ -45,6 +45,12 @@ export const POST = async (
eventId: id, eventId: id,
}); });
// This request comes from the user's browser, so its origin is the address
// that actually works for them. `NEXTAUTH_URL` cannot be trusted here: the
// compose default is http://localhost:3000 even when the app is served from
// a LAN address. PUBLIC_ORIGIN still wins inside requestOrigin().
const returnUrl = `${requestOrigin(req)}/events/${id}`;
const token = signBridgeToken({ const token = signBridgeToken({
sid: session.id, sid: session.id,
eid: id, eid: id,
@@ -53,11 +59,12 @@ export const POST = async (
name: user.name, name: user.name,
kind: "login", kind: "login",
exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS, exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS,
ret: returnUrl,
}); });
return jsonResponse({ return jsonResponse({
url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`, url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`,
expiresAt: session.expiresAt, expiresAt: session.expiresAt,
returnUrl: bridgeReturnUrl(id), returnUrl,
}); });
}; };
+24 -6
View File
@@ -17,10 +17,12 @@ import { mediaStorage } from "@/lib/media-storage";
* GET /api/events/:id/download * GET /api/events/:id/download
* *
* Streams every photo on the event as one ZIP, preserving folder names. Saved * Streams every photo on the event as one ZIP, preserving folder names. Saved
* edits are included beside their originals as `<name>-edited.jpg`. The * edits are included beside their originals as `<name>-edited.jpg`. With
* archive is store-only: JPEGs and camera RAW files are already compressed, so * `?edited=1` the archive contains only the saved edits, which is what a
* deflating them would add CPU and latency without shrinking the download. * photographer wants to hand on after a grading pass. The archive is
* Anyone assigned to the event (or a manager) can download it. * store-only: JPEGs and camera RAW files are already compressed, so deflating
* them would add CPU and latency without shrinking the download. Anyone
* assigned to the event (or a manager) can download it.
*/ */
export const GET = async ( export const GET = async (
req: NextRequest, req: NextRequest,
@@ -36,13 +38,22 @@ export const GET = async (
// `?folderId=` narrows the archive to one folder, so a photographer can pull // `?folderId=` narrows the archive to one folder, so a photographer can pull
// just the shots they need without downloading the whole event. // just the shots they need without downloading the whole event.
const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null; const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null;
const onlyEdited = req.nextUrl.searchParams.get("edited") === "1";
const photos = (await listEventPhotosForArchive(id)).filter( const photos = (await listEventPhotosForArchive(id)).filter(
(photo) => !folderId || photo.folderId === folderId, (photo) =>
(!folderId || photo.folderId === folderId) &&
(!onlyEdited || Boolean(photo.editedStoredName)),
); );
if (photos.length === 0) { if (photos.length === 0) {
return errorResponse( return errorResponse(
404, 404,
folderId ? "this folder has no photos" : "this event has no photos", onlyEdited
? folderId
? "this folder has no edited photos"
: "this event has no edited photos"
: folderId
? "this folder has no photos"
: "this event has no photos",
); );
} }
@@ -55,6 +66,7 @@ export const GET = async (
filename: string; filename: string;
storedName: string; storedName: string;
}[] = []; }[] = [];
if (!onlyEdited) {
for (const photo of photos) { for (const photo of photos) {
entries.push({ entries.push({
key: `${photo.id}:original`, key: `${photo.id}:original`,
@@ -63,6 +75,7 @@ export const GET = async (
storedName: photo.storedName, storedName: photo.storedName,
}); });
} }
}
for (const photo of photos) { for (const photo of photos) {
if (!photo.editedStoredName) continue; if (!photo.editedStoredName) continue;
entries.push({ entries.push({
@@ -124,9 +137,14 @@ export const GET = async (
"content-type": "application/zip", "content-type": "application/zip",
"content-disposition": photoContentDisposition( "content-disposition": photoContentDisposition(
eventArchiveFilename( eventArchiveFilename(
[
folderId folderId
? `${access.event.title} - ${photos[0].folderName}` ? `${access.event.title} - ${photos[0].folderName}`
: access.event.title, : access.event.title,
onlyEdited ? "edited" : null,
]
.filter(Boolean)
.join(" - "),
), ),
false, false,
), ),
@@ -1,10 +1,11 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { mkdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import { copyFile, mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { gateSession } from "@/auth/api"; import { gateSession } from "@/auth/api";
import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events"; import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events";
import { import {
advancedStoredNameForEventPhoto,
editedPhotoFilename, editedPhotoFilename,
editedStoredNameForEventPhoto, editedStoredNameForEventPhoto,
eventPhotoPath, eventPhotoPath,
@@ -12,18 +13,43 @@ import {
} from "@/lib/event-photos"; } from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http"; import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage"; import { mediaStorage } from "@/lib/media-storage";
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments"; import {
defaultPhotoAdjustments,
normalizePhotoAdjustments,
parseStoredPhotoAdjustments,
} from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
const MAX_EDIT_BODY_BYTES = 32 * 1024; const MAX_EDIT_BODY_BYTES = 32 * 1024;
/** True when the advanced editor has left a recipe that describes its render. */
function hasAdvancedRecipe(json: string | null): boolean {
if (!json) return false;
try {
const parsed: unknown = JSON.parse(json);
return Boolean(
parsed && typeof parsed === "object" && Object.keys(parsed).length > 0,
);
} catch {
return false;
}
}
function isNeutral(adjustments: ReturnType<typeof defaultPhotoAdjustments>) {
return (
JSON.stringify(adjustments) === JSON.stringify(defaultPhotoAdjustments())
);
}
/** /**
* POST /api/events/:id/folders/:folderId/photos/:photoId/edit * POST /api/events/:id/folders/:folderId/photos/:photoId/edit
* Body: { adjustments: PhotoAdjustments } * Body: { adjustments: PhotoAdjustments }
* *
* Saves the recipe and renders a fresh full-resolution JPEG beside the * Saves the recipe and renders a fresh full-resolution JPEG beside the
* original. The original file is never changed, so an edit can always be * original. When the advanced editor has already rendered this photo, that
* reopened and adjusted again. * render is the base and the simple recipe is layered on top, so saving here
* never throws the advanced edit away. The original is never changed, so an
* edit can always be reopened and adjusted again.
*/ */
export const POST = async ( export const POST = async (
req: NextRequest, req: NextRequest,
@@ -59,8 +85,12 @@ export const POST = async (
if (!storage.ok) return errorResponse(503, storage.message); if (!storage.ok) return errorResponse(503, storage.message);
const body = (await req.json().catch(() => null)) as const body = (await req.json().catch(() => null)) as
| { adjustments?: unknown } | { adjustments?: unknown; takeOver?: unknown }
| null; | null;
// Taking over retires the advanced recipe: the sliders are rendered from the
// original file instead of on top of the advanced render, so the look is not
// applied twice.
const takeOver = body?.takeOver === true;
const adjustments = normalizePhotoAdjustments(body?.adjustments); const adjustments = normalizePhotoAdjustments(body?.adjustments);
if (!adjustments) { if (!adjustments) {
return errorResponse(400, "invalid photo adjustments"); return errorResponse(400, "invalid photo adjustments");
@@ -80,11 +110,69 @@ export const POST = async (
); );
const editedPath = eventPhotoPath(storage.root, editedStoredName); const editedPath = eventPhotoPath(storage.root, editedStoredName);
// The advanced editor's render is the base for the simple recipe.
let renderPath = sourcePath;
let renderKind = access.photo.kind;
const advancedStoredName = advancedStoredNameForEventPhoto(
access.eventId,
access.photo.id,
);
const advancedPath = eventPhotoPath(storage.root, advancedStoredName);
if (!takeOver && hasAdvancedRecipe(access.photo.advancedEditJson)) {
let advancedInfo = await stat(advancedPath).catch(() => null);
if (!advancedInfo?.isFile()) {
// Rows saved before the advanced render had its own file kept it in the
// edited path; copy it aside once so layered renders never compound.
const previous = access.photo.editedStoredName;
if (previous && previous !== advancedStoredName) {
const legacyPath = eventPhotoPath(storage.root, previous);
const legacyInfo = await stat(legacyPath).catch(() => null);
if (legacyInfo?.isFile()) {
await mkdir(path.dirname(advancedPath), { recursive: true });
await copyFile(legacyPath, advancedPath).catch(() => undefined);
advancedInfo = await stat(advancedPath).catch(() => null);
}
}
}
if (advancedInfo?.isFile()) {
renderPath = advancedPath;
renderKind = "image";
}
// Nothing layered on top: keep the advanced render as the saved edit
// instead of re-rendering it. This is a save with no slider changes, so
// say so rather than claiming a new JPEG was written.
if (renderPath === advancedPath && isNeutral(adjustments)) {
const info = await stat(advancedPath);
const alreadySaved =
access.photo.editedStoredName === advancedStoredName &&
JSON.stringify(parseStoredPhotoAdjustments(access.photo.editJson)) ===
JSON.stringify(adjustments);
const updated = await updateEventPhotoEdit({
photoId: access.photo.id,
editJson: JSON.stringify(adjustments),
editedStoredName: advancedStoredName,
editedSizeBytes: info.size,
editedBy: gate.id,
clearAdvancedEdit: false,
});
if (!updated) return errorResponse(404, "unknown photo");
return jsonResponse({
ok: true,
unchanged: alreadySaved,
adjustments,
editedFilename: editedPhotoFilename(access.photo.filename),
editedSizeBytes: info.size,
editedAt: updated.editedAt,
});
}
}
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>; let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
try { try {
rendered = await renderPhotoJpeg({ rendered = await renderPhotoJpeg({
filePath: sourcePath, filePath: renderPath,
kind: access.photo.kind, kind: renderKind,
adjustments, adjustments,
}); });
} catch (error) { } catch (error) {
@@ -113,6 +201,7 @@ export const POST = async (
editedStoredName, editedStoredName,
editedSizeBytes: rendered.data.byteLength, editedSizeBytes: rendered.data.byteLength,
editedBy: gate.id, editedBy: gate.id,
clearAdvancedEdit: takeOver,
}); });
if (!updated) { if (!updated) {
await unlink(editedPath).catch(() => undefined); await unlink(editedPath).catch(() => undefined);
@@ -127,6 +216,7 @@ export const POST = async (
editedAt: updated.editedAt, editedAt: updated.editedAt,
width: rendered.width, width: rendered.width,
height: rendered.height, height: rendered.height,
tookOver: takeOver,
}); });
} catch (error) { } catch (error) {
await unlink(editedPath).catch(() => undefined); await unlink(editedPath).catch(() => undefined);
@@ -6,6 +6,7 @@ import { gateSession } from "@/auth/api";
import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events"; import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events";
import { canDeleteEventPhoto } from "@/lib/event-access"; import { canDeleteEventPhoto } from "@/lib/event-access";
import { import {
advancedStoredNameForEventPhoto,
editedPhotoFilename, editedPhotoFilename,
eventPhotoPath, eventPhotoPath,
isBrowserRenderablePhoto, isBrowserRenderablePhoto,
@@ -19,8 +20,11 @@ import { mediaStorage } from "@/lib/media-storage";
* *
* Streams the original bytes to anyone assigned to the event (or a manager). * Streams the original bytes to anyone assigned to the event (or a manager).
* `variant=edited` serves the generated full-resolution JPEG instead, so the * `variant=edited` serves the generated full-resolution JPEG instead, so the
* gallery can show the saved look without replacing the original. RAW files * gallery can show the saved look without replacing the original.
* always download; `?download=1` forces an attachment for JPEGs too. * `variant=advanced` serves the advanced editor's own render (without any
* simple-editor layer), which is the base the simple editor previews on top of
* so its sliders can be re-applied without baking them twice. RAW files always
* download; `?download=1` forces an attachment for JPEGs too.
*/ */
export const GET = async ( export const GET = async (
req: NextRequest, req: NextRequest,
@@ -43,7 +47,9 @@ export const GET = async (
return errorResponse(404, "unknown photo"); return errorResponse(404, "unknown photo");
} }
const wantsEdited = req.nextUrl.searchParams.get("variant") === "edited"; const variant = req.nextUrl.searchParams.get("variant");
const wantsEdited = variant === "edited";
const wantsAdvanced = variant === "advanced";
if (wantsEdited && !access.photo.editedStoredName) { if (wantsEdited && !access.photo.editedStoredName) {
return errorResponse(404, "this photo has no saved edit"); return errorResponse(404, "this photo has no saved edit");
} }
@@ -51,13 +57,27 @@ export const GET = async (
const storage = await mediaStorage(); const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message); if (!storage.ok) return errorResponse(503, storage.message);
const filePath = eventPhotoPath( let servedStoredName = access.photo.storedName;
storage.root, if (wantsEdited) {
wantsEdited servedStoredName = access.photo.editedStoredName!;
? access.photo.editedStoredName! } else if (wantsAdvanced) {
: access.photo.storedName, const advancedName = advancedStoredNameForEventPhoto(id, access.photo.id);
); const advancedInfo = await stat(
const filename = wantsEdited eventPhotoPath(storage.root, advancedName),
).catch(() => null);
if (advancedInfo?.isFile()) {
servedStoredName = advancedName;
} else if (access.photo.editedStoredName) {
// Rows saved before the advanced render had its own file kept it here.
servedStoredName = access.photo.editedStoredName;
} else {
return errorResponse(404, "this photo has no advanced edit");
}
}
const generated = wantsEdited || wantsAdvanced;
const filePath = eventPhotoPath(storage.root, servedStoredName);
const filename = generated
? editedPhotoFilename(access.photo.filename) ? editedPhotoFilename(access.photo.filename)
: access.photo.filename; : access.photo.filename;
let size: number; let size: number;
@@ -69,7 +89,7 @@ export const GET = async (
const inline = const inline =
req.nextUrl.searchParams.get("download") !== "1" && req.nextUrl.searchParams.get("download") !== "1" &&
(wantsEdited || isBrowserRenderablePhoto(access.photo.filename)); (generated || isBrowserRenderablePhoto(access.photo.filename));
const stream = createReadStream(filePath); const stream = createReadStream(filePath);
return new Response( return new Response(
@@ -77,7 +97,7 @@ export const GET = async (
{ {
status: 200, status: 200,
headers: { headers: {
"content-type": wantsEdited ? "image/jpeg" : access.photo.mimeType, "content-type": generated ? "image/jpeg" : access.photo.mimeType,
"content-length": String(size), "content-length": String(size),
"content-disposition": photoContentDisposition(filename, inline), "content-disposition": photoContentDisposition(filename, inline),
"cache-control": "private, max-age=0, must-revalidate", "cache-control": "private, max-age=0, must-revalidate",
@@ -2,7 +2,6 @@ import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import sharp from "sharp";
import { gateSession } from "@/auth/api"; import { gateSession } from "@/auth/api";
import { getEventPhotoAccess } from "@/db/events"; import { getEventPhotoAccess } from "@/db/events";
import { import {
@@ -12,8 +11,7 @@ import {
} from "@/lib/event-photos"; } from "@/lib/event-photos";
import { errorResponse } from "@/lib/http"; import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage"; import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments"; import { PhotoRenderError, renderPhotoThumbnail } from "@/lib/photo-render";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
/** /**
* GET /api/events/:id/folders/:folderId/photos/:photoId/thumb * GET /api/events/:id/folders/:folderId/photos/:photoId/thumb
@@ -69,20 +67,15 @@ export const GET = async (
let data: Buffer; let data: Buffer;
try { try {
if (access.photo.kind === "raw") { if (
const rendered = await renderPhotoJpeg({ access.photo.kind === "raw" ||
isBrowserRenderablePhoto(access.photo.filename)
) {
data = await renderPhotoThumbnail({
filePath: sourcePath, filePath: sourcePath,
kind: "raw", kind: access.photo.kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: 640, maxDimension: 640,
}); });
data = rendered.data;
} else if (isBrowserRenderablePhoto(access.photo.filename)) {
data = await sharp(sourcePath, { failOn: "none", limitInputPixels: 500_000_000 })
.autoOrient()
.resize(640, 640, { fit: "inside", withoutEnlargement: true })
.jpeg({ quality: 72 })
.toBuffer();
} else { } else {
return errorResponse(415, "this photo format has no thumbnail"); return errorResponse(415, "this photo format has no thumbnail");
} }
@@ -1,58 +1,14 @@
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { createHash } from "node:crypto";
import { createWriteStream } from "node:fs";
import { mkdir, unlink } from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { gateSession } from "@/auth/api"; import { gateSession } from "@/auth/api";
import { import { getEventFolderAccess } from "@/db/events";
addEventPhoto, import { errorResponse } from "@/lib/http";
findEventPhotoByChecksum, import { uploadEventPhoto } from "@/lib/event-photo-upload";
getEventFolderAccess,
isUniqueViolation,
} from "@/db/events";
import {
MAX_EVENT_PHOTO_BYTES,
eventPhotoKindFor,
eventPhotoMimeFor,
eventPhotoPath,
sanitizePhotoFilename,
storedNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { uuidv7 } from "@/lib/uuid";
class PhotoTooLarge extends Error {}
function publicPhoto(photo: {
id: string;
folderId: string;
filename: string;
mimeType: string;
sizeBytes: number;
kind: "raw" | "image";
createdAt: Date;
}) {
return {
id: photo.id,
folderId: photo.folderId,
filename: photo.filename,
mimeType: photo.mimeType,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
createdAt: photo.createdAt,
};
}
/** /**
* POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3 * POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3
* *
* A single photo is the raw request body (not multipart), so a 100 MB RAW file * Folder-scoped upload kept for direct API use. The event page posts to
* streams straight to disk instead of being buffered in memory. The filename is * `/api/events/:id/photos`, which picks the event's one implicit folder.
* passed as a query parameter because headers cannot carry arbitrary Unicode.
* The SHA-256 is computed while streaming and dedupes a re-upload per folder.
*/ */
export const POST = async ( export const POST = async (
req: NextRequest, req: NextRequest,
@@ -70,93 +26,9 @@ export const POST = async (
return errorResponse(403, "you are not assigned to this event"); return errorResponse(403, "you are not assigned to this event");
} }
// Photos are only ever written to the configured media storage share, so refuse return uploadEventPhoto(req, {
// before reading a single byte when that destination is not ready. eventId: id,
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const suppliedName = req.nextUrl.searchParams.get("name");
if (!suppliedName) return errorResponse(400, "a filename is required");
const filename = sanitizePhotoFilename(suppliedName);
const kind = eventPhotoKindFor(filename);
if (!kind) {
return errorResponse(
415,
"only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)",
);
}
const declaredLength = Number(req.headers.get("content-length") ?? 0);
if (declaredLength > MAX_EVENT_PHOTO_BYTES) {
return errorResponse(413, "that photo is larger than 200 MB");
}
if (!req.body) return errorResponse(400, "a file body is required");
const photoId = uuidv7();
const storedName = storedNameForEventPhoto(id, photoId, filename);
const destination = eventPhotoPath(storage.root, storedName);
await mkdir(path.dirname(destination), { recursive: true });
const hash = createHash("sha256");
let size = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
size += chunk.length;
if (size > MAX_EVENT_PHOTO_BYTES) {
callback(new PhotoTooLarge());
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
try {
await pipeline(
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
meter,
createWriteStream(destination, { flags: "wx" }),
);
} catch (error) {
await unlink(destination).catch(() => undefined);
if (error instanceof PhotoTooLarge) {
return errorResponse(413, "that photo is larger than 200 MB");
}
return errorResponse(500, "the upload did not complete");
}
if (size === 0) {
await unlink(destination).catch(() => undefined);
return errorResponse(400, "the uploaded file was empty");
}
const checksumSha256 = hash.digest("hex");
const existing = await findEventPhotoByChecksum(folderId, checksumSha256);
if (existing) {
await unlink(destination).catch(() => undefined);
return jsonResponse({ photo: publicPhoto(existing), duplicate: true });
}
try {
const photo = await addEventPhoto({
folderId, folderId,
uploaderId: gate.id, uploaderId: gate.id,
filename,
mimeType: eventPhotoMimeFor(filename),
sizeBytes: size,
storedName,
checksumSha256,
kind,
}); });
return jsonResponse({ photo: publicPhoto(photo) }, 201);
} catch (error) {
await unlink(destination).catch(() => undefined);
if (isUniqueViolation(error)) {
const raced = await findEventPhotoByChecksum(folderId, checksumSha256);
if (raced) {
return jsonResponse({ photo: publicPhoto(raced), duplicate: true });
}
}
throw error;
}
}; };
+39
View File
@@ -0,0 +1,39 @@
import { NextRequest } from "next/server";
import { gateSession } from "@/auth/api";
import { ensureEventFolder, getEventAccess } from "@/db/events";
import { errorResponse } from "@/lib/http";
import { uploadEventPhoto } from "@/lib/event-photo-upload";
import { mediaStorage } from "@/lib/media-storage";
/**
* POST /api/events/:id/photos?name=IMG_0001.CR3
*
* The event page has no folder picker, so uploads land in the event's single
* folder (created as "Photos" on the first upload). Everything else is the same
* streamed, checksum-deduped upload the folder route uses.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
// Check storage before creating anything, so a blocked upload leaves no rows.
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const folder = await ensureEventFolder(id, gate.id);
return uploadEventPhoto(req, {
eventId: id,
folderId: folder.id,
uploaderId: gate.id,
});
};
+22 -1
View File
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useState } from "react"; import { useEffect, useState } from "react";
import { signIn } from "next-auth/react"; import { signIn } from "next-auth/react";
import { import {
Card, Card,
@@ -27,11 +27,27 @@ export default function LoginPage() {
}>({ kind: "idle" }); }>({ kind: "idle" });
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [linkNotice, setLinkNotice] = useState<string | null>(null);
const [linkStatus, setLinkStatus] = useState<{ const [linkStatus, setLinkStatus] = useState<{
kind: "idle" | "sending" | "sent" | "error"; kind: "idle" | "sending" | "sent" | "error";
message?: string; message?: string;
}>({ kind: "idle" }); }>({ kind: "idle" });
// /api/dev/complete redirects here when a link is dead. Say why, instead of
// dropping people on a bare sign-in form after the link fails.
useEffect(() => {
const error = new URLSearchParams(window.location.search).get("error");
if (error === "invalid_link") {
setLinkNotice(
"That sign-in link has expired or is invalid. Request a fresh email link below.",
);
} else if (error === "link_used") {
setLinkNotice(
"That sign-in link has already been used. Request a fresh email link below.",
);
}
}, []);
async function onPasswordSubmit(e: React.FormEvent) { async function onPasswordSubmit(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
setPasswordStatus({ kind: "signing" }); setPasswordStatus({ kind: "signing" });
@@ -101,6 +117,11 @@ export default function LoginPage() {
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-5"> <CardContent className="space-y-5">
{linkNotice && (
<p role="alert" className="rounded border border-border bg-muted p-3 text-sm">
{linkNotice}
</p>
)}
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4"> <form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Label htmlFor="login">Username or email</Label> <Label htmlFor="login">Username or email</Label>
+8 -2
View File
@@ -18,7 +18,13 @@ import { db } from "@/db";
import { users } from "@/db/schema"; import { users } from "@/db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { uuidv7 } from "@/lib/uuid"; import { uuidv7 } from "@/lib/uuid";
import { APP_ORIGIN, getUser, normalizeEmail, signMagicToken } from "./magic-link"; import {
APP_ORIGIN,
INVITE_LINK_TTL,
getUser,
normalizeEmail,
signMagicToken,
} from "./magic-link";
import type { UserStatus } from "@/db/schema"; import type { UserStatus } from "@/db/schema";
export type UserAction = "invite" | "approve" | "deny"; export type UserAction = "invite" | "approve" | "deny";
@@ -124,7 +130,7 @@ export async function inviteUser(input: {
appOrigin?: string; appOrigin?: string;
}) { }) {
const user = await resolveOrCreateInvitee(input.email); const user = await resolveOrCreateInvitee(input.email);
const token = await signMagicToken(user.email); const token = await signMagicToken(user.email, INVITE_LINK_TTL);
const origin = input.appOrigin ?? APP_ORIGIN; const origin = input.appOrigin ?? APP_ORIGIN;
const url = `${origin}/api/dev/complete?token=${encodeURIComponent( const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
token, token,
+16 -1
View File
@@ -1,10 +1,25 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { requestOrigin } from "./magic-link"; import { decodeJwt } from "jose";
import { INVITE_LINK_TTL, requestOrigin, signMagicToken } from "./magic-link";
function req(url: string, headers: Record<string, string>) { function req(url: string, headers: Record<string, string>) {
return { url, headers: new Headers(headers) }; return { url, headers: new Headers(headers) };
} }
describe("magic token lifetimes", () => {
it("keeps a just-requested sign-in link short", async () => {
const payload = decodeJwt(await signMagicToken("person@example.com"));
expect(payload.exp! - payload.iat!).toBe(10 * 60);
});
it("lets an invite link survive days in an inbox", async () => {
const payload = decodeJwt(
await signMagicToken("person@example.com", INVITE_LINK_TTL),
);
expect(payload.exp! - payload.iat!).toBe(7 * 24 * 60 * 60);
});
});
describe("requestOrigin", () => { describe("requestOrigin", () => {
it("uses the proxy's forwarded scheme and host", () => { it("uses the proxy's forwarded scheme and host", () => {
expect( expect(
+13 -2
View File
@@ -221,7 +221,18 @@ export async function getOrCreateUser(email: string) {
return raced; return raced;
} }
export async function signMagicToken(email: string): Promise<string> { /**
* Sign-in links are short-lived because they are requested and clicked in the
* same sitting. Invites and welcome mails are not: they land in an inbox and may
* be opened days later, so they get their own lifetime (still single use).
*/
export const SIGN_IN_LINK_TTL = "10m";
export const INVITE_LINK_TTL = "7d";
export async function signMagicToken(
email: string,
ttl: string = SIGN_IN_LINK_TTL,
): Promise<string> {
return new SignJWT({ return new SignJWT({
email, email,
purpose: "magic-link", purpose: "magic-link",
@@ -229,7 +240,7 @@ export async function signMagicToken(email: string): Promise<string> {
.setProtectedHeader({ alg: "HS256" }) .setProtectedHeader({ alg: "HS256" })
.setJti(uuidv7()) .setJti(uuidv7())
.setIssuedAt() .setIssuedAt()
.setExpirationTime("10m") .setExpirationTime(ttl)
.sign(SECRET); .sign(SECRET);
} }
@@ -0,0 +1,63 @@
"use client";
import { useState } from "react";
import { Loader2, Wand2 } from "lucide-react";
import { Button } from "@/components/ui/button";
/**
* Opens the event in the advanced editor. The bridge URL is minted by the API
* with the normal dashboard session, so this is a POST followed by a redirect.
*/
export function AdvancedEditorButton({ eventId }: { eventId: string }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function open() {
setBusy(true);
setError(null);
try {
const res = await fetch(`/api/events/${eventId}/advanced`, {
method: "POST",
});
const data = (await res.json().catch(() => ({}))) as {
url?: string;
error?: string;
};
if (!res.ok || !data.url) {
throw new Error(data.error ?? "The advanced editor could not be opened.");
}
window.location.assign(data.url);
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: "The advanced editor could not be opened.",
);
setBusy(false);
}
}
return (
<span className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={busy}
onClick={open}
>
{busy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
) : (
<Wand2 className="h-3.5 w-3.5" aria-hidden="true" />
)}
Advanced editor
</Button>
{error && (
<span role="alert" className="text-xs text-destructive">
{error}
</span>
)}
</span>
);
}
@@ -1,84 +0,0 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const SELECT_CLASS =
"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2";
/** Create a named folder inside an event ("Originals", "Edited selects"). */
export function FolderCreateForm({ eventId }: { eventId: string }) {
const router = useRouter();
const [name, setName] = useState("");
const [kind, setKind] = useState("originals");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function create() {
setBusy(true);
setError(null);
try {
const res = await fetch(`/api/events/${eventId}/folders`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name, kind }),
});
const data = (await res.json().catch(() => ({}))) as { error?: string };
if (!res.ok) {
setError(data.error ?? "Could not create the folder.");
return;
}
setName("");
router.refresh();
} catch {
setError("Network error.");
} finally {
setBusy(false);
}
}
return (
<div className="space-y-2 rounded-md border border-dashed border-border p-3">
<div className="flex flex-wrap items-end gap-2">
<div className="min-w-40 flex-1 space-y-1">
<Label htmlFor="folder-name">New folder</Label>
<Input
id="folder-name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Originals"
/>
</div>
<div className="space-y-1">
<Label htmlFor="folder-kind">Contents</Label>
<select
id="folder-kind"
className={SELECT_CLASS}
value={kind}
onChange={(event) => setKind(event.target.value)}
>
<option value="originals">RAW / originals</option>
<option value="edited">Edited exports</option>
<option value="mixed">Mixed</option>
</select>
</div>
<Button
type="button"
size="sm"
disabled={busy || name.trim().length === 0}
onClick={create}
>
{busy ? "Creating…" : "Create folder"}
</Button>
</div>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
</div>
);
}
+72 -21
View File
@@ -8,9 +8,45 @@ import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { PhotoViewer, type ViewerPhoto } from "./photo-viewer"; import { PhotoViewer, type ViewerPhoto } from "./photo-viewer";
import type { PhotoAdjustments } from "@/lib/photo-adjustments"; 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 (
<div className="flex h-full w-full flex-col items-center justify-center gap-1 px-2 text-center text-muted-foreground">
<FileImage className="h-8 w-8" aria-hidden="true" />
<span className="text-[11px] font-medium">Preview unavailable</span>
<span className="w-full truncate text-[10px]" title={alt}>
{alt}
</span>
</div>
);
}
return (
// Frames are private; the serving route sets the cache policy.
// eslint-disable-next-line @next/next/no-img-element
<img
src={src}
alt={alt}
loading="lazy"
decoding="async"
onError={() => setFailed(true)}
className="h-full w-full object-cover"
/>
);
}
export interface GalleryPhoto { export interface GalleryPhoto {
id: string; id: string;
/** Storage folder the photo lives in; photos are shown as one event gallery. */
folderId: string;
filename: string; filename: string;
sizeBytes: number; sizeBytes: number;
kind: "raw" | "image"; kind: "raw" | "image";
@@ -19,6 +55,10 @@ export interface GalleryPhoto {
previewable: boolean; previewable: boolean;
editable: boolean; editable: boolean;
adjustments: PhotoAdjustments; 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; editedAt: string | null;
editedSizeBytes: number | null; editedSizeBytes: number | null;
} }
@@ -74,13 +114,13 @@ function extensionOf(filename: string): string {
} }
/** /**
* Folder gallery + uploader. Files upload one at a time as raw request bodies, * The event's photo gallery + uploader. Files upload one at a time as raw
* which keeps a 100 MB RAW frame out of memory and gives usable per-file * request bodies, which keeps a 100 MB RAW frame out of memory and gives usable
* progress on a phone. RAW files show a file tile; JPEG/PNG/WebP preview. * per-file progress on a phone. RAW files show a file tile; JPEG/PNG/WebP
* preview.
*/ */
export function PhotoGallery({ export function PhotoGallery({
eventId, eventId,
folderId,
photos, photos,
canContribute, canContribute,
canManage, canManage,
@@ -89,7 +129,6 @@ export function PhotoGallery({
storageMessage, storageMessage,
}: { }: {
eventId: string; eventId: string;
folderId: string;
photos: GalleryPhoto[]; photos: GalleryPhoto[];
canContribute: boolean; canContribute: boolean;
canManage: boolean; canManage: boolean;
@@ -131,7 +170,7 @@ export function PhotoGallery({
setProgress({ done: index, total: files.length, current: file.name }); setProgress({ done: index, total: files.length, current: file.name });
try { try {
const res = await fetch( const res = await fetch(
`/api/events/${eventId}/folders/${folderId}/photos?name=${encodeURIComponent(file.name)}`, `/api/events/${eventId}/photos?name=${encodeURIComponent(file.name)}`,
{ {
method: "POST", method: "POST",
headers: { headers: {
@@ -171,7 +210,7 @@ export function PhotoGallery({
setNotice( setNotice(
[ [
uploaded > 0 ? `${uploaded} uploaded` : null, uploaded > 0 ? `${uploaded} uploaded` : null,
duplicates > 0 ? `${duplicates} already in this folder` : null, duplicates > 0 ? `${duplicates} already on this event` : null,
] ]
.filter(Boolean) .filter(Boolean)
.join(" · ") || null, .join(" · ") || null,
@@ -187,7 +226,7 @@ export function PhotoGallery({
setError(null); setError(null);
try { try {
const res = await fetch( const res = await fetch(
`/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`, `/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`,
{ method: "DELETE" }, { method: "DELETE" },
); );
const data = (await res.json().catch(() => ({}))) as { error?: string }; const data = (await res.json().catch(() => ({}))) as { error?: string };
@@ -214,7 +253,7 @@ export function PhotoGallery({
{canContribute && ( {canContribute && (
<div className="space-y-2 rounded-md border border-border p-3"> <div className="space-y-2 rounded-md border border-border p-3">
<p className="text-sm font-medium">Upload photos to this folder</p> <p className="text-sm font-medium">Upload photos to this event</p>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Input <Input
ref={inputRef} ref={inputRef}
@@ -272,12 +311,12 @@ export function PhotoGallery({
{photos.length === 0 ? ( {photos.length === 0 ? (
<p className="py-10 text-center text-sm text-muted-foreground"> <p className="py-10 text-center text-sm text-muted-foreground">
This folder is empty. No photos yet. Upload the first frame for this event.
</p> </p>
) : ( ) : (
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4"> <ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
{photos.map((photo) => { {photos.map((photo) => {
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`; const src = `/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`;
const editable = photo.editable && storageReady; const editable = photo.editable && storageReady;
const canRemove = canManage || photo.uploaderId === currentUserId; const canRemove = canManage || photo.uploaderId === currentUserId;
const version = photo.editedAt ? Date.parse(photo.editedAt) : 0; const version = photo.editedAt ? Date.parse(photo.editedAt) : 0;
@@ -303,15 +342,7 @@ export function PhotoGallery({
onClick={() => setViewing(photo)} onClick={() => setViewing(photo)}
> >
{photo.previewable || photo.editedAt || photo.kind === "raw" ? ( {photo.previewable || photo.editedAt || photo.kind === "raw" ? (
// Frames are private; the serving route sets the cache policy. <GalleryImage src={displaySrc} alt={photo.filename} />
// eslint-disable-next-line @next/next/no-img-element
<img
src={displaySrc}
alt={photo.filename}
loading="lazy"
decoding="async"
className="h-full w-full object-cover"
/>
) : ( ) : (
<div className="flex flex-col items-center gap-1 text-muted-foreground"> <div className="flex flex-col items-center gap-1 text-muted-foreground">
<FileImage className="h-8 w-8" aria-hidden="true" /> <FileImage className="h-8 w-8" aria-hidden="true" />
@@ -353,6 +384,23 @@ export function PhotoGallery({
{photo.uploaderName} {photo.uploaderName}
</p> </p>
<div className="flex flex-wrap items-center gap-1"> <div className="flex flex-wrap items-center gap-1">
{photo.editedAt ? (
<>
<a
href={`${src}?variant=edited&download=1&v=${version}`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
>
<Download className="h-3 w-3" aria-hidden="true" />
Download edited
</a>
<a
href={`${src}?download=1`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-muted-foreground hover:underline"
>
Original
</a>
</>
) : (
<a <a
href={`${src}?download=1`} href={`${src}?download=1`}
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline" className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
@@ -360,6 +408,7 @@ export function PhotoGallery({
<Download className="h-3 w-3" aria-hidden="true" /> <Download className="h-3 w-3" aria-hidden="true" />
Download Download
</a> </a>
)}
{editable && ( {editable && (
<button <button
type="button" type="button"
@@ -392,7 +441,7 @@ export function PhotoGallery({
<PhotoViewer <PhotoViewer
key={viewing.id} key={viewing.id}
eventId={eventId} eventId={eventId}
folderId={folderId} folderId={viewing.folderId}
photo={{ photo={{
id: viewing.id, id: viewing.id,
filename: viewing.filename, filename: viewing.filename,
@@ -400,6 +449,8 @@ export function PhotoGallery({
editedAt: viewing.editedAt, editedAt: viewing.editedAt,
editedSizeBytes: viewing.editedSizeBytes, editedSizeBytes: viewing.editedSizeBytes,
adjustments: viewing.adjustments, adjustments: viewing.adjustments,
advancedEdit: viewing.advancedEdit,
advancedSummary: viewing.advancedSummary,
} satisfies ViewerPhoto} } satisfies ViewerPhoto}
onClose={() => setViewing(null)} onClose={() => setViewing(null)}
onSaved={() => router.refresh()} onSaved={() => router.refresh()}
+292 -8
View File
@@ -39,6 +39,7 @@ import {
} from "@/lib/photo-geometry"; } from "@/lib/photo-geometry";
import { PHOTO_EXPORT_PRESETS } from "@/lib/photo-exports"; import { PHOTO_EXPORT_PRESETS } from "@/lib/photo-exports";
import { PHOTO_PRESETS, applyPhotoPreset } from "@/lib/photo-presets"; import { PHOTO_PRESETS, applyPhotoPreset } from "@/lib/photo-presets";
import type { AdvancedEditView, QuickNumericSetting } from "@/lib/advanced-edit";
export interface ViewerPhoto { export interface ViewerPhoto {
id: string; id: string;
@@ -47,6 +48,10 @@ export interface ViewerPhoto {
editedAt: string | null; editedAt: string | null;
editedSizeBytes: number | null; editedSizeBytes: number | null;
adjustments: PhotoAdjustments; adjustments: PhotoAdjustments;
/** The saved edit came from the advanced editor; it cannot be re-applied here. */
advancedEdit: boolean;
/** Read-only view of the advanced recipe plus a quick-editor seed. */
advancedSummary: AdvancedEditView | null;
} }
type EditorTab = "light" | "color" | "detail" | "geometry" | "presets"; type EditorTab = "light" | "color" | "detail" | "geometry" | "presets";
@@ -390,12 +395,36 @@ export function PhotoViewer({
onNext?: () => void; onNext?: () => void;
}) { }) {
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`; const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`;
// An advanced edit is baked into its own render. The viewer previews that
// render and layers this editor's sliders on top, so both editors keep their
// work instead of the advanced look being replaced by a neutral render.
const showsAdvancedEdit = photo.advancedEdit && Boolean(photo.editedAt);
// A photo whose saved look is the advanced render and whose quick layer is
// untouched opens with the advanced settings already in the sliders, so the
// quick editor shows the same numbers the look was made with instead of a
// confusing row of zeros.
const advancedSeed = photo.advancedSummary?.seed ?? null;
const quickLayerIsNeutral =
JSON.stringify(photo.adjustments) === JSON.stringify(defaultPhotoAdjustments());
const autoSeed = showsAdvancedEdit && Boolean(advancedSeed) && quickLayerIsNeutral;
const [takeOverPending, setTakeOverPending] = useState(autoSeed);
const [advancedRetired, setAdvancedRetired] = useState(false);
const autoSeeded = useRef(autoSeed);
const showAdvancedPanel = showsAdvancedEdit && !advancedRetired;
// Once the sliders take over they render from the original file, so the
// preview must not keep the advanced render underneath them.
const basesOnAdvanced = showsAdvancedEdit && !takeOverPending;
const previewSrc = basesOnAdvanced
? `${src}?variant=advanced&v=${photo.editedAt ? Date.parse(photo.editedAt) : 0}`
: `${src}/preview`;
const canvasRef = useRef<HTMLCanvasElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null);
const rotatedRef = useRef<{ key: string; canvas: HTMLCanvasElement } | null>( const rotatedRef = useRef<{ key: string; canvas: HTMLCanvasElement } | null>(
null, null,
); );
const [adjustments, setAdjustments] = useState<PhotoAdjustments>(() => const [adjustments, setAdjustments] = useState<PhotoAdjustments>(() =>
cloneAdjustments(photo.adjustments), autoSeed && advancedSeed
? cloneAdjustments(advancedSeed)
: cloneAdjustments(photo.adjustments),
); );
const [tab, setTab] = useState<EditorTab>("light"); const [tab, setTab] = useState<EditorTab>("light");
const [source, setSource] = useState<HTMLImageElement | null>(null); const [source, setSource] = useState<HTMLImageElement | null>(null);
@@ -416,11 +445,22 @@ export function PhotoViewer({
editedSizeBytes: number; editedSizeBytes: number;
width: number; width: number;
height: number; height: number;
/** Nothing was re-rendered because the saved edit is already this look. */
unchanged?: boolean;
} | null>(null); } | null>(null);
const [savedVersion, setSavedVersion] = useState(() => const [savedVersion, setSavedVersion] = useState(() =>
photo.editedAt ? Date.parse(photo.editedAt) : 0, photo.editedAt ? Date.parse(photo.editedAt) : 0,
); );
const [recipeMessage, setRecipeMessage] = useState<string | null>(null); const [recipeMessage, setRecipeMessage] = useState<string | null>(null);
const [takeOverMessage, setTakeOverMessage] = useState<string | null>(null);
const [hoverSetting, setHoverSetting] = useState<{
label: string;
key: QuickNumericSetting;
amount: number;
} | null>(null);
const inlineRef = useRef<HTMLCanvasElement>(null);
const inlineSourceRef = useRef<HTMLImageElement | null>(null);
const [inlineReady, setInlineReady] = useState(false);
useEffect(() => { useEffect(() => {
const onKey = (event: KeyboardEvent) => { const onKey = (event: KeyboardEvent) => {
@@ -468,12 +508,12 @@ export function PhotoViewer({
"The preview could not be prepared. You can still try saving the edit.", "The preview could not be prepared. You can still try saving the edit.",
); );
}; };
image.src = `${src}/preview`; image.src = previewSrc;
return () => { return () => {
active = false; active = false;
image.src = ""; image.src = "";
}; };
}, [src]); }, [previewSrc]);
useEffect(() => { useEffect(() => {
if (!source) return; if (!source) return;
@@ -559,6 +599,52 @@ export function PhotoViewer({
}; };
}, [adjustments, source, showOriginal]); }, [adjustments, source, showOriginal]);
// The inline preview shows one advanced setting applied to the untouched
// original, so the summary reads as "what this control does" rather than a
// number on its own.
useEffect(() => {
if (!showAdvancedPanel) return;
let active = true;
const image = new Image();
image.onload = () => {
if (!active) return;
inlineSourceRef.current = image;
setInlineReady(true);
};
image.src = `${src}/preview`;
return () => {
active = false;
image.src = "";
};
}, [showAdvancedPanel, src]);
useEffect(() => {
const canvas = inlineRef.current;
const image = inlineSourceRef.current;
if (!canvas || !image || !hoverSetting) return;
const width = 240;
const height = Math.max(
1,
Math.round((width * image.naturalHeight) / Math.max(1, image.naturalWidth)),
);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
const context = canvas.getContext("2d", { willReadFrequently: true });
if (!context) return;
context.drawImage(image, 0, 0, width, height);
const data = context.getImageData(0, 0, width, height);
applyPhotoAdjustmentsToRgba(
data.data,
width,
height,
{ ...defaultPhotoAdjustments(), [hoverSetting.key]: hoverSetting.amount },
4,
);
context.putImageData(data, 0, 0);
}, [hoverSetting, inlineReady]);
function update<K extends keyof PhotoAdjustments>( function update<K extends keyof PhotoAdjustments>(
key: K, key: K,
value: PhotoAdjustments[K], value: PhotoAdjustments[K],
@@ -635,6 +721,32 @@ export function PhotoViewer({
} }
} }
/**
* Seed the sliders from the advanced recipe. The look is already saved in the
* advanced render, so nothing is written until the photographer saves; the
* next save retires the advanced recipe and renders from the original.
*/
function takeOverFromAdvanced() {
const view = photo.advancedSummary;
if (!view) return;
setAdjustments(cloneAdjustments(view.seed));
setTakeOverPending(true);
setTab("light");
setSaveError(null);
setSaveResult(null);
setRecipeMessage(null);
setTakeOverMessage(
"Advanced settings loaded. Review the sliders, then save to make this editor the source of truth.",
);
}
function undoTakeOver() {
setAdjustments(cloneAdjustments(photo.adjustments));
setTakeOverPending(false);
setTakeOverMessage(null);
setSaveError(null);
}
async function save() { async function save() {
setSaving(true); setSaving(true);
setSaveError(null); setSaveError(null);
@@ -642,7 +754,10 @@ export function PhotoViewer({
const response = await fetch(`${src}/edit`, { const response = await fetch(`${src}/edit`, {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ adjustments }), body: JSON.stringify({
adjustments,
...(takeOverPending ? { takeOver: true } : {}),
}),
}); });
const data = (await response.json().catch(() => ({}))) as { const data = (await response.json().catch(() => ({}))) as {
error?: string; error?: string;
@@ -650,6 +765,8 @@ export function PhotoViewer({
editedSizeBytes?: number; editedSizeBytes?: number;
width?: number; width?: number;
height?: number; height?: number;
unchanged?: boolean;
tookOver?: boolean;
}; };
if (!response.ok || !data.editedAt) { if (!response.ok || !data.editedAt) {
setSaveError(data.error ?? "The edited JPEG could not be saved."); setSaveError(data.error ?? "The edited JPEG could not be saved.");
@@ -660,8 +777,15 @@ export function PhotoViewer({
editedSizeBytes: data.editedSizeBytes ?? 0, editedSizeBytes: data.editedSizeBytes ?? 0,
width: data.width ?? 0, width: data.width ?? 0,
height: data.height ?? 0, height: data.height ?? 0,
unchanged: data.unchanged === true,
}); });
setSavedVersion(Date.now()); setSavedVersion(Date.now());
if (data.tookOver === true) {
setAdvancedRetired(true);
setTakeOverMessage(
"Saved from the original file. The advanced recipe is retired and these sliders are now the saved look.",
);
}
onSaved(); onSaved();
} catch { } catch {
setSaveError("Network error while saving the edit."); setSaveError("Network error while saving the edit.");
@@ -811,7 +935,9 @@ export function PhotoViewer({
<div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-2 text-[11px] text-white/55"> <div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-2 text-[11px] text-white/55">
<span> <span>
{showOriginal {showOriginal
? "Original look with crop" ? basesOnAdvanced
? "Before your slider changes"
: "Original look with crop"
: "Live preview · saved at full resolution"} : "Live preview · saved at full resolution"}
</span> </span>
{recipeMessage && <span>{recipeMessage}</span>} {recipeMessage && <span>{recipeMessage}</span>}
@@ -852,6 +978,116 @@ export function PhotoViewer({
<Histogram histogram={histogram} /> <Histogram histogram={histogram} />
</div> </div>
{showAdvancedPanel && photo.advancedSummary && (
<details className="border-b border-border px-3 py-2">
<summary className="flex cursor-pointer items-center justify-between gap-2 text-xs font-medium">
<span>Advanced editor settings</span>
<span className="text-[11px] font-normal text-muted-foreground">
Read-only
</span>
</summary>
<div className="mt-2 space-y-2.5">
<div className="rounded-md border border-border bg-muted/20 p-1.5">
{/* Fixed height: a hover must not move the rows under the
cursor, or the preview would flicker on and off. */}
<div className="flex h-24 items-center justify-center overflow-hidden rounded bg-black/5">
<canvas
ref={inlineRef}
aria-label="Preview of the hovered advanced setting on the original photo"
className={`max-h-full max-w-full rounded ${hoverSetting ? "" : "hidden"}`}
/>
{!hoverSetting && (
<span className="px-2 text-center text-[10px] text-muted-foreground">
Hover a setting to preview it
</span>
)}
</div>
<p className="mt-1 h-7 text-[10px] leading-snug text-muted-foreground">
{hoverSetting
? `${hoverSetting.label} on the original file`
: "Each setting is shown on its own, applied to the original file."}
</p>
</div>
{photo.advancedSummary.sections.length === 0 && (
<p className="text-[11px] leading-snug text-muted-foreground">
The advanced editor saved this photo without changing any
tone or colour setting.
</p>
)}
{photo.advancedSummary.sections.map((section) => (
<div key={section.title}>
<p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
{section.title}
</p>
<dl className="mt-0.5 space-y-0.5">
{section.items.map((item) => (
<div
key={`${section.title}-${item.label}`}
className={`-mx-1 flex items-baseline justify-between gap-3 rounded px-1 text-[11px] ${
item.preview ? "cursor-help hover:bg-muted/70" : ""
}`}
onMouseEnter={() =>
setHoverSetting(
item.preview
? {
label: item.label,
key: item.preview.key,
amount: item.preview.amount,
}
: null,
)
}
onMouseLeave={() => setHoverSetting(null)}
>
<dt className="text-muted-foreground">{item.label}</dt>
<dd className="font-mono tabular-nums">{item.value}</dd>
</div>
))}
</dl>
</div>
))}
{photo.advancedSummary.onlyAdvanced.length > 0 && (
<p className="text-[11px] leading-snug text-muted-foreground">
Only in the advanced editor:{" "}
{photo.advancedSummary.onlyAdvanced.join(", ")}.
</p>
)}
{photo.advancedSummary.caveats.map((caveat) => (
<p
key={caveat}
className="text-[11px] leading-snug text-muted-foreground"
>
{caveat}
</p>
))}
{takeOverPending ? (
<p className="text-[11px] leading-snug text-muted-foreground">
{autoSeeded.current
? "The sliders already hold these settings, previewed on the original file. Saving makes them the saved look."
: "These settings are loaded in the sliders, previewed on the original file. Saving makes them the saved look."}
</p>
) : (
<>
<Button
type="button"
variant="outline"
size="sm"
className="h-8 w-full text-xs"
disabled={saving}
onClick={takeOverFromAdvanced}
>
Take over in the quick editor
</Button>
<p className="text-[11px] leading-snug text-muted-foreground">
Loads these values into the sliders. Saving then retires
the advanced recipe and renders from the original file.
</p>
</>
)}
</div>
</details>
)}
<div className="flex gap-1 overflow-x-auto border-b border-border px-2 py-2"> <div className="flex gap-1 overflow-x-auto border-b border-border px-2 py-2">
{TABS.map((item) => ( {TABS.map((item) => (
<button <button
@@ -1216,18 +1452,66 @@ export function PhotoViewer({
</p> </p>
)} )}
{saveResult && ( {basesOnAdvanced && (
<p className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground">
The advanced editor&apos;s edit is kept as the base. Slider
changes here are saved on top of it, and saving in the advanced
editor again keeps this layer.
</p>
)}
{takeOverPending && (
<div className="space-y-1.5 rounded-md border border-border bg-muted/40 p-2">
<p className="text-[11px] leading-snug text-muted-foreground">
{autoSeeded.current
? "These sliders were filled from the advanced edit and are previewed on the original file."
: "These values came from the advanced edit and are previewed on the original file."}{" "}
Saving makes the quick editor the source of truth and retires
the advanced recipe.
</p>
<button
type="button"
className="text-[11px] font-medium text-primary hover:underline"
onClick={undoTakeOver}
>
Undo takeover
</button>
</div>
)}
{takeOverMessage && !saveError && (
<p
role="status"
className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground"
>
{takeOverMessage}
</p>
)}
{saveResult &&
(saveResult.unchanged ? (
<p
role="status"
className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground"
>
No changes to apply — the saved version is already the
advanced editor&apos;s render. Move a slider to save your own
adjustments on top of it.
</p>
) : (
<div <div
role="status" role="status"
className="space-y-1 rounded-md border border-border bg-muted/40 p-3 text-xs" className="space-y-1 rounded-md border border-border bg-muted/40 p-3 text-xs"
> >
<p className="font-medium">Full-resolution JPEG saved.</p> <p className="font-medium">Full-resolution JPEG saved.</p>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
{saveResult.width} × {saveResult.height} ·{" "} {saveResult.width > 0 && saveResult.height > 0
? `${saveResult.width} × ${saveResult.height} · `
: ""}
{formatBytes(saveResult.editedSizeBytes)} {formatBytes(saveResult.editedSizeBytes)}
</p> </p>
</div> </div>
)} ))}
{hasSavedEdit && ( {hasSavedEdit && (
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3"> <div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
+12
View File
@@ -112,6 +112,12 @@ export interface BridgePhotoRow {
sizeBytes: number; sizeBytes: number;
storedName: string; storedName: string;
editedStoredName: string | null; 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; createdAt: Date;
folderName: string; folderName: string;
} }
@@ -128,6 +134,9 @@ export async function listBridgePhotos(
sizeBytes: eventPhotos.sizeBytes, sizeBytes: eventPhotos.sizeBytes,
storedName: eventPhotos.storedName, storedName: eventPhotos.storedName,
editedStoredName: eventPhotos.editedStoredName, editedStoredName: eventPhotos.editedStoredName,
advancedEditJson: eventPhotos.advancedEditJson,
editJson: eventPhotos.editJson,
editedAt: eventPhotos.editedAt,
createdAt: eventPhotos.createdAt, createdAt: eventPhotos.createdAt,
folderName: eventFolders.name, folderName: eventFolders.name,
}) })
@@ -150,6 +159,9 @@ export async function getBridgePhoto(
sizeBytes: eventPhotos.sizeBytes, sizeBytes: eventPhotos.sizeBytes,
storedName: eventPhotos.storedName, storedName: eventPhotos.storedName,
editedStoredName: eventPhotos.editedStoredName, editedStoredName: eventPhotos.editedStoredName,
advancedEditJson: eventPhotos.advancedEditJson,
editJson: eventPhotos.editJson,
editedAt: eventPhotos.editedAt,
createdAt: eventPhotos.createdAt, createdAt: eventPhotos.createdAt,
folderName: eventFolders.name, folderName: eventFolders.name,
}) })
+107
View File
@@ -73,6 +73,7 @@ export interface EventPhotoRow {
checksumSha256: string; checksumSha256: string;
kind: "raw" | "image"; kind: "raw" | "image";
editJson: string | null; editJson: string | null;
advancedEditJson: string | null;
editedStoredName: string | null; editedStoredName: string | null;
editedSizeBytes: number | null; editedSizeBytes: number | null;
editedAt: Date | null; editedAt: Date | null;
@@ -374,6 +375,7 @@ export async function getFolderDetail(
checksumSha256: eventPhotos.checksumSha256, checksumSha256: eventPhotos.checksumSha256,
kind: eventPhotos.kind, kind: eventPhotos.kind,
editJson: eventPhotos.editJson, editJson: eventPhotos.editJson,
advancedEditJson: eventPhotos.advancedEditJson,
editedStoredName: eventPhotos.editedStoredName, editedStoredName: eventPhotos.editedStoredName,
editedSizeBytes: eventPhotos.editedSizeBytes, editedSizeBytes: eventPhotos.editedSizeBytes,
editedAt: eventPhotos.editedAt, editedAt: eventPhotos.editedAt,
@@ -402,6 +404,106 @@ export async function getFolderDetail(
}; };
} }
/**
* Every photo in an event, newest last, across all of its storage folders.
* The event page renders these as one gallery; folders are an internal detail
* and never shown to photographers.
*/
export async function listEventPhotos(
eventId: string,
): Promise<EventPhotoRow[]> {
return db
.select({
id: eventPhotos.id,
folderId: eventPhotos.folderId,
uploaderId: eventPhotos.uploaderId,
uploaderName: userName,
filename: eventPhotos.filename,
mimeType: eventPhotos.mimeType,
sizeBytes: eventPhotos.sizeBytes,
storedName: eventPhotos.storedName,
checksumSha256: eventPhotos.checksumSha256,
kind: eventPhotos.kind,
editJson: eventPhotos.editJson,
advancedEditJson: eventPhotos.advancedEditJson,
editedStoredName: eventPhotos.editedStoredName,
editedSizeBytes: eventPhotos.editedSizeBytes,
editedAt: eventPhotos.editedAt,
editedBy: eventPhotos.editedBy,
createdAt: eventPhotos.createdAt,
})
.from(eventPhotos)
.innerJoin(eventFolders, eq(eventFolders.id, eventPhotos.folderId))
.innerJoin(users, eq(users.id, eventPhotos.uploaderId))
.where(eq(eventFolders.eventId, eventId))
.orderBy(asc(eventPhotos.createdAt));
}
/**
* The folder new uploads land in. Events no longer expose folders, so this is
* the oldest existing folder (events created before the flattening keep theirs)
* or a single implicit "Photos" folder on the first upload. Two simultaneous
* first uploads race on the unique (event, name) index; the loser reads the
* winner's row.
*/
export async function ensureEventFolder(
eventId: string,
createdBy: string,
): Promise<EventFolderRow> {
const existing = await firstFolderFor(eventId);
if (existing) return existing;
try {
const row = await createEventFolder({
eventId,
name: "Photos",
kind: "mixed",
createdBy,
});
return {
id: row.id,
name: row.name,
kind: row.kind,
createdAt: row.createdAt,
photoCount: 0,
totalBytes: 0,
};
} catch (error) {
if (isUniqueViolation(error)) {
const raced = await firstFolderFor(eventId);
if (raced) return raced;
}
throw error;
}
}
async function firstFolderFor(eventId: string): Promise<EventFolderRow | null> {
const [row] = await db
.select({
folderId: eventFolders.id,
name: eventFolders.name,
kind: eventFolders.kind,
createdAt: eventFolders.createdAt,
photoCount: sql<number>`count(${eventPhotos.id})`,
totalBytes: sql<number>`coalesce(sum(${eventPhotos.sizeBytes}), 0)`,
})
.from(eventFolders)
.leftJoin(eventPhotos, eq(eventPhotos.folderId, eventFolders.id))
.where(eq(eventFolders.eventId, eventId))
.groupBy(eventFolders.id)
.orderBy(asc(eventFolders.createdAt))
.limit(1);
if (!row) return null;
return {
id: row.folderId,
name: row.name,
kind: row.kind,
createdAt: row.createdAt,
photoCount: numeric(row.photoCount),
totalBytes: numeric(row.totalBytes),
};
}
/** /**
* Every photo in an event with its folder name, for the whole-event ZIP. The * Every photo in an event with its folder name, for the whole-event ZIP. The
* caller must check event access first; this query intentionally does not. * caller must check event access first; this query intentionally does not.
@@ -672,11 +774,16 @@ export async function updateEventPhotoEdit(input: {
editedStoredName: string; editedStoredName: string;
editedSizeBytes: number; editedSizeBytes: number;
editedBy: string; editedBy: string;
/** True when the quick editor takes the look over from the advanced render. */
clearAdvancedEdit?: boolean;
}) { }) {
const [row] = await db const [row] = await db
.update(eventPhotos) .update(eventPhotos)
.set({ .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, editJson: input.editJson,
...(input.clearAdvancedEdit ? { advancedEditJson: null } : {}),
editedStoredName: input.editedStoredName, editedStoredName: input.editedStoredName,
editedSizeBytes: input.editedSizeBytes, editedSizeBytes: input.editedSizeBytes,
editedAt: new Date(), editedAt: new Date(),
+125
View File
@@ -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());
});
});
+571
View File
@@ -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<string, unknown> {
return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
}
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<string, unknown>;
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<string, string> = {
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),
};
}
+14 -2
View File
@@ -24,6 +24,12 @@ export interface BridgeTokenPayload {
kind: "login" | "service"; kind: "login" | "service";
/** Unix seconds. */ /** Unix seconds. */
exp: number; 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; export const BRIDGE_LOGIN_TTL_SECONDS = 10 * 60;
@@ -108,9 +114,15 @@ export function verifyBridgeToken(
return payload as BridgeTokenPayload; 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 { 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; if (!origin) return null;
return `${origin.replace(/\/+$/, "")}/events/${eventId}`; return `${origin.replace(/\/+$/, "")}/events/${eventId}`;
} }
+160
View File
@@ -0,0 +1,160 @@
import { createHash } from "node:crypto";
import { createWriteStream } from "node:fs";
import { mkdir, unlink } from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import type { NextRequest } from "next/server";
import {
addEventPhoto,
findEventPhotoByChecksum,
isUniqueViolation,
} from "@/db/events";
import {
MAX_EVENT_PHOTO_BYTES,
eventPhotoKindFor,
eventPhotoMimeFor,
eventPhotoPath,
sanitizePhotoFilename,
storedNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { uuidv7 } from "@/lib/uuid";
class PhotoTooLarge extends Error {}
function publicPhoto(photo: {
id: string;
folderId: string;
filename: string;
mimeType: string;
sizeBytes: number;
kind: "raw" | "image";
createdAt: Date;
}) {
return {
id: photo.id,
folderId: photo.folderId,
filename: photo.filename,
mimeType: photo.mimeType,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
createdAt: photo.createdAt,
};
}
/**
* A single photo is the raw request body (not multipart), so a 100 MB RAW file
* streams straight to disk instead of being buffered in memory. The filename is
* passed as a query parameter because headers cannot carry arbitrary Unicode.
* The SHA-256 is computed while streaming and dedupes a re-upload per folder.
*
* The caller owns the access check and picks the destination folder: the event
* page uploads through `/api/events/:id/photos`, while the folder route is kept
* for older links and direct API use.
*/
export async function uploadEventPhoto(
req: NextRequest,
input: { eventId: string; folderId: string; uploaderId: string },
): Promise<Response> {
// Photos are only ever written to the configured media storage share, so refuse
// before reading a single byte when that destination is not ready.
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const suppliedName = req.nextUrl.searchParams.get("name");
if (!suppliedName) return errorResponse(400, "a filename is required");
const filename = sanitizePhotoFilename(suppliedName);
const kind = eventPhotoKindFor(filename);
if (!kind) {
return errorResponse(
415,
"only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)",
);
}
const declaredLength = Number(req.headers.get("content-length") ?? 0);
if (declaredLength > MAX_EVENT_PHOTO_BYTES) {
return errorResponse(413, "that photo is larger than 200 MB");
}
if (!req.body) return errorResponse(400, "a file body is required");
const photoId = uuidv7();
const storedName = storedNameForEventPhoto(
input.eventId,
photoId,
filename,
);
const destination = eventPhotoPath(storage.root, storedName);
await mkdir(path.dirname(destination), { recursive: true });
const hash = createHash("sha256");
let size = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
size += chunk.length;
if (size > MAX_EVENT_PHOTO_BYTES) {
callback(new PhotoTooLarge());
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
try {
await pipeline(
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
meter,
createWriteStream(destination, { flags: "wx" }),
);
} catch (error) {
await unlink(destination).catch(() => undefined);
if (error instanceof PhotoTooLarge) {
return errorResponse(413, "that photo is larger than 200 MB");
}
return errorResponse(500, "the upload did not complete");
}
if (size === 0) {
await unlink(destination).catch(() => undefined);
return errorResponse(400, "the uploaded file was empty");
}
const checksumSha256 = hash.digest("hex");
const existing = await findEventPhotoByChecksum(
input.folderId,
checksumSha256,
);
if (existing) {
await unlink(destination).catch(() => undefined);
return jsonResponse({ photo: publicPhoto(existing), duplicate: true });
}
try {
const photo = await addEventPhoto({
folderId: input.folderId,
uploaderId: input.uploaderId,
filename,
mimeType: eventPhotoMimeFor(filename),
sizeBytes: size,
storedName,
checksumSha256,
kind,
});
return jsonResponse({ photo: publicPhoto(photo) }, 201);
} catch (error) {
await unlink(destination).catch(() => undefined);
if (isUniqueViolation(error)) {
const raced = await findEventPhotoByChecksum(
input.folderId,
checksumSha256,
);
if (raced) {
return jsonResponse({ photo: publicPhoto(raced), duplicate: true });
}
}
throw error;
}
}
+26
View File
@@ -160,6 +160,19 @@ export function editedStoredNameForEventPhoto(
return `events/${eventId}/edits/${photoId}.jpg`; 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. */ /** Lazily generated small grid thumbnail of the untouched original. */
export function thumbStoredNameForEventPhoto( export function thumbStoredNameForEventPhoto(
eventId: string, eventId: string,
@@ -196,6 +209,19 @@ export function bridgeThumbStoredNameForEventPhoto(
return `events/${eventId}/previews/${photoId}-bridge-thumb.jpg`; 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 { function assertEventPhotoIds(eventId: string, photoId: string): void {
const safeId = /^[A-Za-z0-9_-]+$/; const safeId = /^[A-Za-z0-9_-]+$/;
if (!safeId.test(eventId) || !safeId.test(photoId)) { if (!safeId.test(eventId) || !safeId.test(photoId)) {
+115 -1
View File
@@ -10,13 +10,14 @@
*/ */
import { execFile } from "node:child_process"; 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 { tmpdir } from "node:os";
import path from "node:path"; import path from "node:path";
import { promisify } from "node:util"; import { promisify } from "node:util";
import sharp from "sharp"; import sharp from "sharp";
import { import {
applyPhotoAdjustmentsToRgba, applyPhotoAdjustmentsToRgba,
defaultPhotoAdjustments,
type PhotoAdjustments, type PhotoAdjustments,
} from "./photo-adjustments"; } from "./photo-adjustments";
import { cropInterleavedRgb, cropRectForCanvas } from "./photo-geometry"; import { cropInterleavedRgb, cropRectForCanvas } from "./photo-geometry";
@@ -90,6 +91,119 @@ export interface RenderedPhoto {
height: number; 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<void> } | 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<Buffer> {
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. */ /** Source dimensions after applying the EXIF orientation the browser sees. */
async function orientedDimensions( async function orientedDimensions(
filePath: string, filePath: string,
+2 -2
View File
@@ -60,7 +60,7 @@ export async function sendWelcomeEmail(
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a> <a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
</p> </p>
<p style="font-size: 12px; color: #6b7280;"> <p style="font-size: 12px; color: #6b7280;">
The link expires in 10 minutes and works once. If it has expired, open the The link expires in 7 days and works once. If it has expired, open the
sign-in page and request a fresh link with this email address. After sign-in page and request a fresh link with this email address. After
signing in you can set a password from your profile. signing in you can set a password from your profile.
</p> </p>
@@ -75,7 +75,7 @@ export async function sendWelcomeEmail(
`Sign in: ${user.email}`, `Sign in: ${user.email}`,
`Username: ${user.username || user.email}`, `Username: ${user.username || user.email}`,
"", "",
`Open this link to sign in (expires in 10 minutes, single use):`, `Open this link to sign in (expires in 7 days, single use):`,
url, url,
"", "",
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.", "If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",