Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
car-crushers-portal/functions/api/coconut.ts
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
67 lines (55 sloc)
1.92 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AwsClient } from "aws4fetch"; | |
import { jsonError } from "../common.js"; | |
export async function onRequestPost(context: RequestContext) { | |
const { searchParams } = new URL(context.request.url); | |
const attachment = searchParams.get("attachment"); | |
const token = searchParams.get("token"); | |
if (!attachment || !token) | |
return jsonError("Invalid report id or token", 400); | |
const coconutToken: string | null = await context.env.DATA.get( | |
`coconutjob_${attachment}`, | |
); | |
if (!coconutToken) | |
return jsonError("Request is stale or otherwise invalid", 400); | |
if (coconutToken !== token) return jsonError("Forbidden", 403); | |
await context.env.DATA.delete(`coconutjob_${attachment}`); | |
const aws = new AwsClient({ | |
accessKeyId: context.env.R2_ACCESS_KEY, | |
secretAccessKey: context.env.R2_SECRET_KEY, | |
}); | |
const { event } = await context.request.json() as { event: string }; | |
if (event === "job.failed") { | |
await fetch(context.env.REPORTS_WEBHOOK, { | |
body: JSON.stringify({ | |
embeds: [ | |
{ | |
title: "Transcoding Failed", | |
color: 16711680, | |
description: `Attachment ${attachment} could not be transcoded, please log in to Coconut to see what went wrong.`, | |
}, | |
], | |
}), | |
headers: { | |
"content-type": "application/json", | |
}, | |
method: "POST", | |
}); | |
} else { | |
const R2_URL = `https://car-crushers.${context.env.R2_ZONE}.r2.cloudflarestorage.com`; | |
const copyResp = await aws.fetch(`${R2_URL}/${attachment}`, { | |
headers: { | |
"x-amz-copy-source": `/car-crushers/${attachment}.mp4`, | |
"x-amz-metadata-directive": "COPY", | |
}, | |
method: "PUT", | |
}); | |
await context.env.R2.delete(`${attachment}.mp4`); | |
if (!copyResp.ok) | |
console.log( | |
`Copy status: ${copyResp.status}\n\nCopy response body: ${await copyResp.text()}`, | |
); | |
} | |
return new Response(null, { | |
status: 204, | |
}); | |
} |