commit
Store Genshin images in the bucket, drop the Enka proxy
scripts/syncGenshin.ts copies character, weapon and artifact images from
enka.network into the bucket under genshin/{characters,weapons,artifacts}.
It only fetches and uploads what is missing, so it can be re-run after each
game patch.
The API now links to those copies on raw., so the /genshin/ui proxy route
on m. is no longer used and is removed. genshin/ is an ordinary bucket
folder now, so it also comes off the reserved path list and can be browsed
and uploaded to in the viewer.
Co-Authored-By: Sandrone <[email protected]>
diff --git a/.gitignore b/.gitignore
index 71204c9..cf70112 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,3 +14,6 @@ dist/
# Deno fetched by scripts/ci.sh in CI
.deno/
+
+# Downloaded Genshin images, see scripts/syncGenshin.ts
+.genshin-cache/
diff --git a/scripts/syncGenshin.ts b/scripts/syncGenshin.ts
new file mode 100644
index 0000000..d0dd5c1
--- /dev/null
+++ b/scripts/syncGenshin.ts
@@ -0,0 +1,277 @@
+// scripts/syncGenshin.ts
+
+// Copies Genshin UI images from enka.network into the R2 bucket, sorted into folders.
+// Re-run after each game patch: it only fetches and uploads what is missing.
+//
+// deno run -A scripts/syncGenshin.ts download only
+// deno run -A scripts/syncGenshin.ts --upload download, then upload (needs `wrangler login`)
+//
+// With more than one Cloudflare account, set CLOUDFLARE_ACCOUNT_ID for the upload.
+
+const upstreamBase = "https://enka.network/ui";
+const rawBase = "https://raw.doughmination.gay";
+const bucketName = "cdn";
+const bucketPrefix = "genshin";
+const cacheDir = ".genshin-cache";
+
+const charactersUrl = "https://raw.githubusercontent.com/EnkaNetwork/API-docs/master/store/gi/avatars.json";
+const weaponsUrl = "https://gi.yatta.moe/api/v2/en/weapon";
+const artifactsUrl = "https://gi.yatta.moe/api/v2/en/reliquary";
+
+const userAgent = "genshin-asset-sync/1.0";
+const parallelJobs = 4;
+
+type Folder = "characters" | "weapons" | "artifacts";
+
+type Asset = {
+ folder: Folder;
+ fileName: string;
+};
+
+type CharacterEntry = {
+ SideIconName?: string;
+};
+
+type YattaItem = {
+ id: number;
+ icon?: string;
+};
+
+type YattaList = {
+ data: {
+ items: Record<string, YattaItem>;
+ };
+};
+
+async function fetchJson<Data>(url: string): Promise<Data> {
+ const response = await fetch(url, { headers: { "User-Agent": userAgent } });
+
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
+
+ return (await response.json()) as Data;
+}
+
+// '/ui/UI_AvatarIcon_Side_Aino.png' becomes 'UI_AvatarIcon_Side_Aino', same as the API does
+function iconStem(raw: string | undefined): string {
+ if (!raw) return "";
+
+ const fileName = raw.trim().split("/").pop() ?? "";
+
+ return fileName.toLowerCase().endsWith(".png") ? fileName.slice(0, -4) : fileName;
+}
+
+// Icon, side icon and gacha artwork for every character
+async function characterAssets(): Promise<Asset[]> {
+ const characters = await fetchJson<Record<string, CharacterEntry>>(charactersUrl);
+ const stems = new Set<string>();
+
+ for (const entry of Object.values(characters)) {
+ const sideIcon = iconStem(entry.SideIconName);
+ if (!sideIcon) continue;
+
+ const fullIcon = sideIcon.replace("_Side_", "_");
+
+ stems.add(sideIcon);
+ stems.add(fullIcon);
+ stems.add(fullIcon.replace("UI_AvatarIcon_", "UI_Gacha_AvatarImg_"));
+ }
+
+ // Manekin and Manekina are not in the list, the API adds them by hand
+ for (const name of ["MannequinBoy", "MannequinGirl"]) {
+ stems.add(`UI_AvatarIcon_${name}`);
+ stems.add(`UI_AvatarIcon_Side_${name}`);
+ stems.add(`UI_Gacha_AvatarImg_${name}`);
+ }
+
+ return toAssets("characters", stems);
+}
+
+// Base icon plus the ascended (_Awaken) icon for every weapon
+async function weaponAssets(): Promise<Asset[]> {
+ const weapons = await fetchJson<YattaList>(weaponsUrl);
+ const stems = new Set<string>();
+
+ for (const weapon of Object.values(weapons.data.items)) {
+ if (!weapon.icon) continue;
+
+ stems.add(weapon.icon);
+ stems.add(`${weapon.icon}_Awaken`);
+ }
+
+ return toAssets("weapons", stems);
+}
+
+// Up to five pieces per set. Small sets have fewer, those answer 404 and are remembered.
+async function artifactAssets(): Promise<Asset[]> {
+ const sets = await fetchJson<YattaList>(artifactsUrl);
+ const stems = new Set<string>();
+
+ for (const set of Object.values(sets.data.items)) {
+ for (const piece of [1, 2, 3, 4, 5]) {
+ stems.add(`UI_RelicIcon_${set.id}_${piece}`);
+ }
+ }
+
+ return toAssets("artifacts", stems);
+}
+
+function toAssets(folder: Folder, stems: Set<string>): Asset[] {
+ return [...stems].sort().map((stem) => ({
+ folder,
+ fileName: `${stem}.png`,
+ }));
+}
+
+const localPath = (asset: Asset) => `${cacheDir}/${asset.folder}/${asset.fileName}`;
+const bucketKey = (asset: Asset) => `${bucketPrefix}/${asset.folder}/${asset.fileName}`;
+
+async function fileExists(path: string): Promise<boolean> {
+ try {
+ await Deno.stat(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Names Enka does not have, so later runs skip them
+const missingPath = `${cacheDir}/missing.json`;
+
+async function readMissing(): Promise<Set<string>> {
+ try {
+ return new Set(JSON.parse(await Deno.readTextFile(missingPath)) as string[]);
+ } catch {
+ return new Set();
+ }
+}
+
+// Runs the job over every item, a few at a time
+async function inParallel<Item>(items: Item[], job: (item: Item) => Promise<void>): Promise<void> {
+ const queue = [...items];
+
+ const workers = Array.from({ length: parallelJobs }, async () => {
+ for (let item = queue.shift(); item !== undefined; item = queue.shift()) {
+ await job(item);
+ }
+ });
+
+ await Promise.all(workers);
+}
+
+async function download(assets: Asset[]): Promise<Asset[]> {
+ const missing = await readMissing();
+ const ready: Asset[] = [];
+ let fetched = 0;
+ let failed = 0;
+
+ for (const folder of ["characters", "weapons", "artifacts"]) {
+ await Deno.mkdir(`${cacheDir}/${folder}`, { recursive: true });
+ }
+
+ await inParallel(assets, async (asset) => {
+ const path = localPath(asset);
+
+ if (await fileExists(path)) {
+ ready.push(asset);
+ return;
+ }
+
+ if (missing.has(bucketKey(asset))) return;
+
+ const response = await fetch(`${upstreamBase}/${asset.fileName}`, {
+ headers: { "User-Agent": userAgent },
+ });
+
+ if (response.status === 404) {
+ await response.body?.cancel();
+ missing.add(bucketKey(asset));
+ return;
+ }
+
+ if (!response.ok) {
+ await response.body?.cancel();
+ failed += 1;
+ console.error(`download failed (${response.status}): ${asset.fileName}`);
+ return;
+ }
+
+ await Deno.writeFile(path, new Uint8Array(await response.arrayBuffer()));
+ ready.push(asset);
+ fetched += 1;
+
+ if (fetched % 50 === 0) console.log(`downloaded ${fetched}…`);
+ });
+
+ await Deno.writeTextFile(missingPath, JSON.stringify([...missing].sort(), null, 2));
+
+ console.log(`download: ${fetched} new, ${ready.length} ready, ${missing.size} not on Enka, ${failed} failed`);
+
+ return ready;
+}
+
+async function upload(assets: Asset[]): Promise<void> {
+ let uploaded = 0;
+ let skipped = 0;
+ let failed = 0;
+
+ await inParallel(assets, async (asset) => {
+ const key = bucketKey(asset);
+
+ // The bucket is public on raw., so a HEAD tells us what is already there
+ const existing = await fetch(`${rawBase}/${key}`, { method: "HEAD" });
+
+ if (existing.ok) {
+ skipped += 1;
+ return;
+ }
+
+ const command = new Deno.Command("npx", {
+ args: [
+ "wrangler",
+ "r2",
+ "object",
+ "put",
+ `${bucketName}/${key}`,
+ "--file",
+ localPath(asset),
+ "--content-type",
+ "image/png",
+ "--remote",
+ ],
+ stdout: "null",
+ stderr: "piped",
+ });
+
+ const result = await command.output();
+
+ if (!result.success) {
+ failed += 1;
+ console.error(`upload failed: ${key}\n${new TextDecoder().decode(result.stderr).trim()}`);
+ return;
+ }
+
+ uploaded += 1;
+
+ if (uploaded % 25 === 0) console.log(`uploaded ${uploaded}…`);
+ });
+
+ console.log(`upload: ${uploaded} new, ${skipped} already in the bucket, ${failed} failed`);
+
+ if (failed > 0) Deno.exit(1);
+}
+
+const assets = [
+ ...(await characterAssets()),
+ ...(await weaponAssets()),
+ ...(await artifactAssets()),
+];
+
+console.log(`${assets.length} candidate files`);
+
+const ready = await download(assets);
+
+if (Deno.args.includes("--upload")) {
+ await upload(ready);
+} else {
+ console.log("download only. Add --upload to send them to the bucket.");
+}
diff --git a/src/files.ts b/src/files.ts
index 431ae8f..d3047ed 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -9,7 +9,7 @@ const FILE_CACHE = "public, max-age=86400";
const MAX_KEY_BYTES = 1024;
// Paths the viewer itself answers, so a folder there could never be browsed.
-const RESERVED = ["_app/", "api/", "auth/", "login", "logout", "upload", "licence", "genshin/", "LICENCE.md", ".well-known/", "favicon.svg", "favicon.png", "style.css", "sfx.js"];
+const RESERVED = ["_app/", "api/", "auth/", "login", "logout", "upload", "licence", "LICENCE.md", ".well-known/", "favicon.svg", "favicon.png", "style.css", "sfx.js"];
// Known extensions always get these, since browsers often send nothing useful
// (.glb, fonts, .mov and friends). Anything else keeps what the uploader sent.
diff --git a/src/genshin.ts b/src/genshin.ts
deleted file mode 100644
index 1106c96..0000000
--- a/src/genshin.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-// Proxy + edge-cache for enka.network/ui/* Genshin game assets.
-//
-// GET /genshin/ui/UI_Gacha_AvatarImg_Neuvillette.png
-// -> https://enka.network/ui/UI_Gacha_AvatarImg_Neuvillette.png
-//
-// The Discord bot's Genshin character card pulls a lot of icons per render
-// (splash art, weapon, five artifacts, stat glyphs). Routing them through
-// here means Enka is hit at most once per asset per Cloudflare PoP and then
-// it's served from cache, so card rendering can't get us rate-limited
-// upstream. Enka's asset filenames are content-stable, so the cache is long
-// and immutable.
-
-import type { Handler } from "hono";
-import type { AppEnv } from "./env";
-
-const UPSTREAM = "https://enka.network/ui/";
-const ALLOWED = /^[A-Za-z0-9][A-Za-z0-9_-]*\.(png|webp|jpg|jpeg)$/;
-const CACHE_TTL = 60 * 60 * 24 * 30; // 30 days
-
-export const genshinUi: Handler<AppEnv> = async (c) => {
- const request = c.req.raw;
- const name = c.req.param("name") ?? "";
-
- if (!name || name.includes("..") || !ALLOWED.test(name)) {
- return new Response("Not found", { status: 404 });
- }
-
- const cache = caches.default;
- const cacheKey = new Request(new URL(request.url).toString());
- const cached = await cache.match(cacheKey);
- if (cached) return cached;
-
- let upstream: Response;
- try {
- upstream = await fetch(UPSTREAM + name, {
- headers: {
- "User-Agent": "doughmination-cdn/1.0 (+https://m.doughmination.gay)",
- Accept: "image/avif,image/webp,image/png,*/*",
- },
- cf: { cacheEverything: true, cacheTtl: CACHE_TTL },
- });
- } catch {
- return new Response("Upstream fetch failed", { status: 502 });
- }
-
- if (!upstream.ok) {
- return new Response("Upstream error", {
- status: upstream.status === 404 ? 404 : 502,
- });
- }
-
- const headers = new Headers();
- headers.set("Content-Type", upstream.headers.get("Content-Type") ?? "image/png");
- headers.set("Cache-Control", `public, max-age=${CACHE_TTL}, immutable`);
- headers.set("X-Proxied-From", "enka.network");
-
- const response = new Response(upstream.body, { status: 200, headers });
- c.executionCtx.waitUntil(cache.put(cacheKey, response.clone()));
- return response;
-};
diff --git a/src/main.ts b/src/main.ts
index 77020ca..d21fca9 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -5,7 +5,7 @@
// Order of business for a request:
//
// 1. CORS (allowlisted origins get Access-Control-Allow-Origin)
-// 2. Worker routes: sign-in, the file API (uploads, folders, deletes), the Genshin proxy
+// 2. Worker routes: sign-in, the file API (uploads, folders, deletes)
// 3. Static site files (the Svelte app from ./dist, styles, .well-known, …)
// 4. Otherwise the app shell, if the path is a folder or a file in R2:
// /img browses "img/", /img/foo.png previews that file (with link-embed
@@ -18,7 +18,6 @@ import { cors } from "./cors";
import { fileEmbed } from "./embed";
import { issuer, type AppContext, type AppEnv } from "./env";
import { createFolder, deleteFile, isFolder, listFiles, serveFile, uploadFile } from "./files";
-import { genshinUi } from "./genshin";
const app = new Hono<AppEnv>();
@@ -84,8 +83,6 @@ app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
// --- misc ---------------------------------------------------------------------------
-app.get("/genshin/ui/:name", genshinUi);
-
app.get("/licence", (c) => shell(c));
app.get("/licence.html", (c) => c.redirect("/licence", 301));