Skip to content

Commit

Permalink
refactor: break down utils module
Browse files Browse the repository at this point in the history
  • Loading branch information
msfjarvis committed Dec 20, 2024
1 parent d236160 commit 6a9f76a
Show file tree
Hide file tree
Showing 10 changed files with 81 additions and 90 deletions.
37 changes: 34 additions & 3 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use crate::{
FIXER_STATE,
AsyncError, FIXER_STATE,
bot_ext::BotExt,
dice::roll_die,
dice::{extract_dice_count, roll_die},
fixer::FixerState,
utils::{AsyncError, extract_dice_count, parse_bool},
};
use std::{env, sync::LazyLock};
use teloxide::{
Expand Down Expand Up @@ -187,6 +186,38 @@ async fn flip_filter_state(
current_state: impl Fn(&FixerState) -> bool,
update_state: impl FnOnce(&mut FixerState, bool) + Copy,
) -> Result<(), AsyncError> {
const TRUE_VALUES: [&str; 4] = ["true", "on", "yes", "enable"];
const FALSE_VALUES: [&str; 4] = ["false", "off", "no", "disable"];
static EXPECTED_VALUES: LazyLock<String> = LazyLock::new(|| {
[TRUE_VALUES, FALSE_VALUES]
.concat()
.iter()
.map(|item| format!("'{item}'"))
.collect::<Vec<_>>()
.join(", ")
});

fn parse_bool(input: &str) -> Result<bool, String> {
let input = input.split(' ').collect::<Vec<_>>();
if input.len() > 1 {
return Err(format!(
"Unexpected number of arguments. Expected one of: {}.",
*EXPECTED_VALUES
));
}

match input[0].to_lowercase().as_str() {
arg if TRUE_VALUES.contains(&arg) => Ok(true),
arg if FALSE_VALUES.contains(&arg) => Ok(false),
arg => {
let message = format!(
"Unexpected argument '{arg}'. Expected one of: {}.",
*EXPECTED_VALUES
);
Err(message)
}
}
}
if filter_state.is_empty() {
bot.reply(
message,
Expand Down
5 changes: 1 addition & 4 deletions src/deamp/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
mod model;

use crate::{
bot_ext::BotExt,
utils::{AsyncError, get_urls_from_message},
};
use crate::{AsyncError, bot_ext::BotExt, url::get_urls_from_message};
use model::AMPResponse;
use std::str::FromStr;
use teloxide::{Bot, types::Message, utils::html::link};
Expand Down
28 changes: 24 additions & 4 deletions src/dice.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::{
bot_ext::BotExt,
utils::{AsyncError, extract_dice_count},
};
use crate::{AsyncError, bot_ext::BotExt};
use regex::Regex;
use std::sync::LazyLock;
use teloxide::{Bot, types::Message};
Expand Down Expand Up @@ -46,6 +43,29 @@ pub fn roll_die(sides: u8) -> u8 {
rand::random::<u8>() % sides + 1
}

pub fn extract_dice_count(input: &str, default: u8) -> Result<u8, String> {
if input.is_empty() {
return Ok(default);
}

let input = input.split(' ').collect::<Vec<_>>();
if input.len() > 1 {
return Err(String::from(
"Unexpected number of arguments. Expected a numeric value from 1-255.",
));
}

if let Ok(value) = input[0].parse::<u8>() {
Ok(value)
} else {
let message = format!(
"Unexpected argument '{}'. Expected a number from 1-255.",
input[0]
);
Err(message)
}
}

#[cfg(test)]
mod test {
use super::MATCH_REGEX;
Expand Down
5 changes: 3 additions & 2 deletions src/instagram.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{
AsyncError,
bot_ext::BotExt,
utils::{AsyncError, get_preview_url, get_urls_from_message, scrub_urls},
url::{get_preview_url, get_urls_from_message, scrub_urls},
};
use matchit::Router;
use std::sync::LazyLock;
Expand Down Expand Up @@ -51,6 +52,6 @@ mod test {

#[test]
fn test_url_matcher() {
crate::utils::verify_url_matcher(&URLS, &super::URL_MATCHER);
crate::url::verify_url_matcher(&URLS, &super::URL_MATCHER);
}
}
13 changes: 9 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@ mod logging;
mod medium;
mod reddit;
mod twitter;
mod utils;
mod url;
mod youtube;

use crate::commands::Command;
use crate::logging::TeloxideLogger;
use crate::{
commands::Command,
logging::TeloxideLogger,
url::{get_urls_from_message, has_matching_urls},
};
use dotenvy::dotenv;
use fixer::FixerState;
use std::{
collections::HashMap,
error::Error,
sync::{Arc, LazyLock, Mutex},
};
use teloxide::{
Expand All @@ -28,7 +32,8 @@ use teloxide::{
types::{ChatId, Message, Update},
update_listeners::Polling,
};
use utils::{get_urls_from_message, has_matching_urls};

pub(crate) type AsyncError = Box<dyn Error + Send + Sync + 'static>;

pub(crate) static FIXER_STATE: LazyLock<Mutex<HashMap<ChatId, FixerState>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
Expand Down
5 changes: 1 addition & 4 deletions src/medium.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::{
bot_ext::BotExt,
utils::{AsyncError, scrub_urls},
};
use crate::{AsyncError, bot_ext::BotExt, url::scrub_urls};
use regex::Regex;
use std::sync::LazyLock;
use teloxide::{Bot, types::Message, utils::html::link};
Expand Down
5 changes: 3 additions & 2 deletions src/reddit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{
AsyncError,
bot_ext::BotExt,
utils::{AsyncError, get_preview_url, get_urls_from_message, scrub_urls},
url::{get_preview_url, get_urls_from_message, scrub_urls},
};
use matchit::Router;
use std::sync::LazyLock;
Expand Down Expand Up @@ -59,6 +60,6 @@ mod test {

#[test]
fn test_url_matcher() {
crate::utils::verify_url_matcher(&URLS, &super::URL_MATCHER);
crate::url::verify_url_matcher(&URLS, &super::URL_MATCHER);
}
}
5 changes: 3 additions & 2 deletions src/twitter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{
AsyncError,
bot_ext::BotExt,
utils::{AsyncError, get_preview_url, get_urls_from_message, scrub_urls},
url::{get_preview_url, get_urls_from_message, scrub_urls},
};
use matchit::Router;
use std::sync::LazyLock;
Expand Down Expand Up @@ -51,6 +52,6 @@ mod test {

#[test]
fn test_url_matcher() {
crate::utils::verify_url_matcher(&URLS, &super::URL_MATCHER);
crate::url::verify_url_matcher(&URLS, &super::URL_MATCHER);
}
}
61 changes: 1 addition & 60 deletions src/utils.rs → src/url.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use std::{error::Error, sync::LazyLock};
use teloxide::types::{Message, MessageEntityKind};
use tracing::{error, trace};
use url::Url;

pub(crate) type AsyncError = Box<dyn Error + Send + Sync + 'static>;

pub(crate) fn get_urls_from_message(msg: &Message) -> Vec<Url> {
if let Some(entities) = msg.entities()
&& !entities.is_empty()
Expand Down Expand Up @@ -74,62 +71,6 @@ pub(crate) fn scrub_urls(msg: &Message) -> Option<String> {
}
}

const TRUE_VALUES: [&str; 4] = ["true", "on", "yes", "enable"];
const FALSE_VALUES: [&str; 4] = ["false", "off", "no", "disable"];
static EXPECTED_VALUES: LazyLock<String> = LazyLock::new(|| {
[TRUE_VALUES, FALSE_VALUES]
.concat()
.iter()
.map(|item| format!("'{item}'"))
.collect::<Vec<_>>()
.join(", ")
});

pub(crate) fn parse_bool(input: &str) -> Result<bool, String> {
let input = input.split(' ').collect::<Vec<_>>();
if input.len() > 1 {
return Err(format!(
"Unexpected number of arguments. Expected one of: {}.",
*EXPECTED_VALUES
));
}

match input[0].to_lowercase().as_str() {
arg if TRUE_VALUES.contains(&arg) => Ok(true),
arg if FALSE_VALUES.contains(&arg) => Ok(false),
arg => {
let message = format!(
"Unexpected argument '{arg}'. Expected one of: {}.",
*EXPECTED_VALUES
);
Err(message)
}
}
}

pub(crate) fn extract_dice_count(input: &str, default: u8) -> Result<u8, String> {
if input.is_empty() {
return Ok(default);
}

let input = input.split(' ').collect::<Vec<_>>();
if input.len() > 1 {
return Err(String::from(
"Unexpected number of arguments. Expected a numeric value from 1-255.",
));
}

if let Ok(value) = input[0].parse::<u8>() {
Ok(value)
} else {
let message = format!(
"Unexpected argument '{}'. Expected a number from 1-255.",
input[0]
);
Err(message)
}
}

#[cfg(test)]
pub fn verify_url_matcher(urls: &[&str], router: &matchit::Router<()>) {
use url::Url;
Expand All @@ -142,7 +83,7 @@ pub fn verify_url_matcher(urls: &[&str], router: &matchit::Router<()>) {
}

#[cfg(test)]
mod check_matches_domain_tests {
mod test {
use super::check_matches_domain;
use url::Url;

Expand Down
7 changes: 2 additions & 5 deletions src/youtube.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::{
bot_ext::BotExt,
utils::{AsyncError, get_urls_from_message},
};
use crate::{AsyncError, bot_ext::BotExt, url::get_urls_from_message};
use matchit::Router;
use std::sync::LazyLock;
use teloxide::{Bot, types::Message, utils::html::link};
Expand Down Expand Up @@ -46,6 +43,6 @@ mod test {

#[test]
fn test_url_matcher() {
crate::utils::verify_url_matcher(&URLS, &super::URL_MATCHER);
crate::url::verify_url_matcher(&URLS, &super::URL_MATCHER);
}
}

0 comments on commit 6a9f76a

Please sign in to comment.