feat(events): show every photo on the event page without folders
CI / build (push) Has been cancelled
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>
This commit is contained in:
@@ -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/<id>`, a minimal `/embed/<id>` 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 |
|
||||
|
||||
+7
-15
@@ -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()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<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),
|
||||
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 (
|
||||
<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>
|
||||
)}
|
||||
{editedCount > 0 && (
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a
|
||||
href={`/api/events/${detail.event.id}/download?folderId=${detail.folder.id}&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>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
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 (
|
||||
<div className="space-y-6">
|
||||
@@ -112,6 +146,17 @@ export default async function EventDetailPage({
|
||||
</a>
|
||||
</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 && (
|
||||
<ArchiveEventButton
|
||||
eventId={event.event.id}
|
||||
@@ -180,50 +225,26 @@ export default async function EventDetailPage({
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<FolderOpen className="h-4 w-4" aria-hidden="true" />
|
||||
Folders
|
||||
<ImageIcon className="h-4 w-4" aria-hidden="true" />
|
||||
Photos
|
||||
{photos.length > 0 && (
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
{photos.length}
|
||||
{editedCount > 0 ? ` · ${editedCount} edited` : ""}
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{event.folders.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No folders yet. Create one for originals, dumps, or edited selects.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="grid gap-3 sm:grid-cols-2">
|
||||
{event.folders.map((folder) => (
|
||||
<li key={folder.id}>
|
||||
<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>
|
||||
<PhotoGallery
|
||||
eventId={event.event.id}
|
||||
photos={photos}
|
||||
canContribute={event.canContribute}
|
||||
canManage={event.canManage}
|
||||
currentUserId={user.id}
|
||||
storageReady={archiveStatus.ok}
|
||||
storageMessage={archiveStatus.ok ? "" : archiveStatus.message}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -235,8 +235,8 @@ export default async function MediaPage() {
|
||||
Photos
|
||||
</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
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.
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
@@ -264,7 +264,7 @@ export default async function MediaPage() {
|
||||
return (
|
||||
<Link
|
||||
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"
|
||||
>
|
||||
<div className="flex aspect-square items-center justify-center bg-muted/40">
|
||||
@@ -292,7 +292,7 @@ export default async function MediaPage() {
|
||||
{photo.filename}
|
||||
</p>
|
||||
<p className="truncate text-[11px] text-muted-foreground">
|
||||
{photo.eventTitle} · {photo.folderName}
|
||||
{photo.eventTitle}
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
{bytesLabel(photo.sizeBytes)}
|
||||
|
||||
@@ -450,7 +450,7 @@ export default function AdminGuidePage() {
|
||||
rate-limited and appear under Coverage as new requests. Read the brief,
|
||||
then either <strong>Create event</strong> (which opens an event with
|
||||
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>
|
||||
</GuideSection>
|
||||
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
|
||||
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({
|
||||
return uploadEventPhoto(req, {
|
||||
eventId: id,
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
};
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 && (
|
||||
<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">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
@@ -310,12 +311,12 @@ export function PhotoGallery({
|
||||
|
||||
{photos.length === 0 ? (
|
||||
<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>
|
||||
) : (
|
||||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||
{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({
|
||||
<PhotoViewer
|
||||
key={viewing.id}
|
||||
eventId={eventId}
|
||||
folderId={folderId}
|
||||
folderId={viewing.folderId}
|
||||
photo={{
|
||||
id: viewing.id,
|
||||
filename: viewing.filename,
|
||||
|
||||
@@ -404,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
|
||||
* caller must check event access first; this query intentionally does not.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user