import { NextRequest, NextResponse } from "next/server"; import fs from "fs/promises"; import path from "path"; import { FREE_PLAN } from "@/lib/constants"; import { getSessionUser } from "@/lib/session"; import { getUploadDir } from "@/lib/storage"; const ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"]; const ALLOWED_AUDIO_TYPES = [ "audio/mpeg", "audio/mp3", "audio/wav", "audio/x-wav", "audio/ogg", "audio/flac", "audio/aac", "audio/mp4", "audio/x-m4a", ]; export async function POST(req: NextRequest) { const user = await getSessionUser(); if (!user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const formData = await req.formData(); const file = formData.get("file") as File | null; const type = formData.get("type") as string | null; if (!file || !type) { return NextResponse.json({ error: "Missing file or type" }, { status: 400 }); } if (file.size > FREE_PLAN.maxFileSizeBytes) { return NextResponse.json( { error: `File exceeds ${FREE_PLAN.maxFileSizeBytes / (1024 * 1024)} MB limit` }, { status: 400 }, ); } const allowedTypes = type === "image" ? ALLOWED_IMAGE_TYPES : ALLOWED_AUDIO_TYPES; if (!allowedTypes.includes(file.type) && !file.name.match(/\.(mp3|wav|ogg|flac|aac|m4a|jpg|jpeg|png|webp|gif)$/i)) { return NextResponse.json({ error: "Invalid file type" }, { status: 400 }); } const sessionDir = path.join(getUploadDir(), user.id, "sessions", Date.now().toString()); await fs.mkdir(sessionDir, { recursive: true }); const safeName = file.name.replace(/[^a-zA-Z0-9._-]/g, "_"); const filePath = path.join(sessionDir, safeName); const buffer = Buffer.from(await file.arrayBuffer()); await fs.writeFile(filePath, buffer); return NextResponse.json({ path: filePath, filename: file.name, size: file.size, }); }