diff --git a/.gitignore b/.gitignore
index 9dd9bc9..4d3429a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@
# will have compiled files and executables
debug/
target/
+test/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
diff --git a/README.md b/README.md
index 5a86b23..5ce631a 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ IdleFox is a feature-rich Discord bot designed to streamline the process of find
- `votes.rs`: Manages event and vote data structures, enabling voting functionality within Discord servers.
- `persistence.rs`: Ensures data persistence and integrity between bot runs.
- `server.rs`: Provides server-related functionalities, such as displaying votes and closing ongoing votes.
-- `modules.rs`: Aggregates various voting logic functions into a single module for easier management and use within the application. This includes decision-making features beyond simple vote counting.
+- `modules.rs`: Aggregates various voting logic functions into a single module for easier management and use within the application. This includes decision-making features beyond simple vote counting.
- `error_handling.rs`: Handles error reporting and logging, ensuring that any issues encountered by the bot are appropriately recorded and reported.
A great emphasis is put on organizing the votes themselves, delaying posting them and editing the answers as time goes.
diff --git a/badges/coverage.svg b/badges/coverage.svg
index ead59f4..b1445c0 100644
--- a/badges/coverage.svg
+++ b/badges/coverage.svg
@@ -1 +1 @@
-
+
diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs
index eeff275..7636c04 100644
--- a/src/date/date_tools.rs
+++ b/src/date/date_tools.rs
@@ -148,8 +148,8 @@ pub enum NaiveDateObject {
/// This struct provides an abstraction over a list of date objects, enabling both sequential iteration
/// over the dates in order or direct access to any date by its index. The structure is designed to handle
/// different sources of date information, allowing for flexible data manipulation based on the provided dates.
-#[derive(Debug, Default, Serialize, Deserialize)]
-#[cfg_attr(test, derive(PartialEq, Clone))]
+#[derive(Debug, Default, Serialize, Deserialize, Clone)]
+#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct NaiveDateList {
/// The inner vector
inner: Vec,
diff --git a/src/error_handling.rs b/src/error_handling.rs
index df41160..0dc55ed 100644
--- a/src/error_handling.rs
+++ b/src/error_handling.rs
@@ -103,6 +103,15 @@ pub enum IdleError {
/// This error will happen when an incorrect string is sent to a command invocation
#[error("An error occured while trying to parse a Discord command")]
DiscordContainerParse,
+ /// Indicate a backup write couldn't be done, usually means the file descriptor is busy or permission are incorrect
+ #[error("An error occured while trying to write file {0}")]
+ BackupWriteError(std::io::Error),
+ /// Indicate a backup read couldn't be done, usually means the file descriptor is busy or permission are incorrect
+ #[error("An error occured while trying to read file {0}")]
+ BackupReadError(std::io::Error),
+ /// Indicate a value couldn't be serialized
+ #[error("An error occured while trying to serialize data {0}")]
+ SerdeError(serde_json::Error),
}
impl From>> for IdleError {
diff --git a/src/ids.rs b/src/ids.rs
index 4913eb8..9ed2f23 100644
--- a/src/ids.rs
+++ b/src/ids.rs
@@ -1,18 +1,46 @@
-//! Handle all Ids functionalities
+//! This module contains utilities for generating event ids.
//!
//! Features:
//! Generating a human readable ID for a HUID
//! Finding the HUID from an ID
//! Removing ID as needed
+use crate::votes::EventHolder;
+
/// Generic type representing an ID
pub type EventIdType = String;
/// Generate an id
+///
+/// # Examples
+///
+/// ```
+/// use idlefox::ids::generate_id;
+/// let id: String = generate_id();
+/// println!("Generated id: {}", id);
+/// ```
pub fn generate_id() -> String {
human_ids::generate(None)
}
+/// Generate a unique id, slower in timing but insure zero collision at runtime
+///
+/// # Examples
+///
+/// ```
+/// use idlefox::ids::generate_unique_id;
+/// # use idlefox::votes::EventHolder;
+/// let holder = EventHolder::default();
+/// let id: String = generate_unique_id(&holder);
+/// println!("Generated id: {}", id);
+pub fn generate_unique_id(holder: &EventHolder) -> String {
+ let id = generate_id();
+ match holder.contains_event(&id) {
+ true => generate_unique_id(holder),
+ false => id,
+ }
+}
+
#[cfg(test)]
mod test {
use super::generate_id;
diff --git a/src/io.rs b/src/io.rs
index b607dbe..0817149 100644
--- a/src/io.rs
+++ b/src/io.rs
@@ -26,7 +26,6 @@ use crate::modules::handler;
use crate::votes::EventHolder;
use distance::levenshtein;
use poise::serenity_prelude::{self as serenity};
-
use poise::Modal as _;
use crate::error_handling::IdleError;
@@ -92,7 +91,7 @@ pub enum VoteTypeIdentifier {
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.
+ /// 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]
diff --git a/src/persistence.rs b/src/persistence.rs
index 9604417..d278473 100644
--- a/src/persistence.rs
+++ b/src/persistence.rs
@@ -6,7 +6,105 @@
//!
//!
+use crate::IdleError;
+use serde::{de::DeserializeOwned, Serialize};
+use std::io::{Read, Write};
+
+/// Tries to load the list of pending events from disk or return a default (empty) list
+pub(crate) fn load_from_reader(rdr: Reader) -> Data
+where
+ Data: Default + DeserializeOwned,
+ Reader: Read + Sized,
+{
+ serde_json::from_reader(rdr).unwrap_or_default()
+}
+
+/// Load a struct into an Arc Mutex, mapping errors into BackupError
+///
+/// This macro is direct sugarcoating of the load_from_disk macro
+#[macro_export]
+macro_rules! load_from_reader {
+ ($r_type:ident, $path:expr) => {
+ Arc::new(std::sync::Mutex::new(load_from_reader::<$r_type, File>(
+ File::open($path).map_err(IdleError::BackupReadError)?,
+ )))
+ };
+}
+
+/// Tries to save the list to disk and return an error on failure
+pub(crate) fn save_to_writer(data: Data, mut writer: Writer) -> Result<(), IdleError>
+where
+ Data: Serialize,
+ Writer: Write + Sized,
+{
+ // let mut f = File::create(wrtr).map_err(IdleError::BackupError)?;
+ writer
+ .write(
+ serde_json::to_string_pretty(&data)
+ .map_err(IdleError::SerdeError)?
+ .as_bytes(),
+ )
+ .map_err(IdleError::BackupWriteError)?;
+ Ok(())
+}
+
+/// Save a struct behind an Arc Mutex into a file, mapping errors into BackupError
+///
+/// This macro is direct sugarcoating of the save_to_writer function
+///
+/// # Usage
+///
+/// save_it!()
+#[macro_export]
+macro_rules! save_to_writer {
+ ($value:expr, $r_type:ident, $path:expr) => {
+ save_to_writer::<&$r_type, File>(
+ &$value.lock().unwrap(),
+ File::create($path).map_err(IdleError::BackupWriteError)?,
+ )?;
+ };
+}
+
#[cfg(test)]
mod tests {
- // use super::*;
+ use super::*;
+ use crate::votes::{EventPending, ListOngoingEvents, ListPendingEvents};
+ use std::fs::{create_dir, remove_dir_all, File};
+ use std::io::BufWriter;
+ use std::sync::{Arc, Mutex};
+
+ #[test]
+ fn test_serialisation() {
+ let event_og = ListOngoingEvents::default();
+ let mut buffer = BufWriter::new(Vec::new());
+ let serialisation = save_to_writer(&event_og, &mut buffer);
+ assert!(serialisation.is_ok());
+ let deserialized_data: ListOngoingEvents = load_from_reader(buffer.buffer());
+ assert_eq!(event_og, deserialized_data);
+ }
+
+ #[test]
+ fn test_macro_caller() {
+ test_macros().unwrap()
+ }
+
+ fn test_macros() -> Result<(), IdleError> {
+ let event_og = Arc::new(Mutex::new(ListPendingEvents::default()));
+ {
+ let mut e = event_og.lock().unwrap();
+ println!(" Here {:?}", event_og);
+ for _ in 0..10 {
+ e.add_pending_event(EventPending::default())?;
+ }
+ }
+ let _ = remove_dir_all("test");
+ let _ = create_dir("test");
+ save_to_writer!(&event_og, ListPendingEvents, "test/testwrite.json");
+ let event_new = load_from_reader!(ListPendingEvents, "test/testwrite.json");
+ assert_eq!(
+ event_og.lock().unwrap().to_owned(),
+ event_new.lock().unwrap().to_owned()
+ );
+ Ok(())
+ }
}
diff --git a/src/server.rs b/src/server.rs
index c037574..11b3f4a 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -4,6 +4,10 @@
//! Show all votes (pending and happening)
//! Allow vote closing
//!
+// warp for creating the API
+// Tokio to run an asynchronous server
+// Serde to help serialize incoming JSON
+// parking_lot to create a ReadWriteLock for your local storage
#[cfg(test)]
mod tests {
diff --git a/src/votes/ballots.rs b/src/votes/ballots.rs
index 41b7980..ab1c599 100644
--- a/src/votes/ballots.rs
+++ b/src/votes/ballots.rs
@@ -10,8 +10,8 @@ use super::{BallotValueType, EventIdType, UserDataType};
/// A `Ballot` represents a user interaction towards an event. This struct is used to record the details of a vote,
/// including which user casted it, which event it pertains to, and what value or option was voted for.
-#[derive(Serialize, Deserialize, Debug)]
-#[cfg_attr(test, derive(Clone))]
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct Ballot {
/// The event the vote refers to
linked_event: EventIdType,
diff --git a/src/votes/events.rs b/src/votes/events.rs
index 9eddd6d..65034b7 100644
--- a/src/votes/events.rs
+++ b/src/votes/events.rs
@@ -27,8 +27,8 @@ use super::Ballot;
/// A pending event, waiting to be opened. In this state the even can be safely modified
/// and either manual input or the autostart date will start the vote.
-#[derive(Serialize, Deserialize, Default)]
-#[cfg_attr(test, derive(Clone))]
+#[derive(Serialize, Deserialize, Default, Clone)]
+#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub struct EventPending {
/// The parsed representation of the vote associated with this event.
/// It holds the details required for the voting process.
@@ -43,8 +43,8 @@ impl EventPending {
}
}
-#[derive(Serialize, Deserialize)]
-#[cfg_attr(test, derive(Clone))]
+#[derive(Serialize, Deserialize, Clone)]
+#[cfg_attr(test, derive(Debug, PartialEq))]
// An ongoing event, waiting to be closed thus allowing the ballots to be counted.
pub struct EventOngoing {
/// The parsed representation of the vote associated with this event.
@@ -66,8 +66,8 @@ impl EventOngoing {
}
}
-#[derive(Serialize, Deserialize)]
-#[cfg_attr(test, derive(Clone))]
+#[derive(Serialize, Deserialize, Clone)]
+// #[cfg_attr(test, derive(Clone))]
/// A closed event, while the users cannot interract with it in this state,
/// this event can still be reopened and it's results can be read.
/// All events have an expiry date and in this state the event will be cleaned
@@ -86,8 +86,8 @@ pub struct EventClosed {
/// This structure is specifically used within the application to encapsulate both
/// ongoing and planned voting events, providing a clear and organized way to manage their
/// data throughout their lifecycle.
-#[derive(Debug, Serialize, Deserialize, Default)]
-#[cfg_attr(test, derive(Clone))]
+#[derive(Debug, Serialize, Deserialize, Default, Clone)]
+#[cfg_attr(test, derive(Eq, PartialEq))]
pub(super) struct ParsedVote {
/// The title of the even
pub(super) title: String,
diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs
index 9153bd6..ffd962d 100644
--- a/src/votes/helper_functions.rs
+++ b/src/votes/helper_functions.rs
@@ -1,16 +1,20 @@
//! Submodule including all helper functions to handle vote creation and evolution
//!
-use std::sync::Arc;
-
+use crate::votes::traits::BorrowInner;
use chrono::NaiveDate;
-
-use crate::{ids::EventIdType, IdleError};
+use std::{fs::File, sync::Arc};
use super::{
events::{EventOngoing, EventPending},
- holders::ListClosedEvents,
+ holders::{ListClosedEvents, TypedEvent},
ListOngoingEvents, ListPendingEvents,
};
+use crate::{
+ ids::EventIdType,
+ load_from_reader,
+ persistence::{load_from_reader, save_to_writer},
+ save_to_writer, IdleError,
+};
/// Adds a parsed vote to the list of planned events.
///
@@ -206,3 +210,74 @@ pub struct EventHolder {
/// The newly created discord context
pub discord_ctx: Arc>>,
}
+
+/// Access the inner value by borrowing the inner wrapper
+///
+/// A macro is better than a trait and polymorphic code at this scale
+macro_rules! inner {
+ ($value:expr) => {
+ $value.lock().unwrap().borrow_inner()
+ };
+}
+
+impl EventHolder {
+ pub fn try_load_from_disk() -> Result {
+ Ok(Self {
+ pending_events: load_from_reader!(ListPendingEvents, "data/pending_events.json"),
+ ongoing_events: load_from_reader!(ListOngoingEvents, "data/ongoin_events.json"),
+ closed_events: load_from_reader!(ListClosedEvents, "data/closed_events.json"),
+ old_date: load_from_reader!(NaiveDate, "data/old_date.json"),
+ ..Default::default()
+ })
+ }
+
+ pub fn try_save_to_disk(holder: EventHolder) -> Result<(), IdleError> {
+ save_to_writer!(
+ holder.pending_events,
+ ListPendingEvents,
+ "data/pending_events.json"
+ );
+ save_to_writer!(
+ holder.ongoing_events,
+ ListOngoingEvents,
+ "data/ongoing_events.json"
+ );
+ save_to_writer!(
+ holder.closed_events,
+ ListClosedEvents,
+ "data/closed_events.json"
+ );
+ save_to_writer!(&holder.old_date, NaiveDate, "data/old_date.json");
+ Ok(())
+ }
+
+ /// Check wether the holder contains an event
+ ///
+ /// This is a low level plumbing tool, mostly used to check for collisions
+ pub(crate) fn contains_event(&self, id: &String) -> bool {
+ inner!(self.pending_events).contains_key(id)
+ || inner!(self.pending_events).contains_key(id)
+ || inner!(self.pending_events).contains_key(id)
+ }
+
+ /// Try to find an even by it's id, returns a TypedEvent to keep track of the location of the event
+ ///
+ /// Note that this function is useless right now as it clones the event making it very impractical
+ #[deprecated]
+ #[allow(dead_code)]
+ pub(crate) fn find_event(&self, id: &String) -> Option {
+ inner!(self.pending_events)
+ .get(id)
+ .map(|e| TypedEvent::Pending(e.clone()))
+ .or_else(|| {
+ inner!(self.ongoing_events)
+ .get(id)
+ .map(|e| TypedEvent::Ongoing(e.clone()))
+ })
+ .or_else(|| {
+ inner!(self.closed_events)
+ .get(id)
+ .map(|e| TypedEvent::Closed(e.clone()))
+ })
+ }
+}
diff --git a/src/votes/holders.rs b/src/votes/holders.rs
index 0ba236b..0059a62 100644
--- a/src/votes/holders.rs
+++ b/src/votes/holders.rs
@@ -11,6 +11,7 @@
//! The module aims to provide a robust framework for managing event lifecycles within an
//! application, ensuring separation between pending and ongoing events and supporting
//! actions such as adding, launching, processing, and autoclosing events.
+
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
@@ -27,29 +28,27 @@ use super::{
/// The list of pending events, not yet started
///
-/// This struct represents the collection of events that have been scheduled but have not yet begun.
+/// This struct represents the collection of events that have been scheduled but have not yet begun.
#[derive(Serialize, Deserialize, Default)]
+#[cfg_attr(test, derive(Debug, PartialEq, Clone))]
pub struct ListPendingEvents {
/// The list of pending events
- pending_events: PendingHashmap,
+ pub(super) pending_events: PendingHashmap,
}
impl ListPendingEvents {
/// Add a new event to the list of upcoming events.
///
/// This function generates a new HUID for the event before adding it to the list.
- pub(super) fn add_pending_event(
- &mut self,
- event: EventPending,
- ) -> Result {
+ pub fn add_pending_event(&mut self, event: EventPending) -> Result {
let id = generate_id();
self.pending_events.insert(id.clone(), event);
Ok(id)
}
- /// Process and activate all upcoming events if the auto-launch time has been reached.
+ /// Process and activate all upcoming events if the auto-launch time has been reached.
///
- /// Returns an `IdleError` if there's an issue launching any event or adding it to the ongoing list.
+ /// Returns an `IdleError` if there's an issue launching any event or adding it to the ongoing list.
pub fn process_upcoming(
&mut self,
current_time: NaiveDateTime,
@@ -99,15 +98,20 @@ impl ListPendingEvents {
}
// TODO: maybe add an update_upcoming(date) ?
+ // ///
+ // pub fn contains_event(&self, id: &str) -> bool {
+ // self.pending_events.contains_key(id)
+ // }
}
/// The list of ongoing events, not yet closed
///
/// This struct represents the collection of events that have been initiated but have not yet concluded.
-#[derive(Serialize, Deserialize, Default)]
+#[derive(Serialize, Deserialize, Default, Clone)]
+#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct ListOngoingEvents {
/// The list of ongoing events
- ongoing_events: OngoingHashmap,
+ pub(super) ongoing_events: OngoingHashmap,
}
impl ListOngoingEvents {
@@ -183,7 +187,6 @@ impl ListOngoingEvents {
.map(|(k, _)| k.clone())
.collect()
}
- // TODO: maybe add an update_ongoing(date) ?
}
/// The list of closed events
@@ -193,7 +196,7 @@ impl ListOngoingEvents {
#[derive(Serialize, Deserialize, Default)]
pub struct ListClosedEvents {
/// The list of closed events
- closed_events: ClosedHashmap,
+ pub(super) closed_events: ClosedHashmap,
}
impl ListClosedEvents {
@@ -234,6 +237,18 @@ impl ListClosedEvents {
}
}
+/// A generic event, holding an event and his type as variants,
+/// doing so is the easiest way to pass an event around outside of the event lists
+#[allow(dead_code)]
+pub enum TypedEvent {
+ /// Event that is ongoing.
+ Ongoing(EventOngoing),
+ /// Event that has yet to be resolved.
+ Pending(EventPending),
+ /// Event that has been resolved and is pending deletion.
+ Closed(EventClosed),
+}
+
#[cfg(test)]
mod tests {
use chrono::{Days, Local};
@@ -365,4 +380,10 @@ mod tests {
// TODO: Check the status at several points
}
+
+ #[ignore]
+ #[test]
+ fn serialisation_check() {
+ todo!()
+ }
}
diff --git a/src/votes/mod.rs b/src/votes/mod.rs
index 31f6954..f7408c1 100644
--- a/src/votes/mod.rs
+++ b/src/votes/mod.rs
@@ -19,6 +19,7 @@ mod ballots;
mod events;
mod helper_functions;
mod holders;
+mod traits;
// Republish
pub use ballots::Ballot;
diff --git a/src/votes/traits.rs b/src/votes/traits.rs
new file mode 100644
index 0000000..a2f3857
--- /dev/null
+++ b/src/votes/traits.rs
@@ -0,0 +1,63 @@
+//! Module holding all inner voting traits
+#![allow(dead_code)]
+
+use std::collections::HashMap;
+
+use super::{
+ holders::ListClosedEvents, EventClosed, EventOngoing, EventPending, ListOngoingEvents,
+ ListPendingEvents,
+};
+
+/// Signals that the object will let you borrow an inner dictionnary
+///
+/// Doing so will allow blanket implementations great for generic dictionnary handling
+pub(crate) trait BorrowInner {
+ /// Borrow the inner ongoing events
+ fn borrow_inner(&self) -> &HashMap;
+}
+
+impl BorrowInner for ListClosedEvents {
+ /// Borrow the inner ongoing events
+ fn borrow_inner(&self) -> &HashMap {
+ &self.closed_events
+ }
+}
+
+impl BorrowInner for ListOngoingEvents {
+ /// Borrow the inner ongoing events
+ fn borrow_inner(&self) -> &HashMap {
+ &self.ongoing_events
+ }
+}
+
+impl BorrowInner for ListPendingEvents {
+ /// Borrow the inner ongoing events
+ fn borrow_inner(&self) -> &HashMap {
+ &self.pending_events
+ }
+}
+
+/// Signals that the object will let you mutably borrow an inner dictionnary
+///
+/// Doing so will allow blanket implementations great for generic dictionnary handling
+pub(crate) trait BorrowMutInner {
+ /// Borrow the inner ongoing events
+ fn borrow_inner(&self) -> &HashMap;
+}
+
+/// Blanket inner dictionnary implementation
+///
+/// This trait is meant to allow for inner dictionnary manipulation
+pub(crate) trait EventManipulation {
+ /// get the inner value
+ fn get_attr(&self, s: &str) -> Option<&R>;
+}
+
+impl EventManipulation for T
+where
+ T: BorrowInner,
+{
+ fn get_attr(&self, s: &str) -> Option<&R> {
+ self.borrow_inner().get(s)
+ }
+}