commit
Update how I proxy
diff --git a/Cargo.toml b/Cargo.toml
index e2a4646..0d27c21 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -14,7 +14,7 @@ tempfile = "3"
jpcl = "2.0.0"
percent-encoding = "2"
regex = "1"
-reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "rustls-tls"] }
+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
secrecy = "0.8"
diff --git a/build b/build
new file mode 100755
index 0000000..e18ca44
--- /dev/null
+++ b/build
@@ -0,0 +1,4 @@
+#!/bin/sh
+exec 2>&1
+
+cargo build --release
diff --git a/src/commands/edit/mod.rs b/src/commands/edit/mod.rs
index b5e7251..8dc6be4 100644
--- a/src/commands/edit/mod.rs
+++ b/src/commands/edit/mod.rs
@@ -5,9 +5,11 @@ use serde_json::json;
use serenity::all::{Context, Message};
use crate::{
- Bot, cards,
- discord::{Destination, NO_TARGET, Target, existing_media, user_mentions},
- proxy,
+ Bot,
+ discord::{
+ Destination, NO_TARGET, Target, existing_media, proxy_payload, proxy_text,
+ split_attachment_links, user_mentions,
+ },
};
impl Bot {
@@ -26,17 +28,31 @@ impl Bot {
return Ok(Some(NO_TARGET));
};
- if content.is_empty() && target.attachments.is_empty() {
+ let links = if classic {
+ split_attachment_links(&target.content).1.to_owned()
+ } else {
+ proxy_text(&components).1
+ };
+
+ if content.is_empty() && links.is_empty() && target.attachments.is_empty() {
return Ok(Some(
"That would leave the message empty. Use ❌ to delete it instead.",
));
}
- if classic && proxy::utf16_len(content) > 2000 {
- return Ok(Some(
- "Messages with links can only be 2000 characters long.",
- ));
- }
+ 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."));
+ }
+ json!({ "content": replacement["content"] })
+ } else {
+ let (components, attachments) = existing_media(&target, components, true);
+ let mut replacement = proxy_payload(content, &links, components, true);
+ replacement["attachments"] = json!(attachments);
+ replacement
+ };
+ payload["allowed_mentions"] = user_mentions();
let Some(dest) =
Destination::resolve(ctx, command.channel_id, command.guild_id.unwrap()).await?
@@ -50,21 +66,6 @@ impl Bot {
.as_ref()
.map(ExposeSecret::expose_secret)
.ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
- let mut payload = json!({ "allowed_mentions": user_mentions() });
-
- if classic {
- payload["content"] = json!(content);
- } else {
- let (mut components, attachments) = existing_media(&target, components, true);
-
- if !content.is_empty() {
- components.insert(0, cards::text(content));
- }
-
- payload["components"] = json!(components);
- payload["attachments"] = json!(attachments);
- }
-
ctx.http
.edit_webhook_message(id, dest.thread, token, target.id, &payload, Vec::new())
.await
diff --git a/src/commands/reproxy/mod.rs b/src/commands/reproxy/mod.rs
index 7b64ee1..af61c92 100644
--- a/src/commands/reproxy/mod.rs
+++ b/src/commands/reproxy/mod.rs
@@ -1,12 +1,13 @@
// src/commands/reproxy/mod.rs
-use serde_json::json;
use serenity::all::{Context, Message};
use crate::{
Bot,
- cards::COMPONENTS_V2,
- discord::{Destination, NO_TARGET, Target, existing_media},
+ discord::{
+ Destination, NO_TARGET, Target, attachment_links, proxy_payload, proxy_text,
+ split_attachment_links,
+ },
};
impl Bot {
@@ -42,35 +43,29 @@ impl Bot {
return Ok(Some("Can't use webhooks in this channel.".into()));
};
- let (components, _) = existing_media(&target, components, false);
- let attachments: Vec<_> = target
- .attachments
- .iter()
- .enumerate()
- .map(|(index, file)| json!({ "id": index, "filename": file.filename }))
- .collect();
- let mut payload = json!({ "attachments": attachments });
-
- if classic {
- payload["content"] = json!(target.content);
+ let (body, linked_uploads) = if classic {
+ let (body, links) = split_attachment_links(&target.content);
+ (body.to_owned(), links.to_owned())
} else {
- payload["flags"] = json!(COMPONENTS_V2);
- payload["components"] = json!(components);
- }
-
- let files = futures_util::future::try_join_all(
- target
- .attachments
- .iter()
- .map(|file| self.download(&file.url, file.filename.clone())),
- )
- .await?;
+ proxy_text(&components)
+ };
+ let uploaded_files = attachment_links(&target);
+ let links = [linked_uploads, uploaded_files]
+ .into_iter()
+ .filter(|links| !links.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n");
+ let buttons = components
+ .into_iter()
+ .filter(|component| component["type"] == 1)
+ .collect();
+ let payload = proxy_payload(&body, &links, buttons, false);
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
- .send_proxy(ctx, &dest, &webhook, &speakers, payload, files)
+ .send_proxy(ctx, &dest, &webhook, &speakers, payload)
.await?;
drop(locked);
self.remember(sent, speakers).await;
diff --git a/src/discord.rs b/src/discord.rs
index 69d0199..e58cd0e 100644
--- a/src/discord.rs
+++ b/src/discord.rs
@@ -1,10 +1,9 @@
// src/discord.rs
-use std::sync::{Arc, LazyLock};
+use std::sync::Arc;
use std::time::Instant;
use percent_encoding::percent_decode_str;
-use regex::Regex;
use secrecy::ExposeSecret;
use serde_json::{Value, json};
use serenity::all::*;
@@ -24,6 +23,26 @@ pub fn user_mentions() -> Value {
json!({ "parse": ["users"], "replied_user": false })
}
+pub async fn apply_name_style(ctx: &Context, guild_id: GuildId) {
+ let fields = json!({
+ "display_name_font_id": 16,
+ "display_name_effect_id": 7,
+ "display_name_colors": [
+ 0xD52D00,
+ 0xFF9A56,
+ 0xFFFFFF,
+ 0xD362A4,
+ 0xA30262,
+ ],
+ });
+ let request = Request::new(Route::GuildMemberMe { guild_id }, LightMethod::Patch)
+ .body(Some(fields.to_string().into_bytes()));
+
+ if let Err(error) = ctx.http.request(request).await {
+ eprintln!("Name styling failed in guild {guild_id}: {error}");
+ }
+}
+
pub fn owned(ctx: &Context, message: &Message) -> bool {
message.webhook_id.is_some()
&& ctx
@@ -32,12 +51,121 @@ pub fn owned(ctx: &Context, message: &Message) -> bool {
.is_some_and(|id| Some(id) == message.application_id)
}
-pub fn classic(content: &str) -> bool {
- static LINK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://\S").unwrap());
- proxy::utf16_len(content) <= 2000
- && LINK
- .find_iter(content)
- .any(|hit| !content[..hit.start()].ends_with('<'))
+pub(crate) fn attachment_links(message: &Message) -> String {
+ message
+ .attachments
+ .iter()
+ .map(|attachment| {
+ let url = reqwest::Url::parse(&attachment.url)
+ .ok()
+ .filter(|url| is_attachment_url(url))
+ .map(|mut url| {
+ url.set_query(None);
+ url.to_string()
+ })
+ .unwrap_or_else(|| attachment.url.clone());
+
+ if attachment.filename.starts_with("SPOILER_") {
+ format!("||{url}||")
+ } else {
+ url
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn is_attachment_url(url: &reqwest::Url) -> bool {
+ matches!(url.host_str(), Some("cdn.discordapp.com" | "media.discordapp.net"))
+ && url.path().starts_with("/attachments/")
+}
+
+pub(crate) fn split_attachment_links(content: &str) -> (&str, &str) {
+ let (body, tail) = content.rsplit_once("\n\n").unwrap_or(("", content));
+ if !tail.is_empty()
+ && tail.lines().all(|line| {
+ let url = line
+ .strip_prefix("||")
+ .and_then(|line| line.strip_suffix("||"))
+ .unwrap_or(line);
+ reqwest::Url::parse(url).is_ok_and(|parsed| {
+ !url.contains(char::is_whitespace)
+ && parsed.query().is_none()
+ && is_attachment_url(&parsed)
+ })
+ })
+ {
+ (body, tail)
+ } else {
+ (content, "")
+ }
+}
+
+pub(crate) fn proxy_payload(
+ body: &str,
+ links: &str,
+ 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}")
+ };
+
+ if !force_v2 && proxy::utf16_len(&content) <= 2000 {
+ return json!({
+ "content": content,
+ "components": buttons,
+ });
+ }
+
+ // 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 {
+ components.extend((!content.is_empty()).then(|| cards::text(&content)));
+ } else {
+ let mut remaining = body;
+ while !remaining.is_empty() {
+ let chunk = proxy::truncate(remaining, 4000);
+ components.push(cards::text(chunk));
+ remaining = &remaining[chunk.len()..];
+ }
+
+ let mut link_group = String::new();
+ for link in links.lines() {
+ if proxy::utf16_len(&link_group) + 1 + proxy::utf16_len(link) > 4000
+ && !link_group.is_empty()
+ {
+ components.push(cards::text(std::mem::take(&mut link_group)));
+ }
+ if !link_group.is_empty() {
+ link_group.push('\n');
+ }
+ link_group.push_str(link);
+ }
+ components.extend((!link_group.is_empty()).then(|| cards::text(link_group)));
+ }
+ components.append(&mut buttons);
+ json!({
+ "flags": COMPONENTS_V2,
+ "components": components,
+ })
+}
+
+pub(crate) fn proxy_text(components: &[Value]) -> (String, String) {
+ let mut body = Vec::new();
+ let mut links = Vec::new();
+ for content in components.iter().filter_map(|component| {
+ (component["type"] == 10)
+ .then(|| component["content"].as_str())
+ .flatten()
+ }) {
+ let (text, attachment_urls) = split_attachment_links(content);
+ body.extend((!text.is_empty()).then_some(text));
+ links.extend((!attachment_urls.is_empty()).then_some(attachment_urls));
+ }
+ (body.join(""), links.join("\n"))
}
fn is_thread(kind: ChannelType) -> bool {
@@ -272,12 +400,22 @@ impl Bot {
return Ok(());
};
- let (payload, files) = self.layout(ctx, message, &content).await?;
+ let buttons = reference(ctx, message)
+ .await
+ .map(|original| {
+ cards::link(
+ &format!("↪ {}", cards::display_name(&original)),
+ original.link(),
+ )
+ })
+ .into_iter()
+ .collect();
+ let payload = proxy_payload(&content, &attachment_links(message), buttons, false);
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
- .send_proxy(ctx, &dest, &webhook, &speakers, payload, files)
+ .send_proxy(ctx, &dest, &webhook, &speakers, payload)
.await?;
drop(locked);
self.remember(sent, speakers).await;
@@ -298,7 +436,6 @@ impl Bot {
webhook: &Webhook,
speakers: &[Member],
mut payload: Value,
- files: Vec<CreateAttachment>,
) -> anyhow::Result<(MessageId, u128)> {
let tag = self.system.read().await.info.tag.clone();
let speakers_ref = speakers.iter().collect::<Vec<_>>();
@@ -316,14 +453,17 @@ impl Bot {
.map(ExposeSecret::expose_secret)
.ok_or_else(|| anyhow::anyhow!("webhook had no token"))?;
let started = Instant::now();
- let sent = if files.is_empty() {
- let mut params = vec![("wait", "true".into()), ("with_components", "true".into())];
+ let mut params = vec![
+ ("wait", "true".into()),
+ ("with_components", "true".into()),
+ ];
- if let Some(thread) = dest.thread {
- params.push(("thread_id", thread.to_string()));
- }
+ if let Some(thread) = dest.thread {
+ params.push(("thread_id", thread.to_string()));
+ }
- ctx.http
+ let sent = ctx
+ .http
.fire::<Value>(
Request::new(
Route::WebhookWithToken {
@@ -335,187 +475,11 @@ impl Bot {
.body(Some(serde_json::to_vec(&payload)?))
.params(Some(params)),
)
- .await?
- } else {
- // Serenity's raw webhook helper leaves every upload ID at zero.
- // Build the multipart form with the same indices as the attachment metadata.
- self.upload_webhook(webhook.id, token, dest.thread, &payload, &files)
- .await?
- };
+ .await?;
Ok((
serde_json::from_value(sent["id"].clone())?,
started.elapsed().as_millis(),
- ))
- }
-
- async fn upload_webhook(
- &self,
- webhook: WebhookId,
- token: &str,
- thread: Option<ChannelId>,
- payload: &Value,
- files: &[CreateAttachment],
- ) -> anyhow::Result<Value> {
- let mut url = reqwest::Url::parse("https://discord.com/api/v10/webhooks/")?;
- url.path_segments_mut()
- .expect("Discord API URL has a path")
- .pop_if_empty()
- .push(&webhook.to_string())
- .push(token);
- url.query_pairs_mut()
- .append_pair("wait", "true")
- .append_pair("with_components", "true");
-
- if let Some(thread) = thread {
- url.query_pairs_mut()
- .append_pair("thread_id", &thread.to_string());
- }
-
- let payload_json = serde_json::to_string(payload)?;
-
- for attempt in 0..3 {
- let mut form =
- reqwest::multipart::Form::new().text("payload_json", payload_json.clone());
-
- for (index, file) in files.iter().enumerate() {
- let part = reqwest::multipart::Part::bytes(file.data.clone())
- .file_name(file.filename.clone());
- form = form.part(format!("files[{index}]"), part);
- }
-
- let response = self
- .web
- .post(url.clone())
- .multipart(form)
- .send()
- .await
- .map_err(reqwest::Error::without_url)?;
- let status = response.status();
-
- if status == reqwest::StatusCode::TOO_MANY_REQUESTS && attempt < 2 {
- let rate_limit = response
- .json::<Value>()
- .await
- .map_err(reqwest::Error::without_url)?;
-
- if let Some(seconds) = rate_limit["retry_after"].as_f64()
- && (0.0..=60.0).contains(&seconds)
- {
- tokio::time::sleep(std::time::Duration::from_secs_f64(seconds)).await;
- continue;
- }
- } else if status.is_success() {
- return response
- .json()
- .await
- .map_err(|error| error.without_url().into());
- }
-
- anyhow::bail!("Discord rejected webhook upload (HTTP {status})");
- }
-
- anyhow::bail!("Discord webhook upload exceeded the retry limit")
- }
-
- pub(crate) async fn download(
- &self,
- url: &str,
- filename: String,
- ) -> anyhow::Result<CreateAttachment> {
- let bytes = self
- .web
- .get(url)
- .send()
- .await?
- .error_for_status()?
- .bytes()
- .await?;
- Ok(CreateAttachment::bytes(bytes.to_vec(), filename))
- }
-
- async fn layout(
- &self,
- ctx: &Context,
- message: &Message,
- content: &str,
- ) -> anyhow::Result<(Value, Vec<CreateAttachment>)> {
- static BAD_FILENAME: LazyLock<Regex> =
- LazyLock::new(|| Regex::new(r"[^A-Za-z0-9_.-]").unwrap());
- let classic = classic(content);
- let mut components = Vec::new();
-
- if !classic && !content.is_empty() {
- components.push(cards::text(content));
- }
-
- if let Some(original) = reference(ctx, message).await {
- components.push(cards::link(
- &format!("↪ {}", cards::display_name(&original)),
- original.link(),
- ));
- }
-
- let mut gallery = Vec::new();
- let mut other = Vec::new();
- let mut downloads = Vec::new();
- let mut attachments = Vec::new();
-
- for (index, attachment) in message.attachments.iter().enumerate() {
- let name = format!(
- "{index}-{}",
- BAD_FILENAME.replace_all(&attachment.filename, "_")
- );
- let spoiler = attachment.filename.starts_with("SPOILER_");
- let filename = if classic && spoiler {
- format!("SPOILER_{name}")
- } else {
- name.clone()
- };
- attachments.push(json!({ "id": index, "filename": filename }));
- downloads.push(self.download(&attachment.url, filename));
-
- if classic {
- continue;
- }
-
- let url = format!("attachment://{name}");
- let kind = attachment.content_type.as_deref().unwrap_or_default();
-
- if kind.starts_with("image/") || kind.starts_with("video/") {
- gallery.push(json!({
- "media": { "url": url },
- "spoiler": spoiler,
- }));
- } else {
- other.push(json!({
- "type": 13,
- "file": { "url": url },
- "spoiler": spoiler,
- }));
- }
- }
-
- if !gallery.is_empty() {
- components.push(json!({ "type": 12, "items": gallery }));
- }
-
- components.extend(other);
-
- let mut payload = json!({
- "components": components,
- "attachments": attachments,
- });
-
- if classic {
- payload["content"] = json!(content);
- } else {
- payload["flags"] = json!(COMPONENTS_V2);
- }
-
- Ok((
- payload,
- futures_util::future::try_join_all(downloads).await?,
- ))
+ ))
}
pub(crate) async fn target(
diff --git a/src/main.rs b/src/main.rs
index a3f25bc..d9e6645 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -211,11 +211,16 @@ impl EventHandler for Handler {
if !self.0.started.swap(true, Ordering::Relaxed) {
tokio::spawn(self.0.clone().poll(ctx.clone()));
- tokio::spawn(self.0.clone().live(ctx));
+ tokio::spawn(self.0.clone().live(ctx.clone()));
+ tokio::spawn(async move {
+ for guild in ready.guilds {
+ discord::apply_name_style(&ctx, guild.id).await;
+ }
+ });
}
}
- async fn guild_create(&self, _ctx: Context, guild: Guild, _is_new: Option<bool>) {
+ async fn guild_create(&self, ctx: Context, guild: Guild, is_new: Option<bool>) {
if let Err(error) = self
.0
.update_settings(|settings| {
@@ -225,6 +230,10 @@ impl EventHandler for Handler {
{
eprintln!("Guild add failed: {error}");
}
+
+ if is_new == Some(true) {
+ discord::apply_name_style(&ctx, guild.id).await;
+ }
}
async fn guild_delete(&self, _ctx: Context, guild: UnavailableGuild, _full: Option<Guild>) {
diff --git a/src/tests.rs b/src/tests.rs
index c2d09cf..69525b0 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -123,14 +123,37 @@ fn command_args_fold_case_without_losing_edit_text() {
}
#[test]
-fn visible_short_links_use_classic_messages() {
- assert!(discord::classic("look https://example.com"));
- assert!(!discord::classic("just words"));
- assert!(!discord::classic("<https://example.com>"));
- assert!(!discord::classic(&format!(
- "https://example.com {}",
- "a".repeat(2000)
- )));
+fn proxies_use_native_content_and_keep_the_reply_button() {
+ let upload = "https://cdn.discordapp.com/attachments/1/2/SPOILER_cat.png";
+ let mut file = attachment("SPOILER_cat.png");
+ file["url"] = json!(format!("{upload}?ex=123&is=456&hm=789"));
+ let original = message("speaker", "hello", vec![file]);
+ let links = discord::attachment_links(&original);
+ let button = cards::link("Jump to reply", "https://discord.com/channels/1/2/3".into());
+ let payload = discord::proxy_payload(&original.content, &links, vec![button.clone()], false);
+
+ assert_eq!(links, format!("||{upload}||"));
+ assert_eq!(payload["content"], format!("hello\n\n{links}"));
+ assert_eq!(payload["components"], json!([button]));
+ assert!(payload["flags"].is_null());
+ assert!(payload["attachments"].is_null());
+ assert_eq!(
+ discord::split_attachment_links(payload["content"].as_str().unwrap()),
+ ("hello", links.as_str()),
+ );
+}
+
+#[test]
+fn long_proxies_round_trip_text_and_upload_links() {
+ let body = "a".repeat(4000);
+ let links = "https://cdn.discordapp.com/attachments/1/2/cat.png";
+ let payload = discord::proxy_payload(&body, links, Vec::new(), false);
+
+ assert_eq!(payload["flags"], json!(cards::COMPONENTS_V2));
+ assert_eq!(
+ discord::proxy_text(payload["components"].as_array().unwrap()),
+ (body, links.to_owned()),
+ );
}
#[test]