Adds a basic config and a handling of the reaction emotes #51

Merged
Dandaedre merged 1 commits from config into dev 2025-01-16 17:53:18 +01:00
5 changed files with 170 additions and 9 deletions

2
.gitignore vendored
View File

@ -30,3 +30,5 @@ tarpaulin-report.html
# A module summary
summary.md
config.json

View File

@ -32,18 +32,130 @@
//! # }
//!
use std::fs::File;
#![allow(clippy::all)]
use crate::IdleError;
use std::{fs::File, io::Write};
use log::LevelFilter;
use poise::serenity_prelude::{EmojiId, ReactionType};
use serde::{Deserialize, Serialize};
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};
use crate::error_handling::IdleError;
pub type WeeklyReactionList = Vec<ReactionType>;
/// The global config
/// TODO: Update this doc as the config module is done
/// 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.
#[derive(Serialize, Deserialize)]
pub(crate) struct GlobalConfig {}
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
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,
}
/// Initializes a logger for logging purposes.
///
@ -80,3 +192,42 @@ 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

@ -327,7 +327,7 @@ pub fn parse_single_date(input: &str, context: Option<NaiveDate>) -> Result<Naiv
}
#[cfg(test)]
pub(crate) mod tests {
mod tests {
use super::*;
use crate::date::date_parse::DateRange;

View File

@ -112,6 +112,12 @@ pub enum IdleError {
/// 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,6 +1,6 @@
//! Submodule including all helper functions to handle vote creation and evolution
//!
use crate::votes::traits::BorrowInner;
use crate::{config::GlobalConfig, votes::traits::BorrowInner};
use chrono::NaiveDate;
use std::{
fs::{create_dir, File},
@ -206,12 +206,12 @@ 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
@ -240,6 +240,7 @@ impl EventHolder {
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()
})
}
@ -267,6 +268,7 @@ impl EventHolder {
NaiveDate,
save_path.to_owned() + "/old_date.json"
);
self.config.read().unwrap().try_save_to_disk()?;
Ok(())
}