From fbe054b2112893ac5e7acd48787103a599cf026b Mon Sep 17 00:00:00 2001
From: regalijan <r@regalijan.com>
Date: Thu, 19 Oct 2023 16:51:19 -0400
Subject: [PATCH] Delete all files on report recall

---
 functions/api/reports/recall.ts | 36 +++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/functions/api/reports/recall.ts b/functions/api/reports/recall.ts
index dbd16e9..0e0b6cc 100644
--- a/functions/api/reports/recall.ts
+++ b/functions/api/reports/recall.ts
@@ -1,3 +1,4 @@
+import { GetAccessToken } from "../../gcloud.js";
 import { jsonError } from "../../common.js";
 
 export async function onRequestPost(context: RequestContext) {
@@ -14,7 +15,42 @@ export async function onRequestPost(context: RequestContext) {
   )
     return jsonError("No processing report with that ID found", 404);
 
+  const data: { [k: string]: any } | null = await context.env.DATA.get(
+    `report_${id}`,
+    { type: "json" },
+  );
+
+  if (!data) return jsonError("Report doesn't exist", 404);
+
+  const accessToken = await GetAccessToken(context.env);
+  const attachmentDeletePromises = [];
+  const existingAttachments = [...data.attachments];
+
+  for (const attachment of existingAttachments) {
+    if (!attachment.startsWith("t/")) data.attachments.push(`t/${attachment}`);
+    else data.attachments.push(attachment.replace("t/", ""));
+  }
+
+  for (const attachment of data.attachments)
+    attachmentDeletePromises.push(
+      fetch(
+        `https://storage.googleapis.com/storage/v1/b/portal-carcrushers-cc/o/${encodeURIComponent(
+          attachment,
+        )}`,
+        {
+          headers: {
+            authorization: `Bearer ${accessToken}`,
+          },
+          method: "DELETE",
+        },
+      ),
+    );
+
+  await Promise.allSettled(attachmentDeletePromises);
   await context.env.DATA.delete(`report_${id}`);
+  await context.env.D1.prepare("DELETE FROM reports WHERE id = ?;")
+    .bind(id)
+    .run();
 
   return new Response(null, {
     status: 204,