Dough Git

commit

Speed up proxying, add member details to the info DM, preview links

commit
4a6b8aa936cd04e1120446a36fd5ba3501a7a43f
author
Clove Twilight <[email protected]>
date
2026-11-16 15:01
- Download co-front avatars in parallel
- Run reply lookup and avatar merge together
- d!edit checks the message cache before fetching from Discord
- The info DM lists each member with pronouns, plus the system name
- Messages with links go out without Components v2 so Discord previews them

Co-Authored-By: Sandrone <[email protected]>

diff --git a/src/discord/editMessage.ts b/src/discord/editMessage.ts
index f7a5541..eeb3d96 100644
--- a/src/discord/editMessage.ts
+++ b/src/discord/editMessage.ts
@@ -2,6 +2,7 @@
 
 import {
     type APIMessageTopLevelComponent,
+    MessageFlags,
     MessageReferenceType,
     type Message,
 } from "discord.js";
@@ -20,6 +21,15 @@ async function findTarget(command: Message): Promise<Message | null> {
         return replied && isProxied(replied) ? replied : null;
     }
 
+    // The gateway already cached recent messages; only ask Discord when that misses
+    const cached = command.channel.messages.cache
+        .filter((message) =>
+            BigInt(message.id) < BigInt(command.id) && isProxied(message)
+        )
+        .sort((first, second) => (BigInt(second.id) > BigInt(first.id) ? 1 : -1))
+        .first();
+    if (cached) return cached;
+
     const recent = await command.channel.messages.fetch({
         limit: searchDepth,
         before: command.id,
@@ -47,6 +57,25 @@ export async function editProxied(
         ? channelWebhook
         : await client.fetchWebhook(target.webhookId);
 
+    const threadId = command.channel.isThread() ? command.channel.id : undefined;
+
+    // Link messages were sent classic; the flag can't be added or removed later
+    if (!target.flags.has(MessageFlags.IsComponentsV2)) {
+        if (text.length > 2000) {
+            return "Messages with links can only be 2000 characters long.";
+        }
+
+        await webhook.editMessage(target.id, {
+            content: text,
+            threadId,
+            allowedMentions: {
+                parse: ["users"],
+            },
+        });
+
+        return null;
+    }
+
     await webhook.editMessage(target.id, {
         components: replaceText(
             target.components.map((component) => component.toJSON()),
@@ -55,7 +84,7 @@ export async function editProxied(
         ) as APIMessageTopLevelComponent[],
         // Passing them back is what keeps them; leaving this out would drop them
         attachments: [...target.attachments.values()],
-        threadId: command.channel.isThread() ? command.channel.id : undefined,
+        threadId,
         allowedMentions: {
             parse: ["users"],
         },
diff --git a/src/discord/layout.ts b/src/discord/layout.ts
index 1bee628..4ca700a 100644
--- a/src/discord/layout.ts
+++ b/src/discord/layout.ts
@@ -40,16 +40,18 @@ async function replyButton(message: Message): Promise<ButtonBuilder | null> {
         .setURL(original.url);
 }
 
-// Components v2 only shows attachments that a component points at
+// Components v2 only shows attachments that a component points at.
+// Classic: the text goes in content and files show as plain attachments
 export async function buildLayout(
     message: Message,
     content: string,
+    classic: boolean,
 ): Promise<Layout> {
     const components: TopLevelComponent[] = [];
     const files: AttachmentPayload[] = [];
     const button = await replyButton(message);
 
-    if (content) {
+    if (content && !classic) {
         components.push(new TextDisplayBuilder().setContent(content));
     }
 
@@ -69,11 +71,14 @@ export async function buildLayout(
         const name = `${index}-${attachment.name.replace(/[^\w.-]/g, "_")}`;
         const type = attachment.contentType ?? "";
 
+        // Classic attachments carry the spoiler in the filename instead
         files.push({
             attachment: attachment.url,
-            name,
+            name: classic && attachment.spoiler ? `SPOILER_${name}` : name,
         });
 
+        if (classic) continue;
+
         if (type.startsWith("image/") || type.startsWith("video/")) {
             gallery.addItems(
                 new MediaGalleryItemBuilder()
diff --git a/src/discord/linkPreview.ts b/src/discord/linkPreview.ts
new file mode 100644
index 0000000..c8132df
--- /dev/null
+++ b/src/discord/linkPreview.ts
@@ -0,0 +1,12 @@
+/* src/discord/linkPreview.ts */
+
+// Normal webhook messages cap content at 2000; Text Display allows 4000
+const classicContentLimit = 2000;
+
+// <https://...> is Discord's own way to hide a preview, so it doesn't count
+const previewableLink = /(^|[^<])https?:\/\/\S/;
+
+// Components v2 messages never get link previews, so links go out as normal messages
+export function wantsLinkPreview(content: string): boolean {
+    return content.length <= classicContentLimit && previewableLink.test(content);
+}
diff --git a/src/discord/proxyMessage.ts b/src/discord/proxyMessage.ts
index b333ed9..8f7dd9d 100644
--- a/src/discord/proxyMessage.ts
+++ b/src/discord/proxyMessage.ts
@@ -10,6 +10,8 @@ import { settings } from "../state/settings.ts";
 import { system } from "../state/system.ts";
 import { avatarFor } from "./avatar.ts";
 import { buildLayout } from "./layout.ts";
+import { wantsLinkPreview } from "./linkPreview.ts";
+import { rememberSenders } from "./senders.ts";
 import { getWebhook } from "./webhooks.ts";
 
 export async function proxyMessage(message: Message): Promise<void> {
@@ -27,14 +29,21 @@ export async function proxyMessage(message: Message): Promise<void> {
     const webhook = await getWebhook(message);
     if (!webhook) return;
 
-    const layout = await buildLayout(message, match.content);
+    const classic = wantsLinkPreview(match.content);
 
-    await webhook.send({
-        flags: MessageFlags.IsComponentsV2,
+    // Reply lookup and avatar merge don't depend on each other
+    const [layout, avatarURL] = await Promise.all([
+        buildLayout(message, match.content, classic),
+        avatarFor(webhook, match.members),
+    ]);
+
+    const sent = await webhook.send({
+        flags: classic ? undefined : MessageFlags.IsComponentsV2,
+        content: classic ? match.content : undefined,
         components: layout.components,
         files: layout.files,
         username: webhookName(match.members, system.tag),
-        avatarURL: await avatarFor(webhook, match.members),
+        avatarURL,
         threadId: message.channel.isThread() ? message.channel.id : undefined,
         // shortcut: only user pings pass through, add role checks if you need @role or @everyone
         allowedMentions: {
@@ -42,6 +51,8 @@ export async function proxyMessage(message: Message): Promise<void> {
         },
     });
 
+    rememberSenders(sent.id, match.members);
+
     // Delete only after the proxied copy is sent, so nothing is lost
     await message.delete();
 }
diff --git a/src/discord/reactions.ts b/src/discord/reactions.ts
index 0b70e58..c0fd2f1 100644
--- a/src/discord/reactions.ts
+++ b/src/discord/reactions.ts
@@ -8,12 +8,34 @@ import type {
 } from "discord.js";
 
 import { ownerUserId } from "../config/env.ts";
+import type { Member } from "../proxy/types.ts";
 import { system } from "../state/system.ts";
 import { isProxied } from "./ownership.ts";
+import { sendersOf } from "./senders.ts";
 
 const deleteEmoji = "❌";
 const infoEmoji = "❓";
 
+function memberLine(member: Member): string {
+    const pronouns = member.pronouns ? ` (${member.pronouns})` : "";
+    return `**${member.display_name ?? member.name}**${pronouns}`;
+}
+
+// One line per member when known, else the webhook name it was sent under
+function senderInfo(
+    messageId: string,
+    username: string,
+    url: string,
+): string {
+    const members = sendersOf(messageId);
+    const lines = members ? members.map(memberLine) : [`**${username}**`];
+
+    if (system.name) lines.push(`System: **${system.name}**`);
+    lines.push(`Sent by <@${ownerUserId}>`, url);
+
+    return lines.join("\n");
+}
+
 export async function handleReaction(
     partialReaction: MessageReaction | PartialMessageReaction,
     partialUser: User | PartialUser,
@@ -38,12 +60,9 @@ export async function handleReaction(
         return;
     }
 
-    const systemLine = system.name ? ` of **${system.name}**` : "";
-
     // DMs can be closed; the info just doesn't arrive then
-    await user.send(
-        `**${message.author.username}**${systemLine}\nSent by <@${ownerUserId}>\n${message.url}`,
-    ).catch(() => {});
+    await user.send(senderInfo(message.id, message.author.username, message.url))
+        .catch(() => {});
 
     await reaction.users.remove(user.id).catch(() => {});
 }
diff --git a/src/discord/senders.ts b/src/discord/senders.ts
new file mode 100644
index 0000000..f9936db
--- /dev/null
+++ b/src/discord/senders.ts
@@ -0,0 +1,21 @@
+/* src/discord/senders.ts */
+
+import type { Member } from "../proxy/types.ts";
+
+// Keeps memory flat; older messages fall back to the webhook name
+const maxRemembered = 1000;
+
+// shortcut: in memory only, so ❓ on messages from before a restart shows just the name
+const senders = new Map<string, Member[]>();
+
+export function rememberSenders(messageId: string, members: Member[]): void {
+    senders.set(messageId, members);
+
+    if (senders.size > maxRemembered) {
+        senders.delete(senders.keys().next().value!);
+    }
+}
+
+export function sendersOf(messageId: string): Member[] | undefined {
+    return senders.get(messageId);
+}
diff --git a/src/images/merge.ts b/src/images/merge.ts
index a372d37..c6244bd 100644
--- a/src/images/merge.ts
+++ b/src/images/merge.ts
@@ -21,15 +21,19 @@ export async function mergeAvatars(members: Member[]): Promise<Uint8Array | null
     const stripWidth = Math.floor(size / urls.length);
     const canvas = new Image(size, size);
 
-    for (const [index, url] of urls.entries()) {
+    // Download all at once; the strips are still placed in front order
+    const images = await Promise.all(urls.map(async (url) => {
         const response = await fetch(url);
         if (!response.ok) throw new Error(`Avatar ${url}: HTTP ${response.status}`);
 
-        const decoded = await Image.decode(new Uint8Array(await response.arrayBuffer()));
+        return await Image.decode(new Uint8Array(await response.arrayBuffer()));
+    }));
+
+    for (const [index, decoded] of images.entries()) {
         if (!(decoded instanceof Image)) continue;
 
         // Last strip takes the rounding remainder so there's no gap on the right
-        const width = index === urls.length - 1
+        const width = index === images.length - 1
             ? size - stripWidth * index
             : stripWidth;
 
diff --git a/src/proxy/types.ts b/src/proxy/types.ts
index 42fa8e6..0b02737 100644
--- a/src/proxy/types.ts
+++ b/src/proxy/types.ts
@@ -9,6 +9,7 @@ export interface Member {
     id: string;
     name: string;
     display_name: string | null;
+    pronouns: string | null;
     avatar_url: string | null;
     webhook_avatar_url: string | null;
     proxy_tags: ProxyTag[];
diff --git a/tests/discord/linkPreview_test.ts b/tests/discord/linkPreview_test.ts
new file mode 100644
index 0000000..e242a95
--- /dev/null
+++ b/tests/discord/linkPreview_test.ts
@@ -0,0 +1,20 @@
+/* tests/discord/linkPreview_test.ts */
+
+import { assertEquals } from "@std/assert";
+import { wantsLinkPreview } from "../../src/discord/linkPreview.ts";
+
+Deno.test("plain link wants a preview", () => {
+    assertEquals(wantsLinkPreview("look https://example.com"), true);
+});
+
+Deno.test("text without a link doesn't", () => {
+    assertEquals(wantsLinkPreview("just words"), false);
+});
+
+Deno.test("angle-bracket link stays hidden", () => {
+    assertEquals(wantsLinkPreview("<https://example.com>"), false);
+});
+
+Deno.test("over 2000 chars stays components v2", () => {
+    assertEquals(wantsLinkPreview(`https://example.com ${"a".repeat(2000)}`), false);
+});
diff --git a/tests/fixtures.ts b/tests/fixtures.ts
index 1905981..eb6c17b 100644
--- a/tests/fixtures.ts
+++ b/tests/fixtures.ts
@@ -11,6 +11,7 @@ export function member(
         id,
         name: id,
         display_name: null,
+        pronouns: null,
         avatar_url: null,
         webhook_avatar_url: null,
         proxy_tags: [{ prefix, suffix }],