fmt: package it better

This commit is contained in:
silver 2023-09-17 15:35:41 +01:00
parent 14cbf0bcad
commit 98e61d7548
2 changed files with 173 additions and 177 deletions

View file

@ -15,142 +15,145 @@ use serenity::{
use skynet_discord_bot::{get_now_iso, random_string, Config, DataBase, Wolves, WolvesVerify}; use skynet_discord_bot::{get_now_iso, random_string, Config, DataBase, Wolves, WolvesVerify};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String { pub(crate) mod link {
let db_lock = { use super::*;
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = { pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String {
let data_read = ctx.data.read().await; let db_lock = {
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone() let data_read = ctx.data.read().await;
}; data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
let config = config_lock.read().await; };
let db = db_lock.read().await;
if get_server_member_discord(&db, &command.user.name).await.is_some() { let config_lock = {
return "Already linked".to_string(); let data_read = ctx.data.read().await;
} data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()
};
let config = config_lock.read().await;
let option = command if get_server_member_discord(&db, &command.user.name).await.is_some() {
.data return "Already linked".to_string();
.options
.get(0)
.expect("Expected email option")
.resolved
.as_ref()
.expect("Expected email object");
let email = if let CommandDataOptionValue::String(email) = option {
email
} else {
return "Please provide a valid user".to_string();
};
// check if email exists
let details = match get_server_member_email(&db, email).await {
None => return "Please check is the same as on https://ulwolves.ie/".to_string(),
Some(x) => x,
};
if details.verified {
return "Email already verified".to_string();
}
db_pending_clear_expired(&db).await;
// send mail
if get_from_db(&db, &command.user.name).await.is_some() {
return "Please check email".to_string();
}
// generate a auth key
let auth = random_string(20);
match send_mail(&config, &details, &auth, &command.user.name) {
Ok(_) => match save_to_db(&db, &details, &auth, &command.user.name).await {
Ok(_) => {}
Err(e) => {
return format!("Unable to save to db {} {e:?}", &details.email);
}
},
Err(e) => {
return format!("Unable to send mail to {} {e:?}", &details.email);
} }
let option = command
.data
.options
.get(0)
.expect("Expected email option")
.resolved
.as_ref()
.expect("Expected email object");
let email = if let CommandDataOptionValue::String(email) = option {
email
} else {
return "Please provide a valid user".to_string();
};
// check if email exists
let details = match get_server_member_email(&db, email).await {
None => return "Please check is the same as on https://ulwolves.ie/".to_string(),
Some(x) => x,
};
if details.verified {
return "Email already verified".to_string();
}
db_pending_clear_expired(&db).await;
// send mail
if get_from_db(&db, &command.user.name).await.is_some() {
return "Please check email".to_string();
}
// generate a auth key
let auth = random_string(20);
match send_mail(&config, &details, &auth, &command.user.name) {
Ok(_) => match save_to_db(&db, &details, &auth, &command.user.name).await {
Ok(_) => {}
Err(e) => {
return format!("Unable to save to db {} {e:?}", &details.email);
}
},
Err(e) => {
return format!("Unable to send mail to {} {e:?}", &details.email);
}
}
format!("Verification email sent to {}, user is {} {:?}", email, command.user.name, command.guild_id)
} }
format!("Verification email sent to {}, user is {} {:?}", email, command.user.name, command.guild_id) pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
} command
.name("link")
.description("Set Wolves Email")
.create_option(|option| option.name("email").description("UL Wolves Email").kind(CommandOptionType::String).required(true))
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { async fn get_server_member_discord(db: &Pool<Sqlite>, user: &str) -> Option<Wolves> {
command sqlx::query_as::<_, Wolves>(
.name("link") r#"
.description("Set Wolves Email")
.create_option(|option| option.name("email").description("UL Wolves Email").kind(CommandOptionType::String).required(true))
}
async fn get_server_member_discord(db: &Pool<Sqlite>, user: &str) -> Option<Wolves> {
sqlx::query_as::<_, Wolves>(
r#"
SELECT * SELECT *
FROM wolves FROM wolves
WHERE discord = WHERE discord =
"#, "#,
) )
.bind(user) .bind(user)
.fetch_one(db) .fetch_one(db)
.await .await
.ok() .ok()
} }
async fn get_server_member_email(db: &Pool<Sqlite>, email: &str) -> Option<Wolves> { async fn get_server_member_email(db: &Pool<Sqlite>, email: &str) -> Option<Wolves> {
sqlx::query_as::<_, Wolves>( sqlx::query_as::<_, Wolves>(
r#" r#"
SELECT * SELECT *
FROM wolves FROM wolves
WHERE email = ? WHERE email = ?
"#, "#,
) )
.bind(email) .bind(email)
.fetch_one(db) .fetch_one(db)
.await .await
.ok() .ok()
} }
fn send_mail(config: &Config, email: &Wolves, auth: &str, user: &str) -> Result<smtp::response::Response, smtp::Error> { fn send_mail(config: &Config, email: &Wolves, auth: &str, user: &str) -> Result<smtp::response::Response, smtp::Error> {
let mail = &email.email; let mail = &email.email;
let discord = "https://discord.skynet.ie"; let discord = "https://discord.skynet.ie";
let sender = format!("UL Computer Society <{}>", &config.mail_user); let sender = format!("UL Computer Society <{}>", &config.mail_user);
// Create the html we want to send. // Create the html we want to send.
let html = html! { let html = html! {
head { head {
title { "Hello from Skynet!" } title { "Hello from Skynet!" }
style type="text/css" { style type="text/css" {
"h2, h4 { font-family: Arial, Helvetica, sans-serif; }" "h2, h4 { font-family: Arial, Helvetica, sans-serif; }"
} }
} }
div style="display: flex; flex-direction: column; align-items: center;" { div style="display: flex; flex-direction: column; align-items: center;" {
h2 { "Hello from Skynet!" } h2 { "Hello from Skynet!" }
// Substitute in the name of our recipient. // Substitute in the name of our recipient.
p { "Hi " (user) "," } p { "Hi " (user) "," }
p { p {
"Please use " pre { "/verify " (auth)} " to verify your discord account." "Please use " pre { "/verify " (auth)} " to verify your discord account."
} }
p { p {
"If you have issues please refer to our Discord server:" "If you have issues please refer to our Discord server:"
br; br;
a href=(discord) { (discord) } a href=(discord) { (discord) }
} }
p { p {
"Skynet Team" "Skynet Team"
br; br;
"UL Computer Society" "UL Computer Society"
} }
} }
}; };
let body_text = format!( let body_text = format!(
r#" r#"
Hi {user} Hi {user}
Please use "/verify {auth}" to verify your discord account. Please use "/verify {auth}" to verify your discord account.
@ -161,70 +164,71 @@ fn send_mail(config: &Config, email: &Wolves, auth: &str, user: &str) -> Result<
Skynet Team Skynet Team
UL Computer Society UL Computer Society
"# "#
); );
// Build the message. // Build the message.
let email = Message::builder() let email = Message::builder()
.from(sender.parse().unwrap()) .from(sender.parse().unwrap())
.to(mail.parse().unwrap()) .to(mail.parse().unwrap())
.subject("Skynet-Discord: Link Wolves.") .subject("Skynet-Discord: Link Wolves.")
.multipart( .multipart(
// This is composed of two parts. // This is composed of two parts.
// also helps not trip spam settings (uneven number of url's // also helps not trip spam settings (uneven number of url's
MultiPart::alternative() MultiPart::alternative()
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text)) .singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())), .singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())),
) )
.expect("failed to build email"); .expect("failed to build email");
let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone()); let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone());
// Open a remote connection to gmail using STARTTLS // Open a remote connection to gmail using STARTTLS
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build(); let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
// Send the email // Send the email
mailer.send(&email) mailer.send(&email)
} }
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Option<WolvesVerify> { async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Option<WolvesVerify> {
sqlx::query_as::<_, WolvesVerify>( sqlx::query_as::<_, WolvesVerify>(
r#" r#"
DELETE DELETE
FROM wolves_verify FROM wolves_verify
WHERE date_expiry < ? WHERE date_expiry < ?
"#, "#,
) )
.bind(get_now_iso(true)) .bind(get_now_iso(true))
.fetch_one(pool) .fetch_one(pool)
.await .await
.ok() .ok()
} }
async fn get_from_db(db: &Pool<Sqlite>, user: &str) -> Option<WolvesVerify> { async fn get_from_db(db: &Pool<Sqlite>, user: &str) -> Option<WolvesVerify> {
sqlx::query_as::<_, WolvesVerify>( sqlx::query_as::<_, WolvesVerify>(
r#" r#"
SELECT * SELECT *
FROM wolves_verify FROM wolves_verify
WHERE discord = WHERE discord =
"#, "#,
) )
.bind(user) .bind(user)
.fetch_one(db) .fetch_one(db)
.await .await
.ok() .ok()
} }
async fn save_to_db(db: &Pool<Sqlite>, record: &Wolves, auth: &str, user: &str) -> Result<Option<WolvesVerify>, sqlx::Error> { async fn save_to_db(db: &Pool<Sqlite>, record: &Wolves, auth: &str, user: &str) -> Result<Option<WolvesVerify>, sqlx::Error> {
sqlx::query_as::<_, WolvesVerify>( sqlx::query_as::<_, WolvesVerify>(
" "
INSERT INTO wolves_verify (email, discord, auth_code, date_expiry) INSERT INTO wolves_verify (email, discord, auth_code, date_expiry)
VALUES (?1, ?2, ?3, ?4) VALUES (?1, ?2, ?3, ?4)
", ",
) )
.bind(record.email.to_owned()) .bind(record.email.to_owned())
.bind(user) .bind(user)
.bind(auth.to_owned()) .bind(auth.to_owned())
.bind(get_now_iso(false)) .bind(get_now_iso(false))
.fetch_optional(db) .fetch_optional(db)
.await .await
}
} }

View file

@ -4,10 +4,7 @@ use serenity::{
async_trait, async_trait,
client::{Context, EventHandler}, client::{Context, EventHandler},
model::{ model::{
application::{ application::{command::Command, interaction::Interaction},
command::Command,
interaction::{Interaction, InteractionResponseType},
},
gateway::{GatewayIntents, Ready}, gateway::{GatewayIntents, Ready},
guild, guild,
}, },
@ -59,7 +56,7 @@ impl EventHandler for Handler {
println!("[Main] {} is connected!", ready.user.name); println!("[Main] {} is connected!", ready.user.name);
Command::set_global_application_commands(&ctx.http, |commands| { Command::set_global_application_commands(&ctx.http, |commands| {
commands.create_application_command(|command| commands::link_email::register(command)) commands.create_application_command(|command| commands::link_email::link::register(command))
}) })
.await .await
.ok(); .ok();
@ -71,16 +68,11 @@ impl EventHandler for Handler {
//println!("Received command interaction: {:#?}", command); //println!("Received command interaction: {:#?}", command);
let content = match command.data.name.as_str() { let content = match command.data.name.as_str() {
"link" => commands::link_email::run(&command, &ctx).await, "link" => commands::link_email::link::run(&command, &ctx).await,
_ => "not implemented :(".to_string(), _ => "not implemented :(".to_string(),
}; };
if let Err(why) = command if let Err(why) = command.edit_original_interaction_response(&ctx.http, |response| response.content(content)).await {
.edit_original_interaction_response(&ctx.http, |response| {
response.content(content)
})
.await
{
println!("Cannot respond to slash command: {}", why); println!("Cannot respond to slash command: {}", why);
} }
} }