Dough Git

commit

Well it works

commit
d69030070d99c5c359b25e35eaae3d3eead2b832
author
Clove <[email protected]>
date
2026-11-23 13:14

diff --git a/src/cards.rs b/src/cards.rs
index 9d54785..c6d6b86 100644
--- a/src/cards.rs
+++ b/src/cards.rs
@@ -28,7 +28,7 @@ pub fn link(label: &str, url: String) -> Value {
     })
 }
 
-fn header(content: String, avatar: Option<&str>) -> Value {
+pub(crate) fn header(content: String, avatar: Option<&str>) -> Value {
     let Some(url) = avatar.filter(|url| !url.is_empty()) else {
         return text(content);
     };
diff --git a/src/commands/edit/mod.rs b/src/commands/edit/mod.rs
index a8ff8e8..249eb8c 100644
--- a/src/commands/edit/mod.rs
+++ b/src/commands/edit/mod.rs
@@ -10,6 +10,7 @@ use crate::{
         Destination, NO_TARGET, Target, existing_media, proxy_payload, proxy_text,
         split_attachment_links, user_mentions,
     },
+    proxy_log::ProxyLog,
 };
 
 impl Bot {
@@ -43,7 +44,9 @@ impl Bot {
         let mut payload = if classic {
             let replacement = proxy_payload(content, &links, Vec::new(), false);
             if replacement["content"].is_null() {
-                return Ok(Some("Message text and upload links exceed 2000 characters."));
+                return Ok(Some(
+                    "Message text and upload links exceed 2000 characters.",
+                ));
             }
             json!({ "content": replacement["content"] })
         } else {
@@ -55,8 +58,7 @@ impl Bot {
         payload["allowed_mentions"] = user_mentions();
 
         let guild = command.guild_id.unwrap();
-        let Some(dest) = Destination::resolve(ctx, command.channel_id, guild).await?
-        else {
+        let Some(dest) = Destination::resolve(ctx, command.channel_id, guild).await? else {
             return Ok(Some("Can't use webhooks in this channel."));
         };
         let id = target.webhook_id.unwrap();
@@ -71,7 +73,20 @@ impl Bot {
             .await
             .map_err(|_| anyhow::anyhow!("Discord rejected webhook edit"))?;
         let label = format!("Edited proxy by {}", target.author.name);
-        self.log_proxy(ctx, guild, &target, target.id, &label, content, &links).await;
+        let avatar = target.author.avatar_url();
+        self.log_proxy(
+            ctx,
+            guild,
+            ProxyLog {
+                source: &target,
+                sent: target.id,
+                label: &label,
+                content,
+                links: &links,
+                avatar: avatar.as_deref(),
+            },
+        )
+        .await;
         command.delete(&ctx.http).await?;
         Ok(None)
     }
diff --git a/src/commands/reproxy/mod.rs b/src/commands/reproxy/mod.rs
index 5b6e7fc..3aedadc 100644
--- a/src/commands/reproxy/mod.rs
+++ b/src/commands/reproxy/mod.rs
@@ -3,11 +3,13 @@
 use serenity::all::{Context, Message};
 
 use crate::{
-    Bot, proxy,
+    Bot,
     discord::{
         Destination, NO_TARGET, Target, attachment_links, proxy_payload, proxy_text,
         split_attachment_links,
     },
+    proxy,
+    proxy_log::ProxyLog,
 };
 
 impl Bot {
@@ -38,8 +40,7 @@ impl Bot {
             return Ok(Some(NO_TARGET.into()));
         };
         let guild = command.guild_id.unwrap();
-        let Some(dest) = Destination::resolve(ctx, command.channel_id, guild).await?
-        else {
+        let Some(dest) = Destination::resolve(ctx, command.channel_id, guild).await? else {
             return Ok(Some("Can't use webhooks in this channel.".into()));
         };
 
@@ -64,7 +65,7 @@ impl Bot {
         let slot = self.channel_webhook(&dest).await;
         let mut locked = slot.lock().await;
         let webhook = Self::ensure_webhook(ctx, &dest, &mut locked).await?;
-        let (sent, _) = self
+        let (sent, _, avatar) = self
             .send_proxy(ctx, &dest, &webhook, &speakers, payload)
             .await?;
         drop(locked);
@@ -79,7 +80,19 @@ impl Bot {
         let speaker_refs = speakers.iter().collect::<Vec<_>>();
         let label = format!("Reproxied as {}", proxy::webhook_name(&speaker_refs, None));
         self.remember(sent, speakers).await;
-        self.log_proxy(ctx, guild, &target, sent, &label, &body, &links).await;
+        self.log_proxy(
+            ctx,
+            guild,
+            ProxyLog {
+                source: &target,
+                sent,
+                label: &label,
+                content: &body,
+                links: &links,
+                avatar: avatar.as_deref(),
+            },
+        )
+        .await;
         command.delete(&ctx.http).await?;
         Ok(None)
     }
diff --git a/src/discord.rs b/src/discord.rs
index 37d85e9..8a9b30d 100644
--- a/src/discord.rs
+++ b/src/discord.rs
@@ -12,6 +12,7 @@ use tokio::sync::Mutex;
 
 use crate::{
     Bot,
+    proxy_log::ProxyLog,
     cards::{self, COMPONENTS_V2},
     proxy::{self, Member},
 };
@@ -107,11 +108,7 @@ pub(crate) fn proxy_payload(
     mut buttons: Vec<Value>,
     force_v2: bool,
 ) -> Value {
-    let content = if body.is_empty() || links.is_empty() {
-        format!("{body}{links}")
-    } else {
-        format!("{body}\n\n{links}")
-    };
+    let content = message_text(body, links);
 
     if !force_v2 && proxy::utf16_len(&content) <= 2000 {
         return json!({
@@ -120,6 +117,23 @@ pub(crate) fn proxy_payload(
         });
     }
 
+    let mut components = text_displays(body, links, &content);
+    components.append(&mut buttons);
+    json!({
+        "flags": COMPONENTS_V2,
+        "components": components,
+    })
+}
+
+pub(crate) fn message_text(body: &str, links: &str) -> String {
+    if body.is_empty() || links.is_empty() {
+        format!("{body}{links}")
+    } else {
+        format!("{body}\n\n{links}")
+    }
+}
+
+pub(crate) fn text_displays(body: &str, links: &str, content: &str) -> Vec<Value> {
     // Use separate text displays for the body and links if they exceed one display.
     let mut components = Vec::new();
     if proxy::utf16_len(&content) <= 4000 {
@@ -146,11 +160,7 @@ pub(crate) fn proxy_payload(
         }
         components.extend((!link_group.is_empty()).then(|| cards::text(link_group)));
     }
-    components.append(&mut buttons);
-    json!({
-        "flags": COMPONENTS_V2,
-        "components": components,
-    })
+    components
 }
 
 pub(crate) fn proxy_text(components: &[Value]) -> (String, String) {
@@ -415,7 +425,7 @@ impl Bot {
         let slot = self.channel_webhook(&dest).await;
         let mut locked = slot.lock().await;
         let webhook = Self::ensure_webhook(ctx, &dest, &mut locked).await?;
-        let (sent, send_ms) = self
+        let (sent, send_ms, avatar) = self
         .send_proxy(ctx, &dest, &webhook, &speakers, payload)
         .await?;
         drop(locked);
@@ -431,11 +441,23 @@ impl Bot {
         let speaker_refs = speakers.iter().collect::<Vec<_>>();
         let label = format!("Proxied as {}", proxy::webhook_name(&speaker_refs, None));
         self.remember(sent, speakers).await;
-        self.log_proxy(ctx, guild, message, sent, &label, &content, &links).await;
         println!(
             "Proxied in {}ms (send {send_ms}ms)",
             started.elapsed().as_millis()
         );
+        self.log_proxy(
+            ctx,
+            guild,
+            ProxyLog {
+                source: message,
+                sent,
+                label: &label,
+                content: &content,
+                links: &links,
+                avatar: avatar.as_deref(),
+            },
+        )
+        .await;
         Ok(())
     }
 
@@ -446,12 +468,13 @@ impl Bot {
         webhook: &Webhook,
         speakers: &[Member],
         mut payload: Value,
-    ) -> anyhow::Result<(MessageId, u128)> {
+    ) -> anyhow::Result<(MessageId, u128, Option<String>)> {
         let tag = self.system.read().await.info.tag.clone();
         let speakers_ref = speakers.iter().collect::<Vec<_>>();
         payload["username"] = json!(proxy::webhook_name(&speakers_ref, tag.as_deref()));
 
-        if let Some(url) = self.avatar(ctx, webhook, speakers).await {
+        let avatar = self.avatar(ctx, webhook, speakers).await;
+        if let Some(url) = &avatar {
             payload["avatar_url"] = json!(url);
         }
 
@@ -489,6 +512,7 @@ impl Bot {
         Ok((
             serde_json::from_value(sent["id"].clone())?,
             started.elapsed().as_millis(),
+            avatar,
         ))
     }
 
diff --git a/src/proxy_log.rs b/src/proxy_log.rs
index ad38b1b..db04182 100644
--- a/src/proxy_log.rs
+++ b/src/proxy_log.rs
@@ -5,8 +5,8 @@ use std::sync::LazyLock;
 use std::time::{Duration, Instant};
 
 use regex::Regex;
-use serde_json::json;
-use serenity::all::{Context, GuildId, HttpError, Message, MessageId};
+use serde_json::{Value, json};
+use serenity::all::{Context, GuildId, HttpError, Message, MessageId, UserId};
 use tokio::sync::watch;
 
 use crate::{Bot, cards, discord};
@@ -24,6 +24,48 @@ struct ProxyDeletion {
     confirmed: watch::Receiver<Option<bool>>,
 }
 
+pub(crate) struct ProxyLog<'a> {
+    pub source: &'a Message,
+    pub sent: MessageId,
+    pub label: &'a str,
+    pub content: &'a str,
+    pub links: &'a str,
+    pub avatar: Option<&'a str>,
+}
+
+impl ProxyLog<'_> {
+    fn payload(&self, guild: GuildId, account: UserId) -> Value {
+        let channel = self.source.channel_id;
+        let source = self.source.id;
+        let sent = self.sent;
+        let timestamp = sent.created_at().unix_timestamp();
+        let jump = cards::link(
+            "Jump to proxy",
+            format!("https://discord.com/channels/{guild}/{channel}/{sent}"),
+        );
+
+        let heading = format!("**{}**\n<#{channel}>", self.label);
+        let mut components = vec![cards::header(heading, self.avatar)];
+        let text = discord::message_text(self.content, self.links);
+        components.extend(discord::text_displays(self.content, self.links, &text));
+        components.push(cards::text(format!(
+            "-# Sender <@{account}> · Proxy ID {sent} · Source ID {source} · <t:{timestamp}:f>",
+        )));
+
+        json!({
+            "flags": cards::COMPONENTS_V2,
+            "components": [
+                jump,
+                {
+                    "type": 17,
+                    "components": components,
+                },
+            ],
+            "allowed_mentions": { "parse": [] },
+        })
+    }
+}
+
 impl Bot {
     pub(crate) async fn delete_proxy_source(
         &self,
@@ -107,16 +149,7 @@ impl Bot {
         Ok(())
     }
 
-    pub(crate) async fn log_proxy(
-        &self,
-        ctx: &Context,
-        guild: GuildId,
-        source: &Message,
-        sent: MessageId,
-        label: &str,
-        content: &str,
-        links: &str,
-    ) {
+    pub(crate) async fn log_proxy(&self, ctx: &Context, guild: GuildId, entry: ProxyLog<'_>) {
         let channel = self
             .settings
             .lock()
@@ -128,19 +161,7 @@ impl Bot {
             return;
         };
 
-        let source_channel = source.channel_id;
-        let account = self.owner;
-        let body = format!(
-            "**{label}**\nAccount <@{account}> · Channel <#{source_channel}>\nSource message ID: {}\n\n{content}",
-            source.id,
-        );
-        let jump = cards::link(
-            "Jump to message",
-            format!("https://discord.com/channels/{guild}/{source_channel}/{sent}"),
-        );
-        let mut payload = discord::proxy_payload(&body, links, vec![jump], false);
-        payload["allowed_mentions"] = json!({ "parse": [] });
-
+        let payload = entry.payload(guild, self.owner);
         if let Err(error) = discord::send_json(ctx, channel, &payload).await {
             eprintln!("Proxy logging failed in guild {guild}: {error}");
         }
@@ -242,6 +263,36 @@ fn deleted_message_id(message: &Message) -> Option<MessageId> {
 mod tests {
     use super::*;
 
+    #[test]
+    fn short_proxy_logs_use_a_v2_card_and_jump_to_the_replacement() {
+        let source = crate::tests::message("speaker", "", vec![]);
+        let avatar = "https://cdn.example/avatar.png";
+        let link = "https://cdn.example/upload.png";
+        let payload = ProxyLog {
+            source: &source,
+            sent: MessageId::new(4),
+            label: "Proxied as Speaker",
+            content: "Hello",
+            links: link,
+            avatar: Some(avatar),
+        }
+        .payload(GuildId::new(1), UserId::new(42));
+
+        assert_eq!(payload["flags"], cards::COMPONENTS_V2);
+        assert!(payload.get("content").is_none());
+        assert_eq!(payload["allowed_mentions"]["parse"], json!([]));
+        assert_eq!(
+            payload["components"][0]["components"][0]["url"],
+            "https://discord.com/channels/1/2/4",
+        );
+        let card = &payload["components"][1];
+        assert_eq!(card["type"], 17);
+        assert_eq!(card["components"][0]["accessory"]["media"]["url"], avatar);
+        assert_eq!(card["components"][1]["content"], format!("Hello\n\n{link}"));
+        let metadata = card["components"][2]["content"].as_str().unwrap();
+        assert!(metadata.contains("Sender <@42> · Proxy ID 4 · Source ID 3"));
+    }
+
     #[test]
     fn cleanup_matches_a_trusted_deletion_embed_and_uses_its_final_message_id() {
         let mut raw = serde_json::to_value(crate::tests::message("Carl-bot", "", vec![])).unwrap();