43 lines
2.3 KiB
TypeScript
43 lines
2.3 KiB
TypeScript
// PEP-159: files for a chat message, a comment or a new story. The file is uploaded as soon as it is
|
||
// chosen (multipart: a server action's body is capped at 1 MB, files go up to 20 MB) and gets an id
|
||
// the form sends along; the action links it to the message. Access — the project's people.
|
||
import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_FILES, PeppaError, saveAttachment } from "@peppa/core";
|
||
import { m } from "@peppa/shared/i18n";
|
||
import { asWebActor, currentUser } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { getT } from "@/lib/i18n";
|
||
|
||
export const dynamic = "force-dynamic";
|
||
|
||
export async function POST(req: Request) {
|
||
const t = await getT();
|
||
const fail = (status: number, error: string) => Response.json({ error }, { status });
|
||
const me = await currentUser();
|
||
if (!me) return fail(401, t("Нужен вход"));
|
||
const user = asWebActor(me);
|
||
if (Number(req.headers.get("content-length") ?? 0) > ATTACHMENT_MAX_BYTES * ATTACHMENT_MAX_FILES + 512 * 1024) return fail(413, t("Файл больше 20 МБ. Приложите файл поменьше."));
|
||
let form: FormData;
|
||
try {
|
||
form = await req.formData();
|
||
} catch {
|
||
return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз."));
|
||
}
|
||
const projectId = Number(form.get("projectId"));
|
||
const files = form.getAll("files").filter((v): v is File => typeof v !== "string");
|
||
if (!Number.isInteger(projectId) || !files.length) return fail(400, t("Выберите файл."));
|
||
if (files.length > ATTACHMENT_MAX_FILES) return fail(400, t("Можно приложить не больше {n} файлов.", { n: ATTACHMENT_MAX_FILES }));
|
||
const saved = [];
|
||
const errors: string[] = [];
|
||
for (const f of files) {
|
||
try {
|
||
// Oversized files are refused before their bytes are read into memory.
|
||
if (f.size > ATTACHMENT_MAX_BYTES) throw new PeppaError(m("Файл «{name}» больше 20 МБ. Приложите файл поменьше.", { name: f.name }));
|
||
saved.push(await saveAttachment(db, user, { projectId, name: f.name, data: new Uint8Array(await f.arrayBuffer()) }));
|
||
} catch (e) {
|
||
if (!(e instanceof PeppaError)) throw e;
|
||
errors.push(t.text(e.message));
|
||
}
|
||
}
|
||
return Response.json({ files: saved, errors });
|
||
}
|