Added picox support!

This commit is contained in:
joeyahines committed 2024-02-11 18:39:09 -07:00
1 parent 4dd45ec681
commit c08ec0120d
10 files changed
+284 -266

No files matched your search

+23 -134
View File
@@ -1,14 +1,12 @@
use crate::album_manager::{Album, Image};
use crate::discord::admin::is_admin;
use crate::album_manager::AlbumQuery;
use crate::error::Error;
use crate::{command, group, GlobalData};
use j_db::model::JdbModel;
use serenity::client::Context;
use serenity::framework::standard::{Args, CommandResult};
use serenity::model::channel::Message;
#[group]
#[commands(add_image, remove_album, list_albums, import_from_file)]
#[commands(add_image, list_albums)]
pub struct AlbumCmd;
#[command]
@@ -24,127 +22,23 @@ async fn add_image(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul
let global_data = data.get_mut::<GlobalData>().unwrap();
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()
};
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.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(())
}
#[command]
#[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(())
}
#[command]
#[max_args(1)]
#[description("Remove an imgur album command.")]
#[usage("<name>")]
async fn remove_album(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
let album_name = args.parse::<String>()?;
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
let album = Album::find_album_by_name_or_alias(&global_data.db, &album_name).unwrap();
match album {
None => {
msg.reply(
&ctx.http,
"I already got rid of that one, or I never had it. Who knows!",
)
global_data
.picox
.add_image(&album_name, tags.clone(), &attachment.filename, data)
.await?;
}
Some(album) => {
for img in &album.images {
tokio::fs::remove_file(img.full_path(global_data.cfg.img_path.clone()))
.await
.unwrap();
}
global_data.db.remove::<Album>(album.id().unwrap())?;
msg.reply(&ctx.http, format!("{} album removed!", 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(())
}
@@ -156,14 +50,15 @@ async fn list_albums(ctx: &Context, msg: &Message, _args: Args) -> CommandResult
let global_data = data.get::<GlobalData>().unwrap();
let album_names: Vec<String> = global_data
.db
.filter(|_, _: &Album| true)?
.map(|album| album.album_name)
.collect();
let albums = global_data
.picox
.query_album(AlbumQuery { album_name: None })
.await?;
let album_names: Vec<String> = albums.iter().map(|a| a.album_name.clone()).collect();
if album_names.is_empty() {
msg.reply(&ctx.http, "There are no albums configured!")
msg.reply(&ctx.http, "There are no albums in picox!")
.await?;
} else {
msg.reply(
@@ -185,19 +80,13 @@ pub async fn parse_album(
let data = ctx.data.read().await;
let global_data = data.get::<GlobalData>().unwrap();
let img = match Album::get_random_image(&global_data.db, album_name, tags) {
let img = match global_data.picox.get_random_image(album_name, tags).await {
Ok(img) => img,
Err(err) => {
return match err {
Error::NoAlbumFound => Ok(false),
_ => Err(err),
}
}
Err(_) => return Ok(false),
};
if let Some(img) = img {
msg.reply(&ctx.http, img.link(&global_data.cfg.base_url))
.await?;
msg.reply(&ctx.http, img.link).await?;
} else {
msg.reply(&ctx.http, "No image found :(").await?;
}
+23 -14
View File
@@ -1,10 +1,8 @@
use crate::album_manager::Album;
use crate::album_manager::{Album, AlbumQuery, ImageQuery, ImageSort};
use crate::error::Error;
use crate::models::insult_compliment::{RandomResponseTemplate, ResponseType};
use crate::models::random::RandomConfig;
use crate::{command, group, GlobalData, BAD_APPLE};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serenity::builder::EditMessage;
@@ -53,18 +51,28 @@ struct RandomCtx {
}
impl RandomCtx {
pub fn new(user_name: &str, global_data: &GlobalData) -> Result<Self, Error> {
pub async fn new(user_name: &str, global_data: &GlobalData) -> Result<Self, Error> {
let mut random_image: HashMap<String, String> = HashMap::new();
let albums: Vec<Album> = global_data.db.filter(|_, _album: &Album| true)?.collect();
let albums: Vec<Album> = global_data
.picox
.query_album(AlbumQuery { album_name: None })
.await?;
for album in albums {
let image = album.images.choose(&mut thread_rng());
let images = global_data
.picox
.query_image(ImageQuery {
album: Some(album.album_name.clone()),
tags: vec![],
order: ImageSort::Random,
limit: 1,
})
.await?;
let image = images.first();
if let Some(image) = image {
random_image.insert(
album.album_name.clone(),
image.link(&global_data.cfg.base_url).to_string(),
);
random_image.insert(album.album_name.clone(), image.link.to_string());
}
}
@@ -75,12 +83,12 @@ impl RandomCtx {
}
}
pub fn render_random(
pub async fn render_random(
author_name: &str,
global_data: &GlobalData,
template: &str,
) -> Result<String, Error> {
let random_ctx = RandomCtx::new(author_name, global_data)?;
let random_ctx = RandomCtx::new(author_name, global_data).await?;
Ok(tera::Tera::one_off(
template,
@@ -118,7 +126,8 @@ pub async fn random(ctx: &Context, msg: &Message, random_name: &str) -> CommandR
guild_member.display_name(),
global_data,
response_template_str,
)?;
)
.await?;
msg.reply(&ctx.http, reply).await?;
@@ -144,7 +153,7 @@ pub async fn add_random(ctx: &Context, msg: &Message, mut args: Args) -> Command
args.advance();
let random_response = args.rest();
if let Err(err) = render_random(&msg.author.name, global_data, random_response) {
if let Err(err) = render_random(&msg.author.name, global_data, random_response).await {
msg.reply(
&ctx.http,
format!("Template failed test render, try again: {}", err),
+26 -3
View File
@@ -1,6 +1,8 @@
use crate::album_manager::AlbumQuery;
use crate::models::motivation::{Motivation, MotivationConfig};
use crate::{command, group, GlobalData};
use magick_rust::{DrawingWand, MagickWand, PixelWand};
use reqwest::Client;
use serenity::builder::{CreateAttachment, CreateMessage};
use serenity::client::Context;
use serenity::framework::standard::{Args, CommandError, CommandResult};
@@ -17,7 +19,15 @@ use std::borrow::Cow;
pub struct Motivate;
pub async fn create_motivation_image(motivation: Motivation) -> Result<Vec<u8>, CommandError> {
let motivation_image_blob = tokio::fs::read(motivation.image_path).await?;
let client = Client::new();
let motivation_image_blob = client
.get(motivation.image.link)
.send()
.await?
.bytes()
.await?
.to_vec();
let text = format!("{} {}", motivation.action, motivation.goal);
@@ -72,7 +82,7 @@ async fn motivation(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
let motivation = MotivationConfig::generate_motivation(
&global_data.db,
&global_data.cfg.img_path,
&global_data.picox,
"white",
album_name,
)
@@ -102,8 +112,21 @@ async fn motivation_add_album(ctx: &Context, msg: &Message, args: Args) -> Comma
let global_data = data.get::<GlobalData>().unwrap();
let album = args.parse::<String>()?;
let albums = global_data
.picox
.query_album(AlbumQuery {
album_name: Some(album),
})
.await?;
MotivationConfig::add_album(&global_data.db, &album)?;
let album = if let Some(album) = albums.first().cloned() {
album
} else {
msg.reply(&ctx.http, "Fake album tbh, try again!").await?;
return Ok(());
};
MotivationConfig::add_album(&global_data.db, album.id)?;
msg.reply(&ctx.http, "Done ;)").await?;
+1 -1
View File
@@ -466,7 +466,7 @@ pub async fn restock_shop(ctx: &Context, global_data: &GlobalData) -> Result<(),
let nft_motivation = MotivationConfig::generate_motivation(
&global_data.db,
&global_data.cfg.img_path,
&global_data.picox,
"gold",
None,
)