Dough Git

clove/allInOne

src/proxy_log.rs

back to src

// src/proxy_log.rs

use std::collections::VecDeque;
use std::sync::LazyLock;
use std::time::{Duration, Instant};

use regex::Regex;
use serde_json::{Value, json};
use serenity::all::{Context, GuildId, HttpError, Message, MessageId, UserId};
use tokio::sync::watch;

use crate::{Bot, cards, discord};

const CLEANUP_WINDOW: Duration = Duration::from_secs(30 * 60);
const MAX_RECENT_DELETIONS: usize = 4096;

#[derive(Default)]
pub(crate) struct RecentDeletions(VecDeque<ProxyDeletion>);

struct ProxyDeletion {
    guild: GuildId,
    source: MessageId,
    started: Instant,
    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![jump, 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": [{
                "type": 17,
                "components": components,
            }],
            "allowed_mentions": { "parse": [] },
        })
    }
}

impl Bot {
    pub(crate) async fn delete_proxy_source(
        &self,
        ctx: &Context,
        guild: GuildId,
        source: &Message,
    ) -> serenity::Result<Option<watch::Sender<Option<bool>>>> {
        let cleanup = self
        .settings
        .lock()
        .await
        .proxy_logs
        .get(&guild)
        .is_some_and(|config| config.cleanup);

        if !cleanup {
            source.delete(&ctx.http).await?;
            return Ok(None);
        }

        // A logger can receive the deletion before Discord returns the HTTP response.
        let (result, confirmed) = watch::channel(None);

        {
            let mut recent = self.proxy_deletions.lock().await;

            if recent.0.len() == MAX_RECENT_DELETIONS {
                recent.0.pop_front();
            }

            recent.0.push_back(ProxyDeletion {
                guild,
                source: source.id,
                started: Instant::now(),
                confirmed,
                });
        }

        if let Err(error) = source.delete(&ctx.http).await {
            result.send_replace(Some(false));
            return Err(error);
        }

        // Keep the logger entry until the webhook has accepted the replacement.
        Ok(Some(result))
    }

    pub(crate) async fn clean_proxy_log(
        &self,
        ctx: &Context,
        message: &Message,
        guild: GuildId,
    ) -> anyhow::Result<()> {
        let Some(deleted) = deleted_message_id(message) else {
            return Ok(());
        };
        let cleanup = self
        .settings
        .lock()
        .await
        .proxy_logs
        .get(&guild)
        .is_some_and(|config| config.cleanup);

        if !cleanup {
            return Ok(());
        }

        let confirmation = self
        .proxy_deletions
        .lock()
        .await
        .0
        .iter()
        .rev()
        .find(|entry| {
            entry.guild == guild
            && entry.source == deleted
            && entry.started.elapsed() < CLEANUP_WINDOW
            })
        .map(|entry| entry.confirmed.clone());

        if let Some(mut result) = confirmation
        && result
        .wait_for(Option::is_some)
        .await
        .is_ok_and(|confirmed| *confirmed == Some(true))
        {
            message.delete(&ctx.http).await?;
        }

        Ok(())
    }

    pub(crate) async fn log_proxy(&self, ctx: &Context, guild: GuildId, entry: ProxyLog<'_>) {
        let channel = self
        .settings
        .lock()
        .await
        .proxy_logs
        .get(&guild)
        .and_then(|config| config.channel);
        let Some(channel) = channel else {
            return;
        };

        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}");
        }
    }
}

pub(crate) fn unknown_message(error: &serenity::Error) -> bool {
    matches!(
        error,
        serenity::Error::Http(HttpError::UnsuccessfulRequest(response))
            if response.error.code == 10008
    )
}

fn deleted_message_id(message: &Message) -> Option<MessageId> {
    static MESSAGE_ID: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Message ID: ([0-9]{17,20})\b").unwrap());
    static LOGGER_ID: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Message = ([0-9]{17,20})\b").unwrap());
    static SAPPHIRE_ID: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\*\*Message ID:\*\* \[([0-9]{17,20})\]").unwrap());
    static AUTTAJA_ID: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^Message ([0-9]{17,20}) deleted\b").unwrap());

    // Webhook names and avatars can be set by anyone with the webhook token.
    let sender = if message.webhook_id.is_some() {
        message.application_id?.get()
    } else if message.author.bot {
        message.author.id.get()
    } else {
        return None;
    };
    let embed = message.embeds.first();

    let (pattern, text, use_last_match) = match sender {
        235148962103951360 => {
            let embed = embed?;

            if !embed.title.as_deref()?.starts_with("Message deleted in")
            || embed.timestamp.is_none()
            || embed.footer.is_none()
            {
                return None;
            }

            (&*MESSAGE_ID, embed.description.as_deref()?, true)
        }
        155149108183695360 | 161660517914509312 | 168274214858653696 | 470722245824610306
        | 470722416427925514 | 470722753218084866 | 470723667303727125 | 470724017205149701
        | 470723870270160917 | 347378323418251264 => {
            let embed = embed?;

            if !embed.description.as_deref()?.contains("Deleted in") {
                return None;
            }

            (&*MESSAGE_ID, embed.footer.as_ref()?.text.as_str(), false)
        }
        298822483060981760 | 579149474975449098 => {
            let embed = embed?;

            if !embed
            .description
            .as_deref()?
            .starts_with("Message deleted in")
            {
                return None;
            }

            let field = embed.fields.iter().find(|field| field.name == "ID")?;
            (&*LOGGER_ID, field.value.as_str(), false)
        }
        678344927997853742 => {
            let embed = embed?;

            if !embed.title.as_deref()?.starts_with("Message deleted") {
                return None;
            }

            (&*SAPPHIRE_ID, embed.description.as_deref()?, false)
        }
        563434444321587202 | 292953664492929025 | 356950275044671499 => {
            let embed = embed?;

            if !embed.author.as_ref()?.name.starts_with("Message Deleted") {
                return None;
            }

            (&*MESSAGE_ID, embed.footer.as_ref()?.text.as_str(), false)
        }
        242730576195354624 => {
            let text = embed
            .and_then(|embed| embed.description.as_deref())
            .unwrap_or(&message.content);
            (&*AUTTAJA_ID, text, false)
        }
        _ => return None,
    };

    let found = if use_last_match {
        pattern.captures_iter(text).last()
    } else {
        pattern.captures(text)
    }?;
    found[1].parse().ok()
}

#[cfg(test)]
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.gif";
        let link = "https://cdn.example/upload.gif";
        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"].as_array().unwrap().len(), 1);
        let card = &payload["components"][0];
        assert_eq!(card["type"], 17);
        let jump = &card["components"][0];
        assert_eq!(jump["type"], 1);
        assert_eq!(
            jump["components"][0]["url"],
            "https://discord.com/channels/1/2/4",
        );
        let header = &card["components"][1];
        assert_eq!(header["accessory"]["media"]["url"], avatar);
        assert_eq!(header["components"][0]["content"], "**Proxied as Speaker**\n<#2>");
        assert_eq!(card["components"][2]["content"], format!("Hello\n\n{link}"));
        let metadata = card["components"][3]["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();
        raw["webhook_id"] = json!("1234");
        raw["application_id"] = json!("235148962103951360");
        raw["embeds"] = json!([{
            "title": "Message deleted in #general",
            "description": "Quoted Message ID: 111111111111111111\nMessage ID: 222222222222222222",
            "timestamp": "2026-11-22T00:00:00Z",
            "footer": { "text": "Carl-bot" },
        }]);

        let deletion = serde_json::from_value(raw.clone()).unwrap();
        assert_eq!(
            deleted_message_id(&deletion),
            Some(MessageId::new(222222222222222222))
        );

        let mut spoof = raw.clone();
        spoof["application_id"] = json!("9999");
        assert_eq!(
            deleted_message_id(&serde_json::from_value(spoof).unwrap()),
            None
        );

        raw["embeds"][0]["title"] = json!("Message edited in #general");
        assert_eq!(
            deleted_message_id(&serde_json::from_value(raw).unwrap()),
            None
        );
    }
}