Files
glenloch-media/src/app/api/events/[id]/download/route.ts
T
bhursey ebe0c77f7e
CI / build (push) Has been cancelled
feat(editor): finish the quick/advanced editor handoff
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

157 lines
5.1 KiB
TypeScript

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 `<name>-edited.jpg`. With
* `?edited=1` the archive contains only the saved edits, which is what a
* photographer wants to hand on after a grading pass. 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 onlyEdited = req.nextUrl.searchParams.get("edited") === "1";
const photos = (await listEventPhotosForArchive(id)).filter(
(photo) =>
(!folderId || photo.folderId === folderId) &&
(!onlyEdited || Boolean(photo.editedStoredName)),
);
if (photos.length === 0) {
return errorResponse(
404,
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",
);
}
// 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;
}[] = [];
if (!onlyEdited) {
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<Uint8Array>,
{
status: 200,
headers: {
"content-type": "application/zip",
"content-disposition": photoContentDisposition(
eventArchiveFilename(
[
folderId
? `${access.event.title} - ${photos[0].folderName}`
: access.event.title,
onlyEdited ? "edited" : null,
]
.filter(Boolean)
.join(" - "),
),
false,
),
"cache-control": "private, no-store",
"x-content-type-options": "nosniff",
},
},
);
};