Compare commits

..

2 Commits

Author SHA1 Message Date
Vicky d49f818637 Added barebones reactions proof of concept. 2025-01-15 17:06:54 +01:00
Dandaedre cafc860b6f Examples mostly 2024-11-30 00:43:26 +01:00
22 changed files with 236 additions and 1263 deletions

4
.gitignore vendored
View File

@ -3,8 +3,6 @@
# will have compiled files and executables
debug/
target/
test/
bobito/
# 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
@ -30,5 +28,3 @@ tarpaulin-report.html
# A module summary
summary.md
config.json

View File

@ -3,18 +3,26 @@ name = "idlefox"
version = "0.1.0"
edition = "2021"
[features]
custom_emojis = []
[dependencies]
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"] }
nom = "7.1.3"
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"

326
Jenkinsfile vendored
View File

@ -1,326 +0,0 @@
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
pipeline {
agent { label 'rust_no_docker' }
environment {
CARGO_TERM_COLOR = 'always'
RUST_BACKTRACE = '1'
// CI gets its own Cargo home. This prevents ~/.cargo/config*
// from injecting host-specific linker options.
CARGO_HOME = "${WORKSPACE}/.ci-cargo-home"
// Keep CI artifacts separate from local/project builds.
CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"
// Explicitly use the native FreeBSD compiler/linker.
CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER = 'cc'
// Explicitly neutralize environment-provided Rust flags.
RUSTFLAGS = ''
CARGO_ENCODED_RUSTFLAGS = ''
}
stages {
stage('Checkout') {
steps {
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
echo "Ensuring stable Rust is available..."
rustup toolchain install stable \
--profile minimal \
--component rustfmt \
--component clippy
rustup default stable
# ---------------------------------------------------------
# Prepare isolated Cargo environment
# ---------------------------------------------------------
rm -rf "${CARGO_HOME}"
mkdir -p "${CARGO_HOME}"
rm -rf "${CARGO_TARGET_DIR}"
mkdir -p "${CARGO_TARGET_DIR}"
# Cargo discovers .cargo/config* by walking upward from the
# current working directory. We therefore invoke Cargo from
# a neutral directory outside the repository.
CI_RUN_DIR="/tmp/idlefox-ci-${BUILD_NUMBER}"
rm -rf "${CI_RUN_DIR}"
mkdir -p "${CI_RUN_DIR}"
echo "${CI_RUN_DIR}" > .ci-run-dir
# ---------------------------------------------------------
# Information
# ---------------------------------------------------------
echo
echo "Rust:"
rustc --version
echo
echo "Cargo:"
cargo --version
echo
echo "rustfmt:"
rustfmt --version
echo
echo "Clippy:"
cargo clippy --version
echo
echo "Compiler:"
cc --version
echo
echo "Rust target:"
rustc -vV
echo
echo "Cargo home:"
echo "${CARGO_HOME}"
echo
echo "Cargo target directory:"
echo "${CARGO_TARGET_DIR}"
echo
echo "Neutral Cargo working directory:"
cat .ci-run-dir
echo
echo "Repository Cargo configuration files:"
find "${WORKSPACE}" \
-path '*/.cargo/config' \
-o \
-path '*/.cargo/config.toml' \
2>/dev/null || true
echo
echo "Any mold references in repository Cargo configuration:"
if [ -d "${WORKSPACE}/.cargo" ]; then
grep -Rni 'mold' "${WORKSPACE}/.cargo" || true
fi
echo
echo "CI linker:"
echo "${CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER}"
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking Rust formatting..."
cargo fmt \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all \
-- \
--check
'''
}
}
stage('Check') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking all IdleFox targets..."
cargo check \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Test') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Running IdleFox tests..."
cargo test \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Running Clippy..."
cargo clippy \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Check Benchmarks') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking benchmark compilation..."
cargo check \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--benches \
--all-features
'''
}
}
stage('Build Release') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Building IdleFox release..."
cargo build \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--release \
--all-features
echo
echo "Release build completed."
BINARY="${CARGO_TARGET_DIR}/release/idlefox"
if [ ! -f "${BINARY}" ]; then
echo "ERROR: expected release binary was not produced:"
echo "${BINARY}"
exit 1
fi
echo
echo "Release binary:"
ls -lh "${BINARY}"
echo
echo "Binary type:"
file "${BINARY}" || true
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'Rust CI',
summary: 'IdleFox passed all CI checks.',
text: 'Formatting, compilation checks, tests, Clippy, benchmark compilation, and release build completed successfully using the native FreeBSD linker.',
title: 'Build Successful'
)
echo '✅ IdleFox passed all CI checks.'
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'Rust CI',
summary: 'IdleFox failed CI.',
text: 'Formatting, compilation, tests, Clippy, benchmarks, or the release build failed. Check the Jenkins log.',
title: 'Build Failed'
)
echo '❌ IdleFox CI failed.'
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'Rust CI',
summary: 'IdleFox CI is unstable.',
text: 'The Jenkins build completed with an unstable status.',
title: 'Build Unstable'
)
echo '⚠️ IdleFox CI is unstable.'
}
always {
sh '''
echo "Cleaning IdleFox CI environment..."
if [ -f .ci-run-dir ]; then
CI_RUN_DIR="$(cat .ci-run-dir)"
rm -rf "${CI_RUN_DIR}"
fi
rm -f .ci-run-dir
rm -rf .ci-cargo-home
# Keep target-ci for now so Jenkins retains incremental
# compilation between builds. Uncomment to make every build
# completely clean:
#
# rm -rf target-ci
'''
}
}
}

View File

@ -1 +1 @@
<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: 88%"><title>test-coverage: 88%</title><linearGradient id="bms-7f01f1ef66d48313" 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-7f01f1ef66d48313"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-7f01f1ef66d48313)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-7f01f1ef66d48313)"/></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">88%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">88%</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: 84%"><title>test-coverage: 84%</title><linearGradient id="bms-c15e65abae712a1a" 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-c15e65abae712a1a"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-c15e65abae712a1a)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-c15e65abae712a1a)"/></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">84%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">84%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -2,12 +2,12 @@
//!
//! This module provides a centralized configuration system for IdleFox, allowing you to load and manage your settings in an efficient and flexible manner.
//!
//! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `config.json` file.
//! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `.idlefox.toml` file.
//! If the file does not exist or cannot be loaded, it will automatically create a default version for you.
//!
//! ### Key Features
//!
//! * **Config Loading**: Seamlessly load your existing config from the `config.json` file, ensuring that all settings are preserved and up-to-date.
//! * **Config Loading**: Seamlessly load your existing config from the `.idlefox.toml` file, ensuring that all settings are preserved and up-to-date.
//! * **Default Config Creation**: Automatically generate a default configuration if the specified file cannot be loaded or is missing.
//! * **Legacy Data Import**: Safely import old data from outdated configurations to minimize disruptions during upgrades.
//! * **Faulty Data Recovery**: Implement measures to recover from importing faulty data, ensuring that your IdleFox instance remains stable and functional.
@ -32,131 +32,18 @@
//! # }
//!
#![allow(clippy::all)]
use crate::IdleError;
use std::{fs::File, io::Write};
use std::fs::File;
use log::LevelFilter;
use poise::serenity_prelude::{EmojiId, ReactionType};
use serde::{Deserialize, Serialize};
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};
pub type WeeklyReactionList = Vec<ReactionType>;
use crate::error_handling::IdleError;
/// A structure representing the global configuration for a Discord bot.
///
/// This struct contains various settings and parameters that influence how the bot
/// operates, such as which type of reaction is selected to indicate different days
/// in a weekly schedule, and custom emotes or Unicode characters used for reactions.
/// The global config
/// TODO: Update this doc as the config module is done
#[derive(Serialize, Deserialize)]
pub struct GlobalConfig {
/// The type of reaction selected by the user. Either the default unicode emote or a custom set of emotes.
selected_reaction: SelectedReaction,
/// The list of 7 weekly emotes to use as reaction to indicate the weekly days.
custom_weekly_emotes: WeeklyReactionList,
/// The list of 7 weekly unicode emotes to use as reaction to indicate the weekly days.
custom_weekly_unicode: WeeklyReactionList,
}
impl Default for GlobalConfig {
fn default() -> Self {
GlobalConfig {
selected_reaction: SelectedReaction::Emotes,
custom_weekly_emotes: Self::emotes(),
custom_weekly_unicode: Self::unicode(),
}
}
}
impl GlobalConfig {
/// Try to load the config from disk and return a default config if none is found
pub fn try_load_from_disk() -> Result<GlobalConfig, IdleError> {
// let f = File::open("config.json").map_err(IdleError::LoadingConfig)?;
if let Ok(f) = File::open("config.json") {
Ok(serde_json::from_reader(f).map_err(IdleError::SerdeError)?)
} else {
Ok(GlobalConfig::default())
}
}
/// Try to save the config to disk
// Testing a bad serialisation is pointless
#[cfg(not(tarpaulin_include))]
pub fn try_save_to_disk(&self) -> Result<(), IdleError> {
let mut f = File::create("config.json").map_err(IdleError::SavingConfig)?;
f.write_all(
serde_json::to_string_pretty(&self)
.map_err(IdleError::SerdeError)?
.as_bytes(),
)
.map_err(IdleError::SavingConfig)?;
Ok(())
}
/// Generate the custom emote variant of the reactions
#[cfg(not(tarpaulin_include))]
fn emotes() -> WeeklyReactionList {
vec![
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486629961859154),
name: Some("Lu".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486631182405642),
name: Some("Ma".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486632352612424),
name: Some("Me".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486628409835642),
name: Some("Je".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486635087302737),
name: Some("Ve".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486633271169107),
name: Some("Sa".to_string()),
},
ReactionType::Custom {
animated: false,
id: EmojiId::new(1329486626023276604),
name: Some("Di".to_string()),
},
]
}
/// Generate the unicode variant of the reactions
fn unicode() -> WeeklyReactionList {
vec![
ReactionType::Unicode("1️⃣".to_string()),
ReactionType::Unicode("2️⃣".to_string()),
ReactionType::Unicode("3️⃣".to_string()),
ReactionType::Unicode("4️⃣".to_string()),
ReactionType::Unicode("5️⃣".to_string()),
ReactionType::Unicode("6️⃣".to_string()),
ReactionType::Unicode("7️⃣".to_string()),
]
}
}
/// The type of reaction to use
#[derive(Serialize, Deserialize)]
enum SelectedReaction {
/// Use the custom emotes provided
Emotes,
/// Use the default unicode one
Unicode,
}
pub(crate) struct GlobalConfig {}
/// Initializes a logger for logging purposes.
///
@ -193,42 +80,3 @@ pub fn init_logger() -> Result<(), IdleError> {
])
.map_err(IdleError::LoggerInitFailure)
}
#[cfg(test)]
mod tests {
use std::fs;
use poise::serenity_prelude::ReactionType;
use super::GlobalConfig;
#[test]
fn test_default_cfg() {
let d = GlobalConfig::default();
assert!(d.custom_weekly_emotes.len() >= 7);
assert!(d.custom_weekly_unicode.len() >= 7);
for e in d.custom_weekly_emotes {
if let ReactionType::Custom {
animated,
id: _,
name,
} = e
{
assert_eq!(animated, false);
assert!(name.is_some());
}
}
}
#[test]
fn test_save_cfg() {
let c = GlobalConfig::default();
let try_save_to_disk = c.try_save_to_disk();
assert!(try_save_to_disk.is_ok());
}
#[test]
fn test_load_cfg() {
let _ = fs::remove_file("config.json");
let try_load_from_disk = GlobalConfig::try_load_from_disk();
assert!(try_load_from_disk.is_ok());
}
}

View File

@ -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, Clone)]
#[cfg_attr(test, derive(PartialEq, Eq))]
#[derive(Debug, Default, Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq, Clone))]
pub struct NaiveDateList {
/// The inner vector
inner: Vec<NaiveDateObject>,
@ -327,7 +327,7 @@ pub fn parse_single_date(input: &str, context: Option<NaiveDate>) -> Result<Naiv
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
use crate::date::date_parse::DateRange;
@ -500,20 +500,4 @@ mod tests {
// Simple roundtrip assertion
assert_eq!(list, ron::from_str(&s).unwrap());
}
#[test]
fn test_parse_single() {
let cx = NaiveDate::from_ymd_opt(2023, 2, 12);
let tv = vec![
("ven", cx, NaiveDate::from_ymd_opt(2023, 2, 17).unwrap()),
("11", cx, NaiveDate::from_ymd_opt(2023, 3, 11).unwrap()),
("22", cx, NaiveDate::from_ymd_opt(2023, 2, 22).unwrap()),
("dec 30", cx, NaiveDate::from_ymd_opt(2023, 12, 30).unwrap()),
];
for (input, context, res) in tv {
println!("{:?} ({:?}) => {:?}", input, Some(context), res);
assert_eq!(parse_single_date(input, context).unwrap(), res);
}
}
}

View File

@ -17,7 +17,7 @@
//! left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`.
//! The function uses the context provided to resolve any relative dates within the input string.
//!
//! - [parse_single_date]: This function parses a given input string representing a single date and returns a `NaiveDate`.
//! - [`parse_single_date`]: This function parses a given input string representing a single date and returns a `NaiveDate`.
//! If there are any unparsed parts left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`.
//! The function uses the context provided to resolve any relative dates within the input string.
//!

View File

@ -9,8 +9,7 @@ use chrono::Month;
use log::SetLoggerError;
use poise::serenity_prelude;
use thiserror::Error;
use crate::ids::EventIdType;
use uuid::Uuid;
/// Global error struct for idlefox
///
@ -54,32 +53,32 @@ pub enum IdleError {
/// Indicates an event couldn't be launched
///
/// Raised when there's an issue launching an event usually indicates something went wrong with bookeeping.
/// Note that while a HUID is given, it may no longer exist in memory and might only be found in logs.
/// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs.
#[error("An event couldn't be launched (Id: {0})")]
EventLaunch(EventIdType),
EventLaunch(Uuid),
/// Error indicating multiple events couldn't be pruned
///
/// Raised when one or more events cannot be removed from the ongoing events list.
/// This usually indicates a problem with managing and updating the list of ongoing events.
/// Note that while a HUID is given, it may no longer exist in memory and might only be found in logs.
/// Note that while a UUID is given, it may no longer exist in memory and might only be found in logs.
#[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")]
EventPrune(Vec<EventIdType>),
EventPrune(Vec<Uuid>),
/// Error indicating an event could not be deleted
///
/// This error is raised when attempting to delete an event fails,
/// either due to a problem with bookkeping or because the specified HUID
/// either due to a problem with bookkeping or because the specified UUID
/// does not correspond to any existing events anymore.
#[error("An event couldn't be deleted (Id: {0})")]
DeleteEvent(EventIdType),
DeleteEvent(Uuid),
/// Error indicating that an ongoing event launch couldn't be performed
///
/// This error was likely raised as a launch operation for an event was already underway.
/// Launching multiple times for the same event may lead to inconsistent states or data corruption.
#[error("Couldn't launch event (Id: {0})")]
LaunchingEvent(EventIdType),
LaunchingEvent(Uuid),
/// Error indicating a mutex was poisoned or couldn't be acquired
///
@ -90,34 +89,14 @@ pub enum IdleError {
/// 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 trying to acquire the discord group: {0}")]
#[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 trying to acquire discord guilds")]
#[error("An error occured while tring to acquire discord guilds")]
AcquiringDiscordGuild,
/// Indicates an error occuring while trying to convert from a DiscordContainer into a ParsedVote
///
/// 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} {1}")]
BackupWriteError(String, 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} {1}")]
BackupReadError(String, std::io::Error),
/// Indicate a value couldn't be serialized
#[error("An error occured while trying to serialize data {0}")]
SerdeError(serde_json::Error),
/// Indlcate the config couldn't be loaded properly
#[error("An error occured while trying to load the config {0}")]
LoadingConfig(std::io::Error),
/// Indlcate the config couldn't be saved properly
#[error("An error occured while trying to save the config {0}")]
SavingConfig(std::io::Error),
}
impl From<nom::Err<nom::error::Error<&str>>> for IdleError {

View File

@ -1,67 +1,13 @@
//! This module contains utilities for generating event ids.
//! Handle all Ids functionalities
//!
//! Features:
//! Generating a human readable ID for a HUID
//! Finding the HUID from an ID
//! Generating a human readable ID for a UUID
//! Finding the UUID from an ID
//! Removing ID as needed
use crate::votes::EventHolder;
// use human_ids::generate;
// use std::{env, time::Instant};
/// 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) {
// Testing this collision is not possible
#[cfg(not(tarpaulin_include))]
true => generate_unique_id(holder),
false => id,
}
}
#[cfg(test)]
mod test {
use crate::votes::{add_pending_event, EventHolder, EventPending};
use super::{generate_id, generate_unique_id};
#[test]
fn test_id_generation() {
let id = generate_id();
assert!(!id.is_empty())
}
#[test]
fn test_id_unique() {
let holder = EventHolder::default();
add_pending_event(EventPending::default(), &holder).unwrap();
let id = generate_unique_id(&holder);
assert!(!id.is_empty());
}
}
// let tk = env::var("DISCORD_TOKEN");
// let id = generate(None);
// println!("Token: {:?} Id: {}", tk, id);

View File

@ -26,6 +26,7 @@ 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;
@ -422,16 +423,5 @@ mod tests {
find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()),
Some("ffxiv_progfish".to_string())
);
assert!(find_role_from_str(None, arguments.to_vec()).is_none());
assert!(find_role_from_str(Some("Bob"), Vec::new()).is_none());
}
#[test]
fn create_container() {
VoteContainer::new(
"IO".to_string(),
"desc".to_string(),
VoteTypeIdentifier::WeeklyVote,
);
}
}

View File

@ -12,7 +12,7 @@
pub mod config; // Maybe in lib
pub mod date; // Definitely in lib
mod error_handling; // Likely in lib
pub mod ids; // Definitely in lib
mod ids; // Definitely in lib
pub mod io; // Maybe in lib
mod modules; // Maybe in lib
mod persistence; // Likely in lib
@ -23,6 +23,6 @@ mod watchdog; // Definitely in lib
// // Re export
// pub use votes::add_future_event;
// pub use votes::launch_future_event;
//
pub use error_handling::IdleError;
pub use watchdog::main_scheduler_loop;

View File

@ -6,105 +6,7 @@
//!
//!
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<Data, 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(|e| IdleError::BackupReadError($path.to_owned(), e))?,
)))
};
}
// Testing a bad serialisation is pointless
#[cfg(not(tarpaulin_include))]
/// Tries to save the list to disk and return an error on failure
pub(crate) fn save_to_writer<Data, Writer>(data: Data, mut writer: Writer) -> Result<(), IdleError>
where
Data: Serialize,
Writer: Write + Sized + std::fmt::Debug,
{
writer
.write(
serde_json::to_string_pretty(&data)
.map_err(IdleError::SerdeError)?
.as_bytes(),
)
.map_err(|e| IdleError::BackupWriteError(format!("{:?}", writer), e))?;
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(|e| IdleError::BackupWriteError($path.to_string(), e))?,
)?;
};
}
#[cfg(test)]
mod tests {
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();
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(())
}
// use super::*;
}

View File

@ -4,10 +4,6 @@
//! 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 {

View File

@ -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, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(test, derive(Clone))]
pub struct Ballot {
/// The event the vote refers to
linked_event: EventIdType,

View File

@ -10,25 +10,20 @@
//! can be in, such as planned, ongoing, closed, and cancelled. This helps
//! to track and manage the progression of each voting event according to
//! predefined rules and conditions.
#![allow(dead_code)]
use std::fmt::Display;
use chrono::{Days, Local, NaiveDate, NaiveDateTime, NaiveTime};
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use crate::{
date::{parse_date_list, parse_single_date, NaiveDateList},
io::{VoteContainer, VoteTypeIdentifier},
IdleError,
};
use crate::{date::NaiveDateList, io::VoteContainer, IdleError};
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, Clone)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[derive(Serialize, Deserialize, Default)]
#[cfg_attr(test, derive(Clone))]
pub struct EventPending {
/// The parsed representation of the vote associated with this event.
/// It holds the details required for the voting process.
@ -43,8 +38,8 @@ impl EventPending {
}
}
#[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Serialize, Deserialize)]
#[cfg_attr(test, derive(Clone))]
// 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 +61,8 @@ impl EventOngoing {
}
}
#[derive(Serialize, Deserialize, Clone)]
// #[cfg_attr(test, derive(Clone))]
#[derive(Serialize, Deserialize)]
#[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 +81,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, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
#[derive(Debug, Serialize, Deserialize, Default)]
#[cfg_attr(test, derive(Clone))]
pub(super) struct ParsedVote {
/// The title of the even
pub(super) title: String,
@ -110,56 +105,18 @@ impl ParsedVote {
pub(super) fn launch(&mut self) -> Result<(), IdleError> {
// TODO: Define this
// self.status = EventStatus::Started;
// Maybe send a message ? the bot will need the Huid of the event to be able to add reaction
// Maybe send a message ? the bot will need the Uuid of the event to be able to add reaction
// TODO: This is a vkypoint, as this method will need an IO interaction
Ok(())
}
}
impl ParsedVote {
/// Try to parse a vote from a votecontainer
fn try_from_with_context(
value: VoteContainer,
context: Option<NaiveDate>,
vote_type: VoteTypeIdentifier,
) -> Result<Self, IdleError> {
let context = context.unwrap_or(Local::now().date_naive());
let close_date = parse_single_date(
&value.date_end.ok_or(IdleError::DiscordContainerParse)?,
Some(context),
)?
.and_time(NaiveTime::from_hms_opt(20, 00, 00).unwrap());
// TODO: Have a better auto_delete threshold
let auto_delete_date = close_date.checked_add_days(Days::new(12)).unwrap();
// TODO: Use this to have better date selection handling
match vote_type {
VoteTypeIdentifier::WeeklyVote => {
// Start is next week, end is end of week, days is all week
}
VoteTypeIdentifier::ShortVote => {
// Start is ?, end is ?, days must be given
}
VoteTypeIdentifier::LongVote => (),
VoteTypeIdentifier::Uninitialised => (),
}
Ok(Self {
title: value.title,
description: value.description,
// TODO: Have a logic to find a good start date
launch_date: parse_single_date(
&value.start_date.ok_or(IdleError::DiscordContainerParse)?,
Some(context),
)?
.and_time(NaiveTime::from_hms_opt(20, 00, 00).unwrap()),
close_date,
auto_delete_date,
votes: Vec::new(),
// TODO: How can days be empty ? Add the non_days.
list_candidates: parse_date_list(
&value.days.ok_or(IdleError::DiscordContainerParse)?,
Some(context),
)?,
})
impl TryFrom<VoteContainer> for ParsedVote {
type Error = IdleError;
fn try_from(value: VoteContainer) -> Result<Self, Self::Error> {
let _ = value;
todo!()
}
}
@ -170,35 +127,3 @@ impl Display for ParsedVote {
write!(f, "{:?}", self)
}
}
#[cfg(test)]
mod test {
use super::{EventPending, ParsedVote};
use crate::io::{VoteContainer, VoteTypeIdentifier};
use chrono::NaiveDate;
#[test]
// TODO: Complete this test
fn test_display() {
let pv = ParsedVote::default();
let _ = format!("{}", pv);
let eo = EventPending::default().into_ongoing();
let _ = format!("{}", eo);
}
#[test]
#[ignore]
// TODO: Complete this test
fn test_conversion() {
let cx = NaiveDate::from_ymd_opt(2000, 12, 12);
let v = ParsedVote::try_from_with_context(
VoteContainer::default(),
cx,
VoteTypeIdentifier::WeeklyVote,
);
println!("{:?}", v);
assert!(v.is_ok());
}
}

View File

@ -1,23 +1,17 @@
//! Submodule including all helper functions to handle vote creation and evolution
//!
use crate::{config::GlobalConfig, votes::traits::BorrowInner};
use std::sync::Arc;
use chrono::NaiveDate;
use std::{
fs::{create_dir, File},
sync::Arc,
};
use uuid::Uuid;
use crate::IdleError;
use super::{
events::{EventOngoing, EventPending},
holders::{ListClosedEvents, TypedEvent},
holders::ListClosedEvents,
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.
///
@ -34,25 +28,21 @@ use crate::{
/// let parsed_vote = EventPending::default();
/// let id = add_pending_event(parsed_vote, &ev_ctx).unwrap();
/// ```
pub fn add_pending_event(
event: EventPending,
ev_ctx: &EventHolder,
) -> Result<EventIdType, IdleError> {
pub fn add_pending_event(event: EventPending, ev_ctx: &EventHolder) -> Result<Uuid, IdleError> {
ev_ctx
.pending_events
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.add_pending_event(event)
}
/// Launches a pending event by transferring it from the pending to ongoing events list.
///
/// This function identifies an event by its HUID and moves it from the planned
/// (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`.
/// Otherwise, it returns an error of type `IdleError`.
/// This function identifies an event by its UUID and moves it from the planned (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`. Otherwise, it returns an error of type `IdleError`.
///
/// ## Parameters:
/// - `Huid`: A `Huid` that uniquely identifies the event to be launched.
/// - `uuid`: A `Uuid` that uniquely identifies the event to be launched.
///
/// ## Example:
/// ```rust
@ -60,33 +50,39 @@ pub fn add_pending_event(
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
///
/// make_into_ongoing_event(&id, &ev_ctx).unwrap()
/// make_into_ongoing_event(id, &ev_ctx).unwrap()
/// ```
pub fn make_into_ongoing_event(huid: &EventIdType, ev_ctx: &EventHolder) -> Result<(), IdleError> {
ev_ctx.pending_events.lock().unwrap().launch(huid, ev_ctx)
pub fn make_into_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> {
ev_ctx
.pending_events
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.launch(uuid, ev_ctx)
}
/// Manually adds an ongoing event.
///
/// This function is intended for internal use and directly adds an event
/// to the list of ongoing events. It expects a HUID and a parsed vote as inputs,
/// to the list of ongoing events. It expects a UUID and a parsed vote as inputs,
/// using which it updates the `OngoingEvents` instance.
///
/// ## Parameters:
/// - `huid`: A `Huid` that uniquely identifies the event to be added.
/// - `uuid`: A `Uuid` that uniquely identifies the event to be added.
/// - `event`: A `ParsedVote` struct representing the details of the ongoing event to be added.
///
/// ## Example:
/// ```rust
/// use idlefox::ids::generate_id;
/// use idlefox::votes::{add_ongoing_event, EventHolder, EventPending};
/// # use uuid::Uuid;
/// use idlefox::votes::{add_ongoing_event, EventPending, EventHolder};
/// let ev_ctx = EventHolder::default();
/// let huid = generate_id(); // A new id
/// let uuid = Uuid::new_v4(); // A new id
/// let ongoing = EventPending::default().into_ongoing(); // A very legit event
/// add_ongoing_event(&huid, ongoing, &ev_ctx).unwrap();
///
/// add_ongoing_event(uuid, ongoing, &ev_ctx).unwrap();
/// ```
pub fn add_ongoing_event(
huid: &EventIdType,
uuid: Uuid,
event: EventOngoing,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
@ -94,14 +90,15 @@ pub fn add_ongoing_event(
.ongoing_events
.lock()
.unwrap()
.add_event(huid, event)?;
// .map_err(|_| IdleError::MutexError)?
.add_event(uuid, event)?;
Ok(())
}
/// Destroy an event without closing it and officially ending it
///
/// This function removes an ongoing event from the list of ongoing events.
/// It expects a HUID as input and returns a `Result` containing either a `ParsedVote`
/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote`
/// struct representing the details of the removed event or an `IdleError`.
///
/// ## Example:
@ -111,21 +108,23 @@ pub fn add_ongoing_event(
/// # };
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// make_into_ongoing_event(&id, &ev_ctx).unwrap();
/// make_into_ongoing_event(id, &ev_ctx).unwrap();
///
/// del_ongoing_event(&id, &ev_ctx).unwrap();
/// del_ongoing_event(id, &ev_ctx).unwrap();
/// ```
pub fn del_ongoing_event(
huid: &EventIdType,
ev_ctx: &EventHolder,
) -> Result<EventOngoing, IdleError> {
ev_ctx.ongoing_events.lock().unwrap().del_event(huid)
pub fn del_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<EventOngoing, IdleError> {
ev_ctx
.ongoing_events
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.del_event(uuid)
}
/// Destroy a pending event without closing it
///
/// This function removes a pending event from the list of pending events.
/// It expects a HUID as input and returns a `Result` containing either a `ParsedVote`
/// It expects a UUID as input and returns a `Result` containing either a `ParsedVote`
/// struct representing the details of the removed event or an `IdleError`.
///
/// ## Example:
@ -135,19 +134,21 @@ pub fn del_ongoing_event(
/// # };
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// del_pending_event(&id, &ev_ctx).unwrap();
/// del_pending_event(id, &ev_ctx).unwrap();
/// ```
pub fn del_pending_event(
huid: &EventIdType,
ev_ctx: &EventHolder,
) -> Result<EventPending, IdleError> {
ev_ctx.pending_events.lock().unwrap().del_event(huid)
pub fn del_pending_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<EventPending, IdleError> {
ev_ctx
.pending_events
.lock()
.unwrap()
// .map_err(|_| IdleError::MutexError)?
.del_event(uuid)
}
/// This function is used to close an ongoing event and return the parsed vote associated with it. If the closure is successful, the owned event is returned for post-treatment.
/// # Arguments
///
/// * `huid` - A Huid representing the identifier of the event that is to be closed.
/// * `uuid` - A Uuid representing the identifier of the event that is to be closed.
///
/// ## Example:
/// ```rust
@ -156,15 +157,16 @@ pub fn del_pending_event(
/// # };
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// make_into_ongoing_event(&id, &ev_ctx).unwrap();
/// close_ongoing_event(&id, &ev_ctx).unwrap();
/// make_into_ongoing_event(id, &ev_ctx).unwrap();
/// close_ongoing_event(id, &ev_ctx).unwrap();
/// ```
pub fn close_ongoing_event(huid: &EventIdType, ev_ctx: &EventHolder) -> Result<(), IdleError> {
pub fn close_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> {
ev_ctx
.ongoing_events
.lock()
.unwrap()
.close_event(huid, ev_ctx)
// .map_err(|_| IdleError::MutexError)?
.close_event(uuid, ev_ctx)
}
/// A link to all events, to be shared between threads related to this event pool.
@ -188,145 +190,10 @@ pub struct EventHolder {
/// Closed events have been voted up but havent been deleted and can therefore be watched or opened again.
/// These events will be autodeleted after a while
pub closed_events: Arc<std::sync::Mutex<ListClosedEvents>>,
/// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated.
pub old_date: Arc<std::sync::Mutex<NaiveDate>>,
/// The newly created discord context
pub discord_ctx: Arc<tokio::sync::Mutex<Option<poise::serenity_prelude::Context>>>,
/// A link to the active config
pub config: Arc<std::sync::RwLock<GlobalConfig>>,
}
/// 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(save_path: Option<&str>) -> Result<Self, IdleError> {
let save_path = save_path.unwrap_or("data");
Ok(Self {
pending_events: load_from_reader!(
ListPendingEvents,
save_path.to_owned() + "/pending_events.json"
),
ongoing_events: load_from_reader!(
ListOngoingEvents,
save_path.to_owned() + "/ongoing_events.json"
),
closed_events: load_from_reader!(
ListClosedEvents,
save_path.to_owned() + "/closed_events.json"
),
old_date: load_from_reader!(NaiveDate, save_path.to_owned() + "/old_date.json"),
config: Arc::new(std::sync::RwLock::new(GlobalConfig::try_load_from_disk()?)),
..Default::default()
})
}
pub fn try_save_to_disk(&self, save_path: Option<&str>) -> Result<(), IdleError> {
let save_path = save_path.unwrap_or("data");
let _ = create_dir(save_path);
save_to_writer!(
self.pending_events,
ListPendingEvents,
save_path.to_owned() + "/pending_events.json"
);
save_to_writer!(
self.ongoing_events,
ListOngoingEvents,
save_path.to_owned() + "/ongoing_events.json"
);
save_to_writer!(
self.closed_events,
ListClosedEvents,
save_path.to_owned() + "/closed_events.json"
);
save_to_writer!(
&self.old_date,
NaiveDate,
save_path.to_owned() + "/old_date.json"
);
self.config.read().unwrap().try_save_to_disk()?;
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.ongoing_events).contains_key(id)
|| inner!(self.closed_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<TypedEvent> {
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()))
})
}
}
#[cfg(test)]
mod test {
use crate::votes::{holders::TypedEvent, EventPending};
use super::{add_pending_event, close_ongoing_event, make_into_ongoing_event, EventHolder};
#[test]
fn test_save_load() {
let hld = EventHolder::default();
let (a, b, c) = (
add_pending_event(EventPending::default(), &hld).unwrap(),
add_pending_event(EventPending::default(), &hld).unwrap(),
add_pending_event(EventPending::default(), &hld).unwrap(),
);
make_into_ongoing_event(&b, &hld).unwrap();
make_into_ongoing_event(&c, &hld).unwrap();
close_ongoing_event(&c, &hld).unwrap();
assert!(hld.contains_event(&a));
assert!(hld.contains_event(&b));
assert!(hld.contains_event(&c));
hld.try_save_to_disk(Some("bobito")).unwrap();
let hld2 = EventHolder::try_load_from_disk(Some("bobito")).unwrap();
assert!(hld2.contains_event(&a));
assert!(hld2.contains_event(&b));
assert!(hld2.contains_event(&c));
let (a2, b2, c2) = (
hld.find_event(&a).unwrap(),
hld.find_event(&b).unwrap(),
hld.find_event(&c).unwrap(),
);
// match (a2, b2, c2) {
// TypedEvent::Ongoing(),TypedEvent::Pending(),TypedEvent::Closed() => (),
// _ =>
// }
assert!(matches!(a2, TypedEvent::Pending(_)));
assert!(matches!(b2, TypedEvent::Ongoing(_)));
assert!(matches!(c2, TypedEvent::Closed(_)));
}
}

View File

@ -11,14 +11,11 @@
//! 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};
use uuid::Uuid;
use crate::{
ids::{generate_id, EventIdType},
IdleError,
};
use crate::IdleError;
use super::{
add_ongoing_event,
@ -30,19 +27,18 @@ use super::{
///
/// 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
pub(super) pending_events: PendingHashmap,
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 fn add_pending_event(&mut self, event: EventPending) -> Result<EventIdType, IdleError> {
let id = generate_id();
self.pending_events.insert(id.clone(), event);
/// This function generates a new UUID for the event before adding it to the list.
pub(super) fn add_pending_event(&mut self, event: EventPending) -> Result<Uuid, IdleError> {
let id = Uuid::new_v4();
self.pending_events.insert(id, event);
Ok(id)
}
@ -56,8 +52,8 @@ impl ListPendingEvents {
) -> Result<(), IdleError> {
self.find_upcoming(current_time)
.iter()
.try_for_each(|huid| {
self.launch(huid, ev_ctx)?;
.try_for_each(|uuid| {
self.launch(*uuid, ev_ctx)?;
Ok(())
})
}
@ -65,66 +61,52 @@ impl ListPendingEvents {
/// Launch the specified event by moving it from pending events to ongoing events.
///
/// Returns an `IdleError` if the event cannot be found in pending events.
pub(super) fn launch(
&mut self,
huid: &EventIdType,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
pub(super) fn launch(&mut self, uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> {
let event = self
.pending_events
.remove(huid)
.ok_or(IdleError::EventLaunch(huid.to_string()))?;
add_ongoing_event(huid, event.into_ongoing(), ev_ctx)?;
// make_into_ongoing_event(huid)?;
.remove(&uuid)
.ok_or(IdleError::EventLaunch(uuid))?;
add_ongoing_event(uuid, event.into_ongoing(), ev_ctx)?;
// make_into_ongoing_event(uuid)?;
Ok(())
}
/// Find all events that are scheduled to start after the given date.
///
/// Returns a vector of HUIDs corresponding to the upcoming events.
/// TODO: Consider returning references
pub(super) fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec<EventIdType> {
/// Returns a vector of UUIDs corresponding to the upcoming events.
pub(super) fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec<Uuid> {
self.pending_events
.iter()
.filter(|&(_, e)| e.parsed_vote.launch_date <= current_time)
.map(|(k, _v)| (k.clone()))
.map(|(k, _v)| (*k))
.collect()
}
/// delete the event without launching it
pub fn del_event(&mut self, huid: &EventIdType) -> Result<EventPending, IdleError> {
pub fn del_event(&mut self, uuid: Uuid) -> Result<EventPending, IdleError> {
self.pending_events
.remove(huid)
.ok_or(IdleError::DeleteEvent(huid.to_string()))
.remove(&uuid)
.ok_or(IdleError::DeleteEvent(uuid))
}
// 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, Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Serialize, Deserialize, Default)]
pub struct ListOngoingEvents {
/// The list of ongoing events
pub(super) ongoing_events: OngoingHashmap,
ongoing_events: OngoingHashmap,
}
impl ListOngoingEvents {
/// Add a new event to the list of ongoing events.
///
/// This function also launch the event based and adds a callback with the Huid of the original caller.
pub(crate) fn add_event(
&mut self,
huid: &EventIdType,
mut event: EventOngoing,
) -> Result<(), IdleError> {
/// This function also launch the event based and adds a callback with the Uuid of the original caller.
pub(crate) fn add_event(&mut self, id: Uuid, mut event: EventOngoing) -> Result<(), IdleError> {
event.parsed_vote.launch()?;
self.ongoing_events.insert(huid.clone(), event);
self.ongoing_events.insert(id, event);
Ok(())
}
@ -137,8 +119,8 @@ impl ListOngoingEvents {
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
let failure = Vec::new();
for huid in self.find_autoclose(current_time) {
self.close_event(&huid, ev_ctx)?;
for uuid in self.find_autoclose(current_time) {
self.close_event(uuid, ev_ctx)?;
}
match failure.is_empty() {
true => Ok(()),
@ -152,41 +134,38 @@ impl ListOngoingEvents {
/// puting it into the closed event list.
///
/// Doing so allow for the vote result to be read while it is valid
pub fn close_event(
&mut self,
huid: &EventIdType,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
pub fn close_event(&mut self, uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> {
// TODO: Another vkypoint, as we cant continue without knowing how to send a message
let event = self
.ongoing_events
.remove(huid)
.ok_or(IdleError::LaunchingEvent(huid.to_string()))?;
.remove(&uuid)
.ok_or(IdleError::LaunchingEvent(uuid))?;
ev_ctx
.closed_events
.lock()
.unwrap()
.add_event(huid.clone(), event.into_closed())?;
.add_event(uuid, event.into_closed())?;
Ok(())
}
/// delete the event without launching it
pub fn del_event(&mut self, huid: &EventIdType) -> Result<EventOngoing, IdleError> {
pub fn del_event(&mut self, uuid: Uuid) -> Result<EventOngoing, IdleError> {
self.ongoing_events
.remove(huid)
.ok_or(IdleError::DeleteEvent(huid.to_string()))
.remove(&uuid)
.ok_or(IdleError::DeleteEvent(uuid))
}
/// Find all events that are scheduled to be autoclosed.
///
/// Returns a vector of HUIDs corresponding to the old events.
pub(super) fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec<EventIdType> {
/// Returns a vector of UUIDs corresponding to the old events.
pub(super) fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> {
self.ongoing_events
.iter()
.filter(|(_, e)| e.parsed_vote.close_date <= current_time)
.map(|(k, _)| k.clone())
.map(|(k, _)| *k)
.collect()
}
// TODO: maybe add an update_ongoing(date) ?
}
/// The list of closed events
@ -196,24 +175,24 @@ impl ListOngoingEvents {
#[derive(Serialize, Deserialize, Default)]
pub struct ListClosedEvents {
/// The list of closed events
pub(super) closed_events: ClosedHashmap,
closed_events: ClosedHashmap,
}
impl ListClosedEvents {
/// Add a closed event to the list of closed events
pub fn add_event(&mut self, huid: EventIdType, event: EventClosed) -> Result<(), IdleError> {
self.closed_events.insert(huid, event);
pub fn add_event(&mut self, uuid: Uuid, event: EventClosed) -> Result<(), IdleError> {
self.closed_events.insert(uuid, event);
Ok(())
}
/// Find all events that are too old and supposed to be pruned.
///
/// Returns a vector of HUIDs corresponding to the old events.
pub(super) fn find_old(&mut self, current_time: NaiveDateTime) -> Vec<EventIdType> {
/// Returns a vector of UUIDs corresponding to the old events.
pub(super) fn find_old(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> {
self.closed_events
.iter()
.filter(|(_, e)| e.parsed_vote.auto_delete_date <= current_time)
.map(|(k, _)| k.clone())
.map(|(k, _)| *k)
.collect()
}
/// Remove all outdated votes for the current user
@ -221,12 +200,12 @@ impl ListClosedEvents {
/// This function is expected to be called periodically by the watchdog.
pub(crate) fn prune_old(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> {
let mut failure = Vec::new();
for huid in self.find_old(current_time) {
println!("{}", huid);
if self.closed_events.remove(&huid).is_none() {
for uuid in self.find_old(current_time) {
println!("{}", uuid);
if self.closed_events.remove(&uuid).is_none() {
// Should only happen during hard to reproduce race conditions
#[cfg(not(tarpaulin_include))]
failure.push(huid.clone());
failure.push(uuid);
}
}
match failure.is_empty() {
@ -237,18 +216,6 @@ 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};
@ -281,20 +248,20 @@ mod tests {
// Can we add a vote ?
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
// assert!(gimme!(ev_ctx.pending_events).contains_key(&id)); // Is the vote present ?
del_pending_event(&id, &ev_ctx).unwrap();
del_pending_event(id, &ev_ctx).unwrap();
assert!(!g!(ev_ctx.pending_events).pending_events.contains_key(&id)); // Is the vote now deleted
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
make_into_ongoing_event(&id, &ev_ctx).unwrap(); // Launching this event
make_into_ongoing_event(id, &ev_ctx).unwrap(); // Launching this event
assert!(!g!(ev_ctx.pending_events).pending_events.contains_key(&id)); // Is the vote now not pending
assert!(g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now ongoing
close_ongoing_event(&id, &ev_ctx).unwrap();
close_ongoing_event(id, &ev_ctx).unwrap();
assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing
let id = add_pending_event(ev.clone(), &ev_ctx).unwrap();
make_into_ongoing_event(&id, &ev_ctx).unwrap(); // Launching this event
del_ongoing_event(&id, &ev_ctx).unwrap();
make_into_ongoing_event(id, &ev_ctx).unwrap(); // Launching this event
del_ongoing_event(id, &ev_ctx).unwrap();
assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing
}
@ -331,7 +298,7 @@ mod tests {
assert!(!g!(ev.closed_events).closed_events.contains_key(&id)); // not deleted
// Now some time passed
assert_eq!(g!(ev.pending_events).find_upcoming(later), vec![id.clone()]); // one upcomming event
assert_eq!(g!(ev.pending_events).find_upcoming(later), vec![id]); // one upcomming event
assert!(g!(ev.closed_events).find_old(later).is_empty()); // no old events
assert!(g!(ev.ongoing_events).find_autoclose(later).is_empty()); // no old events
g!(ev.pending_events).process_upcoming(later, &ev).unwrap(); // one event should be processed
@ -343,10 +310,7 @@ mod tests {
// More time passed
assert!(g!(ev.pending_events).find_upcoming(very_later).is_empty()); // one upcomming event
assert_eq!(
g!(ev.ongoing_events).find_autoclose(very_later),
vec![id.clone()]
); // one old event
assert_eq!(g!(ev.ongoing_events).find_autoclose(very_later), vec![id]); // one old event
assert!(g!(ev.closed_events).find_old(very_later).is_empty()); // no old events
g!(ev.pending_events)
.process_upcoming(very_later, &ev)
@ -361,10 +325,7 @@ mod tests {
assert!(g!(ev.pending_events)
.find_upcoming(very_very_later)
.is_empty()); // one upcomming event
assert_eq!(
g!(ev.closed_events).find_old(very_very_later),
vec![id.clone()]
); // one old event
assert_eq!(g!(ev.closed_events).find_old(very_very_later), vec![id]); // one old event
assert!(g!(ev.ongoing_events)
.find_autoclose(very_very_later)
.is_empty()); // no old events
@ -380,10 +341,4 @@ mod tests {
// TODO: Check the status at several points
}
#[ignore]
#[test]
fn serialisation_check() {
todo!()
}
}

View File

@ -19,7 +19,6 @@ mod ballots;
mod events;
mod helper_functions;
mod holders;
mod traits;
// Republish
pub use ballots::Ballot;
@ -30,7 +29,7 @@ pub use holders::{ListOngoingEvents, ListPendingEvents};
use std::collections::HashMap;
use crate::ids::EventIdType;
use uuid::Uuid;
/// The hashmap of pending votes
type PendingHashmap = HashMap<EventIdType, EventPending>;
@ -39,6 +38,11 @@ type OngoingHashmap = HashMap<EventIdType, EventOngoing>;
/// The hashmap of closed votes, still available for reading to check the results
type ClosedHashmap = HashMap<EventIdType, EventClosed>;
/// Placeholder datatype
///
/// Links to an event, active or planned
pub type EventIdType = Uuid;
/// Placeholder user data type
///
/// Links back to an user

View File

@ -1,142 +0,0 @@
//! 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<R> {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, R>;
}
impl BorrowInner<EventClosed> for ListClosedEvents {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, EventClosed> {
&self.closed_events
}
}
impl BorrowInner<EventOngoing> for ListOngoingEvents {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, EventOngoing> {
&self.ongoing_events
}
}
impl BorrowInner<EventPending> for ListPendingEvents {
/// Borrow the inner ongoing events
fn borrow_inner(&self) -> &HashMap<String, EventPending> {
&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<R> {
/// Borrow the inner ongoing events
fn borrow_mut_inner(&mut self) -> &mut HashMap<String, R>;
}
/// Blanket inner dictionnary implementation
///
/// This trait is meant to allow for inner dictionnary manipulation
pub(crate) trait EventManipulation<R> {
/// Get a key in the inner hashmap
fn get_key(&self, s: &str) -> Option<&R>;
// /// Insert a key in the inner hashmap
// fn insert(&self, s: &str);
}
impl<T, R> EventManipulation<R> for T
where
T: BorrowInner<R>,
{
fn get_key(&self, s: &str) -> Option<&R> {
self.borrow_inner().get(s)
}
}
#[cfg(test)]
mod tests {
use crate::votes::events::ParsedVote;
use super::*;
#[derive(Default)]
struct TestI {
inner: HashMap<String, usize>,
}
impl BorrowInner<usize> for TestI {
fn borrow_inner(&self) -> &HashMap<String, usize> {
&self.inner
}
}
impl BorrowMutInner<usize> for TestI {
fn borrow_mut_inner(&mut self) -> &mut HashMap<String, usize> {
&mut self.inner
}
}
impl BorrowMutInner<EventPending> for ListPendingEvents {
fn borrow_mut_inner(&mut self) -> &mut HashMap<String, EventPending> {
&mut self.pending_events
}
}
#[test]
fn test_borrow_impl() {
let mut i = TestI::default();
assert!(i.borrow_inner().is_empty());
i.borrow_mut_inner().insert("Bob".to_owned(), 3);
assert!(i.borrow_inner().contains_key("Bob"));
}
#[test]
fn test_blanket_implementation() {
let mut i = TestI::default();
assert!(i.get_key("blanket").is_none());
i.borrow_mut_inner().insert("blanket".to_owned(), 42);
assert!(i.get_key("blanket").is_some());
}
#[test]
fn test_manual_implementation() {
let (mut e, mut v, mut w) = (
ListClosedEvents::default(),
ListOngoingEvents::default(),
ListPendingEvents::default(),
);
let pv = ParsedVote::default();
assert!(e.get_key("blanket1").is_none());
e.add_event(
"blanket1".to_owned(),
EventClosed {
parsed_vote: pv.clone(),
},
)
.unwrap();
assert!(e.get_key("blanket1").is_some());
assert!(v.get_key("blanket2").is_none());
v.add_event(
&"blanket2".to_owned(),
EventOngoing {
parsed_vote: pv.clone(),
},
)
.unwrap();
assert!(v.get_key("blanket2").is_some());
assert!(w.get_key("blanket3").is_none());
w.borrow_mut_inner()
.insert("blanket3".to_owned(), EventPending::default());
assert!(w.get_key("blanket3").is_some());
}
}

View File

@ -15,7 +15,9 @@
use crate::votes::EventHolder;
use chrono::{DateTime, Local, NaiveDate};
use poise::serenity_prelude::{self, CacheHttp, ChannelId};
use poise::serenity_prelude::{
self, CacheHttp, ChannelId, CreateMessage, EmojiId, Mention, ReactionType, RoleId,
};
/// The main scheduler waiting and dispatch loop.
///
@ -36,21 +38,60 @@ pub async fn main_scheduler_loop(mut interval: tokio::time::Interval, ev_ctx: Ev
}
/// Close to finding out
#[cfg(not(tarpaulin_include))] // Just a test function
async fn fk_around(ev_ctx: &EventHolder) {
println!(
"In the fk_around function ({}):",
Local::now() // &ev_ctx
);
if let Some(discord_ctx) = ev_ctx.discord_ctx.lock().await.as_mut() {
println!("Fking around : {:#?}", discord_ctx);
let mut m = serenity_prelude::Message::default();
m.content = "Bob".into();
println!("Full discord ctx : {:#?}", discord_ctx);
let m = CreateMessage::new().content(format!(
"Hello {}",
Mention::from(RoleId::new(1222612097091768371))
));
// let mut m = serenity_prelude::Message::default();
// discord_ctx.http.get_scheduled_event_users(, , , , )
// discord_ctx.http.get_user(UserId::new(1));
// let m = m
// m.content = format!("Hello {}", Mention::from(UserId::new(1)));
// m.mentions = vec![User::];
// m.mention_roles = vec![];
let r = discord_ctx
.http()
.send_message(ChannelId::new(1300786300143800351), Vec::new(), &m)
.await;
println!("{:?}", r);
if let Ok(msg) = r {
#[cfg(not(feature = "custom_emojis"))]
let msg_result = discord_ctx
.http()
.create_reaction(
msg.channel_id,
msg.id,
&ReactionType::Unicode("1️⃣".to_string()),
)
.await;
#[cfg(feature = "custom_emojis")]
let msg_result = discord_ctx
.http()
.create_reaction(
msg.channel_id,
msg.id,
&ReactionType::Custom {
animated: false,
id: (EmojiId::new(1329095596396642375)),
name: (Some("Foxo".to_string())),
},
)
.await;
println!("{:?}", msg_result);
}
}
}

View File

@ -3,12 +3,12 @@ mod tests {
#[test]
fn generic_integration_test() {
use idlefox::ids::generate_id;
use idlefox::votes::{add_ongoing_event, EventHolder, EventPending};
use idlefox::votes::{
add_pending_event, make_into_ongoing_event, EventHolder, EventPending,
};
let ev_ctx = EventHolder::default();
let huid = generate_id(); // A new id
let ongoing = EventPending::default().into_ongoing(); // A very legit event
let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
add_ongoing_event(&huid, ongoing, &ev_ctx).unwrap();
make_into_ongoing_event(id, &ev_ctx).unwrap()
}
}