From fac9b96cca363df27e5746cb952ac5bae54580e1 Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Sat, 21 Nov 2026 14:37:57 +0000 Subject: [PATCH] feat(events): show every photo on the event page without folders MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 8 +- e2e/events.spec.ts | 22 +-- e2e/growth-and-maintenance.spec.ts | 11 +- .../events/[id]/folders/[folderId]/page.tsx | 141 --------------- src/app/(app)/events/[id]/page.tsx | 129 ++++++++------ src/app/(app)/media/page.tsx | 8 +- src/app/(app)/training/guides/admin/page.tsx | 2 +- .../[id]/folders/[folderId]/photos/route.ts | 146 +--------------- src/app/api/events/[id]/photos/route.ts | 39 +++++ .../app/events/folder-create-form.tsx | 84 --------- src/components/app/events/photo-gallery.tsx | 25 +-- src/db/events.ts | 100 +++++++++++ src/lib/event-photo-upload.ts | 160 ++++++++++++++++++ 13 files changed, 416 insertions(+), 459 deletions(-) delete mode 100644 src/app/(app)/events/[id]/folders/[folderId]/page.tsx create mode 100644 src/app/api/events/[id]/photos/route.ts delete mode 100644 src/components/app/events/folder-create-form.tsx create mode 100644 src/lib/event-photo-upload.ts diff --git a/README.md b/README.md index 4c3b894..22373e5 100644 --- a/README.md +++ b/README.md @@ -68,9 +68,9 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It ### Events and media -- One-off events with a shot brief, location, times, photographer/editor assignments, and per-event shared folders. -- RAW and JPEG uploads streamed to disk, SHA-256 dedupe per folder, 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. +- 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 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, 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. - Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/`, a minimal `/embed/` iframe, and an oEmbed endpoint. - Announcements feed with draft/publish/delete for coordinators and admins. @@ -837,7 +837,7 @@ that the gallery shows. | `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet | | `/availability` | Personal and team blackout management | | `/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 | | `/training`, `/training/guides/*` | Lessons, attachments, role guides | | `/announcements` | Team feed | diff --git a/e2e/events.spec.ts b/e2e/events.spec.ts index 930c57d..e9185a1 100644 --- a/e2e/events.spec.ts +++ b/e2e/events.spec.ts @@ -4,8 +4,8 @@ import { signInAs, resetDb, BASE } from "./dev"; /** * 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 - * RAW original; the second — not the uploader — downloads the untouched bytes. + * photographers; the first uploads a JPEG and a RAW original straight onto the + * event page; the second — not the uploader — downloads the untouched bytes. * 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(); }); - test("an assigned photographer creates a folder and uploads files", async ({ + test("an assigned photographer uploads files on the event page", async ({ page, }) => { await page.setViewportSize({ width: 1200, height: 900 }); await signInAs(page, "avery@glenloch.local"); 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([ { name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO }, { 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 signInAs(page, "sam@glenloch.local"); await page.goto(eventUrl); - await page.getByRole("link", { name: /Originals/ }).click(); const [download] = await Promise.all([ page.waitForEvent("download"), - // Exact: the folder header also offers "Download folder (n)". page.getByRole("link", { name: "Download", exact: true }).first().click(), ]); const downloadPath = await download.path(); @@ -112,11 +106,11 @@ test.describe("event photo sharing", () => { const zip = await readFile(downloadPath!); 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(RAW)).toBe(true); - expect(zip.includes(Buffer.from(`Originals/${PHOTO_NAME}`))).toBe(true); - expect(zip.includes(Buffer.from("Originals/raw.CR3"))).toBe(true); + expect(zip.includes(Buffer.from(`Photos/${PHOTO_NAME}`))).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 ({ @@ -125,7 +119,6 @@ test.describe("event photo sharing", () => { await page.setViewportSize({ width: 1200, height: 900 }); await signInAs(page, "sam@glenloch.local"); await page.goto(eventUrl); - await page.getByRole("link", { name: /Originals/ }).click(); await page .getByRole("button", { name: `View and edit ${PHOTO_NAME}` }) @@ -164,7 +157,7 @@ test.describe("event photo sharing", () => { ]); const zip = await readFile((await zipDownload.path())!); 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 }) => { @@ -178,7 +171,6 @@ test.describe("event photo sharing", () => { await page.setViewportSize({ width: 1200, height: 900 }); await signInAs(page, "admin@glenloch.local"); await page.goto(eventUrl); - await page.getByRole("link", { name: /Originals/ }).click(); const photoHref = await page .getByRole("link", { name: "Download", exact: true }) .first() diff --git a/e2e/growth-and-maintenance.spec.ts b/e2e/growth-and-maintenance.spec.ts index 6db5933..4d3b70a 100644 --- a/e2e/growth-and-maintenance.spec.ts +++ b/e2e/growth-and-maintenance.spec.ts @@ -158,14 +158,11 @@ test.describe("growth goals and maintenance", () => { "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 expect(page.getByRole("alert").first()).toContainText( - "Photo and video uploads are disabled", - ); + await expect( + 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 // directory must block writes: media would silently land on local disk. diff --git a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx deleted file mode 100644 index 7f6d418..0000000 --- a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx +++ /dev/null @@ -1,141 +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 { advancedEditViewFor } from "@/lib/advanced-edit"; -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 = { - 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), - 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 ( -
-
- -
- -
-
-

- {detail.folder.name} -

-

- {detail.photos.length} photo{detail.photos.length === 1 ? "" : "s"}{" "} - · {sizeLabel(detail.folder.totalBytes)} -

-
-
- - {KIND_LABELS[detail.folder.kind] ?? detail.folder.kind} - - {detail.photos.length > 0 && ( - - )} - {editedCount > 0 && ( - - )} -
-
- - -
- ); -} diff --git a/src/app/(app)/events/[id]/page.tsx b/src/app/(app)/events/[id]/page.tsx index 9c87409..f4abdd9 100644 --- a/src/app/(app)/events/[id]/page.tsx +++ b/src/app/(app)/events/[id]/page.tsx @@ -1,9 +1,21 @@ import Link from "next/link"; 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 type { SystemRole } from "@/auth/roles"; -import { getEventDetail, listAssignableUsers } from "@/db/events"; +import { + getEventDetail, + listAssignableUsers, + listEventPhotos, +} from "@/db/events"; import { listEventVideos } from "@/db/videos"; import { bridgeConfigured } from "@/lib/bridge"; import { formatVideoDuration } from "@/lib/event-videos"; @@ -16,18 +28,21 @@ import { PhotographerPanel, type EventPhotographer, } from "@/components/app/events/photographer-panel"; -import { FolderCreateForm } from "@/components/app/events/folder-create-form"; import { DeleteEventButton } from "@/components/app/events/delete-event-button"; import { AdvancedEditorButton } from "@/components/app/events/advanced-editor-button"; import { ArchiveEventButton } from "@/components/app/events/archive-event-button"; import { VideoUploadForm } from "@/components/app/media/video-upload-form"; import { Button } from "@/components/ui/button"; - -const KIND_LABELS: Record = { - originals: "RAW / originals", - edited: "Edited exports", - mixed: "Mixed", -}; +import { + PhotoGallery, + type GalleryPhoto, +} from "@/components/app/events/photo-gallery"; +import { + isBrowserRenderablePhoto, + isEditableEventPhoto, +} from "@/lib/event-photos"; +import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments"; +import { advancedEditViewFor } from "@/lib/advanced-edit"; function when(date: Date): string { return formatInTimezone(date, CHURCH_TIMEZONE, { @@ -50,9 +65,9 @@ function sizeLabel(bytes: number): string { } /** - * One event: brief, assigned photographers, and the shared folders. Managers - * assign people; any assignee can create folders. Folder pages own uploads; - * the event header downloads every photo as one ZIP. + * One event: brief, assigned photographers, and every photo in a single + * gallery. Managers assign people; any assignee can upload here. The header + * downloads every photo (or only the edited ones) as one ZIP. */ export default async function EventDetailPage({ params, @@ -81,6 +96,25 @@ export default async function EventDetailPage({ 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 (
@@ -112,6 +146,17 @@ export default async function EventDetailPage({ )} + {editedCount > 0 && ( + + )} {event.canManage && archiveStatus.ok && ( - - - {event.folders.length === 0 ? ( -

- No folders yet. Create one for originals, dumps, or edited selects. -

- ) : ( -
    - {event.folders.map((folder) => ( -
  • - -
    -

    - {folder.name} -

    - - {KIND_LABELS[folder.kind] ?? folder.kind} - -
    -

    - {folder.photoCount} photo - {folder.photoCount === 1 ? "" : "s"} ·{" "} - {sizeLabel(folder.totalBytes)} -

    - -
  • - ))} -
- )} - - {event.canContribute ? ( - - ) : ( -

- Only assigned photographers, coordinators and admins can add - folders or upload. -

- )} + + diff --git a/src/app/(app)/media/page.tsx b/src/app/(app)/media/page.tsx index 37fa3ac..22afcb5 100644 --- a/src/app/(app)/media/page.tsx +++ b/src/app/(app)/media/page.tsx @@ -235,8 +235,8 @@ export default async function MediaPage() { Photos

- Every photo in the event folders you can open. Download originals - from the event folder. + Every photo in the events you can open. Download originals from + the event page.

@@ -264,7 +264,7 @@ export default async function MediaPage() { return (
@@ -292,7 +292,7 @@ export default async function MediaPage() { {photo.filename}

- {photo.eventTitle} · {photo.folderName} + {photo.eventTitle}

{bytesLabel(photo.sizeBytes)} diff --git a/src/app/(app)/training/guides/admin/page.tsx b/src/app/(app)/training/guides/admin/page.tsx index dc67e45..a9a57a6 100644 --- a/src/app/(app)/training/guides/admin/page.tsx +++ b/src/app/(app)/training/guides/admin/page.tsx @@ -450,7 +450,7 @@ export default function AdminGuidePage() { rate-limited and appear under Coverage as new requests. Read the brief, then either Create event (which opens an event with the requester and ministry attached) or Decline. The - event is where you assign photographers and folders. + event page is where you assign photographers and upload photos.

diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/route.ts index 65d4cc2..5e8b07a 100644 --- a/src/app/api/events/[id]/folders/[folderId]/photos/route.ts +++ b/src/app/api/events/[id]/folders/[folderId]/photos/route.ts @@ -1,58 +1,14 @@ 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 { - addEventPhoto, - findEventPhotoByChecksum, - 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, - }; -} +import { getEventFolderAccess } from "@/db/events"; +import { errorResponse } from "@/lib/http"; +import { uploadEventPhoto } from "@/lib/event-photo-upload"; /** * 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 - * 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. + * Folder-scoped upload kept for direct API use. The event page posts to + * `/api/events/:id/photos`, which picks the event's one implicit folder. */ export const POST = async ( req: NextRequest, @@ -70,93 +26,9 @@ export const POST = async ( return errorResponse(403, "you are not assigned to this event"); } - // 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(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); - }, + return uploadEventPhoto(req, { + eventId: id, + folderId, + uploaderId: gate.id, }); - - try { - await pipeline( - Readable.from(req.body as unknown as AsyncIterable), - 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, - 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; - } }; diff --git a/src/app/api/events/[id]/photos/route.ts b/src/app/api/events/[id]/photos/route.ts new file mode 100644 index 0000000..c509069 --- /dev/null +++ b/src/app/api/events/[id]/photos/route.ts @@ -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, + }); +}; diff --git a/src/components/app/events/folder-create-form.tsx b/src/components/app/events/folder-create-form.tsx deleted file mode 100644 index 5945880..0000000 --- a/src/components/app/events/folder-create-form.tsx +++ /dev/null @@ -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(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 ( -
-
-
- - setName(event.target.value)} - placeholder="Originals" - /> -
-
- - -
- -
- {error && ( -

- {error} -

- )} -
- ); -} diff --git a/src/components/app/events/photo-gallery.tsx b/src/components/app/events/photo-gallery.tsx index 2bb6492..129d800 100644 --- a/src/components/app/events/photo-gallery.tsx +++ b/src/components/app/events/photo-gallery.tsx @@ -45,6 +45,8 @@ function GalleryImage({ src, alt }: { src: string; alt: string }) { export interface GalleryPhoto { id: string; + /** Storage folder the photo lives in; photos are shown as one event gallery. */ + folderId: string; filename: string; sizeBytes: number; kind: "raw" | "image"; @@ -112,13 +114,13 @@ function extensionOf(filename: string): string { } /** - * Folder gallery + uploader. Files upload one at a time as raw request bodies, - * which keeps a 100 MB RAW frame out of memory and gives usable per-file - * progress on a phone. RAW files show a file tile; JPEG/PNG/WebP preview. + * The event's photo gallery + uploader. Files upload one at a time as raw + * request bodies, which keeps a 100 MB RAW frame out of memory and gives usable + * per-file progress on a phone. RAW files show a file tile; JPEG/PNG/WebP + * preview. */ export function PhotoGallery({ eventId, - folderId, photos, canContribute, canManage, @@ -127,7 +129,6 @@ export function PhotoGallery({ storageMessage, }: { eventId: string; - folderId: string; photos: GalleryPhoto[]; canContribute: boolean; canManage: boolean; @@ -169,7 +170,7 @@ export function PhotoGallery({ setProgress({ done: index, total: files.length, current: file.name }); try { const res = await fetch( - `/api/events/${eventId}/folders/${folderId}/photos?name=${encodeURIComponent(file.name)}`, + `/api/events/${eventId}/photos?name=${encodeURIComponent(file.name)}`, { method: "POST", headers: { @@ -209,7 +210,7 @@ export function PhotoGallery({ setNotice( [ uploaded > 0 ? `${uploaded} uploaded` : null, - duplicates > 0 ? `${duplicates} already in this folder` : null, + duplicates > 0 ? `${duplicates} already on this event` : null, ] .filter(Boolean) .join(" · ") || null, @@ -225,7 +226,7 @@ export function PhotoGallery({ setError(null); try { const res = await fetch( - `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`, + `/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`, { method: "DELETE" }, ); const data = (await res.json().catch(() => ({}))) as { error?: string }; @@ -252,7 +253,7 @@ export function PhotoGallery({ {canContribute && (
-

Upload photos to this folder

+

Upload photos to this event

- This folder is empty. + No photos yet. Upload the first frame for this event.

) : (
    {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 canRemove = canManage || photo.uploaderId === currentUserId; const version = photo.editedAt ? Date.parse(photo.editedAt) : 0; @@ -440,7 +441,7 @@ export function PhotoGallery({ { + 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 { + 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 { + const [row] = await db + .select({ + folderId: eventFolders.id, + name: eventFolders.name, + kind: eventFolders.kind, + createdAt: eventFolders.createdAt, + photoCount: sql`count(${eventPhotos.id})`, + totalBytes: sql`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 * caller must check event access first; this query intentionally does not. diff --git a/src/lib/event-photo-upload.ts b/src/lib/event-photo-upload.ts new file mode 100644 index 0000000..04cc689 --- /dev/null +++ b/src/lib/event-photo-upload.ts @@ -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 { + // 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), + 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; + } +}