From fe024c37da4b1512d83dcbdc21b007d4eaed5d6e Mon Sep 17 00:00:00 2001 From: Regalijan Date: Thu, 2 Nov 2023 08:22:08 -0400 Subject: [PATCH] Use direct uploads for infraction (files are processed serverside) --- functions/api/infractions/new.ts | 39 +++++++++++++------------------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/functions/api/infractions/new.ts b/functions/api/infractions/new.ts index 99f4922..c724e91 100644 --- a/functions/api/infractions/new.ts +++ b/functions/api/infractions/new.ts @@ -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,