diff --git a/ROADMAP.md b/ROADMAP.md index 18afce9..58bbcdf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -116,6 +116,6 @@ Plan (backward compatible with the existing file): - `emojis.rs`: application emojis from `assets/emojis/dz_*.png` (SVG sources beside them), uploaded at startup if missing, swapped in for the plain emoji on every button through `ui::emoji_button` and `games::btn`. `assets/emojis` must be copied when deploying. - `commands/info_art.rs`: `userinfo` (banner, status, role chips in role colours), `serverinfo` (members and boost meters), `channelinfo` (a colour per channel type) and `roleinfo`. The mention and ID stay as text under each picture. `richest` and Who Knows use `cardart::chart`; `pager::start_drawn` pages through drawn pictures. - `commands/info_copy.rs`: the buttons under info cards open a private message with values in code blocks. Long lists (every role, channel, emoji, member, permission) go on pages instead of being cut short. Button ids carry what they need (`ii:::`), so they survive restarts. +- `commands/action_art.rs`: pictures for moderation results, AFK, snipe, stolen emojis, VirusTotal reports and download progress. Download progress is a picture every 5 s; `Live::freeze` stops those edits before the finished file goes up, because each edit replaces the message's files. Upload limit is 20 MiB by default since Discord's change on 2026-09-03 (`upload_limit`), more with boost levels 2 and 3. - `/queue` stays text: it's a private, self-deleting list of clickable links. A download's finished message is the video or file itself, so it gets no card. -- Download progress stays text: it updates too often to upload pictures, and uploads would compete with the download. - Security pass: powerful roles are refused in role menus and autoroles (`State::role_gives_power`), redirects are checked at every hop, HSTS, Game Boy page frameable only by Discord. Not done: rate limits, Forgejo on its own subdomain, narrower invite permissions, `cargo audit` (not installed). diff --git a/src/cardart.rs b/src/cardart.rs index 44470cb..a342ddd 100644 --- a/src/cardart.rs +++ b/src/cardart.rs @@ -338,3 +338,67 @@ pub fn chart(c: &Chart) -> Vec { } png(&img) } + +/// A ring `share` of the way round from the top, for scores. +pub fn ring(img: &mut RgbaImage, (cx, cy): (i32, i32), radius: f32, thickness: f32, share: f32, colour: [u8; 3]) { + let r = radius.ceil() as i32 + 1; + for y in -r..=r { + for x in -r..=r { + let d = ((x * x + y * y) as f32).sqrt(); + let cover = (radius + 0.5 - d).min(d - (radius - thickness) + 0.5).clamp(0.0, 1.0); + if cover <= 0.0 { + continue; + } + let turned = (x as f32).atan2(-y as f32).rem_euclid(std::f32::consts::TAU) / std::f32::consts::TAU; + let (ink, strength) = if turned < share { (colour, cover) } else { ([255, 255, 255], cover * 0.16) }; + let (px, py) = (cx + x, cy + y); + if px < 0 || py < 0 || px >= img.width() as i32 || py >= img.height() as i32 { + continue; + } + let p = img.get_pixel_mut(px as u32, py as u32); + for i in 0..3 { + p[i] = (p[i] as f32 * (1.0 - strength) + ink[i] as f32 * strength).round() as u8; + } + } + } +} + +/// Discord's markup as plain words, for text drawn into a picture. `look` turns a kind ('@', '&' or '#') and id into a name. +pub fn plain(text_: &str, look: impl Fn(char, u64) -> Option) -> String { + use regex::{Captures, Regex}; + static MARKUP: OnceLock = OnceLock::new(); + let re = MARKUP.get_or_init(|| Regex::new(r"<(@!?|@&|#)(\d+)>||").expect("the pattern is valid")); + re.replace_all(text_, |c: &Captures| { + if let Some(name) = c.get(3) { + return format!(":{}:", name.as_str()); + } + if let Some(t) = c.get(4) { + return t.as_str().parse().map_or_else(|_| c[0].to_string(), date); + } + let kind = match &c[1] { "@&" => '&', "#" => '#', _ => '@' }; + let id = c[2].parse().unwrap_or(0); + let prefix = if kind == '#' { "#" } else { "@" }; + format!("{prefix}{}", look(kind, id).unwrap_or_else(|| "unknown".to_string())) + }) + .into_owned() +} + +/// [`plain`] using the bot's cache for the names. +pub fn plain_in(state: &crate::state::State, text_: &str) -> String { + use twilight_model::id::Id; + plain(text_, |kind, id| { + let id: Id = Id::new_checked(id)?; + match kind { + '&' => state.cache.role(id.cast()).map(|r| r.name.clone()), + '#' => state.cache.channel(id.cast()).and_then(|c| c.name.clone()), + _ => state.cache.user(id.cast()).map(|u| u.global_name.clone().unwrap_or_else(|| u.name.clone())), + } + }) +} + +pub fn jpeg(img: &RgbaImage) -> Vec { + let mut out = std::io::Cursor::new(Vec::new()); + let rgb = image::DynamicImage::ImageRgba8(img.clone()).to_rgb8(); + let _ = rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 86)); + out.into_inner() +} diff --git a/src/cmd.rs b/src/cmd.rs index d6886ba..4f48df9 100644 --- a/src/cmd.rs +++ b/src/cmd.rs @@ -350,6 +350,17 @@ impl Ctx { self.send(card, true).await } + /// The same as [`Self::reply_file`], seen only by the person who asked (when it's a slash command). + pub async fn reply_private_file(&self, card: Component, name: &str, bytes: Vec) -> Result<()> { + use twilight_model::http::attachment::Attachment; + let Origin::Interaction { token, .. } = &self.origin else { return self.reply_file(card, name, bytes).await }; + self.defer_private().await?; // a no-op if we already answered + let files = [Attachment::from_bytes(name.to_string(), bytes, 1)]; + self.state.http.interaction(self.state.app_id()).create_followup(token).flags(MessageFlags::IS_COMPONENTS_V2 | MessageFlags::EPHEMERAL).components(&[card]) + .attachments(&files).allowed_mentions(Some(&AllowedMentions::default())).await.context("sending a private follow-up with a file")?; + Ok(()) + } + /// Send a card that refers to an uploaded file as `attachment://`. pub async fn reply_file(&self, card: Component, name: &str, bytes: Vec) -> Result<()> { use twilight_model::http::attachment::Attachment; diff --git a/src/commands/action_art.rs b/src/commands/action_art.rs new file mode 100644 index 0000000..806fb4e --- /dev/null +++ b/src/commands/action_art.rs @@ -0,0 +1,248 @@ +//! Pictures for the moments when something happens: moderation actions, AFK, snipe, stolen emojis and virus scans. +//! Their colour says what kind of thing happened. +use crate::cardart::{blit, canvas, chips, finish, line, line_centre, line_right, paragraph, ring, rounded_cover, tile_grid, tint, wash, gradient, PAD, WIDTH}; +use image::{Rgba, RgbaImage}; +use crate::pix; + +pub const FILE: &str = "card.png"; + +const INK: [u8; 3] = [250, 250, 248]; +const SOFT: [u8; 3] = [214, 214, 220]; +const W: i32 = WIDTH as i32; + +/// A round face, or a plain disc when there's no picture. +fn face(img: &mut RgbaImage, picture: Option<&RgbaImage>, x: i32, y: i32, size: i32) { + match picture { + Some(p) => blit(img, &rounded_cover(p, size as u32, size as f32 / 2.0), x, y, (0, 0, W, img.height() as i32)), + None => pix::rounded_rect(img, x, y, size, size, size / 2, Rgba([255, 255, 255, 40])), + } +} + +/// A heading beside a face. Gives back where it ends. +fn head(img: &mut RgbaImage, picture: Option<&RgbaImage>, title: &str, note: &str) -> i32 { + let size = 96; + face(img, picture, PAD, PAD, size); + let x = PAD + size + 20; + line(img, title, (x, PAD + 12), 30.0, true, INK, W - x - PAD); + line(img, note, (x, PAD + 54), 18.0, false, SOFT, W - x - PAD); + PAD + size +} + +fn labelled(img: &mut RgbaImage, label: &str, text: &str, top: i32, lines: usize) -> i32 { + line(img, label, (PAD, top), 15.0, false, SOFT, 400); + let width = W - 2 * PAD - 32; + let probe = paragraph(&mut img.clone(), text, (PAD + 16, top + 34), 18.0, INK, width, lines); + tint(img, (PAD, top + 24, W - 2 * PAD, probe - top - 24 + 10), 8, [255, 255, 255], 0.1); + paragraph(img, text, (PAD + 16, top + 34), 18.0, INK, width, lines) + 10 +} + +// ---- moderation ---------------------------------------------------------------------------------------------------- + +pub struct Moderation<'a> { + pub action: &'a str, + pub accent: u32, + pub name: &'a str, + pub id: u64, + pub avatar: Option, + pub moderator: &'a str, + pub reason: Option<&'a str>, + pub extra: Vec<(String, String)>, +} + +pub fn moderation(m: &Moderation) -> Vec { + let mut img = canvas(m.accent); + let bottom = head(&mut img, m.avatar.as_ref(), m.action, m.name); + let mut tiles = vec![("User ID".to_string(), m.id.to_string()), ("Moderator".to_string(), m.moderator.to_string())]; + tiles.extend(m.extra.iter().cloned()); + let bottom = tile_grid(&mut img, bottom + 16, 2, &tiles); + let bottom = labelled(&mut img, "Reason", m.reason.unwrap_or("No reason given"), bottom + 14, 4); + finish(&img, bottom) +} + +// ---- afk ----------------------------------------------------------------------------------------------------------- + +const NIGHT: u32 = 0x4A4AB8; + +pub fn away(name: &str, avatar: Option<&RgbaImage>, reason: &str, place: &str, since: &str) -> Vec { + let mut img = canvas(NIGHT); + let bottom = head(&mut img, avatar, &format!("{name} is away"), place); + let bottom = labelled(&mut img, "Reason", reason, bottom + 12, 3); + line(&mut img, since, (PAD, bottom + 10), 15.0, false, SOFT, W - 2 * PAD); + finish(&img, bottom + 28) +} + +pub fn welcome_back(name: &str, avatar: Option<&RgbaImage>, away_for: &str, pings: &[String]) -> Vec { + let mut img = canvas(0x2A9C6A); + let note = format!("Away for {away_for}"); + let mut bottom = head(&mut img, avatar, &format!("Welcome back, {name}"), ¬e); + if !pings.is_empty() { + line(&mut img, &format!("{} while you were away", if pings.len() == 1 { "1 ping".to_string() } else { format!("{} pings", pings.len()) }), (PAD, bottom + 16), 15.0, false, SOFT, W); + let items: Vec<_> = pings.iter().map(|p| (p.clone(), None)).collect(); + bottom = chips(&mut img, bottom + 42, &items); + } + finish(&img, bottom) +} + +// ---- snipe --------------------------------------------------------------------------------------------------------- + +pub fn deleted(name: &str, avatar: Option<&RgbaImage>, text: &str, when: &str) -> Vec { + let mut img = canvas(0xC8324A); + let bottom = head(&mut img, avatar, name, &format!("Deleted a message Β· {when}")); + let bottom = labelled(&mut img, "They said", text, bottom + 12, 10); + finish(&img, bottom) +} + +pub fn edited(name: &str, avatar: Option<&RgbaImage>, before: &str, after: &str, when: &str) -> Vec { + let mut img = canvas(0xC8901E); + let bottom = head(&mut img, avatar, name, &format!("Edited a message Β· {when}")); + let bottom = labelled(&mut img, "Before", before, bottom + 12, 6); + let bottom = labelled(&mut img, "After", after, bottom + 8, 6); + finish(&img, bottom) +} + +pub fn reaction(name: &str, avatar: Option<&RgbaImage>, emoji: &str, picture: Option<&RgbaImage>, when: &str) -> Vec { + let mut img = canvas(0x2C6EC8); + let bottom = head(&mut img, avatar, name, &format!("Removed a reaction Β· {when}")); + match picture { + Some(p) => blit(&mut img, &rounded_cover(p, 72, 8.0), PAD, bottom + 16, (0, 0, W, 1000)), + None => blit(&mut img, &crate::cardart::sprite(emoji, 72), PAD, bottom + 16, (0, 0, W, 1000)), + } + finish(&img, bottom + 88) +} + +// ---- stolen emojis ------------------------------------------------------------------------------------------------- + +/// Each emoji with its name and whether it was added. +pub fn stolen(items: &[(Option, String, bool)]) -> Vec { + let mut img = canvas(0x2A9C6A); + let added = items.iter().filter(|i| i.2).count(); + line(&mut img, &if added == 1 { "1 emoji added".to_string() } else { format!("{added} added") }, (PAD, 24), 30.0, true, INK, W); + line(&mut img, &if added == items.len() { "All ready to use in this server".to_string() } else { format!("{} couldn't be added", items.len() - added) }, (PAD, 66), 18.0, false, SOFT, W); + let (columns, gap) = (5, 8); + let size = (W - 2 * PAD - gap * (columns - 1)) / columns; + let height = size + 28; + for (n, (picture, name, ok)) in items.iter().enumerate() { + let (x, y) = (PAD + (n as i32 % columns) * (size + gap), 104 + (n as i32 / columns) * (height + gap)); + tint(&mut img, (x, y, size, height), 8, if *ok { [255, 255, 255] } else { [40, 0, 0] }, if *ok { 0.1 } else { 0.3 }); + if let Some(p) = picture { + let inner = size - 36; + let thumb = pix::thumbnail(p, inner as u32); + blit(&mut img, &thumb, x + (size - thumb.width() as i32) / 2, y + 12 + (inner - thumb.height() as i32) / 2, (0, 0, W, 1000)); + } + line(&mut img, name, (x + 10, y + size - 8), 14.0, false, if *ok { INK } else { [255, 170, 170] }, size - 20); + } + let rows = (items.len() as i32 + columns - 1) / columns; + finish(&img, 104 + rows * (height + gap) - gap) +} + +// ---- virus scan ---------------------------------------------------------------------------------------------------- + +pub struct Scan<'a> { + pub target: &'a str, + pub kind: &'a str, + pub verdict: &'a str, + pub accent: u32, + pub flagged: u64, + pub total: u64, + pub tiles: Vec<(String, String)>, + /// Engine and what it called it. + pub hits: Vec<(String, String)>, +} + +pub fn scan(s: &Scan) -> Vec { + let mut img = canvas(s.accent); + let (cx, cy, radius) = (W - PAD - 74, PAD + 74, 74.0); + let share = if s.flagged == 0 { 1.0 } else { s.flagged as f32 / s.total.max(1) as f32 }; + ring(&mut img, (cx, cy), radius, 12.0, share, INK); + line_centre(&mut img, &s.flagged.to_string(), (cx, cy - 34), 40.0, true, INK); + line_centre(&mut img, &format!("of {}", s.total), (cx, cy + 14), 16.0, false, SOFT); + let width = W - 2 * PAD - 190; + line(&mut img, s.kind, (PAD, PAD), 17.0, false, SOFT, width); + line(&mut img, s.verdict, (PAD, PAD + 24), 34.0, true, INK, width); + paragraph(&mut img, s.target, (PAD, PAD + 78), 16.0, SOFT, width, 3); + let mut bottom = tile_grid(&mut img, PAD + 168, 4, &s.tiles); + if !s.hits.is_empty() { + line(&mut img, "Flagged by", (PAD, bottom + 14), 15.0, false, SOFT, 300); + let mut y = bottom + 40; + for (engine, result) in s.hits.iter().take(12) { + tint(&mut img, (PAD, y, W - 2 * PAD, 30), 6, [0, 0, 0], 0.22); + line(&mut img, engine, (PAD + 12, y + 6), 15.0, true, INK, 240); + line_right(&mut img, &crate::ui::truncate(result, 44), (W - PAD - 12, y + 6), 15.0, false, INK); + y += 34; + } + bottom = y - 4; + } + finish(&img, bottom) +} + +// ---- downloads ----------------------------------------------------------------------------------------------------- + +pub struct Download<'a> { + pub phase: &'a str, + pub title: &'a str, + pub detail: &'a str, + pub thumbnail: Option<&'a RgbaImage>, + pub accent: u32, + pub percent: Option, + /// Figures along the bottom, like size, speed and time left. + pub figures: Vec, +} + +pub fn download(d: &Download) -> Vec { + let (top, bottom) = wash(d.accent); + let mut img = gradient(WIDTH, 216, top, bottom); + let (x, tw, th) = (PAD + 284 + 20, 284, 160); + match d.thumbnail { + Some(t) => { + let shot = pix::cover(t, tw as u32, th as u32); + image::imageops::overlay(&mut img, &shot, PAD as i64, PAD as i64); + } + None => tint(&mut img, (PAD, PAD, tw, th), 8, [255, 255, 255], 0.1), + } + let width = W - x - PAD; + line(&mut img, d.phase, (x, PAD), 16.0, false, SOFT, width - 80); + if let Some(p) = d.percent { + line_right(&mut img, &format!("{p:.0}%"), (W - PAD, PAD - 4), 26.0, true, INK); + } + paragraph(&mut img, if d.title.is_empty() { "Getting the details" } else { d.title }, (x, PAD + 30), 21.0, INK, width, 2); + crate::cardart::meter(&mut img, (x, PAD + 96, width, 10), d.percent.unwrap_or(0.0) as f32 / 100.0, [255, 255, 255]); + line(&mut img, &d.figures.join(" Β· "), (x, PAD + 116), 15.0, false, INK, width); + line(&mut img, d.detail, (x, PAD + 138), 14.0, false, SOFT, width); + crate::cardart::jpeg(&img) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dump(name: &str, bytes: &[u8]) { + if std::env::var("DEZIO_DUMP").is_ok() { + std::fs::write(std::env::temp_dir().join(format!("dezio_act_{name}")), bytes).unwrap(); + } + } + + #[test] + fn every_picture_draws() { + let art = RgbaImage::from_fn(300, 300, |x, y| Rgba([(x / 2) as u8 + 60, 90, (y / 2) as u8 + 80, 255])); + dump("ban.png", &moderation(&Moderation { action: "Member banned", accent: 0xC8324A, name: "spamcat", id: 123456789012345678, avatar: Some(art.clone()), moderator: "Mira", reason: Some("Posting scam links in every channel after a warning."), extra: vec![("Messages deleted".into(), "1 day".into()), ("DM".into(), "Sent".into())] })); + dump("away.png", &away("Mira", Some(&art), "Gone to get food, back in twenty minutes", "In this server", "Send any message to come back")); + dump("back.png", &welcome_back("Mira", Some(&art), "2 hours", &["Rowan: did you see this".into(), "spamcat: hey".into(), "nightowl: are you coming tonight".into()])); + dump("deleted.png", &deleted("Rowan", Some(&art), "I definitely did not say that, and you can't prove it", "5 minutes ago")); + dump("edited.png", &edited("Rowan", Some(&art), "see you at 8", "see you at 9, sorry", "2 minutes ago")); + dump("reaction.png", &reaction("Rowan", Some(&art), "πŸ˜‚", None, "just now")); + dump("stolen.png", &stolen(&[(Some(art.clone()), "partyblob".into(), true), (Some(art.clone()), "sadcat".into(), true), (None, "toolarge".into(), false)])); + let tiles: Vec<(String, String)> = [("Malicious", "4"), ("Suspicious", "1"), ("Harmless", "12"), ("Undetected", "54")].map(|(a, b)| (a.to_string(), b.to_string())).to_vec(); + dump("scan_bad.png", &scan(&Scan { target: "evil-setup-free-nitro.exe", kind: "File scan", verdict: "Dangerous", accent: 0xC8324A, flagged: 5, total: 71, tiles: tiles.clone(), hits: vec![("Kaspersky".into(), "Trojan.Win32.Generic".into()), ("BitDefender".into(), "Gen:Variant.Razy".into())] })); + dump("scan_ok.png", &scan(&Scan { target: "https://example.com/some/page", kind: "Link scan", verdict: "Looks clean", accent: 0x2A9C6A, flagged: 0, total: 71, tiles, hits: vec![] })); + let wide = RgbaImage::from_fn(640, 360, |x, y| Rgba([(x / 3) as u8, 60, (y / 2) as u8 + 60, 255])); + let bytes = download(&Download { phase: "Downloading", title: "A very long video title that keeps going so we can see how it wraps on two lines of the card", detail: "Keeping it under 20 MB", thumbnail: Some(&wide), accent: 0xB4502A, percent: Some(62.0), figures: vec!["11.8 MB of 19 MB".into(), "2.4 MB/s".into(), "3 s left".into()] }); + dump("download.jpg", &bytes); + assert!(bytes.len() < 120_000, "{}", bytes.len()); + } + + #[test] + fn markup_becomes_plain_words() { + let out = crate::cardart::plain("hi <@1> and <@&2> in <#3> :) <:blob:44> ", |k, id| Some(format!("{k}{id}"))); + assert_eq!(out, "hi @@1 and @&2 in ##3 :) :blob: 14 Jul 2017"); + } +} diff --git a/src/commands/games/cookie.rs b/src/commands/games/cookie.rs index 7001a3f..11f1191 100644 --- a/src/commands/games/cookie.rs +++ b/src/commands/games/cookie.rs @@ -517,20 +517,15 @@ impl Bakery { self.earn(gain); } - /// Buy up to `amount` of a building, one by one while you can afford it. Returns (bought, spent). + /// Buy `amount` of a building, all or nothing at the price shown in the menu. Returns (bought, spent). fn buy(&mut self, index: usize, amount: u64) -> (u64, f64) { - let (mut bought, mut spent) = (0, 0.0); - for _ in 0..amount { - let price = cost(index, self.owned[index]); - if self.cookies < price { - break; - } - self.cookies -= price; - self.owned[index] += 1; - bought += 1; - spent += price; + let price = bulk_cost(index, self.owned[index], amount); + if self.cookies < price { + return (0, 0.0); } - (bought, spent) + self.cookies -= price; + self.owned[index] += amount; + (amount, price) } fn sell(&mut self, index: usize, amount: u64) -> (u64, f64) { @@ -637,7 +632,7 @@ fn card(user: u64, name: &str, b: &Bakery, note: Option<&str>, art: bool) -> Com &format!("{} β€” {} πŸͺ", NAMES[i], short(price)), &i.to_string(), EMOJIS[i], - &format!("+{}/sec each Β· own {}{}", short(b.unit_cps(i) * b.multiplier()), b.owned[i], if b.cookies >= cost(i, b.owned[i]) { " Β· βœ… affordable" } else { "" }), + &format!("+{}/sec each Β· own {}{}", short(b.unit_cps(i) * b.multiplier()), b.owned[i], if b.cookies >= price { " Β· βœ… affordable" } else { "" }), false, ) } @@ -723,9 +718,10 @@ pub async fn on_component(state: &Arc, i: &Interaction) { } else { let (n, spent) = b.buy(index, b.amount); note = Some(if n == 0 { - let price = cost(index, b.owned[index]); + let price = bulk_cost(index, b.owned[index], b.amount); picture_changed = false; - format!("πŸ’Έ A {} costs {} β€” you need {} more.", NAMES[index], short(price), short(price - b.cookies)) + let what = if b.amount == 1 { format!("A {} costs", NAMES[index]) } else { format!("{} {} cost", b.amount, NAMES[index]) }; + format!("πŸ’Έ {what} {} β€” you need {} more.", short(price), short(price - b.cookies)) } else { format!("πŸ›’ Bought {n} {} for {} πŸͺ", NAMES[index], short(spent)) }); @@ -871,14 +867,17 @@ mod tests { } #[test] - fn buying_in_bulk_stops_when_you_run_out() { + fn buying_in_bulk_is_all_or_nothing_at_the_shown_price() { let mut b = bakery(); - b.cookies = 100.0; - let (n, spent) = b.buy(0, 10); - assert!(n >= 4 && n < 10 && spent <= 100.0); - assert_eq!(b.owned[0], n); + let ten = bulk_cost(0, 0, 10); + b.cookies = ten - 1.0; + assert_eq!(b.buy(0, 10), (0, 0.0), "one cookie short buys nothing"); + assert_eq!((b.owned[0], b.cookies), (0, ten - 1.0)); + b.cookies = ten; + assert_eq!(b.buy(0, 10), (10, ten)); + assert_eq!((b.owned[0], b.cookies), (10, 0.0)); let (sold, value) = b.sell(0, 100); - assert_eq!(sold, n); + assert_eq!(sold, 10); assert!(value > 0.0 && b.owned[0] == 0); } diff --git a/src/commands/lastfm/extras.rs b/src/commands/lastfm/extras.rs index b51a344..e8c8f92 100644 --- a/src/commands/lastfm/extras.rs +++ b/src/commands/lastfm/extras.rs @@ -721,8 +721,8 @@ pub async fn listen_button(state: &Arc, i: &Interaction) { return interact::private_text(state, i, "❌ Can't tell which song this card is about.").await; }; interact::defer_private(state, i).await; - let limit = i.guild_id.and_then(|g| state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).map_or(10, |t| match t { 2 => 50, 3 => 100, _ => 10 }) * 1024 * 1024; - let limit = limit.min(10 * 1024 * 1024); + let limit = i.guild_id.and_then(|g| state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).map_or(20, |t| match t { 2 => 50, 3 => 100, _ => 20 }) * 1024 * 1024; + let limit = limit.min(20 * 1024 * 1024); let song = match make_song(&artist, &title, limit).await { Ok(s) => s, Err(e) => return interact::followup_text(state, i, &format!("❌ {e}")).await, diff --git a/src/commands/media/download/flow.rs b/src/commands/media/download/flow.rs index 5888f8f..23f8e1e 100644 --- a/src/commands/media/download/flow.rs +++ b/src/commands/media/download/flow.rs @@ -106,6 +106,7 @@ async fn audio_flow(job: &Job, workdir: &Path, cookie: Option<&Path>) -> Result< let info = net_retry(job, || tools::probe(job, &job.url, cookie, false)).await?; let title = str_of(&info, "title").or_else(|| str_of(&info, "id")).unwrap_or("Audio").to_string(); job.set_title(&title); + job.with(|p| p.thumbnail = str_of(&info, "thumbnail").unwrap_or("").to_string()); if is_live(&info) { return Err(DlError::user("Live stream", "Live streams can't be downloaded.")); } @@ -143,6 +144,7 @@ async fn video_flow(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, let mut info = net_retry(job, || tools::probe(job, &job.url, cookie, true)).await?; let title = str_of(&info, "title").or_else(|| str_of(&info, "id")).unwrap_or("Video").to_string(); job.set_title(&title); + job.with(|p| p.thumbnail = str_of(&info, "thumbnail").unwrap_or("").to_string()); if is_live(&info) { return Err(DlError::user("Live stream", "Live streams can't be downloaded.")); } diff --git a/src/commands/media/download/job.rs b/src/commands/media/download/job.rs index 6c60fb9..61d91a2 100644 --- a/src/commands/media/download/job.rs +++ b/src/commands/media/download/job.rs @@ -37,6 +37,7 @@ pub struct Progress { pub emoji: String, pub detail: String, pub title: String, + pub thumbnail: String, pub percent: Option, pub downloaded: f64, pub total: f64, diff --git a/src/commands/media/download/mod.rs b/src/commands/media/download/mod.rs index 7941dc6..76a3b23 100644 --- a/src/commands/media/download/mod.rs +++ b/src/commands/media/download/mod.rs @@ -32,9 +32,10 @@ use twilight_model::channel::message::{AllowedMentions, Embed, EmojiReactionType use twilight_model::http::attachment::Attachment; use twilight_model::id::marker::{ChannelMarker, MessageMarker}; use twilight_model::id::Id; -use twilight_util::builder::embed::EmbedBuilder; +use twilight_util::builder::embed::{EmbedBuilder, ImageSource}; -const UI_TICK: Duration = Duration::from_secs(3); +const UI_TICK: Duration = Duration::from_secs(5); +const PROGRESS_PICTURE: &str = "download.jpg"; const UPLOAD_RETRIES: u32 = 3; const BLURPLE: u32 = 0x5865F2; @@ -151,6 +152,24 @@ fn progress_embed(job: &Job) -> Embed { b.build() } +/// The progress card as a picture: the video's thumbnail, the bar and the numbers. +fn progress_picture(job: &Job, thumbnail: Option<&image::RgbaImage>, accent: u32) -> Vec { + let j = job.snapshot(); + let mut figures = Vec::new(); + if j.total > 0.0 { + figures.push(format!("{} of {}", fmt_bytes(j.downloaded), fmt_bytes(j.total))); + } else if j.downloaded > 0.0 { + figures.push(fmt_bytes(j.downloaded)); + } + if let Some(s) = j.speed.filter(|s| *s > 0.0) { + figures.push(format!("{}/s", fmt_bytes(s))); + } + if let Some(e) = j.eta { + figures.push(format!("{} left", fmt_dur(Some(e as f64)))); + } + crate::commands::action_art::download(&crate::commands::action_art::Download { phase: &j.phase, title: &j.title, detail: &j.detail, thumbnail, accent, percent: j.percent, figures }) +} + fn button(custom_id: &str, label: &str, emoji: &str, style: ButtonStyle, disabled: bool) -> Button { Button { id: None, custom_id: Some(custom_id.into()), disabled, emoji: Some(EmojiReactionType::Unicode { name: emoji.into() }), label: Some(label.into()), style, url: None, sku_id: None } } @@ -177,6 +196,9 @@ struct Live { token: Option, channel: Id, message: Id, + /// Held while the progress picture is edited in. Every edit replaces the message's files, so once the finished + /// video is on its way no late progress edit may land: [`Live::freeze`] waits for any running one and stops the rest. + drawing: tokio::sync::Mutex, } impl Live { @@ -186,12 +208,12 @@ impl Live { match &ctx.origin { Origin::Message { channel_id } => { let m = state.http.create_message(*channel_id).embeds(std::slice::from_ref(embed)).components(components).allowed_mentions(Some(&no_pings)).await?.model().await?; - Ok(Self { state, token: None, channel: *channel_id, message: m.id }) + Ok(Self { state, token: None, channel: *channel_id, message: m.id, drawing: Default::default() }) } Origin::Interaction { token, .. } => { ctx.defer().await?; let m = state.http.interaction(state.app_id()).create_followup(token).embeds(std::slice::from_ref(embed)).components(components).allowed_mentions(Some(&no_pings)).await?.model().await?; - Ok(Self { state, token: Some(token.clone()), channel: ctx.channel_id, message: m.id }) + Ok(Self { state, token: Some(token.clone()), channel: ctx.channel_id, message: m.id, drawing: Default::default() }) } } } @@ -201,7 +223,7 @@ impl Live { let no_pings = AllowedMentions::default(); if let Some(token) = &self.token { let client = self.state.http.interaction(self.state.app_id()); - let mut req = client.update_followup(token, self.message).embeds(Some(embeds)).components(Some(components)).allowed_mentions(Some(&no_pings)); + let mut req = client.update_followup(token, self.message).keep_attachment_ids(&[]).embeds(Some(embeds)).components(Some(components)).allowed_mentions(Some(&no_pings)); if let Some(c) = content { req = req.content(Some(c)); } @@ -210,7 +232,7 @@ impl Live { } req.await.map(|_| ()) } else { - let mut req = self.state.http.update_message(self.channel, self.message).embeds(Some(embeds)).components(Some(components)).allowed_mentions(Some(&no_pings)); + let mut req = self.state.http.update_message(self.channel, self.message).keep_attachment_ids(&[]).embeds(Some(embeds)).components(Some(components)).allowed_mentions(Some(&no_pings)); if let Some(c) = content { req = req.content(Some(c)); } @@ -221,6 +243,11 @@ impl Live { } } + /// No more progress pictures from here on. + async fn freeze(&self) { + *self.drawing.lock().await = true; + } + /// A new message in the same place (extra groups of a gallery, or after the interaction token expired). async fn send(&self, content: Option<&str>, components: &[Component], files: &[Attachment], via_channel: bool) -> Result, twilight_http::Error> { let no_pings = AllowedMentions::default(); @@ -352,13 +379,27 @@ async fn download(ctx: Arc) -> Result<()> { let (job, live) = (job.clone(), live.clone()); tokio::spawn(async move { let mut last = String::new(); + let mut art: (Option, u32) = (None, BLURPLE); + let mut asked = String::new(); loop { tokio::time::sleep(UI_TICK).await; let sig = job.signature(); if sig == last { continue; } - if live.edit(None, &[progress_embed(&job)], &cancel_row(job.owner, job.is_cancelled()), &[]).await.is_ok() { + let thumbnail = job.snapshot().thumbnail; + if !thumbnail.is_empty() && thumbnail != asked { + asked.clone_from(&thumbnail); + art = (super::fetch_picture(&live.state, &thumbnail).await, crate::colors::accent(&live.state, Some(&thumbnail), BLURPLE).await); + } + let bytes = progress_picture(&job, art.0.as_ref(), art.1); + let frozen = live.drawing.lock().await; + if *frozen { + return; + } + let embed = EmbedBuilder::new().color(art.1).image(ImageSource::attachment(PROGRESS_PICTURE).expect("a valid file name")).build(); + let files = [Attachment::from_bytes(PROGRESS_PICTURE.to_string(), bytes, 1)]; + if live.edit(None, &[embed], &cancel_row(job.owner, job.is_cancelled()), &files).await.is_ok() { last = sig; } } @@ -414,6 +455,7 @@ async fn run_job(ctx: &Arc, job: &Arc, live: &Arc, cap: i64, wor } async fn deliver(job: &Job, live: &Live, outcome: Outcome) -> Result<(), DlError> { + live.freeze().await; let owner = job.owner; match outcome { Outcome::Audio(a) => { diff --git a/src/commands/media/download/plan.rs b/src/commands/media/download/plan.rs index f22cc2d..6a683a4 100644 --- a/src/commands/media/download/plan.rs +++ b/src/commands/media/download/plan.rs @@ -11,7 +11,7 @@ pub const MAX_DURATION_SECONDS: f64 = 30.0 * 60.0; pub const DEFAULT_QUALITY_CAP: i64 = 1080; pub const AUDIO_EXT: &str = "opus"; pub const AUDIO_KBPS: i64 = 96; -pub const FALLBACK_UPLOAD_LIMIT: u64 = 10 * 1024 * 1024; +pub const FALLBACK_UPLOAD_LIMIT: u64 = 20 * 1024 * 1024; pub const SAFETY_MARGIN: f64 = 0.95; pub const FINAL_MARGIN: f64 = 0.99; pub const BPP_MIN: f64 = 0.065; diff --git a/src/commands/media/emoji.rs b/src/commands/media/emoji.rs index b5438f8..0b8ad8c 100644 --- a/src/commands/media/emoji.rs +++ b/src/commands/media/emoji.rs @@ -128,10 +128,16 @@ async fn steal(ctx: Arc) -> Result<()> { ctx.defer().await?; let by = format!("{} ({})", ctx.user_name, ctx.user_id); let mut results = Vec::new(); + let mut shown = Vec::new(); for a in assets.iter().take(20) { - results.push(add_asset(&ctx.state, guild, a, &by, name.as_deref()).await); + let result = add_asset(&ctx.state, guild, a, &by, name.as_deref()).await; + shown.push((super::fetch_picture(&ctx.state, &a.url).await, name.clone().unwrap_or_else(|| a.name.clone()), result.starts_with("βœ…"))); + results.push(result); } - ctx.reply(Card::new(Some(GREEN)).text(&results.join("\n")).build()).await + let picture = super::super::action_art::stolen(&shown); + let accent = if shown.iter().all(|s| s.2) { GREEN } else { 0xF39C12 }; + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", super::super::action_art::FILE)]).text(&results.join("\n")).build(); + ctx.reply_file(card, super::super::action_art::FILE, picture).await } // ---- combine ---------------------------------------------------------------------------------------- diff --git a/src/commands/media/mod.rs b/src/commands/media/mod.rs index 04a58a6..1fb129e 100644 --- a/src/commands/media/mod.rs +++ b/src/commands/media/mod.rs @@ -111,13 +111,13 @@ pub fn emoji_url(id: u64, animated: bool, size: u32) -> String { format!("https://cdn.discordapp.com/emojis/{id}.{}?size={size}", if animated { "gif" } else { "png" }) } -/// Upload limit for files in this server (10 MB unless boosted). +/// Upload limit for files in this server: Discord's default is 20 MiB since September 2026, more with boosts. pub fn upload_limit(ctx: &Ctx) -> usize { let tier = ctx.guild_id.and_then(|g| ctx.state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).unwrap_or(0); let mb: usize = match tier { 2 => 50, 3 => 100, - _ => 10, + _ => 20, }; mb * 1024 * 1024 } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 1957bbc..f096a4a 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -12,6 +12,7 @@ pub mod fun; pub mod gameboy; pub mod games; pub mod info; +mod action_art; mod info_art; pub mod info_copy; pub mod lastfm; diff --git a/src/commands/moderation.rs b/src/commands/moderation.rs index 96bc30d..3637c63 100644 --- a/src/commands/moderation.rs +++ b/src/commands/moderation.rs @@ -3,6 +3,7 @@ //! Each exists as `/name` and `D!name`. Prefix versions also accept a reply (reply to someone's //! message with `D!ban spam`). Actions are recorded in the audit log as " (): " //! so the logger credits the real moderator, and members get a DM telling them what happened. +use super::action_art as art; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::converters::{fmt_duration, looks_like_duration, parse_duration, parse_id}; use crate::error::UserError; @@ -113,17 +114,14 @@ fn now() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64) } -fn mod_card(ctx: &Ctx, action: &str, emoji: &str, accent: u32, target: &Who, reason: Option<&str>, extra: &[(&str, String)]) -> twilight_model::channel::message::Component { - let mut lines = vec![ - format!("**User:** <@{}> (`{}` Β· `{}`)", target.id, ui::escape(&target.name), target.id), - format!("**Moderator:** <@{}>", ctx.user_id), - format!("**Reason:** {}", reason.map_or("*No reason given*".to_string(), ui::escape)), - ]; - lines.extend(extra.iter().map(|(k, v)| format!("**{k}:** {v}"))); - Card::new(Some(accent)) - .header(&[&format!("### {emoji} {action}"), &lines.join("\n")], Some(&target.avatar)) - .footer(&ui::timestamp(now(), 'f')) - .build() +/// The result of a moderation action: a picture of what happened, with the mentions still clickable underneath. +async fn send_card(ctx: &Ctx, action: &str, accent: u32, target: &Who, reason: Option<&str>, extra: &[(&str, String)]) -> Result<()> { + let avatar = super::media::fetch_picture(&ctx.state, &target.avatar).await; + let plain_extra = extra.iter().map(|(k, v)| (k.to_string(), crate::cardart::plain_in(&ctx.state, v).replace('`', "").replace('*', ""))).collect(); + let moderator = super::info::display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await; + let picture = art::moderation(&art::Moderation { action, accent, name: &target.name, id: target.id.get(), avatar, moderator: &moderator, reason, extra: plain_extra }); + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@{}> Β· by <@{}> Β· {}", target.id, ctx.user_id, ui::timestamp(now(), 'f'))).build(); + ctx.reply_file(card, art::FILE, picture).await } /// Best-effort DM so people know why; returns whether it arrived. @@ -165,7 +163,7 @@ async fn kick(ctx: Arc) -> Result<()> { let dm = notify(&ctx, target, "kicked", reason).await; ctx.state.http.remove_guild_member(guild, target).reason(&audit_reason(&ctx, reason)).await?; let w = who(&ctx, target).await?; - ctx.reply(mod_card(&ctx, "Member kicked", "πŸ‘’", GOLD, &w, reason, &[("DM", dm_word(dm))])).await + send_card(&ctx, "Member kicked", GOLD, &w, reason, &[("DM", dm_word(dm))]).await } async fn ban(ctx: Arc) -> Result<()> { @@ -199,7 +197,7 @@ async fn ban(ctx: Arc) -> Result<()> { if is_member { extra.push(("DM", dm_word(dm))); } - ctx.reply(mod_card(&ctx, "Member banned", "πŸ”¨", RED, &w, reason, &extra)).await + send_card(&ctx, "Member banned", RED, &w, reason, &extra).await } async fn unban(ctx: Arc) -> Result<()> { @@ -217,7 +215,7 @@ async fn unban(ctx: Arc) -> Result<()> { let reason = reason(&ctx); ctx.state.http.delete_ban(guild, ban.user.id).reason(&audit_reason(&ctx, reason)).await?; let w = Who { id: ban.user.id, name: ban.user.name.clone(), avatar: ui::avatar_url(ban.user.id, ban.user.avatar.as_ref()) }; - ctx.reply(mod_card(&ctx, "Member unbanned", "πŸ•ŠοΈ", GREEN, &w, reason, &[])).await + send_card(&ctx, "Member unbanned", GREEN, &w, reason, &[]).await } type Words = (Option, Option, Option); @@ -267,11 +265,11 @@ async fn timeout(ctx: Arc) -> Result<()> { .await?; let dm = notify(ctx, target, &format!("timed out for {}", fmt_duration(seconds)), reason).await; let w = who(ctx, target).await?; - ctx.reply(mod_card(ctx, "Member timed out", "⏱️", GOLD, &w, reason, &[ + send_card(ctx, "Member timed out", GOLD, &w, reason, &[ ("Duration", fmt_duration(seconds)), ("Ends", ui::timestamp(until, 'R')), ("DM", dm_word(dm)), - ])).await + ]).await } async fn untimeout(ctx: Arc) -> Result<()> { @@ -291,7 +289,7 @@ async fn untimeout(ctx: Arc) -> Result<()> { let reason = reason(&ctx); ctx.state.http.update_guild_member(guild, target).communication_disabled_until(None).reason(&audit_reason(&ctx, reason)).await?; let w = who(&ctx, target).await?; - ctx.reply(mod_card(&ctx, "Timeout removed", "βœ…", GREEN, &w, reason, &[])).await + send_card(&ctx, "Timeout removed", GREEN, &w, reason, &[]).await } async fn nick(ctx: Arc) -> Result<()> { @@ -310,7 +308,7 @@ async fn nick(ctx: Arc) -> Result<()> { let w = who(&ctx, target).await?; let show = |n: &Option| n.as_ref().map_or("*none*".to_string(), |n| format!("`{}`", ui::escape(n))); let title = if new.is_some() { "Nickname changed" } else { "Nickname reset" }; - ctx.reply(mod_card(&ctx, title, "✏️", BLURPLE, &w, reason, &[("Before", show(&old)), ("After", show(&new))])).await + send_card(&ctx, title, BLURPLE, &w, reason, &[("Before", show(&old)), ("After", show(&new))]).await } /// A role by `<@&id>`, id or (case-insensitive) name. @@ -371,8 +369,7 @@ async fn role(ctx: Arc) -> Result<()> { } let w = who(&ctx, target).await?; let accent = if color != 0 { color } else { BLURPLE }; - ctx.reply(mod_card(&ctx, if add { "Role added" } else { "Role removed" }, "πŸ”°", accent, &w, reason, - &[("Role", format!("<@&{role_id}>"))])).await + send_card(&ctx, if add { "Role added" } else { "Role removed" }, accent, &w, reason, &[("Role", format!("<@&{role_id}>"))]).await } async fn slowmode(ctx: Arc) -> Result<()> { diff --git a/src/commands/other.rs b/src/commands/other.rs index a14172a..9050b14 100644 --- a/src/commands/other.rs +++ b/src/commands/other.rs @@ -6,6 +6,7 @@ //! * `mpreg` β€” reply to a message to cover it in πŸ«ƒ. //! //! State: data/afk.json β€” {":": {"reason", "since", "pings": [...]}}. +use super::action_art as art; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::commands::moderation::audit_reason; @@ -119,7 +120,12 @@ async fn afk_cmd(ctx: Arc) -> Result<()> { let guild = if global { None } else { ctx.guild_id }; afk().set(ctx.user_id.get(), guild, &reason); let where_ = if guild.is_none() { "everywhere" } else { "in this server" }; - ctx.reply(Card::new(Some(0x95A5A6)).text(&format!("πŸ’€ <@{}> is now AFK {where_}: {}\n-# Send any message to come back.", ctx.user_id, escape(&reason))).build()).await + let avatar_url = crate::commands::media::avatar(&ctx.state, ctx.user_id, 128).await; + let avatar = crate::commands::media::fetch_picture(&ctx.state, &avatar_url).await; + let name = crate::commands::info::display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await; + let picture = art::away(&name, avatar.as_ref(), &reason, &format!("Away {where_}"), "Send any message to come back"); + let card = Card::new(Some(0x4A4AB8)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@{}> Β· since {}", ctx.user_id, crate::ui::timestamp(unix(), 'R'))).build(); + ctx.reply_file(card, art::FILE, picture).await } fn jump(m: &Message) -> String { @@ -180,16 +186,22 @@ async fn welcome_back(state: &Arc, m: &Message, guild: Option = removed.iter().flat_map(|e| e["pings"].as_array().cloned().unwrap_or_default()).collect(); pings.sort_by_key(|p| p["at"].as_i64().unwrap_or(0)); - let mut lines = vec![format!("πŸ‘‹ Welcome back <@{}>! You were away for **{}**.", m.author.id, fmt_duration((unix() - since).max(0) as u64))]; - if !pings.is_empty() { - lines.push(format!("You were pinged **{}** time{}:", pings.len(), if pings.len() != 1 { "s" } else { "" })); - for p in pings.iter().rev().take(8).rev() { - let text = p["text"].as_str().filter(|t| !t.is_empty()).unwrap_or("message"); - lines.push(format!("-# <@{}> β€” [{}]({})", p["by"].as_u64().unwrap_or(0), p["at"].as_i64().unwrap_or(0), escape(text), p["url"].as_str().unwrap_or(""))); - } + let away_for = fmt_duration((unix() - since).max(0) as u64); + let mut lines = vec![format!("-# <@{}>", m.author.id)]; + let mut chips = vec![]; + for p in pings.iter().rev().take(8).rev() { + let text = p["text"].as_str().filter(|t| !t.is_empty()).unwrap_or("message"); + lines.push(format!("-# <@{}> β€” [{}]({})", p["by"].as_u64().unwrap_or(0), p["at"].as_i64().unwrap_or(0), escape(text), p["url"].as_str().unwrap_or(""))); + let by = p["by"].as_u64().and_then(Id::new_checked).and_then(|u: Id| state.cache.user(u).map(|x| x.global_name.clone().unwrap_or_else(|| x.name.clone()))).unwrap_or_else(|| "Someone".to_string()); + chips.push(format!("{by}: {}", crate::cardart::plain_in(state, text))); } - let card = Card::new(Some(GREEN)).text(&lines.join("\n")).build(); - let sent = state.http.create_message(m.channel_id).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]) + let avatar_url = crate::commands::media::avatar(state, m.author.id, 128).await; + let avatar = crate::commands::media::fetch_picture(state, &avatar_url).await; + let name = crate::commands::info::display_name_of(state, guild, m.author.id).await; + let picture = art::welcome_back(&name, avatar.as_ref(), &away_for, &chips); + let card = Card::new(Some(GREEN)).gallery(&[&format!("attachment://{}", art::FILE)]).text(&lines.join("\n")).build(); + let files = [twilight_model::http::attachment::Attachment::from_bytes(art::FILE.to_string(), picture, 1)]; + let sent = state.http.create_message(m.channel_id).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).attachments(&files) .allowed_mentions(Some(&AllowedMentions::default())).await; if let Ok(sent) = sent { if let Ok(sent) = sent.model().await { diff --git a/src/commands/snipe.rs b/src/commands/snipe.rs index 81570d8..43ffab8 100644 --- a/src/commands/snipe.rs +++ b/src/commands/snipe.rs @@ -4,6 +4,7 @@ //! of each kind per channel are kept in memory and saved to data/snipes.json in batches, so they //! survive restarts without a disk write per message. People can opt out of being sniped (the //! dashboard or `D!snipe optout`), and servers can turn it off. +use super::action_art as art; use super::logs::events::Pre; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::interact; @@ -114,43 +115,66 @@ fn kind_info(kind: &str) -> (&'static str, &'static str) { } fn render(kind: &str, e: &Value, index: usize, total: usize, guild: Option>, channel: Id) -> Card { - let (emoji, label) = kind_info(kind); let guild = guild.map_or("@me".to_string(), |g| g.to_string()); let when = format!("", entry_ts(e)); - let mut card = Card::new(Some(BLURPLE)); - let author = e["author_id"].as_u64().unwrap_or(0); + let colour = match kind { "deleted" => 0xC8324A, "edited" => 0xC8901E, _ => 0x2C6EC8 }; + let mut card = Card::new(Some(colour)).gallery(&[&format!("attachment://{}", art::FILE)]); + let jump = format!("https://discord.com/channels/{guild}/{channel}/{}", e["message_id"].as_u64().unwrap_or(0)); + let who = e[if kind == "reactions" { "user_id" } else { "author_id" }].as_u64().unwrap_or(0); + let mut details = vec![format!("<@{who}>"), when]; + if kind == "deleted" { + let all: Vec<&str> = e["attachments"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let is_img = |u: &str| IMAGE_EXTS.iter().any(|x| u.split('?').next().unwrap_or("").to_lowercase().ends_with(x)); + let images: Vec<&str> = all.iter().copied().filter(|u| is_img(u)).take(4).collect(); + let others: Vec<&str> = all.iter().copied().filter(|u| !images.contains(u)).collect(); + if !images.is_empty() { + card = card.gallery(&images); + } + if !others.is_empty() { + card = card.text(&format!("πŸ“Ž {}", others.iter().enumerate().map(|(i, u)| format!("[file {}](<{u}>)", i + 1)).collect::>().join(" Β· "))); + } + } else { + details.push(format!("[jump]({jump})")); + } + details.push(format!("{} of {total}, newest first", index + 1)); + card.footer(&details.join(" Β· ")) +} + +/// The picture for one entry: who, and what they did. +async fn picture(state: &State, kind: &str, e: &Value, guild: Option>) -> Vec { + let who = e[if kind == "reactions" { "user_id" } else { "author_id" }].as_u64().and_then(Id::new_checked); + let name = e[if kind == "reactions" { "user" } else { "author" }].as_str().map(str::to_string); + let name = match (name, who) { + (Some(n), _) => n, + (None, Some(u)) => crate::commands::info::display_name_of(state, guild, u).await, + _ => "Someone".to_string(), + }; + let avatar = match who { + Some(u) => { + let url = crate::commands::media::avatar(state, u, 128).await; + crate::commands::media::fetch_picture(state, &url).await + } + None => None, + }; + let seconds = (chrono::Utc::now().timestamp() - entry_ts(e) as i64).max(0) as u64; + let when = if seconds < 60 { "just now".to_string() } else { format!("{} ago", crate::converters::fmt_duration(seconds)) }; + let words = |k: &str| { let t = e[k].as_str().unwrap_or(""); if t.is_empty() { "No text".to_string() } else { crate::cardart::plain_in(state, t) } }; match kind { - "deleted" => { - let content = e["content"].as_str().unwrap_or(""); - let body = if content.is_empty() { "*no text*".to_string() } else { escape(&truncate(content, 3000)) }; - card = card.header(&[&format!("### {emoji} {label}"), &format!("{body}\n-# by <@{author}> Β· {when}")], None); - let all: Vec<&str> = e["attachments"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - let is_img = |u: &str| IMAGE_EXTS.iter().any(|x| u.split('?').next().unwrap_or("").to_lowercase().ends_with(x)); - let images: Vec<&str> = all.iter().copied().filter(|u| is_img(u)).take(4).collect(); - let others: Vec<&str> = all.iter().copied().filter(|u| !images.contains(u)).collect(); - if !images.is_empty() { - card = card.gallery(&images); - } - if !others.is_empty() { - card = card.text(&format!("πŸ“Ž {}", others.iter().enumerate().map(|(i, u)| format!("[file {}](<{u}>)", i + 1)).collect::>().join(" Β· "))); - } - } - "edited" => { - let jump = format!("https://discord.com/channels/{guild}/{channel}/{}", e["message_id"].as_u64().unwrap_or(0)); - let show = |k: &str| { let t = e[k].as_str().unwrap_or(""); if t.is_empty() { "*empty*".to_string() } else { escape(&truncate(t, 1500)) } }; - card = card.header(&[&format!("### {emoji} {label}"), &format!("**Before:** {}\n**After:** {}\n-# by <@{author}> Β· {when} Β· [jump]({jump})", show("before"), show("after"))], None); - } + "deleted" => art::deleted(&name, avatar.as_ref(), &words("content"), &when), + "edited" => art::edited(&name, avatar.as_ref(), &words("before"), &words("after"), &when), _ => { - let jump = format!("https://discord.com/channels/{guild}/{channel}/{}", e["message_id"].as_u64().unwrap_or(0)); - let emoji_text = e["emoji"].as_str().unwrap_or("?"); - let thumb = emoji_text.strip_prefix('<').and_then(|t| t.strip_suffix('>')).and_then(|t| { + let emoji = e["emoji"].as_str().unwrap_or("?"); + let custom = emoji.strip_prefix('<').and_then(|t| t.strip_suffix('>')).and_then(|t| { let parts: Vec<&str> = t.split(':').collect(); (parts.len() == 3).then(|| format!("https://cdn.discordapp.com/emojis/{}.{}", parts[2], if parts[0] == "a" { "gif" } else { "png" })) }); - card = card.header(&[&format!("### {emoji} {label}"), &format!("{emoji_text} removed by <@{}> Β· {when} Β· [message]({jump})", e["user_id"].as_u64().unwrap_or(0))], thumb.as_deref()); + let drawn = match custom { + Some(url) => crate::commands::media::fetch_picture(state, &url).await, + None => None, + }; + art::reaction(&name, avatar.as_ref(), emoji, drawn.as_ref(), &when) } } - card.footer(&format!("{} of {total} Β· newest first", index + 1)) } /// The browsing card: previous/next buttons and a kind menu, both carrying their state in the ids. @@ -190,14 +214,20 @@ pub async fn on_component(state: &Arc, i: &Interaction) { if entries(channel.get(), &kind).is_empty() { return; } - interact::update(state, i, view(&kind, index, owner, i.guild_id, channel)).await; + interact::ack(state, i).await; // the picture has to be uploaded, which a direct reply can't carry + let list = entries(channel.get(), &kind); + let bytes = picture(state, &kind, &list[index.min(list.len() - 1)], i.guild_id).await; + interact::edit_with_file(state, i, view(&kind, index, owner, i.guild_id, channel), art::FILE, bytes).await; } async fn show(ctx: &Ctx, kind: &str, index: usize) -> Result<()> { if entries(ctx.channel_id.get(), kind).is_empty() { return ctx.fail(&format!("πŸ” Nothing {} to snipe in this channel.", kind_info(kind).1.to_lowercase())).await; } - ctx.reply(view(kind, index.saturating_sub(1), ctx.user_id.get(), ctx.guild_id, ctx.channel_id)).await + let list = entries(ctx.channel_id.get(), kind); + let at = index.saturating_sub(1).min(list.len() - 1); + let bytes = picture(&ctx.state, kind, &list[at], ctx.guild_id).await; + ctx.reply_file(view(kind, at, ctx.user_id.get(), ctx.guild_id, ctx.channel_id), art::FILE, bytes).await } async fn snipe(ctx: Arc) -> Result<()> { diff --git a/src/commands/tools/virus.rs b/src/commands/tools/virus.rs index c0cf11c..b09630c 100644 --- a/src/commands/tools/virus.rs +++ b/src/commands/tools/virus.rs @@ -1,5 +1,6 @@ //! VirusTotal: `D!vt` / `/viruscheck` β€” a report for a link or a file (free tier: 4 per minute, 500 per day). use crate::cmd::{Command, Ctx, Opt, OptKind}; +use crate::commands::action_art as art; use crate::error::UserError; use crate::state::State; use crate::ui::{escape, truncate, Card, GREEN, RED}; @@ -93,7 +94,10 @@ async fn scan_file(state: &State, key: &str, name: &str, data: Vec) -> Resul wait(state, key, &analysis, &format!("files/{digest}")).await } -pub fn report_card(target: &str, report: &Value, is_file: bool) -> Component { +const PICTURE: &str = "scan.png"; + +/// The report as a picture, with the dates and the link to the full report under it. +pub fn report_card(target: &str, report: &Value, is_file: bool) -> (Component, Vec) { let data = &report["data"]; let attrs = &data["attributes"]; let stats = &attrs["last_analysis_stats"]; @@ -101,42 +105,45 @@ pub fn report_card(target: &str, report: &Value, is_file: bool) -> Component { let (bad, sus) = (n("malicious"), n("suspicious")); let total = bad + sus + n("harmless") + n("undetected"); let (accent, verdict) = if bad >= 3 { - (RED, format!("🚨 **Dangerous** β€” {bad} of {total} engines flag it")) + (0xC8324A, "Dangerous") } else if bad > 0 || sus > 0 { - (0xF39C12, format!("⚠️ **Suspicious** β€” {bad} malicious, {sus} suspicious of {total}")) + (0xC8901E, "Suspicious") } else { - (GREEN, format!("βœ… **Looks clean** β€” 0 of {total} engines flag it")) + (0x2A9C6A, "Looks clean") }; - let mut card = Card::new(Some(accent)).text(&format!("### {} scan\n`{}`\n{verdict}", if is_file { "πŸ“ File" } else { "🌐 Link" }, escape(&truncate(target, 200)))); - let hits: Vec = attrs["last_analysis_results"].as_object().map(|o| o.iter() + let mut hits: Vec<(String, String)> = attrs["last_analysis_results"].as_object().map(|o| o.iter() .filter(|(_, r)| matches!(r["category"].as_str(), Some("malicious" | "suspicious"))) - .map(|(engine, r)| format!("β€’ **{}**: {}", escape(engine), escape(r["result"].as_str().or(r["category"].as_str()).unwrap_or("")))).collect()).unwrap_or_default(); - if !hits.is_empty() { - let more = if hits.len() > 8 { format!("\n-# …and {} more", hits.len() - 8) } else { String::new() }; - card = card.text(&(hits.iter().take(8).cloned().collect::>().join("\n") + &more)); - } + .map(|(engine, r)| (engine.clone(), r["result"].as_str().or(r["category"].as_str()).unwrap_or("").to_string())).collect()).unwrap_or_default(); + hits.sort(); + let mut tiles = vec![("Malicious".to_string(), n("malicious").to_string()), ("Suspicious".to_string(), n("suspicious").to_string()), ("Harmless".to_string(), n("harmless").to_string()), ("Undetected".to_string(), n("undetected").to_string())]; let mut info = vec![]; if is_file { if let Some(t) = attrs["type_description"].as_str() { - info.push(format!("Type: {t}")); + tiles.push(("Type".to_string(), t.to_string())); } if let Some(s) = attrs["size"].as_f64() { - info.push(format!("Size: {:.0} KB", s / 1024.0)); + tiles.push(("Size".to_string(), format!("{:.0} KB", s / 1024.0))); } if let Some(t) = attrs["first_submission_date"].as_i64() { - info.push(format!("First seen ")); + tiles.push(("First seen".to_string(), crate::cardart::date(t))); } } else if let Some(t) = attrs["title"].as_str() { - info.push(format!("Page title: {}", escape(&truncate(t, 80)))); + tiles.push(("Page title".to_string(), t.to_string())); } if let Some(t) = attrs["last_analysis_date"].as_i64() { info.push(format!("Analysed ")); } + if hits.len() > 12 { + info.push(format!("{} more engines flagged it", hits.len() - 12)); + } + let picture = art::scan(&art::Scan { target, kind: if is_file { "File scan" } else { "Link scan" }, verdict, accent, flagged: bad + sus, total, tiles, hits }); + let mut card = Card::new(Some(accent)).gallery(&[&format!("attachment://{PICTURE}")]); if !info.is_empty() { card = card.footer(&info.join(" Β· ")); } let link = format!("https://www.virustotal.com/gui/{}/{}", if is_file { "file" } else { "url" }, data["id"].as_str().unwrap_or("")); - card.row(vec![Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "πŸ”Ž".into() }), label: Some("Full report".into()), style: ButtonStyle::Link, url: Some(link), sku_id: None }]).build() + let full = Button { id: None, custom_id: None, disabled: false, emoji: None, label: Some("Full report".into()), style: ButtonStyle::Link, url: Some(link), sku_id: None }; + (card.row(vec![full]).build(), picture) } async fn viruscheck(ctx: Arc) -> Result<()> { @@ -177,12 +184,17 @@ async fn viruscheck(ctx: Arc) -> Result<()> { } None => scan_url(state, &key, url.as_deref().unwrap_or("")).await, }; - let card = match report { - Ok(r) => report_card(&name, &r, file.is_some()), - Err(e) => Card::new(Some(RED)).text(&format!("❌ Scan failed: {e}")).build(), - }; let _ = status; - if private { ctx.reply_private(card).await } else { ctx.reply(card).await } + match report { + Ok(r) => { + let (card, picture) = report_card(&name, &r, file.is_some()); + if private { ctx.reply_private_file(card, PICTURE, picture).await } else { ctx.reply_file(card, PICTURE, picture).await } + } + Err(e) => { + let card = Card::new(Some(RED)).text(&format!("❌ Scan failed: {e}")).build(); + if private { ctx.reply_private(card).await } else { ctx.reply(card).await } + } + } } pub fn commands() -> Vec { @@ -201,12 +213,12 @@ mod tests { #[test] fn verdicts() { let clean = json!({"data": {"id": "abc", "attributes": {"last_analysis_stats": {"harmless": 60, "undetected": 10}}}}); - let s = serde_json::to_string(&report_card("https://x.y", &clean, false)).unwrap(); - assert!(s.contains("Looks clean") && s.contains("0 of 70")); + let (card, picture) = report_card("https://x.y", &clean, false); + assert!(serde_json::to_string(&card).unwrap().contains(&0x2A9C6Au32.to_string()) && picture.len() > 1000); let bad = json!({"data": {"id": "abc", "attributes": {"last_analysis_stats": {"malicious": 5, "harmless": 60}, "last_analysis_results": {"Eng1": {"category": "malicious", "result": "Trojan.X"}, "Eng2": {"category": "harmless"}}}}}); - let s = serde_json::to_string(&report_card("evil.exe", &bad, true)).unwrap(); - assert!(s.contains("Dangerous") && s.contains("Trojan.X") && !s.contains("Eng2")); + let (card, _) = report_card("evil.exe", &bad, true); + assert!(serde_json::to_string(&card).unwrap().contains(&0xC8324Au32.to_string())); } #[test]