Skip to content

Instantly share code, notes, and snippets.

@Potato22
Created May 21, 2024 20:31
Show Gist options
  • Save Potato22/870a1b3012a10b111b9def8e1bd249d0 to your computer and use it in GitHub Desktop.
Save Potato22/870a1b3012a10b111b9def8e1bd249d0 to your computer and use it in GitHub Desktop.
pottob2worker
// src/backblaze.ts
var B2Error = class extends Error {
details;
constructor(message, response) {
super(message);
this.details = response.message;
}
toString() {
return `${this.message}: ${this.details}`;
}
};
async function b2_authorize_account(accountId, applicationKey) {
const response = await fetch("https://api.backblazeb2.com/b2api/v3/b2_authorize_account", {
method: "GET",
headers: {
Authorization: `Basic ${btoa(`${accountId}:${applicationKey}`)}`
}
});
if (!response.ok) {
throw new B2Error("Failed to authorize account", await response.json());
}
return response.json();
}
async function b2_list_file_names(apiUrl, authorizationToken, bucketId) {
const response = await fetch(`${apiUrl}/b2api/v3/b2_list_file_names?bucketId=${bucketId}`, {
method: "GET",
headers: {
Authorization: authorizationToken
}
});
if (!response.ok) {
throw new B2Error("Failed to list files", await response.json());
}
return response.json();
}
// src/index.ts
var src_default = {
/**
* This is the entry point for your Worker code.
* Whenever you send an API request to your Worker, this is the function that will run.
*/
async fetch(request, env, ctx) {
try {
const url = new URL(request.url);
if (url.pathname === "/" && request.method === "GET") {
return await getHomepage(url, request, env, ctx);
}
if (url.pathname === "/api/v1/list_all_files" && request.method === "GET") {
return await getFileList(url, request, env, ctx);
}
return new Response("Not Found", { status: 404 });
} catch (error) {
console.error(error);
return new Response(error.message, { status: 500 });
}
}
};
async function getHomepage(url, request, env, ctx) {
return new Response("fish", {
headers: { "content-type": "text/plain" }
});
}
async function getFileList(url, request, env, ctx) {
const cacheKey = new Request(request.url, request);
let response = await caches.default.match(cacheKey);
if (response) {
return response;
}
const authorizationData = await b2_authorize_account(env.B2_APP_ID, env.B2_APP_KEY);
const downloadUrl = authorizationData.apiInfo.storageApi.downloadUrl;
const apiUrl = authorizationData.apiInfo.storageApi.apiUrl;
const authorizationToken = authorizationData.authorizationToken;
const listFilesData = await b2_list_file_names(apiUrl, authorizationToken, env.B2_BUCKET_ID);
const customDomainOrigin = "https://gallery.pottoart.uk";
const filesInBucket = listFilesData.files.filter((file) => file.action === "upload").map((file) => ({
name: file.fileName,
size: file.contentLength,
contentType: file.contentType,
uploadTime: new Date(file.uploadTimestamp).toISOString(),
url: `${customDomainOrigin}/file/${env.B2_BUCKET_NAME}/${encodeURI(file.fileName)}`,
fileInfo: file.fileInfo
}));
response = new Response(JSON.stringify(filesInBucket), {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"Cache-Control": "s-maxage=300"
// 5 min cache
}
});
ctx.waitUntil(caches.default.put(cacheKey, response.clone()));
return response;
}
export {
src_default as default
};
//# sourceMappingURL=index.js.map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment