Formatting code

This commit is contained in:
Benjamin Sherriff
2024-05-12 09:05:59 -04:00
parent c971c55aa3
commit 1de68f86ae
46 changed files with 1109 additions and 609 deletions

View File

@@ -1,5 +1,3 @@
version: '3.8'
x-env_file: &env x-env_file: &env
- path: .env - path: .env
required: true required: true

View File

@@ -86,7 +86,10 @@ impl InsertUser {
Ok(user) Ok(user)
} }
pub fn update_profile(email: &str, profile_picture: Option<&str>) -> Result<QueryUser, ServiceError> { pub fn update_profile(
email: &str,
profile_picture: Option<&str>,
) -> Result<QueryUser, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let user = diesel::update(users::table) let user = diesel::update(users::table)
.filter(users::email.eq(&email)) .filter(users::email.eq(&email))
@@ -120,7 +123,7 @@ impl From<QueryUser> for ResponseUser {
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Auth { pub struct Auth {
pub id: String, pub id: String,
pub user: ResponseUser pub user: ResponseUser,
} }
impl FromRequest for Auth { impl FromRequest for Auth {
@@ -131,21 +134,30 @@ impl FromRequest for Auth {
.cookie(SESSION_COOKIE_NAME) .cookie(SESSION_COOKIE_NAME)
.map(|c| c.value().to_string()) .map(|c| c.value().to_string())
.or_else(|| { .or_else(|| {
req.headers().get(http::header::AUTHORIZATION) req
.headers()
.get(http::header::AUTHORIZATION)
.map(|h| h.to_str().unwrap().split_at(7).1.to_string()) .map(|h| h.to_str().unwrap().split_at(7).1.to_string())
}) { }) {
Some(token) => token, Some(token) => token,
None => return ready(Err(ActixError::from(ServiceError { None => {
return ready(Err(ActixError::from(ServiceError {
status: 401, status: 401,
message: "Unauthorized".to_string() message: "Unauthorized".to_string(),
}))) })))
}
}; };
let ip_address = req.peer_addr().unwrap().ip().to_string(); let ip_address = req.peer_addr().unwrap().ip().to_string();
match Session::verify(&session_id, &ip_address) { match Session::verify(&session_id, &ip_address) {
Ok(v) => return ready(Ok(Auth { id: v.0.id, user: v.1.into() })), Ok(v) => {
Err(err) => return ready(Err(ActixError::from(err))) return ready(Ok(Auth {
id: v.0.id,
user: v.1.into(),
}))
}
Err(err) => return ready(Err(ActixError::from(err))),
} }
} }
} }
@@ -156,7 +168,7 @@ pub fn verify_role(auth: &Auth, role: &str) -> Result<(), ServiceError> {
} else { } else {
Err(ServiceError { Err(ServiceError {
status: 403, status: 403,
message: "Forbidden".to_string() message: "Forbidden".to_string(),
}) })
} }
} }

View File

@@ -1,11 +1,18 @@
use std::env; use std::env;
use actix_web::{get, post, web, HttpResponse, ResponseError, cookie::{Cookie, time::Duration}, HttpRequest}; use actix_web::{
get, post, web, HttpResponse, ResponseError,
cookie::{Cookie, time::Duration},
HttpRequest,
};
use log::error; use log::error;
use redis::AsyncCommands; use redis::AsyncCommands;
use siren::ServiceError; use siren::ServiceError;
use crate::{auth::{InsertUser, Auth, LoginRequest, QueryUser, RegisterUser, Session, SESSION_COOKIE_NAME}, storage::{self}}; use crate::{
auth::{InsertUser, Auth, LoginRequest, QueryUser, RegisterUser, Session, SESSION_COOKIE_NAME},
storage::{self},
};
use super::verify_hash; use super::verify_hash;
@@ -14,12 +21,10 @@ async fn register(user: web::Json<RegisterUser>) -> HttpResponse {
let register_user = user.0; let register_user = user.0;
let insert_user: InsertUser = match register_user.convert_to_insert() { let insert_user: InsertUser = match register_user.convert_to_insert() {
Ok(user) => user, Ok(user) => user,
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
match InsertUser::insert(insert_user) { match InsertUser::insert(insert_user) {
Ok(_) => { Ok(_) => HttpResponse::Created().finish(),
HttpResponse::Created().finish()
},
Err(err) => { Err(err) => {
// Obfuscate the service error message to prevent leaking database details // Obfuscate the service error message to prevent leaking database details
if err.status == 409 { if err.status == 409 {
@@ -39,10 +44,12 @@ async fn login(request: HttpRequest, login_request: web::Json<LoginRequest>) ->
let query_user = match QueryUser::get_by_email(&email) { let query_user = match QueryUser::get_by_email(&email) {
Ok(query_user) => query_user, Ok(query_user) => query_user,
Err(_) => return ResponseError::error_response(&ServiceError { Err(_) => {
return ResponseError::error_response(&ServiceError {
status: 401, status: 401,
message: "The email or password was incorrect.".to_string() message: "The email or password was incorrect.".to_string(),
}) })
}
}; };
// Verify password // Verify password
if verify_hash(&login_request.password, &query_user.hash) { if verify_hash(&login_request.password, &query_user.hash) {
@@ -52,7 +59,7 @@ async fn login(request: HttpRequest, login_request: web::Json<LoginRequest>) ->
Ok(conn) => conn, Ok(conn) => conn,
Err(err) => { Err(err) => {
error!("Failed to get redis connection: {}", err); error!("Failed to get redis connection: {}", err);
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
} }
}; };
@@ -61,10 +68,16 @@ async fn login(request: HttpRequest, login_request: web::Json<LoginRequest>) ->
.parse::<i64>() .parse::<i64>()
.expect("SESSION_TTL must be an integer"); .expect("SESSION_TTL must be an integer");
let session_result: redis::RedisResult<()> = conn.set_ex(session.id.to_string(), &serde_json::to_string(&session).unwrap(), (session_ttl * 60) as usize).await; let session_result: redis::RedisResult<()> = conn
.set_ex(
session.id.to_string(),
&serde_json::to_string(&session).unwrap(),
(session_ttl * 60) as usize,
)
.await;
if let Err(err) = session_result { if let Err(err) = session_result {
error!("Failed to set access token in redis: {}", err); error!("Failed to set access token in redis: {}", err);
return ResponseError::error_response(&ServiceError::from(err)) return ResponseError::error_response(&ServiceError::from(err));
}; };
let session_cookie = Cookie::build(SESSION_COOKIE_NAME, session.id.clone()) let session_cookie = Cookie::build(SESSION_COOKIE_NAME, session.id.clone())
@@ -82,12 +95,15 @@ async fn login(request: HttpRequest, login_request: web::Json<LoginRequest>) ->
HttpResponse::Ok() HttpResponse::Ok()
.cookie(session_cookie) .cookie(session_cookie)
.cookie(user_id_cookie) .cookie(user_id_cookie)
.json(Auth { id: session.id, user: query_user.into() }) .json(Auth {
id: session.id,
user: query_user.into(),
})
} else { } else {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 401, status: 401,
message: "The email or password was incorrect.".to_string() message: "The email or password was incorrect.".to_string(),
}) });
} }
} }
@@ -99,7 +115,7 @@ async fn refresh(req: HttpRequest, auth: Auth) -> HttpResponse {
Ok(conn) => conn, Ok(conn) => conn,
Err(err) => { Err(err) => {
error!("Failed to get redis connection: {}", err); error!("Failed to get redis connection: {}", err);
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
} }
}; };
@@ -113,10 +129,16 @@ async fn refresh(req: HttpRequest, auth: Auth) -> HttpResponse {
// Create new session // Create new session
let session = Session::new(&auth.user.email, &ip_address); let session = Session::new(&auth.user.email, &ip_address);
let session_result: redis::RedisResult<()> = conn.set_ex(session.id.to_string(), &serde_json::to_string(&session).unwrap(), (session_ttl * 60) as usize).await; let session_result: redis::RedisResult<()> = conn
.set_ex(
session.id.to_string(),
&serde_json::to_string(&session).unwrap(),
(session_ttl * 60) as usize,
)
.await;
if let Err(err) = session_result { if let Err(err) = session_result {
error!("Failed to set session id in redis: {}", err); error!("Failed to set session id in redis: {}", err);
return ResponseError::error_response(&ServiceError::from(err)) return ResponseError::error_response(&ServiceError::from(err));
}; };
// Create cookies // Create cookies
@@ -130,7 +152,10 @@ async fn refresh(req: HttpRequest, auth: Auth) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.cookie(session_cookie) .cookie(session_cookie)
.cookie(user_id_cookie) .cookie(user_id_cookie)
.json(Auth { id: session.id, user: auth.user }) .json(Auth {
id: session.id,
user: auth.user,
})
} }
#[post("/logout")] #[post("/logout")]
@@ -139,14 +164,14 @@ async fn logout(auth: Auth) -> HttpResponse {
Ok(conn) => conn, Ok(conn) => conn,
Err(err) => { Err(err) => {
error!("Failed to get redis connection: {}", err); error!("Failed to get redis connection: {}", err);
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
} }
}; };
let session_result: redis::RedisResult<()> = conn.del(&auth.id.to_string()).await; let session_result: redis::RedisResult<()> = conn.del(&auth.id.to_string()).await;
if let Err(err) = session_result { if let Err(err) = session_result {
error!("Failed to remove session id in redis: {}", err); error!("Failed to remove session id in redis: {}", err);
return ResponseError::error_response(&ServiceError::from(err)) return ResponseError::error_response(&ServiceError::from(err));
}; };
let session_cookie = Cookie::build(SESSION_COOKIE_NAME, "") let session_cookie = Cookie::build(SESSION_COOKIE_NAME, "")
@@ -189,12 +214,13 @@ pub fn init_routes(config: &mut web::ServiceConfig) {
u.role = "admin".to_string(); u.role = "admin".to_string();
u.verified = true; u.verified = true;
let _ = InsertUser::insert(u); let _ = InsertUser::insert(u);
config.service(web::scope("auth") config.service(
web::scope("auth")
.service(register) .service(register)
.service(login) .service(login)
.service(refresh) .service(refresh)
.service(logout) .service(logout)
.service(me) .service(me)
.service(roles) .service(roles),
); );
} }

View File

@@ -1,7 +1,10 @@
use std::env; use std::env;
use actix_web::cookie::{time::Duration, Cookie}; use actix_web::cookie::{time::Duration, Cookie};
use argon2::{password_hash::{rand_core::OsRng, SaltString}, Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; use argon2::{
password_hash::{rand_core::OsRng, SaltString},
Argon2, PasswordHash, PasswordHasher, PasswordVerifier,
};
use rand::prelude::*; use rand::prelude::*;
use rand_chacha::ChaCha20Rng; use rand_chacha::ChaCha20Rng;
use redis::Commands; use redis::Commands;
@@ -31,7 +34,7 @@ impl Session {
id: csprng_128bit(), id: csprng_128bit(),
user_id: user_id.to_string(), user_id: user_id.to_string(),
ip_address: hash(&ip_address).unwrap(), ip_address: hash(&ip_address).unwrap(),
expiration: (now + chrono::Duration::minutes(ttl)).timestamp() expiration: (now + chrono::Duration::minutes(ttl)).timestamp(),
} }
} }
@@ -40,7 +43,7 @@ impl Session {
// Check if the session exists // Check if the session exists
let session = match conn.get::<_, String>(session_id) { let session = match conn.get::<_, String>(session_id) {
Ok(session) => session, Ok(session) => session,
Err(_) => return Err(ServiceError::new(401, "Unauthorized".to_string())) Err(_) => return Err(ServiceError::new(401, "Unauthorized".to_string())),
}; };
let session: Self = serde_json::from_str(&session)?; let session: Self = serde_json::from_str(&session)?;
// Check if the IP address matches // Check if the IP address matches
@@ -51,12 +54,12 @@ impl Session {
// Check if the user exists // Check if the user exists
let user = match crate::auth::model::QueryUser::get_by_email(&email) { let user = match crate::auth::model::QueryUser::get_by_email(&email) {
Ok(user) => user, Ok(user) => user,
Err(_) => return Err(ServiceError::new(401, "Unauthorized".to_string())) Err(_) => return Err(ServiceError::new(401, "Unauthorized".to_string())),
}; };
// Check if the session has expired // Check if the session has expired
let now = chrono::Utc::now().timestamp(); let now = chrono::Utc::now().timestamp();
if now < session.expiration { if now < session.expiration {
return Ok((session, user)) return Ok((session, user));
} }
} }
Err(ServiceError::new(401, "Unauthorized".to_string())) Err(ServiceError::new(401, "Unauthorized".to_string()))
@@ -79,7 +82,11 @@ impl Session {
fn csprng_128bit() -> String { fn csprng_128bit() -> String {
// Generate a CSPRNG 128-bit (16 byte) ID using alphanumeric characters (a-z, A-Z, 0-9) // Generate a CSPRNG 128-bit (16 byte) ID using alphanumeric characters (a-z, A-Z, 0-9)
let rng = ChaCha20Rng::from_entropy(); let rng = ChaCha20Rng::from_entropy();
rng.sample_iter(rand::distributions::Alphanumeric).take(16).map(char::from).collect() rng
.sample_iter(rand::distributions::Alphanumeric)
.take(16)
.map(char::from)
.collect()
} }
pub fn hash(str: &str) -> Result<String, ServiceError> { pub fn hash(str: &str) -> Result<String, ServiceError> {
@@ -93,10 +100,10 @@ pub fn verify_hash(str: &str, hash: &str) -> bool {
let bytes = str.as_bytes(); let bytes = str.as_bytes();
let parsed_hash = match PasswordHash::new(hash) { let parsed_hash = match PasswordHash::new(hash) {
Ok(h) => h, Ok(h) => h,
Err(_) => return false Err(_) => return false,
}; };
match Argon2::default().verify_password(bytes, &parsed_hash) { match Argon2::default().verify_password(bytes, &parsed_hash) {
Ok(_) => true, Ok(_) => true,
Err(_) => false Err(_) => false,
} }
} }

View File

@@ -4,7 +4,9 @@ use log::{debug, warn};
use reqwest::Url; use reqwest::Url;
use serenity::client::Cache; use serenity::client::Cache;
use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction}; use serenity::model::application::interaction::{
InteractionResponseType, application_command::ApplicationCommandInteraction,
};
use serenity::model::prelude::{GuildId, ChannelId}; use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User; use serenity::model::user::User;
use serenity::prelude::*; use serenity::prelude::*;
@@ -21,33 +23,60 @@ pub mod skip;
pub mod stop; pub mod stop;
pub mod volume; pub mod volume;
pub async fn join_by_user(cache: &Arc<Cache>, manager: Arc<Songbird>, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), ServiceError> { pub async fn join_by_user(
cache: &Arc<Cache>,
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
user: &User,
) -> Result<(), ServiceError> {
let guild_id = match guild_id_option { let guild_id = match guild_id_option {
Some(g) => g, Some(g) => g,
None => return Err(ServiceError { status: 422, message: format!("{}", "No guild ID set") }) None => {
return Err(ServiceError {
status: 422,
message: format!("{}", "No guild ID set"),
})
}
}; };
let channel_id = match find_voice_channel(cache, &guild_id, &user) { let channel_id = match find_voice_channel(cache, &guild_id, &user) {
Ok(channel) => channel, Ok(channel) => channel,
Err(err) => return Err(ServiceError { status: 500, message: err.to_string() }) Err(err) => {
return Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
}; };
join(manager, guild_id, &channel_id).await join(manager, guild_id, &channel_id).await
} }
pub async fn join(manager: Arc<Songbird>, guild_id: &GuildId, channel_id: &ChannelId) -> Result<(), ServiceError> { pub async fn join(
manager: Arc<Songbird>,
guild_id: &GuildId,
channel_id: &ChannelId,
) -> Result<(), ServiceError> {
debug!("<{}> Joining channel {}", guild_id.0, channel_id.0); debug!("<{}> Joining channel {}", guild_id.0, channel_id.0);
let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await; let (_handle_lock, success) = manager
.join(guild_id.to_owned(), channel_id.to_owned())
.await;
match success { match success {
Ok(s) => Ok(s), Ok(s) => Ok(s),
Err(err) => { Err(err) => {
warn!("Failed to join channel: {:?}", err); warn!("Failed to join channel: {:?}", err);
Err(ServiceError { status: 500, message: err.to_string() }) Err(ServiceError {
status: 500,
message: err.to_string(),
})
} }
} }
} }
pub async fn leave(manager: Arc<Songbird>, guild_id_option: &Option<GuildId>) -> Result<(), String> { pub async fn leave(
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
) -> Result<(), String> {
let guild_id = match guild_id_option { let guild_id = match guild_id_option {
Some(g) => g, Some(g) => g,
None => { None => {
@@ -58,39 +87,72 @@ pub async fn leave(manager: Arc<Songbird>, guild_id_option: &Option<GuildId>) ->
if manager.get(*guild_id).is_some() { if manager.get(*guild_id).is_some() {
debug!("<{}> Disconnecting from channel", guild_id.0); debug!("<{}> Disconnecting from channel", guild_id.0);
if let Err(e) = manager.remove(*guild_id).await { if let Err(e) = manager.remove(*guild_id).await {
return Err(format!("{}", e)) return Err(format!("{}", e));
} }
} }
Ok(()) Ok(())
} }
fn find_voice_channel(cache: &Arc<Cache>, guild_id: &GuildId, user: &User) -> Result<ChannelId, String> { fn find_voice_channel(
cache: &Arc<Cache>,
guild_id: &GuildId,
user: &User,
) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(cache.to_owned()) { let guild = match guild_id.to_guild_cached(cache.to_owned()) {
Some(g) => g, Some(g) => g,
None => return Err(format!("Guild not found")) None => return Err(format!("Guild not found")),
}; };
match guild.voice_states.get(&user.id).and_then(|voice_state| voice_state.channel_id) { match guild
.voice_states
.get(&user.id)
.and_then(|voice_state| voice_state.channel_id)
{
Some(channel) => Ok(channel), Some(channel) => Ok(channel),
None => return Err(format!("User is not in a voice channel")) None => return Err(format!("User is not in a voice channel")),
} }
} }
pub async fn create_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<(), SerenityError> { pub async fn create_response(
command.create_interaction_response(&ctx.http, |response: &mut serenity::builder::CreateInteractionResponse<'_>| { ctx: &Context,
command: &ApplicationCommandInteraction,
content: String,
) -> Result<(), SerenityError> {
command
.create_interaction_response(
&ctx.http,
|response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response response
.kind(InteractionResponseType::ChannelMessageWithSource) .kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message: &mut serenity::builder::CreateInteractionResponseData<'_>| message.content(content)) .interaction_response_data(
}).await |message: &mut serenity::builder::CreateInteractionResponseData<'_>| {
message.content(content)
},
)
},
)
.await
} }
pub async fn edit_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<serenity::model::channel::Message, SerenityError> { pub async fn edit_response(
command.edit_original_interaction_response(&ctx.http, |response: &mut serenity::builder::EditInteractionResponse| { ctx: &Context,
response.content(content) command: &ApplicationCommandInteraction,
}).await content: String,
) -> Result<serenity::model::channel::Message, SerenityError> {
command
.edit_original_interaction_response(
&ctx.http,
|response: &mut serenity::builder::EditInteractionResponse| response.content(content),
)
.await
} }
pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, volume: Option<f32>) -> Result<Metadata, SongbirdError> { pub async fn add_song(
call: Arc<Mutex<Call>>,
url: &str,
lazy: bool,
volume: Option<f32>,
) -> Result<Metadata, SongbirdError> {
let source = Restartable::ytdl(url.to_owned(), lazy).await?; let source = Restartable::ytdl(url.to_owned(), lazy).await?;
let mut handler = call.lock().await; let mut handler = call.lock().await;
let track: Input = source.into(); let track: Input = source.into();
@@ -115,9 +177,10 @@ pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
None None
} else { } else {
Some( Some(
serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err( serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err(|err| ServiceError {
|err| ServiceError { status: 500, message: err.to_string() } status: 500,
) message: err.to_string(),
}),
) )
} }
}) })
@@ -134,11 +197,16 @@ pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
fn is_valid_url(url: &str) -> (bool, bool) { fn is_valid_url(url: &str) -> (bool, bool) {
Url::parse(url).ok().map_or((false, false), |valid_url| { Url::parse(url).ok().map_or((false, false), |valid_url| {
let is_playlist: bool = valid_url.query_pairs().find(|(key, _)| key == "list").map_or(false, |_| true); let is_playlist: bool = valid_url
.query_pairs()
.find(|(key, _)| key == "list")
.map_or(false, |_| true);
(true, is_playlist) (true, is_playlist)
}) })
} }
pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> { pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> {
songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization") songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialization")
} }

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
None => { None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await { if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
return; return;

View File

@@ -10,7 +10,10 @@ use siren::ServiceError;
use songbird::{EventHandler, Songbird}; use songbird::{EventHandler, Songbird};
use crate::bot::ytdlp::PlaylistItem; use crate::bot::ytdlp::PlaylistItem;
use crate::bot::{guilds::QueryGuild, commands::audio::{leave, get_playlist_urls, add_song, get_songbird}}; use crate::bot::{
guilds::QueryGuild,
commands::audio::{leave, get_playlist_urls, add_song, get_songbird},
};
use super::{create_response, edit_response, is_valid_url, join_by_user}; use super::{create_response, edit_response, is_valid_url, join_by_user};
@@ -22,20 +25,23 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
Some(s) => s.to_owned(), Some(s) => s.to_owned(),
None => { None => {
warn!("Missing track option"); warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await { if let Err(why) =
create_response(&ctx, &command, format!("Track option is missing")).await
{
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
return; return;
} }
} },
None => { None => {
warn!("Missing track option"); warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await { if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await
{
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
return; return;
} }
} },
None => { None => {
warn!("Missing track option"); warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await { if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
@@ -52,12 +58,14 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
let manager = get_songbird(ctx).await; let manager = get_songbird(ctx).await;
match join_by_user(&ctx.cache, manager,&command.guild_id, &command.user).await { match join_by_user(&ctx.cache, manager, &command.guild_id, &command.user).await {
Ok(_) => { Ok(_) => {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
None => { None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await { if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
return; return;
@@ -76,15 +84,17 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
if let Err(why) = edit_response(&ctx, &command, message).await { if let Err(why) = edit_response(&ctx, &command, message).await {
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
}, }
Err(err) => { Err(err) => {
warn!("Failed to play track: {}", err); warn!("Failed to play track: {}", err);
if let Err(why) = edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await { if let Err(why) =
edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
} }
}; };
}, }
Err(err) => { Err(err) => {
warn!("{}", err); warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await { if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
@@ -94,7 +104,11 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: String) -> Result<i32, ServiceError> { pub async fn play_track(
manager: Arc<Songbird>,
guild_id: GuildId,
track_url: String,
) -> Result<i32, ServiceError> {
let mut track_count = 0; let mut track_count = 0;
if let Some(handler_lock) = manager.get(guild_id) { if let Some(handler_lock) = manager.get(guild_id) {
let is_queue_empty = { let is_queue_empty = {
@@ -105,7 +119,10 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
let valid = is_valid_url(&track_url); let valid = is_valid_url(&track_url);
if !valid.0 { if !valid.0 {
warn!("Invalid track url: {}", track_url); warn!("Invalid track url: {}", track_url);
return Err(ServiceError { status: 422, message: format!("Invalid track url: {}", track_url) }) return Err(ServiceError {
status: 422,
message: format!("Invalid track url: {}", track_url),
});
} }
let mut playlist_items: Vec<PlaylistItem> = Vec::new(); let mut playlist_items: Vec<PlaylistItem> = Vec::new();
if valid.1 { if valid.1 {
@@ -113,7 +130,10 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
Ok(items) => items, Ok(items) => items,
Err(err) => { Err(err) => {
warn!("Failed to get playlist urls: {}", err); warn!("Failed to get playlist urls: {}", err);
return Err(ServiceError { status: 422, message: err.to_string() }) return Err(ServiceError {
status: 422,
message: err.to_string(),
});
} }
}; };
} else { } else {
@@ -122,26 +142,42 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
url: track_url, url: track_url,
title: "".to_string(), title: "".to_string(),
duration: 0, duration: 0,
playlist_index: 0 playlist_index: 0,
}; };
playlist_items.push(playlist_item); playlist_items.push(playlist_item);
} }
for item in playlist_items { for item in playlist_items {
match add_song(handler_lock.clone(), &item.url, is_queue_empty, Some(guild.volume as f32 / 100.0)).await { match add_song(
handler_lock.clone(),
&item.url,
is_queue_empty,
Some(guild.volume as f32 / 100.0),
)
.await
{
Ok(added_song) => { Ok(added_song) => {
let track_title = added_song.title.unwrap(); let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title); debug!("Added track: {}", track_title);
let mut handler = handler_lock.lock().await; let mut handler = handler_lock.lock().await;
handler.remove_all_global_events(); handler.remove_all_global_events();
handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), TrackEndNotifier { guild_id, call: manager.clone() }); handler.add_global_event(
track_count += 1; songbird::Event::Track(songbird::TrackEvent::End),
TrackEndNotifier {
guild_id,
call: manager.clone(),
}, },
);
track_count += 1;
}
Err(err) => { Err(err) => {
warn!("Failed to add song: {}", err); warn!("Failed to add song: {}", err);
if let Err(why) = leave(manager, &Some(guild_id)).await { if let Err(why) = leave(manager, &Some(guild_id)).await {
error!("Failed to leave voice channel: {}", why); error!("Failed to leave voice channel: {}", why);
} }
return Err(ServiceError { status: 422, message: err.to_string() }) return Err(ServiceError {
status: 422,
message: err.to_string(),
});
} }
} }
} }
@@ -150,7 +186,11 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("play").description("Plays the given track").create_option(|option| { option command
.name("play")
.description("Plays the given track")
.create_option(|option| {
option
.name("track") .name("track")
.description("The track to be played") .description("The track to be played")
.kind(serenity::model::prelude::command::CommandOptionType::String) .kind(serenity::model::prelude::command::CommandOptionType::String)
@@ -160,7 +200,7 @@ pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicatio
struct TrackEndNotifier { struct TrackEndNotifier {
pub call: std::sync::Arc<songbird::Songbird>, pub call: std::sync::Arc<songbird::Songbird>,
pub guild_id: serenity::model::id::GuildId pub guild_id: serenity::model::id::GuildId,
} }
#[async_trait] #[async_trait]

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
None => { None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await { if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
return; return;
@@ -39,5 +41,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("resume").description("Resume the current track") command
.name("resume")
.description("Resume the current track")
} }

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
None => { None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await { if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
return; return;

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
None => { None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await { if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
return; return;
@@ -34,5 +36,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("stop").description("Stop the current track and clear the queue") command
.name("stop")
.description("Stop the current track and clear the queue")
} }

View File

@@ -19,20 +19,23 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
Some(p) => p as i32, Some(p) => p as i32,
None => { None => {
warn!("Unable to get volume option as a string"); warn!("Unable to get volume option as a string");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await { if let Err(why) =
create_response(&ctx, &command, format!("Volume option is missing")).await
{
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
return; return;
} }
} },
None => { None => {
warn!("Missing volume option value"); warn!("Missing volume option value");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await { if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await
{
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
return; return;
} }
} },
None => { None => {
warn!("Missing volume option"); warn!("Missing volume option");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await { if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
@@ -51,7 +54,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
None => { None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await { if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why); error!("Failed to edit response message: {}", why);
} }
return; return;
@@ -59,7 +64,8 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}; };
let manager = get_songbird(ctx).await; let manager = get_songbird(ctx).await;
set_volume(manager, guild_id, volume).await; set_volume(manager, guild_id, volume).await;
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await { if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await
{
error!("Failed to set the volume: {}", why); error!("Failed to set the volume: {}", why);
} }
} }
@@ -79,7 +85,11 @@ pub async fn set_volume(manager: Arc<Songbird>, guild_id: GuildId, volume: i32)
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("volume").description("Set the audio player volume").create_option(|option| { option command
.name("volume")
.description("Set the audio player volume")
.create_option(|option| {
option
.name("volume") .name("volume")
.description("Volume between 0 and 100") .description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer) .kind(serenity::model::prelude::command::CommandOptionType::Integer)

View File

@@ -26,31 +26,34 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
}, },
]; ];
match QueryMessage::get_all(&QueryFilters { match QueryMessage::get_all(
&QueryFilters {
by_guild_id: Some(guild_id.0 as i64), by_guild_id: Some(guild_id.0 as i64),
by_channel_id: Some(channel_id.0 as i64), by_channel_id: Some(channel_id.0 as i64),
by_user_id: Some(author_id.0 as i64), by_user_id: Some(author_id.0 as i64),
..Default::default() ..Default::default()
}, 100, 1) { },
100,
1,
) {
Ok(m) => { Ok(m) => {
for message in m { for message in m {
messages.push( messages.push(ChatCompletionMessage {
ChatCompletionMessage {
role: GPTRole::User, role: GPTRole::User,
content: format!("{}", message.request) content: format!("{}", message.request),
} });
); messages.push(ChatCompletionMessage {
messages.push(
ChatCompletionMessage {
role: GPTRole::Assistant, role: GPTRole::Assistant,
content: format!("{}", message.response) content: format!("{}", message.response),
});
} }
);
} }
}, Err(err) => warn!("Could not load previous messages: {}", err),
Err(err) => warn!("Could not load previous messages: {}", err)
}; };
messages.push(ChatCompletionMessage { role: GPTRole::User, content: parsed_content.clone() }); messages.push(ChatCompletionMessage {
role: GPTRole::User,
content: parsed_content.clone(),
});
let request = ChatCompletionRequest { let request = ChatCompletionRequest {
model: oai.default_model.clone(), model: oai.default_model.clone(),
@@ -61,14 +64,18 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
max_tokens: Some(oai.max_tokens), max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6), presence_penalty: Some(0.6),
frequency_penalty: Some(0.0), frequency_penalty: Some(0.0),
user: Some(msg.author.name.clone()) user: Some(msg.author.name.clone()),
}; };
// Get the thread channel ID // Get the thread channel ID
let thread_name = generate_thread_name(oai, &parsed_content, 99).await; let thread_name = generate_thread_name(oai, &parsed_content, 99).await;
let response_channel = match msg.channel_id.create_private_thread(&ctx.http, |thread| { let response_channel = match msg
.channel_id
.create_private_thread(&ctx.http, |thread| {
thread.name(thread_name).kind(ChannelType::PublicThread) thread.name(thread_name).kind(ChannelType::PublicThread)
}).await { })
.await
{
Ok(c) => { Ok(c) => {
let allow = Permissions::SEND_MESSAGES; let allow = Permissions::SEND_MESSAGES;
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES; let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
@@ -80,9 +87,7 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
let _ = c.create_permission(&ctx.http, &overwrite).await; let _ = c.create_permission(&ctx.http, &overwrite).await;
c.id c.id
} }
Err(_) => { Err(_) => channel_id,
channel_id
}
}; };
let typing = response_channel.start_typing(&ctx.http).unwrap(); let typing = response_channel.start_typing(&ctx.http).unwrap();
@@ -144,7 +149,10 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String { async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
let message = ChatCompletionMessage { let message = ChatCompletionMessage {
role: GPTRole::User, role: GPTRole::User,
content: format!("---\n{}\n---\nSummarize the message above into a concise Discord thread title", s) content: format!(
"---\n{}\n---\nSummarize the message above into a concise Discord thread title",
s
),
}; };
let request = ChatCompletionRequest { let request = ChatCompletionRequest {
model: oai.default_model.clone(), model: oai.default_model.clone(),
@@ -155,13 +163,14 @@ async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
max_tokens: Some(oai.max_tokens), max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6), presence_penalty: Some(0.6),
frequency_penalty: Some(0.0), frequency_penalty: Some(0.0),
user: None user: None,
}; };
// Truncate the response to the max number of characters // Truncate the response to the max number of characters
let mut response = match s.char_indices().nth(max_chars) { let mut response = match s.char_indices().nth(max_chars) {
None => s, None => s,
Some((idx, _)) => &s[..idx] Some((idx, _)) => &s[..idx],
}.to_string(); }
.to_string();
// Set the response to the OAI response // Set the response to the OAI response
match oai.chat_completion(request).await { match oai.chat_completion(request).await {
Ok(r) => { Ok(r) => {

View File

@@ -0,0 +1 @@

View File

@@ -1,6 +1,6 @@
pub mod audio; pub mod audio;
pub mod help;
pub mod chat; pub mod chat;
pub mod help;
pub mod ping; pub mod ping;
pub mod schedule;
pub mod roll; pub mod roll;
pub mod schedule;

View File

@@ -1,5 +1,8 @@
use log::debug; use log::debug;
use serenity::{model::prelude::interaction::application_command::CommandDataOption, builder::CreateApplicationCommand}; use serenity::{
model::prelude::interaction::application_command::CommandDataOption,
builder::CreateApplicationCommand,
};
pub fn run(_options: &[CommandDataOption]) -> String { pub fn run(_options: &[CommandDataOption]) -> String {
debug!("Ping command executed"); debug!("Ping command executed");

View File

@@ -1,6 +1,12 @@
use log::{error, warn}; use log::{error, warn};
use rand::Rng; use rand::Rng;
use serenity::{builder::CreateApplicationCommand, client::Context, model::application::{command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction}}; use serenity::{
builder::CreateApplicationCommand,
client::Context,
model::application::{
command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction,
},
};
use crate::bot::commands::audio::edit_response; use crate::bot::commands::audio::edit_response;
@@ -49,10 +55,17 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
total += roll; total += roll;
rolls.push(roll); rolls.push(roll);
} }
let response = format!("{}d{}{} = {}", let response = format!(
"{}d{}{} = {}",
count, count,
sides, sides,
if modifier > 0 { format!("+{}", modifier) } else if modifier < 0 { format!("-{}", modifier) } else { "".to_string() }, if modifier > 0 {
format!("+{}", modifier)
} else if modifier < 0 {
format!("-{}", modifier)
} else {
"".to_string()
},
total + (modifier as u32) total + (modifier as u32)
); );
if let Err(why) = edit_response(&ctx, &command, response).await { if let Err(why) = edit_response(&ctx, &command, response).await {
@@ -60,13 +73,12 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
Err(why) => { Err(why) => {
if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await { if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await
{
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
} }
} }
} }
fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> { fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
@@ -74,9 +86,9 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
let count = match parts.next() { let count = match parts.next() {
Some(c) => match c.parse::<u32>() { Some(c) => match c.parse::<u32>() {
Ok(n) => n, Ok(n) => n,
Err(_) => return Err(format!("Invalid dice count: {}", c)) Err(_) => return Err(format!("Invalid dice count: {}", c)),
}, },
None => return Err(format!("Invalid dice string: {}", dice)) None => return Err(format!("Invalid dice string: {}", dice)),
}; };
let mut positive_modifier = true; let mut positive_modifier = true;
let mut parts = match parts.next() { let mut parts = match parts.next() {
@@ -91,8 +103,8 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
} else { } else {
p.split("+") p.split("+")
} }
}, }
None => return Err(format!("Invalid dice string: {}", dice)) None => return Err(format!("Invalid dice string: {}", dice)),
}; };
let sides = match parts.next() { let sides = match parts.next() {
Some(s) => match s.parse::<u32>() { Some(s) => match s.parse::<u32>() {
@@ -103,9 +115,9 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
return Err(format!("Invalid dice sides: {}", s)); return Err(format!("Invalid dice sides: {}", s));
} }
} }
Err(_) => return Err(format!("Invalid dice sides: {}", s)) Err(_) => return Err(format!("Invalid dice sides: {}", s)),
}, },
None => return Err(format!("Invalid dice string: {}", dice)) None => return Err(format!("Invalid dice string: {}", dice)),
}; };
let modifier = match parts.next() { let modifier = match parts.next() {
Some(m) => match m.parse::<i32>() { Some(m) => match m.parse::<i32>() {
@@ -115,16 +127,19 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
} else { } else {
n * -1 n * -1
} }
}
Err(_) => return Err(format!("Invalid dice modifier: {}", m)),
}, },
Err(_) => return Err(format!("Invalid dice modifier: {}", m)) None => 0,
},
None => 0
}; };
Ok((count, sides, modifier)) Ok((count, sides, modifier))
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("roll").description("Rolls D&D dice").create_option(|option| { command
.name("roll")
.description("Rolls D&D dice")
.create_option(|option| {
option option
.name("dice") .name("dice")
.description("Dice to roll") .description("Dice to roll")

View File

@@ -0,0 +1 @@

View File

@@ -9,7 +9,7 @@ use crate::storage::{schema::guilds, connection};
pub struct QueryGuild { pub struct QueryGuild {
pub id: i64, pub id: i64,
pub bot_id: i64, pub bot_id: i64,
pub volume: i32 pub volume: i32,
} }
impl QueryGuild { impl QueryGuild {
@@ -25,19 +25,23 @@ impl QueryGuild {
pub struct InsertGuild { pub struct InsertGuild {
pub id: i64, pub id: i64,
pub bot_id: i64, pub bot_id: i64,
pub volume: i32 pub volume: i32,
} }
impl InsertGuild { impl InsertGuild {
pub fn insert(guild: Self) -> Result<QueryGuild, ServiceError> { pub fn insert(guild: Self) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let guild = diesel::insert_into(guilds::table).values(guild).get_result(&mut conn)?; let guild = diesel::insert_into(guilds::table)
.values(guild)
.get_result(&mut conn)?;
Ok(guild) Ok(guild)
} }
pub fn update_audio(id: i64, volume: i32) -> Result<QueryGuild, ServiceError> { pub fn update_audio(id: i64, volume: i32) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let guild = diesel::update(guilds::table.filter(guilds::id.eq(id))).set(guilds::volume.eq(volume)).get_result(&mut conn)?; let guild = diesel::update(guilds::table.filter(guilds::id.eq(id)))
.set(guilds::volume.eq(volume))
.get_result(&mut conn)?;
Ok(guild) Ok(guild)
} }
} }

View File

@@ -5,74 +5,104 @@ use serde::{Serialize, Deserialize};
use serenity::model::prelude::{GuildChannel, ChannelType}; use serenity::model::prelude::{GuildChannel, ChannelType};
use siren::{ServiceError, Response}; use siren::{ServiceError, Response};
use crate::{AppState, bot::commands::audio::{play::play_track, join}, bot::guilds::QueryGuild, auth::{Auth, verify_role}}; use crate::{
AppState,
bot::commands::audio::{play::play_track, join},
bot::guilds::QueryGuild,
auth::{Auth, verify_role},
};
#[get("/guilds")] #[get("/guilds")]
async fn get_guilds(data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn get_guilds(data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_results = &data.http.get_guilds(None, None).await; let guild_results = &data.http.get_guilds(None, None).await;
let guilds = match guild_results { let guilds = match guild_results {
Ok(guilds) => guilds, Ok(guilds) => guilds,
Err(err) => return ResponseError::error_response(&ServiceError { Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
HttpResponse::Ok().json(Response { HttpResponse::Ok().json(Response {
data: guilds, data: guilds,
metadata: None metadata: None,
}) })
} }
#[get("/{id}/text")] #[get("/{id}/text")]
async fn get_text_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn get_text_channels(
id: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await; let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
let channels = match channel_results { let channels = match channel_results {
Ok(channels) => channels.iter().filter(|c| c.kind == ChannelType::Text).collect::<Vec<&GuildChannel>>(), Ok(channels) => channels
Err(err) => return ResponseError::error_response(&ServiceError { .iter()
.filter(|c| c.kind == ChannelType::Text)
.collect::<Vec<&GuildChannel>>(),
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
HttpResponse::Ok().json(Response { HttpResponse::Ok().json(Response {
data: channels, data: channels,
metadata: None metadata: None,
}) })
} }
#[get("/{id}/voice")] #[get("/{id}/voice")]
async fn get_voice_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn get_voice_channels(
id: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await; let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
let channels = match channel_results { let channels = match channel_results {
Ok(channels) => channels.iter().filter(|c| c.kind == ChannelType::Voice).collect::<Vec<&GuildChannel>>(), Ok(channels) => channels
Err(err) => return ResponseError::error_response(&ServiceError { .iter()
.filter(|c| c.kind == ChannelType::Voice)
.collect::<Vec<&GuildChannel>>(),
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
HttpResponse::Ok().json(Response { HttpResponse::Ok().json(Response {
data: channels, data: channels,
metadata: None metadata: None,
}) })
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct ChannelMessage { struct ChannelMessage {
message: String message: String,
} }
#[post("/{guild_id}/text/{channel_id}/message")] #[post("/{guild_id}/text/{channel_id}/message")]
async fn send_message(path: web::Path<(String, String)>, text: web::Json<ChannelMessage>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn send_message(
path: web::Path<(String, String)>,
text: web::Json<ChannelMessage>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let (guild_id, channel_id) = path.into_inner(); let (guild_id, channel_id) = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -80,7 +110,7 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -89,7 +119,7 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -99,7 +129,7 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -109,16 +139,19 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
None => { None => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: format!("Could not find channel with id {}", channel_id) message: format!("Could not find channel with id {}", channel_id),
}) })
} }
}; };
if let Err(err) = channel.say(&Pin::new(&data.http).get_ref(), &text.message).await { if let Err(err) = channel
.say(&Pin::new(&data.http).get_ref(), &text.message)
.await
{
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) });
}; };
HttpResponse::Ok().finish() HttpResponse::Ok().finish()
@@ -126,38 +159,55 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct PlayRequest { struct PlayRequest {
track_url: String track_url: String,
} }
#[post("/{guild_id}/voice/{channel_id}/play")] #[post("/{guild_id}/voice/{channel_id}/play")]
async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayRequest>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn play(
path: web::Path<(String, String)>,
play_request: web::Json<PlayRequest>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let (guild_id, channel_id) = path.into_inner(); let (guild_id, channel_id) = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
} }
}; };
let channel_id = match channel_id.parse::<u64>() { let channel_id = match channel_id.parse::<u64>() {
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
} }
}; };
let http = Pin::new(&data.http).get_ref(); let http = Pin::new(&data.http).get_ref();
let guild = match http.get_guild(guild_id).await { let guild = match http.get_guild(guild_id).await {
Ok(guild) => guild, Ok(guild) => guild,
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
} }
}; };
let channel = match http.get_channel(channel_id).await { let channel = match http.get_channel(channel_id).await {
Ok(channel) => channel, Ok(channel) => channel,
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
} }
}; };
@@ -165,15 +215,22 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayReq
match join(Arc::clone(&manager), &guild.id, &channel.id()).await { match join(Arc::clone(&manager), &guild.id, &channel.id()).await {
Ok(_) => { Ok(_) => {
match play_track(Arc::clone(&data.songbird), guild.id, play_request.track_url.to_string()).await { match play_track(
Arc::clone(&data.songbird),
guild.id,
play_request.track_url.to_string(),
)
.await
{
Ok(_) => HttpResponse::Ok().finish(), Ok(_) => HttpResponse::Ok().finish(),
Err(err) => { Err(err) => return ResponseError::error_response(&err),
return ResponseError::error_response(&err)
} }
} }
},
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { status: 500, message: err.to_string() }) return ResponseError::error_response(&ServiceError {
status: 500,
message: err.to_string(),
})
} }
} }
} }
@@ -181,7 +238,7 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayReq
#[post("/{guild_id}/voice/stop")] #[post("/{guild_id}/voice/stop")]
async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_id = path.into_inner(); let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -189,7 +246,7 @@ async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -203,9 +260,13 @@ async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
} }
#[post("/{guild_id}/voice/resume")] #[post("/{guild_id}/voice/resume")]
async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn resume(
path: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_id = path.into_inner(); let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -213,7 +274,7 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: A
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -223,8 +284,8 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: A
if let Err(err) = handler.queue().resume() { if let Err(err) = handler.queue().resume() {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) });
} }
} }
@@ -232,9 +293,13 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: A
} }
#[post("/{guild_id}/voice/pause")] #[post("/{guild_id}/voice/pause")]
async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn pause(
path: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_id = path.into_inner(); let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -242,7 +307,7 @@ async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Au
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -252,8 +317,8 @@ async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Au
if let Err(err) = handler.queue().pause() { if let Err(err) = handler.queue().pause() {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) });
} }
} }
@@ -262,13 +327,13 @@ async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Au
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct SetVolume { struct SetVolume {
volume: String volume: String,
} }
#[get("/{guild_id}/voice/volume")] #[get("/{guild_id}/voice/volume")]
async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse { async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_id = path.into_inner(); let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -276,7 +341,7 @@ async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -286,7 +351,7 @@ async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -295,9 +360,14 @@ async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
} }
#[post("/{guild_id}/voice/volume")] #[post("/{guild_id}/voice/volume")]
async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn set_volume(
path: web::Path<String>,
volume: web::Json<SetVolume>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_id = path.into_inner(); let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -305,7 +375,7 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -316,7 +386,10 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
let guild = match http.get_guild(guild_id).await { let guild = match http.get_guild(guild_id).await {
Ok(guild) => guild, Ok(guild) => guild,
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
} }
}; };
crate::bot::commands::audio::volume::set_volume(manager, guild.id, volume).await; crate::bot::commands::audio::volume::set_volume(manager, guild.id, volume).await;
@@ -327,7 +400,7 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
#[post("/{guild_id}/voice/skip")] #[post("/{guild_id}/voice/skip")]
async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse { async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") { if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err) return ResponseError::error_response(&err);
}; };
let guild_id = path.into_inner(); let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
@@ -335,7 +408,7 @@ async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
Err(err) => { Err(err) => {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
} }
}; };
@@ -345,8 +418,8 @@ async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
if let Err(err) = handler.queue().skip() { if let Err(err) = handler.queue().skip() {
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) });
} }
} }
@@ -354,9 +427,8 @@ async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
} }
pub fn init_routes(config: &mut web::ServiceConfig) { pub fn init_routes(config: &mut web::ServiceConfig) {
config config.service(get_guilds).service(
.service(get_guilds) web::scope("guilds")
.service(web::scope("guilds")
.service(get_text_channels) .service(get_text_channels)
.service(get_voice_channels) .service(get_voice_channels)
.service(send_message) .service(send_message)
@@ -366,6 +438,6 @@ pub fn init_routes(config: &mut web::ServiceConfig) {
.service(pause) .service(pause)
.service(set_volume) .service(set_volume)
.service(get_volume) .service(get_volume)
.service(skip) .service(skip),
); );
} }

View File

@@ -12,7 +12,7 @@ use super::commands::audio::create_response;
pub struct Handler { pub struct Handler {
// Open AI Config // Open AI Config
pub oai: Option<oai::OAI> pub oai: Option<oai::OAI>,
} }
#[async_trait] #[async_trait]
@@ -28,18 +28,21 @@ impl EventHandler for Handler {
Ok(mentioned) => { Ok(mentioned) => {
let bot_in_thread = match msg.channel_id.get_thread_members(&ctx.http).await { let bot_in_thread = match msg.channel_id.get_thread_members(&ctx.http).await {
Ok(t) => { Ok(t) => {
match t.iter().find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0) { match t
.iter()
.find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0)
{
Some(_) => true, Some(_) => true,
None => false None => false,
} }
} }
Err(_) => false Err(_) => false,
}; };
if mentioned || bot_in_thread { if mentioned || bot_in_thread {
commands::chat::generate_response(&ctx, &msg, oai).await; commands::chat::generate_response(&ctx, &msg, oai).await;
} }
} }
Err(why) => warn!("Could not check mentions: {:?}", why) Err(why) => warn!("Could not check mentions: {:?}", why),
}; };
} }
None => {} None => {}
@@ -59,7 +62,7 @@ impl EventHandler for Handler {
_ => { _ => {
let content: String = match command.data.name.as_str() { let content: String = match command.data.name.as_str() {
"ping" => commands::ping::run(&command.data.options), "ping" => commands::ping::run(&command.data.options),
_ => "Unknown command".to_string() _ => "Unknown command".to_string(),
}; };
if let Err(why) = create_response(&ctx, &command, content).await { if let Err(why) = create_response(&ctx, &command, content).await {
@@ -78,22 +81,60 @@ impl EventHandler for Handler {
let _ = InsertGuild::insert(InsertGuild { let _ = InsertGuild::insert(InsertGuild {
id: (guild.id.0 as i64), id: (guild.id.0 as i64),
bot_id: ctx.cache.current_user().id.0 as i64, bot_id: ctx.cache.current_user().id.0 as i64,
volume: 100 volume: 100,
}); });
let commands = guild.id.set_application_commands(&ctx.http, |commands| { let commands = guild
.id
.set_application_commands(&ctx.http, |commands| {
commands commands
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) }) .create_application_command(
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::roll::register(command) }) |command: &mut serenity::builder::CreateApplicationCommand| {
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) }) commands::ping::register(command)
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::stop::register(command) }) },
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::pause::register(command) }) )
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::resume::register(command) }) .create_application_command(
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::skip::register(command) }) |command: &mut serenity::builder::CreateApplicationCommand| {
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::volume::register(command) }) commands::roll::register(command)
}).await; },
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::play::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::stop::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::pause::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::resume::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::skip::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::volume::register(command)
},
)
})
.await;
match commands { match commands {
Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.0), Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.0),
Err(why) => error!("Could not register commands for guild {}: {:?}", guild.id.0, why) Err(why) => error!(
"Could not register commands for guild {}: {:?}",
guild.id.0, why
),
}; };
} }
} }

View File

@@ -2,7 +2,10 @@ use diesel::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use siren::ServiceError; use siren::ServiceError;
use crate::storage::{schema::messages::{self}, connection}; use crate::storage::{
schema::messages::{self},
connection,
};
#[derive(Queryable, Selectable, Insertable, AsChangeset, Serialize, Deserialize)] #[derive(Queryable, Selectable, Insertable, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = messages)] #[diesel(table_name = messages)]
@@ -28,7 +31,7 @@ pub struct QueryFilters {
pub by_request: Option<String>, pub by_request: Option<String>,
pub by_response: Option<String>, pub by_response: Option<String>,
pub by_request_tags: Option<Vec<String>>, pub by_request_tags: Option<Vec<String>>,
pub by_response_tags: Option<Vec<String>> pub by_response_tags: Option<Vec<String>>,
} }
impl Default for QueryFilters { impl Default for QueryFilters {
@@ -42,7 +45,7 @@ impl Default for QueryFilters {
by_request: None, by_request: None,
by_response: None, by_response: None,
by_request_tags: None, by_request_tags: None,
by_response_tags: None by_response_tags: None,
} }
} }
} }
@@ -50,7 +53,10 @@ impl Default for QueryFilters {
impl QueryMessage { impl QueryMessage {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> { pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let mut query = messages::table.limit(limit as i64).order(messages::created.asc()).into_boxed(); let mut query = messages::table
.limit(limit as i64)
.order(messages::created.asc())
.into_boxed();
// Limit query to page and limit // Limit query to page and limit
let offset = (page - 1) * limit; let offset = (page - 1) * limit;
query = query.offset(offset as i64); query = query.offset(offset as i64);

View File

@@ -3,7 +3,10 @@ use log::error;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use siren::{Response, Metadata, ServiceError}; use siren::{Response, Metadata, ServiceError};
use crate::{bot::messages::{QueryMessage, QueryFilters}, auth::{Auth, verify_role}}; use crate::{
bot::messages::{QueryMessage, QueryFilters},
auth::{Auth, verify_role},
};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct GetAllParams { struct GetAllParams {
@@ -23,15 +26,17 @@ struct GetAllParams {
#[get("/messages")] #[get("/messages")]
async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse { async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") { let _ = match verify_role(&auth, "admin") {
Ok(_) => {}, Ok(_) => {}
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
let params = match web::Query::<GetAllParams>::from_query(req.query_string()) { let params = match web::Query::<GetAllParams>::from_query(req.query_string()) {
Ok(params) => params, Ok(params) => params,
Err(err) => return ResponseError::error_response(&ServiceError { Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
let mut filters = QueryFilters::default(); let mut filters = QueryFilters::default();
filters.by_id = params.id.clone(); filters.by_id = params.id.clone();
@@ -49,17 +54,15 @@ async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse {
let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page); let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page);
match QueryMessage::get_all(&filters, limit, page) { match QueryMessage::get_all(&filters, limit, page) {
Ok(messages) => { Ok(messages) => HttpResponse::Ok().json(Response {
HttpResponse::Ok().json(Response {
data: messages, data: messages,
metadata: Some(Metadata { metadata: Some(Metadata {
total: total_count as i32, total: total_count as i32,
limit, limit,
page, page,
pages: max_page pages: max_page,
}) }),
}) }),
},
Err(err) => { Err(err) => {
error!("{:?}", err.message); error!("{:?}", err.message);
ResponseError::error_response(&err) ResponseError::error_response(&err)
@@ -70,8 +73,8 @@ async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse {
#[post("/messages")] #[post("/messages")]
async fn create(message: web::Json<QueryMessage>, auth: Auth) -> HttpResponse { async fn create(message: web::Json<QueryMessage>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") { let _ = match verify_role(&auth, "admin") {
Ok(_) => {}, Ok(_) => {}
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
match QueryMessage::insert(message.into_inner()) { match QueryMessage::insert(message.into_inner()) {
Ok(message) => HttpResponse::Created().json(message), Ok(message) => HttpResponse::Created().json(message),

View File

@@ -11,7 +11,7 @@ pub enum GPTRole {
#[serde(rename = "assistant")] #[serde(rename = "assistant")]
Assistant, Assistant,
#[serde(rename = "function")] #[serde(rename = "function")]
Function Function,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -41,7 +41,7 @@ pub struct ChatCompletionRequest {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionMessage { pub struct ChatCompletionMessage {
pub role: GPTRole, pub role: GPTRole,
pub content: String pub content: String,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -52,14 +52,14 @@ pub struct ChatCompletionResponse {
pub created: i64, pub created: i64,
pub model: String, pub model: String,
pub usage: Usage, pub usage: Usage,
pub choices: Vec<Choice> pub choices: Vec<Choice>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage { pub struct Usage {
pub prompt_tokens: i64, pub prompt_tokens: i64,
pub completion_tokens: i64, pub completion_tokens: i64,
pub total_tokens: i64 pub total_tokens: i64,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -67,13 +67,13 @@ pub struct Choice {
pub message: ChatCompletionMessage, pub message: ChatCompletionMessage,
pub finish_reason: String, pub finish_reason: String,
pub index: i64, pub index: i64,
pub logprobs: Option<String> pub logprobs: Option<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
enum ResponseEvent { enum ResponseEvent {
ChatCompletionResponse(ChatCompletionResponse), ChatCompletionResponse(ChatCompletionResponse),
ResponseError(ResponseError) ResponseError(ResponseError),
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -82,13 +82,13 @@ struct ResponseError {
message: Option<String>, message: Option<String>,
param: Option<String>, param: Option<String>,
#[serde(rename = "type")] #[serde(rename = "type")]
error_type: Option<String> error_type: Option<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
struct ErrorDetails { struct ErrorDetails {
code: Option<String>, code: Option<String>,
message: Option<String> message: Option<String>,
} }
pub struct OAI { pub struct OAI {
@@ -99,13 +99,18 @@ pub struct OAI {
pub token: String, pub token: String,
pub max_tokens: i64, pub max_tokens: i64,
pub default_model: String, pub default_model: String,
pub max_context_questions: i64 pub max_context_questions: i64,
} }
impl OAI { impl OAI {
pub async fn chat_completion(&self, request: ChatCompletionRequest) -> Result<ChatCompletionResponse, ServiceError> { pub async fn chat_completion(
&self,
request: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, ServiceError> {
let url = format!("{}/chat/completions", self.base_url); let url = format!("{}/chat/completions", self.base_url);
let response = self.client.post(&url) let response = self
.client
.post(&url)
.bearer_auth(&self.token) .bearer_auth(&self.token)
.header("Content-Type", "application/json".to_string()) .header("Content-Type", "application/json".to_string())
.json(&request) .json(&request)
@@ -121,8 +126,13 @@ impl OAI {
// } // }
let res = serde_json::from_value::<ChatCompletionResponse>(value)?; let res = serde_json::from_value::<ChatCompletionResponse>(value)?;
return Ok(res); return Ok(res);
}, }
Err(err) => return Err(ServiceError { status: 500, message: format!("Error: {}", err) }) Err(err) => {
return Err(ServiceError {
status: 500,
message: format!("Error: {}", err),
})
}
} }
} }
} }

View File

@@ -4,7 +4,6 @@ use std::process::{Child, Command, Output, Stdio};
pub use model::*; pub use model::*;
const YOUTUBE_DL_COMMAND: &str = "yt-dlp"; const YOUTUBE_DL_COMMAND: &str = "yt-dlp";
pub struct YtDlp { pub struct YtDlp {
@@ -15,7 +14,8 @@ pub struct YtDlp {
impl YtDlp { impl YtDlp {
pub fn new() -> Self { pub fn new() -> Self {
let mut cmd = Command::new(YOUTUBE_DL_COMMAND); let mut cmd = Command::new(YOUTUBE_DL_COMMAND);
cmd.env("LC_ALL", "en_US.UTF-8") cmd
.env("LC_ALL", "en_US.UTF-8")
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stdin(Stdio::piped()) .stdin(Stdio::piped())
.stderr(Stdio::piped()); .stderr(Stdio::piped());
@@ -31,7 +31,8 @@ impl YtDlp {
} }
pub fn execute(&mut self) -> std::io::Result<Output> { pub fn execute(&mut self) -> std::io::Result<Output> {
self.command self
.command
.args(self.args.clone()) .args(self.args.clone())
.spawn() .spawn()
.and_then(Child::wait_with_output) .and_then(Child::wait_with_output)

View File

@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct PlaylistItem { pub struct PlaylistItem {
pub id: String, pub id: String,

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1 @@

View File

@@ -14,7 +14,7 @@ pub enum AbilityType {
#[serde(rename = "wisdom")] #[serde(rename = "wisdom")]
Wisdom, Wisdom,
#[serde(rename = "charisma")] #[serde(rename = "charisma")]
Charisma Charisma,
} }
impl AbilityType { impl AbilityType {
@@ -25,7 +25,7 @@ impl AbilityType {
AbilityType::Constitution => "Constitution".to_string(), AbilityType::Constitution => "Constitution".to_string(),
AbilityType::Intelligence => "Intelligence".to_string(), AbilityType::Intelligence => "Intelligence".to_string(),
AbilityType::Wisdom => "Wisdom".to_string(), AbilityType::Wisdom => "Wisdom".to_string(),
AbilityType::Charisma => "Charisma".to_string() AbilityType::Charisma => "Charisma".to_string(),
} }
} }
} }
@@ -40,7 +40,7 @@ impl FromStr for AbilityType {
"Intelligence" => Ok(AbilityType::Intelligence), "Intelligence" => Ok(AbilityType::Intelligence),
"Wisdom" => Ok(AbilityType::Wisdom), "Wisdom" => Ok(AbilityType::Wisdom),
"Charisma" => Ok(AbilityType::Charisma), "Charisma" => Ok(AbilityType::Charisma),
_ => Err(()) _ => Err(()),
} }
} }
} }

View File

@@ -1,7 +1,6 @@
use std::str::FromStr; use std::str::FromStr;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub enum ConditionType { pub enum ConditionType {
#[serde(rename = "blinded")] #[serde(rename = "blinded")]
@@ -33,7 +32,7 @@ pub enum ConditionType {
#[serde(rename = "stunned")] #[serde(rename = "stunned")]
Stunned, Stunned,
#[serde(rename = "unconscious")] #[serde(rename = "unconscious")]
Unconscious Unconscious,
} }
impl ConditionType { impl ConditionType {
@@ -53,7 +52,7 @@ impl ConditionType {
ConditionType::Prone => "Prone".to_string(), ConditionType::Prone => "Prone".to_string(),
ConditionType::Restrained => "Restrained".to_string(), ConditionType::Restrained => "Restrained".to_string(),
ConditionType::Stunned => "Stunned".to_string(), ConditionType::Stunned => "Stunned".to_string(),
ConditionType::Unconscious => "Unconscious".to_string() ConditionType::Unconscious => "Unconscious".to_string(),
} }
} }
} }
@@ -77,7 +76,7 @@ impl FromStr for ConditionType {
"Restrained" => Ok(ConditionType::Restrained), "Restrained" => Ok(ConditionType::Restrained),
"Stunned" => Ok(ConditionType::Stunned), "Stunned" => Ok(ConditionType::Stunned),
"Unconscious" => Ok(ConditionType::Unconscious), "Unconscious" => Ok(ConditionType::Unconscious),
_ => Err(()) _ => Err(()),
} }
} }
} }

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1 @@

View File

@@ -2,7 +2,11 @@ mod model;
mod routes; mod routes;
mod types; mod types;
use std::{fs::{metadata, File, read_dir}, path::Path, io::BufReader}; use std::{
fs::{metadata, File, read_dir},
path::Path,
io::BufReader,
};
use log::{warn, trace}; use log::{warn, trace};
pub use model::*; pub use model::*;
@@ -35,7 +39,7 @@ pub fn load_data(data_dir_path: &str) {
trace!("Spell '{}' already exists", spell.name); trace!("Spell '{}' already exists", spell.name);
continue; continue;
} }
}, }
Err(err) => { Err(err) => {
warn!("Error checking if spell '{}' exists: {}", spell.name, err); warn!("Error checking if spell '{}' exists: {}", spell.name, err);
continue; continue;
@@ -44,8 +48,8 @@ pub fn load_data(data_dir_path: &str) {
let spell = InsertSpell::insert(spell.into()).unwrap(); let spell = InsertSpell::insert(spell.into()).unwrap();
trace!("Inserted spell: {}", spell.name); trace!("Inserted spell: {}", spell.name);
} }
}, }
Err(err) => warn!("Error reading spells from file: {}", err) Err(err) => warn!("Error reading spells from file: {}", err),
}; };
} }
} }
@@ -53,6 +57,9 @@ pub fn load_data(data_dir_path: &str) {
} }
} }
} else { } else {
warn!("Data path '{}' does not exist, no data imported", data_dir_path); warn!(
"Data path '{}' does not exist, no data imported",
data_dir_path
);
} }
} }

View File

@@ -6,7 +6,10 @@ use crate::storage::connection;
use crate::storage::schema::spells::{self}; use crate::storage::schema::spells::{self};
use crate::dnd::{classes::AbilityType, conditions::ConditionType}; use crate::dnd::{classes::AbilityType, conditions::ConditionType};
use super::{SchoolType, CastingTime, SpellAttackType, SpellDamageType, Range, Area, Components, Duration, Source, Description, DurationType, Effect}; use super::{
SchoolType, CastingTime, SpellAttackType, SpellDamageType, Range, Area, Components, Duration,
Source, Description, DurationType, Effect,
};
#[derive(Debug, Queryable, QueryableByName, Serialize, Deserialize)] #[derive(Debug, Queryable, QueryableByName, Serialize, Deserialize)]
#[diesel(table_name = spells)] #[diesel(table_name = spells)]
@@ -75,7 +78,14 @@ impl QuerySpell {
query = query.filter(spells::name.ilike(format!("%{}%", name))); query = query.filter(spells::name.ilike(format!("%{}%", name)));
} }
if let Some(schools) = &filters.by_schools { if let Some(schools) = &filters.by_schools {
query = query.filter(spells::school.eq_any(schools.iter().map(|school| school.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::school.eq_any(
schools
.iter()
.map(|school| school.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(levels) = &filters.by_levels { if let Some(levels) = &filters.by_levels {
query = query.filter(spells::level.eq_any(levels)); query = query.filter(spells::level.eq_any(levels));
@@ -90,16 +100,44 @@ impl QuerySpell {
query = query.filter(spells::classes.overlaps_with(classes)); query = query.filter(spells::classes.overlaps_with(classes));
} }
if let Some(damage_inflict) = &filters.by_damage_inflict { if let Some(damage_inflict) = &filters.by_damage_inflict {
query = query.filter(spells::damage_inflict.overlaps_with(damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::damage_inflict.overlaps_with(
damage_inflict
.iter()
.map(|damage_inflict| damage_inflict.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(damage_resist) = &filters.by_damage_resist { if let Some(damage_resist) = &filters.by_damage_resist {
query = query.filter(spells::damage_resist.overlaps_with(damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::damage_resist.overlaps_with(
damage_resist
.iter()
.map(|damage_resist| damage_resist.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(conditions) = &filters.by_conditions { if let Some(conditions) = &filters.by_conditions {
query = query.filter(spells::conditions.overlaps_with(conditions.iter().map(|condition| condition.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::conditions.overlaps_with(
conditions
.iter()
.map(|condition| condition.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(saving_throw) = &filters.by_saving_throw { if let Some(saving_throw) = &filters.by_saving_throw {
query = query.filter(spells::saving_throw.overlaps_with(saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::saving_throw.overlaps_with(
saving_throw
.iter()
.map(|saving_throw| saving_throw.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(attack_type) = &filters.by_attack_type { if let Some(attack_type) = &filters.by_attack_type {
query = query.filter(spells::attack_type.eq(attack_type.to_string())); query = query.filter(spells::attack_type.eq(attack_type.to_string()));
@@ -116,7 +154,14 @@ impl QuerySpell {
query = query.filter(spells::name.ilike(format!("%{}%", name))); query = query.filter(spells::name.ilike(format!("%{}%", name)));
} }
if let Some(schools) = &filters.by_schools { if let Some(schools) = &filters.by_schools {
query = query.filter(spells::school.eq_any(schools.iter().map(|school| school.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::school.eq_any(
schools
.iter()
.map(|school| school.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(levels) = &filters.by_levels { if let Some(levels) = &filters.by_levels {
query = query.filter(spells::level.eq_any(levels)); query = query.filter(spells::level.eq_any(levels));
@@ -131,16 +176,44 @@ impl QuerySpell {
query = query.filter(spells::classes.overlaps_with(classes)); query = query.filter(spells::classes.overlaps_with(classes));
} }
if let Some(damage_inflict) = &filters.by_damage_inflict { if let Some(damage_inflict) = &filters.by_damage_inflict {
query = query.filter(spells::damage_inflict.overlaps_with(damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::damage_inflict.overlaps_with(
damage_inflict
.iter()
.map(|damage_inflict| damage_inflict.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(damage_resist) = &filters.by_damage_resist { if let Some(damage_resist) = &filters.by_damage_resist {
query = query.filter(spells::damage_resist.overlaps_with(damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::damage_resist.overlaps_with(
damage_resist
.iter()
.map(|damage_resist| damage_resist.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(conditions) = &filters.by_conditions { if let Some(conditions) = &filters.by_conditions {
query = query.filter(spells::conditions.overlaps_with(conditions.iter().map(|condition| condition.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::conditions.overlaps_with(
conditions
.iter()
.map(|condition| condition.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(saving_throw) = &filters.by_saving_throw { if let Some(saving_throw) = &filters.by_saving_throw {
query = query.filter(spells::saving_throw.overlaps_with(saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect::<Vec<String>>())); query = query.filter(
spells::saving_throw.overlaps_with(
saving_throw
.iter()
.map(|saving_throw| saving_throw.to_string())
.collect::<Vec<String>>(),
),
);
} }
if let Some(attack_type) = &filters.by_attack_type { if let Some(attack_type) = &filters.by_attack_type {
query = query.filter(spells::attack_type.eq(attack_type.to_string())); query = query.filter(spells::attack_type.eq(attack_type.to_string()));
@@ -179,19 +252,23 @@ pub struct InsertSpell {
pub conditions: Vec<String>, pub conditions: Vec<String>,
pub saving_throw: Vec<String>, pub saving_throw: Vec<String>,
pub attack_type: Option<String>, pub attack_type: Option<String>,
pub data: serde_json::Value pub data: serde_json::Value,
} }
impl InsertSpell { impl InsertSpell {
pub fn insert(spell: Self) -> Result<QuerySpell, ServiceError> { pub fn insert(spell: Self) -> Result<QuerySpell, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let spell = diesel::insert_into(spells::table).values(spell).get_result(&mut conn)?; let spell = diesel::insert_into(spells::table)
.values(spell)
.get_result(&mut conn)?;
Ok(spell) Ok(spell)
} }
pub fn update(id: i32, spell: Self) -> Result<QuerySpell, ServiceError> { pub fn update(id: i32, spell: Self) -> Result<QuerySpell, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let spell = diesel::update(spells::table.filter(spells::id.eq(id))).set(spell).get_result(&mut conn)?; let spell = diesel::update(spells::table.filter(spells::id.eq(id)))
.set(spell)
.get_result(&mut conn)?;
Ok(spell) Ok(spell)
} }
} }
@@ -226,7 +303,7 @@ pub struct Spell {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>, pub tags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<Description> pub description: Option<Description>,
} }
impl From<QuerySpell> for Spell { impl From<QuerySpell> for Spell {
@@ -241,16 +318,31 @@ impl From<QuerySpell> for Spell {
school: SchoolType::Abjuration, school: SchoolType::Abjuration,
level: 0, level: 0,
ritual: false, ritual: false,
casting_time: CastingTime { value: 0, casting_type: "".to_string(), note: None }, casting_time: CastingTime {
value: 0,
casting_type: "".to_string(),
note: None,
},
effect: None, effect: None,
saving_throw: None, saving_throw: None,
attack_type: None, attack_type: None,
damage_inflict: None, damage_inflict: None,
damage_resist: None, damage_resist: None,
conditions: None, conditions: None,
range: Range { range_type: "".to_string(), value: None, unit: None }, range: Range {
range_type: "".to_string(),
value: None,
unit: None,
},
area: None, area: None,
components: Components { verbal: false, somatic: false, material: false, materials_needed: None, materials_cost: None, materials_consumed: None }, components: Components {
verbal: false,
somatic: false,
material: false,
materials_needed: None,
materials_cost: None,
materials_consumed: None,
},
durations: vec![], durations: vec![],
classes: vec![], classes: vec![],
sources: vec![], sources: vec![],
@@ -258,7 +350,7 @@ impl From<QuerySpell> for Spell {
description: None, description: None,
} }
} }
} };
} }
} }
@@ -269,35 +361,57 @@ impl Into<InsertSpell> for Spell {
school: self.school.to_string(), school: self.school.to_string(),
level: self.level, level: self.level,
ritual: self.ritual, ritual: self.ritual,
concentration: self.durations.iter().any(|duration| match duration.duration_type { concentration: self
.durations
.iter()
.any(|duration| match duration.duration_type {
DurationType::Concentration => true, DurationType::Concentration => true,
_ => false _ => false,
}), }),
classes: self.classes.iter().map(|class| class.to_string()).collect::<Vec<String>>(), classes: self
.classes
.iter()
.map(|class| class.to_string())
.collect::<Vec<String>>(),
damage_inflict: match &self.damage_inflict { damage_inflict: match &self.damage_inflict {
Some(damage_inflict) => damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect(), Some(damage_inflict) => damage_inflict
None => vec![] .iter()
.map(|damage_inflict| damage_inflict.to_string())
.collect(),
None => vec![],
}, },
damage_resist: match &self.damage_resist { damage_resist: match &self.damage_resist {
Some(damage_resist) => damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect(), Some(damage_resist) => damage_resist
None => vec![] .iter()
.map(|damage_resist| damage_resist.to_string())
.collect(),
None => vec![],
}, },
conditions: match &self.conditions { conditions: match &self.conditions {
Some(conditions) => conditions.iter().map(|condition| condition.to_string()).collect(), Some(conditions) => conditions
None => vec![] .iter()
.map(|condition| condition.to_string())
.collect(),
None => vec![],
}, },
saving_throw: match &self.saving_throw { saving_throw: match &self.saving_throw {
Some(saving_throw) => saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect(), Some(saving_throw) => saving_throw
None => vec![] .iter()
.map(|saving_throw| saving_throw.to_string())
.collect(),
None => vec![],
}, },
attack_type: self.attack_type.as_ref().map(|attack_type| attack_type.to_string()), attack_type: self
.attack_type
.as_ref()
.map(|attack_type| attack_type.to_string()),
data: match serde_json::to_value(&self) { data: match serde_json::to_value(&self) {
Ok(data) => data, Ok(data) => data,
Err(err) => { Err(err) => {
log::error!("Failed to serialize spell: {}", err); log::error!("Failed to serialize spell: {}", err);
serde_json::Value::Null serde_json::Value::Null
} }
} },
} };
} }
} }

View File

@@ -3,7 +3,10 @@ use log::error;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use siren::{Response, Metadata, ServiceError}; use siren::{Response, Metadata, ServiceError};
use crate::{dnd::spells::{QuerySpell, QueryFilters}, auth::{Auth, verify_role}}; use crate::{
dnd::spells::{QuerySpell, QueryFilters},
auth::{Auth, verify_role},
};
use super::{Spell, InsertSpell}; use super::{Spell, InsertSpell};
@@ -29,50 +32,57 @@ struct GetAllParams {
async fn get_all(req: HttpRequest) -> HttpResponse { async fn get_all(req: HttpRequest) -> HttpResponse {
let params = match web::Query::<GetAllParams>::from_query(req.query_string()) { let params = match web::Query::<GetAllParams>::from_query(req.query_string()) {
Ok(params) => params, Ok(params) => params,
Err(err) => return ResponseError::error_response(&ServiceError { Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
let mut filters = QueryFilters::default(); let mut filters = QueryFilters::default();
filters.by_name = params.name.clone(); filters.by_name = params.name.clone();
filters.like_name = params.like_name.clone(); filters.like_name = params.like_name.clone();
filters.by_schools = match &params.schools { filters.by_schools = match &params.schools {
Some(schools) => Some(schools.split(",").map(|s| s.to_string()).collect()), Some(schools) => Some(schools.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
filters.by_levels = match &params.levels { filters.by_levels = match &params.levels {
Some(levels) => Some(levels.split(",").map(|s| match s.to_string().parse::<i32>() { Some(levels) => Some(
levels
.split(",")
.map(|s| match s.to_string().parse::<i32>() {
Ok(level) => level, Ok(level) => level,
Err(_) => 0 Err(_) => 0,
}).collect()), })
None => None .collect(),
),
None => None,
}; };
filters.by_ritual = params.ritual; filters.by_ritual = params.ritual;
filters.by_concentration = params.concentration; filters.by_concentration = params.concentration;
filters.by_classes = match &params.classes { filters.by_classes = match &params.classes {
Some(classes) => Some(classes.split(",").map(|s| s.to_string()).collect()), Some(classes) => Some(classes.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
filters.by_damage_inflict = match &params.damage_inflict { filters.by_damage_inflict = match &params.damage_inflict {
Some(damage_inflict) => Some(damage_inflict.split(",").map(|s| s.to_string()).collect()), Some(damage_inflict) => Some(damage_inflict.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
filters.by_damage_resist = match &params.damage_resist { filters.by_damage_resist = match &params.damage_resist {
Some(damage_resist) => Some(damage_resist.split(",").map(|s| s.to_string()).collect()), Some(damage_resist) => Some(damage_resist.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
filters.by_conditions = match &params.conditions { filters.by_conditions = match &params.conditions {
Some(conditions) => Some(conditions.split(",").map(|s| s.to_string()).collect()), Some(conditions) => Some(conditions.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
filters.by_saving_throw = match &params.saving_throw { filters.by_saving_throw = match &params.saving_throw {
Some(saving_throw) => Some(saving_throw.split(",").map(|s| s.to_string()).collect()), Some(saving_throw) => Some(saving_throw.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
filters.by_attack_type = match &params.attack_type { filters.by_attack_type = match &params.attack_type {
Some(attack_type) => Some(attack_type.split(",").map(|s| s.to_string()).collect()), Some(attack_type) => Some(attack_type.split(",").map(|s| s.to_string()).collect()),
None => None None => None,
}; };
// Limit must be between 1 and 100 // Limit must be between 1 and 100
let limit = std::cmp::min(std::cmp::max(params.limit.unwrap_or(100), 1), 100); let limit = std::cmp::min(std::cmp::max(params.limit.unwrap_or(100), 1), 100);
@@ -81,7 +91,10 @@ async fn get_all(req: HttpRequest) -> HttpResponse {
// Page must be between 1 and max_page // Page must be between 1 and max_page
let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page); let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page);
match web::block(move || QuerySpell::get_all(&filters, limit, page)).await.unwrap() { match web::block(move || QuerySpell::get_all(&filters, limit, page))
.await
.unwrap()
{
Ok(spells) => { Ok(spells) => {
let mut response: Vec<Spell> = Vec::new(); let mut response: Vec<Spell> = Vec::new();
for query_spell in spells { for query_spell in spells {
@@ -96,10 +109,10 @@ async fn get_all(req: HttpRequest) -> HttpResponse {
total: total_count as i32, total: total_count as i32,
limit, limit,
page, page,
pages: max_page pages: max_page,
}),
}) })
}) }
},
Err(err) => { Err(err) => {
error!("{:?}", err.message); error!("{:?}", err.message);
ResponseError::error_response(&err) ResponseError::error_response(&err)
@@ -111,10 +124,12 @@ async fn get_all(req: HttpRequest) -> HttpResponse {
async fn get_by_id(id: web::Path<String>) -> HttpResponse { async fn get_by_id(id: web::Path<String>) -> HttpResponse {
let id = match id.parse::<i32>() { let id = match id.parse::<i32>() {
Ok(id) => id, Ok(id) => id,
Err(err) => return ResponseError::error_response(&ServiceError { Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
match web::block(move || QuerySpell::get_by_id(id)).await.unwrap() { match web::block(move || QuerySpell::get_by_id(id)).await.unwrap() {
Ok(query_spell) => { Ok(query_spell) => {
@@ -123,9 +138,9 @@ async fn get_by_id(id: web::Path<String>) -> HttpResponse {
spell.id = Some(id); spell.id = Some(id);
HttpResponse::Ok().json(Response { HttpResponse::Ok().json(Response {
data: spell, data: spell,
metadata: None metadata: None,
}) })
}, }
Err(err) => { Err(err) => {
error!("{:?}", err.message); error!("{:?}", err.message);
ResponseError::error_response(&err) ResponseError::error_response(&err)
@@ -136,8 +151,8 @@ async fn get_by_id(id: web::Path<String>) -> HttpResponse {
#[post("/spells")] #[post("/spells")]
async fn create(spell: web::Json<Spell>, auth: Auth) -> HttpResponse { async fn create(spell: web::Json<Spell>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") { let _ = match verify_role(&auth, "admin") {
Ok(_) => {}, Ok(_) => {}
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
match InsertSpell::insert(spell.into_inner().into()) { match InsertSpell::insert(spell.into_inner().into()) {
Ok(spell) => HttpResponse::Created().json(Spell::from(spell)), Ok(spell) => HttpResponse::Created().json(Spell::from(spell)),
@@ -151,17 +166,22 @@ async fn create(spell: web::Json<Spell>, auth: Auth) -> HttpResponse {
#[put("/spells/{id}")] #[put("/spells/{id}")]
async fn update(id: web::Path<String>, spell: web::Json<Spell>, auth: Auth) -> HttpResponse { async fn update(id: web::Path<String>, spell: web::Json<Spell>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") { let _ = match verify_role(&auth, "admin") {
Ok(_) => {}, Ok(_) => {}
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
let id = match id.parse::<i32>() { let id = match id.parse::<i32>() {
Ok(id) => id, Ok(id) => id,
Err(err) => return ResponseError::error_response(&ServiceError { Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
match web::block(move || InsertSpell::update(id, spell.into_inner().into())).await.unwrap() { match web::block(move || InsertSpell::update(id, spell.into_inner().into()))
.await
.unwrap()
{
Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)), Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)),
Err(err) => { Err(err) => {
error!("{:?}", err.message); error!("{:?}", err.message);
@@ -173,15 +193,17 @@ async fn update(id: web::Path<String>, spell: web::Json<Spell>, auth: Auth) -> H
#[delete("/spells/{id}")] #[delete("/spells/{id}")]
async fn delete(id: web::Path<String>, auth: Auth) -> HttpResponse { async fn delete(id: web::Path<String>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") { let _ = match verify_role(&auth, "admin") {
Ok(_) => {}, Ok(_) => {}
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
let id = match id.parse::<i32>() { let id = match id.parse::<i32>() {
Ok(id) => id, Ok(id) => id,
Err(err) => return ResponseError::error_response(&ServiceError { Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422, status: 422,
message: err.to_string() message: err.to_string(),
}) })
}
}; };
match web::block(move || QuerySpell::delete(id)).await.unwrap() { match web::block(move || QuerySpell::delete(id)).await.unwrap() {
Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)), Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)),
@@ -193,10 +215,11 @@ async fn delete(id: web::Path<String>, auth: Auth) -> HttpResponse {
} }
pub fn init_routes(config: &mut web::ServiceConfig) { pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(web::scope("dnd") config.service(
web::scope("dnd")
.service(get_all) .service(get_all)
.service(get_by_id) .service(get_by_id)
.service(create) .service(create)
.service(update) .service(update),
); );
} }

View File

@@ -18,7 +18,7 @@ pub enum SchoolType {
#[serde(rename = "necromancy")] #[serde(rename = "necromancy")]
Necromancy, Necromancy,
#[serde(rename = "transmutation")] #[serde(rename = "transmutation")]
Transmutation Transmutation,
} }
impl SchoolType { impl SchoolType {
@@ -31,7 +31,7 @@ impl SchoolType {
SchoolType::Evocation => "evocation".to_string(), SchoolType::Evocation => "evocation".to_string(),
SchoolType::Illusion => "illusion".to_string(), SchoolType::Illusion => "illusion".to_string(),
SchoolType::Necromancy => "necromancy".to_string(), SchoolType::Necromancy => "necromancy".to_string(),
SchoolType::Transmutation => "transmutation".to_string() SchoolType::Transmutation => "transmutation".to_string(),
} }
} }
} }
@@ -49,7 +49,7 @@ impl FromStr for SchoolType {
"illusion" => Ok(SchoolType::Illusion), "illusion" => Ok(SchoolType::Illusion),
"necromancy" => Ok(SchoolType::Necromancy), "necromancy" => Ok(SchoolType::Necromancy),
"transmutation" => Ok(SchoolType::Transmutation), "transmutation" => Ok(SchoolType::Transmutation),
_ => Err(()) _ => Err(()),
} }
} }
} }
@@ -59,7 +59,7 @@ pub struct CastingTime {
pub value: i32, pub value: i32,
#[serde(rename = "unit")] #[serde(rename = "unit")]
pub casting_type: String, pub casting_type: String,
pub note: Option<String> pub note: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -74,7 +74,7 @@ impl SpellAttackType {
pub fn to_string(&self) -> String { pub fn to_string(&self) -> String {
match self { match self {
SpellAttackType::Melee => "melee".to_string(), SpellAttackType::Melee => "melee".to_string(),
SpellAttackType::Ranged => "ranged".to_string() SpellAttackType::Ranged => "ranged".to_string(),
} }
} }
} }
@@ -86,7 +86,7 @@ impl FromStr for SpellAttackType {
match s { match s {
"melee" => Ok(SpellAttackType::Melee), "melee" => Ok(SpellAttackType::Melee),
"ranged" => Ok(SpellAttackType::Ranged), "ranged" => Ok(SpellAttackType::Ranged),
_ => Err(()) _ => Err(()),
} }
} }
} }
@@ -118,7 +118,7 @@ pub enum SpellDamageType {
#[serde(rename = "slashing")] #[serde(rename = "slashing")]
Slashing, Slashing,
#[serde(rename = "thunder")] #[serde(rename = "thunder")]
Thunder Thunder,
} }
impl SpellDamageType { impl SpellDamageType {
@@ -136,7 +136,7 @@ impl SpellDamageType {
SpellDamageType::Psychic => "psychic".to_string(), SpellDamageType::Psychic => "psychic".to_string(),
SpellDamageType::Radiant => "radiant".to_string(), SpellDamageType::Radiant => "radiant".to_string(),
SpellDamageType::Slashing => "slashing".to_string(), SpellDamageType::Slashing => "slashing".to_string(),
SpellDamageType::Thunder => "thunder".to_string() SpellDamageType::Thunder => "thunder".to_string(),
} }
} }
} }
@@ -159,7 +159,7 @@ impl FromStr for SpellDamageType {
"radiant" => Ok(SpellDamageType::Radiant), "radiant" => Ok(SpellDamageType::Radiant),
"slashing" => Ok(SpellDamageType::Slashing), "slashing" => Ok(SpellDamageType::Slashing),
"thunder" => Ok(SpellDamageType::Thunder), "thunder" => Ok(SpellDamageType::Thunder),
_ => Err(()) _ => Err(()),
} }
} }
} }
@@ -171,7 +171,7 @@ pub struct Range {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<i32>, pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String> pub unit: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -181,7 +181,7 @@ pub struct Area {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<i32>, pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String> pub unit: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -191,7 +191,7 @@ pub struct Duration {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<i32>, pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String> pub unit: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -205,36 +205,39 @@ pub enum DurationType {
#[serde(rename = "dispelled")] #[serde(rename = "dispelled")]
UntilDispelled, UntilDispelled,
#[serde(rename = "special")] #[serde(rename = "special")]
Special Special,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Source { pub struct Source {
pub source: String, pub source: String,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<i32> pub page: Option<i32>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Description { pub struct Description {
pub entries: Vec<Entry> pub entries: Vec<Entry>,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Entry { pub struct Entry {
pub text: Option<String>, pub text: Option<String>,
pub list: Option<Vec<String>>, pub list: Option<Vec<String>>,
pub table: Option<EntryTable> pub table: Option<EntryTable>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct EntryTable { pub struct EntryTable {
pub headers: Vec<String>, pub headers: Vec<String>,
pub rows: Vec<Vec<String>> pub rows: Vec<Vec<String>>,
} }
impl<'de> Deserialize<'de> for Entry { impl<'de> Deserialize<'de> for Entry {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?; let value = serde_json::Value::deserialize(deserializer)?;
match value { match value {
serde_json::Value::String(s) => Ok(Entry { serde_json::Value::String(s) => Ok(Entry {
@@ -246,9 +249,9 @@ impl<'de> Deserialize<'de> for Entry {
let text = match o.get("text") { let text = match o.get("text") {
Some(t) => match t.as_str() { Some(t) => match t.as_str() {
Some(s) => Some(s.to_string()), Some(s) => Some(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry text")) None => return Err(serde::de::Error::custom("Invalid entry text")),
}, },
None => None None => None,
}; };
let list = match o.get("list") { let list = match o.get("list") {
Some(i) => match i.as_array() { Some(i) => match i.as_array() {
@@ -257,14 +260,14 @@ impl<'de> Deserialize<'de> for Entry {
for item in a { for item in a {
match item.as_str() { match item.as_str() {
Some(s) => list.push(s.to_string()), Some(s) => list.push(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry list item")) None => return Err(serde::de::Error::custom("Invalid entry list item")),
} }
} }
Some(list) Some(list)
}
None => return Err(serde::de::Error::custom("Invalid entry list items")),
}, },
None => return Err(serde::de::Error::custom("Invalid entry list items")) None => None,
},
None => None
}; };
let table = match o.get("table") { let table = match o.get("table") {
Some(t) => match t.as_object() { Some(t) => match t.as_object() {
@@ -277,13 +280,13 @@ impl<'de> Deserialize<'de> for Entry {
for item in a { for item in a {
match item.as_str() { match item.as_str() {
Some(s) => headers.push(s.to_string()), Some(s) => headers.push(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry table header")) None => return Err(serde::de::Error::custom("Invalid entry table header")),
} }
} }
}
None => return Err(serde::de::Error::custom("Invalid entry table headers")),
}, },
None => return Err(serde::de::Error::custom("Invalid entry table headers")) None => return Err(serde::de::Error::custom("Missing entry table headers")),
},
None => return Err(serde::de::Error::custom("Missing entry table headers"))
}; };
match o.get("rows") { match o.get("rows") {
Some(r) => match r.as_array() { Some(r) => match r.as_array() {
@@ -295,41 +298,41 @@ impl<'de> Deserialize<'de> for Entry {
for item in a { for item in a {
match item.as_str() { match item.as_str() {
Some(s) => row.push(s.to_string()), Some(s) => row.push(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry table row item")) None => {
return Err(serde::de::Error::custom(
"Invalid entry table row item",
))
}
} }
} }
rows.push(row); rows.push(row);
}, }
None => return Err(serde::de::Error::custom("Invalid entry table row")) None => return Err(serde::de::Error::custom("Invalid entry table row")),
} }
} }
}
None => return Err(serde::de::Error::custom("Invalid entry table rows")),
}, },
None => return Err(serde::de::Error::custom("Invalid entry table rows")) None => return Err(serde::de::Error::custom("Missing entry table rows")),
},
None => return Err(serde::de::Error::custom("Missing entry table rows"))
}; };
Some(EntryTable { Some(EntryTable { headers, rows })
headers, }
rows None => return Err(serde::de::Error::custom("Invalid entry table")),
})
}, },
None => return Err(serde::de::Error::custom("Invalid entry table")) None => None,
},
None => None
}; };
Ok(Entry { Ok(Entry { text, list, table })
text, }
list, _ => Err(serde::de::Error::custom("Invalid entry")),
table
})
},
_ => Err(serde::de::Error::custom("Invalid entry"))
} }
} }
} }
impl Serialize for Entry { impl Serialize for Entry {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_map(Some(1))?; let mut map = serializer.serialize_map(Some(1))?;
if let Some(text) = &self.text { if let Some(text) = &self.text {
map.serialize_entry("text", text)?; map.serialize_entry("text", text)?;
@@ -354,10 +357,10 @@ pub struct Components {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub materials_cost: Option<i32>, pub materials_cost: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub materials_consumed: Option<bool> pub materials_consumed: Option<bool>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Effect { pub struct Effect {
pub effect_type: Option<String> pub effect_type: Option<String>,
} }

View File

@@ -22,7 +22,7 @@ pub struct Message {
pub struct Response<T> { pub struct Response<T> {
pub data: T, pub data: T,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata> pub metadata: Option<Metadata>,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -30,7 +30,7 @@ pub struct Metadata {
pub total: i32, pub total: i32,
pub limit: i32, pub limit: i32,
pub page: i32, pub page: i32,
pub pages: i32 pub pages: i32,
} }
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
@@ -69,20 +69,14 @@ impl From<std::string::FromUtf8Error> for ServiceError {
impl From<DieselError> for ServiceError { impl From<DieselError> for ServiceError {
fn from(error: DieselError) -> ServiceError { fn from(error: DieselError) -> ServiceError {
match error { match error {
DieselError::DatabaseError(kind, err) => { DieselError::DatabaseError(kind, err) => match kind {
match kind {
diesel::result::DatabaseErrorKind::UniqueViolation => { diesel::result::DatabaseErrorKind::UniqueViolation => {
ServiceError::new(409, err.message().to_string()) ServiceError::new(409, err.message().to_string())
},
_ => ServiceError::new(500, err.message().to_string())
} }
_ => ServiceError::new(500, err.message().to_string()),
}, },
DieselError::NotFound => { DieselError::NotFound => ServiceError::new(404, "The record was not found".to_string()),
ServiceError::new(404, "The record was not found".to_string()) DieselError::SerializationError(err) => ServiceError::new(422, err.to_string()),
},
DieselError::SerializationError(err) => {
ServiceError::new(422, err.to_string())
},
err => ServiceError::new(500, format!("Unknown database error: {}", err)), err => ServiceError::new(500, format!("Unknown database error: {}", err)),
} }
} }
@@ -121,10 +115,8 @@ impl From<redis::RedisError> for ServiceError {
impl From<s3::error::S3Error> for ServiceError { impl From<s3::error::S3Error> for ServiceError {
fn from(error: s3::error::S3Error) -> ServiceError { fn from(error: s3::error::S3Error) -> ServiceError {
match error { match error {
s3::error::S3Error::Http(code, message) => { s3::error::S3Error::Http(code, message) => ServiceError::new(code, message),
ServiceError::new(code, message) _ => ServiceError::new(500, format!("Unknown s3 error: {}", error)),
},
_ => ServiceError::new(500, format!("Unknown s3 error: {}", error))
} }
} }
} }
@@ -165,6 +157,7 @@ impl ResponseError for ServiceError {
false => "Internal server error".to_string(), false => "Internal server error".to_string(),
}; };
HttpResponse::build(status_code).json(serde_json::json!({ "status": status_code.as_u16(), "message": error_message })) HttpResponse::build(status_code)
.json(serde_json::json!({ "status": status_code.as_u16(), "message": error_message }))
} }
} }

View File

@@ -17,8 +17,8 @@ use actix_web::{HttpServer, App, web};
use crate::bot::handler::Handler; use crate::bot::handler::Handler;
mod auth; mod auth;
mod dnd;
mod bot; mod bot;
mod dnd;
mod storage; mod storage;
mod users; mod users;
@@ -29,7 +29,7 @@ async fn main() -> std::io::Result<()> {
storage::init().await; storage::init().await;
match env::var("DATA_DIR_PATH") { match env::var("DATA_DIR_PATH") {
Ok(data_dir_path) => dnd::load_data(&data_dir_path), Ok(data_dir_path) => dnd::load_data(&data_dir_path),
Err(err) => warn!("Unable to load initial database data: {}", err) Err(err) => warn!("Unable to load initial database data: {}", err),
}; };
let token: String = env::var("DISCORD_TOKEN").expect("Expected a token in the environment"); let token: String = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
@@ -46,10 +46,10 @@ async fn main() -> std::io::Result<()> {
} }
match http.get_current_user().await { match http.get_current_user().await {
Ok(bot) => (owners, bot.id), Ok(bot) => (owners, bot.id),
Err(why) => panic!("Could not access the bot id: {:?}", why) Err(why) => panic!("Could not access the bot id: {:?}", why),
} }
}, }
Err(why) => panic!("Could not access application info: {:?}", why) Err(why) => panic!("Could not access application info: {:?}", why),
}; };
let handler = match env::var("OPENAI_API_KEY") { let handler = match env::var("OPENAI_API_KEY") {
@@ -66,7 +66,7 @@ async fn main() -> std::io::Result<()> {
max_context_questions: 30, max_context_questions: 30,
max_tokens: 2048, max_tokens: 2048,
default_model, default_model,
}) }),
} }
} }
Err(err) => { Err(err) => {
@@ -79,8 +79,7 @@ async fn main() -> std::io::Result<()> {
let mut client = Client::builder(token, intents) let mut client = Client::builder(token, intents)
.event_handler(handler) .event_handler(handler)
.framework(StandardFramework::new() .framework(StandardFramework::new().configure(|c| c.owners(owners)))
.configure(|c| c.owners(owners)))
.register_songbird_with(Arc::clone(&songbird)) .register_songbird_with(Arc::clone(&songbird))
.await .await
.expect("Error creating client"); .expect("Error creating client");
@@ -91,14 +90,15 @@ async fn main() -> std::io::Result<()> {
let app_data = Arc::new(AppState { let app_data = Arc::new(AppState {
http, http,
cache, cache,
songbird: Arc::clone(&songbird) songbird: Arc::clone(&songbird),
}); });
let shard_manager = Arc::clone(&client.shard_manager); let shard_manager = Arc::clone(&client.shard_manager);
tokio::spawn(async move { tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Could not register ctrl+c handler"); tokio::signal::ctrl_c()
.await
.expect("Could not register ctrl+c handler");
shard_manager.lock().await.shutdown_all().await; shard_manager.lock().await.shutdown_all().await;
}); });
@@ -127,23 +127,23 @@ async fn main() -> std::io::Result<()> {
.configure(crate::bot::guilds::init_routes) .configure(crate::bot::guilds::init_routes)
.configure(crate::bot::messages::init_routes) .configure(crate::bot::messages::init_routes)
}) })
.bind(format!("{}:{}", host, port)) { .bind(format!("{}:{}", host, port))
{
Ok(b) => { Ok(b) => {
info!("Binding server to {}:{}", host, port); info!("Binding server to {}:{}", host, port);
b b
}, }
Err(err) => { Err(err) => {
error!("Could not bind server: {}", err); error!("Could not bind server: {}", err);
return Err(err); return Err(err);
} }
}; };
server.run() server.run().await
.await
} }
pub struct AppState { pub struct AppState {
pub http: Arc<Http>, pub http: Arc<Http>,
pub cache: Arc<Cache>, pub cache: Arc<Cache>,
pub songbird: Arc<Songbird> pub songbird: Arc<Songbird>,
} }

View File

@@ -22,9 +22,15 @@ lazy_static! {
let host = env::var("DATABASE_HOST").unwrap_or("localhost".to_string()); let host = env::var("DATABASE_HOST").unwrap_or("localhost".to_string());
let name = env::var("DATABASE_NAME").expect("DATABASE_NAME is not set"); let name = env::var("DATABASE_NAME").expect("DATABASE_NAME is not set");
let port = env::var("DATABASE_PORT").unwrap_or("5432".to_string()); let port = env::var("DATABASE_PORT").unwrap_or("5432".to_string());
let url = format!("postgres://{}:{}@{}:{}/{}", username, password, host, port, name); let url = format!(
"postgres://{}:{}@{}:{}/{}",
username, password, host, port, name
);
let manager = DieselConnectionManager::<PgConnection>::new(url); let manager = DieselConnectionManager::<PgConnection>::new(url);
DbPool::builder().test_on_check_out(true).build(manager).expect("Failed to create db pool") DbPool::builder()
.test_on_check_out(true)
.build(manager)
.expect("Failed to create db pool")
}; };
static ref REDIS: RedisClient = { static ref REDIS: RedisClient = {
let host = env::var("REDIS_HOST").unwrap_or("localhost".to_string()); let host = env::var("REDIS_HOST").unwrap_or("localhost".to_string());
@@ -49,10 +55,12 @@ lazy_static! {
secret_key: Some(password), secret_key: Some(password),
security_token: None, security_token: None,
session_token: None, session_token: None,
expiration: None expiration: None,
}; };
Bucket::new("siren", region.clone(), credentials.clone()).expect("Failed to create S3 Bucket").with_path_style() Bucket::new("siren", region.clone(), credentials.clone())
.expect("Failed to create S3 Bucket")
.with_path_style()
}; };
} }
@@ -64,12 +72,13 @@ pub async fn init() {
let mut pool: DbConnection = connection().expect("Failed to get db connection"); let mut pool: DbConnection = connection().expect("Failed to get db connection");
match pool.run_pending_migrations(MIGRATIONS) { match pool.run_pending_migrations(MIGRATIONS) {
Ok(_) => info!("Database initialized"), Ok(_) => info!("Database initialized"),
Err(err) => error!("Failed to initialize database; {}", err) Err(err) => error!("Failed to initialize database; {}", err),
}; };
} }
pub fn connection() -> Result<DbConnection, ServiceError> { pub fn connection() -> Result<DbConnection, ServiceError> {
POOL.get() POOL
.get()
.map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e))) .map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e)))
} }
@@ -100,9 +109,11 @@ async fn create_bucket() {
secret_key: Some(password), secret_key: Some(password),
security_token: None, security_token: None,
session_token: None, session_token: None,
expiration: None expiration: None,
}; };
let _ = Bucket::create_with_path_style("siren", region, credentials, BucketConfiguration::default()).await; let _ =
Bucket::create_with_path_style("siren", region, credentials, BucketConfiguration::default())
.await;
} }
pub async fn upload_file(path: &str, content: &[u8]) -> Result<ResponseData, ServiceError> { pub async fn upload_file(path: &str, content: &[u8]) -> Result<ResponseData, ServiceError> {

View File

@@ -4,7 +4,10 @@ use log::error;
use serenity::futures::StreamExt; use serenity::futures::StreamExt;
use siren::ServiceError; use siren::ServiceError;
use crate::{auth::{Auth, InsertUser, QueryUser}, storage::{upload_file, get_file, delete_file}}; use crate::{
auth::{Auth, InsertUser, QueryUser},
storage::{upload_file, get_file, delete_file},
};
#[post("/picture")] #[post("/picture")]
async fn set_picture(mut payload: Multipart, auth: Auth) -> HttpResponse { async fn set_picture(mut payload: Multipart, auth: Auth) -> HttpResponse {
@@ -12,7 +15,7 @@ async fn set_picture(mut payload: Multipart, auth: Auth) -> HttpResponse {
let mut bytes = web::BytesMut::new(); let mut bytes = web::BytesMut::new();
let mut field = match item { let mut field = match item {
Ok(field) => field, Ok(field) => field,
Err(err) => return ResponseError::error_response(&err) Err(err) => return ResponseError::error_response(&err),
}; };
let content_type = field.content_disposition(); let content_type = field.content_disposition();
// Get file name and construct the file path // Get file name and construct the file path
@@ -20,25 +23,29 @@ async fn set_picture(mut payload: Multipart, auth: Auth) -> HttpResponse {
Some(name) => { Some(name) => {
// Verify extension is supported // Verify extension is supported
match name.split(".").last() { match name.split(".").last() {
Some(ext) => { Some(ext) => match ext {
match ext {
"png" | "jpg" | "jpeg" => name, "png" | "jpg" | "jpeg" => name,
_ => return ResponseError::error_response(&ServiceError { _ => {
return ResponseError::error_response(&ServiceError {
status: 400, status: 400,
message: "File extension is not supported".to_string() message: "File extension is not supported".to_string(),
}) })
} }
}, },
None => return ResponseError::error_response(&ServiceError { None => {
return ResponseError::error_response(&ServiceError {
status: 400, status: 400,
message: "Unknown file extension".to_string() message: "Unknown file extension".to_string(),
}) })
} }
}, }
None => return ResponseError::error_response(&ServiceError { }
None => {
return ResponseError::error_response(&ServiceError {
status: 400, status: 400,
message: "File name is not provided".to_string() message: "File name is not provided".to_string(),
}) })
}
}; };
let path = format!("users/{}/{}", auth.user.email, file_name); let path = format!("users/{}/{}", auth.user.email, file_name);
@@ -62,13 +69,13 @@ async fn set_picture(mut payload: Multipart, auth: Auth) -> HttpResponse {
return ResponseError::error_response(&err); return ResponseError::error_response(&err);
} }
}; };
}, }
Err(err) => { Err(err) => {
error!("Failed to upload file: {}", err); error!("Failed to upload file: {}", err);
return ResponseError::error_response(&err); return ResponseError::error_response(&err);
} }
} }
}; }
return HttpResponse::Ok().finish(); return HttpResponse::Ok().finish();
} }
@@ -97,8 +104,7 @@ async fn get_picture(auth: Auth) -> HttpResponse {
#[delete("/picture")] #[delete("/picture")]
async fn delete_picture(auth: Auth) -> HttpResponse { async fn delete_picture(auth: Auth) -> HttpResponse {
match QueryUser::get_by_email(&auth.user.email) { match QueryUser::get_by_email(&auth.user.email) {
Ok(user) => { Ok(user) => match user.profile_picture {
match user.profile_picture {
Some(path) => { Some(path) => {
match delete_file(&path).await { match delete_file(&path).await {
Ok(_) => { Ok(_) => {
@@ -115,9 +121,8 @@ async fn delete_picture(auth: Auth) -> HttpResponse {
return ResponseError::error_response(&err); return ResponseError::error_response(&err);
} }
}; };
},
None => {}
} }
None => {}
}, },
Err(err) => { Err(err) => {
error!("Failed to get user: {}", err); error!("Failed to get user: {}", err);
@@ -128,9 +133,10 @@ async fn delete_picture(auth: Auth) -> HttpResponse {
} }
pub fn init_routes(config: &mut web::ServiceConfig) { pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(web::scope("users") config.service(
web::scope("users")
.service(set_picture) .service(set_picture)
.service(get_picture) .service(get_picture)
.service(delete_picture) .service(delete_picture),
); );
} }