diff --git a/ROADMAP.md b/ROADMAP.md index 9d20443..6a68dbe 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -114,5 +114,7 @@ Plan (backward compatible with the existing file): - Casino spins are one GIF that plays once and lands on the real result, then the same final frame as a still with the buttons back (`games/art.rs`). Balance is `art::wallet`. Slot symbols and weather icons are colour emoji drawn into the picture. - `tools/weather_art.rs`: sky by condition, detail tiles, 24-hour chart with chance of rain, 5-day ranges. The place name stays off the picture on purpose. - `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. +- `/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 9a53fbc..44470cb 100644 --- a/src/cardart.rs +++ b/src/cardart.rs @@ -194,3 +194,147 @@ pub fn rounded_cover(art: &RgbaImage, size: u32, radius: f32) -> RgbaImage { }); square } + +/// A backdrop's two colours from one colour: rich at the top, deep at the bottom. Greys stay grey. +pub fn wash(accent: u32) -> ([u8; 3], [u8; 3]) { + let c = [(accent >> 16) as u8, (accent >> 8) as u8, accent as u8].map(f32::from); + let high = c[0].max(c[1]).max(c[2]).max(1.0); + let full = c.map(|v| v * 200.0 / high); + (full.map(|v| (v * 0.5) as u8), full.map(|v| (v * 0.14) as u8)) +} + +const INK: [u8; 3] = [250, 250, 248]; +const SOFT: [u8; 3] = [214, 214, 220]; + +/// A wide backdrop to draw on; [`finish`] cuts it to the height actually used. +pub fn canvas(accent: u32) -> RgbaImage { + let (top, bottom) = wash(accent); + gradient(WIDTH, 1000, top, bottom) +} + +pub fn finish(img: &RgbaImage, bottom: i32) -> Vec { + png(&image::imageops::crop_imm(img, 0, 0, WIDTH, (bottom + PAD).clamp(1, img.height() as i32) as u32).to_image()) +} + +/// Tiles in `columns` columns, each a label over a value. Gives back where the last row ends. +pub fn tile_grid(img: &mut RgbaImage, top: i32, columns: i32, items: &[(String, String)]) -> i32 { + let (gap, height) = (8, 64); + let width = (WIDTH as i32 - 2 * PAD - gap * (columns - 1)) / columns; + for (i, (label, value)) in items.iter().enumerate() { + let (x, y) = (PAD + (i as i32 % columns) * (width + gap), top + (i as i32 / columns) * (height + gap)); + tint(img, (x, y, width, height), 8, [255, 255, 255], 0.1); + line(img, label, (x + 12, y + 9), 14.0, false, SOFT, width - 20); + line(img, value, (x + 12, y + 30), 19.0, true, INK, width - 20); + } + let rows = (items.len() as i32 + columns - 1) / columns; + top + rows * height + (rows - 1).max(0) * gap +} + +/// Small labels that wrap, each with an optional coloured dot. Gives back where they end. +pub fn chips(img: &mut RgbaImage, top: i32, items: &[(String, Option<[u8; 3]>)]) -> i32 { + let (mut x, mut y, height) = (PAD, top, 32); + let look = text::Look::new(None, false, INK); + for (label, dot) in items { + let label = fit_line(label, 15.0, &look, 300.0); + let width = text::width_of(&label, 15.0, &look).ceil() as i32 + if dot.is_some() { 38 } else { 24 }; + if x + width > WIDTH as i32 - PAD { + x = PAD; + y += height + 6; + } + tint(img, (x, y, width, height), 8, [255, 255, 255], 0.12); + let mut tx = x + 12; + if let Some(c) = dot { + pix::rounded_rect(img, x + 10, y + 10, 12, 12, 6, rgba(*c)); + tx += 16; + } + line(img, &label, (tx, y + 6), 15.0, false, INK, width); + x += width + 6; + } + if items.is_empty() { top } else { y + height } +} + +/// A bar `share` full. +pub fn meter(img: &mut RgbaImage, (x, y, width, height): (i32, i32, i32, i32), share: f32, colour: [u8; 3]) { + tint(img, (x, y, width, height), height / 2, [255, 255, 255], 0.14); + let fill = (width as f32 * share.clamp(0.0, 1.0)) as i32; + if fill > 0 { + pix::rounded_rect(img, x, y, fill.max(height), height, height / 2, rgba(colour)); + } +} + +/// Wrapped text, at most `lines` lines. Gives back where it ends. +pub fn paragraph(img: &mut RgbaImage, text_: &str, (x, y): (i32, i32), size: f32, colour: [u8; 3], width: i32, lines: usize) -> i32 { + let look = text::Look::new(None, false, colour); + let mut shown = text_.to_string(); + let mut para = text::layout(&shown, size, &look, Some(width as f32), Align::Left); + while para.lines > lines && shown.chars().count() > 4 { + let keep = shown.chars().count() * lines / para.lines.max(1); + shown = shown.chars().take(keep.max(1).saturating_sub(2)).collect::().trim_end().to_string() + "…"; + para = text::layout(&shown, size, &look, Some(width as f32), Align::Left); + } + para.draw(img, x, y); + y + para.height.ceil() as i32 +} + +/// `12 Mar 2021`. +pub fn date(unix: i64) -> String { + chrono::DateTime::from_timestamp(unix, 0).map_or("?".to_string(), |d| d.format("%-d %b %Y").to_string()) +} + +/// `5 years ago`. +pub fn ago(unix: i64) -> String { + let days = (chrono::Utc::now().timestamp() - unix).max(0) / 86400; + let (n, unit) = if days >= 365 { (days / 365, "year") } else if days >= 30 { (days / 30, "month") } else { (days, "day") }; + match n { + 0 => "today".to_string(), + 1 => format!("1 {unit} ago"), + n => format!("{n} {unit}s ago"), + } +} + +pub struct Row { + pub rank: usize, + pub name: String, + pub by: Option, + /// How full the bar is, 0..1. + pub share: f32, + pub value: String, +} + +pub struct Chart { + pub title: String, + pub note: String, + pub accent: u32, + pub rows: Vec, + pub cover: Option>, + pub empty: String, +} + +/// A ranked list with bars: the Last.fm charts, the richest players, the queue. +pub fn chart(c: &Chart) -> Vec { + let w = WIDTH as i32; + let row_h = 48; + let height = 104 + row_h * c.rows.len().max(1) as i32 + 16; + let (top, bottom) = wash(c.accent); + let mut img = gradient(WIDTH, height as u32, top, bottom); + line(&mut img, &c.title, (PAD, 24), 28.0, true, INK, w - 2 * PAD - 96); + line(&mut img, &c.note, (PAD, 62), 18.0, false, SOFT, w - 2 * PAD - 96); + if let Some(a) = &c.cover { + blit(&mut img, &rounded_cover(a, 72, 8.0), w - PAD - 72, 20, (0, 0, w, height)); + } + if c.rows.is_empty() { + line(&mut img, &c.empty, (PAD, 112), 18.0, false, SOFT, w - 2 * PAD); + } + let fill = top.map(|v| v.saturating_mul(2).max(70)); + for (i, row) in c.rows.iter().enumerate() { + let y = 104 + i as i32 * row_h; + let (bar_x, bar_w) = (PAD + 44, w - 2 * PAD - 44); + tint(&mut img, (bar_x, y, bar_w, row_h - 6), 6, [255, 255, 255], 0.06); + tint(&mut img, (bar_x, y, (bar_w as f32 * row.share.clamp(0.02, 1.0)) as i32, row_h - 6), 6, fill, 0.8); + line_right(&mut img, &row.rank.to_string(), (PAD + 30, y + 9), 19.0, true, if row.rank == 1 { [255, 214, 110] } else { SOFT }); + let label = row.by.as_ref().map_or(row.name.clone(), |b| format!("{} · {b}", row.name)); + line(&mut img, &label, (bar_x + 12, y + 10), 18.0, row.rank <= 3, INK, bar_w - 150); + line_right(&mut img, &row.value, (bar_x + bar_w - 12, y + 12), 15.0, false, INK); + } + png(&img) +} diff --git a/src/commands/games/casino.rs b/src/commands/games/casino.rs index 5b137fe..3c66839 100644 --- a/src/commands/games/casino.rs +++ b/src/commands/games/casino.rs @@ -865,15 +865,24 @@ async fn richest(ctx: Arc) -> Result<()> { if rows.is_empty() { return ctx.say("Nobody here has played yet!").await; } - let medals = ["🥇", "🥈", "🥉"]; - let lines: Vec = rows.iter().enumerate().map(|(i, (u, m))| format!("{} <@{u}> — {}", medals.get(i).map_or(format!("`{:>2}.`", i + 1), |s| s.to_string()), fmt(*m))).collect(); let guild = ctx.guild_id.and_then(|g| ctx.state.cache.guild(g).map(|g| g.name().to_string())).unwrap_or_default(); - let title = format!("### 🏆 Richest players{}", if everywhere { String::new() } else { format!(" in {}", escape(&guild)) }); - let pages: Vec = lines.chunks(10).map(|chunk| { - let card = Card::new(Some(GOLD)).text(&format!("{title}\n{}", chunk.join("\n"))); - pager::fixed(card) - }).collect(); - pager::start(&ctx, pages, Duration::from_secs(300)).await + let note = if everywhere { "Everywhere".to_string() } else { format!("In {guild}") }; + let most = rows.first().map_or(1, |r| r.1.max(1)); + let mut people = Vec::with_capacity(rows.len()); + for (i, (u, coins)) in rows.iter().enumerate() { + let name = match Id::::new_checked(*u) { + Some(id) => display_name_of(&ctx.state, ctx.guild_id, id).await, + None => "Someone".to_string(), + }; + people.push((i + 1, name, *coins)); + } + let count = people.len().div_ceil(10); + let art: pager::Art = Arc::new(move |page| { + let rows = people.iter().skip(page * 10).take(10).map(|(rank, name, coins)| crate::cardart::Row { rank: *rank, name: name.clone(), by: None, share: *coins as f32 / most as f32, value: format!("{} coins", thousands((*coins).max(0) as u64)) }).collect(); + crate::cardart::chart(&crate::cardart::Chart { title: "Richest players".to_string(), note: note.clone(), accent: 0xC8962E, rows, cover: None, empty: String::new() }) + }); + let pages: Vec = (0..count).map(|_| pager::fixed(picture(GOLD, art::STILL))).collect(); + pager::start_drawn(&ctx, pages, Duration::from_secs(300), art::STILL, art).await } fn suggest_choice(_: Arc, _focused: String, current: String, _: Option>, _: Id) -> BoxFuture<'static, Vec<(String, String)>> { diff --git a/src/commands/info.rs b/src/commands/info.rs index d45d2fc..d02f9cb 100644 --- a/src/commands/info.rs +++ b/src/commands/info.rs @@ -6,6 +6,8 @@ //! //! Banners and accent colours need an extra API call per user; results are cached for 10 minutes so //! repeated lookups are instant and don't burn rate limits. +use super::info_art as art; +use super::media::fetch_picture; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::colors; @@ -167,7 +169,7 @@ async fn target(ctx: &Ctx, option: &str) -> Result { // ---- user ---------------------------------------------------------------------------------- -async fn user_card(state: &State, user: &User, guild: Option>) -> Component { +async fn user_card(state: &State, user: &User, guild: Option>) -> (Component, Vec) { let full = full_user(state, user.id).await; let member = guild.and_then(|g| state.cache.member(g, user.id).map(|m| (g, m))); let role_color = member.as_ref().and_then(|(g, m)| { @@ -180,72 +182,76 @@ async fn user_card(state: &State, user: &User, guild: Option>) - let accent = colors::accent(state, Some(&avatar), accent).await; let created = created_at(user.id.get()); let badges: Vec<&str> = user.public_flags.map(|f| BADGES.iter().filter(|(b, _)| f.contains(*b)).map(|(_, n)| *n).collect()).unwrap_or_default(); - let mut lines = vec![ - format!("**Username:** `{}`{}", user.name, user.global_name.as_ref().map_or(String::new(), |g| format!(" · **Display name:** {}", escape(g)))), - format!("**ID:** `{}`{}", user.id, if user.bot { " · 🤖 Bot" } else { "" }), - format!("**Account created:** {} ({})", ts(created, 'D'), ts(created, 'R')), - ]; + let mut tiles = vec![("Account created".to_string(), art::when(created))]; + let (mut status, mut role_rows, mut more_roles, mut permissions) = (None, vec![], 0, vec![]); + if user.bot { + tiles.push(("Account".to_string(), "Bot".to_string())); + } if !badges.is_empty() { - lines.push(format!("**Badges:** {}", badges.join(", "))); + tiles.push(("Badges".to_string(), badges.join(", "))); } - let mut card = Card::new(Some(accent)).header(&[&format!("### 👤 {}", escape(&display_name(state, guild, user))), &lines.join("\n")], Some(&avatar)); - if let Some((g, m)) = member { + if let Some(j) = m.joined_at() { + tiles.insert(1, ("Joined".to_string(), art::when(j.as_secs()))); + } let mut roles: Vec<(i64, Id)> = m.roles().iter().filter_map(|r| state.cache.role(*r).map(|x| (x.position, *r))).collect(); roles.sort_by_key(|(p, _)| std::cmp::Reverse(*p)); - let shown: Vec = roles.iter().take(20).map(|(_, r)| format!("<@&{r}>")).collect(); - let role_text = if roles.is_empty() { "None".to_string() } else { shown.join(" ") + &if roles.len() > 20 { format!(" +{} more", roles.len() - 20) } else { String::new() } }; - let mut server = vec![]; - if let Some(j) = m.joined_at() { - server.push(format!("**Joined:** {} ({})", ts(j.as_secs(), 'D'), ts(j.as_secs(), 'R'))); - } + more_roles = roles.len().saturating_sub(20); + #[allow(deprecated)] + let rows: Vec<(String, Option<[u8; 3]>)> = roles.iter().take(20).filter_map(|(_, r)| state.cache.role(*r).map(|x| (x.name.clone(), (x.color != 0).then(|| [(x.color >> 16) as u8, (x.color >> 8) as u8, x.color as u8])))).collect(); + role_rows = rows; if let Some(n) = m.nick() { - server.push(format!("**Nickname:** {}", escape(n))); + tiles.push(("Nickname".to_string(), n.to_string())); } + status = Some(match state.cache.presence(g, user.id).map(|p| p.status()) { + Some(Status::Online) => ("Online", [76, 195, 138]), + Some(Status::Idle) => ("Idle", [240, 178, 50]), + Some(Status::DoNotDisturb) => ("Do not disturb", [229, 72, 77]), + _ => ("Offline", [133, 133, 139]), + }); + tiles.push(("Status".to_string(), status.map_or("Offline", |s| s.0).to_string())); if let Some(p) = state.cache.presence(g, user.id) { - server.push(format!("**Status:** {}", match p.status() { - Status::Online => "🟢 Online", Status::Idle => "🌙 Idle", Status::DoNotDisturb => "⛔ Do not disturb", _ => "⚫ Offline", - })); if let Some(a) = p.activities().iter().find(|a| a.kind != ActivityType::Custom && !a.name.is_empty()) { let verb = match a.kind { ActivityType::Playing => "Playing", ActivityType::Listening => "Listening to", ActivityType::Watching => "Watching", ActivityType::Streaming => "Streaming", ActivityType::Competing => "Competing in", _ => "Doing", }; - let detail = if a.kind == ActivityType::Listening { a.details.as_ref().map_or(String::new(), |d| format!(" — {}", escape(d))) } else { String::new() }; - server.push(format!("**Activity:** {verb} {}{detail}", escape(&a.name))); + let detail = if a.kind == ActivityType::Listening { a.details.as_ref().map_or(String::new(), |d| format!(": {d}")) } else { String::new() }; + tiles.push(("Activity".to_string(), format!("{verb} {}{detail}", a.name))); } - } else { - server.push("**Status:** ⚫ Offline".to_string()); } if let Some(b) = m.premium_since() { - server.push(format!("**Boosting since:** {}", ts(b.as_secs(), 'D'))); + tiles.push(("Boosting since".to_string(), art::when(b.as_secs()))); } if let Some(t) = m.communication_disabled_until().filter(|t| (t.as_secs() as f64) > crate::audit::now()) { - server.push(format!("**⏱️ Timed out** until {}", ts(t.as_secs(), 'f'))); + tiles.push(("Timed out until".to_string(), crate::cardart::date(t.as_secs()))); } let perms = state.guild_permissions(g, user.id); let mut key: Vec<&str> = KEY_PERMS.iter().filter(|(p, _)| perms.contains(*p)).map(|(_, n)| *n).collect(); if key.contains(&"Administrator") { key = vec!["Administrator"]; } - if !key.is_empty() { - server.push(format!("**Key permissions:** {}", key.join(", "))); - } - server.push(format!("**Roles ({}):** {role_text}", roles.len())); - card = card.separator(true, false).text(&server.join("\n")); + permissions = key.into_iter().map(str::to_string).collect(); } + let banner_url = full.and_then(|f| f.banner); + let banner = match &banner_url { + Some(b) => fetch_picture(state, b).await, + None => None, + }; + let bytes = art::user(&art::User { accent, name: display_name(state, guild, user), handle: format!("@{}", user.name), avatar: fetch_picture(state, &avatar).await, banner, status, tiles, roles: role_rows, more_roles, permissions }); let mut buttons = vec![link_button("Avatar", &avatar)]; - if let Some(b) = full.and_then(|f| f.banner) { - card = card.gallery(&[&b]); - buttons.push(link_button("Banner", &b)); + if let Some(b) = &banner_url { + buttons.push(link_button("Banner", b)); } - card.row(buttons).build() + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@{}> · ID `{}`", user.id, user.id)).row(buttons).build(); + (card, bytes) } async fn userinfo(ctx: Arc) -> Result<()> { let user = target(&ctx, "user").await?; ctx.defer().await?; - ctx.reply(user_card(&ctx.state, &user, ctx.guild_id).await).await + let (card, picture) = user_card(&ctx.state, &user, ctx.guild_id).await; + ctx.reply_file(card, art::FILE, picture).await } // ---- server -------------------------------------------------------------------------------- @@ -258,7 +264,7 @@ fn sticker_limit(tier: u8) -> usize { [5, 15, 30, 60][tier.min(3) as usize] } -async fn server_card(state: &State, guild: Id) -> Result { +async fn server_card(state: &State, guild: Id) -> Result<(Component, Vec)> { let Some(g) = state.cache.guild(guild) else { bail_user!("I can't see that server.") }; let cache = &state.cache; let members: Vec> = cache.guild_members(guild).map(|m| m.iter().copied().collect()).unwrap_or_default(); @@ -266,14 +272,6 @@ async fn server_card(state: &State, guild: Id) -> Result let online = members.iter().filter(|u| cache.presence(guild, **u).is_some_and(|p| p.status() != Status::Offline)).count(); let total = g.member_count().unwrap_or(members.len() as u64) as usize; let created = created_at(guild.get()); - let mut basics = vec![ - format!("**Owner:** <@{}>", g.owner_id()), - format!("**Created:** {} ({})", ts(created, 'D'), ts(created, 'R')), - format!("**ID:** `{guild}` · **Verification:** {:?}", g.verification_level()), - ]; - if let Some(d) = g.description() { - basics.insert(0, escape(&truncate(d, 300))); - } let icon = g.icon().map(|i| format!("https://cdn.discordapp.com/icons/{guild}/{i}.{}?size=256", if i.is_animated() { "gif" } else { "png" })); let banner = g.banner().map(|b| format!("https://cdn.discordapp.com/banners/{guild}/{b}.png?size=1024")); let accent = colors::accent(state, icon.as_deref().or(banner.as_deref()), BLURPLE).await; @@ -290,37 +288,52 @@ async fn server_card(state: &State, guild: Id) -> Result let emojis = cache.guild_emojis(guild).map_or(0, |e| e.len()); let stickers = cache.guild_stickers(guild).map_or(0, |e| e.len()); let boosters = members.iter().filter(|u| cache.member(guild, **u).is_some_and(|m| m.premium_since().is_some())).count(); - let mut counts = vec![ - format!("👥 **{}** members · {} people, {} bots · 🟢 {} online", thousands(total as u64), thousands(total.saturating_sub(bots) as u64), thousands(bots as u64), thousands(online as u64)), - format!("💬 **{}** text · 🔊 **{voice}** voice · 🗂️ **{}** categories{}", n(ChannelType::GuildText) + n(ChannelType::GuildAnnouncement), n(ChannelType::GuildCategory), - if n(ChannelType::GuildForum) > 0 { format!(" · 📋 **{}** forums", n(ChannelType::GuildForum)) } else { String::new() }), - format!("🎭 **{roles}** roles · 😀 **{emojis}/{}** emojis · 🏷️ **{stickers}/{}** stickers", emoji_limit(tier), sticker_limit(tier)), - format!("💎 Level **{tier}** · **{}** boosts from **{boosters}** members", g.premium_subscription_count().unwrap_or(0)), - ]; - counts.retain(|l| !l.is_empty()); - let mut card = Card::new(Some(accent)).header(&[&format!("### 🏰 {}", escape(g.name())), &basics.join("\n")], icon.as_deref()).separator(true, false).text(&counts.join("\n")); let features: Vec = g.features().into_iter().filter_map(|f| { let name = format!("{f:?}"); ["Community", "Partnered", "Verified", "Discoverable", "VanityUrl", "AnimatedIcon", "Banner", "RoleIcons", "WelcomeScreenEnabled", "MemberVerificationGateEnabled"] .contains(&name.as_str()).then(|| name) }).collect(); - if !features.is_empty() { - card = card.footer(&format!("Features: {}", features.join(", "))); + let (name, description, owner, boosts, verification) = (g.name().to_string(), g.description().map(str::to_string), g.owner_id(), g.premium_subscription_count().unwrap_or(0), format!("{:?}", g.verification_level())); + drop(g); + let owner_name = display_name_of(state, Some(guild), owner).await; + let mut tiles = vec![ + ("Text".to_string(), (n(ChannelType::GuildText) + n(ChannelType::GuildAnnouncement)).to_string()), + ("Voice".to_string(), voice.to_string()), + ("Categories".to_string(), n(ChannelType::GuildCategory).to_string()), + ("Roles".to_string(), roles.to_string()), + ("Emojis".to_string(), format!("{emojis} of {}", emoji_limit(tier))), + ("Stickers".to_string(), format!("{stickers} of {}", sticker_limit(tier))), + ("Owner".to_string(), owner_name), + ("Created".to_string(), crate::cardart::date(created)), + ("Verification".to_string(), verification), + ]; + if n(ChannelType::GuildForum) > 0 { + tiles.insert(3, ("Forums".to_string(), n(ChannelType::GuildForum).to_string())); } + let bytes = art::server(&art::Server { + accent, name, description, tiles, features, tier, + icon: match &icon { Some(i) => fetch_picture(state, i).await, None => None }, + banner: match &banner { Some(b) => fetch_picture(state, b).await, None => None }, + members: total as u64, bots: bots as u64, online: online as u64, boosts: boosts, boosters: boosters as u64, + }); + let mut card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("Owner <@{owner}> · ID `{guild}`")); let mut buttons = vec![]; if let Some(i) = &icon { buttons.push(link_button("Icon", i)); } if let Some(b) = &banner { - card = card.gallery(&[b]); buttons.push(link_button("Banner", b)); } - Ok(card.row(buttons).build()) + if !buttons.is_empty() { + card = card.row(buttons); + } + Ok((card.build(), bytes)) } async fn serverinfo(ctx: Arc) -> Result<()> { - let card = server_card(&ctx.state, ctx.guild()?).await?; - ctx.reply(card).await + ctx.defer().await?; + let (card, picture) = server_card(&ctx.state, ctx.guild()?).await?; + ctx.reply_file(card, art::FILE, picture).await } // ---- channel & role ------------------------------------------------------------------------ @@ -329,36 +342,48 @@ async fn channelinfo(ctx: Arc) -> Result<()> { let guild = ctx.guild()?; let id = ctx.args.id("channel").and_then(Id::new_checked).unwrap_or(ctx.channel_id); let Some(c) = ctx.state.cache.channel(id).map(|c| c.clone()) else { bail_user!("I can't see that channel.") }; - let kind = format!("{:?}", c.kind); + let (accent, symbol, kind) = art::channel_look(&format!("{:?}", c.kind)); let created = created_at(id.get()); - let mut lines = vec![format!("**Type:** {kind} · **ID:** `{id}`"), format!("**Created:** {} ({})", ts(created, 'D'), ts(created, 'R'))]; + let mut tiles = vec![("Created".to_string(), crate::cardart::date(created))]; if let Some(p) = c.parent_id.and_then(|p| ctx.state.cache.channel(p).and_then(|p| p.name.clone())) { - lines.push(format!("**Category:** {}", escape(&p))); + tiles.push(("Category".to_string(), p)); } + let mut topic = None; if matches!(c.kind, ChannelType::GuildText | ChannelType::GuildAnnouncement | ChannelType::GuildForum) { - if let Some(t) = c.topic.as_deref().filter(|t| !t.is_empty()) { - lines.push(format!("**Topic:** {}", escape(&truncate(t, 500)))); - } + topic = c.topic.clone(); let sm = c.rate_limit_per_user.unwrap_or(0); - lines.push(format!("**Slowmode:** {} · **NSFW:** {}", if sm > 0 { format!("{sm}s") } else { "off".into() }, if c.nsfw.unwrap_or(false) { "yes" } else { "no" })); + tiles.push(("Slowmode".to_string(), if sm > 0 { format!("{sm} seconds") } else { "Off".to_string() })); + tiles.push(("Age restricted".to_string(), if c.nsfw.unwrap_or(false) { "Yes" } else { "No" }.to_string())); } - if matches!(c.kind, ChannelType::GuildVoice | ChannelType::GuildStageVoice) { - lines.push(format!("**Bitrate:** {} kbps · **User limit:** {} · **Region:** {}", c.bitrate.unwrap_or(0) / 1000, - c.user_limit.filter(|l| *l > 0).map_or("none".into(), |l| l.to_string()), c.rtc_region.as_deref().unwrap_or("automatic"))); - let inside: Vec = ctx.state.cache.voice_channel_states(id).map(|it| it.take(15).map(|s| format!("<@{}>", s.user_id())).collect()).unwrap_or_default(); - if !inside.is_empty() { - lines.push(format!("**In voice ({}):** {}", inside.len(), inside.join(", "))); + let mut inside = vec![]; + let is_voice = matches!(c.kind, ChannelType::GuildVoice | ChannelType::GuildStageVoice); + if is_voice { + tiles.push(("Bitrate".to_string(), format!("{} kbps", c.bitrate.unwrap_or(0) / 1000))); + tiles.push(("User limit".to_string(), c.user_limit.filter(|l| *l > 0).map_or("None".to_string(), |l| l.to_string()))); + tiles.push(("Region".to_string(), c.rtc_region.clone().unwrap_or_else(|| "Automatic".to_string()))); + let users: Vec<_> = ctx.state.cache.voice_channel_states(id).map(|it| it.take(24).map(|s| s.user_id()).collect()).unwrap_or_default(); + for u in users { + inside.push(display_name_of(&ctx.state, Some(guild), u).await); } } if c.kind == ChannelType::GuildCategory { let n = ctx.state.cache.guild_channels(guild).map_or(0, |ids| ids.iter().filter(|i| ctx.state.cache.channel(**i).is_some_and(|x| x.parent_id == Some(id))).count()); - lines.push(format!("**Channels:** {n}")); + tiles.push(("Channels".to_string(), n.to_string())); } let everyone = ctx.state.cache.role(guild.cast()).map_or(Permissions::empty(), |r| r.permissions); - let (view, send) = (everyone.contains(Permissions::VIEW_CHANNEL), everyone.contains(Permissions::SEND_MESSAGES)); - lines.push(format!("**Everyone can:** {}, {}", if view { "view".into() } else { "~~view~~" }, if send { "send".into() } else { "~~send~~" })); - let card = Card::new(Some(BLURPLE)).header(&[&format!("### #️⃣ {}", escape(c.name.as_deref().unwrap_or("?"))), &format!("<#{id}>\n{}", lines.join("\n"))], None).build(); - ctx.reply(card).await + let mut can = vec![]; + if everyone.contains(Permissions::VIEW_CHANNEL) { + can.push("view"); + } + if is_voice && everyone.contains(Permissions::CONNECT) { + can.push("connect"); + } else if !is_voice && everyone.contains(Permissions::SEND_MESSAGES) { + can.push("send"); + } + tiles.push(("Everyone can".to_string(), if can.is_empty() { "Nothing".to_string() } else { let t = can.join(", "); t[..1].to_uppercase() + &t[1..] })); + let bytes = art::channel(&art::Channel { accent, symbol, name: c.name.clone().unwrap_or_else(|| "?".to_string()), kind: kind.to_string(), topic, tiles, inside }); + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<#{id}> · ID `{id}`")).build(); + ctx.reply_file(card, art::FILE, bytes).await } async fn roleinfo(ctx: Arc) -> Result<()> { @@ -374,20 +399,24 @@ async fn roleinfo(ctx: Arc) -> Result<()> { let members = cache.guild_members(guild).map_or(0, |ms| ms.iter().filter(|u| cache.member(guild, **u).is_some_and(|m| m.roles().contains(&id))).count()); let total = cache.guild_roles(guild).map_or(1, |r| r.len()) - 1; let created = created_at(id.get()); - let lines = vec![ - format!("<@&{id}> · **ID:** `{id}`"), - format!("**Colour:** `#{:06X}` · **Position:** {} of {total}", role.color, role.position), - format!("**Members:** {} · **Created:** {}", thousands(members as u64), ts(created, 'D')), - format!("**Shown separately:** {} · **Mentionable:** {}{}", if role.hoist { "yes" } else { "no" }, if role.mentionable { "yes" } else { "no" }, if role.managed { " · **Managed by an integration**" } else { "" }), - ]; let perms = if role.permissions.contains(Permissions::ADMINISTRATOR) { vec!["Administrator (every permission)".to_string()] } else { perm_list(role.permissions) }; let icon = role.icon.map(|i| format!("https://cdn.discordapp.com/role-icons/{id}/{i}.png")); - let card = Card::new(Some(if role.color != 0 { role.color } else { BLURPLE })) - .header(&[&format!("### 🎭 {}", escape(&role.name)), &lines.join("\n")], icon.as_deref()) - .separator(true, false) - .text(&format!("**Permissions:** {}", if perms.is_empty() { "none beyond @everyone".to_string() } else { perms.join(", ") })) - .build(); - ctx.reply(card).await + let yes = |b: bool| if b { "Yes" } else { "No" }.to_string(); + let mut tiles = vec![ + ("Members".to_string(), thousands(members as u64)), + ("Position".to_string(), format!("{} of {total}", role.position)), + ("Colour".to_string(), if role.color != 0 { format!("#{:06X}", role.color) } else { "None".to_string() }), + ("Created".to_string(), crate::cardart::date(created)), + ("Shown separately".to_string(), yes(role.hoist)), + ("Mentionable".to_string(), yes(role.mentionable)), + ]; + if role.managed { + tiles.push(("Managed by".to_string(), "An integration".to_string())); + } + let picture = match &icon { Some(i) => fetch_picture(&ctx.state, i).await, None => None }; + let bytes = art::role(&art::Role { accent: role.color, name: role.name.clone(), icon: picture, tiles, permissions: perms }); + let card = Card::new(Some(if role.color != 0 { role.color } else { BLURPLE })).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@&{id}> · ID `{id}`")).build(); + ctx.reply_file(card, art::FILE, bytes).await } // ---- avatar & banner ----------------------------------------------------------------------- diff --git a/src/commands/info_art.rs b/src/commands/info_art.rs new file mode 100644 index 0000000..2fd23b5 --- /dev/null +++ b/src/commands/info_art.rs @@ -0,0 +1,282 @@ +//! The pictures for `userinfo`, `serverinfo`, `channelinfo` and `roleinfo`. Each takes its colour from what it describes: +//! the avatar, the server icon, the kind of channel, the role. +use crate::cardart::{ago, blit, canvas, chips, date, finish, line, meter, paragraph, rounded_cover, sprite, tile_grid, tint, PAD, WIDTH}; +use crate::converters::thousands; +use crate::pix; +use image::{imageops, Rgba, RgbaImage}; + +pub const FILE: &str = "info.png"; + +const INK: [u8; 3] = [250, 250, 248]; +const SOFT: [u8; 3] = [214, 214, 220]; +const W: i32 = WIDTH as i32; + +/// Label and value pairs from plain strings. +pub fn tiles(items: &[(&str, String)]) -> Vec<(String, String)> { + items.iter().map(|(a, b)| (a.to_string(), b.clone())).collect() +} + +pub fn when(unix: i64) -> String { + format!("{} · {}", date(unix), ago(unix)) +} + +/// A picture cut to a full-width strip across the top. +fn banner_strip(img: &mut RgbaImage, banner: &RgbaImage, height: u32) { + let strip = pix::cover(banner, WIDTH, height); + imageops::overlay(img, &strip, 0, 0); +} + +// ---- user ---------------------------------------------------------------------------------------------------------- + +pub struct User { + pub accent: u32, + pub name: String, + pub handle: String, + pub avatar: Option, + pub banner: Option, + /// `None` outside a server. + pub status: Option<(&'static str, [u8; 3])>, + pub tiles: Vec<(String, String)>, + pub roles: Vec<(String, Option<[u8; 3]>)>, + pub more_roles: usize, + pub permissions: Vec, +} + +pub fn user(u: &User) -> Vec { + let mut img = canvas(u.accent); + let band = 150; + match &u.banner { + Some(b) => banner_strip(&mut img, b, band as u32), + None => tint(&mut img, (0, 0, W, band), 0, [255, 255, 255], 0.08), + } + let (size, x, y) = (136, PAD, band - 72); + let ring = *img.get_pixel(0, 240); // the backdrop's colour, to lift the avatar off the banner + pix::rounded_rect(&mut img, x - 6, y - 6, size + 12, size + 12, (size + 12) / 2, ring); + match &u.avatar { + Some(a) => blit(&mut img, &rounded_cover(a, size as u32, size as f32 / 2.0), x, y, (0, 0, W, 1000)), + None => pix::rounded_rect(&mut img, x, y, size, size, size / 2, Rgba([60, 60, 66, 255])), + } + if let Some((_, colour)) = u.status { + pix::rounded_rect(&mut img, x + size - 40, y + size - 40, 36, 36, 18, ring); + pix::rounded_rect(&mut img, x + size - 34, y + size - 34, 24, 24, 12, Rgba([colour[0], colour[1], colour[2], 255])); + } + let tx = x + size + 24; + line(&mut img, &u.name, (tx, band + 12), 30.0, true, INK, W - tx - PAD); + line(&mut img, &u.handle, (tx, band + 52), 18.0, false, SOFT, W - tx - PAD); + let mut bottom = tile_grid(&mut img, band + 96, 2, &u.tiles); + if !u.roles.is_empty() { + line(&mut img, &format!("Roles · {}", u.roles.len() + u.more_roles), (PAD, bottom + 16), 15.0, false, SOFT, 300); + let mut items = u.roles.clone(); + if u.more_roles > 0 { + items.push((format!("{} more", u.more_roles), None)); + } + bottom = chips(&mut img, bottom + 42, &items); + } + if !u.permissions.is_empty() { + line(&mut img, "Key permissions", (PAD, bottom + 16), 15.0, false, SOFT, 300); + let items: Vec<_> = u.permissions.iter().map(|p| (p.clone(), None)).collect(); + bottom = chips(&mut img, bottom + 42, &items); + } + finish(&img, bottom) +} + +// ---- server -------------------------------------------------------------------------------------------------------- + +pub struct Server { + pub accent: u32, + pub name: String, + pub description: Option, + pub icon: Option, + pub banner: Option, + pub members: u64, + pub bots: u64, + pub online: u64, + pub tier: u8, + pub boosts: u64, + pub boosters: u64, + pub tiles: Vec<(String, String)>, + pub features: Vec, +} + +/// The boosts each level needs. +const LEVELS: [u64; 4] = [0, 2, 7, 14]; + +pub fn server(s: &Server) -> Vec { + let mut img = canvas(s.accent); + let mut y = PAD; + if let Some(b) = &s.banner { + banner_strip(&mut img, b, 140); + y = 164; + } + let size = 96; + match &s.icon { + Some(i) => blit(&mut img, &rounded_cover(i, size as u32, 20.0), PAD, y, (0, 0, W, 1000)), + None => { + tint(&mut img, (PAD, y, size, size), 20, [255, 255, 255], 0.12); + let letters: String = s.name.split_whitespace().filter_map(|w| w.chars().next()).take(3).collect(); + crate::cardart::line_centre(&mut img, &letters, (PAD + size / 2, y + 30), 28.0, true, INK); + } + } + let tx = PAD + size + 20; + line(&mut img, &s.name, (tx, y + 4), 30.0, true, INK, W - tx - PAD); + let mut bottom = y + size; + if let Some(d) = s.description.as_deref().filter(|d| !d.is_empty()) { + bottom = bottom.max(paragraph(&mut img, d, (tx, y + 46), 16.0, SOFT, W - tx - PAD, 2)); + } else { + line(&mut img, &format!("{} members", thousands(s.members)), (tx, y + 46), 17.0, false, SOFT, W - tx - PAD); + } + + // two big blocks: who's here, and the boost level + let top = bottom + 16; + let width = (W - 2 * PAD - 8) / 2; + tint(&mut img, (PAD, top, width, 124), 10, [255, 255, 255], 0.1); + line(&mut img, "Members", (PAD + 14, top + 10), 15.0, false, SOFT, 200); + line(&mut img, &thousands(s.members), (PAD + 14, top + 32), 34.0, true, INK, width - 28); + let people = s.members.saturating_sub(s.bots); + meter(&mut img, (PAD + 14, top + 82, width - 28, 8), s.online as f32 / s.members.max(1) as f32, [76, 195, 138]); + line(&mut img, &format!("{} online · {} people · {} bots", thousands(s.online), thousands(people), thousands(s.bots)), (PAD + 14, top + 96), 14.0, false, SOFT, width - 28); + + let x = PAD + width + 8; + tint(&mut img, (x, top, width, 124), 10, [255, 255, 255], 0.1); + line(&mut img, "Boosts", (x + 14, top + 10), 15.0, false, SOFT, 200); + line(&mut img, &format!("Level {}", s.tier), (x + 14, top + 32), 34.0, true, INK, width - 28); + let (low, high) = (LEVELS[s.tier.min(3) as usize], LEVELS[(s.tier.min(2) + 1) as usize]); + let share = if s.tier >= 3 { 1.0 } else { s.boosts.saturating_sub(low) as f32 / (high - low) as f32 }; + meter(&mut img, (x + 14, top + 82, width - 28, 8), share, [244, 127, 255]); + let next = if s.tier >= 3 { "Top level".to_string() } else { format!("{} of {high} for level {}", s.boosts, s.tier + 1) }; + line(&mut img, &format!("{} boosters · {next}", s.boosters), (x + 14, top + 96), 14.0, false, SOFT, width - 28); + + bottom = tile_grid(&mut img, top + 124 + 8, 4, &s.tiles); + if !s.features.is_empty() { + let items: Vec<_> = s.features.iter().map(|f| (f.clone(), None)).collect(); + bottom = chips(&mut img, bottom + 12, &items); + } + finish(&img, bottom) +} + +// ---- channel ------------------------------------------------------------------------------------------------------- + +pub struct Channel { + pub accent: u32, + pub symbol: &'static str, + pub name: String, + pub kind: String, + pub topic: Option, + pub tiles: Vec<(String, String)>, + /// Who's in a voice channel right now. + pub inside: Vec, +} + +pub fn channel(c: &Channel) -> Vec { + let mut img = canvas(c.accent); + tint(&mut img, (PAD, PAD, 88, 88), 16, [255, 255, 255], 0.14); + if c.symbol.is_ascii() { + crate::cardart::line_centre(&mut img, c.symbol, (PAD + 44, PAD + 14), 46.0, true, INK); + } else { + blit(&mut img, &sprite(c.symbol, 64), PAD + 12, PAD + 12, (0, 0, W, 1000)); + } + let tx = PAD + 88 + 20; + line(&mut img, &c.name, (tx, PAD + 6), 30.0, true, INK, W - tx - PAD); + line(&mut img, &c.kind, (tx, PAD + 50), 18.0, false, SOFT, W - tx - PAD); + let mut bottom = PAD + 88; + if let Some(t) = c.topic.as_deref().filter(|t| !t.is_empty()) { + line(&mut img, "Topic", (PAD, bottom + 16), 15.0, false, SOFT, 200); + bottom = paragraph(&mut img, t, (PAD, bottom + 38), 17.0, INK, W - 2 * PAD, 4); + } + bottom = tile_grid(&mut img, bottom + 16, 3, &c.tiles); + if !c.inside.is_empty() { + line(&mut img, &format!("In voice · {}", c.inside.len()), (PAD, bottom + 16), 15.0, false, SOFT, 300); + let items: Vec<_> = c.inside.iter().map(|n| (n.clone(), Some([76, 195, 138]))).collect(); + bottom = chips(&mut img, bottom + 42, &items); + } + finish(&img, bottom) +} + +/// The colour and symbol for each kind of channel. +pub fn channel_look(kind: &str) -> (u32, &'static str, &'static str) { + match kind { + "GuildVoice" => (0x1E9664, "🔊", "Voice channel"), + "GuildStageVoice" => (0x7A4FD0, "🎙️", "Stage channel"), + "GuildAnnouncement" => (0xC8701E, "📣", "Announcement channel"), + "GuildCategory" => (0x6C7480, "📁", "Category"), + "GuildForum" => (0x1E8C96, "💬", "Forum"), + "PublicThread" | "PrivateThread" | "AnnouncementThread" => (0xB44696, "🧵", "Thread"), + _ => (0x2C6EC8, "#", "Text channel"), + } +} + +// ---- role ---------------------------------------------------------------------------------------------------------- + +pub struct Role { + pub accent: u32, + pub name: String, + pub icon: Option, + pub tiles: Vec<(String, String)>, + pub permissions: Vec, +} + +pub fn role(r: &Role) -> Vec { + let mut img = canvas(if r.accent == 0 { 0x6C7480 } else { r.accent }); + let colour = [(r.accent >> 16) as u8, (r.accent >> 8) as u8, r.accent as u8]; + match &r.icon { + Some(i) => blit(&mut img, &rounded_cover(i, 88, 16.0), PAD, PAD, (0, 0, W, 1000)), + None => { + tint(&mut img, (PAD, PAD, 88, 88), 16, [255, 255, 255], 0.14); + pix::rounded_rect(&mut img, PAD + 20, PAD + 20, 48, 48, 24, Rgba([colour[0], colour[1], colour[2], 255])); + } + } + let tx = PAD + 88 + 20; + line(&mut img, &r.name, (tx, PAD + 6), 30.0, true, INK, W - tx - PAD); + line(&mut img, "Role", (tx, PAD + 50), 18.0, false, SOFT, 200); + let mut bottom = tile_grid(&mut img, PAD + 88 + 16, 3, &r.tiles); + line(&mut img, "Permissions", (PAD, bottom + 16), 15.0, false, SOFT, 300); + if r.permissions.is_empty() { + line(&mut img, "None beyond @everyone", (PAD, bottom + 40), 17.0, false, INK, 400); + bottom += 64; + } else { + let items: Vec<_> = r.permissions.iter().map(|p| (p.clone(), None)).collect(); + bottom = chips(&mut img, bottom + 42, &items); + } + finish(&img, bottom) +} + +#[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_info_{name}.png")), bytes).unwrap(); + } + } + + #[test] + fn all_four_cards_draw() { + let art = RgbaImage::from_fn(300, 300, |x, y| Rgba([(x / 2) as u8 + 60, 90, (y / 2) as u8 + 80, 255])); + let wide = RgbaImage::from_fn(600, 240, |x, _| Rgba([200 - (x / 4) as u8, 120, (x / 4) as u8 + 60, 255])); + let u = user(&User { accent: 0x8A3FB4, name: "Mira".into(), handle: "@mira".into(), avatar: Some(art.clone()), banner: Some(wide.clone()), status: Some(("Online", [76, 195, 138])), + tiles: tiles(&[("Account created", when(1_500_000_000)), ("Joined", when(1_700_000_000)), ("Top role", "Moderator".into()), ("Activity", "Listening to Spotify".into())]), + roles: vec![("Moderator".into(), Some([46, 120, 240])), ("DJ".into(), Some([182, 87, 208])), ("Member".into(), None), ("Night shift".into(), Some([60, 190, 130]))], more_roles: 2, + permissions: vec!["Kick Members".into(), "Ban Members".into(), "Manage Messages".into()] }); + dump("user", &u); + let s = server(&Server { accent: 0x2A7FB4, name: "Night Shift".into(), description: Some("A place for people who are awake at the wrong time.".into()), icon: Some(art.clone()), banner: None, members: 412, bots: 6, online: 96, tier: 2, boosts: 9, boosters: 6, + tiles: tiles(&[("Text", "24".into()), ("Voice", "6".into()), ("Categories", "5".into()), ("Roles", "18".into()), ("Emojis", "41 of 150".into()), ("Stickers", "3 of 30".into()), ("Owner", "Rowan".into()), ("Created", date(1_600_000_000))]), features: vec!["Community".into(), "Banner".into()] }); + dump("server", &s); + let (accent, symbol, kind) = channel_look("GuildVoice"); + let c = channel(&Channel { accent, symbol, name: "Music".into(), kind: kind.into(), topic: None, tiles: tiles(&[("Created", when(1_600_000_000)), ("Category", "Hangout".into()), ("Bitrate", "96 kbps".into()), ("User limit", "None".into()), ("Region", "Automatic".into()), ("Everyone can", "View, connect".into())]), inside: vec!["Mira".into(), "Rowan".into(), "Dezio".into()] }); + dump("channel", &c); + let (accent, symbol, kind) = channel_look("GuildText"); + let t = channel(&Channel { accent, symbol, name: "general".into(), kind: kind.into(), topic: Some("Say hi, share what you're listening to, and keep it kind. ".repeat(6)), tiles: tiles(&[("Created", when(1_600_000_000)), ("Category", "Hangout".into()), ("Slowmode", "Off".into()), ("Age restricted", "No".into()), ("Everyone can", "View, send".into())]), inside: vec![] }); + dump("text", &t); + let r = role(&Role { accent: 0x2E78F0, name: "Moderator".into(), icon: None, tiles: tiles(&[("Members", "6".into()), ("Position", "3 of 18".into()), ("Colour", "#2E78F0".into()), ("Created", when(1_600_000_000)), ("Shown separately", "Yes".into()), ("Mentionable", "No".into())]), permissions: vec!["Kick Members".into(), "Ban Members".into(), "Manage Messages".into(), "Moderate Members".into()] }); + dump("role", &r); + assert!(u.len() > 1000 && s.len() > 1000 && c.len() > 1000 && r.len() > 1000); + } + + #[test] + fn every_kind_of_channel_has_its_own_look() { + let kinds = ["GuildVoice", "GuildStageVoice", "GuildAnnouncement", "GuildCategory", "GuildForum", "PublicThread", "GuildText"]; + let colours: std::collections::HashSet = kinds.iter().map(|k| channel_look(k).0).collect(); + assert_eq!(colours.len(), kinds.len()); + } +} diff --git a/src/commands/lastfm/art.rs b/src/commands/lastfm/art.rs index 27a5f29..0587528 100644 --- a/src/commands/lastfm/art.rs +++ b/src/commands/lastfm/art.rs @@ -1,8 +1,6 @@ //! Last.fm's pictures, coloured from the album art so every song looks like itself. -use crate::cardart::{blit, gradient, line, line_right, png, rounded_cover, tint}; -use crate::converters::thousands; +use crate::cardart::{blit, gradient, line, png, rounded_cover, tint, wash}; use image::RgbaImage; -use std::sync::Arc; pub const FILE: &str = "lastfm.png"; @@ -11,14 +9,6 @@ const PAD: i32 = 28; const INK: [u8; 3] = [250, 250, 248]; const SOFT: [u8; 3] = [214, 214, 220]; -/// The card's two backdrop colours from the album's colour: rich at the top, deep at the bottom. -fn wash(accent: u32) -> ([u8; 3], [u8; 3]) { - let c = [(accent >> 16) as u8, (accent >> 8) as u8, accent as u8].map(f32::from); - let high = c[0].max(c[1]).max(c[2]).max(1.0); - let full = c.map(|v| v * 200.0 / high); - (full.map(|v| (v * 0.5) as u8), full.map(|v| (v * 0.14) as u8)) -} - pub struct Now { pub status: String, pub title: String, @@ -61,63 +51,19 @@ pub fn now_playing(n: &Now) -> Vec { png(&img) } -pub struct Row { - pub rank: usize, - pub name: String, - pub by: Option, - pub plays: u64, -} - -pub struct Chart { - pub title: String, - pub note: String, - pub accent: u32, - pub rows: Vec, - /// The biggest play count of the whole list, so bars keep their scale across pages. - pub top: u64, - pub cover: Option>, - pub empty: String, -} - -pub fn chart(c: &Chart) -> Vec { - let row_h = 48; - let height = 104 + row_h * c.rows.len().max(1) as i32 + 16; - let (top, bottom) = wash(c.accent); - let mut img = gradient(W as u32, height as u32, top, bottom); - line(&mut img, &c.title, (PAD, 24), 28.0, true, INK, W - 2 * PAD - 96); - line(&mut img, &c.note, (PAD, 62), 18.0, false, SOFT, W - 2 * PAD - 96); - if let Some(a) = &c.cover { - blit(&mut img, &rounded_cover(a, 72, 8.0), W - PAD - 72, 20, (0, 0, W, height)); - } - if c.rows.is_empty() { - line(&mut img, &c.empty, (PAD, 112), 18.0, false, SOFT, W - 2 * PAD); - } - let fill = wash(c.accent).0.map(|v| v.saturating_mul(2).max(70)); - for (i, row) in c.rows.iter().enumerate() { - let y = 104 + i as i32 * row_h; - let (bar_x, bar_w) = (PAD + 44, W - 2 * PAD - 44); - let share = (row.plays as f32 / c.top.max(1) as f32).clamp(0.02, 1.0); - tint(&mut img, (bar_x, y, bar_w, row_h - 6), 6, [255, 255, 255], 0.06); - tint(&mut img, (bar_x, y, (bar_w as f32 * share) as i32, row_h - 6), 6, fill, 0.8); - line_right(&mut img, &row.rank.to_string(), (PAD + 30, y + 9), 19.0, true, if row.rank == 1 { [255, 214, 110] } else { SOFT }); - let label = row.by.as_ref().map_or(row.name.clone(), |b| format!("{} · {b}", row.name)); - line(&mut img, &label, (bar_x + 12, y + 10), 18.0, row.rank <= 3, INK, bar_w - 130); - line_right(&mut img, &format!("{} plays", thousands(row.plays)), (bar_x + bar_w - 12, y + 12), 15.0, false, INK); - } - png(&img) -} - #[cfg(test)] mod tests { use super::*; + use crate::cardart::{chart, Chart, Row}; use image::Rgba; + use std::sync::Arc; #[test] fn both_pictures_draw_with_the_album_colour() { let art = RgbaImage::from_fn(300, 300, |x, y| Rgba([180, (x / 2) as u8, (y / 3) as u8, 255])); let now = now_playing(&Now { status: "Now playing · nightowl".into(), title: "Slow Drive Home".into(), artist: "Marlow Reed".into(), album: Some("Rear View".into()), accent: 0xB4502A, cover: Some(art.clone()), stats: vec![("Scrobbles".into(), "48,210".into()), ("Plays of this track".into(), "37".into())], previous: Some("Paper Lanterns by The Quiet Hours".into()) }); - let rows = (0..10).map(|i| Row { rank: i + 1, name: format!("Artist name {i}"), by: (i % 2 == 0).then(|| "Someone".to_string()), plays: 900 - i as u64 * 80 }).collect(); - let top = chart(&Chart { title: "Top albums · nightowl".into(), note: "Last 30 days".into(), accent: 0x2A7FB4, rows, top: 900, cover: Some(Arc::new(art)), empty: String::new() }); + let rows = (0..10).map(|i| Row { rank: i + 1, name: format!("Artist name {i}"), by: (i % 2 == 0).then(|| "Someone".to_string()), share: 1.0 - i as f32 * 0.09, value: format!("{} plays", 900 - i * 80) }).collect(); + let top = chart(&Chart { title: "Top albums · nightowl".into(), note: "Last 30 days".into(), accent: 0x2A7FB4, rows, cover: Some(Arc::new(art)), empty: String::new() }); if std::env::var("DEZIO_DUMP").is_ok() { std::fs::write(std::env::temp_dir().join("dezio_fm_now.png"), &now).unwrap(); std::fs::write(std::env::temp_dir().join("dezio_fm_top.png"), &top).unwrap(); diff --git a/src/commands/lastfm/extras.rs b/src/commands/lastfm/extras.rs index 1e4bd62..b51a344 100644 --- a/src/commands/lastfm/extras.rs +++ b/src/commands/lastfm/extras.rs @@ -95,11 +95,11 @@ pub async fn cover_for(state: &State, kind: &str, item: &Value) -> Option, kind: &str, name: &str, artist: Option<&str>) -> Component { +async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist: Option<&str>) -> (Component, Option>) { let guild = ctx.guild_id.unwrap(); let members: Vec<(u64, String)> = all_links().into_iter().filter(|(u, _)| twilight_model::id::Id::new_checked(*u).is_some_and(|id| ctx.state.cache.member(guild, id).is_some())).collect(); if members.is_empty() { - return Card::new(Some(RED)).text("### ❌ No linked accounts\nNo one in this server has linked Last.fm yet.").build(); + return (Card::new(Some(RED)).text("### ❌ No linked accounts\nNo one in this server has linked Last.fm yet.").build(), None); } let results = futures::future::join_all(members.iter().map(|(u, un)| async move { match api.entity(kind, name, artist, Some(un)).await { @@ -112,7 +112,7 @@ async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist } })) .await; - let Some(entity) = results.iter().find_map(|r| r.2.clone()) else { return Card::new(Some(RED)).text(&format!("### ❌ Not found\nLast.fm doesn't know that {kind}.")).build() }; + let Some(entity) = results.iter().find_map(|r| r.2.clone()) else { return (Card::new(Some(RED)).text(&format!("### ❌ Not found\nLast.fm doesn't know that {kind}.")).build(), None) }; let mut listeners: Vec<(u64, u64)> = results.iter().filter(|r| r.1 > 0).map(|r| (r.0, r.1)).collect(); listeners.sort_by_key(|l| std::cmp::Reverse(l.1)); let display = entity["name"].as_str().unwrap_or(name).to_string(); @@ -122,21 +122,33 @@ async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist "album" => best_image(&entity["image"]), _ => best_image(&entity["album"]["image"]), }; - let medals = ["🥇", "🥈", "🥉"]; - let lines: Vec = listeners.iter().take(15).enumerate().map(|(i, (u, c))| format!("{} <@{u}> — **{}** plays", medals.get(i).map_or(format!("`{}.`", i + 1), |m| m.to_string()), crate::converters::thousands(*c))).collect(); let guild_name = ctx.state.cache.guild(guild).map(|g| g.name().to_string()).unwrap_or_default(); - let subtitle = match &entity_artist { - Some(a) => format!("by **{}**", escape(a)), - None => format!("in {}", escape(&guild_name)), - }; let accent = colors::accent(&ctx.state, image.as_deref(), GREEN).await; let total: u64 = listeners.iter().map(|l| l.1).sum(); - Card::new(Some(accent)) - .header(&[&format!("-# 🏆 Who knows this {kind}?"), &format!("### {}\n{subtitle}", link(&truncate(&display, 90), entity["url"].as_str()))], image.as_deref()) - .separator(true, false) - .text(&if lines.is_empty() { "*No one here has played this yet.*".to_string() } else { lines.join("\n") }) + let most = listeners.first().map_or(1, |l| l.1); + let mut rows = Vec::new(); + for (i, (u, plays)) in listeners.iter().take(15).enumerate() { + let name = match twilight_model::id::Id::new_checked(*u) { + Some(id) => crate::commands::info::display_name_of(&ctx.state, Some(guild), id).await, + None => "Someone".to_string(), + }; + rows.push(crate::cardart::Row { rank: i + 1, name, by: None, share: *plays as f32 / most as f32, value: format!("{} plays", crate::converters::thousands(*plays)) }); + } + let cover = match &image { + Some(url) => crate::commands::media::fetch_picture(&ctx.state, url).await.map(Arc::new), + None => None, + }; + let note = match &entity_artist { + Some(a) => format!("by {a} · in {guild_name}"), + None => format!("in {guild_name}"), + }; + let picture = crate::cardart::chart(&crate::cardart::Chart { title: display.clone(), note, accent, rows, cover, empty: "No one here has played this yet".to_string() }); + let card = Card::new(Some(accent)) + .text(&format!("-# 🏆 Who knows this {kind}? {}", link(&truncate(&display, 90), entity["url"].as_str()))) + .gallery(&[&format!("attachment://{}", super::art::FILE)]) .footer(&format!("{} listener{} · {} plays · {} linked members", listeners.len(), if listeners.len() != 1 { "s" } else { "" }, crate::converters::thousands(total), members.len())) - .build() + .build(); + (card, Some(picture)) } async fn run_whoknows(ctx: &Arc, kind: &str, query: Option<&str>) -> Result<()> { @@ -171,7 +183,10 @@ async fn run_whoknows(ctx: &Arc, kind: &str, query: Option<&str>) -> Result let example = match kind { "artist" => "Artist", "track" => "Artist - Track", _ => "Artist - Album" }; return super::error(ctx, &format!("Tell me what to look up (`{example}`) or play something first.")).await; }; - ctx.reply(whoknows_card(ctx, &api, kind, &n, artist.as_deref()).await).await + match whoknows_card(ctx, &api, kind, &n, artist.as_deref()).await { + (card, Some(picture)) => ctx.reply_file(card, super::art::FILE, picture).await, + (card, None) => ctx.reply(card).await, + } } async fn wk(ctx: Arc) -> Result<()> { diff --git a/src/commands/lastfm/views.rs b/src/commands/lastfm/views.rs index 386570a..87d9e17 100644 --- a/src/commands/lastfm/views.rs +++ b/src/commands/lastfm/views.rs @@ -2,6 +2,7 @@ use super::super::games::{btn, Game, Rendered, Reply}; use super::api::{as_list, best_image, fm_url, track_from_url, Error, Lfm}; use super::{link, period_label, PERIODS, PLAYING_EMOJI}; +use crate::cardart::{chart, Chart, Row}; use crate::colors; use crate::converters::thousands; use crate::state::State; @@ -172,17 +173,18 @@ impl Game for Top { fn render(&self, t: u32) -> Rendered { let top = self.items.first().map_or(1, |i| num(i, "playcount")); - let rows: Vec = self.items.iter().enumerate().skip(self.page * PER_PAGE).take(PER_PAGE).map(|(idx, item)| super::art::Row { + let rows: Vec = self.items.iter().enumerate().skip(self.page * PER_PAGE).take(PER_PAGE).map(|(idx, item)| Row { rank: idx + 1, name: item["name"].as_str().unwrap_or("?").to_string(), by: (self.kind != "artists").then(|| item["artist"]["name"].as_str().unwrap_or("?").to_string()), - plays: num(item, "playcount"), + share: num(item, "playcount") as f32 / top.max(1) as f32, + value: format!("{} plays", thousands(num(item, "playcount"))), }).collect(); let mut footer = if self.total > 0 { format!("{} {} in this period", thousands(self.total), self.kind) } else { String::new() }; if self.pages() > 1 { footer.push_str(&format!("{}page {}/{}", if footer.is_empty() { "" } else { " · " }, self.page + 1, self.pages())); } - let bytes = super::art::chart(&super::art::Chart { title: format!("Top {} · {}", self.kind, self.b.username), note: period_label(&self.period).to_string(), accent: self.accent, rows, top, cover: self.cover.clone(), empty: format!("No {} scrobbled in this period", self.kind) }); + let bytes = chart(&Chart { title: format!("Top {} · {}", self.kind, self.b.username), note: period_label(&self.period).to_string(), accent: self.accent, rows, cover: self.cover.clone(), empty: format!("No {} scrobbled in this period", self.kind) }); let mut card = Card::new(Some(self.accent)).gallery(&[&format!("attachment://{}", super::art::FILE)]); if !footer.is_empty() { card = card.footer(&footer); diff --git a/src/commands/media/mod.rs b/src/commands/media/mod.rs index 4f60488..04a58a6 100644 --- a/src/commands/media/mod.rs +++ b/src/commands/media/mod.rs @@ -65,6 +65,12 @@ pub async fn fetch_limited(state: &State, url: &str, max: usize) -> Option Option { + let bytes = fetch_limited(state, url, 4 * 1024 * 1024).await?; + tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten() +} + /// A user's avatar picture (animated ones as GIF). Looks the user up if we haven't seen them. pub async fn avatar(state: &State, user: Id, size: u32) -> String { let hash = match state.cache.user(user) { diff --git a/src/commands/mod.rs b/src/commands/mod.rs index a74b2e3..bce4a76 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 info_art; pub mod lastfm; pub mod logs; pub mod media; diff --git a/src/pager.rs b/src/pager.rs index cbaa675..64e3cb9 100644 --- a/src/pager.rs +++ b/src/pager.rs @@ -15,10 +15,13 @@ use twilight_model::application::interaction::{Interaction, InteractionData}; use twilight_model::channel::message::component::{ButtonStyle, Component}; pub type Page = Arc Card + Send + Sync>; +/// Draws the picture for one page. +pub type Art = Arc Vec + Send + Sync>; struct Pager { owner: u64, pages: Vec, + art: Option<(String, Art)>, expires: Instant, } @@ -60,13 +63,17 @@ pub fn render(token: &str, pages: &[Page], index: usize) -> Component { /// Keep `pages` for the buttons and give back the first page's card. pub fn register(owner: u64, pages: Vec, ttl: Duration) -> Component { + keep(owner, pages, None, ttl) +} + +fn keep(owner: u64, pages: Vec, art: Option<(String, Art)>, ttl: Duration) -> Component { let tok = token(); let first = render(&tok, &pages, 0); if pages.len() > 1 { let mut all = pagers().lock().unwrap(); let now = Instant::now(); all.retain(|_, p| p.expires > now); - all.insert(tok, Pager { owner, pages, expires: now + ttl }); + all.insert(tok, Pager { owner, pages, art, expires: now + ttl }); } first } @@ -76,17 +83,28 @@ pub async fn start(ctx: &Ctx, pages: Vec, ttl: Duration) -> Result<()> { ctx.reply(register(ctx.user_id.get(), pages, ttl)).await } +/// The same for pages whose cards show a drawn picture, `attachment://`. +pub async fn start_drawn(ctx: &Ctx, pages: Vec, ttl: Duration, name: &str, art: Art) -> Result<()> { + let first = art(0); + ctx.reply_file(keep(ctx.user_id.get(), pages, Some((name.to_string(), art)), ttl), name, first).await +} + pub async fn on_component(state: &Arc, i: &Interaction) { let Some(InteractionData::MessageComponent(d)) = i.data.as_ref() else { return }; let mut p = d.custom_id.split(':').skip(1); let (Some(tok), Some(to)) = (p.next(), p.next().and_then(|s| s.parse::().ok())) else { return }; let Some(user) = i.author() else { return }; - let found = pagers().lock().unwrap().get(tok).map(|p| (p.owner, p.pages.clone(), p.expires)); + let found = pagers().lock().unwrap().get(tok).map(|p| (p.owner, p.pages.clone(), p.art.clone(), p.expires)); match found { - Some((_, _, expires)) if expires < Instant::now() => interact::private_text(state, i, "These pages expired — run the command again.").await, + Some((_, _, _, expires)) if expires < Instant::now() => interact::private_text(state, i, "These pages expired — run the command again.").await, None => interact::private_text(state, i, "These pages expired — run the command again.").await, - Some((owner, _, _)) if owner != user.id.get() => interact::private_text(state, i, "These buttons belong to someone else.").await, - Some((_, pages, _)) => interact::update(state, i, render(tok, &pages, to)).await, + Some((owner, _, _, _)) if owner != user.id.get() => interact::private_text(state, i, "These buttons belong to someone else.").await, + Some((_, pages, Some((name, art)), _)) => { + interact::ack(state, i).await; // the picture has to be uploaded, which a direct reply can't carry + let bytes = tokio::task::spawn_blocking(move || art(to)).await.unwrap_or_default(); + interact::edit_with_file(state, i, render(tok, &pages, to), &name, bytes).await; + } + Some((_, pages, None, _)) => interact::update(state, i, render(tok, &pages, to)).await, } }