83 lines
4.5 KiB
TypeScript
83 lines
4.5 KiB
TypeScript
import { and, eq } from "drizzle-orm";
|
|
import { after } from "next/server";
|
|
import { getDb } from "@/db";
|
|
import { commissionMessages, commissionTickets } from "@/db/schema";
|
|
import type { CommissionMessageEvent } from "@/lib/commission/message-event";
|
|
import { sendCommissionMessagePush } from "@/lib/commission/push";
|
|
import { notifyCommission } from "@/lib/commission/server";
|
|
import { authorizeTicket } from "@/lib/commission/tickets";
|
|
import { getMediaStorage } from "@/lib/media/storage";
|
|
import { inspectImage } from "@/lib/media/inspect";
|
|
import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http";
|
|
import { limitRequest } from "@/lib/security/rate-limit";
|
|
import * as z from "zod";
|
|
|
|
export async function POST(request: Request, context: RouteContext<"/api/commission/tickets/[id]/messages">) {
|
|
try {
|
|
requireSameOrigin(request);
|
|
const { id } = await context.params;
|
|
const { ticket, user } = await authorizeTicket(id);
|
|
if (ticket.status !== "open") throw new HttpError(409, "ticket-closed");
|
|
await limitRequest("commission-message", user.id, 60);
|
|
if (!request.headers.get("content-type")?.startsWith("multipart/form-data;"))
|
|
throw new HttpError(415, "expected-multipart");
|
|
return await withUploadSlot(async () => {
|
|
const form = await boundedBody(request, 10 * 10 * 1024 * 1024 + 64 * 1024).formData();
|
|
const value = form.get("text");
|
|
const body = typeof value === "string" ? value.trim() : "";
|
|
const images = form.getAll("image");
|
|
const replyValue = form.get("replyToId");
|
|
const replyToId = replyValue === null || replyValue === "" ? null : replyValue;
|
|
if (body.length > 4000 || images.length > 10 || images.some((image) => !(image instanceof File)))
|
|
throw new HttpError(400, "invalid-message");
|
|
if (replyToId !== null) {
|
|
if (typeof replyToId !== "string" || !z.uuid().safeParse(replyToId).success)
|
|
throw new HttpError(400, "invalid-reply");
|
|
const [parent] = await getDb().select({ id: commissionMessages.id }).from(commissionMessages)
|
|
.where(and(eq(commissionMessages.id, replyToId), eq(commissionMessages.ticketId, id))).limit(1);
|
|
if (!parent) throw new HttpError(404, "reply-not-found");
|
|
}
|
|
if (!body && !images.length) throw new HttpError(400, "empty-message");
|
|
const imageFiles = images as File[];
|
|
if (imageFiles.some((image) => image.size === 0 || image.size > 10 * 1024 * 1024 ||
|
|
!["image/png", "image/jpeg", "image/webp"].includes(image.type)))
|
|
throw new HttpError(415, "invalid-message-image");
|
|
const imageObjectKeys: string[] = [];
|
|
let messageId: string;
|
|
try {
|
|
const storage = imageFiles.length ? await getMediaStorage() : null;
|
|
for (const image of imageFiles) {
|
|
const bytes = new Uint8Array(await image.arrayBuffer());
|
|
await inspectImage(bytes, image.type as "image/png" | "image/jpeg" | "image/webp");
|
|
const key = `commission/messages/${crypto.randomUUID()}`;
|
|
imageObjectKeys.push(key);
|
|
await storage!.write(key, bytes, { type: image.type, acl: "public-read" });
|
|
}
|
|
messageId = await getDb().transaction(async (tx) => {
|
|
const [message] = await tx.insert(commissionMessages).values({ ticketId: id, authorId: user.id, replyToId,
|
|
text: body || null, imageObjectKeys })
|
|
.returning({ id: commissionMessages.id });
|
|
await tx.update(commissionTickets).set({ updatedAt: new Date() }).where(eq(commissionTickets.id, id));
|
|
return message.id;
|
|
});
|
|
} catch (cause) {
|
|
if (imageObjectKeys.length) {
|
|
const storage = await getMediaStorage();
|
|
await Promise.all(imageObjectKeys.map((key) => storage.delete(key).catch(() => undefined)));
|
|
}
|
|
throw cause;
|
|
}
|
|
const message: CommissionMessageEvent = { messageId, ticketId: id,
|
|
ticketTitle: ticket.title || `Ticket #${id.slice(0, 8)}`,
|
|
authorId: user.id, authorName: user.name, text: body || null };
|
|
await notifyCommission(id, ticket.userId, `message:${JSON.stringify(message)}`);
|
|
after(() => sendCommissionMessagePush({ id: messageId, ticketId: id,
|
|
ticketTitle: message.ticketTitle, customerId: ticket.userId, authorId: user.id,
|
|
authorName: user.name, text: body || null }).catch(() => {
|
|
console.error("Commission push delivery failed");
|
|
}));
|
|
return Response.json({ ok: true, messageId }, { status: 201 });
|
|
});
|
|
} catch (cause) { return errorResponse(cause); }
|
|
}
|