Use direct uploads for infraction (files are processed serverside)

This commit is contained in:
Regalijan 2023-11-02 08:22:08 -04:00
parent 6f2bb0ebd1
commit fe024c37da
Signed by: regalijan
GPG Key ID: 5D4196DA269EF520

View File

@ -1,4 +1,4 @@
import { GenerateUploadURL } from "../../gcloud.js";
import { GetAccessToken } from "../../gcloud.js";
import { jsonError } from "../../common.js";
const allowedFileTypes = [
@ -69,11 +69,13 @@ export async function onRequestPost(context: RequestContext) {
files.push(file);
}
const urlPromises = [];
const uploadPromises = [];
const origin = context.request.headers.get("Origin");
if (!origin) return jsonError("Origin header missing", 400);
const accessToken = await GetAccessToken(context.env);
for (const file of files) {
if (!allowedFileTypes.includes(file.type))
return jsonError(`File ${file.name} is not valid`, 415);
@ -82,35 +84,26 @@ export async function onRequestPost(context: RequestContext) {
Math.random() * 10000000,
).toString()}/${file.name}`;
urlPromises.push(
GenerateUploadURL(
context.env,
attachmentKey,
file.size,
(allowedFileTypes.find((t) => t === file.type) as string).split("/")[1],
origin,
uploadPromises.push(
fetch(
`https://storage.googleapis.com/upload/storage/v1/b/portal-carcrushers-cc/o?name=${encodeURIComponent(
attachmentKey,
)}&uploadType=media`,
{
headers: {
authorization: `Bearer ${accessToken}`,
"content-type": file.type,
},
},
),
);
}
const settledURLPromises = await Promise.allSettled(urlPromises);
if (settledURLPromises.find((p) => p.status === "rejected"))
return jsonError("Failed to process one or more files", 500);
await Promise.allSettled(uploadPromises);
const infractionId = `${body.get(
"user",
)}${Date.now()}${context.request.headers.get("cf-ray")?.split("-")[0]}`;
const uploadReqs = [];
for (let i = 0; i < files.length; i++) {
uploadReqs.push(
fetch(settledURLPromises[i] as unknown as string, {
body: files[i],
method: "PUT",
}),
);
}
await context.env.DATA.put(
infractionId,