Colourful drawn weather, Last.fm and wallet cards
Weather gets a sky that follows the conditions, detail tiles, a 24-hour chart and 5-day ranges, without ever showing the place. /fm now playing and top charts are coloured from the album art, and the wallet shows the stats. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
466e522cd3
commit
32a4e41c2c
11 changed files with 551 additions and 103 deletions
|
|
@ -108,3 +108,11 @@ Plan (backward compatible with the existing file):
|
|||
- Music panel: an animated GIF drawn by `commands/music/card.rs`, laid out like the website's player: cover and title, moving bars, clock and progress. Each GIF is 30 s at 20 fps, storing only changed pixels and is replaced about every 20 s while people listen, its clock started ahead by the measured upload time; a new panel posts a still JPEG first, and paused stays still. Bar heights follow the song's real loudness (`source::peaks`), their shape is drawn, not a real spectrum. Bar colours come from the album cover (greys for a cover with no colour). Typed searches go to YouTube Music for the real artist, album, year and square art, falling back to plain YouTube; links keep their own details. Without Attach Files the panel falls back to the text card. The 🔗 button shows the song's link to whoever pressed it, privately.
|
||||
- Voice: a failed join now forgets the call, and a song whose position stands still for 45 s tells the channel and leaves. Joins failed on 2026-11-06 because the Chromebook's network gives an IPv6 address with no IPv6 route; /etc/gai.conf now prefers IPv4 (backup /root/gai.conf.bak-2026-11-06). A running bot only picks that up after a restart.
|
||||
- Known gap, unchanged: on a stage channel the bot can't unsuppress itself (twilight's `suppress()` only sets true).
|
||||
|
||||
## Drawn cards and Dezio's own emojis (2026-11-06)
|
||||
- `cardart.rs` is the shared kit (text, backdrops, tiles, GIFs that store only changed pixels). Colour follows the content: blackjack on green felt, slots in wine red, weather skies by condition, Last.fm from the album art, dark only where it suits, like the music player.
|
||||
- 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.
|
||||
- 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).
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use color_quant::NeuQuant;
|
|||
use cosmic_text::Align;
|
||||
use image::{Rgba, RgbaImage};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
pub const WIDTH: u32 = 800;
|
||||
pub const HEIGHT: u32 = 384;
|
||||
|
|
@ -124,3 +125,72 @@ pub fn gif(samples: &[&RgbaImage], frames: impl Iterator<Item = RgbaImage>, dela
|
|||
drop(encoder);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
const WHITE: [u8; 3] = [245, 245, 240];
|
||||
|
||||
/// A colour emoji as a picture, drawn once.
|
||||
pub fn sprite(emoji: &str, size: u32) -> RgbaImage {
|
||||
static SEEN: OnceLock<Mutex<HashMap<(String, u32), RgbaImage>>> = OnceLock::new();
|
||||
let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
|
||||
seen.entry((emoji.to_string(), size))
|
||||
.or_insert_with(|| {
|
||||
let mut img = RgbaImage::from_pixel(size, size, Rgba([0, 0, 0, 0]));
|
||||
let para = text::layout(emoji, size as f32 * 0.72, &text::Look::new(None, false, WHITE), None, Align::Left);
|
||||
para.draw(&mut img, (size as f32 - para.width) as i32 / 2, (size as f32 - para.height) as i32 / 2);
|
||||
img
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Lay `colour` over a rounded rectangle at the given strength (0..1), for tiles on a coloured backdrop.
|
||||
pub fn tint(img: &mut RgbaImage, (x, y, w, h): (i32, i32, i32, i32), radius: i32, colour: [u8; 3], strength: f32) {
|
||||
for py in y.max(0)..(y + h).min(img.height() as i32) {
|
||||
for px in x.max(0)..(x + w).min(img.width() as i32) {
|
||||
let (dx, dy) = ((px - x).min(x + w - 1 - px), (py - y).min(y + h - 1 - py));
|
||||
if dx < radius && dy < radius && (radius - dx - 1).pow(2) + (radius - dy - 1).pow(2) > radius * radius {
|
||||
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) + colour[i] as f32 * strength).round() as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A round-capped line, for charts.
|
||||
pub fn stroke(img: &mut RgbaImage, (x0, y0): (f32, f32), (x1, y1): (f32, f32), radius: f32, colour: [u8; 3]) {
|
||||
let steps = ((x1 - x0).abs().max((y1 - y0).abs()).ceil() as usize).max(1);
|
||||
for s in 0..=steps {
|
||||
let t = s as f32 / steps as f32;
|
||||
let (cx, cy) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
|
||||
let r = radius.ceil() as i32 + 1;
|
||||
for py in cy as i32 - r..=cy as i32 + r {
|
||||
for px in cx as i32 - r..=cx as i32 + r {
|
||||
if px < 0 || py < 0 || px >= img.width() as i32 || py >= img.height() as i32 {
|
||||
continue;
|
||||
}
|
||||
let d = ((px as f32 + 0.5 - cx).powi(2) + (py as f32 + 0.5 - cy).powi(2)).sqrt();
|
||||
let cover = (radius + 0.5 - d).clamp(0.0, 1.0);
|
||||
if cover > 0.0 {
|
||||
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 - cover) + colour[i] as f32 * cover).round() as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cover or avatar cut to a square with soft rounded corners.
|
||||
pub fn rounded_cover(art: &RgbaImage, size: u32, radius: f32) -> RgbaImage {
|
||||
let mut square = pix::cover(art, size, size);
|
||||
let s = size as f32;
|
||||
pix::fade_alpha(&mut square, |x, y| {
|
||||
let dx = (radius - (x as f32 + 0.5)).max((x as f32 + 0.5) - (s - radius)).max(0.0);
|
||||
let dy = (radius - (y as f32 + 0.5)).max((y as f32 + 0.5) - (s - radius)).max(0.0);
|
||||
radius + 0.5 - (dx * dx + dy * dy).sqrt()
|
||||
});
|
||||
square
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,9 @@
|
|||
//! The casino's pictures. Spins are GIFs that play once and land on the real result; the same final frame is then drawn
|
||||
//! as a still, with the buttons back underneath.
|
||||
use crate::cardart::{blit, gif, line, line_centre, line_right, png, rgba, scene, Scene, HEIGHT, PAD, WIDTH};
|
||||
use crate::{pix, text};
|
||||
use cosmic_text::Align;
|
||||
use crate::cardart::{blit, gif, gradient, line, line_centre, line_right, png, rgba, rounded_cover, scene, sprite, tint, Scene, HEIGHT, PAD, WIDTH};
|
||||
use crate::pix;
|
||||
use image::{Rgba, RgbaImage};
|
||||
use std::collections::HashMap;
|
||||
use std::f32::consts::{PI, TAU};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
pub const STILL: &str = "casino.png";
|
||||
pub const MOVING: &str = "casino.gif";
|
||||
|
|
@ -27,20 +24,6 @@ fn frames_for(seconds: f64) -> usize {
|
|||
(seconds * 100.0 / FRAME_DELAY as f64) as usize
|
||||
}
|
||||
|
||||
/// A colour emoji as a picture, drawn once.
|
||||
fn sprite(emoji: &str, size: u32) -> RgbaImage {
|
||||
static SEEN: OnceLock<Mutex<HashMap<(String, u32), RgbaImage>>> = OnceLock::new();
|
||||
let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
|
||||
seen.entry((emoji.to_string(), size))
|
||||
.or_insert_with(|| {
|
||||
let mut img = RgbaImage::from_pixel(size, size, Rgba([0, 0, 0, 0]));
|
||||
let para = text::layout(emoji, size as f32 * 0.72, &text::Look::new(None, false, WHITE), None, Align::Left);
|
||||
para.draw(&mut img, (size as f32 - para.width) as i32 / 2, (size as f32 - para.height) as i32 / 2);
|
||||
img
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
// ---- blackjack ---------------------------------------------------------------------------------------------------
|
||||
|
||||
const CARD_W: u32 = 92;
|
||||
|
|
@ -313,10 +296,40 @@ pub fn wheel_spin(number: u32, note: &str, odds: &[(&str, &str)], money: &Money)
|
|||
}
|
||||
|
||||
|
||||
// ---- wallet --------------------------------------------------------------------------------------------------------
|
||||
|
||||
pub struct Wallet<'a> {
|
||||
pub name: &'a str,
|
||||
pub balance: String,
|
||||
pub avatar: Option<RgbaImage>,
|
||||
/// Label and value of each figure.
|
||||
pub figures: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
pub fn wallet(w: &Wallet) -> Vec<u8> {
|
||||
let mut img = gradient(WIDTH, 300, [122, 88, 22], [40, 26, 8]);
|
||||
let soft = [240, 222, 180];
|
||||
if let Some(a) = &w.avatar {
|
||||
let face = rounded_cover(a, 112, 56.0);
|
||||
blit(&mut img, &face, PAD, 28, (0, 0, WIDTH as i32, 300));
|
||||
}
|
||||
let x = PAD + 112 + 24;
|
||||
line(&mut img, &format!("{}'s wallet", w.name), (x, 28), 20.0, false, soft, WIDTH as i32 - x - PAD);
|
||||
line(&mut img, &w.balance, (x, 56), 52.0, true, [255, 226, 140], WIDTH as i32 - x - PAD);
|
||||
let count = w.figures.len().max(1) as i32;
|
||||
let (gap, width) = (8, (WIDTH as i32 - 2 * PAD - 8 * (count - 1)) / count);
|
||||
for (i, (label, value)) in w.figures.iter().enumerate() {
|
||||
let x = PAD + i as i32 * (width + gap);
|
||||
tint(&mut img, (x, 172, width, 96), 8, [255, 255, 255], 0.1);
|
||||
line(&mut img, label, (x + 14, 186), 16.0, false, soft, width - 24);
|
||||
line(&mut img, value, (x + 14, 218), 26.0, true, WHITE, width - 24);
|
||||
}
|
||||
png(&img)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::cardart::gradient;
|
||||
|
||||
fn money() -> Money {
|
||||
Money { left: "Bet 250 coins".into(), right: "Balance 1,840 coins".into() }
|
||||
|
|
@ -340,6 +353,7 @@ mod tests {
|
|||
dump("coin.png", &coin_still("heads", "You picked heads, a win pays 2×", &money(), "It landed heads, you win"));
|
||||
dump("slots.png", &slots_still(Some(["💎", "💎", "🔔"]), "Two of a kind pays 2×", &TABLE, 2, &money()));
|
||||
dump("wheel.png", &wheel_still(Some(5), "It landed on 5 red", "You bet red", &ODDS, &money()));
|
||||
dump("wallet.png", &wallet(&Wallet { name: "nightowl", balance: "12,480 coins".into(), avatar: Some(RgbaImage::from_pixel(64, 64, Rgba([90, 120, 200, 255]))), figures: vec![("Games".into(), "214".into()), ("Won".into(), "47%".into()), ("Wagered".into(), "88,200".into()), ("Best win".into(), "+4,000".into()), ("Rank".into(), "#3".into())] }));
|
||||
println!("stills {:?}", started.elapsed());
|
||||
for (name, make) in [
|
||||
("coin.gif", Box::new(|| coin_flip("tails", "You picked heads", &money())) as Box<dyn Fn() -> Option<Vec<u8>>>),
|
||||
|
|
|
|||
|
|
@ -803,19 +803,25 @@ async fn balance_cmd(ctx: Arc<Ctx>) -> Result<()> {
|
|||
let money = balance(target.get());
|
||||
let stats = store().get("players").map(|p| p[target.get().to_string()].clone()).unwrap_or(Value::Null);
|
||||
let rank = top(None, 10_000).iter().position(|(u, _)| *u == target.get()).map(|i| i + 1);
|
||||
let mut lines = vec![format!("## {}", fmt(money))];
|
||||
let games = stats["games"].as_i64().unwrap_or(0);
|
||||
let mut figures = vec![("Games".to_string(), thousands(games as u64))];
|
||||
if games > 0 {
|
||||
lines.push(format!("🎲 {} games · {:.0}% won · {} wagered", thousands(games as u64), stats["wins"].as_f64().unwrap_or(0.0) / games as f64 * 100.0, thousands(stats["wagered"].as_u64().unwrap_or(0))));
|
||||
figures.push(("Won".to_string(), format!("{:.0}%", stats["wins"].as_f64().unwrap_or(0.0) / games as f64 * 100.0)));
|
||||
figures.push(("Wagered".to_string(), thousands(stats["wagered"].as_u64().unwrap_or(0))));
|
||||
if let Some(best) = stats["best"].as_u64().filter(|b| *b > 0) {
|
||||
lines.push(format!("🏆 Best win: +{}", thousands(best)));
|
||||
figures.push(("Best win".to_string(), format!("+{}", thousands(best))));
|
||||
}
|
||||
}
|
||||
if let Some(r) = rank {
|
||||
lines.push(format!("-# #{r} richest overall"));
|
||||
figures.push(("Rank".to_string(), format!("#{r}")));
|
||||
}
|
||||
let avatar = super::super::media::avatar(&ctx.state, target, 128).await;
|
||||
ctx.reply(Card::new(Some(CASINO)).header(&[&format!("### 💰 {}'s wallet", escape(&name)), &lines.join("\n")], Some(&avatar)).build()).await
|
||||
let avatar_url = super::super::media::avatar(&ctx.state, target, 256).await;
|
||||
let avatar = match super::super::media::fetch_limited(&ctx.state, &avatar_url, 4 * 1024 * 1024).await {
|
||||
Some(bytes) => tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten(),
|
||||
None => None,
|
||||
};
|
||||
let bytes = art::wallet(&art::Wallet { name: &name, balance: format!("{} coins", thousands(money.max(0) as u64)), avatar, figures });
|
||||
ctx.reply_file(picture(CASINO, art::STILL).build(), art::STILL, bytes).await
|
||||
}
|
||||
|
||||
async fn donate(ctx: Arc<Ctx>) -> Result<()> {
|
||||
|
|
|
|||
128
src/commands/lastfm/art.rs
Normal file
128
src/commands/lastfm/art.rs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
//! 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 image::RgbaImage;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const FILE: &str = "lastfm.png";
|
||||
|
||||
const W: i32 = 800;
|
||||
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,
|
||||
pub artist: String,
|
||||
pub album: Option<String>,
|
||||
pub accent: u32,
|
||||
pub cover: Option<RgbaImage>,
|
||||
pub stats: Vec<(String, String)>,
|
||||
pub previous: Option<String>,
|
||||
}
|
||||
|
||||
pub fn now_playing(n: &Now) -> Vec<u8> {
|
||||
let (top, bottom) = wash(n.accent);
|
||||
let mut img = gradient(W as u32, 384, top, bottom);
|
||||
let size = 328;
|
||||
match &n.cover {
|
||||
Some(c) => blit(&mut img, &rounded_cover(c, size as u32, 12.0), PAD, PAD, (0, 0, W, 384)),
|
||||
None => tint(&mut img, (PAD, PAD, size, size), 12, [255, 255, 255], 0.1),
|
||||
}
|
||||
let x = PAD + size + 28;
|
||||
let width = W - x - PAD;
|
||||
line(&mut img, &n.status, (x, 30), 17.0, false, SOFT, width);
|
||||
line(&mut img, &n.title, (x, 54), 32.0, true, INK, width);
|
||||
line(&mut img, &n.artist, (x, 102), 22.0, false, INK, width);
|
||||
if let Some(a) = &n.album {
|
||||
line(&mut img, a, (x, 134), 18.0, false, SOFT, width);
|
||||
}
|
||||
let count = n.stats.len().max(1) as i32;
|
||||
let tile = (width - 8 * (count - 1)) / count;
|
||||
for (i, (label, value)) in n.stats.iter().enumerate() {
|
||||
let tx = x + i as i32 * (tile + 8);
|
||||
tint(&mut img, (tx, 180, tile, 76), 8, [255, 255, 255], 0.12);
|
||||
line(&mut img, label, (tx + 12, 190), 14.0, false, SOFT, tile - 20);
|
||||
line(&mut img, value, (tx + 12, 214), 24.0, true, INK, tile - 20);
|
||||
}
|
||||
if let Some(p) = &n.previous {
|
||||
line(&mut img, "Before this", (x, 276), 14.0, false, SOFT, width);
|
||||
line(&mut img, p, (x, 296), 18.0, false, INK, width);
|
||||
}
|
||||
png(&img)
|
||||
}
|
||||
|
||||
pub struct Row {
|
||||
pub rank: usize,
|
||||
pub name: String,
|
||||
pub by: Option<String>,
|
||||
pub plays: u64,
|
||||
}
|
||||
|
||||
pub struct Chart {
|
||||
pub title: String,
|
||||
pub note: String,
|
||||
pub accent: u32,
|
||||
pub rows: Vec<Row>,
|
||||
/// The biggest play count of the whole list, so bars keep their scale across pages.
|
||||
pub top: u64,
|
||||
pub cover: Option<Arc<RgbaImage>>,
|
||||
pub empty: String,
|
||||
}
|
||||
|
||||
pub fn chart(c: &Chart) -> Vec<u8> {
|
||||
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 image::Rgba;
|
||||
|
||||
#[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() });
|
||||
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();
|
||||
}
|
||||
assert!(now.len() > 1000 && top.len() > 1000);
|
||||
assert_ne!(wash(0xB4502A), wash(0x2A7FB4));
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@
|
|||
//! 96 kbit/s Opus file in a message only they can see, which deletes itself after ~14 minutes).
|
||||
mod api;
|
||||
mod extras;
|
||||
mod art;
|
||||
mod views;
|
||||
|
||||
use self::api::{as_list, best_image, fm_url, Lfm};
|
||||
|
|
@ -151,7 +152,8 @@ async fn show(ctx: &Arc<Ctx>, mode: &str, user: Id<UserMarker>, kind: &str, peri
|
|||
let base = views::Base { state: state.clone(), api: api.clone(), owner: ctx.user_id.get(), user: user.get(), name, avatar, username: username.clone() };
|
||||
if mode == "nowplaying" {
|
||||
return match views::now_playing(&base).await {
|
||||
Ok(card) => ctx.reply(card).await,
|
||||
Ok((card, Some(picture))) => ctx.reply_file(card, art::FILE, picture).await,
|
||||
Ok((card, None)) => ctx.reply(card).await,
|
||||
Err(e) => error(ctx, &e.to_string()).await,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,46 +43,48 @@ fn owner_only(owner: u64, who: u64) -> Result<(), String> {
|
|||
|
||||
// ---- now playing ----------------------------------------------------------------------------------------------------
|
||||
|
||||
pub async fn now_playing(b: &Base) -> Result<Component, Error> {
|
||||
pub async fn now_playing(b: &Base) -> Result<(Component, Option<Vec<u8>>), Error> {
|
||||
let (tracks, info) = tokio::join!(b.api.recent(&b.username, 2), b.api.user_info(&b.username));
|
||||
let (tracks, info) = (tracks?, info?);
|
||||
let Some(track) = tracks.first() else {
|
||||
return Ok(Card::new(Some(RED)).text(&format!("### No scrobbles yet\n{} hasn't scrobbled anything.", escape(&b.username))).build());
|
||||
return Ok((Card::new(Some(RED)).text(&format!("### No scrobbles yet\n{} hasn't scrobbled anything.", escape(&b.username))).build(), None));
|
||||
};
|
||||
let artist = track["artist"]["#text"].as_str().unwrap_or("Unknown artist");
|
||||
let title = track["name"].as_str().unwrap_or("Unknown track");
|
||||
let album = track["album"]["#text"].as_str().filter(|a| !a.is_empty());
|
||||
let playing = track["@attr"]["nowplaying"].as_str() == Some("true");
|
||||
let plays = b.api.entity("track", title, Some(artist), Some(&b.username)).await.ok().map(|d| num(&d, "userplaycount")).filter(|p| *p > 0);
|
||||
let status = if playing {
|
||||
format!("-# {PLAYING_EMOJI} Now playing · {}", escape(&b.name))
|
||||
} else {
|
||||
match track["date"]["uts"].as_str() {
|
||||
Some(uts) => format!("-# ⏮️ Last played <t:{uts}:R> · {}", escape(&b.name)),
|
||||
None => format!("-# ⏮️ Last played · {}", escape(&b.name)),
|
||||
}
|
||||
};
|
||||
let mut body = format!("### {}\n**{}**", link(&truncate(title, 90), track["url"].as_str()), link(artist, Some(&fm_url(&[artist]))));
|
||||
if let Some(a) = album {
|
||||
body.push_str(&format!(" · *{}*", escape(&truncate(a, 80))));
|
||||
}
|
||||
let cover = best_image(&track["image"]);
|
||||
let accent = colors::accent(&b.state, cover.as_deref(), GREEN).await;
|
||||
let mut footer = vec", escape(&b.username), b.username), format!("{} scrobbles", thousands(num(&info, "playcount")))];
|
||||
let art_image = match &cover {
|
||||
Some(url) => match crate::commands::media::fetch_limited(&b.state, url, 4 * 1024 * 1024).await {
|
||||
Some(bytes) => tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten(),
|
||||
None => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let status = if playing { format!("Now playing · {}", b.name) } else { format!("Last played · {}", b.name) };
|
||||
let mut stats = vec![("Scrobbles".to_string(), thousands(num(&info, "playcount")))];
|
||||
if let Some(p) = plays {
|
||||
footer.push(format!("{} play{} of this track", thousands(p), if p != 1 { "s" } else { "" }));
|
||||
stats.push(("Plays of this track".to_string(), thousands(p)));
|
||||
}
|
||||
let mut card = Card::new(Some(accent)).header(&[&status, &body], cover.as_deref()).footer(&footer.join(" · "));
|
||||
if let (Some(prev), true) = (tracks.get(1), playing) {
|
||||
card = card.footer(&format!("Previous: {} — {}", escape(&truncate(prev["name"].as_str().unwrap_or("?"), 60)), escape(prev["artist"]["#text"].as_str().unwrap_or("?"))));
|
||||
let previous = tracks.get(1).filter(|_| playing).map(|p| format!("{} by {}", p["name"].as_str().unwrap_or("?"), p["artist"]["#text"].as_str().unwrap_or("?")));
|
||||
let picture = super::art::now_playing(&super::art::Now { status, title: title.to_string(), artist: artist.to_string(), album: album.map(str::to_string), accent, cover: art_image, stats, previous });
|
||||
let mut links = vec![link(&truncate(title, 60), track["url"].as_str()), link(artist, Some(&fm_url(&[artist])))];
|
||||
links.push(format!("[{}](<https://www.last.fm/user/{}>)", escape(&b.username), b.username));
|
||||
if !playing {
|
||||
if let Some(uts) = track["date"]["uts"].as_str() {
|
||||
links.push(format!("<t:{uts}:R>"));
|
||||
}
|
||||
}
|
||||
let mut card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", super::art::FILE)]).footer(&links.join(" · "));
|
||||
if let Some(url) = track["url"].as_str().filter(|u| track_from_url(u).is_some()) {
|
||||
let go = twilight_model::channel::message::component::Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎵".into() }), label: Some("Go to song".into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None };
|
||||
let mut listen = button("fm:listen", "Listen to song", ButtonStyle::Primary);
|
||||
listen.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎧".into() });
|
||||
card = card.row(vec![go, listen]);
|
||||
}
|
||||
Ok(card.build())
|
||||
Ok((card.build(), Some(picture)))
|
||||
}
|
||||
|
||||
// ---- shared card pieces -------------------------------------------------------------------------------------------------
|
||||
|
|
@ -118,7 +120,7 @@ pub struct Top {
|
|||
period: String,
|
||||
items: Vec<Value>,
|
||||
total: u64,
|
||||
thumbnail: Option<String>,
|
||||
cover: Option<Arc<image::RgbaImage>>,
|
||||
accent: u32,
|
||||
page: usize,
|
||||
over: bool,
|
||||
|
|
@ -135,7 +137,14 @@ impl Top {
|
|||
None => None,
|
||||
};
|
||||
let accent = colors::accent(&b.state, thumbnail.as_deref().or(Some(&b.avatar)), GREEN).await;
|
||||
Ok(Self { b, kind, period, items, total, thumbnail, accent, page: 0, over: false })
|
||||
let cover = match &thumbnail {
|
||||
Some(url) => match crate::commands::media::fetch_limited(&b.state, url, 4 * 1024 * 1024).await {
|
||||
Some(bytes) => tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten().map(Arc::new),
|
||||
None => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
Ok(Self { b, kind, period, items, total, cover, accent, page: 0, over: false })
|
||||
}
|
||||
|
||||
fn pages(&self) -> usize {
|
||||
|
|
@ -158,32 +167,25 @@ impl Game for Top {
|
|||
|
||||
fn render(&self, t: u32) -> Rendered {
|
||||
let top = self.items.first().map_or(1, |i| num(i, "playcount"));
|
||||
let lines: Vec<String> = self.items.iter().enumerate().skip(self.page * PER_PAGE).take(PER_PAGE).map(|(idx, item)| {
|
||||
let (i, name, plays) = (idx + 1, item["name"].as_str().unwrap_or("?"), num(item, "playcount"));
|
||||
let entry = if self.kind == "artists" {
|
||||
format!("**{}**", link(&truncate(name, 60), Some(item["url"].as_str().map(str::to_string).unwrap_or_else(|| fm_url(&[name])).as_str())))
|
||||
} else {
|
||||
format!("**{}** — {}", link(&truncate(name, 55), item["url"].as_str()), escape(&truncate(item["artist"]["name"].as_str().unwrap_or("?"), 40)))
|
||||
};
|
||||
let medal = match i { 1 => "🥇".to_string(), 2 => "🥈".to_string(), 3 => "🥉".to_string(), n => format!("`{n:>2}`") };
|
||||
format!("{medal} {entry}\n-# `{}` {} plays", bar(plays, top), thousands(plays))
|
||||
let rows: Vec<super::art::Row> = self.items.iter().enumerate().skip(self.page * PER_PAGE).take(PER_PAGE).map(|(idx, item)| super::art::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"),
|
||||
}).collect();
|
||||
let icon = KINDS.iter().find(|k| k.0 == self.kind).map_or("🎤", |k| k.1);
|
||||
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 mut card = Card::new(Some(self.accent))
|
||||
.header(&[&format!("### {icon} Top {} · {}", self.kind, escape(&self.b.username)), &format!("-# {} · <@{}>", period_label(&self.period), self.b.user)], Some(self.thumbnail.as_deref().unwrap_or(&self.b.avatar)))
|
||||
.separator(true, false)
|
||||
.text(&if lines.is_empty() { format!("*No {} scrobbled in this period.*", self.kind) } else { lines.join("\n") });
|
||||
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 mut card = Card::new(Some(self.accent)).gallery(&[&format!("attachment://{}", super::art::FILE)]);
|
||||
if !footer.is_empty() {
|
||||
card = card.footer(&footer);
|
||||
}
|
||||
let options = PERIODS.iter().map(|(k, l)| { let mut o = select_option(l, k, "🕒", "", *k == self.period); o.emoji = None; o }).collect();
|
||||
let mut buttons: Vec<_> = KINDS.iter().map(|(k, e)| btn(t, &format!("kind_{k}"), &(k[..1].to_uppercase() + &k[1..]), e, if *k == self.kind { ButtonStyle::Primary } else { ButtonStyle::Secondary }, false)).collect();
|
||||
buttons.extend(nav(t, self.page, self.pages()));
|
||||
card.select(select_menu(&format!("gm:{t}:period"), "Time period", options)).row(buttons).into()
|
||||
Rendered { card: card.select(select_menu(&format!("gm:{t}:period"), "Time period", options)).row(buttons), file: Some((super::art::FILE.to_string(), bytes)) }
|
||||
}
|
||||
|
||||
fn click(&mut self, _: u64, action: &str, values: &[String], _: &HashMap<String, String>) -> Reply {
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ use twilight_model::id::Id;
|
|||
pub mod translate;
|
||||
pub mod virus;
|
||||
pub mod weather;
|
||||
mod weather_art;
|
||||
|
||||
// ---- calculator ----------------------------------------------------------------------------
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! Weather: Open-Meteo (no key). `D!weather <place>` / `/weather`; `D!weather home <place>` saves your
|
||||
//! place privately so plain `weather` works; the °C/°F button remembers your choice.
|
||||
use super::weather_art;
|
||||
use crate::cmd::{Command, Ctx, Opt, OptKind};
|
||||
use crate::error::UserError;
|
||||
use crate::interact;
|
||||
|
|
@ -22,7 +23,6 @@ use twilight_model::id::Id;
|
|||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const NOT_FOUND: &str = "🌍 I couldn't find that place. Try a city (`Paris`), a city and state or country (`Denver Colorado`, `Springfield, IL`) or a US ZIP code (`10001`).";
|
||||
const FAHRENHEIT_COUNTRIES: &[&str] = &["US", "LR", "MM", "BS", "BZ", "KY", "PW", "FM", "MH", "PR", "GU", "VI", "AS", "MP"];
|
||||
const ARROWS: [&str; 8] = ["↓", "↙", "←", "↖", "↑", "↗", "→", "↘"]; // where the wind blows *to*
|
||||
|
||||
const US_STATES: &[(&str, &str)] = &[
|
||||
("AL", "Alabama"), ("AK", "Alaska"), ("AZ", "Arizona"), ("AR", "Arkansas"), ("CA", "California"), ("CO", "Colorado"),
|
||||
|
|
@ -176,6 +176,7 @@ pub async fn forecast(state: &State, place: &Place) -> Option<Value> {
|
|||
json(state, "https://api.open-meteo.com/v1/forecast", &[
|
||||
("latitude", &lat), ("longitude", &lon), ("timezone", "auto"), ("forecast_days", "5"),
|
||||
("current", "temperature_2m,relative_humidity_2m,apparent_temperature,is_day,precipitation,weather_code,cloud_cover,pressure_msl,wind_speed_10m,wind_direction_10m,wind_gusts_10m,uv_index"),
|
||||
("hourly", "temperature_2m,precipitation_probability"), ("forecast_hours", "24"),
|
||||
("daily", "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,sunrise,sunset"),
|
||||
]).await
|
||||
}
|
||||
|
|
@ -208,47 +209,69 @@ fn day_name(iso: &str) -> String {
|
|||
chrono::NaiveDate::parse_from_str(iso, "%Y-%m-%d").map_or(iso.to_string(), |d| d.format("%a %d").to_string())
|
||||
}
|
||||
|
||||
fn card(place: &Place, data: &Value, owner: u64, fahrenheit: bool, private: bool) -> Component {
|
||||
const PICTURE: &str = "weather.png";
|
||||
|
||||
/// The numbers for the picture. Temperatures on the chart follow the reader's units.
|
||||
fn view(data: &Value, fahrenheit: bool, private: bool) -> weather_art::View {
|
||||
let u = Units(fahrenheit);
|
||||
let (now, daily) = (&data["current"], &data["daily"]);
|
||||
let (now, daily, hourly) = (&data["current"], &data["daily"], &data["hourly"]);
|
||||
let is_day = now["is_day"].as_i64().unwrap_or(1) == 1;
|
||||
let (emoji, text) = wmo(now["weather_code"].as_i64().unwrap_or(0), is_day);
|
||||
let dir = now["wind_direction_10m"].as_f64();
|
||||
let arrow = dir.map_or("", |d| ARROWS[((d / 45.0).round() as usize) % 8]);
|
||||
let mut details = vec![
|
||||
format!("💧 Humidity **{}%**", now["relative_humidity_2m"].as_i64().map_or("?".to_string(), |h| h.to_string())),
|
||||
format!("🌬️ Wind **{}** {arrow} (gusts {})", u.speed(now["wind_speed_10m"].as_f64()), u.speed(now["wind_gusts_10m"].as_f64())),
|
||||
format!("☁️ Clouds **{}%** · 🌧️ {}", now["cloud_cover"].as_i64().map_or("?".to_string(), |h| h.to_string()), u.rain(now["precipitation"].as_f64())),
|
||||
format!("🧭 Pressure **{:.0} hPa**", now["pressure_msl"].as_f64().unwrap_or(0.0)),
|
||||
let code = now["weather_code"].as_i64().unwrap_or(0);
|
||||
let (emoji, text) = wmo(code, is_day);
|
||||
let from = now["wind_direction_10m"].as_f64().map_or("", |d| ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][((d / 45.0).round() as usize) % 8]);
|
||||
let percent = |key: &str| now[key].as_i64().map_or("?".to_string(), |v| format!("{v}%"));
|
||||
let sun = match (daily["sunrise"][0].as_str(), daily["sunset"][0].as_str()) {
|
||||
(Some(r), Some(s)) => format!("{} to {}", &r[r.len().saturating_sub(5)..], &s[s.len().saturating_sub(5)..]),
|
||||
_ => "?".to_string(),
|
||||
};
|
||||
let tiles = vec![
|
||||
("Humidity".to_string(), percent("relative_humidity_2m")),
|
||||
("Wind".to_string(), format!("{} {from}", u.speed(now["wind_speed_10m"].as_f64()))),
|
||||
("Gusts".to_string(), u.speed(now["wind_gusts_10m"].as_f64())),
|
||||
("UV index".to_string(), now["uv_index"].as_f64().map_or("?".to_string(), |v| format!("{v:.0}"))),
|
||||
("Pressure".to_string(), format!("{:.0} hPa", now["pressure_msl"].as_f64().unwrap_or(0.0))),
|
||||
("Clouds".to_string(), percent("cloud_cover")),
|
||||
("Rain now".to_string(), u.rain(now["precipitation"].as_f64())),
|
||||
("Sun".to_string(), sun),
|
||||
];
|
||||
if let Some(uv) = now["uv_index"].as_f64() {
|
||||
details.push(format!("🕶️ UV index **{uv:.0}**"));
|
||||
}
|
||||
if let (Some(r), Some(s)) = (daily["sunrise"][0].as_str(), daily["sunset"][0].as_str()) {
|
||||
details.push(format!("🌅 {} · 🌇 {}", &r[r.len().saturating_sub(5)..], &s[s.len().saturating_sub(5)..]));
|
||||
}
|
||||
let days: Vec<String> = daily["time"].as_array().map(|t| t.iter().take(5).enumerate().map(|(i, d)| {
|
||||
let name = if i == 0 { "Today".to_string() } else { day_name(d.as_str().unwrap_or("")) };
|
||||
let (de, dt) = wmo(daily["weather_code"][i].as_i64().unwrap_or(0), true);
|
||||
let rain = daily["precipitation_probability_max"][i].as_i64().filter(|r| *r > 0).map_or(String::new(), |r| format!(" · 💧{r}%"));
|
||||
format!("`{name:<6}` {de} **{}** / {} · {dt}{rain}", u.t(daily["temperature_2m_max"][i].as_f64()), u.t(daily["temperature_2m_min"][i].as_f64()))
|
||||
let shown = |c: f64| if fahrenheit { c * 9.0 / 5.0 + 32.0 } else { c };
|
||||
let hours = hourly["time"].as_array().map(|t| t.iter().take(24).enumerate().filter_map(|(i, h)| {
|
||||
let time = h.as_str()?;
|
||||
Some((time[time.len().saturating_sub(5)..].to_string(), shown(hourly["temperature_2m"][i].as_f64()?), hourly["precipitation_probability"][i].as_i64().unwrap_or(0)))
|
||||
}).collect()).unwrap_or_default();
|
||||
// Never say where: the place is shown only to the person who asked, via 📍.
|
||||
let head = format!("## {emoji} {}", if private { "Weather at your saved place" } else { "Weather" });
|
||||
let degrees = |c: Option<f64>| c.map_or("?".to_string(), |c| format!("{:.0}°", shown(c)));
|
||||
let days = daily["time"].as_array().map(|t| t.iter().take(5).enumerate().map(|(i, d)| {
|
||||
let (high, low) = (daily["temperature_2m_max"][i].as_f64(), daily["temperature_2m_min"][i].as_f64());
|
||||
weather_art::Day {
|
||||
name: if i == 0 { "Today".to_string() } else { day_name(d.as_str().unwrap_or("")) },
|
||||
emoji: wmo(daily["weather_code"][i].as_i64().unwrap_or(0), true).0,
|
||||
high: high.unwrap_or(0.0), low: low.unwrap_or(0.0), high_text: degrees(high), low_text: degrees(low),
|
||||
rain: daily["precipitation_probability_max"][i].as_i64().filter(|r| *r > 0),
|
||||
}
|
||||
}).collect()).unwrap_or_default();
|
||||
weather_art::View {
|
||||
// Never say where: the place is shown only to the person who asked, via 📍.
|
||||
title: if private { "Weather at your saved place".to_string() } else { "Weather".to_string() },
|
||||
temperature: u.t(now["temperature_2m"].as_f64()), condition: text.to_string(), feels: format!("feels like {}", u.t(now["apparent_temperature"].as_f64())),
|
||||
emoji, code, day: is_day, tiles, hours, days,
|
||||
}
|
||||
}
|
||||
|
||||
/// The card and its picture.
|
||||
fn card(place: &Place, data: &Value, owner: u64, fahrenheit: bool, private: bool) -> (Component, Vec<u8>) {
|
||||
let picture = weather_art::render(&view(data, fahrenheit, private));
|
||||
let is_day = data["current"]["is_day"].as_i64().unwrap_or(1) == 1;
|
||||
let id = |a: &str| format!("wx:{owner}:{a}:{}:{:.3}:{:.3}:{}", if fahrenheit { "f" } else { "c" }, place.lat, place.lon, if private { 1 } else { 0 });
|
||||
Card::new(Some(if is_day { 0x4A90E2 } else { 0x2C3E66 }))
|
||||
.text(&head)
|
||||
.text(&format!("# {}\n**{text}** · feels like {}", u.t(now["temperature_2m"].as_f64()), u.t(now["apparent_temperature"].as_f64())))
|
||||
.text(&details.join("\n"))
|
||||
.separator(true, false)
|
||||
.text(&days.join("\n"))
|
||||
let card = Card::new(Some(if is_day { 0x4A90E2 } else { 0x2C3E66 }))
|
||||
.gallery(&[&format!("attachment://{PICTURE}")])
|
||||
.footer("Open-Meteo")
|
||||
.row(vec![
|
||||
emoji_button(&id("unit"), Some(if fahrenheit { "Show °C" } else { "Show °F" }), "🌡️", false),
|
||||
emoji_button(&id("refresh"), Some("Refresh"), "🔄", false),
|
||||
emoji_button(&id("where"), Some("Place"), "📍", false),
|
||||
])
|
||||
.build()
|
||||
.build();
|
||||
(card, picture)
|
||||
}
|
||||
|
||||
/// Names of the places behind recent weather cards, so "📍 Place" can tell its owner.
|
||||
|
|
@ -292,7 +315,8 @@ async fn show(ctx: &Ctx, location: Option<&str>, units: Option<&str>) -> Result<
|
|||
}
|
||||
let where_ = [Some(place.name.clone()), place.admin1.clone(), place.country.clone()].into_iter().flatten().collect::<Vec<_>>().join(", ");
|
||||
remembered().lock().unwrap().insert(place_key(&format!("{:.3}", place.lat), &format!("{:.3}", place.lon)), (Instant::now(), where_));
|
||||
ctx.reply(card(&place, &data, user, fahrenheit, saved)).await
|
||||
let (component, picture) = card(&place, &data, user, fahrenheit, saved);
|
||||
ctx.reply_file(component, PICTURE, picture).await
|
||||
}
|
||||
|
||||
fn data_missing(_: &str) -> bool {
|
||||
|
|
@ -367,7 +391,9 @@ pub async fn on_component(state: &Arc<State>, i: &Interaction) {
|
|||
let Some(data) = forecast(state, &place).await else {
|
||||
return interact::private_text(state, i, "🌍 The weather service didn't answer — try again in a moment.").await;
|
||||
};
|
||||
interact::update(state, i, card(&place, &data, owner, fahrenheit, private)).await;
|
||||
interact::ack(state, i).await; // the picture has to be uploaded, which a direct reply can't carry
|
||||
let (component, picture) = card(&place, &data, owner, fahrenheit, private);
|
||||
interact::edit_with_file(state, i, component, PICTURE, picture).await;
|
||||
}
|
||||
|
||||
/// (label, value) suggestions while someone types a place.
|
||||
|
|
@ -458,11 +484,11 @@ mod tests {
|
|||
"precipitation_probability_max": [10, 60], "sunrise": ["2026-10-23T07:30"], "sunset": ["2026-10-23T18:10"]}
|
||||
});
|
||||
let place = Place { lat: 1.0, lon: 2.0, ..Default::default() };
|
||||
let c = card(&place, &data, 5, false, true);
|
||||
let (c, picture) = card(&place, &data, 5, false, true);
|
||||
let (n, t) = crate::ui::cost(&c);
|
||||
assert!(n <= 40 && t < 4000);
|
||||
let text = serde_json::to_string(&c).unwrap();
|
||||
assert!(text.contains("Weather at your saved place") && text.contains("12°C") && text.contains("Overcast"));
|
||||
assert!(n <= 40 && t < 4000 && picture.len() > 1000);
|
||||
let v = view(&data, false, true);
|
||||
assert!(v.title == "Weather at your saved place" && v.temperature == "12°C" && v.condition == "Overcast");
|
||||
}
|
||||
|
||||
/// Talks to the real services: `cargo test live_weather -- --ignored --nocapture`
|
||||
|
|
@ -477,7 +503,7 @@ mod tests {
|
|||
println!("{q} -> {} / {:?} / {:?} ({}, {})", p.name, p.admin1, p.country, p.lat, p.lon);
|
||||
let f = forecast(&state, &p).await.unwrap_or_else(|| panic!("no forecast for {q}"));
|
||||
assert!(f["current"]["temperature_2m"].is_number());
|
||||
let c = card(&p, &f, 1, false, false);
|
||||
let (c, _) = card(&p, &f, 1, false, false);
|
||||
assert!(crate::ui::cost(&c).0 <= 40);
|
||||
}
|
||||
let hints = suggest_places(Arc::new(state), String::new(), "denver colo".into(), None, Id::new(1)).await;
|
||||
|
|
|
|||
191
src/commands/tools/weather_art.rs
Normal file
191
src/commands/tools/weather_art.rs
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
//! The weather picture: the sky changes with the conditions, and everything worth knowing is on the card.
|
||||
//! The place's name is left out on purpose: only the person who asked may see it.
|
||||
use crate::cardart::{blit, gradient, line, line_centre, line_right, png, sprite, stroke, tint};
|
||||
use image::RgbaImage;
|
||||
|
||||
const W: i32 = 800;
|
||||
const H: i32 = 576;
|
||||
const PAD: i32 = 28;
|
||||
|
||||
pub struct Day {
|
||||
pub name: String,
|
||||
pub emoji: &'static str,
|
||||
/// In °C, whatever the reader's units.
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub high_text: String,
|
||||
pub low_text: String,
|
||||
pub rain: Option<i64>,
|
||||
}
|
||||
|
||||
pub struct View {
|
||||
pub title: String,
|
||||
pub temperature: String,
|
||||
pub condition: String,
|
||||
pub feels: String,
|
||||
pub emoji: &'static str,
|
||||
pub code: i64,
|
||||
pub day: bool,
|
||||
/// Label and value of each detail tile.
|
||||
pub tiles: Vec<(String, String)>,
|
||||
/// The next 24 hours: label, temperature, chance of rain.
|
||||
pub hours: Vec<(String, f64, i64)>,
|
||||
pub days: Vec<Day>,
|
||||
}
|
||||
|
||||
struct Sky {
|
||||
top: [u8; 3],
|
||||
bottom: [u8; 3],
|
||||
ink: [u8; 3],
|
||||
soft: [u8; 3],
|
||||
tile: [u8; 3],
|
||||
line: [u8; 3],
|
||||
}
|
||||
|
||||
fn sky(code: i64, day: bool) -> Sky {
|
||||
const LIGHT: [u8; 3] = [255, 255, 255];
|
||||
const SOFT: [u8; 3] = [226, 234, 245];
|
||||
let dark = |top, bottom, line| Sky { top, bottom, ink: LIGHT, soft: SOFT, tile: [255, 255, 255], line };
|
||||
match (code, day) {
|
||||
(95..=99, _) => dark([38, 28, 78], [96, 62, 138], [255, 214, 92]),
|
||||
(71..=77 | 85 | 86, true) => Sky { top: [122, 170, 224], bottom: [216, 232, 248], ink: [20, 40, 70], soft: [44, 70, 104], tile: [255, 255, 255], line: [28, 92, 176] },
|
||||
(71..=77 | 85 | 86, false) => dark([30, 44, 88], [84, 112, 160], [190, 226, 255]),
|
||||
(51..=67 | 80..=82, true) => dark([40, 74, 122], [86, 128, 168], [156, 222, 255]),
|
||||
(51..=67 | 80..=82, false) => dark([16, 28, 60], [40, 66, 108], [140, 208, 255]),
|
||||
(45 | 48, true) => dark([104, 120, 134], [156, 168, 176], [255, 240, 196]),
|
||||
(45 | 48, false) => dark([44, 52, 66], [84, 94, 108], [214, 226, 240]),
|
||||
(3, true) => dark([84, 106, 136], [136, 158, 182], [255, 228, 150]),
|
||||
(2, true) => dark([44, 118, 206], [136, 186, 232], [255, 226, 120]),
|
||||
(_, true) => dark([28, 112, 220], [90, 182, 244], [255, 222, 96]),
|
||||
(_, false) => dark([12, 18, 54], [52, 44, 118], [176, 196, 255]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Blue when it's cold through to red when it's hot, in °C.
|
||||
fn heat(c: f64) -> [u8; 3] {
|
||||
let stops = [(-10.0, [120, 180, 255]), (5.0, [110, 220, 230]), (15.0, [130, 230, 140]), (24.0, [255, 214, 90]), (34.0, [255, 118, 76])];
|
||||
for pair in stops.windows(2) {
|
||||
let ((a, ca), (b, cb)) = (pair[0], pair[1]);
|
||||
if c <= b {
|
||||
let t = ((c - a) / (b - a)).clamp(0.0, 1.0) as f32;
|
||||
return [0, 1, 2].map(|i| (ca[i] as f32 * (1.0 - t) + cb[i] as f32 * t).round() as u8);
|
||||
}
|
||||
}
|
||||
stops[4].1
|
||||
}
|
||||
|
||||
fn tiles(img: &mut RgbaImage, v: &View, s: &Sky) {
|
||||
let (w, h, gap, top) = (180, 56, 8, 168);
|
||||
for (i, (label, value)) in v.tiles.iter().take(8).enumerate() {
|
||||
let (x, y) = (PAD + (i as i32 % 4) * (w + gap), top + (i as i32 / 4) * (h + gap));
|
||||
tint(img, (x, y, w, h), 8, s.tile, 0.16);
|
||||
line(img, label, (x + 12, y + 7), 14.0, false, s.soft, w - 20);
|
||||
line(img, value, (x + 12, y + 26), 18.0, true, s.ink, w - 20);
|
||||
}
|
||||
}
|
||||
|
||||
fn chart(img: &mut RgbaImage, v: &View, s: &Sky) {
|
||||
let (x, y, w, h) = (PAD, 296, W - 2 * PAD, 116);
|
||||
tint(img, (x, y, w, h), 8, s.tile, 0.12);
|
||||
line(img, "Next 24 hours", (x + 12, y + 6), 14.0, false, s.soft, 200);
|
||||
if v.hours.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let (low, high) = v.hours.iter().fold((f64::MAX, f64::MIN), |(l, h2), p| (l.min(p.1), h2.max(p.1)));
|
||||
let span = (high - low).max(1.0);
|
||||
let (left, right, top, bottom) = (x + 44, x + w - 16, y + 30, y + h - 26);
|
||||
let px = |i: usize| left as f32 + i as f32 / (v.hours.len() - 1) as f32 * (right - left) as f32;
|
||||
let py = |t: f64| bottom as f32 - ((t - low) / span) as f32 * (bottom - top) as f32;
|
||||
// chance of rain as soft bars behind the line
|
||||
for (i, (_, _, rain)) in v.hours.iter().enumerate() {
|
||||
if *rain > 0 {
|
||||
let height = (*rain as f32 / 100.0 * (bottom - top) as f32) as i32;
|
||||
tint(img, (px(i) as i32 - 6, bottom - height, 12, height), 2, [130, 196, 255], 0.5);
|
||||
}
|
||||
}
|
||||
for pair in 0..v.hours.len() - 1 {
|
||||
stroke(img, (px(pair), py(v.hours[pair].1)), (px(pair + 1), py(v.hours[pair + 1].1)), 2.0, s.line);
|
||||
}
|
||||
line_right(img, &format!("{high:.0}°"), (left - 8, top - 8), 14.0, false, s.ink);
|
||||
line_right(img, &format!("{low:.0}°"), (left - 8, bottom - 18), 14.0, false, s.soft);
|
||||
for (i, (label, _, _)) in v.hours.iter().enumerate() {
|
||||
if i % 6 == 0 {
|
||||
line_centre(img, label, (px(i) as i32, bottom + 4), 13.0, false, s.soft);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn days(img: &mut RgbaImage, v: &View, s: &Sky) {
|
||||
let count = v.days.len().clamp(1, 5) as i32;
|
||||
let (gap, top, h) = (8, 420, 132);
|
||||
let w = (W - 2 * PAD - gap * (count - 1)) / count;
|
||||
let (lowest, highest) = v.days.iter().fold((f64::MAX, f64::MIN), |(l, h2), d| (l.min(d.low), h2.max(d.high)));
|
||||
let span = (highest - lowest).max(1.0);
|
||||
for (i, d) in v.days.iter().take(5).enumerate() {
|
||||
let x = PAD + i as i32 * (w + gap);
|
||||
tint(img, (x, top, w, h), 8, s.tile, 0.16);
|
||||
line(img, &d.name, (x + 12, top + 8), 15.0, true, s.ink, w - 60);
|
||||
blit(img, &sprite(d.emoji, 40), x + w - 48, top + 6, (0, 0, W, H));
|
||||
line(img, &d.high_text, (x + 12, top + 50), 21.0, true, s.ink, w - 20);
|
||||
line_right(img, &d.low_text, (x + w - 12, top + 54), 16.0, false, s.soft);
|
||||
// where this day sits in the week's range, in colours for how warm it is
|
||||
let (a, b) = (((d.low - lowest) / span) as f32, ((d.high - lowest) / span) as f32);
|
||||
let (left, width) = ((x + 12) as f32, (w - 24) as f32);
|
||||
tint(img, (x + 12, top + 86, w - 24, 6), 3, s.tile, 0.2);
|
||||
let steps = ((b - a) * width).max(4.0) as i32;
|
||||
for step in 0..steps {
|
||||
let t = step as f64 / steps.max(1) as f64;
|
||||
let colour = heat(d.low + (d.high - d.low) * t);
|
||||
tint(img, ((left + a * width) as i32 + step, top + 86, 1, 6), 0, colour, 1.0);
|
||||
}
|
||||
if let Some(rain) = d.rain {
|
||||
line(img, &format!("Rain {rain}%"), (x + 12, top + 102), 14.0, false, s.soft, w - 20);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(v: &View) -> Vec<u8> {
|
||||
let s = sky(v.code, v.day);
|
||||
let mut img = gradient(W as u32, H as u32, s.top, s.bottom);
|
||||
line(&mut img, &v.title, (PAD, 20), 18.0, false, s.soft, 460);
|
||||
line(&mut img, &v.temperature, (PAD, 42), 68.0, true, s.ink, 400);
|
||||
line(&mut img, &v.condition, (PAD, 130), 21.0, true, s.ink, 400);
|
||||
let look = crate::text::Look::new(None, true, s.ink);
|
||||
let shift = crate::text::width_of(&v.condition, 21.0, &look).ceil() as i32;
|
||||
line(&mut img, &v.feels, (PAD + shift + 12, 132), 18.0, false, s.soft, 300);
|
||||
blit(&mut img, &sprite(v.emoji, 148), W - PAD - 148, 8, (0, 0, W, H));
|
||||
tiles(&mut img, v, &s);
|
||||
chart(&mut img, v, &s);
|
||||
days(&mut img, v, &s);
|
||||
png(&img)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn view(code: i64, day: bool, emoji: &'static str, condition: &str) -> View {
|
||||
let names = ["Today", "Sat 07", "Sun 08", "Mon 09", "Tue 10"];
|
||||
let emojis = ["⛅", "🌧️", "☀️", "🌦️", "❄️"];
|
||||
View {
|
||||
title: "Weather".into(), temperature: "12°C".into(), condition: condition.into(), feels: "feels like 10°C".into(), emoji, code, day,
|
||||
tiles: [("Humidity", "64%"), ("Wind", "14 km/h NE"), ("Gusts", "31 km/h"), ("UV index", "3"), ("Pressure", "1015 hPa"), ("Clouds", "40%"), ("Rain now", "0.0 mm"), ("Sun", "07:12 to 17:48")].map(|(a, b)| (a.to_string(), b.to_string())).to_vec(),
|
||||
hours: (0..24).map(|h| (format!("{:02}:00", (h + 21) % 24), 8.0 + 6.0 * (h as f64 / 24.0 * 6.28).sin(), if (6..12).contains(&h) { 60 } else { 0 })).collect(),
|
||||
days: (0..5).map(|i| Day { name: names[i].into(), emoji: emojis[i], high: 14.0 - i as f64, low: 4.0 + i as f64, high_text: format!("{}°", 14 - i), low_text: format!("{}°", 4 + i), rain: (i % 2 == 1).then_some(40) }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sky_changes_with_the_weather() {
|
||||
assert_ne!(sky(0, true).top, sky(0, false).top);
|
||||
assert_ne!(sky(0, true).top, sky(95, true).top);
|
||||
assert_ne!(sky(63, true).top, sky(73, true).top);
|
||||
for (name, v) in [("clear", view(0, true, "☀️", "Clear sky")), ("night", view(0, false, "🌙", "Clear sky")), ("rain", view(63, true, "🌧️", "Rain")), ("snow", view(73, true, "🌨️", "Snow"))] {
|
||||
let bytes = render(&v);
|
||||
assert!(bytes.len() < 900_000);
|
||||
if std::env::var("DEZIO_DUMP").is_ok() {
|
||||
std::fs::write(std::env::temp_dir().join(format!("dezio_wx_{name}.png")), bytes).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -175,7 +175,7 @@ pub async fn edit_with_file(state: &State, i: &Interaction, card: Component, nam
|
|||
use twilight_model::http::attachment::Attachment;
|
||||
let files = [Attachment::from_bytes(name.to_string(), bytes, 1)];
|
||||
let r = state.http.interaction(state.app_id()).update_response(&i.token).flags(MessageFlags::IS_COMPONENTS_V2)
|
||||
.components(Some(&[card])).attachments(&files).await;
|
||||
.components(Some(&[card])).attachments(&files).keep_attachment_ids(&[]).await;
|
||||
if let Err(e) = r {
|
||||
tracing::warn!("couldn't replace the picture: {e}");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue