commit
Add banner uploads and a one-off image mover
Member banners are uploads-only, like avatars, through a shared upload route. Owners can also move every member and system image that still lives elsewhere into the site's R2; links that 404 are removed. Co-Authored-By: Sandrone <[email protected]>
diff --git a/src/lib/server/plural/routes/admin.ts b/src/lib/server/plural/routes/admin.ts
index 274586b..3657212 100644
--- a/src/lib/server/plural/routes/admin.ts
+++ b/src/lib/server/plural/routes/admin.ts
@@ -8,9 +8,10 @@ import { createRoute, z } from "@hono/zod-openapi";
import { router, ok, signedIn } from "../openapi";
import { MessageSchema } from "../schemas";
-import { requireAuth, requireAdmin } from "../middleware/auth";
+import { requireAuth, requireAdmin, requireOwner } from "../middleware/auth";
import { broadcastFrontendUpdate } from "../ws";
import { rt } from "../runtime";
+import { localiseMedia } from "../services/localise";
export const adminRoutes = router();
@@ -30,6 +31,30 @@ adminRoutes.openapi(
},
);
+// One-off: copy every outside image link into this site's R2, dropping links that are gone
+adminRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/admin/media/localise",
+ tags: ["Admin"],
+ summary: "Move every member and system image onto this site (owner). Links that 404 are removed",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ responses: ok(
+ z.object({
+ copied: z.array(z.string()),
+ removed: z.array(z.string()),
+ kept: z.array(z.string()),
+ }),
+ ),
+ }),
+ async (c) => {
+ const report = await localiseMedia();
+ await broadcastFrontendUpdate("members_update", {});
+ return c.json(report, 200);
+ },
+);
+
// Member avatars uploaded from the admin page. Public, so Discord and browsers can load them
adminRoutes.openapi(
createRoute({
diff --git a/src/lib/server/plural/routes/members.ts b/src/lib/server/plural/routes/members.ts
index 6be3eb4..b0b0672 100644
--- a/src/lib/server/plural/routes/members.ts
+++ b/src/lib/server/plural/routes/members.ts
@@ -112,48 +112,67 @@ membersRoutes.openapi(
);
// No SVG: it would run scripts from this site's own origin
-const AVATAR_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
+const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
-membersRoutes.openapi(
- createRoute({
- method: "post",
- path: "/members/{member_identifier}/avatar",
- tags: ["Members"],
+// Each upload gets one fixed R2 key per member, so a new upload overwrites the last
+const IMAGE_UPLOADS = [
+ {
+ path: "avatar",
+ field: "avatar_url",
summary: "Upload a member's avatar (owner). Replaces the old one, including the proxy avatar",
- security: signedIn,
- middleware: [requireAuth, requireOwner] as const,
- request: {
- params: IdentifierParam,
- },
- responses: ok(MemberSchema, "The updated member"),
- }),
- async (c) => {
- const member = await findMember(c.req.valid("param").member_identifier);
- if (!member) throw new HttpError(404, "Member not found");
+ patch: (url: string) => ({
+ avatar_url: url,
+ webhook_avatar_url: null,
+ }),
+ },
+ {
+ path: "banner",
+ field: "banner",
+ summary: "Upload a member's banner (owner). Replaces the old one",
+ patch: (url: string) => ({
+ banner: url,
+ }),
+ },
+] as const;
- const type = c.req.header("Content-Type") ?? "";
- if (!AVATAR_TYPES.includes(type)) throw new HttpError(415, "Use a PNG, JPEG, GIF or WebP image");
+for (const upload of IMAGE_UPLOADS) {
+ membersRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: `/members/{member_identifier}/${upload.path}`,
+ tags: ["Members"],
+ summary: upload.summary,
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: {
+ params: IdentifierParam,
+ },
+ responses: ok(MemberSchema, "The updated member"),
+ }),
+ async (c) => {
+ const member = await findMember(c.req.valid("param").member_identifier);
+ if (!member) throw new HttpError(404, "Member not found");
- const body = await c.req.arrayBuffer();
- if (body.byteLength === 0) throw new HttpError(400, "The image is empty");
- if (body.byteLength > MAX_MEDIA_BYTES) throw new HttpError(413, "The image is over 10 MB");
+ const type = c.req.header("Content-Type") ?? "";
+ if (!IMAGE_TYPES.includes(type)) throw new HttpError(415, "Use a PNG, JPEG, GIF or WebP image");
- // One fixed key per member, so each upload overwrites the last
- const key = `member-${member.id}-avatar_url`;
- await rt().env.MEDIA.put(key, body, {
- httpMetadata: {
- contentType: type,
- },
- });
+ const body = await c.req.arrayBuffer();
+ if (body.byteLength === 0) throw new HttpError(400, "The image is empty");
+ if (body.byteLength > MAX_MEDIA_BYTES) throw new HttpError(413, "The image is over 10 MB");
- // New query each time so Discord and browsers drop their cached copy
- const updated = await updateMember(member.id as string, {
- avatar_url: `${mediaUrl(key)}?v=${Date.now()}`,
- webhook_avatar_url: null,
- });
- return c.json(await enrichOne(updated), 200);
- },
-);
+ const key = `member-${member.id}-${upload.field}`;
+ await rt().env.MEDIA.put(key, body, {
+ httpMetadata: {
+ contentType: type,
+ },
+ });
+
+ // New query each time so Discord and browsers drop their cached copy
+ const updated = await updateMember(member.id as string, upload.patch(`${mediaUrl(key)}?v=${Date.now()}`));
+ return c.json(await enrichOne(updated), 200);
+ },
+ );
+}
membersRoutes.openapi(
createRoute({
diff --git a/src/lib/server/plural/schemas.ts b/src/lib/server/plural/schemas.ts
index a3c2986..cdd80a3 100644
--- a/src/lib/server/plural/schemas.ts
+++ b/src/lib/server/plural/schemas.ts
@@ -97,7 +97,6 @@ const memberFields = {
.regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD")
.nullable(),
pronouns: z.string().max(100).nullable(),
- banner: Url,
description: z.string().max(1000).nullable(),
proxy_tags: z.array(ProxyTagSchema).max(100),
keep_proxy: z.boolean(),
diff --git a/src/lib/server/plural/services/localise.ts b/src/lib/server/plural/services/localise.ts
new file mode 100644
index 0000000..0d9d466
--- /dev/null
+++ b/src/lib/server/plural/services/localise.ts
@@ -0,0 +1,134 @@
+/* src/lib/server/plural/services/localise.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { rt } from "../runtime";
+import type { JsonObject } from "../types";
+import { MAX_MEDIA_BYTES, mediaUrl } from "./media";
+import { getMembers, getSystem, updateMember, updateSystem } from "./system";
+
+// No SVG: it would run scripts from this site's own origin
+const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
+
+export interface LocaliseReport {
+ copied: string[];
+ removed: string[];
+ kept: string[];
+}
+
+type Outcome = { kind: "copied"; url: string } | { kind: "removed" } | { kind: "kept"; reason: string };
+
+function external(url: unknown): url is string {
+ return typeof url === "string" && url !== "" && !url.startsWith(mediaUrl(""));
+}
+
+// Only 404 and 410 mean gone; anything else (403, 5xx, network) keeps the old link
+async function copyInto(source: string, key: string): Promise<Outcome> {
+ let response: Response;
+ try {
+ response = await fetch(source);
+ } catch (error) {
+ return {
+ kind: "kept",
+ reason: error instanceof Error ? error.message : "network error",
+ };
+ }
+
+ if (response.status === 404 || response.status === 410) return { kind: "removed" };
+ if (!response.ok) return { kind: "kept", reason: `HTTP ${response.status}` };
+
+ const type = (response.headers.get("Content-Type") ?? "").split(";")[0]?.trim() ?? "";
+ if (!IMAGE_TYPES.includes(type)) return { kind: "kept", reason: `not a PNG, JPEG, GIF or WebP (${type || "no type"})` };
+
+ const body = await response.arrayBuffer();
+ if (body.byteLength > MAX_MEDIA_BYTES) return { kind: "kept", reason: "over 10 MB" };
+
+ await rt().env.MEDIA.put(key, body, {
+ httpMetadata: {
+ contentType: type,
+ },
+ });
+ return {
+ kind: "copied",
+ url: `${mediaUrl(key)}?v=${Date.now()}`,
+ };
+}
+
+// Applies one outcome to the patch and the report. Returns the new value for the field
+function record(outcome: Outcome, label: string, report: LocaliseReport): string | null | undefined {
+ if (outcome.kind === "copied") {
+ report.copied.push(label);
+ return outcome.url;
+ }
+ if (outcome.kind === "removed") {
+ report.removed.push(label);
+ return null;
+ }
+ report.kept.push(`${label}: ${outcome.reason}`);
+ return undefined;
+}
+
+async function localiseMember(member: JsonObject, report: LocaliseReport): Promise<void> {
+ const id = String(member.id);
+ const name = String(member.name ?? id);
+ const patch: JsonObject = {};
+
+ // The avatar is the one image now; an old separate proxy avatar fills in when there's no avatar
+ const avatarSource = external(member.avatar_url)
+ ? member.avatar_url
+ : member.avatar_url
+ ? null
+ : external(member.webhook_avatar_url)
+ ? member.webhook_avatar_url
+ : null;
+
+ if (avatarSource) {
+ const value = record(await copyInto(avatarSource, `member-${id}-avatar_url`), `${name} avatar`, report);
+ if (value !== undefined) {
+ patch.avatar_url = value;
+ patch.webhook_avatar_url = null;
+ }
+ } else if (external(member.webhook_avatar_url)) {
+ // The avatar is already local, so the proxy uses it too
+ patch.webhook_avatar_url = null;
+ report.removed.push(`${name} separate proxy avatar (now uses the avatar)`);
+ }
+
+ if (external(member.banner)) {
+ const value = record(await copyInto(member.banner, `member-${id}-banner`), `${name} banner`, report);
+ if (value !== undefined) patch.banner = value;
+ }
+
+ if (Object.keys(patch).length > 0) await updateMember(id, patch);
+}
+
+async function localiseSystem(report: LocaliseReport): Promise<void> {
+ const system = await getSystem();
+ const patch: JsonObject = {};
+
+ for (const field of ["avatar_url", "banner"] as const) {
+ const source = system[field];
+ if (!external(source)) continue;
+
+ const value = record(await copyInto(source, `system-${field}`), `system ${field}`, report);
+ if (value !== undefined) patch[field] = value;
+ }
+
+ if (Object.keys(patch).length > 0) await updateSystem(patch);
+}
+
+// One-off: moves every member and system image onto this site's R2
+export async function localiseMedia(): Promise<LocaliseReport> {
+ const report: LocaliseReport = {
+ copied: [],
+ removed: [],
+ kept: [],
+ };
+
+ for (const member of await getMembers()) await localiseMember(member, report);
+ await localiseSystem(report);
+
+ return report;
+}
diff --git a/src/routes/admin/members/+page.svelte b/src/routes/admin/members/+page.svelte
index 7713bad..0607a7d 100644
--- a/src/routes/admin/members/+page.svelte
+++ b/src/routes/admin/members/+page.svelte
@@ -41,11 +41,6 @@
label: "Birthday",
placeholder: "YYYY-MM-DD, year 0004 hides it",
},
- {
- key: "banner",
- label: "Banner URL",
- placeholder: "https://…",
- },
] as const;
type FieldKey = (typeof FIELDS)[number]["key"];
@@ -58,6 +53,8 @@
let message = $state<MessageType>(null);
let avatarFile = $state<FileList | null>(null);
+ let bannerFile = $state<FileList | null>(null);
+ let localiseKept = $state<string[]>([]);
const chosen = $derived(members.find((member) => member.id === chosenId) ?? null);
@@ -68,7 +65,6 @@
pronouns: "",
color: "",
birthday: "",
- banner: "",
description: "",
proxy_tags: "",
};
@@ -95,8 +91,9 @@
function pick(member: PluralMember | null) {
chosenId = member?.id ?? null;
- // A picked image belongs to the member it was picked for
+ // Picked images belong to the member they were picked for
avatarFile = new DataTransfer().files;
+ bannerFile = new DataTransfer().files;
message = null;
if (!member) {
form = emptyForm();
@@ -108,7 +105,6 @@
pronouns: member.pronouns ?? "",
color: member.color ?? "",
birthday: member.birthday ?? "",
- banner: member.banner ?? "",
description: member.description ?? "",
proxy_tags: tagsToText(member.proxy_tags),
};
@@ -162,7 +158,16 @@
// Read before pick() below clears them
const creating = !chosenId;
- const file = avatarFile?.[0];
+ const uploads = [
+ {
+ path: "avatar",
+ file: avatarFile?.[0],
+ },
+ {
+ path: "banner",
+ file: bannerFile?.[0],
+ },
+ ];
void run(async () => {
const path = chosenId ? `/plural/members/${encodeURIComponent(chosenId)}` : "/plural/members";
@@ -175,15 +180,18 @@
await reload();
pick(members.find((member) => member.id === saved.id) ?? null);
- // The picked image waited in the form until the member existed
- if (file) {
- await authFetch(`/plural/members/${encodeURIComponent(saved.id)}/avatar`, {
+ // Picked images waited in the form until the member existed
+ const picked = uploads.filter((upload) => upload.file);
+ for (const { path, file } of picked) {
+ await authFetch(`/plural/members/${encodeURIComponent(saved.id)}/${path}`, {
method: "POST",
headers: {
- "Content-Type": file.type,
+ "Content-Type": file!.type,
},
body: file,
- }, "Member saved, but the avatar upload failed");
+ }, `Member saved, but the ${path} upload failed`);
+ }
+ if (picked.length > 0) {
await reload();
pick(members.find((member) => member.id === saved.id) ?? null);
}
@@ -192,6 +200,22 @@
}, "Failed to save member");
}
+ // One-off: moves outside image links onto this site
+ function localise() {
+ if (!confirm("Copy every member and system image onto this site? Links that 404 get removed.")) return;
+
+ void run(async () => {
+ const report = await authFetch<{
+ copied: string[];
+ removed: string[];
+ kept: string[];
+ }>("/plural/admin/media/localise", { method: "POST" }, "Moving images failed");
+ await reload();
+ localiseKept = report.kept;
+ return `Copied ${report.copied.length}, removed ${report.removed.length}, kept ${report.kept.length} as they were`;
+ }, "Moving images failed");
+ }
+
function remove() {
if (!chosen || !confirm(`Delete ${memberName(chosen)}? Their past switches stay in the history.`)) return;
@@ -244,6 +268,14 @@
{chosen ? "Uploads when you save. Replaces the current avatar and the proxy avatar" : "Uploads when you create the member"}. PNG, JPEG, GIF or WebP, up to 10 MB
</small>
</label>
+
+ <label class="field">
+ <span>Banner</span>
+ <input type="file" accept="image/png,image/jpeg,image/gif,image/webp" bind:files={bannerFile} />
+ <small class="muted">
+ {chosen ? "Uploads when you save. Replaces the current banner" : "Uploads when you create the member"}. Same formats, up to 10 MB
+ </small>
+ </label>
{/if}
<label class="field">
@@ -289,6 +321,24 @@
</section>
</div>
+ {#if auth.isOwner}
+ <section class="panel stack localise">
+ <h2>Move images to this site</h2>
+ <p class="muted small">Copies every avatar and banner that still lives elsewhere into this site's storage. Links that 404 are removed.</p>
+ <div class="buttons">
+ <button type="button" disabled={saving} onclick={localise}>Move images</button>
+ </div>
+ {#if localiseKept.length > 0}
+ <p class="small">Kept as they were, try again later:</p>
+ <ul class="small">
+ {#each localiseKept as line (line)}
+ <li>{line}</li>
+ {/each}
+ </ul>
+ {/if}
+ </section>
+ {/if}
+
{/if}
</div>
</Protected>
@@ -303,4 +353,8 @@
font-size: 1.05rem;
}
+ .localise {
+ margin-top: 1.25rem;
+ }
+
</style>