import { ZipArchive } from "archiver"; import { NextRequest } from "next/server"; import { stat } from "node:fs/promises"; import { PassThrough, Readable } from "node:stream"; import { gateSession } from "@/auth/api"; import { getEventAccess, listEventPhotosForArchive } from "@/db/events"; import { assignArchivePaths, eventArchiveFilename } from "@/lib/event-archive"; import { editedPhotoFilename, eventPhotoPath, photoContentDisposition, } from "@/lib/event-photos"; import { errorResponse } from "@/lib/http"; import { mediaStorage } from "@/lib/media-storage"; /** * GET /api/events/:id/download * * Streams every photo on the event as one ZIP, preserving folder names. Saved * edits are included beside their originals as `-edited.jpg`. The * archive is 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 ( 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"); // `?folderId=` narrows the archive to one folder, so a photographer can pull // just the shots they need without downloading the whole event. const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null; const photos = (await listEventPhotosForArchive(id)).filter( (photo) => !folderId || photo.folderId === folderId, ); if (photos.length === 0) { return errorResponse( 404, folderId ? "this folder has no photos" : "this event has no photos", ); } // Originals claim their names first, then generated edits join the same // folder. A real upload named `photo-edited.jpg` therefore keeps its name and // the generated version is numbered instead. const entries: { key: string; folderName: string; filename: string; storedName: string; }[] = []; for (const photo of photos) { entries.push({ key: `${photo.id}:original`, folderName: photo.folderName, filename: photo.filename, storedName: photo.storedName, }); } for (const photo of photos) { if (!photo.editedStoredName) continue; entries.push({ key: `${photo.id}:edited`, folderName: photo.folderName, filename: editedPhotoFilename(photo.filename), storedName: photo.editedStoredName, }); } const names = assignArchivePaths( entries.map((entry) => ({ id: entry.key, folderName: entry.folderName, filename: entry.filename, })), ); const storage = await mediaStorage(); if (!storage.ok) return errorResponse(503, storage.message); const available: { path: string; name: string }[] = []; for (const entry of entries) { const filePath = eventPhotoPath(storage.root, entry.storedName); try { const info = await stat(filePath); if (!info.isFile()) continue; available.push({ path: filePath, name: names.get(entry.key)! }); } catch { console.warn(`event ${id}: skipping missing archive entry ${entry.key}`); } } if (available.length === 0) { return errorResponse(404, "the event photos are missing from storage"); } // archiver uses readable-stream, so bridge through a core PassThrough before // handing the response to the Web Streams API. const output = new PassThrough(); const archive = new ZipArchive({ store: true }); archive.on("warning", (error) => { console.warn(`event ${id}: zip warning`, error); }); archive.on("error", (error) => { console.error(`event ${id}: zip failed`, error); output.destroy(error); }); archive.pipe(output); for (const file of available) { archive.file(file.path, { name: file.name }); } void archive.finalize().catch((error) => output.destroy(error)); return new Response( Readable.toWeb(output) as unknown as ReadableStream, { status: 200, headers: { "content-type": "application/zip", "content-disposition": photoContentDisposition( eventArchiveFilename( folderId ? `${access.event.title} - ${photos[0].folderName}` : access.event.title, ), false, ), "cache-control": "private, no-store", "x-content-type-options": "nosniff", }, }, ); };