Merged my own stupid divergence
This commit is contained in:
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -4270,7 +4270,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "watcat"
|
name = "watcat"
|
||||||
version = "0.4.0"
|
version = "0.5.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"arabic_reshaper",
|
"arabic_reshaper",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "watcat"
|
name = "watcat"
|
||||||
version = "0.4.0"
|
version = "0.5.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@ -29,10 +29,11 @@ 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~~
|
||||||
+ make various parameters user-configurable
|
+ make various parameters user-configurable
|
||||||
+ use tiny-skia instead of magick-rust?
|
+ use tiny-skia instead of magick-rust?
|
||||||
|
|||||||
244
src/main.rs
244
src/main.rs
@ -11,10 +11,12 @@ 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 std::env;
|
use std::env;
|
||||||
use std::sync::{Once, Arc};
|
use std::sync::{Arc, Once};
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use palette::color_difference::ImprovedCiede2000;
|
use palette::color_difference::ImprovedCiede2000;
|
||||||
@ -24,8 +26,8 @@ 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;
|
||||||
@ -52,13 +54,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),+)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -79,7 +81,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,51 +120,59 @@ 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: &str,
|
||||||
|
id: UserId,
|
||||||
|
) -> Result<lastfm::track::NowPlayingTrack, Reply> {
|
||||||
let lastfm_user = match arg {
|
let lastfm_user = match arg {
|
||||||
"" => get_lastfm_username(ctx, id).await,
|
"" => get_lastfm_username(ctx, id).await,
|
||||||
_ => Some(arg.to_string()),
|
_ => Some(arg.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: &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: &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: &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() {
|
||||||
@ -185,18 +195,18 @@ async fn spot(ctx: &Context, arg: &str, id: UserId) -> Reply {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Reply {
|
async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> 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_info = text::TrackInfo {
|
let track_info = text::TrackInfo {
|
||||||
title: track.name,
|
title: track.name,
|
||||||
artist: track.artist.name,
|
artist: track.artist.name,
|
||||||
album: track.album,
|
album: track.album,
|
||||||
};
|
};
|
||||||
let image_uri = match track.image.extralarge {
|
let 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 image = match get_image(ctx, image_uri.as_str()).await {
|
||||||
@ -270,14 +280,14 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId, avatar: Option<String>) -> Re
|
|||||||
"Failed to set accent color"
|
"Failed to set accent color"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let use_dark_color = match validate_color(&colors[0]) {
|
let use_dark_color = match validate_color(&colors[0]) {
|
||||||
Some(color) => {
|
Some(color) => {
|
||||||
let black_delta_e = Lab::<D65>::new(0.0, 0.0, 0.0).improved_difference(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);
|
let white_delta_e = Lab::<D65>::new(100.0, 0.0, 0.0).improved_difference(color);
|
||||||
black_delta_e > white_delta_e
|
black_delta_e > white_delta_e
|
||||||
}
|
}
|
||||||
_ => false
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
handle_magick_result!(white.set_color("#ffffff"), "Failed to init white");
|
handle_magick_result!(white.set_color("#ffffff"), "Failed to init white");
|
||||||
@ -328,15 +338,24 @@ 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"
|
||||||
@ -367,17 +386,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,8 +409,35 @@ 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())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn help(arg: &str) -> Reply {
|
||||||
|
Reply::Text(format!(
|
||||||
|
"```{}```",
|
||||||
|
match arg {
|
||||||
|
"" =>
|
||||||
|
"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 help [command]: displays a help message"
|
||||||
|
.to_owned(),
|
||||||
|
"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(),
|
||||||
|
"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(),
|
||||||
|
"art" =>
|
||||||
|
"usage: .k art [lastfm user]\nfetches user's now playing track's album art\naliases: .k art, .kart, .ka"
|
||||||
|
.to_owned(),
|
||||||
|
"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(),
|
||||||
|
"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>, .ks, .kspot"
|
||||||
|
.to_owned(),
|
||||||
|
_ => format!("unknown command: {arg}"),
|
||||||
|
}
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
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}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -406,23 +452,34 @@ impl EventHandler for Handler {
|
|||||||
(".set", arg, "") | (".k", "set", arg) | (".kset", 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, "") => {
|
(".k", "art", arg) | (".k", arg, "art") | (".ka" | ".kart", arg, "") => {
|
||||||
log!("{} received", msg.content);
|
log!("{} received", msg.content);
|
||||||
Some(art(&ctx, arg, msg.author.id).await)
|
Some(art(&ctx, arg, msg.author.id).await)
|
||||||
},
|
}
|
||||||
(".k", "url" | "uri" | "link", arg) | (".k", arg, "url" | "uri" | "link") | (".ku" | ".kl" | ".kurl", arg, "") => {
|
(".k", "url" | "uri" | "link", arg)
|
||||||
log!("{} received", msg.content);
|
| (".k", arg, "url" | "uri" | "link")
|
||||||
Some(url(&ctx, arg, msg.author.id).await)
|
| (".ku" | ".kl" | ".kurl", arg, "") => {
|
||||||
},
|
log!("{} received", msg.content);
|
||||||
(".k", "spot" | "spotify", arg) | (".k", arg, "spot" | "spotify") | (".ks" | ".kspot", arg, "") => {
|
Some(url(&ctx, arg, msg.author.id).await)
|
||||||
log!("{} received", msg.content);
|
}
|
||||||
Some(spot(&ctx, arg, msg.author.id).await)
|
(".k", "spot" | "spotify", arg)
|
||||||
},
|
| (".k", arg, "spot" | "spotify")
|
||||||
(".fmi" | ".k" | ".kf" | ".ki" | ".kfmi", arg, "") | (".k", "fm" | "fmi" | "get" | "img", arg) => {
|
| (".ks" | ".kspot", arg, "") => {
|
||||||
|
log!("{} received", msg.content);
|
||||||
|
Some(spot(&ctx, arg, msg.author.id).await)
|
||||||
|
}
|
||||||
|
(".k", "help" | "h" | "?", arg)
|
||||||
|
| (".k", arg, "help" | "h" | "?")
|
||||||
|
| (".kh" | ".k?", arg, "") => {
|
||||||
|
log!("{} received", msg.content);
|
||||||
|
Some(help(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 {
|
||||||
@ -454,12 +511,12 @@ 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 DBResponse {
|
struct DBResponse {
|
||||||
@ -516,9 +573,7 @@ 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.write().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");
|
||||||
@ -558,8 +613,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
|
||||||
@ -571,8 +627,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
|
||||||
@ -583,11 +642,16 @@ 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 mut discord_client = Client::builder(&token, intents)
|
let mut discord_client = Client::builder(&token, intents)
|
||||||
.event_handler(Handler)
|
.event_handler(Handler)
|
||||||
.await
|
.await
|
||||||
@ -598,7 +662,7 @@ 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));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Err(why) = discord_client.start().await {
|
if let Err(why) = discord_client.start().await {
|
||||||
|
|||||||
135
src/text.rs
135
src/text.rs
@ -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()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user