From 39277340839c85efb67ed6d7494aefa2da201ab6 Mon Sep 17 00:00:00 2001 From: Brendan Golden Date: Mon, 28 Oct 2024 01:06:21 +0000 Subject: [PATCH] feat: split out minecraft --- src/bin/update_minecraft.rs | 3 +- src/commands/minecraft.rs | 16 ++-- src/common/database.rs | 18 ---- src/common/minecraft.rs | 167 ++++++++++++++++++++++++++++++++++++ src/common/mod.rs | 3 +- src/lib.rs | 140 +----------------------------- 6 files changed, 182 insertions(+), 165 deletions(-) create mode 100644 src/common/minecraft.rs diff --git a/src/bin/update_minecraft.rs b/src/bin/update_minecraft.rs index f959d99..cae6b62 100644 --- a/src/bin/update_minecraft.rs +++ b/src/bin/update_minecraft.rs @@ -1,6 +1,7 @@ -use skynet_discord_bot::{get_config, get_minecraft_config, update_server, whitelist_wipe}; +use skynet_discord_bot::get_config; use std::collections::HashSet; use skynet_discord_bot::common::database::db_init; +use skynet_discord_bot::common::minecraft::{get_minecraft_config, update_server, whitelist_wipe}; #[tokio::main] async fn main() { diff --git a/src/commands/minecraft.rs b/src/commands/minecraft.rs index fb87326..962fe1f 100644 --- a/src/commands/minecraft.rs +++ b/src/commands/minecraft.rs @@ -16,9 +16,10 @@ pub(crate) mod user { use super::*; use crate::commands::link_email::link::get_server_member_discord; use serenity::model::id::UserId; - use skynet_discord_bot::{whitelist_update, Config}; + use skynet_discord_bot::Config; use sqlx::Error; - use skynet_discord_bot::common::database::{Minecraft, Wolves}; + use skynet_discord_bot::common::database::Wolves; + use skynet_discord_bot::common::minecraft::{whitelist_update, Minecraft}; pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { command.name("link_minecraft").description("Link your minecraft account").create_option(|option| { @@ -123,8 +124,9 @@ pub(crate) mod server { use sqlx::Error; // this is to managfe the server side of commands related to minecraft use super::*; - use skynet_discord_bot::{is_admin, update_server, Config}; - use skynet_discord_bot::common::database::Minecraft; + use skynet_discord_bot::{is_admin, Config}; + use skynet_discord_bot::common::minecraft::Minecraft; + use skynet_discord_bot::common::minecraft::update_server; pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { command.name("minecraft_add").description("Add a minecraft server").create_option(|option| { @@ -203,8 +205,9 @@ pub(crate) mod server { use serenity::builder::CreateApplicationCommand; use serenity::client::Context; use serenity::model::prelude::application_command::ApplicationCommandInteraction; - use skynet_discord_bot::{get_minecraft_config_server, is_admin, server_information, Config}; + use skynet_discord_bot::{is_admin, Config}; use skynet_discord_bot::common::database::DataBase; + use skynet_discord_bot::common::minecraft::{get_minecraft_config_server, server_information}; pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { command.name("minecraft_list").description("List your minecraft servers") @@ -267,7 +270,8 @@ pub(crate) mod server { use serenity::model::prelude::application_command::{ApplicationCommandInteraction, CommandDataOptionValue}; use skynet_discord_bot::is_admin; use sqlx::{Error, Pool, Sqlite}; - use skynet_discord_bot::common::database::{DataBase, Minecraft}; + use skynet_discord_bot::common::database::DataBase; + use skynet_discord_bot::common::minecraft::Minecraft; pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { command.name("minecraft_delete").description("Delete a minecraft server").create_option(|option| { diff --git a/src/common/database.rs b/src/common/database.rs index 6eb1734..9674499 100644 --- a/src/common/database.rs +++ b/src/common/database.rs @@ -178,24 +178,6 @@ impl<'r> FromRow<'r, SqliteRow> for Servers { } } -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct Minecraft { - pub discord: GuildId, - pub minecraft: String, -} - -impl<'r> FromRow<'r, SqliteRow> for Minecraft { - fn from_row(row: &'r SqliteRow) -> Result { - let server_tmp: i64 = row.try_get("server_discord")?; - let discord = GuildId::from(server_tmp as u64); - - Ok(Self { - discord, - minecraft: row.try_get("server_minecraft")?, - }) - } -} - #[derive(Debug, Clone, Deserialize, Serialize)] pub struct RoleAdder { pub server: GuildId, diff --git a/src/common/minecraft.rs b/src/common/minecraft.rs new file mode 100644 index 0000000..55ce53b --- /dev/null +++ b/src/common/minecraft.rs @@ -0,0 +1,167 @@ +use serde::{Deserialize, Serialize}; +use serde::de::DeserializeOwned; +use sqlx::{Error, FromRow, Pool, Row, Sqlite}; +use serenity::model::id::GuildId; +use sqlx::sqlite::SqliteRow; +use crate::Config; +use crate::set_roles::get_server_member_bulk; + + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct Minecraft { + pub discord: GuildId, + pub minecraft: String, +} + +impl<'r> FromRow<'r, SqliteRow> for Minecraft { + fn from_row(row: &'r SqliteRow) -> Result { + let server_tmp: i64 = row.try_get("server_discord")?; + let discord = GuildId::from(server_tmp as u64); + + Ok(Self { + discord, + minecraft: row.try_get("server_minecraft")?, + }) + } +} + + +/** +loop through all members of server +get a list of folks with mc accounts that are members +and a list that arent members + */ +pub async fn update_server(server_id: &str, db: &Pool, g_id: &GuildId, config: &Config) { + let mut usernames = vec![]; + for member in get_server_member_bulk(db, g_id).await { + if let Some(x) = member.minecraft { + usernames.push(x); + } + } + if !usernames.is_empty() { + whitelist_update(&usernames, server_id, &config.discord_token_minecraft).await; + } +} + +async fn post(url: &str, bearer: &str, data: &T) { + match surf::post(url) + .header("Authorization", bearer) + .header("Content-Type", "application/json") + .header("Accept", "Application/vnd.pterodactyl.v1+json") + .body_json(&data) + { + Ok(req) => { + req.await.ok(); + } + Err(e) => { + dbg!(e); + } + } +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerDetailsResSub { + pub identifier: String, + pub name: String, + pub description: String, + pub is_suspended: bool, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerDetailsRes { + pub attributes: ServerDetailsResSub, +} + +async fn get(url: &str, bearer: &str) -> Option { + match surf::get(url) + .header("Authorization", bearer) + .header("Content-Type", "application/json") + .header("Accept", "Application/vnd.pterodactyl.v1+json") + .recv_json() + .await + { + Ok(res) => Some(res), + Err(e) => { + dbg!(e); + + None + } + } +} + +#[derive(Deserialize, Serialize, Debug)] +struct BodyCommand { + command: String, +} + +#[derive(Deserialize, Serialize, Debug)] +struct BodyDelete { + root: String, + files: Vec, +} + +pub async fn whitelist_update(add: &Vec, server: &str, token: &str) { + let url_base = format!("http://panel.games.skynet.ie/api/client/servers/{server}"); + let bearer = format!("Bearer {token}"); + + for name in add { + let data = BodyCommand { + command: format!("whitelist add {name}"), + }; + post(&format!("{url_base}/command"), &bearer, &data).await; + } +} + +pub async fn whitelist_wipe(server: &str, token: &str) { + let url_base = format!("http://panel.games.skynet.ie/api/client/servers/{server}"); + let bearer = format!("Bearer {token}"); + + // delete whitelist + let deletion = BodyDelete { + root: "/".to_string(), + files: vec!["whitelist.json".to_string()], + }; + post(&format!("{url_base}/files/delete"), &bearer, &deletion).await; + + // recreate teh file, passing in the type here so the compiler knows what type of vec it is + post::>(&format!("{url_base}/files/write?file=%2Fwhitelist.json"), &bearer, &vec![]).await; + + // reload the whitelist + let data = BodyCommand { + command: "whitelist reload".to_string(), + }; + post(&format!("{url_base}/command"), &bearer, &data).await; +} + +pub async fn server_information(server: &str, token: &str) -> Option { + let url_base = format!("http://panel.games.skynet.ie/api/client/servers/{server}"); + let bearer = format!("Bearer {token}"); + get::(&format!("{url_base}/"), &bearer).await +} + +pub async fn get_minecraft_config(db: &Pool) -> Vec { + sqlx::query_as::<_, Minecraft>( + r#" + SELECT * + FROM minecraft + "#, + ) + .fetch_all(db) + .await + .unwrap_or_default() +} + +pub async fn get_minecraft_config_server(db: &Pool, g_id: GuildId) -> Vec { + sqlx::query_as::<_, Minecraft>( + r#" + SELECT * + FROM minecraft + WHERE server_discord = ?1 + "#, + ) + .bind(*g_id.as_u64() as i64) + .fetch_all(db) + .await + .unwrap_or_default() +} + diff --git a/src/common/mod.rs b/src/common/mod.rs index a992f8b..3302619 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,2 +1,3 @@ pub mod wolves; -pub mod database; \ No newline at end of file +pub mod database; +pub mod minecraft; \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index dfc7c4f..5dbbe0d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,7 +19,7 @@ use sqlx::{ }; use std::{env, sync::Arc}; use tokio::sync::RwLock; -use common::database::{Minecraft, ServerMembersWolves, Servers}; +use common::database::{ServerMembersWolves, Servers}; pub struct Config { // manages where teh database is stored @@ -267,141 +267,3 @@ pub async fn is_admin(command: &ApplicationCommandInteraction, ctx: &Context) -> None } } - -/** -loop through all members of server -get a list of folks with mc accounts that are members -and a list that arent members - */ -pub async fn update_server(server_id: &str, db: &Pool, g_id: &GuildId, config: &Config) { - let mut usernames = vec![]; - for member in get_server_member_bulk(db, g_id).await { - if let Some(x) = member.minecraft { - usernames.push(x); - } - } - if !usernames.is_empty() { - whitelist_update(&usernames, server_id, &config.discord_token_minecraft).await; - } -} - -async fn post(url: &str, bearer: &str, data: &T) { - match surf::post(url) - .header("Authorization", bearer) - .header("Content-Type", "application/json") - .header("Accept", "Application/vnd.pterodactyl.v1+json") - .body_json(&data) - { - Ok(req) => { - req.await.ok(); - } - Err(e) => { - dbg!(e); - } - } -} - -#[derive(Deserialize, Serialize, Debug)] -pub struct ServerDetailsResSub { - pub identifier: String, - pub name: String, - pub description: String, - pub is_suspended: bool, -} -#[derive(Deserialize, Serialize, Debug)] -pub struct ServerDetailsRes { - pub attributes: ServerDetailsResSub, -} - -async fn get(url: &str, bearer: &str) -> Option { - match surf::get(url) - .header("Authorization", bearer) - .header("Content-Type", "application/json") - .header("Accept", "Application/vnd.pterodactyl.v1+json") - .recv_json() - .await - { - Ok(res) => Some(res), - Err(e) => { - dbg!(e); - - None - } - } -} - -#[derive(Deserialize, Serialize, Debug)] -struct BodyCommand { - command: String, -} - -#[derive(Deserialize, Serialize, Debug)] -struct BodyDelete { - root: String, - files: Vec, -} - -pub async fn whitelist_update(add: &Vec, server: &str, token: &str) { - let url_base = format!("http://panel.games.skynet.ie/api/client/servers/{server}"); - let bearer = format!("Bearer {token}"); - - for name in add { - let data = BodyCommand { - command: format!("whitelist add {name}"), - }; - post(&format!("{url_base}/command"), &bearer, &data).await; - } -} - -pub async fn whitelist_wipe(server: &str, token: &str) { - let url_base = format!("http://panel.games.skynet.ie/api/client/servers/{server}"); - let bearer = format!("Bearer {token}"); - - // delete whitelist - let deletion = BodyDelete { - root: "/".to_string(), - files: vec!["whitelist.json".to_string()], - }; - post(&format!("{url_base}/files/delete"), &bearer, &deletion).await; - - // recreate teh file, passing in the type here so the compiler knows what type of vec it is - post::>(&format!("{url_base}/files/write?file=%2Fwhitelist.json"), &bearer, &vec![]).await; - - // reload the whitelist - let data = BodyCommand { - command: "whitelist reload".to_string(), - }; - post(&format!("{url_base}/command"), &bearer, &data).await; -} - -pub async fn server_information(server: &str, token: &str) -> Option { - let url_base = format!("http://panel.games.skynet.ie/api/client/servers/{server}"); - let bearer = format!("Bearer {token}"); - get::(&format!("{url_base}/"), &bearer).await -} - -pub async fn get_minecraft_config(db: &Pool) -> Vec { - sqlx::query_as::<_, Minecraft>( - r#" - SELECT * - FROM minecraft - "#, - ) - .fetch_all(db) - .await - .unwrap_or_default() -} - -pub async fn get_minecraft_config_server(db: &Pool, g_id: GuildId) -> Vec { - sqlx::query_as::<_, Minecraft>( - r#" - SELECT * - FROM minecraft - WHERE server_discord = ?1 - "#, - ) - .bind(*g_id.as_u64() as i64) - .fetch_all(db) - .await - .unwrap_or_default() -}