vote_rebased #1

Merged
Dandaedre merged 3 commits from vote_rebased into dev 2024-10-31 01:06:13 +01:00
10 changed files with 489 additions and 131 deletions

12
.gitignore vendored
View File

@ -14,8 +14,14 @@ Cargo.lock
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# Added by cargo
/target
# The discord token
.token
# The coverage report
tarpaulin-report.html
# The log files
*.log

View File

@ -7,6 +7,15 @@ edition = "2021"
poise = "0.6.1"
poise_macros = "0.6.1"
tokio = { version = "1.41.0", features = ["rt-multi-thread"] }
chrono = { version = "0.4.38", features = ["serde"] }
human_ids = "0.1.1"
once_cell = { version = "1.20.2", features = ["std"] }
serde = { version = "1.0.214", features = ["alloc", "derive"] }
thiserror = "1.0.65"
tracing = { version = "0.1.40", features = ["async-await", "std"] }
uuid = { version = "1.11.0", features = ["v4", "v7", "serde", "fast-rng"] }
simplelog = { version = "0.12.2", features = ["paris"] }
log = { version = "0.4.22", features = ["std"] }
[profile.dev]
debug = 0

15
TODO.md Normal file
View File

@ -0,0 +1,15 @@
# Test Driven
[ ] Config Load and persistance
[ ] Config recovery
[ ] Error testing framework
# Tasks
## Dan
[ ] Finish testing to reach 100% coverage
[ ] Implement Resilience & Recovery
## Vky
[ ] Write documentation for all functions in IO.rs
[ ] Replace the usage of print with the appropriate logging where needed
[ ] Create all module signature for queries

17
src/config.rs Normal file
View File

@ -0,0 +1,17 @@
//! Handles all config related functions
//!
//! Tries to load a config from .idlefox.toml
//! and creates a default version if it fails to do so
//!
//! Features:
//! Create, loads and saves config
//! Default config
//! Import old data from outdated configs
//! Recover from importing faulty data
//!
use serde::{Deserialize, Serialize};
/// The global config
#[derive(Serialize, Deserialize)]
pub(crate) struct GlobalConfig {}

109
src/date.rs Normal file
View File

@ -0,0 +1,109 @@
//! All parsing and logic associated to finding and parsing dates used in all commands
//!
//! Features:
//! Simple parsing logic: (dayname, daynumber, day month) with implicit month / year
//! Range finding: (date) - (date)
//! Comma separated dates: (date), (date)
//! Date utilities: Finding next monday etc...
#![allow(dead_code)]
use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday};
use crate::error_handling::IdleError;
// All structures
/// A punctual day (just one date)
pub struct DateEventPunctual {}
/// An interval
pub struct DateEventInterval {}
/// A date, wether punctual or interval
pub struct DateEventDate {}
/// A series of dates or intervals
pub struct DateEvent {}
// Define parser
// Defines date routines
/// Returns the date corresponding to the implicit Weekday
///
/// Aka the next day implied by the day given
/// If no context is given, the date is the same day next week from the current day
pub(crate) fn relative_day_to_date(day: Weekday, context: Option<NaiveDate>) -> NaiveDate {
let context = context.unwrap_or(Local::now().date_naive()) + Duration::weeks(1);
let offset = context.weekday() as i64 - day as i64;
context - Duration::days(offset)
}
/// A placeholder for a partial date, as a date with no year associated
#[derive(Debug)]
pub(crate) struct PartialDate {
/// The month implied in the date
month: Option<Month>,
/// The day of the month implied in the date
day: u32,
}
/// Finds the date corresponding to the loosely defined implicit partial date
///
/// If no context is given, the date will be inferred as the next valid date from now
pub(crate) fn relative_date_to_date(
date: PartialDate,
context: Option<NaiveDate>,
) -> Result<NaiveDate, IdleError> {
let context = context.unwrap_or(Local::now().date_naive());
// Change the base date depending on the context
match match date.month {
Some(m) if m.number_from_month() >= context.month() => context
.with_month(m.number_from_month())
.ok_or(IdleError::DateParsing),
Some(_m) => context
.checked_add_months(Months::new(12))
.ok_or(IdleError::DateParsing),
None if date.day >= context.day() => Ok(context),
None => context
.checked_add_months(Months::new(1))
.ok_or(IdleError::DateParsing),
} {
Ok(new_base) => new_base
.with_day(date.day)
.ok_or(IdleError::DateParsing(date)),
Err(_) => Err(IdleError::DateParsing(date)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_relatave_dates() {
let date = NaiveDate::from_ymd_opt(2024, 10, 30);
let date_next_mon = NaiveDate::from_ymd_opt(2024, 11, 4);
let date_next_tue = NaiveDate::from_ymd_opt(2024, 11, 7);
let date2 = NaiveDate::from_ymd_opt(2024, 12, 30);
let date2_next_sat = NaiveDate::from_ymd_opt(2025, 1, 11);
let date3 = NaiveDate::from_ymd_opt(2025, 1, 16);
let date3_next_sat = NaiveDate::from_ymd_opt(2025, 1, 26);
assert_eq!(
relative_day_to_date(Weekday::Mon, date),
date_next_mon.unwrap()
);
assert_eq!(
relative_day_to_date(Weekday::Thu, date),
date_next_tue.unwrap()
);
assert_eq!(
relative_day_to_date(Weekday::Sat, date2),
date2_next_sat.unwrap()
);
assert_eq!(
relative_day_to_date(Weekday::Sun, date3),
date3_next_sat.unwrap()
);
}
}

30
src/error_handling.rs Normal file
View File

@ -0,0 +1,30 @@
//! All error related structures and functions
//!
//!
#![allow(dead_code)]
use poise::serenity_prelude;
use thiserror::Error;
use crate::date::PartialDate;
// // Since the errors themselves are very verbose, this seemed like complete overkill
// #[allow(clippy::missing_docs_in_private_items)]
/// Global error struct for idlefox
#[derive(Error, Debug)]
pub enum IdleError {
/// Error republished when encountering an unrecoverable state in the API
#[error("An unrecoverable error occured while interfacing with the Discord API")]
GenericDiscordAPI,
/// Error sent when a date given by the user doesn't make sense (aka dec 32, feb 30 etc)
#[error("An error happened while tring to make sense of the date {0:?}")]
DateParsing(PartialDate),
/// A generic error when handling discord API calls
#[error("An error occured while processing a Discord API call")]
SerenityAPI(#[from] serenity_prelude::Error),
}
#[cfg(test)]
mod tests {
// use super::*;
}

8
src/ids.rs Normal file
View File

@ -0,0 +1,8 @@
//! Handle all Ids functionalities
//!
//! Features:
//! Generating a human readable ID for a UUID
//! Finding the UUID from an ID
//! Removing ID as needed
// use human_ids::generate;

141
src/io.rs
View File

@ -4,6 +4,147 @@
//! All recv and send functions to discord
//! Helper function for advanced checks
use poise::serenity_prelude as serenity;
/// User data, which is stored and accessible in all command invocations
pub struct Data {}
/// A generic temporary serenity error
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>;
// // Displays your or another user's account creation date
// // Dummy command from poise documentation
// #[poise::command(slash_command, prefix_command)]
// async fn how_old(
// ctx: Context<'_>,
// #[description = "Selected user"] user: Option<serenity::User>,
// ) -> Result<(), Error> {
// let u = user.as_ref().unwrap_or_else(|| ctx.author());
// let response = format!("{}'s account was created at {}", u.name, u.created_at());
// ctx.say(response).await?;
// Ok(())
// }
/// The result of a vote creation
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
struct VoteCreation {
/// The title of the event
#[name = "Titre"]
#[placeholder = "Titre de votre événement"]
title: String,
/// The name of the event
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
/// The group that shall be tagged by the bot
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
/// The description of the event
#[paragraph]
#[name = "Description"]
#[placeholder = "petite description de votre événement"]
description: String,
/// The time a which the event shall take place
#[name = "Horaires"]
#[placeholder = "'21h - 23h' par défaut"]
hours: Option<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"]
// start_date: Option<String>,
// #[name = "Jours non dispos"]
// #[placeholder = "'lun', '30', '2 dec'"]
// non_days: Option<String>,
}
#[poise::command(slash_command)]
pub async fn vote_modal(
ctx: poise::ApplicationContext<'_, Data, GenericError>,
) -> Result<(), GenericError> {
use poise::Modal as _;
let data = VoteCreation::execute(ctx).await?;
println!("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());
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
#[derive(Debug, poise::ChoiceParameter)]
pub enum ListOfRoles {
// TODO: This needs to be a list of all guildRoles under Users (included)
#[name = "hunters"]
Hunters,
}
// Since this is a discord command and not a real rust command, this many arguments is "normal"
#[allow(clippy::too_many_arguments)]
#[poise::command(prefix_command, slash_command)]
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Nom du jeu"] short_name: Option<String>,
#[description = "Groupe"] group: ListOfRoles,
#[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?;
Ok(())
}
/// TODO: Fill doc
#[poise::command(prefix_command, slash_command)]
pub async fn component_modal(ctx: Context<'_>) -> Result<(), GenericError> {
let reply = {
let components = vec![serenity::CreateActionRow::Buttons(vec![
serenity::CreateButton::new("open_modal")
.label("Open modal")
.style(poise::serenity_prelude::ButtonStyle::Success),
])];
poise::CreateReply::default()
.content("Click the button below to open the modal")
.components(components)
};
ctx.send(reply).await?;
while let Some(mci) = serenity::ComponentInteractionCollector::new(ctx.serenity_context())
.timeout(std::time::Duration::from_secs(120))
.filter(move |mci| mci.data.custom_id == "open_modal")
.await
{
let data =
poise::execute_modal_on_component_interaction::<VoteCreation>(ctx, mci, None, None)
.await?;
println!("Got data: {:?}", data);
}
Ok(())
}
#[cfg(test)]
mod tests {
// use super::*;

View File

@ -5,6 +5,16 @@
// This line is here to force the use of extensive documentation
#![warn(clippy::missing_docs_in_private_items)]
use io::{component_modal, vote_command, vote_modal, Data};
use log::LevelFilter;
use simplelog::{
debug, error, info, ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger,
};
mod config;
mod date;
mod error_handling;
mod ids;
mod io;
mod modules;
mod persistence;
@ -13,137 +23,37 @@ mod votes;
mod watchdog;
use poise::serenity_prelude as serenity;
// use poise::{serenity_prelude as serenity, CreateReply};
struct Data {} // User data, which is stored and accessible in all command invocations
type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>;
// // Displays your or another user's account creation date
// // Dummy command from poise documentation
// #[poise::command(slash_command, prefix_command)]
// async fn how_old(
// ctx: Context<'_>,
// #[description = "Selected user"] user: Option<serenity::User>,
// ) -> Result<(), Error> {
// let u = user.as_ref().unwrap_or_else(|| ctx.author());
// let response = format!("{}'s account was created at {}", u.name, u.created_at());
// ctx.say(response).await?;
// Ok(())
// }
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
struct VoteCreation {
#[name = "Titre"]
#[placeholder = "Titre de votre événement"]
title: String,
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
#[paragraph]
#[name = "Description"]
#[placeholder = "petite description de votre événement"]
description: String,
#[name = "Horaires"]
#[placeholder = "'21h - 23h' par défaut"]
hours: Option<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"]
// start_date: Option<String>,
// #[name = "Jours non dispos"]
// #[placeholder = "'lun', '30', '2 dec'"]
// non_days: Option<String>,
}
// vote_modal
#[poise::command(slash_command)]
pub async fn vote_modal(ctx: poise::ApplicationContext<'_, Data, Error>) -> Result<(), Error> {
use poise::Modal as _;
let data = VoteCreation::execute(ctx).await?;
println!("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());
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
#[derive(Debug, poise::ChoiceParameter)]
pub enum ListOfRoles {
// This needs to be a list of all guildRoles under Users (included)
#[name = "hunters"]
Hunters,
}
// vote_command
#[poise::command(prefix_command, slash_command)]
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Nom du jeu"] short_name: Option<String>,
#[description = "Groupe"] group: ListOfRoles,
#[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<(), Error> {
ctx.say(format!(
"{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
title, short_name, group, description, hours, start_date, non_days
))
.await?;
Ok(())
}
#[poise::command(prefix_command, slash_command)]
pub async fn component_modal(ctx: crate::Context<'_>) -> Result<(), Error> {
let reply = {
let components = vec![serenity::CreateActionRow::Buttons(vec![
serenity::CreateButton::new("open_modal")
.label("Open modal")
.style(poise::serenity_prelude::ButtonStyle::Success),
])];
poise::CreateReply::default()
.content("Click the button below to open the modal")
.components(components)
};
ctx.send(reply).await?;
while let Some(mci) = serenity::ComponentInteractionCollector::new(ctx.serenity_context())
.timeout(std::time::Duration::from_secs(120))
.filter(move |mci| mci.data.custom_id == "open_modal")
.await
{
let data =
poise::execute_modal_on_component_interaction::<VoteCreation>(ctx, mci, None, None)
.await?;
println!("Got data: {:?}", data);
}
Ok(())
}
use std::fs::File;
#[cfg(not(tarpaulin_include))]
#[tokio::main]
async fn main() {
CombinedLogger::init(vec![
TermLogger::new(
LevelFilter::Warn,
Config::default(),
TerminalMode::Mixed,
ColorChoice::Auto,
),
WriteLogger::new(
LevelFilter::Info,
Config::default(),
// TODO: Maybe add la date du jour de lancement ?
File::create("idlefox.log").unwrap(),
),
])
.unwrap();
error!("Bright red error");
info!("This only appears in the log file");
debug!("This level is currently not enabled for any logger");
// use human_ids::generate;
// use std::{env, time::Instant};
// let tk = env::var("DISCORD_TOKEN");
// let id = generate(None);
// println!("Token: {:?} Id: {}", tk, id);
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents = serenity::GatewayIntents::non_privileged();
let framework = poise::Framework::builder()

View File

@ -7,6 +7,119 @@
//! ListCurrentEvents (struct)
//! ListFutureEvents (struct)
//!
#![allow(dead_code)]
use std::{collections::HashMap, sync::LazyLock};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
/// Placeholder datatype
///
/// Links to an event, active or planned
type EventDataType = Uuid;
/// Placeholder user data type
///
/// Links back to an user
#[deprecated(note = "This is an incorrect type to define an user")]
type UserDataType = String;
/// What an user voted for
#[deprecated(note = "This is an incorrect type to define a vote")]
type VoteValueType = String;
/// A vote, represents a user interraction towards an event
#[derive(Serialize, Deserialize)]
pub(crate) struct Vote {
/// The event the vote refers to
linked_event: EventDataType,
/// The user casting the vote
user_handle: UserDataType,
/// What the user voted for
vote_value: VoteValueType,
}
/// Data type representing a date
type DateDataType = String;
/// The global status of the event
#[derive(Serialize, Deserialize)]
pub(crate) enum EventStatus {
/// The event exists but wasn't started yet
Pending,
/// The event was started but the finish date wasn't reached yet
Started,
/// The event was started and the date finish date was reached without being closed
Finished,
/// The event was closed and the outcome was made public
Closed,
/// The event was cancelled
Cancelled,
}
/// An event, wether ongoing or planned
#[derive(Serialize, Deserialize)]
pub(crate) struct Event {
/// The title of the even
title: String,
/// Description of the event
description: String,
/// The global status of the vote
status: EventStatus,
/// Date at which to autostart the vote process
launch_date: Option<DateDataType>,
/// Date at which to autoclose the vote process
close_date: Option<DateDataType>,
/// The inner list of votes cast
votes: Vec<Vote>,
/// The list of values to vote for, this list all the valid dates to vote for
vote_values: Vec<DateDataType>,
}
// This split in two differents structs conceptually represents
// the fact that very differents actions will be performed for each struct
type EventListType = HashMap<Uuid, Event>;
/// The list of pending events, not yet started
#[derive(Serialize, Deserialize)]
pub(crate) struct PendingEvents {
/// The list of pending events
pending_events: EventListType,
}
impl PendingEvents {
/// Create a new empty list of events, called in case of a first initialization
///
/// However a deserialization will always be performed if possible
fn new() -> Self {
Self {
pending_events: EventListType::new(),
}
}
}
/// The list of ongoing events, not yet closed
#[derive(Serialize, Deserialize)]
pub(crate) struct OngoingEvents {
/// The list of ongoing events
ongoing_events: EventListType,
}
impl OngoingEvents {
/// Create a new empty list of ongoing events, called in case of a first initialization
///
/// However a deserialisation will always be performed if possible
fn new() -> Self {
Self {
ongoing_events: EventListType::new(),
}
}
}
/// The thread safe list of pending events
static CURRENT_EVENTS: LazyLock<PendingEvents> = LazyLock::new(PendingEvents::new);
/// The thread safe list of ongoing events
static PENDING_EVENTS: LazyLock<OngoingEvents> = LazyLock::new(OngoingEvents::new);
#[cfg(test)]
mod tests {