Merge branch '#4-id-instead-of-name' into 'main'

feat: completed migration

Closes #4

See merge request compsoc1/skynet/discord-bot!2
This commit is contained in:
silver 2023-09-26 00:16:24 +00:00
commit 6a0b664e7d
6 changed files with 63 additions and 55 deletions

View file

@ -11,7 +11,6 @@ name = "update_data"
[[bin]] [[bin]]
name = "update_users" name = "update_users"
[dependencies] [dependencies]
serenity = { version = "0.11.6", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "cache"] } serenity = { version = "0.11.6", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "cache"] }
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] } tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }

View file

@ -16,8 +16,6 @@ async fn main() {
get_wolves_csv(&db, &config).await; get_wolves_csv(&db, &config).await;
// handle wolves api here // handle wolves api here
get_wolves(&db).await; get_wolves(&db).await;
// get from skynet for the compsoc server only
get_skynet(&db, &config).await;
} }
async fn get_wolves_csv(db: &Pool<Sqlite>, config: &Config) { async fn get_wolves_csv(db: &Pool<Sqlite>, config: &Config) {
@ -133,35 +131,6 @@ pub struct SkynetResult {
discord: String, discord: String,
id_member: String, id_member: String,
} }
async fn get_skynet(db: &Pool<Sqlite>, config: &Config) {
let url = format!("{}/ldap/discord?auth={}", &config.ldap_api, &config.auth);
if let Ok(result) = surf::get(url).recv_json::<Vec<SkynetResult>>().await {
for user in result {
add_users_skynet(db, &user).await;
}
}
}
async fn add_users_skynet(db: &Pool<Sqlite>, user: &SkynetResult) {
match sqlx::query_as::<_, Wolves>(
"
UPDATE wolves
SET discord = ?
WHERE id_wolves = ?
",
)
.bind(&user.discord)
.bind(&user.id_member)
.fetch_optional(db)
.await
{
Ok(_) => {}
Err(e) => {
println!("Failure to insert skynet user into database {:?}", user);
println!("{:?}", e);
}
}
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct WolvesResult { struct WolvesResult {

View file

@ -82,7 +82,7 @@ async fn bulk_check(ctx: Arc<Context>) {
if let Ok(x) = server.members(&ctx, None, None).await { if let Ok(x) = server.members(&ctx, None, None).await {
for mut member in x { for mut member in x {
if members.contains(&member.user.name) { if members.contains(&member.user.id) {
let mut roles = vec![]; let mut roles = vec![];
if let Some(role) = &role_past { if let Some(role) = &role_past {

View file

@ -6,7 +6,7 @@ use serenity::{
prelude::{command::CommandOptionType, interaction::application_command::CommandDataOptionValue}, prelude::{command::CommandOptionType, interaction::application_command::CommandDataOptionValue},
}, },
}; };
use skynet_discord_bot::{DataBase, Servers, Wolves}; use skynet_discord_bot::{DataBase, Servers};
use sqlx::{Error, Pool, Sqlite}; use sqlx::{Error, Pool, Sqlite};
pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String { pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String {
@ -130,11 +130,11 @@ pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicatio
}) })
} }
async fn add_server(db: &Pool<Sqlite>, server: &Servers) -> Result<Option<Wolves>, Error> { async fn add_server(db: &Pool<Sqlite>, server: &Servers) -> Result<Option<Servers>, Error> {
let role_past = server.role_past.map(|x| *x.as_u64() as i64); let role_past = server.role_past.map(|x| *x.as_u64() as i64);
let role_current = server.role_current.map(|x| *x.as_u64() as i64); let role_current = server.role_current.map(|x| *x.as_u64() as i64);
sqlx::query_as::<_, Wolves>( sqlx::query_as::<_, Servers>(
" "
INSERT OR REPLACE INTO servers (server, wolves_api, role_past, role_current) INSERT OR REPLACE INTO servers (server, wolves_api, role_past, role_current)
VALUES (?1, ?2, ?3, ?4) VALUES (?1, ?2, ?3, ?4)

View file

@ -17,6 +17,7 @@ use sqlx::{Pool, Sqlite};
pub(crate) mod link { pub(crate) mod link {
use super::*; use super::*;
use serenity::model::id::UserId;
pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String { pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String {
let db_lock = { let db_lock = {
@ -31,7 +32,7 @@ pub(crate) mod link {
}; };
let config = config_lock.read().await; let config = config_lock.read().await;
if get_server_member_discord(&db, &command.user.name).await.is_some() { if get_server_member_discord(&db, &command.user.id).await.is_some() {
return "Already linked".to_string(); return "Already linked".to_string();
} }
@ -71,7 +72,7 @@ pub(crate) mod link {
// generate a auth key // generate a auth key
let auth = random_string(20); let auth = random_string(20);
match send_mail(&config, &details, &auth, &command.user.name) { match send_mail(&config, &details, &auth, &command.user.name) {
Ok(_) => match save_to_db(&db, &details, &auth, &command.user.name).await { Ok(_) => match save_to_db(&db, &details, &auth, &command.user.id).await {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
return format!("Unable to save to db {} {e:?}", &details.email); return format!("Unable to save to db {} {e:?}", &details.email);
@ -92,7 +93,7 @@ pub(crate) mod link {
.create_option(|option| option.name("email").description("UL Wolves Email").kind(CommandOptionType::String).required(true)) .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> { async fn get_server_member_discord(db: &Pool<Sqlite>, user: &UserId) -> Option<Wolves> {
sqlx::query_as::<_, Wolves>( sqlx::query_as::<_, Wolves>(
r#" r#"
SELECT * SELECT *
@ -100,7 +101,7 @@ pub(crate) mod link {
WHERE discord = ? WHERE discord = ?
"#, "#,
) )
.bind(user) .bind(*user.as_u64() as i64)
.fetch_one(db) .fetch_one(db)
.await .await
.ok() .ok()
@ -218,7 +219,7 @@ pub(crate) mod link {
.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: &UserId) -> 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)
@ -226,7 +227,7 @@ pub(crate) mod link {
", ",
) )
.bind(record.email.to_owned()) .bind(record.email.to_owned())
.bind(user) .bind(*user.as_u64() as i64)
.bind(auth.to_owned()) .bind(auth.to_owned())
.bind(get_now_iso(false)) .bind(get_now_iso(false))
.fetch_optional(db) .fetch_optional(db)

View file

@ -10,6 +10,7 @@ use serenity::{
use chrono::{Datelike, SecondsFormat, Utc}; use chrono::{Datelike, SecondsFormat, Utc};
use rand::{distributions::Alphanumeric, thread_rng, Rng}; use rand::{distributions::Alphanumeric, thread_rng, Rng};
use serenity::model::id::UserId;
use sqlx::{ use sqlx::{
sqlite::{SqliteConnectOptions, SqlitePoolOptions, SqliteRow}, sqlite::{SqliteConnectOptions, SqlitePoolOptions, SqliteRow},
Error, FromRow, Pool, Row, Sqlite, Error, FromRow, Pool, Row, Sqlite,
@ -125,40 +126,78 @@ pub struct ServerMembersWolves {
pub id_wolves: String, pub id_wolves: String,
pub expiry: String, pub expiry: String,
pub email: String, pub email: String,
pub discord: Option<String>, pub discord: Option<UserId>,
pub minecraft: Option<String>, pub minecraft: Option<String>,
} }
impl<'r> FromRow<'r, SqliteRow> for ServerMembersWolves { impl<'r> FromRow<'r, SqliteRow> for ServerMembersWolves {
fn from_row(row: &'r SqliteRow) -> Result<Self, Error> { fn from_row(row: &'r SqliteRow) -> Result<Self, Error> {
let server_tmp: i64 = row.try_get("server")?; let server_tmp: i64 = row.try_get("server")?;
let server = GuildId::from(server_tmp as u64); let server = GuildId::from(server_tmp as u64);
let discord = match row.try_get("discord") {
Ok(x) => {
let tmp: i64 = x;
Some(UserId::from(tmp as u64))
}
_ => None,
};
Ok(Self { Ok(Self {
server, server,
id_wolves: row.try_get("id_wolves")?, id_wolves: row.try_get("id_wolves")?,
expiry: row.try_get("expiry")?, expiry: row.try_get("expiry")?,
email: row.try_get("email")?, email: row.try_get("email")?,
discord: row.try_get("discord")?, discord,
minecraft: row.try_get("minecraft")?, minecraft: row.try_get("minecraft")?,
}) })
} }
} }
#[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Wolves { pub struct Wolves {
pub id_wolves: String, pub id_wolves: String,
pub email: String, pub email: String,
pub discord: Option<String>, pub discord: Option<UserId>,
pub minecraft: Option<String>, pub minecraft: Option<String>,
} }
impl<'r> FromRow<'r, SqliteRow> for Wolves {
fn from_row(row: &'r SqliteRow) -> Result<Self, Error> {
let discord = match row.try_get("discord") {
Ok(x) => {
let tmp: i64 = x;
Some(UserId::from(tmp as u64))
}
_ => None,
};
#[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)] Ok(Self {
id_wolves: row.try_get("id_wolves")?,
email: row.try_get("email")?,
discord,
minecraft: row.try_get("minecraft")?,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WolvesVerify { pub struct WolvesVerify {
pub email: String, pub email: String,
pub discord: String, pub discord: UserId,
pub auth_code: String, pub auth_code: String,
pub date_expiry: String, pub date_expiry: String,
} }
impl<'r> FromRow<'r, SqliteRow> for WolvesVerify {
fn from_row(row: &'r SqliteRow) -> Result<Self, Error> {
let user_tmp: i64 = row.try_get("discord")?;
let discord = UserId::from(user_tmp as u64);
Ok(Self {
email: row.try_get("email")?,
discord,
auth_code: row.try_get("auth_code")?,
date_expiry: row.try_get("date_expiry")?,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Servers { pub struct Servers {
@ -213,9 +252,9 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
sqlx::query( sqlx::query(
"CREATE TABLE IF NOT EXISTS wolves ( "CREATE TABLE IF NOT EXISTS wolves (
id_wolves text PRIMARY KEY, id_wolves text PRIMARY KEY,
email text not null, email text not null,
discord text, discord integer,
minecraft text minecraft text
)", )",
) )
@ -226,10 +265,10 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
sqlx::query( sqlx::query(
"CREATE TABLE IF NOT EXISTS wolves_verify ( "CREATE TABLE IF NOT EXISTS wolves_verify (
discord text PRIMARY KEY, discord integer PRIMARY KEY,
email text not null, email text not null,
auth_code text not null, auth_code text not null,
date_expiry text not null date_expiry text not null
)", )",
) )
.execute(&pool) .execute(&pool)