feat(media): primary media storage, growth goals, retention and delivery tools
CI / build (push) Has been cancelled
CI / build (push) Has been cancelled
Event photos and videos are now stored only on the NFS/local share named in Settings -> Media storage. Uploads, photo editing, video processing and the per-event filing step refuse to run until that share is configured and writable, so nothing is silently written inside the container. Video originals, renditions, posters and sidecars share one folder on the share. Also adds volunteer growth goals with a mentor queue, an admin retention and storage sweep with a cron entry point, cached gallery thumbnails with per-folder ZIP downloads, a server-rendered booth-sheet PDF, and in-app confirm/release for every upcoming assignment. Service reminders now ignore the one-off event reminder rule, which had been queueing an extra bogus reminder for each published service. Generated with Codebuff 🤖 Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { gateCron } from "@/auth/api";
|
||||
import { pruneRetention } from "@/db/retention";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* GET /api/dev/cron/retention — monthly housekeeping (cron `0 4 1 * *`).
|
||||
*
|
||||
* Deletes terminal notification rows and consumed tokens past their window and
|
||||
* sweeps orphan training attachments. Auth: `Authorization: Bearer
|
||||
* $CRON_SECRET` (or `?secret=`) for a scheduler, otherwise a coordinator
|
||||
* session. Running it twice is harmless.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateCron(req);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
const removed = await pruneRetention();
|
||||
return new Response(JSON.stringify({ ok: true, removed }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "retention failed";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { pruneRetention, retentionSummary } from "@/db/retention";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { RETENTION_LIMITS } from "@/lib/retention";
|
||||
|
||||
const sweepSchema = z.object({
|
||||
notificationDays: z
|
||||
.number()
|
||||
.int()
|
||||
.min(RETENTION_LIMITS.minDays)
|
||||
.max(RETENTION_LIMITS.maxDays)
|
||||
.optional(),
|
||||
tokenDays: z
|
||||
.number()
|
||||
.int()
|
||||
.min(RETENTION_LIMITS.minDays)
|
||||
.max(RETENTION_LIMITS.maxDays)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/** GET /api/dev/retention — counts, sizes, and what the next sweep would remove. */
|
||||
export async function GET() {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
return jsonResponse({ summary: await retentionSummary() });
|
||||
} catch (error) {
|
||||
console.error("[retention] summary failed", error);
|
||||
return errorResponse(500, "could not read retention counts");
|
||||
}
|
||||
}
|
||||
|
||||
/** POST /api/dev/retention — sweep old mail, tokens and orphan training files. */
|
||||
export async function POST(req: Request) {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = sweepSchema.safeParse(await req.json().catch(() => ({})));
|
||||
if (!parsed.success) return errorResponse(400, "invalid retention window");
|
||||
|
||||
try {
|
||||
const result = await pruneRetention(parsed.data);
|
||||
return jsonResponse({ ok: true, removed: result, summary: await retentionSummary() });
|
||||
} catch (error) {
|
||||
console.error("[retention] sweep failed", error);
|
||||
return errorResponse(500, "retention sweep failed");
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ function publicSettings(settings: StorageSettings) {
|
||||
};
|
||||
}
|
||||
|
||||
/** GET /api/dev/storage — NFS/archive destination and mount readiness. */
|
||||
/** GET /api/dev/storage — media storage destination and mount readiness. */
|
||||
export const GET = async () => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
@@ -9,11 +9,8 @@ import {
|
||||
listEventPhotosForArchive,
|
||||
} from "@/db/events";
|
||||
import { listEventVideos } from "@/db/videos";
|
||||
import { eventVideoUploadDir } from "@/lib/event-videos";
|
||||
import {
|
||||
checkArchiveDestination,
|
||||
getStorageSettings,
|
||||
} from "@/db/storage-settings";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import {
|
||||
archiveEventPhotos,
|
||||
EventArchiveError,
|
||||
@@ -42,14 +39,12 @@ export const POST = async (
|
||||
return errorResponse(403, "only an event manager may archive this event");
|
||||
}
|
||||
|
||||
// Archiving copies live photos into the dated folder on the same configured
|
||||
// share; without a named share there is no archive to write to.
|
||||
const media = await mediaStorage();
|
||||
if (!media.ok) return errorResponse(409, media.message);
|
||||
const storage = await getStorageSettings();
|
||||
const status = await checkArchiveDestination(storage);
|
||||
if (!status.ready) {
|
||||
return errorResponse(
|
||||
409,
|
||||
`${status.message} Configure the NFS archive in Settings first.`,
|
||||
);
|
||||
}
|
||||
const uploadRoot = media.root;
|
||||
|
||||
const photos = await listEventPhotosForArchive(id);
|
||||
const videos = await listEventVideos(id);
|
||||
@@ -84,10 +79,9 @@ export const POST = async (
|
||||
}
|
||||
|
||||
try {
|
||||
await rm(eventPhotoDir(id), { recursive: true, force: true });
|
||||
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
|
||||
await rm(eventPhotoDir(uploadRoot, id), { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: archived but live files remain`, error);
|
||||
console.error(`event ${id}: archived but live photos remain`, error);
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
photoContentDisposition,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/download
|
||||
@@ -22,7 +23,7 @@ import { errorResponse } from "@/lib/http";
|
||||
* Anyone assigned to the event (or a manager) can download it.
|
||||
*/
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
@@ -32,9 +33,17 @@ export const GET = async (
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
|
||||
const photos = await listEventPhotosForArchive(id);
|
||||
// `?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, "this event has no photos");
|
||||
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
|
||||
@@ -71,9 +80,12 @@ export const GET = async (
|
||||
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(entry.storedName);
|
||||
const filePath = eventPhotoPath(storage.root, entry.storedName);
|
||||
try {
|
||||
const info = await stat(filePath);
|
||||
if (!info.isFile()) continue;
|
||||
@@ -111,7 +123,11 @@ export const GET = async (
|
||||
headers: {
|
||||
"content-type": "application/zip",
|
||||
"content-disposition": photoContentDisposition(
|
||||
eventArchiveFilename(access.event.title),
|
||||
eventArchiveFilename(
|
||||
folderId
|
||||
? `${access.event.title} - ${photos[0].folderName}`
|
||||
: access.event.title,
|
||||
),
|
||||
false,
|
||||
),
|
||||
"cache-control": "private, no-store",
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
isEditableEventPhoto,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
|
||||
@@ -52,6 +53,11 @@ export const POST = async (
|
||||
return errorResponse(415, "this photo format cannot be edited");
|
||||
}
|
||||
|
||||
// The rendered JPEG is written beside the original on the media share.
|
||||
// Editing must never fall back to container storage.
|
||||
const storage = await mediaStorage();
|
||||
if (!storage.ok) return errorResponse(503, storage.message);
|
||||
|
||||
const body = (await req.json().catch(() => null)) as
|
||||
| { adjustments?: unknown }
|
||||
| null;
|
||||
@@ -60,7 +66,7 @@ export const POST = async (
|
||||
return errorResponse(400, "invalid photo adjustments");
|
||||
}
|
||||
|
||||
const sourcePath = eventPhotoPath(access.photo.storedName);
|
||||
const sourcePath = eventPhotoPath(storage.root, access.photo.storedName);
|
||||
try {
|
||||
const source = await stat(sourcePath);
|
||||
if (!source.isFile()) return errorResponse(404, "the file is missing from storage");
|
||||
@@ -72,7 +78,7 @@ export const POST = async (
|
||||
access.eventId,
|
||||
access.photo.id,
|
||||
);
|
||||
const editedPath = eventPhotoPath(editedStoredName);
|
||||
const editedPath = eventPhotoPath(storage.root, editedStoredName);
|
||||
|
||||
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
|
||||
try {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/folders/:folderId/photos/:photoId/export?size=2048
|
||||
@@ -45,10 +46,16 @@ export const GET = async (
|
||||
return errorResponse(400, "unknown export size");
|
||||
}
|
||||
|
||||
const storage = await mediaStorage();
|
||||
if (!storage.ok) return errorResponse(503, storage.message);
|
||||
|
||||
let data: Buffer;
|
||||
try {
|
||||
if (access.photo.editedStoredName) {
|
||||
const editedPath = eventPhotoPath(access.photo.editedStoredName);
|
||||
const editedPath = eventPhotoPath(
|
||||
storage.root,
|
||||
access.photo.editedStoredName,
|
||||
);
|
||||
const info = await stat(editedPath);
|
||||
if (!info.isFile()) throw new Error("missing edit");
|
||||
data = await sharp(editedPath)
|
||||
@@ -62,7 +69,7 @@ export const GET = async (
|
||||
.toBuffer();
|
||||
} else if (access.photo.editJson) {
|
||||
const rendered = await renderPhotoJpeg({
|
||||
filePath: eventPhotoPath(access.photo.storedName),
|
||||
filePath: eventPhotoPath(storage.root, access.photo.storedName),
|
||||
kind: access.photo.kind,
|
||||
adjustments: parseStoredPhotoAdjustments(access.photo.editJson),
|
||||
maxDimension: preset.maxDimension,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
previewStoredNameForEventPhoto,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
|
||||
@@ -44,7 +45,10 @@ export const GET = async (
|
||||
return errorResponse(415, "this photo format cannot be previewed in the editor");
|
||||
}
|
||||
|
||||
const sourcePath = eventPhotoPath(access.photo.storedName);
|
||||
const storage = await mediaStorage();
|
||||
if (!storage.ok) return errorResponse(503, storage.message);
|
||||
|
||||
const sourcePath = eventPhotoPath(storage.root, access.photo.storedName);
|
||||
try {
|
||||
const source = await stat(sourcePath);
|
||||
if (!source.isFile()) return errorResponse(404, "the file is missing from storage");
|
||||
@@ -53,6 +57,7 @@ export const GET = async (
|
||||
}
|
||||
|
||||
const previewPath = eventPhotoPath(
|
||||
storage.root,
|
||||
previewStoredNameForEventPhoto(access.eventId, access.photo.id),
|
||||
);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
photoContentDisposition,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/folders/:folderId/photos/:photoId[?download=1|variant=edited]
|
||||
@@ -47,7 +48,11 @@ export const GET = async (
|
||||
return errorResponse(404, "this photo has no saved edit");
|
||||
}
|
||||
|
||||
const storage = await mediaStorage();
|
||||
if (!storage.ok) return errorResponse(503, storage.message);
|
||||
|
||||
const filePath = eventPhotoPath(
|
||||
storage.root,
|
||||
wantsEdited
|
||||
? access.photo.editedStoredName!
|
||||
: access.photo.storedName,
|
||||
@@ -115,11 +120,16 @@ export const DELETE = async (
|
||||
}
|
||||
|
||||
await deleteEventPhoto(photoId);
|
||||
await unlink(eventPhotoPath(access.photo.storedName)).catch(() => undefined);
|
||||
if (access.photo.editedStoredName) {
|
||||
await unlink(eventPhotoPath(access.photo.editedStoredName)).catch(
|
||||
const storage = await mediaStorage();
|
||||
if (storage.ok) {
|
||||
await unlink(eventPhotoPath(storage.root, access.photo.storedName)).catch(
|
||||
() => undefined,
|
||||
);
|
||||
if (access.photo.editedStoredName) {
|
||||
await unlink(
|
||||
eventPhotoPath(storage.root, access.photo.editedStoredName),
|
||||
).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventPhotoAccess } from "@/db/events";
|
||||
import {
|
||||
eventPhotoPath,
|
||||
isBrowserRenderablePhoto,
|
||||
thumbStoredNameForEventPhoto,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/folders/:folderId/photos/:photoId/thumb
|
||||
*
|
||||
* A 640px square-croppable JPEG of the original for the gallery grid. Without
|
||||
* it a 400-photo event ships hundreds of megabytes of camera originals to a
|
||||
* phone. Cached on disk (the original never changes) and safe to cache in the
|
||||
* browser, since the URL is keyed by photo id.
|
||||
*/
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string; folderId: string; photoId: string }>;
|
||||
},
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, folderId, photoId } = await params;
|
||||
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
|
||||
if (!access || access.photo.folderId !== folderId || access.eventId !== id) {
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
|
||||
const storage = await mediaStorage();
|
||||
if (!storage.ok) return errorResponse(503, storage.message);
|
||||
|
||||
const thumbPath = eventPhotoPath(
|
||||
storage.root,
|
||||
thumbStoredNameForEventPhoto(access.eventId, access.photo.id),
|
||||
);
|
||||
|
||||
try {
|
||||
const cached = await stat(thumbPath);
|
||||
if (cached.isFile()) {
|
||||
return imageResponse(await readFile(thumbPath));
|
||||
}
|
||||
} catch {
|
||||
// not cached yet
|
||||
}
|
||||
|
||||
const sourcePath = eventPhotoPath(storage.root, access.photo.storedName);
|
||||
try {
|
||||
const source = await stat(sourcePath);
|
||||
if (!source.isFile()) {
|
||||
return errorResponse(404, "the file is missing from storage");
|
||||
}
|
||||
} catch {
|
||||
return errorResponse(404, "the file is missing from storage");
|
||||
}
|
||||
|
||||
let data: Buffer;
|
||||
try {
|
||||
if (access.photo.kind === "raw") {
|
||||
const rendered = await renderPhotoJpeg({
|
||||
filePath: sourcePath,
|
||||
kind: "raw",
|
||||
adjustments: defaultPhotoAdjustments(),
|
||||
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 {
|
||||
return errorResponse(415, "this photo format has no thumbnail");
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof PhotoRenderError) {
|
||||
return errorResponse(415, error.message);
|
||||
}
|
||||
console.warn(`event photo ${photoId}: thumbnail failed`, error);
|
||||
return errorResponse(500, "could not build a thumbnail");
|
||||
}
|
||||
|
||||
await mkdir(path.dirname(thumbPath), { recursive: true });
|
||||
const tempPath = `${thumbPath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(tempPath, data);
|
||||
await rename(tempPath, thumbPath);
|
||||
} catch (error) {
|
||||
console.warn(`event photo ${photoId}: thumbnail cache write failed`, error);
|
||||
}
|
||||
|
||||
return imageResponse(data);
|
||||
};
|
||||
|
||||
function imageResponse(data: Buffer): Response {
|
||||
return new Response(new Uint8Array(data), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "image/jpeg",
|
||||
"cache-control": "private, max-age=31536000, immutable",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
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 {}
|
||||
@@ -69,6 +70,11 @@ 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);
|
||||
@@ -88,7 +94,7 @@ export const POST = async (
|
||||
|
||||
const photoId = uuidv7();
|
||||
const storedName = storedNameForEventPhoto(id, photoId, filename);
|
||||
const destination = eventPhotoPath(storedName);
|
||||
const destination = eventPhotoPath(storage.root, storedName);
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
|
||||
const hash = createHash("sha256");
|
||||
|
||||
@@ -6,11 +6,9 @@ import { writeAudit } from "@/db/audit";
|
||||
import { deleteEvent, getEventAccess } from "@/db/events";
|
||||
import { listEventVideos } from "@/db/videos";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import { eventPhotoDir } from "@/lib/event-photos";
|
||||
import {
|
||||
eventVideoArchiveDir,
|
||||
eventVideoUploadDir,
|
||||
} from "@/lib/event-videos";
|
||||
import { eventVideoArchiveDir } from "@/lib/event-videos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
@@ -34,30 +32,29 @@ export const DELETE = async (
|
||||
const deleted = await deleteEvent(id);
|
||||
if (!deleted) return errorResponse(404, "unknown event");
|
||||
|
||||
try {
|
||||
await rm(eventPhotoDir(id), { recursive: true, force: true });
|
||||
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: database deleted but files remain`, error);
|
||||
const media = await mediaStorage();
|
||||
if (media.ok) {
|
||||
try {
|
||||
await rm(eventPhotoDir(media.root, id), { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: database deleted but photos remain`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Video originals are the largest files; remove each one from the archive
|
||||
// after the cascade has removed its row, so a deletion cannot orphan GBs.
|
||||
// Video originals are the largest files; remove the whole event video folder
|
||||
// on the archive after the cascade has removed the rows, so a deletion cannot
|
||||
// orphan GBs. Originals and derivatives share one folder per video.
|
||||
try {
|
||||
const storage = await getStorageSettings();
|
||||
for (const video of videos) {
|
||||
await rm(
|
||||
eventVideoArchiveDir(
|
||||
storage.archivePath,
|
||||
video.archiveFolder,
|
||||
id,
|
||||
video.id,
|
||||
),
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
const folders = new Set(videos.map((video) => video.archiveFolder));
|
||||
for (const folder of folders) {
|
||||
await rm(eventVideoArchiveDir(storage.archivePath, folder, id), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: NFS video originals were not removed`, error);
|
||||
console.error(`event ${id}: NFS video files were not removed`, error);
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { parseByteRange } from "@/lib/range";
|
||||
|
||||
/** Download the untouched camera original from the NFS archive. */
|
||||
/** Download the untouched camera original from media storage. */
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; videoId: string }> },
|
||||
@@ -35,12 +35,12 @@ export const GET = async (
|
||||
access.video.originalStoredName,
|
||||
);
|
||||
} catch {
|
||||
return errorResponse(404, "the NFS archive is not configured");
|
||||
return errorResponse(404, "media storage is not configured");
|
||||
}
|
||||
|
||||
const info = await stat(filePath).catch(() => null);
|
||||
if (!info?.isFile()) {
|
||||
return errorResponse(404, "the original video is missing from the NFS archive");
|
||||
return errorResponse(404, "the original video is missing from media storage");
|
||||
}
|
||||
|
||||
const range = parseByteRange(req.headers.get("range"), info.size);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
@@ -9,11 +8,7 @@ import {
|
||||
getEventVideoAccess,
|
||||
} from "@/db/videos";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import {
|
||||
eventVideoArchiveDir,
|
||||
eventVideoUploadPath,
|
||||
webStoredNameForEventVideo,
|
||||
} from "@/lib/event-videos";
|
||||
import { eventVideoArchiveDir } from "@/lib/event-videos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
|
||||
@@ -62,16 +57,7 @@ export const DELETE = async (
|
||||
const removed = await deleteEventVideo(videoId);
|
||||
if (!removed) return errorResponse(404, "unknown video");
|
||||
|
||||
const derivativeDir = path.dirname(
|
||||
eventVideoUploadPath(
|
||||
removed.webStoredName ??
|
||||
webStoredNameForEventVideo(removed.eventId, removed.id),
|
||||
),
|
||||
);
|
||||
await rm(derivativeDir, { recursive: true, force: true }).catch((error) => {
|
||||
console.error(`video ${videoId}: derivatives were not removed`, error);
|
||||
});
|
||||
|
||||
// One folder on the share holds the original, renditions, poster and sidecar.
|
||||
try {
|
||||
const storage = await getStorageSettings();
|
||||
await rm(
|
||||
@@ -84,7 +70,7 @@ export const DELETE = async (
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`video ${videoId}: NFS original was not removed`, error);
|
||||
console.error(`video ${videoId}: NFS files were not removed`, error);
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
|
||||
@@ -6,10 +6,7 @@ import { Readable } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventAccess } from "@/db/events";
|
||||
import {
|
||||
checkArchiveDestination,
|
||||
getStorageSettings,
|
||||
} from "@/db/storage-settings";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import {
|
||||
EVENT_VIDEO_VISIBILITIES,
|
||||
type EventVideoVisibility,
|
||||
@@ -142,14 +139,10 @@ export const POST = async (
|
||||
(req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) ||
|
||||
null;
|
||||
|
||||
const storage = await getStorageSettings();
|
||||
const archiveStatus = await checkArchiveDestination(storage);
|
||||
if (!archiveStatus.ready) {
|
||||
return errorResponse(
|
||||
409,
|
||||
`${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`,
|
||||
);
|
||||
}
|
||||
// Staging chunks also land on the media storage share, never in the container.
|
||||
const media = await mediaStorage();
|
||||
if (!media.ok) return errorResponse(409, media.message);
|
||||
const storage = media.settings;
|
||||
|
||||
// Stage under a client-scoped name, never under a final video id. The final
|
||||
// id is generated by the server when the last chunk arrives, so a caller
|
||||
|
||||
@@ -8,7 +8,7 @@ import { pipeline } from "node:stream/promises";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventAccess } from "@/db/events";
|
||||
import { listEventVideos } from "@/db/videos";
|
||||
import { checkArchiveDestination, getStorageSettings } from "@/db/storage-settings";
|
||||
import { mediaStorage } from "@/lib/media-storage";
|
||||
import {
|
||||
MAX_EVENT_VIDEO_BYTES,
|
||||
eventVideoArchivePath,
|
||||
@@ -30,7 +30,7 @@ class VideoTooLarge extends Error {}
|
||||
/**
|
||||
* POST /api/events/:id/videos?name=service.mp4&title=Sunday&visibility=team
|
||||
*
|
||||
* Raw request body. The camera original streams straight to the NFS archive and
|
||||
* Raw request body. The camera original streams straight to media storage and
|
||||
* is hashed while it writes, so a 4 GB file never sits in memory. The stored
|
||||
* row starts as `processing`; FFmpeg creates the web MP4/poster in the
|
||||
* background and the browser polls the video endpoint for readiness.
|
||||
@@ -89,14 +89,11 @@ export const POST = async (
|
||||
}
|
||||
if (!req.body) return errorResponse(400, "a video body is required");
|
||||
|
||||
const storage = await getStorageSettings();
|
||||
const archiveStatus = await checkArchiveDestination(storage);
|
||||
if (!archiveStatus.ready) {
|
||||
return errorResponse(
|
||||
409,
|
||||
`${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`,
|
||||
);
|
||||
}
|
||||
// Videos are written only to the configured media storage share. No share, no
|
||||
// upload: the app must never fall back to container-local storage.
|
||||
const media = await mediaStorage();
|
||||
if (!media.ok) return errorResponse(409, media.message);
|
||||
const storage = media.settings;
|
||||
|
||||
const videoId = uuidv7();
|
||||
const storedName = originalStoredNameForEventVideo(id, videoId, filename);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { z } from "zod";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { hasPermission } from "@/auth/permissions";
|
||||
import {
|
||||
advanceGrowthGoal,
|
||||
createGrowthGoal,
|
||||
GrowthGoalError,
|
||||
listGoalsForUser,
|
||||
listGrowthQueue,
|
||||
} from "@/db/growthGoals";
|
||||
import { SKILL_LEVELS } from "@/db/schema";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const createSchema = z.object({
|
||||
skillId: z.string().min(1),
|
||||
targetLevel: z.enum(SKILL_LEVELS),
|
||||
targetDate: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.optional()
|
||||
.nullable(),
|
||||
});
|
||||
|
||||
const actionSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
action: z.enum([
|
||||
"assignMentor",
|
||||
"decline",
|
||||
"startShadow",
|
||||
"progressShadow",
|
||||
"achieve",
|
||||
"pause",
|
||||
"resume",
|
||||
]),
|
||||
mentorUserId: z.string().min(1).optional().nullable(),
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/growth-goals — the signed-in volunteer's goals
|
||||
* GET /api/growth-goals?scope=queue — coordinator/mentor queue (+ candidates)
|
||||
*/
|
||||
export async function GET(req: Request) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const scope = new URL(req.url).searchParams.get("scope");
|
||||
if (scope === "queue") {
|
||||
if (!hasPermission(gate.systemRole, "schedule.publish")) {
|
||||
return errorResponse(403, "coordinators only");
|
||||
}
|
||||
return jsonResponse({ goals: await listGrowthQueue() });
|
||||
}
|
||||
return jsonResponse({ goals: await listGoalsForUser(gate.id) });
|
||||
}
|
||||
|
||||
/** POST /api/growth-goals — ask to grow toward a level for one skill. */
|
||||
export async function POST(req: Request) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = createSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) return errorResponse(400, "invalid growth goal");
|
||||
|
||||
try {
|
||||
const goal = await createGrowthGoal({
|
||||
userId: gate.id,
|
||||
skillId: parsed.data.skillId,
|
||||
targetLevel: parsed.data.targetLevel,
|
||||
targetDate: parsed.data.targetDate ?? null,
|
||||
});
|
||||
return jsonResponse({ ok: true, ...goal }, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof GrowthGoalError) {
|
||||
return errorResponse(error.status, error.message);
|
||||
}
|
||||
console.error("[growth-goals] create failed", error);
|
||||
return errorResponse(500, "failed to create the goal");
|
||||
}
|
||||
}
|
||||
|
||||
/** PATCH /api/growth-goals — advance a goal (coordinator). */
|
||||
export async function PATCH(req: Request) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
if (!hasPermission(gate.systemRole, "schedule.publish")) {
|
||||
return errorResponse(403, "coordinators only");
|
||||
}
|
||||
|
||||
const parsed = actionSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) return errorResponse(400, "invalid action");
|
||||
|
||||
try {
|
||||
const result = await advanceGrowthGoal({
|
||||
goalId: parsed.data.id,
|
||||
action: parsed.data.action,
|
||||
actorId: gate.id,
|
||||
mentorUserId: parsed.data.mentorUserId ?? null,
|
||||
});
|
||||
return jsonResponse({ ok: true, ...result });
|
||||
} catch (error) {
|
||||
if (error instanceof GrowthGoalError) {
|
||||
return errorResponse(error.status, error.message);
|
||||
}
|
||||
console.error("[growth-goals] action failed", error);
|
||||
return errorResponse(500, "failed to update the goal");
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,9 @@ import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
|
||||
import { eventVideoUploadPath } from "@/lib/event-videos";
|
||||
import { eventVideoArchivePath } from "@/lib/event-videos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
export const GET = async (
|
||||
@@ -33,7 +34,12 @@ export const GET = async (
|
||||
}
|
||||
let filePath: string;
|
||||
try {
|
||||
filePath = eventVideoUploadPath(video.posterStoredName);
|
||||
const storage = await getStorageSettings();
|
||||
filePath = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
video.archiveFolder,
|
||||
video.posterStoredName,
|
||||
);
|
||||
} catch {
|
||||
return errorResponse(404, "unknown poster");
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@ import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
|
||||
import {
|
||||
eventVideoUploadPath,
|
||||
eventVideoArchivePath,
|
||||
sanitizeVideoFilename,
|
||||
videoContentDisposition,
|
||||
webRenditionStoredNameForEventVideo,
|
||||
@@ -49,12 +50,19 @@ export const GET = async (
|
||||
let filePath: string;
|
||||
let info: Awaited<ReturnType<typeof stat>> | null = null;
|
||||
try {
|
||||
filePath = eventVideoUploadPath(video.webStoredName);
|
||||
const storage = await getStorageSettings();
|
||||
filePath = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
video.archiveFolder,
|
||||
video.webStoredName,
|
||||
);
|
||||
info = await stat(filePath).catch(() => null);
|
||||
|
||||
const quality = req.nextUrl.searchParams.get("quality");
|
||||
if ((quality === "720" || quality === "480") && info?.isFile()) {
|
||||
const renditionPath = eventVideoUploadPath(
|
||||
const renditionPath = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
video.archiveFolder,
|
||||
webRenditionStoredNameForEventVideo(
|
||||
video.eventId,
|
||||
video.id,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getRunSheet } from "@/db/runSheet";
|
||||
import { boothSheetFilename, buildBoothSheetPdf } from "@/lib/booth-sheet-pdf";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
* GET /api/run-sheet/:instanceId/pdf
|
||||
*
|
||||
* The printable booth sheet as a real PDF. Any signed-in team member can pull
|
||||
* it (the run sheet itself is team-visible); it is generated from the current
|
||||
* database state each time, so it can never show a stale team.
|
||||
*/
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ instanceId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { instanceId } = await params;
|
||||
const sheet = await getRunSheet(instanceId);
|
||||
if (!sheet) return errorResponse(404, "unknown run sheet");
|
||||
|
||||
try {
|
||||
const pdf = await buildBoothSheetPdf(sheet);
|
||||
const filename = boothSheetFilename(sheet).replace(/[^A-Za-z0-9._-]/g, "_");
|
||||
return new Response(new Uint8Array(pdf), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/pdf",
|
||||
"content-disposition": `attachment; filename="${filename}"`,
|
||||
"cache-control": "private, no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[run-sheet-pdf] build failed", error);
|
||||
return errorResponse(500, "could not build the booth sheet");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user