"use server"; import { revalidatePath } from "next/cache"; import { writeFile, mkdir } from "fs/promises"; import path from "path"; import { requireStaff } from "@/lib/admin/guard"; const MEDIA_DIR = "public/assets/images/media"; const MAX_SIZE = 5 * 1024 * 1024; // 5MB const ALLOWED = ["image/png", "image/jpeg", "image/gif", "image/webp"]; export async function uploadMedia(formData: FormData): Promise { await requireStaff(); const file = formData.get("file") as File | null; if (!file || file.size === 0) return; if (file.size > MAX_SIZE) throw new Error("File too large (max 5MB)"); if (!ALLOWED.includes(file.type)) throw new Error("Invalid file type"); const baseDir = path.resolve(process.cwd(), MEDIA_DIR); // eslint-disable-next-line security/detect-non-literal-fs-filename await mkdir(baseDir, { recursive: true }); const ext = file.name.split(".").pop() ?? "png"; const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`; const bytes = await file.arrayBuffer(); const filePath = path.resolve(baseDir, name); if (!filePath.startsWith(baseDir + path.sep)) throw new Error("Invalid path"); // eslint-disable-next-line security/detect-non-literal-fs-filename await writeFile(filePath, Buffer.from(bytes)); revalidatePath("/api/media"); revalidatePath("/admin/media"); } export async function deleteMedia(name: string): Promise { await requireStaff(); const { unlink } = await import("fs/promises"); const baseDir = path.resolve(process.cwd(), MEDIA_DIR); const filePath = path.resolve(baseDir, name); if (!filePath.startsWith(baseDir + path.sep)) return; try { await unlink(filePath); } catch { // File may not exist } revalidatePath("/api/media"); revalidatePath("/admin/media"); } export async function uploadMediaAndReturn(formData: FormData): Promise { await requireStaff(); const file = formData.get("file") as File | null; if (!file || file.size === 0) return ""; if (file.size > MAX_SIZE) return ""; if (!ALLOWED.includes(file.type)) return ""; const baseDir = path.resolve(process.cwd(), MEDIA_DIR); // eslint-disable-next-line security/detect-non-literal-fs-filename await mkdir(baseDir, { recursive: true }); const ext = file.name.split(".").pop() ?? "png"; const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`; const bytes = await file.arrayBuffer(); const filePath = path.resolve(baseDir, name); if (!filePath.startsWith(baseDir + path.sep)) return ""; // eslint-disable-next-line security/detect-non-literal-fs-filename await writeFile(filePath, Buffer.from(bytes)); revalidatePath("/api/media"); revalidatePath("/admin/media"); return `/api/media/${name}`; }