41 lines
1.9 KiB
JavaScript
41 lines
1.9 KiB
JavaScript
import { addonsJs, indexHtml } from "./assets.js";
|
|
|
|
const BING_ARCHIVE = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US";
|
|
|
|
async function bingMetadata() {
|
|
const response = await fetch(BING_ARCHIVE, { headers: { accept: "application/json" } });
|
|
if (!response.ok) throw new Error(`Bing metadata request failed: ${response.status}`);
|
|
const image = (await response.json()).images?.[0];
|
|
if (!image?.url) throw new Error("Bing did not return today's image");
|
|
return {
|
|
title: image.copyright || "Bing Daily Image",
|
|
url: new URL(image.url, "https://www.bing.com").toString(),
|
|
};
|
|
}
|
|
|
|
function headers(type, cache = "public, max-age=3600") {
|
|
return { "content-type": type, "cache-control": cache };
|
|
}
|
|
|
|
export default {
|
|
async fetch(request) {
|
|
const url = new URL(request.url);
|
|
try {
|
|
if (url.pathname === "/api/bing-wallpaper") {
|
|
return Response.json(await bingMetadata(), { headers: { "cache-control": "public, max-age=3600" } });
|
|
}
|
|
if (url.pathname === "/api/bing-wallpaper-image") {
|
|
const image = await bingMetadata();
|
|
const response = await fetch(image.url);
|
|
if (!response.ok) throw new Error(`Bing image request failed: ${response.status}`);
|
|
return new Response(response.body, { headers: headers(response.headers.get("content-type") || "image/jpeg", "public, max-age=21600") });
|
|
}
|
|
} catch (error) {
|
|
return Response.json({ error: "Bing wallpaper is temporarily unavailable", detail: String(error) }, { status: 502 });
|
|
}
|
|
if (url.pathname === "/addons.js") return new Response(addonsJs, { headers: headers("application/javascript; charset=utf-8") });
|
|
if (url.pathname === "/" || url.pathname === "/index.html") return new Response(indexHtml, { headers: headers("text/html; charset=utf-8", "no-cache") });
|
|
return new Response("Not found", { status: 404 });
|
|
},
|
|
};
|