55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getServerSession } from "@/lib/auth";
|
|
import { db } from "@/lib/db";
|
|
import { sounds } from "@/lib/db/schema";
|
|
import { writeFile, mkdir } from "fs/promises";
|
|
import path from "path";
|
|
import { v4 as uuidv4 } from "uuid";
|
|
|
|
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "sounds");
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const session = await getServerSession();
|
|
if (!session || !session.isAdmin) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
try {
|
|
const formData = await req.formData();
|
|
const file = formData.get("file") as File | null;
|
|
if (!file) return NextResponse.json({ error: "No file" }, { status: 400 });
|
|
|
|
if (!file.name.toLowerCase().endsWith(".ogg")) {
|
|
return NextResponse.json({ error: "Only OGG files allowed" }, { status: 400 });
|
|
}
|
|
|
|
if (file.size > 2 * 1024 * 1024) {
|
|
return NextResponse.json({ error: "File too large (max 2MB)" }, { status: 400 });
|
|
}
|
|
|
|
await mkdir(UPLOAD_DIR, { recursive: true });
|
|
const ext = path.extname(file.name);
|
|
const filename = `${uuidv4()}${ext}`;
|
|
const filepath = path.join(UPLOAD_DIR, filename);
|
|
const bytes = await file.arrayBuffer();
|
|
await writeFile(filepath, Buffer.from(bytes));
|
|
|
|
// approximate duration
|
|
const duration = Math.round((file.size / (64 * 128)) * 10) / 10;
|
|
|
|
const id = uuidv4();
|
|
db.insert(sounds).values({
|
|
id,
|
|
originalName: file.name,
|
|
storedFilename: filename,
|
|
duration: Math.min(duration, 6),
|
|
uploadedBy: session.id,
|
|
createdAt: new Date().toISOString(),
|
|
}).run();
|
|
|
|
return NextResponse.json({ url: `/uploads/sounds/${filename}` });
|
|
} catch {
|
|
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
|
|
}
|
|
}
|