mergedev #31

Merged
Dandaedre merged 10 commits from mergedev into dev 2024-11-07 21:21:47 +01:00
7 changed files with 326 additions and 57 deletions

View File

@ -21,6 +21,7 @@ criterion = "0.5"
serde_json = { version = "1.0.132", features = ["alloc"] }
postcard = { version = "1.0.10", features = ["alloc"] }
ron = "0.8.1"
distance = "0.4.0"
[profile.dev]
debug = 0

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="130" height="18" role="img" aria-label="test-coverage: 100%"><title>test-coverage: 100%</title><linearGradient id="bms-0d308125ce4bf4b9" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-0d308125ce4bf4b9"><rect width="130" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0d308125ce4bf4b9)"><rect width="87" height="18" fill="#555"/><rect x="87" width="43" height="18" fill="#97ca00"/><rect width="130" height="18" fill="url(#bms-0d308125ce4bf4b9)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1075" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="330">100%</text><text x="1075" y="130" transform="scale(.1)" fill="#fff" textLength="330">100%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 91%"><title>test-coverage: 91%</title><linearGradient id="bms-face6f22b39fe244" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-face6f22b39fe244"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-face6f22b39fe244)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-face6f22b39fe244)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">91%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">91%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -88,6 +88,18 @@ pub enum IdleError {
/// This is likely due to a thread being terminated but could also arise from a deadlock or a subtle race condition
#[error("An error happened while trying to acquire a mutex")]
MutexError,
/// 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<nom::Err<nom::error::Error<&str>>> for IdleError {

308
src/io.rs
View File

@ -19,7 +19,14 @@
//! }
//! ```
//!
use poise::serenity_prelude as serenity;
#![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 {}
@ -28,13 +35,77 @@ type GenericError = Box<dyn std::error::Error + Send + Sync>;
/// 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
pub(crate) title: String,
/// Description of the event
pub(crate) description: String,
/// An optional serenity::RoleId to specify the role group concerned by the vote.
pub(crate) group: Option<serenity::RoleId>,
/// Optional hours describing the specific date of the event
pub(crate) hours: Option<String>,
/// Short name, used in voting titles
pub(crate) short_name: Option<String>,
/// Auto-Start date of the event (in human-readable format)
pub(crate) start_date: Option<String>,
/// Days not selected for the vote
pub(crate) non_days: Option<String>,
/// Days selected for the vote
pub(crate) days: Option<String>,
/// Date the event begins
pub(crate) date_begin: Option<String>,
/// Date the event ends
pub(crate) date_end: Option<String>,
/// An identifier for the vote
pub(crate) 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()
}
}
}
/// 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,
}
/// 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"]
struct VoteCreation {
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"]
@ -52,10 +123,6 @@ struct VoteCreation {
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
/// 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"]
@ -66,14 +133,14 @@ struct VoteCreation {
}
#[cfg(test)] // This default implementation only exists during testing
impl Default for VoteCreation {
impl Default for WeeklyVoteModal {
fn default() -> Self {
VoteCreation {
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(),
}
}
}
@ -88,40 +155,100 @@ impl Default for VoteCreation {
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(underlying_data) = data {
log::info!(
"@{:?} **{:?}**\n{:?}\n{:?}, {:?}",
underlying_data.group,
underlying_data.title,
underlying_data.description,
underlying_data.short_name,
underlying_data.hours
);
let data = VoteCreation::execute(ctx).await?;
log::info!("Got data: {:?}", data);
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());
// 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(),
)
.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 cannot 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 reply = poise::CreateReply::default().content(format!(
"@{} **{}**\n{}\n{}, {}",
group, title, description, short_name, hours
));
ctx.send(reply).await?;
let serotoninenjoyer = VoteContainer {
title: underlying_data.title,
description: underlying_data.description,
group,
hours: underlying_data.hours,
short_name: underlying_data.short_name,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
handler(serotoninenjoyer);
// let reply = poise::CreateReply::default().content(format!(
// "@{} **{}**\n{}\n{}, {}",
// group, title, description, short_name, hours
// ));
// ctx.send(reply).await?;
};
Ok(())
}
/// List of choices for all the roles.
/// Attempts to find the most closely matching role from a list based on a provided group name.
///
/// 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,
/// 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<String>` 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<String> {
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 = (None, 5);
for role in roles {
let d = levenshtein(role, group);
if d < lowest.1 {
lowest = (Some(role), d);
};
}
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,
// }
/// Text command for extensive vote creation
// Since this is a discord command and not a real rust command, this many arguments is "normal"
#[allow(clippy::too_many_arguments)]
@ -131,17 +258,32 @@ pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Nom du jeu"] short_name: Option<String>,
#[description = "Groupe"] group: ListOfRoles,
#[description = "Groupe"] group: Option<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[description = "Date de début du vote"] start_date: Option<String>,
#[description = "Jours non dispos"] non_days: Option<String>,
) -> 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()
};
let _ = ctx;
handler(rhubarb);
// TODO: Log and check that the handle does handle everything
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, short_name, group, description, hours, start_date, non_days
// ))
// .await?;
Ok(())
}
@ -155,17 +297,29 @@ pub async fn vote_command(
pub async fn short_vote(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Groupe"] group: ListOfRoles,
#[description = "Groupe"] group: Option<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[description = "Jours"] days: String,
#[description = "Date de début du vote"] start_date: Option<String>,
) -> Result<(), GenericError> {
ctx.say(format!(
"{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
title, group, description, hours, start_date, days
))
.await?;
handler(VoteContainer {
title,
group,
description,
hours,
days: Some(days),
start_date,
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, group, description, hours, start_date, days
// ))
// .await?;
Ok(())
}
@ -184,18 +338,30 @@ 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?;
handler(VoteContainer {
title,
description,
start_date,
date_begin: Some(date_begin),
date_end: Some(date_end),
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// 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");
@ -221,5 +387,41 @@ pub async fn discord_main_loop() {
#[cfg(test)]
mod tests {
// use super::*;
use super::*;
#[test]
fn test_levenshtein() {
let arguments = [
"hunters",
"ffxiv_idle",
"ffxiv_progfish",
"ffxiv_minilvl",
"dbd",
"dnd",
"r6",
"apex",
"boardgames",
];
// 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())
);
}
}

View File

@ -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

View File

@ -5,6 +5,59 @@
//! Many handler functions
//! Every module encompassing a feature
use crate::{
date::date_parse::DateObject,
io::{VoteContainer, VoteTypeIdentifier},
};
/// Handles generic VoteContainers, parses their data and feeds them into specific VoteObjects
#[allow(unused_variables, unused_mut)]
pub fn handler(vote_container: VoteContainer) {
// Following should be left as is
let title = vote_container.title;
let description = vote_container.description;
let group = vote_container.group;
let mut hours = vote_container.hours;
let mut start_date = vote_container.start_date;
// TODO: Give vky the tools to parse dates and time
// Needs to be parsed as start and end hours
let short_name = vote_container.short_name;
// Needs to be parsed as single date or set to today's date if None
let mut non_days = vote_container.non_days;
// Needs to be parsed as a list of days spanning one week after start_date
let mut days = vote_container.days;
// Needs to be parsed as a list of days spanning one week after start_date
let mut date_begin = vote_container.date_begin;
// Needs to be parsed as a single date
let mut date_end = vote_container.date_end;
// Needs to be parsed as a single date
match vote_container.identifier {
VoteTypeIdentifier::WeeklyVote => todo!(),
VoteTypeIdentifier::ShortVote => todo!(),
VoteTypeIdentifier::LongVote => todo!(),
VoteTypeIdentifier::Uninitialised => log::error!("Handler got an uninitialised vote."),
}
}
/// Parent structure for every vote
#[allow(dead_code)]
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::*;

View File

@ -314,11 +314,11 @@ impl Display for ParsedVote {
}
}
// This split in two differents structs conceptually represents
// the fact that very differents actions will be performed for each struct
/// This split in two differents structs conceptually represents
/// the fact that very differents actions will be performed for each struct
type EventListType = HashMap<Uuid, ParsedVote>;
// The list of pending events, not yet started
/// The list of pending events, not yet started
///
/// This struct represents the collection of events that have been scheduled but have not yet begun.
#[derive(Serialize, Deserialize, Default)]