From 1b6563464d9d671c3f61f08d9167937c22b8373f Mon Sep 17 00:00:00 2001 From: Vicky Date: Mon, 4 Nov 2024 12:36:05 +0100 Subject: [PATCH 1/9] added first draft of vote treatment structure --- src/io.rs | 2 +- src/modules.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/io.rs b/src/io.rs index fecf2fa..6e23bbe 100644 --- a/src/io.rs +++ b/src/io.rs @@ -34,7 +34,7 @@ type Context<'a> = poise::Context<'a, Data, GenericError>; #[derive(Debug, poise::Modal)] #[allow(dead_code)] // fields only used for Debug print #[name = "Créer un nouveau Vote"] -struct VoteCreation { +pub(crate) struct VoteCreation { /// The description of the event #[paragraph] #[name = "Description"] diff --git a/src/modules.rs b/src/modules.rs index 2e936d2..ddc50df 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -5,7 +5,53 @@ //! Many handler functions //! Every module encompassing a feature +use crate::io::VoteCreation; + #[cfg(test)] mod tests { // use super::*; } + +fn treatment_vote_modal( + ctx: poise::ApplicationContext<'_, Data, GenericError>, + data: VoteCreation, +) { + // parse data + // -> group needs to be matched with existing group or return an error + // -> check which of short_name and hours exist and decide on formatting + // create the final product and send to scheduler for next voting window + unimplemented!() +} + +fn treatment_vote_command( + ctx: poise::ApplicationContext<'_, Data, GenericError>, + data: VoteCreation, +) { + // parse data + // -> check which of short_name and hours exist and decide on formatting + // create the final product and send to scheduler with the start_date and non_days if specified + unimplemented!() +} + +fn treatment_short_vote( + ctx: poise::ApplicationContext<'_, Data, GenericError>, + data: VoteCreation, +) { + // parse data + // -> check whether hours exist and decide on formatting + // create the final product and send to scheduler with the start_date if specified and days + unimplemented!() +} + +fn treatment_long_vote(ctx: poise::ApplicationContext<'_, Data, GenericError>, data: VoteCreation) { + // parse data + // create the final product and pass it along with the start_date if it's here and the begining and end dates + unimplemented!() +} + +// 1: user types command (vote_modal) +// 2: modal pops +// 3: data from the modal gets parsed +// 3.1 : group has to be matched with groups else error +// 3.2 : check whether or not there are hours and short names, and decide on the formatting depending on it +// 4: send final output to scheduler, with (if possible) context so it can reply instead of sending a new post -- 2.45.1 From f053fa222d1a224770eebcb48c27e8fa205a8d4d Mon Sep 17 00:00:00 2001 From: Vicky Date: Mon, 4 Nov 2024 16:32:16 +0100 Subject: [PATCH 2/9] Added VoteContainer and some placeholder functions --- src/io.rs | 106 +++++++++++++++++++++++++++++++++++++++++-------- src/modules.rs | 54 +++++-------------------- 2 files changed, 98 insertions(+), 62 deletions(-) diff --git a/src/io.rs b/src/io.rs index 6e23bbe..7b4b267 100644 --- a/src/io.rs +++ b/src/io.rs @@ -19,7 +19,7 @@ //! } //! ``` //! -use poise::serenity_prelude as serenity; +use poise::serenity_prelude::{self as serenity}; /// User data, which is stored and accessible in all command invocations pub struct Data {} @@ -28,13 +28,66 @@ type GenericError = Box; /// The context (in a discord sence) of a message type Context<'a> = poise::Context<'a, Data, GenericError>; +/// Generic object that is used to transfer vote data to other parts of the code. +pub struct VoteContainer { + title: String, + description: String, + group: Option, + hours: Option, + short_name: Option, + start_date: Option, + non_days: Option, + days: Option, + date_begin: Option, + date_end: Option, + identifier: VoteTypeIdentifier, +} + +/// Only title, description and identifier are mandatory +impl VoteContainer { + pub fn new(title: String, description: String, identifier: VoteTypeIdentifier) -> Self { + Self { + title, + description, + identifier, + ..Default::default() + } + } +} + +/// Default is None +impl Default for VoteContainer { + fn default() -> Self { + Self { + title: "".to_string(), + description: "".to_string(), + group: None, + hours: None, + short_name: None, + start_date: None, + non_days: None, + days: None, + date_begin: None, + date_end: None, + identifier: VoteTypeIdentifier::Uninitialised, + } + } +} + +pub enum VoteTypeIdentifier { + WeeklyVote, + ShortVote, + LongVote, + Uninitialised, +} + /// The result of a vote creation. /// /// This struct is used to store and display the results of creating a new vote via a discord modal form. #[derive(Debug, poise::Modal)] #[allow(dead_code)] // fields only used for Debug print #[name = "Créer un nouveau Vote"] -pub(crate) struct VoteCreation { +pub(crate) struct WeeklyVoteModal { /// The description of the event #[paragraph] #[name = "Description"] @@ -66,9 +119,9 @@ pub(crate) struct VoteCreation { } #[cfg(test)] // This default implementation only exists during testing -impl Default for VoteCreation { +impl Default for WeeklyVoteModal { fn default() -> Self { - VoteCreation { + WeeklyVoteModal { description: "Dummy vote".into(), group: Some("Base group".into()), hours: Some("21h - 23".into()), @@ -90,21 +143,40 @@ pub async fn vote_modal( ) -> Result<(), GenericError> { use poise::Modal as _; - let data = VoteCreation::execute(ctx).await?; - // TODO: Change with logging - println!("Got data: {:?}", data); + let data = WeeklyVoteModal::execute(ctx).await?; if let Some(unwrapped_data) = data { - let group = unwrapped_data.group.unwrap_or("".into()); - let title = unwrapped_data.title; - let description = unwrapped_data.description; - let short_name = unwrapped_data.short_name.unwrap_or("".into()); - let hours = unwrapped_data.hours.unwrap_or("".into()); + log::info!( + "@{:?} **{:?}**\n{:?}\n{:?}, {:?}", + unwrapped_data.group, + unwrapped_data.title, + unwrapped_data.description, + unwrapped_data.short_name, + unwrapped_data.hours + ); - let reply = poise::CreateReply::default().content(format!( - "@{} **{}**\n{}\n{}, {}", - group, title, description, short_name, hours - )); - ctx.send(reply).await?; + log::info!("{:?}", ctx); + + // let group = unwrapped_data.group.unwrap_or("".into()); + // let title = unwrapped_data.title; + // let description = unwrapped_data.description; + // let short_name = unwrapped_data.short_name.unwrap_or("".into()); + // let hours = unwrapped_data.hours.unwrap_or("".into()); + + let serotoninenjoyer = VoteContainer { + title: unwrapped_data.title, + description: unwrapped_data.description, + group: unwrapped_data.group, + hours: unwrapped_data.hours, + short_name: unwrapped_data.short_name, + identifier: VoteTypeIdentifier::WeeklyVote, + ..Default::default() + }; + + // let reply = poise::CreateReply::default().content(format!( + // "@{} **{}**\n{}\n{}, {}", + // group, title, description, short_name, hours + // )); + // ctx.send(reply).await?; }; Ok(()) diff --git a/src/modules.rs b/src/modules.rs index ddc50df..979c55a 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -5,53 +5,17 @@ //! Many handler functions //! Every module encompassing a feature -use crate::io::VoteCreation; +struct LongVote { + // todo +} +struct ShortVote { + // todo +} +struct WeeklyVote { + // todo +} #[cfg(test)] mod tests { // use super::*; } - -fn treatment_vote_modal( - ctx: poise::ApplicationContext<'_, Data, GenericError>, - data: VoteCreation, -) { - // parse data - // -> group needs to be matched with existing group or return an error - // -> check which of short_name and hours exist and decide on formatting - // create the final product and send to scheduler for next voting window - unimplemented!() -} - -fn treatment_vote_command( - ctx: poise::ApplicationContext<'_, Data, GenericError>, - data: VoteCreation, -) { - // parse data - // -> check which of short_name and hours exist and decide on formatting - // create the final product and send to scheduler with the start_date and non_days if specified - unimplemented!() -} - -fn treatment_short_vote( - ctx: poise::ApplicationContext<'_, Data, GenericError>, - data: VoteCreation, -) { - // parse data - // -> check whether hours exist and decide on formatting - // create the final product and send to scheduler with the start_date if specified and days - unimplemented!() -} - -fn treatment_long_vote(ctx: poise::ApplicationContext<'_, Data, GenericError>, data: VoteCreation) { - // parse data - // create the final product and pass it along with the start_date if it's here and the begining and end dates - unimplemented!() -} - -// 1: user types command (vote_modal) -// 2: modal pops -// 3: data from the modal gets parsed -// 3.1 : group has to be matched with groups else error -// 3.2 : check whether or not there are hours and short names, and decide on the formatting depending on it -// 4: send final output to scheduler, with (if possible) context so it can reply instead of sending a new post -- 2.45.1 From 8860dee7e6ea76aca0a0103ac6fb38e45c8dca06 Mon Sep 17 00:00:00 2001 From: Vicky Date: Tue, 5 Nov 2024 12:29:54 +0100 Subject: [PATCH 3/9] Added more compatibilty with new structure --- src/io.rs | 96 ++++++++++++++++++++++++++++++++++++-------------- src/modules.rs | 6 ++++ 2 files changed, 75 insertions(+), 27 deletions(-) diff --git a/src/io.rs b/src/io.rs index 7b4b267..05456f0 100644 --- a/src/io.rs +++ b/src/io.rs @@ -19,6 +19,7 @@ //! } //! ``` //! +use crate::modules::handler; use poise::serenity_prelude::{self as serenity}; /// User data, which is stored and accessible in all command invocations @@ -37,10 +38,12 @@ pub struct VoteContainer { short_name: Option, start_date: Option, non_days: Option, - days: Option, - date_begin: Option, - date_end: Option, + days: String, + date_begin: String, + date_end: String, identifier: VoteTypeIdentifier, + // ctx: Context<'_>, + // Context needs a "lifetime" parameter, I have no idea what that is } /// Only title, description and identifier are mandatory @@ -66,9 +69,9 @@ impl Default for VoteContainer { short_name: None, start_date: None, non_days: None, - days: None, - date_begin: None, - date_end: None, + days: "".to_string(), + date_begin: "".to_string(), + date_end: "".to_string(), identifier: VoteTypeIdentifier::Uninitialised, } } @@ -88,6 +91,10 @@ pub enum VoteTypeIdentifier { #[allow(dead_code)] // fields only used for Debug print #[name = "Créer un nouveau Vote"] pub(crate) struct WeeklyVoteModal { + /// The title of the event + #[name = "Titre"] + #[placeholder = "Titre de votre événement"] + title: String, /// The description of the event #[paragraph] #[name = "Description"] @@ -105,10 +112,6 @@ pub(crate) struct WeeklyVoteModal { #[name = "Nom du jeu"] #[placeholder = "'FFXIV', 'MHW', 'D&D'..."] short_name: Option, - /// The title of the event - #[name = "Titre"] - #[placeholder = "Titre de votre événement"] - title: String, // Max fields is 5 so the two below will have to be command-exclusive // #[name = "Date de début du vote"] // #[placeholder = "'ven', '10', '21 jan', vide pour la prochaine période de votes"] @@ -122,11 +125,11 @@ pub(crate) struct WeeklyVoteModal { impl Default for WeeklyVoteModal { fn default() -> Self { WeeklyVoteModal { + title: "The base test vote".into(), description: "Dummy vote".into(), group: Some("Base group".into()), hours: Some("21h - 23".into()), short_name: Some("Base vote".into()), - title: "The base test vote".into(), } } } @@ -172,6 +175,8 @@ pub async fn vote_modal( ..Default::default() }; + handler(serotoninenjoyer); + // let reply = poise::CreateReply::default().content(format!( // "@{} **{}**\n{}\n{}, {}", // group, title, description, short_name, hours @@ -210,11 +215,25 @@ pub async fn vote_command( #[description = "Date de début du vote"] start_date: Option, #[description = "Jours non dispos"] non_days: Option, ) -> Result<(), GenericError> { - ctx.say(format!( - "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}", - title, short_name, group, description, hours, start_date, non_days - )) - .await?; + let rhubarb = VoteContainer { + title, + description, + // group, + hours, + short_name, + start_date, + non_days, + identifier: VoteTypeIdentifier::WeeklyVote, + ..Default::default() + }; + + handler(rhubarb); + + // ctx.say(format!( + // "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}", + // title, short_name, group, description, hours, start_date, non_days + // )) + // .await?; Ok(()) } @@ -234,11 +253,23 @@ pub async fn short_vote( #[description = "Jours"] days: String, #[description = "Date de début du vote"] start_date: Option, ) -> Result<(), GenericError> { - ctx.say(format!( - "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}", - title, group, description, hours, start_date, days - )) - .await?; + let aortavalve = VoteContainer { + title, + // group, + description, + hours, + days, + start_date, + ..Default::default() + }; + + handler(aortavalve); + + // ctx.say(format!( + // "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}", + // title, group, description, hours, start_date, days + // )) + // .await?; Ok(()) } @@ -257,18 +288,29 @@ pub async fn long_vote( #[description = "Date de début de la période de l'événement"] date_begin: String, #[description = "Date de fin de la période de l'événement"] date_end: String, ) -> Result<(), GenericError> { - ctx.say(format!( - "{:?} ; {:?} ; {:?} ; {:?} ; {:?}", - title, description, start_date, date_begin, date_end - )) - .await?; + let cartoy = VoteContainer { + title, + description, + start_date, + date_begin, + date_end, + ..Default::default() + }; + + handler(cartoy); + + // ctx.say(format!( + // "{:?} ; {:?} ; {:?} ; {:?} ; {:?}", + // title, description, start_date, date_begin, date_end + // )) + // .await?; Ok(()) } /// The main discord interaction loop /// /// Registers all functions and starts a bot client -// As an async loop it is untestable by nature, however thsi loop aims to stay as simple as possible to be "self testing" +// As an async loop it is untestable by nature, however this loop aims to stay as simple as possible to be "self testing" #[cfg(not(tarpaulin_include))] pub async fn discord_main_loop() { let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN"); diff --git a/src/modules.rs b/src/modules.rs index 979c55a..cce54b5 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -5,6 +5,8 @@ //! Many handler functions //! Every module encompassing a feature +use crate::io::VoteContainer; + struct LongVote { // todo } @@ -15,6 +17,10 @@ struct WeeklyVote { // todo } +pub fn handler(vc: VoteContainer) { + todo!() +} + #[cfg(test)] mod tests { // use super::*; -- 2.45.1 From 656a75b224a256431483ef603a8f2e216828c5c8 Mon Sep 17 00:00:00 2001 From: Vicky Date: Tue, 5 Nov 2024 15:10:20 +0100 Subject: [PATCH 4/9] added role finding logic to modal --- Cargo.toml | 1 + src/io.rs | 43 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e29711f..1b1cd11 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ simplelog = { version = "0.12.2", features = ["paris"] } log = { version = "0.4.22", features = ["std"] } nom = "7.1.3" criterion = "0.5" +distance = "0.4.0" [profile.dev] debug = 0 diff --git a/src/io.rs b/src/io.rs index 05456f0..92a3de0 100644 --- a/src/io.rs +++ b/src/io.rs @@ -20,6 +20,7 @@ //! ``` //! use crate::modules::handler; +use distance::levenshtein; use poise::serenity_prelude::{self as serenity}; /// User data, which is stored and accessible in all command invocations @@ -33,7 +34,7 @@ type Context<'a> = poise::Context<'a, Data, GenericError>; pub struct VoteContainer { title: String, description: String, - group: Option, + group: Option, hours: Option, short_name: Option, start_date: Option, @@ -157,7 +158,7 @@ pub async fn vote_modal( unwrapped_data.hours ); - log::info!("{:?}", ctx); + log::info!("{:?}", &ctx); // let group = unwrapped_data.group.unwrap_or("".into()); // let title = unwrapped_data.title; @@ -165,10 +166,27 @@ pub async fn vote_modal( // let short_name = unwrapped_data.short_name.unwrap_or("".into()); // let hours = unwrapped_data.hours.unwrap_or("".into()); + let saucisse = find_role_from_string( + unwrapped_data.group, + ctx.guild() + .unwrap() + .roles + .values() + .map(|v| v.name.clone()) + .collect(), + ) + .map(|find_role_from_string| { + ctx.guild() + .unwrap() + .role_by_name(&find_role_from_string) + .unwrap() + .id + }); + let serotoninenjoyer = VoteContainer { title: unwrapped_data.title, description: unwrapped_data.description, - group: unwrapped_data.group, + group: saucisse, hours: unwrapped_data.hours, short_name: unwrapped_data.short_name, identifier: VoteTypeIdentifier::WeeklyVote, @@ -187,6 +205,23 @@ pub async fn vote_modal( Ok(()) } +fn find_role_from_string(group: Option, roles: Vec) -> Option { + if group.is_none() || roles.is_empty() { + return None; + } + + let group = group.unwrap(); + let mut lowest: (Option, usize) = (None, group.len() + 5); + for role in roles { + let d = levenshtein(&role, &group); + if d < lowest.1 { + lowest = (Some(role), d); + }; + } + + lowest.0 +} + /// List of choices for all the roles. /// /// This enum is used to define a set of predefined choices that users can select from when creating a new vote. @@ -209,7 +244,7 @@ pub async fn vote_command( ctx: Context<'_>, #[description = "Titre"] title: String, #[description = "Nom du jeu"] short_name: Option, - #[description = "Groupe"] group: ListOfRoles, + #[description = "Groupe"] group: Option, #[description = "Description"] description: String, #[description = "Horaires"] hours: Option, #[description = "Date de début du vote"] start_date: Option, -- 2.45.1 From aa79b75b597ea1f83e840f2f9cdf8cea38839a0b Mon Sep 17 00:00:00 2001 From: Vicky Date: Tue, 5 Nov 2024 15:29:11 +0100 Subject: [PATCH 5/9] Added test for levenshtein distance --- src/io.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/io.rs b/src/io.rs index 92a3de0..5b33b4b 100644 --- a/src/io.rs +++ b/src/io.rs @@ -211,7 +211,8 @@ fn find_role_from_string(group: Option, roles: Vec) -> Option, usize) = (None, group.len() + 5); + // We are hard-coding the maximum value above which we prefer returning None rather than a guess + let mut lowest: (Option, usize) = (None, 5); for role in roles { let d = levenshtein(&role, &group); if d < lowest.1 { @@ -371,5 +372,28 @@ pub async fn discord_main_loop() { #[cfg(test)] mod tests { - // use super::*; + use super::*; + #[test] + fn test_levenshtein() { + let arguments: Vec = vec![ + "hunters", + "ffxiv_idle", + "ffxiv_progfish", + "ffxiv_minilvl", + "dbd", + "dnd", + "r6", + "apex", + "boardgames", + ] + .iter() + .map(|v| v.to_string()) + .collect(); + println!("{:?}", arguments); + println!( + "{:?}", + find_role_from_string(Some("bodyoncetoldme".to_string()), arguments.clone()) + ); + assert!(find_role_from_string(Some("bodyoncetoldme".to_string()), arguments).is_none()) + } } -- 2.45.1 From 5e27a178ce7d77d9173398594fc4bca1707442e5 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 5 Nov 2024 23:18:53 +0100 Subject: [PATCH 6/9] Updates the doc changes some string into &str and updates coverage --- badges/coverage.svg | 1 + badges/test.svg | 2 +- badges/version.svg | 1 + src/error_handling.rs | 12 +++ src/io.rs | 216 ++++++++++++++++++++++++++---------------- src/lib.rs | 1 + src/modules.rs | 11 +-- 7 files changed, 149 insertions(+), 95 deletions(-) create mode 100644 badges/coverage.svg create mode 100644 badges/version.svg diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..16d4a9f --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 96%test-coverage96% diff --git a/badges/test.svg b/badges/test.svg index a34aaf8..a7859aa 100644 --- a/badges/test.svg +++ b/badges/test.svg @@ -1 +1 @@ -build: passingbuildpassing +test: passingtestpassing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..c28c459 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1.0version0.1.0 diff --git a/src/error_handling.rs b/src/error_handling.rs index 9e4c343..44963c3 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -51,6 +51,18 @@ pub enum IdleError { /// It may indicate that the file reader is read-only, and manual intervention will be required to resolve the problem. #[error("An error occurred while initializing the logger: {0}")] LoggerInitFailure(#[from] SetLoggerError), + + /// Represents an error while acquiring a Discord group + /// + /// Raised when there is an error attempting to acquire the discord group + #[error("An error occured while tring to acquire the discord group: {0}")] + AcquiringDiscordGroup(String), + + /// Indicates an error while acquiring Discord guilds + /// + /// This may happen when a function was called outside of the context of a server (likely a DM to the bot). + #[error("An error occured while tring to acquire discord guilds")] + AcquiringDiscordGuild, } impl From>> for IdleError { diff --git a/src/io.rs b/src/io.rs index 5b33b4b..c568376 100644 --- a/src/io.rs +++ b/src/io.rs @@ -19,10 +19,15 @@ //! } //! ``` //! +#![allow(dead_code)] use crate::modules::handler; use distance::levenshtein; use poise::serenity_prelude::{self as serenity}; +use poise::Modal as _; + +use crate::error_handling::IdleError; + /// User data, which is stored and accessible in all command invocations pub struct Data {} /// A generic temporary serenity error @@ -30,21 +35,34 @@ type GenericError = Box; /// The context (in a discord sence) of a message type Context<'a> = poise::Context<'a, Data, GenericError>; +/// A `VoteContainer` holds the details of a vote that is to be created. +/// +/// This struct aggregates all the necessary data describing this event within a Discord guild (server). /// Generic object that is used to transfer vote data to other parts of the code. +#[derive(Default)] pub struct VoteContainer { + /// The title of the event title: String, + /// Description of the event description: String, + /// An optional serenity::RoleId to specify the role group concerned by the vote. group: Option, + /// Optional hours describing the specific date of the event hours: Option, + /// Short name, used in voting titles short_name: Option, + /// Auto-Start date of the event (in human-readable format) start_date: Option, - non_days: Option, - days: String, + /// Days not selected for the vote + non_days: Option, // TODO: What ? + /// Days selected for the vote + days: String, // TODO: What ? + /// Date the event begins date_begin: String, + /// Date the event ends date_end: String, + /// An identifier for the vote identifier: VoteTypeIdentifier, - // ctx: Context<'_>, - // Context needs a "lifetime" parameter, I have no idea what that is } /// Only title, description and identifier are mandatory @@ -59,29 +77,40 @@ impl VoteContainer { } } -/// Default is None -impl Default for VoteContainer { - fn default() -> Self { - Self { - title: "".to_string(), - description: "".to_string(), - group: None, - hours: None, - short_name: None, - start_date: None, - non_days: None, - days: "".to_string(), - date_begin: "".to_string(), - date_end: "".to_string(), - identifier: VoteTypeIdentifier::Uninitialised, - } - } -} +// /// Default is None +// impl Default for VoteContainer { +// fn default() -> Self { +// Self { +// title: "".to_string(), +// description: "".to_string(), +// group: None, +// hours: None, +// short_name: None, +// start_date: None, +// non_days: None, +// days: "".to_string(), +// date_begin: "".to_string(), +// date_end: "".to_string(), +// identifier: VoteTypeIdentifier::Uninitialised, +// } +// } +// } +/// Identifies the type of the vote being created. +/// +/// This enum represents different types of votes, such as regular weekly votes, +/// short-term votes, and long-term votes. It also serves as an indicator when a vote type +/// hasn't been initialized yet. +#[derive(Default)] pub enum VoteTypeIdentifier { + // Represents a recurring weekly vote, with the list of days voted upon being one week WeeklyVote, + /// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan. ShortVote, + /// Represents a long-term vote, where the list of days voted upon extends beyond a week. LongVote, + /// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value. + #[default] Uninitialised, } @@ -145,50 +174,46 @@ impl Default for WeeklyVoteModal { pub async fn vote_modal( ctx: poise::ApplicationContext<'_, Data, GenericError>, ) -> Result<(), GenericError> { - use poise::Modal as _; - let data = WeeklyVoteModal::execute(ctx).await?; - if let Some(unwrapped_data) = data { + if let Some(underlying_data) = data { log::info!( "@{:?} **{:?}**\n{:?}\n{:?}, {:?}", - unwrapped_data.group, - unwrapped_data.title, - unwrapped_data.description, - unwrapped_data.short_name, - unwrapped_data.hours + underlying_data.group, + underlying_data.title, + underlying_data.description, + underlying_data.short_name, + underlying_data.hours ); log::info!("{:?}", &ctx); - // let group = unwrapped_data.group.unwrap_or("".into()); - // let title = unwrapped_data.title; - // let description = unwrapped_data.description; - // let short_name = unwrapped_data.short_name.unwrap_or("".into()); - // let hours = unwrapped_data.hours.unwrap_or("".into()); - - let saucisse = find_role_from_string( - unwrapped_data.group, - ctx.guild() - .unwrap() - .roles - .values() - .map(|v| v.name.clone()) - .collect(), + // This whole shenennigan only exists to find a group as specified by text and if so apply it + // However many steps can subtly break and cannot be truly accounted for + let guild = ctx + .guild() + .ok_or_else(|| IdleError::AcquiringDiscordGuild)?; // Maybe the guild cannot be retrieved from the context, such as in a DM + let group = find_role_from_str( + underlying_data.group.as_deref(), + guild.roles.values().map(|v| v.name.as_str()).collect(), ) - .map(|find_role_from_string| { - ctx.guild() - .unwrap() - .role_by_name(&find_role_from_string) - .unwrap() - .id - }); + .ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exits or the match is too far or the group wasn't specified + .and_then(|role_found: String| { + guild + .role_by_name(&role_found) + .ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group canno't be acquired by that name + .map(|v| v.id) + }) + .inspect_err( + |e| /* Do something when an error occurs*/ log::error!("An error occured when selecting groups from {:?}: {}",&underlying_data.group,e), + ) // An inspect that could be used to signal something went wrong acquiring or applying the guild + .ok(); let serotoninenjoyer = VoteContainer { - title: unwrapped_data.title, - description: unwrapped_data.description, - group: saucisse, - hours: unwrapped_data.hours, - short_name: unwrapped_data.short_name, + title: underlying_data.title, + description: underlying_data.description, + group, + hours: underlying_data.hours, + short_name: underlying_data.short_name, identifier: VoteTypeIdentifier::WeeklyVote, ..Default::default() }; @@ -205,36 +230,46 @@ pub async fn vote_modal( Ok(()) } -fn find_role_from_string(group: Option, roles: Vec) -> Option { +/// Attempts to find the most closely matching role from a list based on a provided group name. +/// +/// This function takes a `group` string and a vector of role names, and returns the closest match found. +/// If the input `group` is None or the `roles` vector is empty, the function will return None. +/// The search uses the Levenshtein distance algorithm to determine the similarity between strings. +/// +/// # Arguments +/// +/// * `group` - An `Option` representing the target group name for which a match should be found. +/// * `roles` - A vector of `String`s containing role names to compare against the target group name. +fn find_role_from_str(group: Option<&str>, roles: Vec<&str>) -> Option { if group.is_none() || roles.is_empty() { return None; } let group = group.unwrap(); // We are hard-coding the maximum value above which we prefer returning None rather than a guess - let mut lowest: (Option, usize) = (None, 5); + let mut lowest = (None, 5); for role in roles { - let d = levenshtein(&role, &group); + let d = levenshtein(role, group); if d < lowest.1 { lowest = (Some(role), d); }; } - lowest.0 + lowest.0.map(|s| s.to_owned()) } -/// List of choices for all the roles. -/// -/// This enum is used to define a set of predefined choices that users can select from when creating a new vote. -/// Each choice represents a role within the guild, and it can be referred to using the enum variant name. -#[derive(Debug, poise::ChoiceParameter)] -pub enum ListOfRoles { - // TODO: This needs to be a list of all guildRoles under Users (included) - // TODO: This needs to be fetched dynamically from the server - /// placeholder for a role - #[name = "hunters"] - Hunters, -} +// /// List of choices for all the roles. +// /// +// /// This enum is used to define a set of predefined choices that users can select from when creating a new vote. +// /// Each choice represents a role within the guild, and it can be referred to using the enum variant name. +// #[derive(Debug, poise::ChoiceParameter)] +// pub enum ListOfRoles { +// // TODO: This needs to be a list of all guildRoles under Users (included) +// // TODO: This needs to be fetched dynamically from the server +// /// placeholder for a role +// #[name = "hunters"] +// Hunters, +// } /// Text command for extensive vote creation // Since this is a discord command and not a real rust command, this many arguments is "normal" @@ -283,7 +318,7 @@ pub async fn vote_command( pub async fn short_vote( ctx: Context<'_>, #[description = "Titre"] title: String, - #[description = "Groupe"] group: ListOfRoles, + #[description = "Groupe"] group: Option, #[description = "Description"] description: String, #[description = "Horaires"] hours: Option, #[description = "Jours"] days: String, @@ -291,7 +326,7 @@ pub async fn short_vote( ) -> Result<(), GenericError> { let aortavalve = VoteContainer { title, - // group, + group, description, hours, days, @@ -375,7 +410,7 @@ mod tests { use super::*; #[test] fn test_levenshtein() { - let arguments: Vec = vec![ + let arguments = [ "hunters", "ffxiv_idle", "ffxiv_progfish", @@ -385,15 +420,28 @@ mod tests { "r6", "apex", "boardgames", - ] - .iter() - .map(|v| v.to_string()) - .collect(); - println!("{:?}", arguments); - println!( - "{:?}", - find_role_from_string(Some("bodyoncetoldme".to_string()), arguments.clone()) + ]; + // println!("{:?}", arguments); + // println!( + // "{:?}", + // find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec()) + // ); + assert!(find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec()).is_none()); + assert_eq!( + find_role_from_str(Some("ffxivid"), arguments.to_vec()), + Some("ffxiv_idle".to_string()) + ); + assert_eq!( + find_role_from_str(Some("hunte"), arguments.to_vec()), + Some("hunters".to_string()) + ); + assert_eq!( + find_role_from_str(Some("dbd"), arguments.to_vec()), + Some("dbd".to_string()) + ); + assert_eq!( + find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()), + Some("ffxiv_progfish".to_string()) ); - assert!(find_role_from_string(Some("bodyoncetoldme".to_string()), arguments).is_none()) } } diff --git a/src/lib.rs b/src/lib.rs index f04cbe3..23910d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ //! //! The root module serves as a central entry point for users interested in using any part of the library. //! +#![warn(clippy::missing_docs_in_private_items)] pub mod config; // Maybe in lib pub mod date; // Definitely in lib diff --git a/src/modules.rs b/src/modules.rs index cce54b5..3f416ba 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -7,16 +7,7 @@ use crate::io::VoteContainer; -struct LongVote { - // todo -} -struct ShortVote { - // todo -} -struct WeeklyVote { - // todo -} - +/// Handles the vote ? pub fn handler(vc: VoteContainer) { todo!() } -- 2.45.1 From 0b7b1c49ad3f565cac5cdd653cb481b3c6dce7ab Mon Sep 17 00:00:00 2001 From: Vicky Date: Wed, 6 Nov 2024 12:34:37 +0100 Subject: [PATCH 7/9] Added skeleton for the handler, and made sure VoteContainer is as future-proof as can be --- src/io.rs | 47 ++++++++++++++--------------------------------- src/modules.rs | 23 +++++++++++++++++++++-- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/io.rs b/src/io.rs index c568376..283f6ad 100644 --- a/src/io.rs +++ b/src/io.rs @@ -42,25 +42,25 @@ type Context<'a> = poise::Context<'a, Data, GenericError>; #[derive(Default)] pub struct VoteContainer { /// The title of the event - title: String, + pub(crate) title: String, /// Description of the event - description: String, + pub(crate) description: String, /// An optional serenity::RoleId to specify the role group concerned by the vote. - group: Option, + pub(crate) group: Option, /// Optional hours describing the specific date of the event - hours: Option, + pub(crate) hours: Option, /// Short name, used in voting titles - short_name: Option, + pub(crate) short_name: Option, /// Auto-Start date of the event (in human-readable format) - start_date: Option, + pub(crate) start_date: Option, /// Days not selected for the vote - non_days: Option, // TODO: What ? + pub(crate) non_days: Option, /// Days selected for the vote - days: String, // TODO: What ? + pub(crate) days: Option, /// Date the event begins - date_begin: String, + pub(crate) date_begin: Option, /// Date the event ends - date_end: String, + pub(crate) date_end: Option, /// An identifier for the vote identifier: VoteTypeIdentifier, } @@ -77,25 +77,6 @@ impl VoteContainer { } } -// /// Default is None -// impl Default for VoteContainer { -// fn default() -> Self { -// Self { -// title: "".to_string(), -// description: "".to_string(), -// group: None, -// hours: None, -// short_name: None, -// start_date: None, -// non_days: None, -// days: "".to_string(), -// date_begin: "".to_string(), -// date_end: "".to_string(), -// identifier: VoteTypeIdentifier::Uninitialised, -// } -// } -// } - /// Identifies the type of the vote being created. /// /// This enum represents different types of votes, such as regular weekly votes, @@ -289,7 +270,7 @@ pub async fn vote_command( let rhubarb = VoteContainer { title, description, - // group, + group, hours, short_name, start_date, @@ -329,7 +310,7 @@ pub async fn short_vote( group, description, hours, - days, + days: Some(days), start_date, ..Default::default() }; @@ -363,8 +344,8 @@ pub async fn long_vote( title, description, start_date, - date_begin, - date_end, + date_begin: Some(date_begin), + date_end: Some(date_end), ..Default::default() }; diff --git a/src/modules.rs b/src/modules.rs index 3f416ba..987e41b 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -5,11 +5,30 @@ //! Many handler functions //! Every module encompassing a feature -use crate::io::VoteContainer; +use crate::{date::parse_date_list, io::VoteContainer}; /// Handles the vote ? pub fn handler(vc: VoteContainer) { - todo!() + let title = vc.title; + // should be left as is + let description = vc.description; + // should be left as is + let group = vc.group; + // should be left as is + let hours = vc.hours; + // needs to be parsed as start and end hours + let short_name = vc.short_name; + // can be left as is + let start_date = vc.start_date; + // needs to be parsed as single date or set to today's date if None + let non_days = vc.non_days; + // needs to be parsed as a list of days spanning one week after start_date + let days = vc.days; + // needs to be parsed as a list of days spanning one week after start_date + let date_begin = vc.date_begin; + // needs to be parsed as a single date + let date_end = vc.date_end; + // needs to be parsed as a single date } #[cfg(test)] -- 2.45.1 From 692ef6389aefd75a00da215084ca576655a7d6a6 Mon Sep 17 00:00:00 2001 From: Vicky Date: Thu, 7 Nov 2024 10:41:04 +0100 Subject: [PATCH 8/9] minor typo edits --- src/io.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/io.rs b/src/io.rs index 283f6ad..9b89066 100644 --- a/src/io.rs +++ b/src/io.rs @@ -177,11 +177,11 @@ pub async fn vote_modal( underlying_data.group.as_deref(), guild.roles.values().map(|v| v.name.as_str()).collect(), ) - .ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exits or the match is too far or the group wasn't specified + .ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exist or the match is too far or the group wasn't specified .and_then(|role_found: String| { guild .role_by_name(&role_found) - .ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group canno't be acquired by that name + .ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group cannot be acquired by that name .map(|v| v.id) }) .inspect_err( -- 2.45.1 From 15c463045570471ab38c850fd86a17180d44b107 Mon Sep 17 00:00:00 2001 From: Vicky Date: Thu, 7 Nov 2024 11:52:56 +0100 Subject: [PATCH 9/9] Added more on the handler --- src/io.rs | 2 +- src/modules.rs | 44 ++++++++++++++++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/io.rs b/src/io.rs index 9b89066..14efed9 100644 --- a/src/io.rs +++ b/src/io.rs @@ -62,7 +62,7 @@ pub struct VoteContainer { /// Date the event ends pub(crate) date_end: Option, /// An identifier for the vote - identifier: VoteTypeIdentifier, + pub(crate) identifier: VoteTypeIdentifier, } /// Only title, description and identifier are mandatory diff --git a/src/modules.rs b/src/modules.rs index 987e41b..9415cd0 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -5,9 +5,14 @@ //! Many handler functions //! Every module encompassing a feature -use crate::{date::parse_date_list, io::VoteContainer}; +use tokio::net::UnixListener; -/// Handles the vote ? +use crate::{ + date::{self, date_parse::DateObject}, + io::{VoteContainer, VoteTypeIdentifier}, +}; + +/// Handles generic VoteContainers, parses their data and feeds them into specific VoteObjects pub fn handler(vc: VoteContainer) { let title = vc.title; // should be left as is @@ -15,22 +20,45 @@ pub fn handler(vc: VoteContainer) { // should be left as is let group = vc.group; // should be left as is - let hours = vc.hours; + let mut hours = vc.hours; // needs to be parsed as start and end hours let short_name = vc.short_name; // can be left as is - let start_date = vc.start_date; + let mut start_date = vc.start_date; // needs to be parsed as single date or set to today's date if None - let non_days = vc.non_days; + let mut non_days = vc.non_days; // needs to be parsed as a list of days spanning one week after start_date - let days = vc.days; + let mut days = vc.days; // needs to be parsed as a list of days spanning one week after start_date - let date_begin = vc.date_begin; + let mut date_begin = vc.date_begin; // needs to be parsed as a single date - let date_end = vc.date_end; + let mut date_end = vc.date_end; // needs to be parsed as a single date + + match vc.identifier { + VoteTypeIdentifier::WeeklyVote => todo!(), + VoteTypeIdentifier::ShortVote => todo!(), + VoteTypeIdentifier::LongVote => todo!(), + VoteTypeIdentifier::Uninitialised => log::error!("Handler got an uninitialised vote."), + } } +/// Parent structure for every vote +struct VoteObject { + /// Title of the event to vote for + title: String, + /// Description of the event to vote for + description: String, + /// Date from which on the vote should be published + start_date: DateObject, + /// Date after which the vote should be closed + close_date: DateObject, + /// Date after which the vote should be deleted from memory + delete_date: DateObject, +} + +// TIL you can't do child structs on rust and now this pretty bit of code above is useless and I feel sad about it + #[cfg(test)] mod tests { // use super::*; -- 2.45.1