Added http caching of lastfm images
This commit is contained in:
78
src/main.rs
78
src/main.rs
@ -1,5 +1,8 @@
|
||||
extern crate dotenvy;
|
||||
extern crate lastfm;
|
||||
extern crate reqwest;
|
||||
extern crate reqwest_middleware;
|
||||
use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};
|
||||
|
||||
use serenity::async_trait;
|
||||
use serenity::builder::{CreateAttachment, CreateMessage};
|
||||
@ -28,7 +31,10 @@ enum Reply {
|
||||
macro_rules! handle_magick_result {
|
||||
($a: expr, $b: literal) => {
|
||||
match $a {
|
||||
Ok(_) => {}
|
||||
Ok(_) => {
|
||||
#[cfg(debug_assertions)]
|
||||
println!("debug: {} run successfully", stringify!($a));
|
||||
}
|
||||
Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)),
|
||||
}
|
||||
};
|
||||
@ -49,11 +55,11 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId) -> Reply {
|
||||
"" => get_lastfm_username(ctx, id).await,
|
||||
_ => Some(arg.to_string()),
|
||||
};
|
||||
let client = match lastfm_user {
|
||||
Some(s) => lastfm::Client::<String, String>::from_env(s),
|
||||
None => return Reply::Text("No last.fm username set.".to_string()),
|
||||
let lastfm_client = match lastfm_user {
|
||||
Some(s) => lastfm::Client::<String, String>::from_env(s),
|
||||
None => return Reply::Text("No last.fm username set.".to_string()),
|
||||
};
|
||||
let now_playing = match client.now_playing().await {
|
||||
let now_playing = match lastfm_client.now_playing().await {
|
||||
Ok(np) => np,
|
||||
Err(e) => return Reply::Text(format!("Error: grabbing last.fm user data failed {e}")),
|
||||
};
|
||||
@ -65,6 +71,14 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId) -> Reply {
|
||||
Some(iu) => iu,
|
||||
None => return Reply::Text("Error: getting image uri failed".to_string()),
|
||||
};
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
println!("{}", image_uri);
|
||||
|
||||
let image = match get_image(ctx, image_uri.as_str()).await {
|
||||
Ok(i) => i,
|
||||
Err(e) => return Reply::Text(format!("{}", e)),
|
||||
};
|
||||
let mut base_color = PixelWand::new();
|
||||
let mut white = PixelWand::new();
|
||||
let mut main_wand = MagickWand::new();
|
||||
@ -77,7 +91,7 @@ async fn fmi(ctx: &Context, arg: &str, id: UserId) -> Reply {
|
||||
"Failed to set init base color"
|
||||
);
|
||||
handle_magick_result!(
|
||||
art_wand.read_image(image_uri.as_str()),
|
||||
art_wand.read_image_blob(image),
|
||||
"Failed to read image from uri"
|
||||
);
|
||||
handle_magick_result!(
|
||||
@ -158,8 +172,8 @@ async fn fmi(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;
|
||||
Reply::Text(format!("set user {}", arg))
|
||||
set_lastfm_username(ctx, id, arg.to_string()).await;
|
||||
Reply::Text(format!("set user {}", arg))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@ -190,8 +204,12 @@ impl EventHandler for Handler {
|
||||
}
|
||||
}
|
||||
|
||||
struct PoolContainer;
|
||||
struct HttpContainer;
|
||||
impl TypeMapKey for HttpContainer {
|
||||
type Value = reqwest_middleware::ClientWithMiddleware;
|
||||
}
|
||||
|
||||
struct PoolContainer;
|
||||
impl TypeMapKey for PoolContainer {
|
||||
type Value = SqlitePool;
|
||||
}
|
||||
@ -234,10 +252,31 @@ async fn set_lastfm_username(ctx: &Context, id: UserId, user: String) {
|
||||
INSERT INTO users
|
||||
VALUES (?1, ?2)
|
||||
"#,
|
||||
id, user
|
||||
id,
|
||||
user
|
||||
)
|
||||
.execute(pool)
|
||||
.await.expect("Failed to insert");
|
||||
.await
|
||||
.expect("Failed to insert");
|
||||
}
|
||||
|
||||
async fn get_image(ctx: &Context, url: &str) -> Result<Vec<u8>, reqwest_middleware::Error> {
|
||||
let data = ctx.data.write().await;
|
||||
let http = data
|
||||
.get::<HttpContainer>()
|
||||
.expect("Failed to get http client");
|
||||
match http.get(url).send().await {
|
||||
Ok(resp) => {
|
||||
#[cfg(debug_assertions)]
|
||||
println!("{:?}", resp);
|
||||
Ok(resp
|
||||
.bytes()
|
||||
.await
|
||||
.expect("Unable to resolve bytes")
|
||||
.to_vec())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
@ -258,17 +297,24 @@ async fn main() {
|
||||
| GatewayIntents::DIRECT_MESSAGES
|
||||
| GatewayIntents::MESSAGE_CONTENT;
|
||||
|
||||
let mut client = Client::builder(&token, intents)
|
||||
let mut discord_client = Client::builder(&token, intents)
|
||||
.event_handler(Handler)
|
||||
.await
|
||||
.expect("Err creating client");
|
||||
|
||||
.expect("Err creating Discord client");
|
||||
let http = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
|
||||
.with(Cache(HttpCache {
|
||||
mode: CacheMode::Default,
|
||||
manager: CACacheManager::default(),
|
||||
options: HttpCacheOptions::default(),
|
||||
}))
|
||||
.build();
|
||||
{
|
||||
let mut data = client.data.write().await;
|
||||
let mut data = discord_client.data.write().await;
|
||||
data.insert::<PoolContainer>(pool);
|
||||
data.insert::<HttpContainer>(http);
|
||||
}
|
||||
|
||||
if let Err(why) = client.start().await {
|
||||
if let Err(why) = discord_client.start().await {
|
||||
println!("Client error: {why:?}");
|
||||
} else {
|
||||
println!("watcat started");
|
||||
|
||||
Reference in New Issue
Block a user