Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Use R2 for my data view
  • Loading branch information
regalijan committed Mar 27, 2024
1 parent 8af6678 commit 9301d6e
Showing 1 changed file with 18 additions and 47 deletions.
65 changes: 18 additions & 47 deletions functions/api/me/items/[type]/[id].ts
Expand Up @@ -19,57 +19,28 @@ export async function onRequestGet(context: RequestContext) {
return jsonError("Item does not exist", 404);

if (type === "report") {
let unsignedUrls = [];
const exp = Math.round(Date.now() / 1000) + 1800;

for (const attachment of data.attachments)
unsignedUrls.push(
`https://mediaproxy.carcrushers.cc/${attachment}?Expires=${exp}&KeyName=portal-media-linkgen`,
const { AwsClient } = await import("aws4fetch");
const aws = new AwsClient({
accessKeyId: context.env.R2_ACCESS_KEY,
secretAccessKey: context.env.R2_SECRET_KEY,
});

let urls = [];

for (const attachment of data.attachments) {
const { url } = await aws.sign(
`https://car-crushers.${context.env.R2_ZONE}.r2.cloudflarestorage.com/${attachment}?X-Amz-Expires=1800`,
{
aws: {
signQuery: true,
},
},
);

let resolvedUrls = [];
let signingPromises = [];
const key = await crypto.subtle.importKey(
"raw",
Uint8Array.from(atob(context.env.URL_SIGNING_KEY), (c) =>
c.charCodeAt(0),
),
{ hash: "SHA-1", name: "HMAC" },
false,
["sign"],
);

for (let i = 0; i < unsignedUrls.length; i++)
signingPromises.push(
crypto.subtle.sign(
"HMAC",
key,
new TextEncoder().encode(unsignedUrls[i]),
),
);

let signatures: ArrayBuffer[];

try {
signatures = await Promise.all(signingPromises);
} catch (e) {
console.log(e);

return jsonError("Failed to create signed links", 500);
}

for (let i = 0; i < signatures.length; i++) {
resolvedUrls.push(
`${unsignedUrls[i]}&Signature=${btoa(
String.fromCharCode(...new Uint8Array(signatures[i])),
)
.replaceAll("+", "-")
.replaceAll("/", "_")
.replaceAll("=", "")}`,
);
urls.push(url);
}

data.resolved_attachments = resolvedUrls;
data.resolved_attachments = urls;
}

return jsonResponse(JSON.stringify(data));
Expand Down

0 comments on commit 9301d6e

Please sign in to comment.