Removed imgur support

+ Added my own basic image handling
+ Probably not perfect but works good enough in testing
+ clippy + fmt
This commit is contained in:
2023-06-04 14:10:01 -06:00
parent 14032692b4
commit 7847bd38b9
14 changed files with 339 additions and 257 deletions
+99 -52
View File
@@ -1,6 +1,6 @@
use crate::album_manager::{Album, Image};
use crate::discord::admin::is_admin;
use crate::error::Error;
use crate::imgur::get_album_images;
use crate::models::album::AlbumConfig;
use crate::{command, group, GlobalData};
use j_db::model::JdbModel;
use serenity::client::Context;
@@ -8,64 +8,106 @@ use serenity::framework::standard::{Args, CommandResult};
use serenity::model::channel::Message;
#[group]
#[commands(add_album, remove_album, list_albums)]
pub struct Album;
#[commands(add_image, remove_album, list_albums, import_from_file)]
pub struct AlbumCmd;
#[command]
#[only_in(guilds)]
#[min_args(2)]
#[max_args(2)]
#[description("Add an imgur album command.")]
#[usage("<name> <album link>")]
async fn add_album(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
#[min_args(1)]
#[description("Add an image to an album")]
#[usage("<album_name>")]
async fn add_image(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let album_name = args.parse::<String>()?;
args.advance();
let album_id = args.parse::<String>()?;
let album_id: String = if album_id.contains("imgur") {
let parts: Vec<&str> = album_id.split("/a/").collect();
if parts.len() == 2 {
parts[1].to_string()
} else {
msg.reply(&ctx.http, "Invalid imgur album, check your link.")
.await?;
return Ok(());
}
} else {
album_id
};
let tags: Vec<String> = args.rest().split(',').map(|s| s.to_string()).collect();
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
let images = match get_album_images(&global_data.cfg.imgur_client_id, &album_id).await {
Ok(img) => img,
Err(e) => {
msg.reply(
&ctx.http,
"Error adding album, check your link and try again",
)
.await?;
let album = Album::find_album_by_name_or_alias(&global_data.db, &album_name).unwrap();
println!("Error adding album: {}", e);
return Ok(());
}
let mut album = if let Some(album) = album {
album
} else {
Album::add_album(&global_data.db, &album_name).unwrap()
};
global_data
.db
.insert(AlbumConfig::new(&album_name, &album_id))?;
for attachment in &msg.attachments {
let data = attachment.download().await.unwrap();
let img = Image::new(
&data,
&attachment.filename,
global_data.cfg.img_path.clone(),
tags.clone(),
)
.await;
album.images.push(img);
}
global_data
.bot_state
.albums
.insert(album_name.clone(), images);
global_data.db.insert(album).unwrap();
msg.reply(&ctx.http, format!("{} album added!", album_name))
.await?;
let plural = if msg.attachments.len() > 1 { "s" } else { "" };
msg.reply(
&ctx.http,
format!("Image{} added to {}!", plural, album_name),
)
.await?;
Ok(())
}
#[command]
#[only_in(guilds)]
#[min_args(1)]
#[description("Bulk add images")]
#[usage("<path>")]
async fn import_from_file(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let album_name = args.parse::<String>()?;
args.advance();
let album_path = args.parse::<String>()?;
let album_path = album_path.replace('"', "");
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
if !is_admin(&msg.author.id, &global_data.cfg) {
return Ok(());
}
let album = Album::find_album_by_name_or_alias(&global_data.db, &album_name).unwrap();
let mut album = if let Some(album) = album {
album
} else {
Album::add_album(&global_data.db, &album_name).unwrap()
};
let mut dir = tokio::fs::read_dir(album_path).await.unwrap();
while let Some(entry) = dir.next_entry().await? {
let data = tokio::fs::read(entry.path()).await?;
let img = Image::new(
&data,
entry.path().file_name().unwrap().to_str().unwrap(),
global_data.cfg.img_path.clone(),
vec![],
)
.await;
album.images.push(img);
}
global_data.db.insert(album).unwrap();
let plural = if msg.attachments.len() > 1 { "s" } else { "" };
msg.reply(
&ctx.http,
format!("Image{} added to {}!", plural, album_name),
)
.await?;
Ok(())
}
@@ -82,7 +124,7 @@ async fn remove_album(ctx: &Context, msg: &Message, args: Args) -> CommandResult
let global_data = data.get_mut::<GlobalData>().unwrap();
let album = AlbumConfig::get_album_by_name(&global_data.db, &album_name)?;
let album = Album::find_album_by_name_or_alias(&global_data.db, &album_name).unwrap();
match album {
None => {
@@ -93,9 +135,13 @@ async fn remove_album(ctx: &Context, msg: &Message, args: Args) -> CommandResult
.await?;
}
Some(album) => {
global_data.bot_state.albums.remove(&album_name);
for img in &album.images {
tokio::fs::remove_file(img.full_path(global_data.cfg.img_path.clone()))
.await
.unwrap();
}
global_data.db.remove::<AlbumConfig>(album.id().unwrap())?;
global_data.db.remove::<Album>(album.id().unwrap())?;
msg.reply(&ctx.http, format!("{} album removed!", album_name))
.await?;
@@ -116,8 +162,8 @@ async fn list_albums(ctx: &Context, msg: &Message, _args: Args) -> CommandResult
let album_names: Vec<String> = global_data
.db
.filter(|_, _: &AlbumConfig| true)?
.map(|album| album.name)
.filter(|_, _: &Album| true)?
.map(|album| album.album_name)
.collect();
if album_names.is_empty() {
@@ -143,7 +189,7 @@ pub async fn parse_album(
let data = ctx.data.read().await;
let global_data = data.get::<GlobalData>().unwrap();
let img = match global_data.bot_state.get_image(album_name, tags) {
let img = match Album::get_random_image(&global_data.db, album_name, tags) {
Ok(img) => img,
Err(err) => {
return match err {
@@ -154,7 +200,8 @@ pub async fn parse_album(
};
if let Some(img) = img {
msg.reply(&ctx.http, img.link).await?;
msg.reply(&ctx.http, img.link(&global_data.cfg.base_url))
.await?;
} else {
msg.reply(&ctx.http, "No image found :(").await?;
}
+8 -3
View File
@@ -1,3 +1,4 @@
use crate::album_manager::Album;
use crate::error::Error;
use crate::models::insult_compliment::{RandomResponseTemplate, ResponseType};
use crate::models::random::RandomConfig;
@@ -55,11 +56,15 @@ impl RandomCtx {
pub fn new(user_name: &str, global_data: &GlobalData) -> Result<Self, Error> {
let mut random_image: HashMap<String, String> = HashMap::new();
for (album_name, images) in &global_data.bot_state.albums {
let image = images.choose(&mut thread_rng());
let albums: Vec<Album> = global_data.db.filter(|_, _album: &Album| true)?.collect();
for album in albums {
let image = album.images.choose(&mut thread_rng());
if let Some(image) = image {
random_image.insert(album_name.clone(), image.link.clone());
random_image.insert(
album.album_name.clone(),
image.link(&global_data.cfg.base_url).to_string(),
);
}
}
+4 -7
View File
@@ -16,7 +16,7 @@ use std::borrow::Cow;
pub struct Motivate;
pub async fn create_motivation_image(motivation: Motivation) -> Result<Vec<u8>, CommandError> {
let motivation_image_blob = reqwest::get(&motivation.image_url).await?.bytes().await?;
let motivation_image_blob = tokio::fs::read(motivation.image_path).await?;
let text = format!("{} {}", motivation.action, motivation.goal);
@@ -64,12 +64,9 @@ async fn motivation(ctx: &Context, msg: &Message, _args: Args) -> CommandResult
let data = ctx.data.read().await;
let global_data = data.get::<GlobalData>().unwrap();
let motivation = MotivationConfig::generate_motivation(
&global_data.db,
&global_data.cfg.imgur_client_id,
"white",
)
.await?;
let motivation =
MotivationConfig::generate_motivation(&global_data.db, &global_data.cfg.img_path, "white")
.await?;
let image = create_motivation_image(motivation).await?;
+1 -1
View File
@@ -312,7 +312,7 @@ pub async fn restock_shop(ctx: &Context) -> Result<(), CommandError> {
let nft_motivation = MotivationConfig::generate_motivation(
&global_data.db,
&global_data.cfg.imgur_client_id,
&global_data.cfg.img_path,
"gold",
)
.await