Compare commits

...

7 Commits

Author SHA1 Message Date
9591dcdd3e Added override file 2025-10-30 22:24:17 -05:00
d0f0d07b51 Use static kmeans seed 2025-07-31 07:37:47 -05:00
6ee36cb65a Added arbitrary spotify search 2025-07-31 07:03:24 -05:00
d3ad04bc33 Added color cache 2025-07-31 04:10:02 -05:00
42270b18f0 Merged my own stupid divergence 2025-07-31 02:39:15 -05:00
d6ea8977a6 Fixed spotify more 2025-07-31 00:44:48 -05:00
5da8b2b193 Added help command, fixed Spotify search 2025-07-31 00:27:10 -05:00
7 changed files with 536 additions and 241 deletions

View File

@ -1,3 +1,10 @@
DISCORD_TOKEN= DISCORD_TOKEN=
LASTFM_API_KEY= LASTFM_API_KEY=
DATABASE_URL=sqlite:watcat.db DATABASE_URL=sqlite:watcat.db
# optional, for spotify support
RSPOTIFY_CLIENT_ID=
RSPOTIFY_CLIENT_SECRET=
# optional, to set color cache size. set to 0 to disable
MAX_CACHE_SIZE=

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
/.env /.env
/watcat.db* /watcat.db*
/http-cacache /http-cacache
/overrides.txt

36
Cargo.lock generated
View File

@ -1100,6 +1100,12 @@ dependencies = [
"foldhash", "foldhash",
] ]
[[package]]
name = "hashbrown"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
[[package]] [[package]]
name = "hashlink" name = "hashlink"
version = "0.10.0" version = "0.10.0"
@ -1570,12 +1576,12 @@ checksum = "d0263a3d970d5c054ed9312c0057b4f3bde9c0b33836d3637361d4a9e6e7a408"
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.9.0" version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown 0.15.3", "hashbrown 0.16.0",
] ]
[[package]] [[package]]
@ -2958,9 +2964,19 @@ dependencies = [
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.219" version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
@ -2976,9 +2992,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.219" version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -4270,7 +4286,7 @@ dependencies = [
[[package]] [[package]]
name = "watcat" name = "watcat"
version = "0.3.0" version = "0.6.1"
dependencies = [ dependencies = [
"arabic_reshaper", "arabic_reshaper",
"dotenvy", "dotenvy",
@ -4695,9 +4711,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "0.7.10" version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec" checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]

View File

@ -1,6 +1,6 @@
[package] [package]
name = "watcat" name = "watcat"
version = "0.4.0" version = "0.6.2"
edition = "2024" edition = "2024"
[dependencies] [dependencies]

View File

@ -29,10 +29,13 @@ TODO
---- ----
+ ~~add art and lastfm url fetching~~ + ~~add art and lastfm url fetching~~
+ add help command + ~~add help command~~
+ ~~refactor to combine repeated parts of art, url, and fmi.~~ + ~~refactor to combine repeated parts of art, url, and fmi.~~
+ use macro for commands + ~~use macro for commands~~
+ use Option instead of empty string sentinel value + ~~use Option instead of empty string sentinel value~~
+ ~~add cache for album art colors~~
+ ~~add spotify link fetching~~ + ~~add spotify link fetching~~
+ ~~add arbitrary spotify searching~~
+ ~~use static seed for kmeans~~
+ make various parameters user-configurable + make various parameters user-configurable
+ use tiny-skia instead of magick-rust? + use tiny-skia instead of magick-rust?

View File

@ -2,7 +2,7 @@ extern crate dotenvy;
extern crate lastfm; extern crate lastfm;
extern crate reqwest; extern crate reqwest;
extern crate reqwest_middleware; extern crate reqwest_middleware;
use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions}; use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions,};
use serenity::async_trait; use serenity::async_trait;
use serenity::builder::{CreateAttachment, CreateMessage}; use serenity::builder::{CreateAttachment, CreateMessage};
@ -11,10 +11,14 @@ use serenity::model::id::UserId;
use serenity::prelude::*; use serenity::prelude::*;
extern crate magick_rust; extern crate magick_rust;
use magick_rust::{ColorspaceType, CompositeOperator, MagickWand, PixelWand, magick_wand_genesis, FilterType}; use magick_rust::{
ColorspaceType, CompositeOperator, FilterType, MagickWand, PixelWand, magick_wand_genesis,
};
use magick_rust::bindings::MagickSetSeed;
use std::env; use std::env;
use std::sync::{Once, Arc}; use std::collections::HashMap;
use std::sync::{Arc, Once};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use palette::color_difference::ImprovedCiede2000; use palette::color_difference::ImprovedCiede2000;
@ -24,12 +28,15 @@ use palette::white_point::D65;
extern crate sqlx; extern crate sqlx;
use sqlx::sqlite::SqlitePool; use sqlx::sqlite::SqlitePool;
use rspotify::{ClientCredsSpotify, Credentials, clients::BaseClient,};
use rspotify::model::{enums::types::SearchType, search::SearchResult}; use rspotify::model::{enums::types::SearchType, search::SearchResult};
use rspotify::{ClientCredsSpotify, Credentials, clients::BaseClient};
use imagetext::fontdb::FontDB; use imagetext::fontdb::FontDB;
use imagetext::superfont::SuperFont; use imagetext::superfont::SuperFont;
use std::time::SystemTime;
use std::io::Read;
mod text; mod text;
static START: Once = Once::new(); static START: Once = Once::new();
@ -52,13 +59,13 @@ macro_rules! now {
macro_rules! log { macro_rules! log {
($a:expr) => { ($a:expr) => {
if env::var("DEBUG").unwrap_or("0".to_string()) == "1" { if env::var("DEBUG").unwrap_or("0".to_owned()) == "1" {
println!(concat!("debug: {} ", $a), now!()) println!(concat!("debug: {} ", $a), now!())
} }
}; };
($a:expr, $($b:expr),+) => { ($a:expr, $($b:expr),+) => {
if env::var("DEBUG").unwrap_or("0".to_string()) == "1" { if env::var("DEBUG").unwrap_or("0".to_owned()) == "1" {
println!(concat!("debug: {} ", $a), now!(), $($b),+) println!(concat!("debug: {} ", $a), now!(), $($b),+)
} }
}; };
@ -67,8 +74,9 @@ macro_rules! log {
macro_rules! handle_magick_result { macro_rules! handle_magick_result {
($a: expr, $b: literal) => { ($a: expr, $b: literal) => {
match $a { match $a {
Ok(_) => { Ok(a) => {
log!("{} run successfully", stringify!($a)); log!("{} run successfully", stringify!($a));
a
} }
Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)), Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)),
} }
@ -79,7 +87,7 @@ macro_rules! handle_magick_option {
($a: expr, $b: literal) => { ($a: expr, $b: literal) => {
match $a { match $a {
Some(res) => res, Some(res) => res,
None => return Reply::Text($b.to_string()), None => return Reply::Text($b.to_owned()),
} }
}; };
} }
@ -118,58 +126,65 @@ fn validate_color(col: &PixelWand) -> Option<Lab> {
Some(Lab::<D65>::from_components(color_raw)) Some(Lab::<D65>::from_components(color_raw))
} }
async fn get_track(ctx: &Context, arg: &str, id: UserId) -> Result<lastfm::track::NowPlayingTrack, Reply> { async fn get_track(
ctx: &Context,
arg: Option<&str>,
id: UserId,
) -> Result<lastfm::track::NowPlayingTrack, Reply> {
let lastfm_user = match arg { let lastfm_user = match arg {
"" => get_lastfm_username(ctx, id).await, None => get_lastfm_username(ctx, id).await,
_ => Some(arg.to_string()), Some(user) => Some(user.to_owned()),
}; };
let lastfm_client = match lastfm_user { let lastfm_client = match lastfm_user {
Some(s) => lastfm::Client::<String, String>::from_env(s), Some(s) => lastfm::Client::<String, String>::from_env(s),
None => return Err(Reply::Text("No last.fm username set.".to_string())), None => return Err(Reply::Text("No last.fm username set.".to_owned())),
}; };
let now_playing = match lastfm_client.now_playing().await { let now_playing = match lastfm_client.now_playing().await {
Ok(np) => np, Ok(np) => np,
Err(e) => return Err(Reply::Text(format!("Error: grabbing last.fm user data failed {e}"))), Err(e) => {
return Err(Reply::Text(format!(
"Error: grabbing last.fm user data failed {e}"
)));
}
}; };
let track = match now_playing { let track = match now_playing {
Some(track) => track, Some(track) => track,
None => return Err(Reply::Text("Nothing playing.".to_string())), None => return Err(Reply::Text("Nothing playing.".to_owned())),
}; };
Ok(track) Ok(track)
} }
async fn art(ctx: &Context, arg: &str, id: UserId) -> Reply { async fn art(ctx: &Context, arg: Option<&str>, id: UserId) -> Reply {
let track = match get_track(ctx, arg, id).await { let track = match get_track(ctx, arg, id).await {
Ok(track) => track, Ok(track) => track,
Err(e) => return e, Err(e) => return e,
};
let track_art = match track.image.extralarge {
Some(track_art) => track_art,
None => return Reply::Text("Error: getting image uri failed".to_string()),
}; };
Reply::Text(track_art.to_string()) let track_art = match track.image.extralarge {
Some(track_art) => track_art,
None => return Reply::Text("Error: getting image uri failed".to_owned()),
};
Reply::Text(track_art.to_owned())
} }
async fn url(ctx: &Context, arg: &str, id: UserId) -> Reply { async fn url(ctx: &Context, arg: Option<&str>, id: UserId) -> Reply {
let track = match get_track(ctx, arg, id).await { let track = match get_track(ctx, arg, id).await {
Ok(track) => track, Ok(track) => track,
Err(e) => return e, Err(e) => return e,
}; };
Reply::Text(track.url) Reply::Text(track.url)
} }
async fn spot(ctx: &Context, arg: &str, id: UserId) -> Reply { async fn spot(ctx: &Context, arg: Option<&str>, id: UserId) -> Reply {
let track = match get_track(ctx, arg, id).await { let track = match get_track(ctx, arg, id).await {
Ok(track) => track, Ok(track) => track,
Err(e) => return e, Err(e) => return e,
}; };
let mut data = ctx.data.write().await; let mut data = ctx.data.write().await;
let spotify_option = data.get_mut::<SpotifyHaver>().expect("Failed to have spotify option"); let spotify_option = data.get_mut::<SpotifyHaver>().expect("Failed to have spotify option");
if spotify_option.is_none() { if spotify_option.is_none() {
return Reply::Text("Unable to use Spotify command: Contact bot Administrator.".to_owned()) return Reply::Text("Unable to use Spotify commands: Contact bot Administrator.".to_owned())
} }
let spotify_arc_mutex = spotify_option.as_mut().unwrap(); let spotify_arc_mutex = spotify_option.as_mut().unwrap();
//let spotify_arc_mutex_ref = Arc::clone(&spotify_arc_mutex);
let spotify_client = spotify_arc_mutex.lock().await; let spotify_client = spotify_arc_mutex.lock().await;
spotify_client.request_token().await.unwrap(); spotify_client.request_token().await.unwrap();
let search = spotify_client.search(format!("{} {}", track.name, track.artist.name).as_str(), SearchType::Track, None, None, None, None).await; let search = spotify_client.search(format!("{} {}", track.name, track.artist.name).as_str(), SearchType::Track, None, None, None, None).await;
@ -178,32 +193,83 @@ async fn spot(ctx: &Context, arg: &str, id: UserId) -> Reply {
Err(e) => return Reply::Text(format!("Failed to get track {e}")), Err(e) => return Reply::Text(format!("Failed to get track {e}")),
_ => return Reply::Text("Spotify search failed".to_owned()), _ => return Reply::Text("Spotify search failed".to_owned()),
}; };
match &tracks.items[0].external_urls.get("spotify") { match &tracks.items.first().map(|x| x.external_urls.get("spotify")) {
Some(url) => Reply::Text(url.to_owned().to_owned()), Some(Some(url)) => Reply::Text(url.to_owned().to_owned()),
None => Reply::Text("Unable to get spotify url".to_owned()), _ => Reply::Text("Unable to get spotify url".to_owned()),
} }
} }
async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Reply { async fn get_overrides_inner(last_modified: Option<SystemTime>) -> Option<HashMap<String, String>> {
let track = match get_track(ctx, arg, id).await { let mut file = match std::fs::File::open("overrides.txt") {
Ok(track) => track, Ok(a) => a,
Err(e) => return e, Err(_) => return None,
}; };
let track_info = text::TrackInfo { let file_stats = match file.metadata() {
title: track.name, Ok(a) => a,
artist: track.artist.name, Err(_) => return None,
album: track.album, };
let file_modified_time = match file_stats.modified() {
Ok(a) => a,
Err(_) => return None,
};
let reload = match last_modified {
None => true,
Some(last_modified) => match file_modified_time.duration_since(last_modified) {
Err(_) => true,
Ok(a) => a != std::time::Duration::default()
}
};
if !reload { return None; }
let mut contents = "".to_owned();
match file.read_to_string(&mut contents) {
Ok(_) => (),
Err(_) => return None,
};
Some(contents.as_str().lines().map(|x| {
let mut split = x.split("@");
let a: &str = split.next().unwrap_or("").trim();
let b: &str = split.next().unwrap_or("").trim();
(a.to_owned(), b.to_owned())
}).collect())
}
async fn get_overrides(ctx: &Context) -> HashMap<String, String> {
let data = ctx.data.write().await;
let overrides = data.get::<OverridesHaver>().expect("Failed to have overrides");
let mut map = overrides.map.lock().await;
let new_map = get_overrides_inner(overrides.last_modified).await;
if let Some(new_map) = new_map {
*map = new_map;
}
map.clone()
}
async fn fmi(ctx: &Context, arg: Option<&str>, id: UserId, avatar: Option<String>) -> Reply {
let track = match get_track(ctx, arg, id).await {
Ok(track) => track,
Err(e) => return e,
}; };
let image_uri = match track.image.extralarge { let track_info = text::TrackInfo {
title: track.name,
artist: track.artist.name,
album: track.album,
};
let original_image_uri = match track.image.extralarge {
Some(iu) => iu, Some(iu) => iu,
None => return Reply::Text("Error: getting image uri failed".to_string()), None => return Reply::Text("Error: getting image uri failed".to_owned()),
}; };
let image = match get_image(ctx, image_uri.as_str()).await { let overrides = get_overrides(ctx).await;
Ok(i) => i, let image_uri: String = match overrides.get(&format!("{} | {}", track_info.artist, track_info.album)) {
Err(e) => return Reply::Text(format!("{e}")), Some(s) => s,
}; None => match overrides.get(&track_info.album) {
Some(s) => s,
None => &original_image_uri,
},
}.to_owned();
let mut base_color = PixelWand::new(); let mut base_color = PixelWand::new();
let mut accent_color = PixelWand::new();
let mut white = PixelWand::new(); let mut white = PixelWand::new();
let main_wand = MagickWand::new(); let main_wand = MagickWand::new();
let art_wand = MagickWand::new(); let art_wand = MagickWand::new();
@ -211,73 +277,101 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Re
let mask_wand = MagickWand::new(); let mask_wand = MagickWand::new();
let text_image_wand = MagickWand::new(); let text_image_wand = MagickWand::new();
handle_magick_result!( let image = match get_image(ctx, image_uri.as_str()).await {
base_color.set_color("#7f7f7f"), Ok(i) => i,
"Failed to set init base color" Err(e) => return Reply::Text(format!("{e}")),
); };
handle_magick_result!( handle_magick_result!(
art_wand.read_image_blob(image), art_wand.read_image_blob(image),
"Failed to read image from uri" "Failed to read image from uri"
); );
handle_magick_result!( handle_magick_result!(
art_wand.transform_image_colorspace(ColorspaceType::Lab), art_wand.transform_image_colorspace(ColorspaceType::Lab),
"Failed to set art colorspace" "Failed to set art colorspace"
); );
handle_magick_result!(
base_color.set_color("#7f7f7f"),
"Failed to set init base color"
);
let color_cache_entry = {
let data = ctx.data.write().await;
let color_cache = data.get::<ColorsHaver>().expect("Failed to have colors option");
if color_cache.max > 0 {
let color_cache_map = color_cache.map.lock().await;
color_cache_map.get(image_uri.as_str()).map(|s| s.to_owned())
} else {
None
}
};
let (art_width, art_height) = (art_wand.get_image_width(), art_wand.get_image_height()); let (base_lab, accent_lab) = match color_cache_entry {
handle_magick_result!( Some(value) => value.to_owned(),
art_wand_cluster.new_image(art_width, art_height, &base_color), None => {
"Failed to init cluster image" let (art_width, art_height) = (art_wand.get_image_width(), art_wand.get_image_height());
); handle_magick_result!(
handle_magick_result!( art_wand_cluster.new_image(art_width, art_height, &base_color),
art_wand_cluster.compose_images(&art_wand, CompositeOperator::SrcOver, true, 0, 0), "Failed to init cluster image"
"Failed to copy onto cluster image" );
); handle_magick_result!(
// least stupid way I could figure out to do this, since it seems that MagickWand::new_from_wand() doesn't work art_wand_cluster.compose_images(&art_wand, CompositeOperator::SrcOver, true, 0, 0),
handle_magick_result!( "Failed to copy onto cluster image"
art_wand_cluster.set_image_colorspace(ColorspaceType::Lab), );
"Failed to set cluster colorspace" // least stupid way I could figure out to do this, since it seems that MagickWand::new_from_wand() doesn't work
); handle_magick_result!(
handle_magick_result!( art_wand_cluster.set_image_colorspace(ColorspaceType::Lab),
art_wand_cluster.kmeans(10, 200, 0.001), "Failed to set cluster colorspace"
"Failed to run kmeans" );
); unsafe { MagickSetSeed(0x5F3759DF); }
let mut colors = handle_magick_option!( handle_magick_result!(
art_wand_cluster.get_image_histogram(), art_wand_cluster.kmeans(10, 200, 0.001),
"Failed to get color histogram" "Failed to run kmeans"
); );
colors.sort_by_cached_key(|color| -(color.get_color_count() as isize)); let mut colors = handle_magick_option!(
let base_lab = validate_color(&colors[0]).expect("Failed to validate base color"); art_wand_cluster.get_image_histogram(),
let other_colors = colors "Failed to get color histogram"
.iter() );
.filter_map(|col| { colors.sort_by_cached_key(|color| -(color.get_color_count() as isize));
let testing_color = validate_color(col)?; let base_lab = validate_color(&colors[0]).expect("Failed to validate base color");
match testing_color.improved_difference(base_lab) { let other_colors = colors
10.0.. => Some(testing_color), .iter()
_ => None, .filter_map(|col| {
} let testing_color = validate_color(col)?;
}) match testing_color.improved_difference(base_lab) {
.collect::<Vec<_>>(); 10.0.. => Some(testing_color),
let mut accent_color = PixelWand::new(); _ => None,
handle_magick_result!( }
accent_color.set_color("cielab(0.0,0.0,0.0)"), })
"Failed to init accent color" .collect::<Vec<_>>();
); let mut accent_lab = "cielab(0.0,0.0,0.0)".to_owned();
if let Some(color) = other_colors.first() { if let Some(color) = other_colors.first() {
let col = format!("cielab{:?}", color.into_components()); accent_lab = format!("cielab{:?}", color.into_components());
handle_magick_result!( }
accent_color.set_color(col.as_str()), let base_lab = handle_magick_result!(colors[0].get_color_as_string(), "Failed to serialize base color");
"Failed to set accent color" let data = ctx.data.write().await;
); let color_cache = data.get::<ColorsHaver>().expect("Failed to have colors option");
} let mut color_cache_map = color_cache.map.lock().await;
if color_cache_map.keys().len() > color_cache.max {
let use_dark_color = match validate_color(&colors[0]) { let key: String = color_cache_map.iter().next().unwrap().0.to_owned();
Some(color) => { color_cache_map.remove(&key);
let black_delta_e = Lab::<D65>::new(0.0, 0.0, 0.0).improved_difference(color); }
let white_delta_e = Lab::<D65>::new(100.0, 0.0, 0.0).improved_difference(color); color_cache_map.insert(image_uri, (base_lab.clone(), accent_lab.clone()));
black_delta_e > white_delta_e (base_lab, accent_lab)
} }
_ => false };
handle_magick_result!(base_color.set_color(base_lab.as_str()), "Failed to deserialize base color");
handle_magick_result!(accent_color.set_color(accent_lab.as_str()), "Failed to deserialize accent color");
let use_dark_color = match validate_color(&base_color) {
Some(color) => {
let black_delta_e = Lab::<D65>::new(0.0, 0.0, 0.0).improved_difference(color);
let white_delta_e = Lab::<D65>::new(100.0, 0.0, 0.0).improved_difference(color);
black_delta_e > white_delta_e
}
_ => false,
}; };
handle_magick_result!(white.set_color("#ffffff"), "Failed to init white"); handle_magick_result!(white.set_color("#ffffff"), "Failed to init white");
@ -328,22 +422,31 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Re
"Failed to set avatar colorspace" "Failed to set avatar colorspace"
); );
let (image_width, image_height) = (548, 147); let (image_width, image_height) = (548, 147);
let data = ctx.data.write().await; let data = ctx.data.write().await;
let fonts = data let fonts = data.get::<FontsHaver>().expect("Failed to load fonts");
.get::<FontsHaver>().expect("Failed to load fonts"); let text_image_blob = match text::fmi_text(
let text_image_blob = match text::fmi_text(image_width, image_height, track_info, fonts, 19.0, use_dark_color) { image_width,
Ok(bytes) => bytes, image_height,
Err(e) => return Reply::Text(e), track_info,
fonts,
19.0,
use_dark_color,
) {
Ok(bytes) => bytes,
Err(e) => return Reply::Text(e),
}; };
handle_magick_result!(text_image_wand.read_image_blob(&text_image_blob), "Failed to load text image"); handle_magick_result!(
text_image_wand.read_image_blob(&text_image_blob),
"Failed to load text image"
);
handle_magick_result!( handle_magick_result!(
text_image_wand.transform_image_colorspace(ColorspaceType::Lab), text_image_wand.transform_image_colorspace(ColorspaceType::Lab),
"Failed to set avatar colorspace" "Failed to set avatar colorspace"
); );
handle_magick_result!( handle_magick_result!(
main_wand.new_image(image_width as usize, image_height as usize, &colors[0]), main_wand.new_image(image_width as usize, image_height as usize, &base_color),
"Failed to create wand" "Failed to create wand"
); );
handle_magick_result!( handle_magick_result!(
@ -351,13 +454,13 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Re
"Failed to set main colorspace" "Failed to set main colorspace"
); );
handle_magick_result!( handle_magick_result!(
art_wand.adaptive_resize_image(124, 124), art_wand.resize_image(124, 124, FilterType::RobidouxSharp),
"Failed to resize art" "Failed to resize art"
); );
handle_magick_result!( /*handle_magick_result!(
art_wand_cluster.adaptive_resize_image(124, 124), art_wand_cluster.adaptive_resize_image(124, 124),
"Failed to resize art_cluster" "Failed to resize art_cluster"
); );*/
handle_magick_result!( handle_magick_result!(
main_wand.compose_images(&art_wand, CompositeOperator::SrcOver, false, 12, 12), main_wand.compose_images(&art_wand, CompositeOperator::SrcOver, false, 12, 12),
"Failed to combine art image" "Failed to combine art image"
@ -367,17 +470,17 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Re
"Failed to combine mask" "Failed to combine mask"
); );
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
if env::var("DEBUG_IMAGE").unwrap_or("0".to_string()) == "1" { if env::var("DEBUG_IMAGE").unwrap_or("0".to_owned()) == "1" {
handle_magick_result!( handle_magick_result!(
main_wand.compose_images( main_wand.compose_images(
&art_wand_cluster, &art_wand_cluster,
CompositeOperator::SrcOver, CompositeOperator::SrcOver,
false, false,
160, 160,
12 12
), ),
"Failed to combine debug image" "Failed to combine debug image"
); );
} }
handle_magick_result!( handle_magick_result!(
main_wand.compose_images(&text_image_wand, CompositeOperator::SrcOver, false, 0, 0), main_wand.compose_images(&text_image_wand, CompositeOperator::SrcOver, false, 0, 0),
@ -390,45 +493,138 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Re
Reply::Image(main_wand.write_image_blob("png").unwrap()) Reply::Image(main_wand.write_image_blob("png").unwrap())
} }
async fn text(ctx: &Context, arg: Option<&str>, id: UserId) -> Reply {
let track = match get_track(ctx, arg, id).await {
Ok(track) => track,
Err(e) => return e,
};
Reply::Text(format!(
"{}\n{}\n{}",
track.name,
track.artist.name,
track.album,
))
}
fn help(arg: Option<&str>) -> Reply {
Reply::Text(format!(
"```{}```",
match arg {
None =>
"usage: .k <img|set|art|url|spotify|help> [lastfm user]\n .k img [lastfm user]: get now playing\n .k set <lastfm user>: sets your username for the future\n .k art [lastfm user]: get now playing album art\n .k url [lastfm user]: get now playing lastfm url\n .k spot [lastfm user]: get now playing spotify link\n .k search <search query>: searches spotify\n .k help [command]: displays a help message"
.to_owned(),
Some("img" | "fmi" | "fm" | "get") =>
"usage: .k img [lastfm user]\nreturns a pretty-printed image of the user's now playing track on last.fm, using the album art's colors to theme the image. see also: .k set\naliases: .kfmi, .k <fmi|get|img>, .kf, .ki, or even just .k"
.to_owned(),
Some("set") =>
"usage: .k set <lastfm user>\nties a lastfm username to your account. use this to not require your username for .k fmi every time, for example\naliases: .kset"
.to_owned(),
Some("art") =>
"usage: .k art [lastfm user]\nfetches user's now playing track's album art\naliases: .k art, .kart, .ka"
.to_owned(),
Some("url" | "link") =>
"usage: .k url [lastfm user]\nfetches a lastfm link to user's now playing track\naliases: .k url, .k link, .kl, .ku, .kurl"
.to_owned(),
Some("spot" | "spotify") =>
"usage: .k spotify [lastfm user]\nsearches spotify for the user's now playing track and returns a link to that track\naliases: .k <spot|spotify>, .kx, .kspot"
.to_owned(),
Some("search") =>
"usage: .k search <search query>\nsearches spotify with an arbitrary query and returns the first result\naliases: .k search, .ks".to_owned(),
Some(cmd) => format!("unknown command: {cmd}"),
}
))
}
async fn set(ctx: &Context, arg: &str, id: UserId) -> Reply { async fn set(ctx: &Context, arg: &str, id: UserId) -> Reply {
set_lastfm_username(ctx, id, arg.to_string()).await; set_lastfm_username(ctx, id, arg.to_owned()).await;
Reply::Text(format!("set user {arg}")) Reply::Text(format!("set user {arg}"))
} }
//macro_rules! cmd { async fn search(ctx: &Context, arg: &str) -> Reply {
// (c:lit, abbr:lit, a:ident) => { let mut data = ctx.data.write().await;
// (".k", $c, $a) | (".k", $a, $c) | (concat!(".k", $abbr), $ident, "") let spotify_option = data.get_mut::<SpotifyHaver>().expect("Failed to have spotify option");
// } if spotify_option.is_none() {
//} return Reply::Text("Unable to use Spotify commands: Contact bot Administrator.".to_owned())
}
let spotify_arc_mutex = spotify_option.as_mut().unwrap();
let spotify_client = spotify_arc_mutex.lock().await;
spotify_client.request_token().await.unwrap();
let search = spotify_client.search(arg, SearchType::Track, None, None, None, None).await;
let tracks = match search {
Ok(SearchResult::Tracks(track_page)) => track_page,
Err(e) => return Reply::Text(format!("Failed to get track {e}")),
_ => return Reply::Text("Spotify search failed".to_owned()),
};
match &tracks.items.first().map(|x| x.external_urls.get("spotify")) {
Some(Some(url)) => Reply::Text(url.to_owned().to_owned()),
_ => Reply::Text("Unable to get spotify url".to_owned()),
}
}
macro_rules! cmd_pattern {
($long_cmd:pat, $short_pattern:pat, $arg_name:pat) => {
(Some(".k"), Some($long_cmd), $arg_name) | (Some(".k"), $arg_name, Some($long_cmd)) | (Some($short_pattern), $arg_name, None)
}
}
#[async_trait] #[async_trait]
impl EventHandler for Handler { impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) { async fn message(&self, ctx: Context, msg: Message) {
let mut cmd_iter = msg.content.split(" "); let mut cmd_iter = msg.content.split(" ");
let cmd = cmd_iter.next().unwrap_or(""); let cmd = cmd_iter.next();
let arg1 = cmd_iter.next().unwrap_or(""); let arg1 = cmd_iter.next();
let arg2 = cmd_iter.next().unwrap_or(""); let arg2 = cmd_iter.next();
let resp = match (cmd, arg1, arg2) { let resp = match (cmd, arg1, arg2) {
(".set", arg, "") | (".k", "set", arg) | (".kset", arg, "") => { (Some(".k"), Some("help" | "h" | "?"), arg) // skip the ".k <command> help" syntax
| (Some(".kh") | Some(".k?"), arg, None) => {
log!("{} received", msg.content);
Some(help(arg))
}
cmd_pattern!("set", ".kset" | ".set", Some(arg)) =>
/*(".set", arg, "") | (".k", "set", arg) | (".kset", arg, "") =>*/ {
log!("{} received", msg.content); log!("{} received", msg.content);
Some(set(&ctx, arg, msg.author.id).await) Some(set(&ctx, arg, msg.author.id).await)
}, },
(".k", "art", arg) | (".k", arg, "art") | (".ka" | ".kart", arg, "") => { cmd_pattern!("art", ".ka" | ".kart", arg) =>
log!("{} received", msg.content); /*(".k", "art", arg) | (".k", arg, "art") | (".ka" | ".kart", arg, "") =>*/ {
Some(art(&ctx, arg, msg.author.id).await) log!("{} received", msg.content);
Some(art(&ctx, arg, msg.author.id).await)
}, },
(".k", "url" | "uri" | "link", arg) | (".k", arg, "url" | "uri" | "link") | (".ku" | ".kl" | ".kurl", arg, "") => { cmd_pattern!("url" | "uri" | "link", ".ku" | ".kl", arg) =>
log!("{} received", msg.content); /*(".k", "url" | "uri" | "link", arg)
Some(url(&ctx, arg, msg.author.id).await) | (".k", arg, "url" | "uri" | "link")
| (".ku" | ".kl" | ".kurl", arg, "") =>*/ {
log!("{} received", msg.content);
Some(url(&ctx, arg, msg.author.id).await)
}, },
(".k", "spot" | "spotify", arg) | (".k", arg, "spot" | "spotify") | (".ks" | ".kspot", arg, "") => { cmd_pattern!("text", ".kt", arg) =>
log!("{} received", msg.content); /*(".k", "url" | "uri" | "link", arg)
Some(spot(&ctx, arg, msg.author.id).await) | (".k", arg, "url" | "uri" | "link")
| (".ku" | ".kl" | ".kurl", arg, "") =>*/ {
log!("{} received", msg.content);
Some(text(&ctx, arg, msg.author.id).await)
}, },
(".fmi" | ".k" | ".kf" | ".ki" | ".kfmi", arg, "") | (".k", "fm" | "fmi" | "get" | "img", arg) => { cmd_pattern!("spot" | "spotify", ".kx", arg) =>
/*(".k", "spot" | "spotify", arg)
| (".k", arg, "spot" | "spotify")
| (".ks" | ".kspot", arg, "") =>*/ {
log!("{} received", msg.content);
Some(spot(&ctx, arg, msg.author.id).await)
},
(Some(".ks"), Some(_), _) => {
log!("{} received", msg.content);
Some(search(&ctx, &msg.content[4..]).await)
},
(Some(".k"), Some("search"), Some(_)) => {
log!("{} received", msg.content);
Some(search(&ctx, &msg.content[10..]).await)
},
cmd_pattern!("fm" | "fmi" | "get" | "img", ".fmi" | ".k" | ".kf" | ".ki" | ".kfmi", arg) =>
/*(".fmi" | ".k" | ".kf" | ".ki" | ".kfmi", arg, "")
| (".k", "fm" | "fmi" | "get" | "img", arg) =>*/ {
log!("{} received", msg.content); log!("{} received", msg.content);
Some(fmi(&ctx, arg, msg.author.id, msg.author.avatar_url()).await) Some(fmi(&ctx, arg, msg.author.id, msg.author.avatar_url()).await)
}, }
_ => None, _ => None,
}; };
if let Some(reply) = resp { if let Some(reply) = resp {
@ -460,12 +656,30 @@ impl TypeMapKey for PoolHaver {
struct FontsHaver; struct FontsHaver;
impl TypeMapKey for FontsHaver { impl TypeMapKey for FontsHaver {
type Value = (SuperFont<'static>, SuperFont<'static>); type Value = (SuperFont<'static>, SuperFont<'static>);
} }
struct SpotifyHaver; struct SpotifyHaver;
impl TypeMapKey for SpotifyHaver { impl TypeMapKey for SpotifyHaver {
type Value = Option<Arc<Mutex<ClientCredsSpotify>>>; type Value = Option<Arc<Mutex<ClientCredsSpotify>>>;
}
struct ColorCache {
map: Arc<Mutex<HashMap<String, (String, String)>>>,
max: usize,
}
struct ColorsHaver;
impl TypeMapKey for ColorsHaver {
type Value = ColorCache;
}
struct Overrides {
map: Arc<Mutex<HashMap<String, String>>>,
last_modified: Option<SystemTime>,
}
struct OverridesHaver;
impl TypeMapKey for OverridesHaver {
type Value = Overrides;
} }
struct DBResponse { struct DBResponse {
@ -501,7 +715,7 @@ async fn get_lastfm_username(ctx: &Context, id: UserId) -> Option<String> {
async fn set_lastfm_username(ctx: &Context, id: UserId, user: String) { async fn set_lastfm_username(ctx: &Context, id: UserId, user: String) {
log!("set db user {} {}", id, user); log!("set db user {} {}", id, user);
let data = ctx.data.write().await; let data = ctx.data.read().await;
let pool = data let pool = data
.get::<PoolHaver>() .get::<PoolHaver>()
.expect("Failed to get pool container"); .expect("Failed to get pool container");
@ -520,11 +734,9 @@ async fn set_lastfm_username(ctx: &Context, id: UserId, user: String) {
} }
async fn get_image(ctx: &Context, url: &str) -> Result<Vec<u8>, reqwest_middleware::Error> { async fn get_image(ctx: &Context, url: &str) -> Result<Vec<u8>, reqwest_middleware::Error> {
log!("get {}", url); log!("get {}", url);
let data = ctx.data.write().await; let data = ctx.data.read().await;
let http = data let http = data.get::<HttpHaver>().expect("Failed to get http client");
.get::<HttpHaver>()
.expect("Failed to get http client");
match http.get(url).send().await { match http.get(url).send().await {
Ok(resp) => { Ok(resp) => {
log!("response received"); log!("response received");
@ -564,8 +776,9 @@ async fn main() {
})) }))
.build(); .build();
FontDB::load_from_dir("fonts"); //singlet instance??? wha????? FontDB::load_from_dir("fonts"); //singlet instance??? wha?????
let regular_fonts = FontDB::query(" let regular_fonts = FontDB::query(
"
NotoSans-Regular NotoSans-Regular
NotoSansHK-Regular NotoSansHK-Regular
NotoSansJP-Regular NotoSansJP-Regular
@ -577,8 +790,11 @@ async fn main() {
NotoEmoji-Regular NotoEmoji-Regular
Symbola Symbola
Unifont Unifont
").expect("Failed to load regular fonts"); ",
let bold_fonts = FontDB::query(" )
.expect("Failed to load regular fonts");
let bold_fonts = FontDB::query(
"
NotoSans-SemiBold NotoSans-SemiBold
NotoSansJP-Medium NotoSansJP-Medium
NotoSansKR-Medium NotoSansKR-Medium
@ -589,11 +805,26 @@ async fn main() {
NotoEmoji-Medium NotoEmoji-Medium
Symbola Symbola
Unifont Unifont
").expect("Failed to load bold fonts"); ",
)
.expect("Failed to load bold fonts");
let spotify_creds = Credentials::from_env(); let spotify_creds = Credentials::from_env();
let spotify = spotify_creds.map(ClientCredsSpotify::new).map(Mutex::new).map(Arc::new); let spotify = spotify_creds.map(ClientCredsSpotify::new);
if let Some(spotify_client) = &spotify {
let _ = &spotify_client.request_token().await.unwrap();
}
let colors_cache = ColorCache {
map: Arc::new(Mutex::new(HashMap::new())),
max: env::var("MAX_CACHE_SIZE").unwrap_or("".to_owned()).parse::<usize>().unwrap_or(1000000),
};
let overrides = Overrides {
map: Arc::new(Mutex::new(HashMap::new())),
last_modified: None,
};
let mut discord_client = Client::builder(&token, intents) let mut discord_client = Client::builder(&token, intents)
.event_handler(Handler) .event_handler(Handler)
.await .await
@ -604,7 +835,9 @@ async fn main() {
data.insert::<PoolHaver>(pool); data.insert::<PoolHaver>(pool);
data.insert::<HttpHaver>(http); data.insert::<HttpHaver>(http);
data.insert::<FontsHaver>((regular_fonts, bold_fonts)); data.insert::<FontsHaver>((regular_fonts, bold_fonts));
data.insert::<SpotifyHaver>(spotify); data.insert::<SpotifyHaver>(spotify.map(Mutex::new).map(Arc::new));
data.insert::<ColorsHaver>(colors_cache);
data.insert::<OverridesHaver>(overrides);
} }
if let Err(why) = discord_client.start().await { if let Err(why) = discord_client.start().await {

View File

@ -3,12 +3,12 @@
// since I'm using the same text rendering library, my code is almost one-to-one // since I'm using the same text rendering library, my code is almost one-to-one
use arabic_reshaper::arabic_reshape; use arabic_reshaper::arabic_reshape;
use imagetext::measure::text_width;
use imagetext::superfont::SuperFont;
use imagetext::wrap::{text_wrap, WrapStyle};
use imagetext::prelude::{scale, BLACK, WHITE, Outline, draw_text_wrapped, TextAlign, stroke};
use image::{RgbaImage, ExtendedColorType, ImageEncoder};
use image::codecs::png::PngEncoder; use image::codecs::png::PngEncoder;
use image::{ExtendedColorType, ImageEncoder, RgbaImage};
use imagetext::measure::text_width;
use imagetext::prelude::{BLACK, Outline, TextAlign, WHITE, draw_text_wrapped, scale, stroke};
use imagetext::superfont::SuperFont;
use imagetext::wrap::{WrapStyle, text_wrap};
use unicode_bidi::BidiInfo; use unicode_bidi::BidiInfo;
enum TextField { enum TextField {
@ -68,54 +68,89 @@ fn process_text(
(wrapped_strs, width) (wrapped_strs, width)
} }
fn draw_info(image: &mut RgbaImage, text: String, text_type: TextField, font: &SuperFont<'static>, font_size: f32, dark_text: bool) -> Result<(), String> { fn draw_info(
let (lines, width) = process_text(&text, &text_type, font, font_size); image: &mut RgbaImage,
let text = lines.join(""); text: String,
let y = match text_type { text_type: TextField,
TextField::Title => 24.0, font: &SuperFont<'static>,
TextField::Artist => 73.0, font_size: f32,
TextField::Album => 96.0, dark_text: bool,
}; ) -> Result<(), String> {
let color = if dark_text { &BLACK } else { &WHITE }; let (lines, width) = process_text(&text, &text_type, font, font_size);
match draw_text_wrapped( let text = lines.join("");
image, let y = match text_type {
color, TextField::Title => 24.0,
Outline::Solid { TextField::Artist => 73.0,
stroke: &stroke(0.5), TextField::Album => 96.0,
fill: color, };
}, let color = if dark_text { &BLACK } else { &WHITE };
146.0, match draw_text_wrapped(
y, image,
0.0, color,
0.0, Outline::Solid {
width as f32, stroke: &stroke(0.5),
scale(font_size), fill: color,
font, },
&text, 146.0,
1.0, y,
TextAlign::Left, 0.0,
WrapStyle::Character, 0.0,
) { width as f32,
Ok(_) => Ok(()), scale(font_size),
Err(e) => Err(e.to_string()), font,
} &text,
1.0,
TextAlign::Left,
WrapStyle::Character,
) {
Ok(_) => Ok(()),
Err(e) => Err(e.to_string()),
}
} }
pub struct TrackInfo { pub struct TrackInfo {
pub title: String, pub title: String,
pub artist: String, pub artist: String,
pub album: String, pub album: String,
} }
pub fn fmi_text(width: u32, height: u32, track: TrackInfo, fonts: &(SuperFont<'static>, SuperFont<'static>), font_size: f32, dark_text: bool) -> Result<Vec<u8>, String> { pub fn fmi_text(
let mut img = RgbaImage::new(width, height); width: u32,
draw_info(&mut img, track.title, TextField::Title, &fonts.1.clone(), font_size, dark_text)?; height: u32,
draw_info(&mut img, track.artist, TextField::Artist, &fonts.0.clone(), font_size, dark_text)?; track: TrackInfo,
draw_info(&mut img, track.album, TextField::Album, &fonts.0.clone(), font_size, dark_text)?; fonts: &(SuperFont<'static>, SuperFont<'static>),
let mut blob = Vec::<u8>::new(); font_size: f32,
let png_encoder = PngEncoder::new(&mut blob); dark_text: bool,
match png_encoder.write_image(&img, width, height, ExtendedColorType::Rgba8) { ) -> Result<Vec<u8>, String> {
Ok(()) => Ok(blob), let mut img = RgbaImage::new(width, height);
Err(_) => Err("Failed to encode text png".to_string()), draw_info(
} &mut img,
track.title,
TextField::Title,
&fonts.1.clone(),
font_size,
dark_text,
)?;
draw_info(
&mut img,
track.artist,
TextField::Artist,
&fonts.0.clone(),
font_size,
dark_text,
)?;
draw_info(
&mut img,
track.album,
TextField::Album,
&fonts.0.clone(),
font_size,
dark_text,
)?;
let mut blob = Vec::<u8>::new();
let png_encoder = PngEncoder::new(&mut blob);
match png_encoder.write_image(&img, width, height, ExtendedColorType::Rgba8) {
Ok(()) => Ok(blob),
Err(_) => Err("Failed to encode text png".to_string()),
}
} }