Compare commits

...

65 Commits
main ... dev

Author SHA1 Message Date
Dandaedre faba5f1422 Update Jenkinsfile
Rust CI IdleFox passed all CI checks.
Gitea/idlefox/pipeline/head This commit looks good Details
2026-09-13 14:01:18 +02:00
Dandaedre 048be0e619 Update Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:49:51 +02:00
Dandaedre 3968fb97ff Update Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:44:32 +02:00
Dandaedre fec62385a0 Add Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:18:22 +02:00
Dandaedre fca5e8ef7a Some typos 2025-01-17 23:58:02 +01:00
Dandaedre af2f1ef2ea Updates some dependencies 2025-01-17 16:28:29 +01:00
Dandaedre cb88215e7f Adds a basic config and a handling of the reaction emotes 2025-01-16 17:52:23 +01:00
Dandaedre 773c5dd2ff coverage (#46)
Reviewed-on: #46
Co-authored-by: Dandaedre <max.beffroi@gmail.com>
Co-committed-by: Dandaedre <max.beffroi@gmail.com>
2024-12-05 16:48:54 +01:00
Dandaedre 0e3a7fb3ad Adds a blanket implementation and a trait for Borrowable inner dictionnary 2024-12-05 04:56:59 -06:00
Dandaedre 9a671a16e7 Adds a way to peak into inner values of event holders and generate truly unique ids 2024-12-04 21:28:56 +01:00
Dandaedre 4cbeadaeeb Changes names for import's sake 2024-12-04 08:15:45 -06:00
Dandaedre 53b8f1df3e Adds more persistence tests 2024-12-03 05:46:59 -06:00
Dandaedre e179620113 Adds a mock of (untested) persistence 2024-12-01 18:42:52 +01:00
Dandaedre bbd008b092 Changes uuid::id to String with human_ids 2024-12-01 17:33:13 +01:00
Dandaedre 1a055c7e2a Adds a little more testing and coverage 2024-11-30 18:19:46 +01:00
Dandaedre 7bb6b78352 Corrects a horrid mistake 2024-11-29 21:29:57 +01:00
Dandaedre 0d693eb299 Fixes several big mistakes and finishes cherry picking 2024-11-29 19:00:38 +01:00
Vicky 954f6a663b Reworked voting options and in particular modals 2024-11-29 18:21:55 +01:00
Dandaedre 4609d910da Adds a single helper function 2024-11-29 18:20:30 +01:00
Dandaedre 2ac6929ab1 Silly mistake made by having an await outside of the box.pin 2024-11-29 18:20:15 +01:00
Vicky 37af7715e8 Furthered fk_around a bit. Breaks very bad. 2024-11-26 14:06:39 +01:00
Dandaedre 9ac93d7cb3 Changed the vote parsing to be an inner struct to avoid using a status enum
Reviewed-on: #37
Co-authored-by: Dandaedre <max.rigaut@gmail.com>
Co-committed-by: Dandaedre <max.rigaut@gmail.com>
2024-11-10 05:10:14 +01:00
Dandaedre b4a3998ae4 Refactors votes into four files 2024-11-09 19:24:27 +01:00
Dandaedre 035aa514bc Trying out 2024-11-09 16:49:33 +01:00
Dandaedre bbbfbd4e31 Bandaid on the async, not sure it's really working as intended 2024-11-09 16:32:45 +01:00
Dandaedre 01b88dac09 Accepts merge from vky changes
Reviewed-on: #31
2024-11-07 21:21:46 +01:00
Dandaedre 275241172a Merge branch 'tentative_structure' into dev 2024-11-07 21:19:47 +01:00
Vicky 15c4630455 Added more on the handler 2024-11-07 11:52:56 +01:00
Vicky 692ef6389a minor typo edits 2024-11-07 10:41:04 +01:00
Dandaedre 47ffc337e8 Fills coverage and doctests 2024-11-07 00:51:00 +01:00
Dandaedre 199c7bd6c7 Updates tests and coverage 2024-11-06 23:41:16 +01:00
Dandaedre 1d74496a26 Updated some tests to add more coverage 2024-11-06 21:07:27 +01:00
Dandaedre 6780a56abe Adds a lot of testing and examples 2024-11-06 18:17:47 +01:00
Dandaedre e085c0e737 Adds a lot of test and docs and some of the votes/watchdog implementations 2024-11-06 18:17:47 +01:00
Dandaedre a356f978fd Adds some logic on the votes and watchdog 2024-11-06 18:17:47 +01:00
Vicky 0b7b1c49ad Added skeleton for the handler, and made sure VoteContainer is as future-proof as can be 2024-11-06 12:34:37 +01:00
Dandaedre 5e27a178ce Updates the doc changes some string into &str and updates coverage 2024-11-05 23:18:53 +01:00
Vicky de74a0abdd Replaced println with log, updated todo 2024-11-05 18:14:49 +01:00
Vicky aa79b75b59 Added test for levenshtein distance 2024-11-05 15:29:11 +01:00
Vicky 656a75b224 added role finding logic to modal 2024-11-05 15:10:20 +01:00
Vicky 8860dee7e6 Added more compatibilty with new structure 2024-11-05 12:29:54 +01:00
Dandaedre 1e02cfb3d1 Adds a blanket implementation of the Watchdog 2024-11-04 18:01:03 +01:00
Vicky f053fa222d Added VoteContainer and some placeholder functions 2024-11-04 16:32:16 +01:00
Vicky 1b6563464d added first draft of vote treatment structure 2024-11-04 12:36:05 +01:00
Dandaedre 530f8e6736 Adds a new entry function to parse
Adds more badges and a benchmark
2024-11-04 01:10:52 +01:00
Vicky 9647655f69 Update README.md
small tweaks and added new commands (vote_short and vote_long)
2024-11-03 22:52:40 +01:00
Dandaedre 39a9d065f4 Changes the readme to be a little better looking 2024-11-03 03:11:03 +01:00
Dandaedre 52775f26b7 Adds coverage (and a badge) to the project 2024-11-03 02:38:28 +01:00
Vicky 60519150d1 Added text commands /vote_long et /vote_short, added some doc 2024-11-02 20:20:27 +01:00
Dandaedre b9d3e59b0f Adds a lib and fixes all doctests 2024-11-02 19:09:54 +01:00
Dandaedre 936c5161e2 Adds all docs for date, adds functions to make a Naivedate from the parsed strings 2024-11-02 17:17:45 +01:00
Dandaedre 0c0aff7106 Adds more doc 2024-11-02 02:07:15 +01:00
Dandaedre 5649066bd9 Adds doc for the config and some of the date handling 2024-11-02 02:07:15 +01:00
Dandaedre 2c408403bd Update TODO.md
Signed-off-by: Dandaedre <max.rigaut+gitea@gmail.com>
2024-10-31 21:07:49 +01:00
Dandaedre e1a411e2e7 Separate votes into module, updates todo and silences some warnings 2024-10-31 17:35:19 +01:00
Dandaedre 71c7428c4e Adds all date parsing and refactors date into a module 2024-10-31 17:35:19 +01:00
Vicky 207bf2815c Merge pull request 'minor_doc' (#3) from minor_doc into dev
Reviewed-on: #3
2024-10-31 11:56:18 +01:00
Vicky 989f851eee Updated readme for /vote_command 2024-10-31 11:53:18 +01:00
Vicky b3eb0c8a73 added barebones doc 2024-10-31 11:53:18 +01:00
Dandaedre f3a2fc15a8 Adds a parser dependency and refactors the main loop 2024-10-31 11:47:52 +01:00
Dandaedre 0e98907d38 Adds a Todo, some basic logging and a couple of docs 2024-10-31 01:05:09 +01:00
Dandaedre 1513f25c76 Adds error handling and dates 2024-10-30 17:59:30 +01:00
Dandaedre 7c6fee6914 Adds a config file and implements a base votes structs 2024-10-30 17:55:39 +01:00
Vicky 43990f43a0 Renames the modal command to vote_modal and creates vote_command 2024-10-30 14:09:41 +01:00
Vicky ee29c47387 First draft of modal vote 2024-10-29 15:59:12 +01:00
32 changed files with 3897 additions and 42 deletions

19
.gitignore vendored
View File

@ -3,6 +3,8 @@
# 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
@ -14,8 +16,19 @@ 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
# A module summary
summary.md
config.json

1
.ignore Normal file
View File

@ -0,0 +1 @@
badges/*

View File

@ -4,6 +4,19 @@ version = "0.1.0"
edition = "2021"
[dependencies]
poise = "0.6.1"
tokio = { version = "1.41.0", features = ["rt-multi-thread"] }
chrono = { version = "0.4.38", features = ["serde"] }
human_ids = "0.1.1"
serde = { version = "1.0.214", features = ["alloc", "derive"] }
thiserror = "1.0.65"
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"] }
ron = "0.8.1"
distance = "0.4.0"
[profile.dev]
debug = 0
@ -16,3 +29,20 @@ panic = "abort"
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
[[bin]]
name = "idlefox"
path = "src/main.rs"
[lib]
name = "idlefox"
path = "src/lib.rs"
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "parser_benchmark"
harness = false

50
FEATURES.md Normal file
View File

@ -0,0 +1,50 @@
# List of commands and their inner workings
## `/vote_modal`
*Creates a new discord modal to walk the user through the creation of a new vote*
### Input
* title (String): The title for the futur event;
* short_name (Option<String>): Optional short name for the event;
* group (Option<String>): If specified, **must** be among the existing guildRoles in order for the bot to tag said guildRole;
* description (String): Description for the event;
* hours(Option<String>): Time window for the event.
### Output
> ## {title}
> @{group} {description}
> **{short_name} ; **{hours}**
Should the optional fields be left out, it could look like this:
> ## {title}
> {description}
> **21h - 23h**
## `/vote_command`
*More comprehensive, only-textual, version of vote_modal to create a new vote*
### Input
* title (String): The title for the futur event;
* short_name (Option<String>): Optional short name for the event;
* group (Option<String>): If specified, **must** be among the existing guildRoles in order for the bot to tag said guildRole;
* description (String): Description for the event;
* hours(Option<String>): Time window for the event;
* start_date(Option<String>): Date after which the bot will publish the vote in the first open-voting window (if it exists);
* non_days(Option<String>): Days for which the bot should replace the reaction from a number to a neutral emoji.
### Parsing logic
30/10/2024
> lun mar mer jeu ven sam dim
> le prochain jour qui correspond (a ce jour)
> ex: lun -> lun 4 nov
> 10, 21, 2
> le prochain jour qui correspond (a cette date)
> ex: 10 -> dim 10 nov
> 30 nov, 1 jan, 10 aou
> cette date exacte
> ex: 30 nov -> sam 30 nov
### Long votes
> Nouvel event!
> Description
> id: xxx
[Voter mes dispos] -> t'ouvre un modal
-> /dispo id: xxx date: 10 jan - 20 jan, 23 jan, 25 jan, 1 fev - 30 fev omit: 15 fev
-> /dispo id: xxx omit: 30 fev

326
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,326 @@
// 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,7 +1,46 @@
# idlefox
![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg)
A Rust Discord Bot, in charge of greatly simplifying the process of finding a meeting date, organising an event and choosing between several options.
A great emphasis is put on organizing the votes themselves, delaying posting them and editing the answers as time goes.
This bot also spins a web interface to allow real time monitoring of all activities and (for admins) close the votes via said interface
IdleFox is a feature-rich Discord bot designed to streamline the process of finding meeting dates, organizing events, and making decisions among multiple options. With its user-friendly commands and robust command system, IdleFox helps facilitate effective communication within server communities.
### Key Features
- **Advanced Date Handling**: IdleFox offers robust date parsing and manipulation, supporting complex date formats and context-aware conversions.
- **Find Meeting Dates**: Easily coordinate with your community through reaction-voting for dates.
- **Event Organization**: Start events to organize group activities, meetups, or campaigns.
- **Decision Making**: Use the bot's voting functionalities to make informed decisions among multiple options.
- **Vote Management**: Keep track of ongoing votes and manage their lifecycle from initiation to closure.
- **Vote Organization**: Delays vote posting and allows continuous editing of answers as time progresses.
- **Web Interface**: Provides monitoring of all activities and enables admins to close votes through a web interface.
## Bot Components
- `main.rs`: Initializes logging and starts the main loop for handling Discord interactions.
- `config.rs`: Manages configuration settings for the bot, ensuring data persistence and recovery.
- `date/`: Provides functionalities for date parsing, conversion, and manipulation.
- `dateparse.rs`: Parses input strings into date objects using nom parsers.
- `date_tools.rs`: Transforms dates into more precise formats based on context.
- `io.rs`: Interacts with Discord through Serenity and Poise libraries to handle commands and events.
- `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.
- `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.
This bot also spins a web interface to allow real time monitoring of all activities and (for admins) close the votes via said interface
## List of commands
* `/vote_modal` Pops up a modal (discord form) helping the user through creating a vote.
* `/vote_command` Comprehensive text command for creating a vote.
* `/vote_short` Creates an exceptional (non-weekly) vote. This is used for events outside of the normal voting window and can't go above 7 days-options.
* `/vote_long` Creates a vote for a long period of time (from 8 days to 12 months). This is used for important events that must be planned extremely long in advance.
### Contributing
IdleFox welcomes contributions from the community. To contribute, fork the repository, make your changes, and submit a pull request for review.
### License
This project is licensed under the MIT License. For more information, see the LICENSE file.

1
badges/coverage.svg Normal file
View File

@ -0,0 +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>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/test.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" 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-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></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="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/version.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.1.0"><title>version: 0.1.0</title><linearGradient id="bms-0431e50b7af7883f" 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-0431e50b7af7883f"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0431e50b7af7883f)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-0431e50b7af7883f)"/></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="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.1.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.1.0</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,23 @@
use chrono::NaiveDate;
use criterion::{criterion_group, criterion_main, Criterion};
use idlefox::date::parse_date_list;
use std::hint::black_box;
fn complex_date_parse(input: &str) -> usize {
let context = NaiveDate::from_ymd_opt(2023, 10, 1);
let list = parse_date_list(input, context).unwrap();
list.len()
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("complex_date_parse", |b| {
b.iter(|| {
complex_date_parse(black_box(
"Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text",
))
})
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

1
src/.token Normal file
View File

@ -0,0 +1 @@
MTMwMDc2ODk2MTgwNTI5MTUzMA.GlMP_L.PU1953SsJ-8naI2rXSRLZuZw1jzV7CgckYtOSk

234
src/config.rs Normal file
View File

@ -0,0 +1,234 @@
//! # IdleFox Configuration Module
//!
//! 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.
//! 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.
//! * **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.
//!
//! ### Usage
//!
//! To use this module effectively, you can follow these steps:
//!
//! 1. Use the `init_logger()` function from the IdleFox logging module (as shown below) to initialize the logger with your custom log level and output destination.
//!
//! Example usage:
//!
//! ```rust
//! # use idlefox::config;
//! # fn main() {
//! // Initialize the logger with a custom log level of info
//! config::init_logger().expect("Failed to initialize logger");
//! // Log some messages at different levels (e.g., debug, warn, error)
//! let message = "This is an example message";
//! log::warn!("{}", message);
//! log::error!("{}", message);
//! # }
//!
#![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};
pub type WeeklyReactionList = Vec<ReactionType>;
/// 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 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,
}
/// Initializes a logger for logging purposes.
///
/// This function sets up two loggers: one for terminal output (with warning level) and another for file-based logging (with info level).
///
/// The terminal logger will display warnings, while the file logger will write all logs at or above the info level to an "idlefox.log" file in the current working directory.
///
/// # Examples
///
/// ```
/// idlefox::config::init_logger().expect("Failed to initialize logger");
/// // Log a message at the info level.
/// log::info!("This will be written to idlefox.log");
///
/// // Log a warning at the warn level, which should appear on screen as well.
/// log::warn!("Warning: This will be written on file and on screen");
/// ```
///
#[cfg(not(tarpaulin_include))]
pub fn init_logger() -> Result<(), IdleError> {
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(),
),
])
.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());
}
}

406
src/date/date_parse.rs Normal file
View File

@ -0,0 +1,406 @@
//! The module provides functions for parsing date strings into Rust structs.
//! The pseudo grammar is defined as:
//! ```py
//! date = (day) (month) | (month) (day) | (weekday)
//! daterange = (date) - (date)
//! dateobject = (date) | (daterange)
//! datelist = (dateobject) (, (dateobject))*
//! ```
//! All strings parsed will be parsed into a [DateList], as the function [parse_str_into_date] always assume you are providing it a list of ranges.
//! Parsing a single date is outside of the scope of this module and should be implemented separately if needed.
//!
//! Please note that while an invalid input will return an error, a partially valid input will yield partial results.
//!
//! # Functions
//! The following functions are used to parse user data:
//! * [parse_simple_date]
//! ### Usage
//! ```
//! use idlefox::date::parse_str_into_date;
//! let result = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14");
//!
//! // Parses into 12 dec - 23 feb
//! let partial_result = parse_str_into_date("12 dec - 23 febelunmer");
//! ```
#![allow(dead_code)]
use chrono::{Month, Weekday};
use nom::{
branch::alt,
bytes::complete::tag_no_case,
character::complete::{char, digit1, space0},
combinator::{map, value},
multi::separated_list1,
sequence::{delimited, separated_pair, tuple},
IResult, ParseTo,
};
/// The DatePoint enum represents a single relative date, which can be either a day and an optional month or a weekday.
///
/// ### Parsing
/// The date is parsed from the following formats:
/// * ``Day (Month)?`` - with ``Day`` as a day as a ``(\d)+`` and month as a two or three letter str. Specifies a day and an optional month.
/// * ``WeekDay`` - with ``WeekDay`` as a three letter str. Specifies a weekday.
///
/// ### Data Structure
/// * Date: Represents a day specified by its position in the month, along with an optional month.
/// * day: The day of the month.
/// * month: An optional Month enum value (see [chrono::Month]).
/// * Weekday: Represents a Weekday (as in Mon, Tue, etc.). (see [chrono::Weekday])
///
/// ### Examples
/// ```
/// # use chrono::{Month, Weekday};
/// # use idlefox::date::date_parse::DatePoint;
/// // Manually create a date with day and month
/// let date_point1 = DatePoint::Date { day: 15, month: Some(Month::January) };
/// // Manually create a weekday
/// let date_point3 = DatePoint::Weekday(Weekday::Mon);
/// ```
#[derive(Debug, Clone, Copy)]
#[cfg_attr(test, derive(PartialEq))]
pub enum DatePoint {
/// A day specified by it's position in the month, and an optionnal month
Date {
/// The day of the month
day: u32,
/// An optional month
month: Option<Month>,
},
/// A weekday (as in Mon, Tue, etc..)
Weekday(Weekday),
}
/// The DateRange struct represents a date range, encompassing a starting point and an endpoint.
///
/// ### Parsing
/// The date range is parsed from the following format:
/// * ``DatePoint - DatePoint`` - with DatePoint as a [DatePoint]
///
/// ### Data Structure
/// • start: The starting date in the range.
/// • stop: The end date in the range.
/// ### Examples
/// ```
/// # use chrono::Month;
/// # use idlefox::date::date_parse::{DatePoint, DateRange};
/// // Create a date range from two DatePoint values
/// let date_range = DateRange {
/// start: DatePoint::Date { day: 1, month: Some(Month::January) },
/// stop: DatePoint::Date { day: 31, month: Some(Month::December) },
/// };
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct DateRange {
/// The starting date in the range
pub start: DatePoint,
/// The end date in the range
pub stop: DatePoint,
}
/// The DateObject enum represents the main date structure, which can be either a date range or a single date.
///
/// ### Parsing
/// The date object is parsed from the following formats:
/// * [DateRange]: Represents a range between two relative dates.
/// * [DatePoint]: Represents a single date.
///
///
/// ### Examples
/// ```
/// # use chrono::Month;
/// # use idlefox::date::date_parse::{DateObject, DatePoint, DateRange};
/// // Create a DateObject representing a range
/// let date_object1 = DateObject::Range(DateRange {
/// start: DatePoint::Date { day: 1, month: Some(Month::January) },
/// stop: DatePoint::Date { day: 31, month: Some(Month::December) },
/// });
///
/// // Create a DateObject representing a single date
/// let date_object2 = DateObject::Single(DatePoint::Date { day: 15, month: Some(Month::February) });
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum DateObject {
/// A range between two relative dates
Range(DateRange),
/// A single date
Single(DatePoint),
}
// struct DateList {
// inner: Vec<DateObject>,
// }
/// The DateList type represents a list of dates, which can contain either single dates or date ranges.
///
/// ### Parsing
/// The date list is parsed from the following format:
/// * ``DateObject (, DateObject)*`` - with ``DateObject`` as a [DateObject]
///
/// ### Data Structure
/// A vector of DateObject elements.
///
/// ### Examples
/// ```
/// # use chrono::Month;
/// # use idlefox::date::date_parse::{DateList, DateObject, DatePoint, DateRange};
/// // Create a DateList with a single date and a range
/// let date_list = DateList::from(vec![
/// DateObject::Single(DatePoint::Date {
/// day: 15,
/// month: Some(Month::January),
/// }),
/// DateObject::Range(DateRange {
/// start: DatePoint::Date {
/// day: 1,
/// month: Some(Month::February),
/// },
/// stop: DatePoint::Date {
/// day: 28,
/// month: Some(Month::February),
/// },
/// }),
/// ]);
/// ```
pub type DateList = Vec<DateObject>;
/// The parse_month function parses a month from a given input string. It supports both French and English denominations.
///
/// ### Parsing Logic
/// The function uses the [nom::branch::alt] combinator to handle both French and English month denominations.
/// Each denomination is represented by an alt combinator that matches the corresponding month value.
fn parse_month(input: &str) -> IResult<&str, Month> {
alt((
alt((
value(Month::January, tag_no_case("jan")),
value(Month::February, tag_no_case("fev")),
value(Month::February, tag_no_case("feb")),
value(Month::March, tag_no_case("mar")),
value(Month::March, tag_no_case("avr")),
value(Month::April, tag_no_case("apr")),
value(Month::May, tag_no_case("mai")),
value(Month::May, tag_no_case("may")),
value(Month::June, tag_no_case("juin")),
value(Month::June, tag_no_case("jun")),
value(Month::July, tag_no_case("juil")),
value(Month::July, tag_no_case("jul")),
value(Month::August, tag_no_case("aou")),
value(Month::August, tag_no_case("aug")),
value(Month::September, tag_no_case("sep")),
value(Month::October, tag_no_case("oct")),
value(Month::November, tag_no_case("nov")),
value(Month::December, tag_no_case("dec")),
)),
alt((
value(Month::January, tag_no_case("jr")),
value(Month::February, tag_no_case("fr")),
value(Month::March, tag_no_case("ms")),
value(Month::April, tag_no_case("al")),
value(Month::May, tag_no_case("mi")),
value(Month::June, tag_no_case("jn")),
value(Month::July, tag_no_case("jt")),
value(Month::August, tag_no_case("at")),
value(Month::September, tag_no_case("se")),
value(Month::October, tag_no_case("oe")),
value(Month::November, tag_no_case("ne")),
value(Month::December, tag_no_case("de")),
)),
))(input)
}
/// The parse_weekday function parses a weekday from a given input string.
/// It supports both French and English weekday abbreviations.
///
/// ### Parsing Logic
/// The function uses the [nom::sequence::delimited] combinator to remove leading and trailing spaces from the input string.
/// Inside the delimiter, it uses the [nom::branch::alt] combinator to match any of the supported weekday abbreviations.
///
/// ### Errors
/// Will return an Error if the input can't be matched to a day
fn parse_weekday(input: &str) -> IResult<&str, Weekday> {
delimited(
space0,
alt((
value(Weekday::Mon, tag_no_case("mon")),
value(Weekday::Mon, tag_no_case("lun")),
value(Weekday::Tue, tag_no_case("tue")),
value(Weekday::Tue, tag_no_case("mar")),
value(Weekday::Wed, tag_no_case("wed")),
value(Weekday::Wed, tag_no_case("mer")),
value(Weekday::Thu, tag_no_case("thu")),
value(Weekday::Thu, tag_no_case("jeu")),
value(Weekday::Fri, tag_no_case("fri")),
value(Weekday::Fri, tag_no_case("ven")),
value(Weekday::Sat, tag_no_case("sat")),
value(Weekday::Sat, tag_no_case("sam")),
value(Weekday::Sun, tag_no_case("sun")),
value(Weekday::Sun, tag_no_case("dim")),
)),
space0,
)(input)
}
/// The parse_simple_date function parses a single date from a given input string.
/// It supports different date formats:
/// * Day (Month)?
/// * (Month)? Day
/// * Day
///
/// ### Parsing Logic
/// The function uses the [nom::branch::alt] combinator to handle the different date formats.
/// Each format is represented by a separate [nom::combinator::map] combinator that extracts
/// the necessary date information and constructs the DatePoint object.
pub fn parse_simple_date(input: &str) -> IResult<&str, DatePoint> {
alt((
map(
tuple((space0, parse_month, space0, digit1, space0)),
|(_, month, _sep, day, _)| DatePoint::Date {
day: day.parse_to().unwrap(),
month: Some(month),
},
),
map(
tuple((space0, digit1, space0, parse_month, space0)),
|(_, day, _, month, _)| DatePoint::Date {
day: day.parse_to().unwrap(),
month: Some(month),
},
),
map(delimited(space0, digit1, space0), |day: &str| {
DatePoint::Date {
day: day.parse_to().unwrap(),
month: None,
}
}),
map(parse_weekday, DatePoint::Weekday),
))(input)
}
/// The parse_date_object function parses a single date object from a given input string.
/// It supports two formats:
/// * Date - Date
/// * Date
/// ### Parsing Logic
///
/// The function uses the [nom::branch::alt] combinator to handle the two date formats.
/// Each format is represented by a separate [nom::combinator::map] combinator that parses the date range or single date object.
/// ### Examples
/// ```
/// # use idlefox::date::date_parse::parse_date_object;
/// // Parse "20dec -31jan"
/// let result1 = parse_date_object("20dec -31jan").unwrap();
///
/// // Parse "Lun"
/// let result2 = parse_date_object("Lun").unwrap();
/// ```
pub fn parse_date_object(input: &str) -> IResult<&str, DateObject> {
alt((
map(
separated_pair(parse_simple_date, char('-'), parse_simple_date),
|(start, stop)| DateObject::Range(DateRange { start, stop }),
),
map(parse_simple_date, DateObject::Single),
))(input)
}
/// The parse_str_into_date function parses a list of date objects from a given input string.
/// Each date object is separated by a comma.
///
/// ### Parsing Logic
///
/// The function uses the [nom::multi::separated_list1] combinator to parse a list of date objects separated by commas.
/// Each date object is then parsed again using the [parse_date_object] function.
/// # Examples
/// ```
/// # use idlefox::date::parse_str_into_date;
/// // Parse "12 dec - 23 feb, lun - mer, 12, 14"
/// let list_dates = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14").unwrap();
/// ```
pub fn parse_str_into_date(input: &str) -> IResult<&str, Vec<DateObject>> {
separated_list1(char(','), parse_date_object)(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parsing() {
let (leftover_input, output) = parse_month("jan €rré jan feb v").unwrap();
assert_eq!(leftover_input, " €rré jan feb v");
assert_eq!(output, Month::January);
let (leftover_input, output) =
parse_str_into_date(" 10 jan €rré10 jan 10 jan").unwrap();
assert_eq!(leftover_input, "€rré10 jan 10 jan");
let result = [DateObject::Single(DatePoint::Date {
day: 10,
month: Some(Month::January),
})];
test_dates(&output, &result);
let (leftover_input, output) = parse_str_into_date(" 10 jan 20").unwrap();
assert_eq!(leftover_input, "20");
let result = [DateObject::Single(DatePoint::Date {
day: 10,
month: Some(Month::January),
})];
test_dates(&output, &result);
let (leftover_input, output) = parse_str_into_date("feb 10 jan 20").unwrap();
assert_eq!(leftover_input, "jan 20");
let result = [DateObject::Single(DatePoint::Date {
day: 10,
month: Some(Month::February),
})];
test_dates(&output, &result);
let (leftover_input, output) =
parse_str_into_date(" 10 jan - 10 jan, tue , 23,mon-tue,").unwrap();
assert_eq!(leftover_input, ",");
let result = [
DateObject::Range(DateRange {
start: DatePoint::Date {
day: 10,
month: Some(Month::January),
},
stop: DatePoint::Date {
day: 10,
month: Some(Month::January),
},
}),
DateObject::Single(DatePoint::Weekday(Weekday::Tue)),
DateObject::Single(DatePoint::Date {
day: 23,
month: None,
}),
DateObject::Range(DateRange {
start: DatePoint::Weekday(Weekday::Mon),
stop: DatePoint::Weekday(Weekday::Tue),
}),
];
test_dates(&output, &result);
}
fn test_dates(output: &Vec<DateObject>, result: &[DateObject]) {
println!("{:?}", output);
for (a, b) in output.iter().zip(result.iter()) {
println!("Found: {:?}. Expected: {:?}", a, b);
assert_eq!(a, b);
}
}
}
// Procedural approach, in case all fails
// /// Parse all DatesObjects separated by commas
// fn parse_date_input(input: &str) -> Result<Vec<&str>, IdleError> {
// let (_, list_date) = separated_list0(char(','), complete::is_not(","))(input)?;
// // let find_ranges= list_date.iter().map(|date| separated_pair(, , )).collect();
// Ok(list_date)
// }
// // /// Parse all DatesObjects separated by commas
// fn parse_all_commas(input: &str) -> IResult<&str, Vec<&str>> {
// separated_list0(char(','), complete::is_not(","))(input)
// }

519
src/date/date_tools.rs Normal file
View File

@ -0,0 +1,519 @@
//! Utilities to handle date and relative date selection
use crate::{date::date_parse::parse_simple_date, error_handling::IdleError};
use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday};
use serde::{Deserialize, Serialize};
use super::{
date_parse::{DateObject, DatePoint},
parse_str_into_date,
};
/// 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
///
/// # Arguments
///
/// * `day`: The desired weekday.
/// * `context`: An optional date to use as a reference for calculating the relative day.
/// If not provided, the current date plus one week is used.
///
/// # Returns
///
/// A [NaiveDate] representing the calculated date based on the given weekday and context.
///
/// # Example
///
/// ```rust
/// # use chrono::{Weekday, Local};
/// # use idlefox::date::date_tools::relative_day_to_date;
/// let today = Local::now().date_naive();
/// // Get the date for next Monday relative to today
/// let monday = relative_day_to_date(Weekday::Mon, Some(today));
/// ```
pub fn relative_day_to_date(weekday: Weekday, context: Option<NaiveDate>) -> NaiveDate {
let context = context.unwrap_or(Local::now().date_naive()) + Duration::weeks(1);
let offset = context.weekday() as i64 - weekday as i64;
context - Duration::days(offset)
}
/// The relative_date_to_date function finds the date corresponding to a loosely defined implicit partial date.
///
/// The date returned will be the next valid date after the context.
///
/// ### Arguments
///
/// • date: The partial date to convert.
/// • context: An optional context date. If no context is given, the date will be inferred as the next valid date from now.
///
/// ### Returns
///
/// A [chrono::NaiveDate] representing the date corresponding to the given partial date in the context of the provided date.
///
/// ### Example
/// ```
/// # use chrono::NaiveDate;
/// # use idlefox::date::date_tools::relative_date_to_date;
/// // In this context we are trying to get the dates relative to the 14th of the month
/// let context_date = NaiveDate::from_ymd_opt(2023, 2, 14).unwrap();
/// // Get the next 16, relative to our context
/// let date = relative_date_to_date(16, None, Some(context_date)).unwrap();
/// assert_eq!(date, NaiveDate::from_ymd_opt(2023, 2, 16).unwrap()); // The next 16th in in february
/// // Get the next 1st, relative to our context
/// let date = relative_date_to_date(1, None, Some(context_date)).unwrap();
/// assert_eq!(date, NaiveDate::from_ymd_opt(2023, 3, 1).unwrap()); // The next 1st in in march, the next month
/// ```
pub fn relative_date_to_date(
day: u32,
month: Option<Month>,
context: Option<NaiveDate>,
) -> Result<NaiveDate, IdleError> {
let context = context.unwrap_or(Local::now().date_naive());
let mut new_dat = NaiveDate::from_ymd_opt(
context.year_ce().1 as i32,
match month {
Some(m) => m.number_from_month(),
None => context.month(),
},
day,
)
.ok_or(IdleError::InvalidDate(day, month))?;
if month.is_none() && day < context.day() {
new_dat = new_dat.checked_add_months(Months::new(1)).unwrap();
}
if new_dat.month() < context.month() {
new_dat = new_dat.checked_add_months(Months::new(12)).unwrap();
}
Ok(new_dat)
}
impl DatePoint {
/// Converts a DatePoint to a NaiveDate, optionally relative to a given context date.
///
/// The conversion depends on the specific type of [DatePoint]:
/// - For `DatePoint::Date { day, month }`, it calculates the next valid date after the provided or current context.
/// - For `DatePoint::Weekday(weekday)`, it finds the next occurrence of that weekday relative to the context.
///
/// # Arguments
///
/// * `self`: The [DatePoint] to convert.
/// * `context`: An optional reference date. If not provided, the function uses the current date as a default.
///
/// # Returns
///
/// A Result containing a [NaiveDate] if successful, or an [IdleError] if the date could not be calculated due to invalid input.
///
/// # Examples
///
/// ```
///use chrono::{Local, Month};
///use idlefox::date::date_parse::{DateObject, DatePoint};
///let today = Local::now().date_naive();
///let date_point = DatePoint::Date {
/// day: 14,
/// month: Some(Month::February),
///};
///let next_valid_date_object = DateObject::Single(date_point);
///let naive_date = next_valid_date_object
/// .to_naive_date_object(Some(today))
/// .unwrap();
/// ```
fn to_naive_date(self, context: Option<NaiveDate>) -> Result<NaiveDate, IdleError> {
match self {
DatePoint::Date { day, month } => relative_date_to_date(day, month, context),
DatePoint::Weekday(weekday) => Ok(relative_day_to_date(weekday, context)),
}
}
}
/// An enum representing either a single [NaiveDate] or a date range between two [NaiveDate].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
// #[cfg_attr(test, derive(PartialEq))]
pub enum NaiveDateObject {
/// A range between two dates, inclusive at both ends.
Range {
/// Start of the range
start: NaiveDate,
/// End of the range
stop: NaiveDate,
},
/// A single [NaiveDate] object.
Single(NaiveDate),
}
/// A collection of [NaiveDateObject]s, allowing for sequential and random access to their start dates.
///
/// 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))]
pub struct NaiveDateList {
/// The inner vector
inner: Vec<NaiveDateObject>,
/// The leftover, unparsed string
unparsed: Option<String>,
}
impl DateObject {
/// Converts this [DateObject] to a corresponding [NaiveDateObject], using the provided context for relative date calculations.
///
/// # Examples
///
/// ```
/// # use idlefox::date::date_parse::{DateObject, DatePoint};
/// # use chrono::{Local, Month};
/// let today = Local::now().date_naive();
/// let date_point = DatePoint::Date {
/// day: 14,
/// month: Some(Month::March),
/// }; // February 14
/// let next_valid_date_object = DateObject::Single(date_point);
/// let naive_date = next_valid_date_object
/// .to_naive_date_object(Some(today))
/// .unwrap();
/// ```
pub fn to_naive_date_object(
&self,
context: Option<NaiveDate>,
) -> Result<NaiveDateObject, IdleError> {
match self {
DateObject::Range(date_range) => {
// This shenenigan is important otherwise very long ranges can overlap and become negative making no sense
let start = date_range.start.to_naive_date(context)?;
Ok(NaiveDateObject::Range {
start,
stop: date_range.stop.to_naive_date(Some(start))?,
})
}
DateObject::Single(date_point) => {
Ok(NaiveDateObject::Single(date_point.to_naive_date(context)?))
}
}
}
}
impl NaiveDateList {
/// Creates a new [NaiveDateList] from an existing vector of [NaiveDateObject]s.
pub fn new(inner: Vec<NaiveDateObject>, unparsed: Option<&str>) -> Self {
Self {
inner,
unparsed: unparsed.map(|v| v.to_string()),
}
}
/// Returns the number of dates in this [NaiveDateList].
pub fn len(&self) -> usize {
self.inner.len()
}
/// Checks if this [NaiveDateList] is empty.
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Retrieves a reference to the [NaiveDateObject] at the specified index.
pub fn get(&self, index: usize) -> Option<&NaiveDateObject> {
self.inner.get(index)
}
/// Creates a new [NaiveDateList] from an existing vector of [DateObject]s and a context date.
///
/// The `context` is used to resolve any relative dates in the `inner` list.
///
/// # Examples
///
/// ```
/// # use chrono::Local;
/// # use idlefox::date::{
/// # date_parse::{DateObject, DatePoint},
/// # date_tools::NaiveDateList,
/// # };
/// let today = Local::now().date_naive();
/// let date_point = DatePoint::Date {
/// day: 14,
/// month: Some(chrono::Month::January),
/// };
/// let next_valid_date_object = DateObject::Single(date_point);
/// let list = NaiveDateList::from_context(vec![next_valid_date_object], Some(today), None);
/// assert!(list.is_ok());
/// ```
pub fn from_context(
inner: Vec<DateObject>,
context: Option<NaiveDate>,
unparsed: Option<&str>,
) -> Result<Self, IdleError> {
let mut new = Vec::new();
for elem in inner {
new.push(elem.to_naive_date_object(context)?);
}
Ok(Self {
inner: new,
unparsed: unparsed.map(|v| v.to_owned()),
})
}
}
// // TODO: If needed, make an iterator over all dates that this list of date encompasses
// impl IntoIterator for NaiveDateList {
// type Item = NaiveDateObject;
// type IntoIter = std::vec::IntoIter<Self::Item>;
// fn into_iter(self) -> Self::IntoIter {
// self.inner.into_iter()
// }
// }
/// This function parses a given input string representing date information and returns a `NaiveDateList`,
/// which is a collection of sequential or random accessible date objects. 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.
///
/// # Arguments
///
/// * `input` - A string slice containing the date information to be parsed. This string may include various date formats,
/// single or range of dates, and possibly unparsed text.
/// * `context` - An optional NaiveDate that provides a context for resolving relative dates within the input. If no context
/// is provided, the function will attempt to use today's date as a fallback.
///
/// # Returns
///
/// A Result containing a `NaiveDateList` on success or an `IdleError` if parsing fails. The `Result` also includes any
/// unparsed text that was left over after processing the input string.
///
/// # Examples
///
/// ```
/// # use idlefox::date::parse_date_list;
/// # use chrono::NaiveDate;
/// let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fry and some other text";
/// let context = NaiveDate::from_ymd_opt(2023, 10, 1);
/// let result = parse_date_list(input, context);
/// assert!(result.is_ok());
/// match result {
/// Ok(date_list) => println!("Parsed dates: {}", date_list.len()),
/// Err(e) => eprintln!("Error parsing dates: {}", e),
/// }
/// ```
pub fn parse_date_list(
input: &str,
context: Option<NaiveDate>,
) -> Result<NaiveDateList, IdleError> {
let (leftover, objects) = match parse_str_into_date(input)? {
("", objects) => (None, objects),
(leftover, objects) => (Some(leftover), objects),
};
NaiveDateList::from_context(objects, context, leftover)
}
/// This function parses a given input string representing a single date and returns a `NaiveDate`.
/// The function uses the context provided to resolve any relative dates within the input string.
///
/// # Arguments
/// * `input` - A string slice containing the date information to be parsed. This string may include various date formats,
/// and possibly unparsed text.
/// * `context` - An optional NaiveDate that provides a context for resolving relative dates within the input. If no context
/// is provided, the function will attempt to use today's date as a fallback.
///
/// # Returns
/// A Result containing a `NaiveDate` on success or an `IdleError` if parsing fails.
pub fn parse_single_date(input: &str, context: Option<NaiveDate>) -> Result<NaiveDate, IdleError> {
// As we simply ignore the leftover, we can directly call the to_naive_date method
parse_simple_date(input)?.1.to_naive_date(context)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::date::date_parse::DateRange;
#[test]
fn test_relative_days() {
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()
);
}
#[test]
fn test_relative_date() {
let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap());
assert_eq!(
relative_date_to_date(16, Some(Month::December), context).unwrap(),
NaiveDate::from_ymd_opt(2024, 12, 16).unwrap()
);
assert_eq!(
relative_date_to_date(7, Some(Month::January), context).unwrap(),
NaiveDate::from_ymd_opt(2025, 1, 7).unwrap()
);
assert_eq!(
relative_date_to_date(17, None, context).unwrap(),
NaiveDate::from_ymd_opt(2024, 11, 17).unwrap()
);
assert_eq!(
relative_date_to_date(5, None, context).unwrap(),
NaiveDate::from_ymd_opt(2024, 12, 5).unwrap()
);
assert!(relative_date_to_date(52, None, None).is_err());
// TODO: Do we consider this to be normal behaviour ?
assert!(relative_date_to_date(
31,
Some(Month::February),
NaiveDate::from_ymd_opt(2020, 1, 30)
)
.is_err());
assert_eq!(
relative_date_to_date(
12,
Some(Month::February),
NaiveDate::from_ymd_opt(2020, 1, 30)
)
.unwrap(),
NaiveDate::from_ymd_opt(2020, 2, 12).unwrap()
);
}
#[test]
fn test_impl_date() {
let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap());
assert_eq!(
DatePoint::Weekday(Weekday::Mon)
.to_naive_date(context)
.unwrap(),
NaiveDate::from_ymd_opt(2024, 11, 11).unwrap()
);
assert_eq!(
DatePoint::Date {
day: 10,
month: Some(Month::January)
}
.to_naive_date(context)
.unwrap(),
NaiveDate::from_ymd_opt(2025, 1, 10).unwrap()
);
}
#[test]
fn test_impl_dateobj() {
let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap());
let date_a = DatePoint::Date {
day: 10,
month: Some(Month::January),
};
let date_b = DatePoint::Date {
day: 21,
month: Some(Month::December),
};
assert_eq!(
DateObject::Single(date_a)
.to_naive_date_object(context)
.unwrap(),
NaiveDateObject::Single(NaiveDate::from_ymd_opt(2025, 1, 10).unwrap())
);
let date_obj = DateObject::Range(DateRange {
start: date_a,
stop: date_b,
})
.to_naive_date_object(context)
.unwrap();
assert_eq!(
date_obj,
NaiveDateObject::Range {
start: NaiveDate::from_ymd_opt(2025, 1, 10).unwrap(),
stop: NaiveDate::from_ymd_opt(2025, 12, 21).unwrap()
}
);
let vec_obj = NaiveDateList::new(vec![date_obj.clone()], None);
assert_eq!(vec_obj.len(), 1);
assert!(!vec_obj.is_empty());
assert_eq!(vec_obj.get(0).unwrap(), &date_obj);
assert!(!NaiveDateList::from_context(
vec![DateObject::Single(date_a), DateObject::Single(date_a)],
context,
None,
)
.unwrap()
.is_empty());
assert!(NaiveDateList::from_context(
vec![
DateObject::Single(DatePoint::Date {
day: 32,
month: None
}),
DateObject::Single(date_a)
],
context,
None,
)
.is_err());
}
#[test]
fn test_date_list() {
use chrono::NaiveDate;
let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text";
let context = NaiveDate::from_ymd_opt(2023, 10, 1);
let list = parse_date_list(input, context).unwrap();
assert_eq!(list.unparsed, Some("and some other text".to_string()));
assert_eq!(list.len(), 5);
let input = "Oct 5, Nov 15";
let list = parse_date_list(input, None).unwrap();
assert_eq!(list.unparsed, None);
assert_eq!(list.len(), 2);
}
#[test]
fn test_serialisation() {
let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text";
let context = NaiveDate::from_ymd_opt(2023, 10, 1);
let list = parse_date_list(input, context).unwrap();
let s = ron::to_string(&list).unwrap();
// 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);
}
}
}

65
src/date/mod.rs Normal file
View File

@ -0,0 +1,65 @@
//! The `date` module provides functionality to parse dates from strings and perform operations on dates.
//!
//! It consists of two submodules:
//!
//! - `dateparse`: This submodule is responsible for parsing a string representation of a date into a vector of [date_parse::DateObject] instances.
//! It utilizes in house representation of date as they are without context and therefore dont represent a real date yet.
//!
//! - `date_tools`: This submodule offers utility functions for working with dates.
//! It's main goal is do give a context for a subjective and incomplete date to transform it into a [chrono::NaiveDate] type from the chrono crate.
//!
//! # Functions
//!
//! The following functions are re-exported from the `date_tools` submodule:
//!
//! - [parse_date_list]: This function parses a given input string representing date information and returns a `NaiveDateList`,
//! which is a collection of sequential or random accessible date objects. 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.
//!
//! - [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.
//!
//! # Examples
//!
//! ```
//! # use idlefox::date::parse_date_list;
//! # use chrono::NaiveDate;
//! let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fry and some other text";
//! let context = NaiveDate::from_ymd_opt(2023, 10, 1);
//! let result = parse_date_list(input, context);
//! assert!(result.is_ok());
//! match result {
//! Ok(date_list) => println!("Parsed dates: {}", date_list.len()),
//! Err(e) => eprintln!("Error parsing dates: {}", e),
//! }
//! ```
#![allow(dead_code)]
// 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 {}
// Defines date routines
pub mod date_parse;
pub mod date_tools;
// Republishing important functions
pub use date_parse::parse_str_into_date;
pub use date_tools::parse_date_list;
pub use date_tools::parse_single_date;
pub use date_tools::NaiveDateList;
pub use date_tools::NaiveDateObject;
// pub use date_tools::naivelistfromstr;
// pub use date_tools::naivedayfromstr;

147
src/error_handling.rs Normal file
View File

@ -0,0 +1,147 @@
//! This module provides a set of error types that can be used to handle various issues
//! with interacting with the Discord API or handling date-related tasks.
//!
//! The errors in this module are designed to provide detailed information about what
//! went wrong, making it easier to diagnose and fix problems.
#![allow(dead_code)]
use chrono::Month;
use log::SetLoggerError;
use poise::serenity_prelude;
use thiserror::Error;
use crate::ids::EventIdType;
/// Global error struct for idlefox
///
/// This enum represents various errors that can occur when interacting with most of the section of the program
#[derive(Error, Debug)]
pub enum IdleError {
/// Error indicating a critical failure in the Discord API interaction
///
/// This error is raised when an unrecoverable issue occurs while interfacing with the Discord API.
/// It may be recoverable by retrying the request or seeking assistance from the API provider.
#[error("An unrecoverable error occurred during Discord API interaction")]
GenericApiFailure,
/// Error indicating an invalid date format or an invalid date (dec 32, feb 30, etc..)
///
/// This error is raised when a user-provided date string cannot be parsed into a valid (date, month).
#[error("An error happened while tring to make sense of the date ({0:?},{1:?})")]
InvalidDate(u32, Option<Month>),
/// Generic error indicating an unexpected issue during Discord API call processing
///
/// This error is raised when an unforeseen issue occurs while handling a Discord API request.
/// It may be recoverable by re-trying the request or seeking assistance from the API provider.
#[error("An unexpected error occurred during Discord API processing: {0}")]
ApiProcessingError(#[from] serenity_prelude::Error),
/// Error indicating an invalid date string
///
/// This error is raised when a user-provided date string cannot be parsed into a valid [crate::date::date_parse::DatePoint].
/// Notifying the user and asking for manual correction will likely be required
#[error("An error occured while parsing the date given {0:?}")]
InvalidDateParsing(nom::Err<nom::error::Error<Box<str>>>),
/// Error indicating an issue with logging initialization
///
/// This error is raised when a critical issue occurs during logging initialization.
/// It may indicate that the file reader is read-only, and manual intervention will be required to resolve the problem.
#[error("An error occurred while initializing the logger: {0}")]
LoggerInitFailure(#[from] SetLoggerError),
/// 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.
#[error("An event couldn't be launched (Id: {0})")]
EventLaunch(EventIdType),
/// 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.
#[error("One or more events couldn't be removed from the ongoing events list (Id(s): {0:?})")]
EventPrune(Vec<EventIdType>),
/// 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
/// does not correspond to any existing events anymore.
#[error("An event couldn't be deleted (Id: {0})")]
DeleteEvent(EventIdType),
/// 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),
/// Error indicating a mutex was poisoned or couldn't be acquired
///
/// This is likely due to a thread being terminated but could also arise from a deadlock or a subtle race condition
#[error("An error happened while trying to acquire a mutex")]
MutexError,
/// Represents an error while acquiring a Discord group
///
/// Raised when there is an error attempting to acquire the discord group
#[error("An error occured while trying 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")]
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 {
fn from(err: nom::Err<nom::error::Error<&str>>) -> Self {
Self::InvalidDateParsing(err.map_input(|input| input.into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn into_error() -> Result<(), IdleError> {
Err(nom::Err::Error(nom::error::Error::new(
"",
nom::error::ErrorKind::Tag,
)))?
}
#[test]
fn test_nom_error() {
match into_error() {
Err(IdleError::InvalidDateParsing(_d)) => {}
_ => panic!("The convertion from a nom error into a IdleError failed"),
};
}
}

67
src/ids.rs Normal file
View File

@ -0,0 +1,67 @@
//! 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) {
// 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());
}
}

437
src/io.rs
View File

@ -1,10 +1,437 @@
//! All IO related functions, include all Discord IO functions
//! Functions to handle I/O operations with Discord.
//!
//! Features:
//! All recv and send functions to discord
//! Helper function for advanced checks
//! This module contains functions for interacting with the Discord API,
//! including receiving and sending messages, reactions, and managing channels and guilds. It also includes
//! helper functions for performing advanced checks and validations on received data.
//! ### Notes:
//! - The code provided uses the Serenity and Poise frameworks to create a Discord bot that can interact with users through commands and modals.
//! - The `discord_main_loop()` function starts the bot client and registers all command handlers, while the other functions handle specific tasks related to vote creation.
//! - The `VoteCreation` struct is designed to be filled in by users through a modal form or text command arguments. It can then be used to create a new vote within the guild.
//!
//! ### Example usage:
//!
//! ```no_run
//! use idlefox::io::discord_main_loop;
//! use idlefox::votes::EventHolder;
//!
//! #[tokio::main]
//! async fn main() {
//! let ctx = EventHolder::default();
//! discord_main_loop(ctx).await;
//! }
//! ```
//!
#![allow(dead_code)]
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;
/// User data, which is stored and accessible in all command invocations
pub struct Data {
/// The global event holder
event_holder: EventHolder,
}
/// 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>;
/// A `VoteContainer` holds the details of a vote that is to be created.
///
/// This struct aggregates all the necessary data describing this event within a Discord guild (server).
/// Generic object that is used to transfer vote data to other parts of the code.
#[derive(Default)]
pub struct VoteContainer {
/// The title of the event
pub(crate) title: String,
/// Description of the event
pub(crate) description: String,
/// An optional serenity::RoleId to specify the role group concerned by the vote.
pub(crate) group: Option<serenity::RoleId>,
/// Optional hours describing the specific date of the event
pub(crate) hours: Option<String>,
/// Auto-Start date of the event (in human-readable format)
pub(crate) start_date: Option<String>,
/// Days not selected for the vote
pub(crate) non_days: Option<String>,
/// Days selected for the vote
pub(crate) days: Option<String>,
/// Date the event begins
pub(crate) date_begin: Option<String>,
/// Date the event ends
pub(crate) date_end: Option<String>,
/// An identifier for the vote
pub(crate) identifier: VoteTypeIdentifier,
}
/// Only title, description and identifier are mandatory
impl VoteContainer {
pub fn new(title: String, description: String, identifier: VoteTypeIdentifier) -> Self {
Self {
title,
description,
identifier,
..Default::default()
}
}
}
/// Identifies the type of the vote being created.
///
/// This enum represents different types of votes, such as regular weekly votes,
/// short-term votes, and long-term votes. It also serves as an indicator when a vote type
/// hasn't been initialized yet.
#[derive(Default)]
pub enum VoteTypeIdentifier {
// Represents a recurring weekly vote, with the list of days voted upon being one week
WeeklyVote,
/// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan.
ShortVote,
/// Represents a long-term vote, where the list of days voted upon extends beyond a week.
LongVote,
/// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value.
#[default]
Uninitialised,
}
/// The result of a vote creation.
///
/// This struct is used to store and display the results of creating a new vote via a discord modal form.
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
pub(crate) struct WeeklyVoteModal {
/// The title of the event
#[name = "Titre"]
#[placeholder = "Titre de votre événement"]
title: String,
/// The description of the event
#[paragraph]
#[name = "Description"]
#[placeholder = "petite description de votre événement"]
description: String,
/// The group that will be tagged by the bot
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
/// The date from which the vote can become active
#[name = "Date de début du vote"]
#[placeholder = "'ven', '10', '21 jan', vide pour la prochaine période de votes"]
start_date: Option<String>,
/// Days for which reactions should "not count"
#[name = "Jours non dispos"]
#[placeholder = "'lun', '30', '2 dec'"]
non_days: Option<String>,
// Max fields is 5 so the two below will have to be command-exclusive
// /// The time a which the event shall take place
// #[name = "Horaires"]
// #[placeholder = "'21h - 23h' par défaut"]
// hours: Option<String>,
}
#[cfg(test)] // This default implementation only exists during testing
impl Default for WeeklyVoteModal {
fn default() -> Self {
WeeklyVoteModal {
title: "The base test vote".into(),
description: "Dummy vote".into(),
group: Some("Base group".into()),
start_date: Some("10 fev".to_owned()),
non_days: Some("10".to_owned()),
}
}
}
/// Creates a Discord Modal for a user-friendly vote creation form.
///
/// This function triggers the creation of a modal that allows users to input details about an event they would like to organize.
/// The input fields are predefined and include the title, short name of the game or event, group to tag, description,
/// and hours at which the event will take place.
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
#[poise::command(slash_command)]
pub async fn vote_modal(
ctx: poise::ApplicationContext<'_, Data, GenericError>,
) -> Result<(), GenericError> {
let data = WeeklyVoteModal::execute(ctx).await?;
if let Some(underlying_data) = data {
log::info!(
"@{:?} **{:?}**\n{:?}\n{:?}, {:?}",
underlying_data.group,
underlying_data.title,
underlying_data.description,
underlying_data.title,
underlying_data.non_days
);
// This whole shenennigan only exists to find a group as specified by text and if so apply it
// However many steps can subtly break and cannot be truly accounted for
let guild = ctx
.guild()
.ok_or_else(|| IdleError::AcquiringDiscordGuild)?; // Maybe the guild cannot be retrieved from the context, such as in a DM
let group = find_role_from_str(
underlying_data.group.as_deref(),
guild.roles.values().map(|v| v.name.as_str()).collect(),
)
.ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exist or the match is too far or the group wasn't specified
.and_then(|role_found: String| {
guild
.role_by_name(&role_found)
.ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group cannot be acquired by that name
.map(|v| v.id)
})
.inspect_err(
|e| /* Do something when an error occurs*/ log::error!("An error occured when selecting groups from {:?}: {}",&underlying_data.group,e),
) // An inspect that could be used to signal something went wrong acquiring or applying the guild
.ok();
let serotoninenjoyer = VoteContainer {
title: underlying_data.title,
description: underlying_data.description,
group,
// hours: underlying_data.hours,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
handler(serotoninenjoyer);
// let reply = poise::CreateReply::default().content(format!(
// "@{} **{}**\n{}\n{}, {}",
// group, title, description, short_name, hours
// ));
// ctx.send(reply).await?;
};
Ok(())
}
/// Attempts to find the most closely matching role from a list based on a provided group name.
///
/// This function takes a `group` string and a vector of role names, and returns the closest match found.
/// If the input `group` is None or the `roles` vector is empty, the function will return None.
/// The search uses the Levenshtein distance algorithm to determine the similarity between strings.
///
/// # Arguments
///
/// * `group` - An `Option<String>` representing the target group name for which a match should be found.
/// * `roles` - A vector of `String`s containing role names to compare against the target group name.
fn find_role_from_str(group: Option<&str>, roles: Vec<&str>) -> Option<String> {
if group.is_none() || roles.is_empty() {
return None;
}
let group = group.unwrap();
// We are hard-coding the maximum value above which we prefer returning None rather than a guess
let mut lowest = (None, 5);
for role in roles {
let d = levenshtein(role, group);
if d < lowest.1 {
lowest = (Some(role), d);
};
}
lowest.0.map(|s| s.to_owned())
}
// /// List of choices for all the roles.
// ///
// /// This enum is used to define a set of predefined choices that users can select from when creating a new vote.
// /// Each choice represents a role within the guild, and it can be referred to using the enum variant name.
// #[derive(Debug, poise::ChoiceParameter)]
// pub enum ListOfRoles {
// // TODO: This needs to be a list of all guildRoles under Users (included)
// // TODO: This needs to be fetched dynamically from the server
// /// placeholder for a role
// #[name = "hunters"]
// Hunters,
// }
/// Text command for extensive vote creation
// Since this is a discord command and not a real rust command, this many arguments is "normal"
#[allow(clippy::too_many_arguments)]
#[poise::command(prefix_command, slash_command)]
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Groupe"] group: Option<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[description = "Date de début du vote"] start_date: Option<String>,
#[description = "Jours non dispos"] non_days: Option<String>,
) -> Result<(), GenericError> {
let rhubarb = VoteContainer {
title,
description,
group,
hours,
start_date,
non_days,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
let _ = ctx;
handler(rhubarb);
// TODO: Log and check that the handle does handle everything
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, short_name, group, description, hours, start_date, non_days
// ))
// .await?;
Ok(())
}
/// Text command for the creation of exeptional votes ; outside normal voting windows.
///
/// This text command is composed of optional group, hours and start_date ; and compulsory title, description and days. days will indicate which days of the week after the start_date will be available for voting.
// 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)]
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
pub async fn short_vote(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Groupe"] group: Option<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[description = "Jours"] days: String,
#[description = "Date de début du vote"] start_date: Option<String>,
) -> Result<(), GenericError> {
handler(VoteContainer {
title,
group,
description,
hours,
days: Some(days),
start_date,
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, group, description, hours, start_date, days
// ))
// .await?;
Ok(())
}
/// Text command for the creation of long votes
///
/// Text command for the creation of votes that span on a very long period to decide on dates for larger-scale events.
/// Takes mandatory title, description, beginning and end date and optional starting date for the vote.
#[allow(clippy::too_many_arguments)] // As this is not a real command by a discord command, there isn't really that many arguments
#[poise::command(prefix_command, slash_command)]
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
pub async fn long_vote(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Description"] description: String,
#[description = "Date de début de la période de l'événement"] date_begin: String,
#[description = "Date de fin de la période de l'événement"] date_end: String,
#[description = "Date (optionelle) de début du vote"] start_date: Option<String>,
) -> Result<(), GenericError> {
handler(VoteContainer {
title,
description,
start_date,
date_begin: Some(date_begin),
date_end: Some(date_end),
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, description, start_date, date_begin, date_end
// ))
// .await?;
Ok(())
}
/// The main discord interaction loop
///
/// Registers all functions and starts a bot client
// As an async loop it is untestable by nature, however this loop aims to stay as simple as possible to be "self testing"
#[cfg(not(tarpaulin_include))]
pub async fn discord_main_loop(event_holder: EventHolder) {
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents = serenity::GatewayIntents::non_privileged();
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: vec![vote_command(), vote_modal(), short_vote(), long_vote()],
..Default::default()
})
.setup(|ctx, _ready, framework| {
Box::pin(async move {
event_holder.discord_ctx.lock().await.replace(ctx.clone());
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data { event_holder })
})
})
.build();
let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;
client.unwrap().start().await.unwrap();
}
#[cfg(test)]
mod tests {
// use super::*;
use super::*;
#[test]
fn test_levenshtein() {
let arguments = [
"hunters",
"ffxiv_idle",
"ffxiv_progfish",
"ffxiv_minilvl",
"dbd",
"dnd",
"r6",
"apex",
"boardgames",
];
// println!("{:?}", arguments);
// println!(
// "{:?}",
// find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec())
// );
assert!(find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec()).is_none());
assert_eq!(
find_role_from_str(Some("ffxivid"), arguments.to_vec()),
Some("ffxiv_idle".to_string())
);
assert_eq!(
find_role_from_str(Some("hunte"), arguments.to_vec()),
Some("hunters".to_string())
);
assert_eq!(
find_role_from_str(Some("dbd"), arguments.to_vec()),
Some("dbd".to_string())
);
assert_eq!(
find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()),
Some("ffxiv_progfish".to_string())
);
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,
);
}
}

28
src/lib.rs Normal file
View File

@ -0,0 +1,28 @@
//! This is the root module of the `idlefox` library.
//!
//! It includes modules related to configuration, date parsing and handling, input/output operations, persistence management,
//! server-side operations, voting mechanisms, and process watchdog functionality. Each module provides functionalities for
//! managing different aspects of idle processes, such as reading from/write to files, storing data persistently,
//! running servers, receiving votes, monitoring process status, and more.
//!
//! The root module serves as a central entry point for users interested in using any part of the library.
//!
#![warn(clippy::missing_docs_in_private_items)]
pub mod config; // Maybe in lib
pub mod date; // Definitely in lib
mod error_handling; // Likely in lib
pub mod ids; // Definitely in lib
pub mod io; // Maybe in lib
mod modules; // Maybe in lib
mod persistence; // Likely in lib
mod server; // Maybe in lib
pub mod votes; // Likely in lib
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

@ -5,14 +5,25 @@
// This line is here to force the use of extensive documentation
#![warn(clippy::missing_docs_in_private_items)]
mod io;
mod modules;
mod persistence;
mod server;
mod votes;
mod watchdog;
use idlefox::config::init_logger;
use idlefox::io::discord_main_loop;
use idlefox::main_scheduler_loop;
use tokio::time;
// The main loop is untestable
#[cfg(not(tarpaulin_include))]
fn main() {
println!("Hello, world!");
#[tokio::main]
async fn main() {
use idlefox::votes::EventHolder;
use tokio::task;
// TODO: Actually load them from disk
let event_context = EventHolder::default();
init_logger().unwrap();
// TODO: Check that this is actually what we want
task::spawn(main_scheduler_loop(
time::interval(time::Duration::from_secs(5)),
event_context.clone(),
));
discord_main_loop(event_context).await;
}

View File

@ -5,6 +5,59 @@
//! Many handler functions
//! Every module encompassing a feature
use crate::{
date::date_parse::DateObject,
io::{VoteContainer, VoteTypeIdentifier},
};
/// Handles generic VoteContainers, parses their data and feeds them into specific VoteObjects
#[allow(unused_variables, unused_mut)]
pub fn handler(vote_container: VoteContainer) {
// Following should be left as is
let title = vote_container.title;
let description = vote_container.description;
let group = vote_container.group;
let mut hours = vote_container.hours;
let mut start_date = vote_container.start_date;
// TODO: Give vky the tools to parse dates and time
// Needs to be parsed as start and end hours
// let short_name = vote_container.short_name;
// Needs to be parsed as single date or set to today's date if None
let mut non_days = vote_container.non_days;
// Needs to be parsed as a list of days spanning one week after start_date
let mut days = vote_container.days;
// Needs to be parsed as a list of days spanning one week after start_date
let mut date_begin = vote_container.date_begin;
// Needs to be parsed as a single date
let mut date_end = vote_container.date_end;
// Needs to be parsed as a single date
match vote_container.identifier {
VoteTypeIdentifier::WeeklyVote => todo!(),
VoteTypeIdentifier::ShortVote => todo!(),
VoteTypeIdentifier::LongVote => todo!(),
VoteTypeIdentifier::Uninitialised => log::error!("Handler got an uninitialised vote."),
}
}
/// Parent structure for every vote
#[allow(dead_code)]
struct VoteObject {
/// Title of the event to vote for
title: String,
/// Description of the event to vote for
description: String,
/// Date from which on the vote should be published
start_date: DateObject,
/// Date after which the vote should be closed
close_date: DateObject,
/// Date after which the vote should be deleted from memory
delete_date: DateObject,
}
// TIL you can't do child structs on rust and now this pretty bit of code above is useless and I feel sad about it
#[cfg(test)]
mod tests {
// use super::*;

View File

@ -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<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 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(())
}
}

View File

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

View File

@ -1,14 +0,0 @@
//! Handles all votes related logic
//!
//! Features:
//! Structs & Traits
//! Votes (struct)
//! Event (struct)
//! ListCurrentEvents (struct)
//! ListFutureEvents (struct)
//!
#[cfg(test)]
mod tests {
// use super::*;
}

22
src/votes/ballots.rs Normal file
View File

@ -0,0 +1,22 @@
//! The ballot submodule provides functionality for managing user ballots, which include casting votes towards events.
//!
//! # Important Structures
//!
//! * `Ballot`: Represents a single vote cast by a user towards an event. It includes fields for the event ID, user handle,
//! and the value or option voted for.
use serde::{Deserialize, Serialize};
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))]
pub struct Ballot {
/// The event the vote refers to
linked_event: EventIdType,
/// The user casting the vote
user_handle: UserDataType,
/// What the user voted for
vote_value: BallotValueType,
}

204
src/votes/events.rs Normal file
View File

@ -0,0 +1,204 @@
//! The `voting_events` submodule is dedicated to managing the lifecycle and
//! functionality of voting events
//!
//! * `ParsedVote`: A comprehensive structure that represents a single vote,
//! encapsulating both ongoing and planned votes. It stores information
//! about the event's title, description, status, start and end dates,
//! auto-delete date, votes cast by users, list of valid options (candidates)
//! for the vote, and type of vote being conducted.
//! * `EventStatus`: An enumeration that defines various states a voting event
//! 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 serde::{Deserialize, Serialize};
use crate::{
date::{parse_date_list, parse_single_date, NaiveDateList},
io::{VoteContainer, VoteTypeIdentifier},
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))]
pub struct EventPending {
/// The parsed representation of the vote associated with this event.
/// It holds the details required for the voting process.
pub(super) parsed_vote: ParsedVote,
}
impl EventPending {
pub fn into_ongoing(self) -> EventOngoing {
EventOngoing {
parsed_vote: self.parsed_vote,
}
}
}
#[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.
/// It holds the details required for the voting process.
pub(super) parsed_vote: ParsedVote,
}
impl Display for EventOngoing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.parsed_vote.fmt(f)
}
}
impl EventOngoing {
pub fn into_closed(self) -> EventClosed {
EventClosed {
parsed_vote: self.parsed_vote,
}
}
}
#[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
/// up after a while.
///
/// Closing an event will call the cleanup and completion functions.
pub struct EventClosed {
/// The parsed representation of the vote associated with this event.
/// It holds the details required for the voting process.
pub(super) parsed_vote: ParsedVote,
}
/// A `ParsedVote` represents a voting event that has been parsed and validated. It
/// contains all necessary information about the voting process itself.
///
/// 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))]
pub(super) struct ParsedVote {
/// The title of the even
pub(super) title: String,
/// Description of the event
pub(super) description: String,
/// Date at which to autostart the vote process
pub(super) launch_date: NaiveDateTime,
/// Date at which to autoclose the vote process
pub(super) close_date: NaiveDateTime,
/// Date at which to autodelete the vote process
pub(super) auto_delete_date: NaiveDateTime,
/// The inner list of votes cast
pub(super) votes: Vec<Ballot>,
/// The list of values to vote for, this list all the valid dates to vote for
pub(super) list_candidates: NaiveDateList,
}
impl ParsedVote {
/// All the logic behind a vote becoming live
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
// 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 Display for ParsedVote {
/// A display for a vote, it is exactly what the discord bot will send
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO: Complete this (vky)
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

@ -0,0 +1,332 @@
//! Submodule including all helper functions to handle vote creation and evolution
//!
use crate::{config::GlobalConfig, votes::traits::BorrowInner};
use chrono::NaiveDate;
use std::{
fs::{create_dir, File},
sync::Arc,
};
use super::{
events::{EventOngoing, EventPending},
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.
///
/// This function will use the `PendingEvents` instance to store the provided event.
/// The structure of the input parameter `event` is expected to be a correctly formatted parsed vote.
///
/// ## Parameters:
/// - `event`: A `ParsedVote` struct representing the details of the event to be scheduled.
///
/// ## Example:
/// ```rust
/// use idlefox::votes::{add_pending_event, EventHolder, EventPending};
/// let ev_ctx = EventHolder::default();
/// 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> {
ev_ctx
.pending_events
.lock()
.unwrap()
.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`.
///
/// ## Parameters:
/// - `Huid`: A `Huid` that uniquely identifies the event to be launched.
///
/// ## Example:
/// ```rust
/// use idlefox::votes::{add_pending_event, make_into_ongoing_event, EventPending, EventHolder};
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &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)
}
/// 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,
/// using which it updates the `OngoingEvents` instance.
///
/// ## Parameters:
/// - `huid`: A `Huid` 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};
/// let ev_ctx = EventHolder::default();
/// let huid = generate_id(); // A new id
/// let ongoing = EventPending::default().into_ongoing(); // A very legit event
/// add_ongoing_event(&huid, ongoing, &ev_ctx).unwrap();
/// ```
pub fn add_ongoing_event(
huid: &EventIdType,
event: EventOngoing,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
ev_ctx
.ongoing_events
.lock()
.unwrap()
.add_event(huid, 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`
/// struct representing the details of the removed event or an `IdleError`.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{
/// # add_pending_event, del_ongoing_event, make_into_ongoing_event, EventPending, EventHolder
/// # };
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &ev_ctx).unwrap();
/// make_into_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)
}
/// 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`
/// struct representing the details of the removed event or an `IdleError`.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{
/// # add_pending_event, del_pending_event, make_into_ongoing_event, EventPending, EventHolder
/// # };
/// let ev_ctx = EventHolder::default();
/// let id = add_pending_event(EventPending::default(), &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)
}
/// 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.
///
/// ## Example:
/// ```rust
/// # use idlefox::votes::{
/// # add_pending_event, close_ongoing_event, make_into_ongoing_event, EventPending, EventHolder,
/// # };
/// 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();
/// ```
pub fn close_ongoing_event(huid: &EventIdType, ev_ctx: &EventHolder) -> Result<(), IdleError> {
ev_ctx
.ongoing_events
.lock()
.unwrap()
.close_event(huid, ev_ctx)
}
/// A link to all events, to be shared between threads related to this event pool.
///
/// This struct serves as a central hub for managing and accessing different states of events within the
/// system. It provides access to pending, ongoing, and potentially closed events.
/// The use of `Arc<Mutex<>>` ensures that the events can be safely shared and modified across multiple
/// threads without running into race conditions or other concurrency issues.
#[derive(Clone, Default)]
pub struct EventHolder {
/// A reference-counted pointer to a mutex-protected `PendingEvents` instance, managing all pending events.
///
/// Pending events are those that have been scheduled but not yet started
pub pending_events: Arc<std::sync::Mutex<ListPendingEvents>>,
/// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all ongoing events.
///
/// Ongoing events are currently running but not yet closed.
pub ongoing_events: Arc<std::sync::Mutex<ListOngoingEvents>>,
/// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all closed events.
///
/// 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(_)));
}
}

389
src/votes/holders.rs Normal file
View File

@ -0,0 +1,389 @@
//! This module is responsible for managing events in an application. It includes
//! functionality to handle both pending and ongoing events, with support for categorizing
//! them based on their status.
//!
//! *Important Structures:*
//! - `PendingEvents`: Manages pending events
//! - `OngoingEvents`: Manages ongoing events
//! - `ClosedEvents`: Represents closed events (TODO: Implementation needed)
//!
//! Note:
//! 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 crate::{
ids::{generate_id, EventIdType},
IdleError,
};
use super::{
add_ongoing_event,
events::{EventClosed, EventOngoing, EventPending},
ClosedHashmap, EventHolder, OngoingHashmap, PendingHashmap,
};
/// The list of pending events, not yet started
///
/// This struct represents the collection of events that have been scheduled but have not yet begun.
#[derive(Serialize, Deserialize, Default)]
#[cfg_attr(test, derive(Debug, PartialEq, Clone))]
pub struct ListPendingEvents {
/// The list of pending events
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 fn add_pending_event(&mut self, event: EventPending) -> Result<EventIdType, IdleError> {
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.
///
/// 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,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
self.find_upcoming(current_time)
.iter()
.try_for_each(|huid| {
self.launch(huid, ev_ctx)?;
Ok(())
})
}
/// 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> {
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)?;
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> {
self.pending_events
.iter()
.filter(|&(_, e)| e.parsed_vote.launch_date <= current_time)
.map(|(k, _v)| (k.clone()))
.collect()
}
/// delete the event without launching it
pub fn del_event(&mut self, huid: &EventIdType) -> Result<EventPending, IdleError> {
self.pending_events
.remove(huid)
.ok_or(IdleError::DeleteEvent(huid.to_string()))
}
// 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))]
pub struct ListOngoingEvents {
/// The list of ongoing events
pub(super) 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> {
event.parsed_vote.launch()?;
self.ongoing_events.insert(huid.clone(), event);
Ok(())
}
/// Remove all outdated votes for the current user
///
/// This function is expected to be called periodically by the watchdog.
pub(crate) fn autoclose(
&mut self,
current_time: NaiveDateTime,
ev_ctx: &EventHolder,
) -> Result<(), IdleError> {
let failure = Vec::new();
for huid in self.find_autoclose(current_time) {
self.close_event(&huid, ev_ctx)?;
}
match failure.is_empty() {
true => Ok(()),
// Should only happen during hard to reproduce race conditions
#[cfg(not(tarpaulin_include))]
false => Err(IdleError::EventPrune(failure)),
}
}
/// Close an event removing it from the ongoing event list and
/// 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> {
// 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()))?;
ev_ctx
.closed_events
.lock()
.unwrap()
.add_event(huid.clone(), event.into_closed())?;
Ok(())
}
/// delete the event without launching it
pub fn del_event(&mut self, huid: &EventIdType) -> Result<EventOngoing, IdleError> {
self.ongoing_events
.remove(huid)
.ok_or(IdleError::DeleteEvent(huid.to_string()))
}
/// 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> {
self.ongoing_events
.iter()
.filter(|(_, e)| e.parsed_vote.close_date <= current_time)
.map(|(k, _)| k.clone())
.collect()
}
}
/// The list of closed events
///
/// This struct represents the collection of events that have been concluded,
/// to display the results of the votes.
#[derive(Serialize, Deserialize, Default)]
pub struct ListClosedEvents {
/// The list of closed events
pub(super) 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);
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> {
self.closed_events
.iter()
.filter(|(_, e)| e.parsed_vote.auto_delete_date <= current_time)
.map(|(k, _)| k.clone())
.collect()
}
/// Remove all outdated votes for the current user
///
/// 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() {
// Should only happen during hard to reproduce race conditions
#[cfg(not(tarpaulin_include))]
failure.push(huid.clone());
}
}
match failure.is_empty() {
true => Ok(()),
#[cfg(not(tarpaulin_include))]
false => Err(IdleError::EventPrune(failure)),
}
}
}
/// 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};
use crate::votes::{
add_pending_event, close_ongoing_event, del_ongoing_event, del_pending_event,
events::ParsedVote, make_into_ongoing_event,
};
use super::*;
macro_rules! g {
($ev: expr) => {
$ev.lock().unwrap()
};
}
// Test all structs can be safely initialized
#[test]
fn init_test() {
let ev_ctx = EventHolder::default();
assert!(ev_ctx.pending_events.lock().is_ok());
assert!(ev_ctx.ongoing_events.lock().is_ok());
}
#[test]
fn test_base_vote_handling() {
let ev = EventPending::default();
let ev_ctx = EventHolder::default();
// 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();
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
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();
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();
assert!(!g!(ev_ctx.ongoing_events).ongoing_events.contains_key(&id)); // Is the vote now not ongoing
}
#[test]
fn test_upcomming_events() {
let ev = EventHolder::default();
let now = Local::now().naive_local();
let later = now.checked_add_days(Days::new(1)).unwrap();
let very_later = now.checked_add_days(Days::new(3)).unwrap();
let very_very_later = now.checked_add_days(Days::new(7)).unwrap();
let event = EventPending {
parsed_vote: ParsedVote {
launch_date: later,
close_date: very_later,
auto_delete_date: very_very_later,
..Default::default()
},
};
assert!(now < later);
assert!(later < very_later);
let id = add_pending_event(event, &ev).unwrap();
assert!(g!(ev.pending_events).find_upcoming(now).is_empty()); // no upcomming events
assert!(g!(ev.closed_events).find_old(now).is_empty()); // no old events
assert!(g!(ev.ongoing_events).find_autoclose(now).is_empty()); // no old events
g!(ev.pending_events).process_upcoming(now, &ev).unwrap(); // nothing should be processed
g!(ev.closed_events).prune_old(now).unwrap(); // nothing should be processed
g!(ev.ongoing_events).autoclose(now, &ev).unwrap(); // nothing should be processed
assert!(g!(ev.pending_events).find_upcoming(now).is_empty()); // no upcomming events
assert!(g!(ev.closed_events).find_old(now).is_empty()); // no old events
assert!(g!(ev.ongoing_events).find_autoclose(now).is_empty()); // no old events
assert!(g!(ev.pending_events).pending_events.contains_key(&id)); // it's still here
assert!(!g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it's wasn't processed
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!(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
g!(ev.closed_events).prune_old(later).unwrap(); // nothing should be processed
g!(ev.ongoing_events).autoclose(later, &ev).unwrap(); // nothing should be processed
assert!(!g!(ev.pending_events).pending_events.contains_key(&id)); // it's not here anymore
assert!(g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it was processed
assert!(!g!(ev.closed_events).closed_events.contains_key(&id)); // not deleted
// 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!(g!(ev.closed_events).find_old(very_later).is_empty()); // no old events
g!(ev.pending_events)
.process_upcoming(very_later, &ev)
.unwrap(); // no event should be processed
g!(ev.closed_events).prune_old(very_later).unwrap(); // nothing should be processed
g!(ev.ongoing_events).autoclose(very_later, &ev).unwrap(); // nothing should be processed
assert!(!g!(ev.pending_events).pending_events.contains_key(&id)); // it's not here anymore
assert!(!g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it was processed
assert!(g!(ev.closed_events).closed_events.contains_key(&id)); // it was processed
// More more time passed
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!(g!(ev.ongoing_events)
.find_autoclose(very_very_later)
.is_empty()); // no old events
g!(ev.pending_events)
.process_upcoming(very_very_later, &ev)
.unwrap(); // no event should be processed
g!(ev.closed_events).prune_old(very_very_later).unwrap(); // nothing should be processed
g!(ev.ongoing_events)
.autoclose(very_very_later, &ev)
.unwrap(); // nothing should be processed
assert!(!g!(ev.pending_events).pending_events.contains_key(&id)); // it's not here anymore
assert!(!g!(ev.ongoing_events).ongoing_events.contains_key(&id)); // it was processed
// TODO: Check the status at several points
}
#[ignore]
#[test]
fn serialisation_check() {
todo!()
}
}

50
src/votes/mod.rs Normal file
View File

@ -0,0 +1,50 @@
//! Module that handles all the logic related to votes within an application.
//!
//! This module provides the necessary structures and traits to manage events
//! and their corresponding votes. It includes:
//!
//! - Structs: `Event`, `Vote`, `PendingEvents`, and `OngoingEvents`.
//! - Traits: None at this time.
//! - Enums: `EventStatus` that represents different states an event can be in.
//!
//! Note:
//! - The types `UserDataType`, `VoteValueType`, and some fields are marked
//! as deprecated and should not be used.
//! They are placeholders for the actual data structures which need to be
//! defined correctly.
#![allow(deprecated)]
#![warn(clippy::missing_docs_in_private_items)]
mod ballots;
mod events;
mod helper_functions;
mod holders;
mod traits;
// Republish
pub use ballots::Ballot;
pub use events::{EventClosed, EventOngoing, EventPending};
pub use helper_functions::EventHolder;
pub use helper_functions::*;
pub use holders::{ListOngoingEvents, ListPendingEvents};
use std::collections::HashMap;
use crate::ids::EventIdType;
/// The hashmap of pending votes
type PendingHashmap = HashMap<EventIdType, EventPending>;
/// The hashmap of ongoing, opened votes
type OngoingHashmap = HashMap<EventIdType, EventOngoing>;
/// The hashmap of closed votes, still available for reading to check the results
type ClosedHashmap = HashMap<EventIdType, EventClosed>;
/// Placeholder user data type
///
/// Links back to an user
#[deprecated(note = "This is an incorrect type to define an user")]
pub type UserDataType = String;
/// What an user voted for
#[deprecated(note = "This is an incorrect type to define a voting ballot")]
pub type BallotValueType = String;

142
src/votes/traits.rs Normal file
View File

@ -0,0 +1,142 @@
//! 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

@ -1,12 +1,183 @@
//! Event scheduler in charge of waiting out events and enabling them when times comes
//! The `scheduler` module contains the logic for managing time-based tasks and events.
//! It is responsible for running scheduled tasks and garbage collecting old events.
//!
//! Features:
//! Time based garbage collector
//! Time managed events
//!
//! This module includes several components:
//!
//! - **Scheduler Thread**: A background thread that runs in an infinite loop,
//! checking for upcoming events and executing them when their scheduled times are reached.
//! - **Time-based Garbage Collection**: The scheduler periodically cleans up old events
//! that have passed their scheduled execution time, ensuring that memory usage remains efficient.
//!
//! Key functions in this module include:
//!
//! - `watchdog_update`: Updates the internal state of the scheduler,
//! checks for and runs upcoming events, and performs garbage collection if necessary.
use crate::votes::EventHolder;
use chrono::{DateTime, Local, NaiveDate};
use poise::serenity_prelude::{self, CacheHttp, ChannelId};
/// The main scheduler waiting and dispatch loop.
///
///
/// This function continuously waits for the specified time interval to elapse,
/// then spawns a blocking task to perform the `watchdog_update` function. The
/// loop continues indefinitely, allowing for continuous scheduling of the
/// `watchdog_update` task at the specified intervals.
#[cfg(not(tarpaulin_include))] // This loop is untestable instead the logic is kept to the minimal
pub async fn main_scheduler_loop(mut interval: tokio::time::Interval, ev_ctx: EventHolder) {
loop {
fk_around(&ev_ctx).await;
interval.tick().await;
// tokio::spawn(async {watchdog_update().await;}); // For async task
let ev = ev_ctx.clone();
tokio::task::spawn_blocking(move || watchdog_update(Local::now(), 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();
let r = discord_ctx
.http()
.send_message(ChannelId::new(1300786300143800351), Vec::new(), &m)
.await;
println!("{:?}", r);
}
}
/// The `watchdog_update` function updates the state of the watchdog and executes the necessary tasks.
///
/// This function takes the current time as an argument, which is used to determine whether a new day has passed
/// and to update the internal calendar state. It then lists all upcoming events that are scheduled to be run
/// and executes them. Additionally, it schedules any ongoing tasks for future execution.
///
/// If a new day has been detected (based on the current time), it prunes old events from the list of ongoing events.
// TODO: Thouroughly test
fn watchdog_update(current_time: DateTime<Local>, ev_ctx: EventHolder) {
// Update day and tell if a day passed
let is_new_day = update_date(current_time.date_naive(), &ev_ctx);
// List all upcoming events and run all events that should be ran
if let Err(e) = ev_ctx
.pending_events
.lock()
.unwrap()
.process_upcoming(current_time.naive_local(), &ev_ctx)
{
// Process the error, log it and try to recover, this error can only happen during a difficult
// to reproduce data race where a task would be edited or externally deleted just as it is about to be launched
#[cfg(not(tarpaulin_include))]
log::error!("{}:{} {:?}", file!(), line!(), e);
}
// Execute all scheduled tasks
// * Clean old events if a new day passed
if is_new_day {
if let Err(e) = ev_ctx
.closed_events
.lock()
.unwrap()
.prune_old(current_time.naive_local())
{
// Process the error, log it and try to recover, this error can only happen during a difficult
// to reproduce data race where a task would be edited or externally deleted just as it is about to be deleted
#[cfg(not(tarpaulin_include))]
log::error!("{}:{} {:?}", file!(), line!(), e);
}
if let Err(e) = ev_ctx
.ongoing_events
.lock()
.unwrap()
.autoclose(current_time.naive_local(), &ev_ctx)
{
// Process the error, log it and try to recover, this error can only happen during a difficult
// to reproduce data race where a task would be edited or externally deleted just as it is about to be closed
#[cfg(not(tarpaulin_include))]
log::error!("{}:{} {:?}", file!(), line!(), e);
}
}
// TODO: Save global state
}
// /// A lazily-initialized, thread-safe storage for the previous day's date.
// ///
// /// This constant is used to track when a new day has started. When a new day is detected,
// /// it updates this value to reflect the current date and time.
// static OLD_DATE: LazyLock<Mutex<NaiveDate>> =
// LazyLock::new(|| Mutex::new(Local::now().date_naive()));
/// The `update_date` function updates the internal calendar state by taking a new date and comparing it with the previous day's date.
///
/// It returns a boolean indicating whether a new day has passed.
/// This function is critical for determining when to prune old events from the ongoing event list.
/// ## Note
/// This whole function exists only in the purpose of manually testing the autopruning and autotesting of all time-related function.
fn update_date(date: NaiveDate, ev_ctx: &EventHolder) -> bool {
let old = ev_ctx.old_date.lock().unwrap().signed_duration_since(date);
if old.num_days() < 0 {
*ev_ctx.old_date.lock().unwrap() = date;
true
} else {
false
}
}
#[cfg(test)]
mod tests {
// use super::*;
use chrono::Days;
use super::*;
#[test]
fn initialisation() {
let ev_ctx = EventHolder::default();
assert!(ev_ctx.old_date.lock().is_ok());
let date = Local::now().date_naive();
update_date(date, &ev_ctx);
assert!(!update_date(date, &ev_ctx));
}
#[test]
fn test_watchdog_update() {
let ctx = EventHolder::default();
let date = Local::now();
watchdog_update(date, ctx.clone());
let date2 = date.checked_add_days(Days::new(12)).unwrap();
assert!(update_date(date2.date_naive(), &ctx));
let date2 = date.checked_add_days(Days::new(14)).unwrap();
watchdog_update(date2, ctx.clone());
}
#[test]
#[ignore]
fn test_watchdog_pruning() {
// Add an event for a date
// Check that the watchdog erased it now that it is passed
// Check that if is set long in the past the event isn't launched as it is not valid and is instead destroyed immediately
// Check that an event cannot stay in memory if it is invalid or wont be launched
unimplemented!()
}
#[test]
#[ignore]
fn test_watchdog_launching() {
// Add an event for a date
// Check that the watchdog launched it
unimplemented!()
}
#[test]
#[ignore]
fn watchdog_autosave() {
// Check that every update of the watchdog saves the votes
unimplemented!()
}
}

14
tests/generic.rs Normal file
View File

@ -0,0 +1,14 @@
#[cfg(test)]
mod tests {
#[test]
fn generic_integration_test() {
use idlefox::ids::generate_id;
use idlefox::votes::{add_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
add_ongoing_event(&huid, ongoing, &ev_ctx).unwrap();
}
}