Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor #14

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ pub async fn init() -> anyhow::Result<()> {
Err(_) => ["database.sled"].iter().collect::<PathBuf>(),
};

let db = sled::open(&path).context(format!(
"Unable to open database at {}",
path.to_string_lossy()
))?;
let db = sled::open(&path).context(format!("Unable to open database at {}", path.display()))?;

let session_storage = db.open_tree("session_storage")?;
let listener_storage = db.open_tree("listener_storage")?;
Expand Down
16 changes: 6 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,10 +287,7 @@ impl Config {

let user_agent =
HeaderValue::from_str(&(NAME.to_string() + "/" + VERSION)).with_context(|| {
format!(
"Unable to create valid user agent from {} and {}",
NAME, VERSION
)
format!("Unable to create valid user agent from {NAME} and {VERSION}")
})?;

let (group_pings, group_ping_users) = load_group_ping_settings(&toml)?;
Expand Down Expand Up @@ -342,21 +339,21 @@ impl From<&str> for SensitiveSpelling {
impl Display for SpellCheckKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
SpellCheckKind::SpellCheckInsensitive(v) => write!(f, "{}", v),
SpellCheckKind::SpellCheckSensitive(v) => write!(f, "{}", v),
SpellCheckKind::SpellCheckInsensitive(v) => v.fmt(f),
SpellCheckKind::SpellCheckSensitive(v) => v.fmt(f),
}
}
}

impl Display for InsensitiveSpelling {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.spelling)
self.spelling.fmt(f)
}
}

impl Display for SensitiveSpelling {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.spelling)
self.spelling.fmt(f)
}
}

Expand Down Expand Up @@ -583,8 +580,7 @@ fn load_group_ping_settings(
// If list of users are not found, print error to console and move on
None => {
return Err(anyhow!(format!(
"Group alias %{} has no corresponding group. Ignoring...",
alias
"Group alias %{alias} has no corresponding group. Ignoring...",
)))
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/helpers/bot_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl fmt::Display for MatrixNoticeResponse {
}
}
let response = response.trim();
write!(f, "{}", response)
f.write_str(response)
}
}

Expand All @@ -160,7 +160,7 @@ impl fmt::Display for MatrixFormattedTextResponse {
}
}
let response = response.trim();
write!(f, "{}", response)
f.write_str(response)
}
}

Expand All @@ -174,6 +174,6 @@ impl fmt::Display for MatrixFormattedNoticeResponse {
}
}
let response = response.trim();
write!(f, "{}", response)
f.write_str(response)
}
}
5 changes: 3 additions & 2 deletions src/helpers/check_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ pub enum CheckFormatError {
impl fmt::Display for CheckFormatError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
CheckFormatError::FormatNotSupported(e) =>
write!(f, "Message parsed properly, but format {} is not supported so no conversion is taking place.", e),
CheckFormatError::FormatNotSupported(e) => {
write!(f, "Message parsed properly, but format {e} is not supported so no conversion is taking place.")
}
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/services/matrix/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,12 @@ impl MatrixListener {
)
.await
{
error!("{}", e);
error!("{e}");
};
}
Ok(_) => {}
Err(e) => {
debug!("{:?}", e);
debug!("{e:?}");
trace!("Content: {:?}", raw_event.json())
}
}
Expand All @@ -146,7 +146,7 @@ impl MatrixListener {
)
.await
{
error!("{}", e);
error!("{e}");
};
trace!("Handled invite event")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,9 @@ fn determine_users(config: &MatrixListenerConfig, text: &str, users: &mut HashSe
for user in config.group_pings.values().flatten() {
users.insert(user.clone());
}
} else {
if let Some(v) = config.group_pings.get(&cap[1]) {
for user in v {
users.insert(user.clone());
}
} else if let Some(v) = config.group_pings.get(&cap[1]) {
for user in v {
users.insert(user.clone());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use std::convert::TryInto;
use std::time::SystemTime;
use text_expansion::text_expansion;
use tokio::sync::mpsc::Sender;
use tracing::{debug, trace, error};
use tracing::{debug, error, trace};
use unit_conversion::unit_conversion;

/// Handler for all text based non-command events
Expand Down Expand Up @@ -109,7 +109,7 @@ pub async fn commandless_handler(
}
if config.enable_corrections
&& relates_to.is_none()
&& correction_time_cooldown(&storage, room_id)
&& correction_time_cooldown(storage, room_id)
&& !config.correction_exclusion.contains(room_id)
&& !notice_response.is_some()
&& !text_response.is_some()
Expand All @@ -126,7 +126,7 @@ pub async fn commandless_handler(
{
Ok(_) => {
let _ = storage.insert(
"last_correction_time_".to_owned() + &room_id.to_string(),
format!("last_correction_time_{room_id}"),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_secs()
Expand All @@ -141,35 +141,33 @@ pub async fn commandless_handler(
}
}
Err(e) => {
Err(anyhow!("{}", e))?;
Err(anyhow!("{e}"))?;
}
}
}
Ok(())
}

fn correction_time_cooldown(storage: &Tree, room_id: &RoomId) -> bool {
match storage.get("last_correction_time_".to_owned() + &room_id.to_string()) {
match storage.get(format!("last_correction_time_{room_id}")) {
Ok(t) => {
match t {
Some(v) => {
let bytes: [u8; 8] = v.to_vec().try_into().unwrap();
let old_time = u64::from_be_bytes(bytes);
let new_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
let new_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();

if new_time < old_time + 300 {
true
} else {
false
}
},
None => true // Will only be None if this client has not yet corrected anyone in specified room, so return true to allow correction
new_time < old_time + 300
}
None => true, // Will only be None if this client has not yet corrected anyone in specified room, so return true to allow correction
}

},
}
Err(e) => {
error!("Somehow unable to retrieve correction time cooldown key from database. Error is {}", e);
error!("Somehow unable to retrieve correction time cooldown key from database. Error is {e}");
false // Will only be Err in truly extreme situations. Log + return false to prevent correction and thus potential spam.
}
}
}
}
24 changes: 12 additions & 12 deletions src/services/matrix/matrix_handlers/listeners/help_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ pub async fn help_handler(
}
} else {
trace!(
"Rooms are limited and room {} is not in the allowed list of help command rooms",
room_id
"Rooms are limited and room {room_id} is not in the allowed list of help command rooms",
);
}
Ok(())
Expand Down Expand Up @@ -180,8 +179,8 @@ USAGE:
\t%server

AVAILABLE GROUPS:
{}", available_groups
)
{available_groups}
")
}

async fn github_search_help_message(config: &MatrixListenerConfig) -> String {
Expand All @@ -208,7 +207,8 @@ USAGE:
\tjf#1234

AVAILABLE REPOS:
{}", available_repos)
{available_repos}
")
}

async fn link_help_message(config: &MatrixListenerConfig) -> String {
Expand Down Expand Up @@ -247,11 +247,11 @@ USAGE:
\tlink@hwa

AVAILABLE KEYWORDS:
{}
{available_keywords}

AVAILABLE LINKS:
{}
", available_keywords, available_links)
{available_links}
")
}

async fn text_expansion_help_message(config: &MatrixListenerConfig) -> String {
Expand All @@ -278,8 +278,8 @@ USAGE:
\t$kodi

AVAILABLE KEYWORDS:
{}
", available_keywords)
{available_keywords}
")
}

async fn unit_conversion_help_message(config: &MatrixListenerConfig) -> String {
Expand Down Expand Up @@ -318,6 +318,6 @@ SPEED:
km/h | kmh | kph | kmph | mph

SPACE EXCLUDED UNITS:
{}
", space_excluded_units)
{space_excluded_units}
")
}
2 changes: 1 addition & 1 deletion src/services/matrix/matrix_handlers/listeners/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub async fn handle_invite_event(
config: &MatrixListenerConfig,
send: &mut Sender<MatrixMessage>,
) -> anyhow::Result<()> {
trace!("Invited by {} to room {} ", &sender, &room_id);
trace!("Invited by {sender} to room {room_id}");
if config.admins.contains(sender) {
let message = MatrixInviteMessage {
kind: MatrixInviteType::Accept,
Expand Down
8 changes: 4 additions & 4 deletions src/services/matrix/matrix_handlers/responders/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub async fn send_ban_message(
client: &MatrixClient,
) -> anyhow::Result<()> {
for room_id in rooms {
debug!("Banning user {} in room {}...", user, room_id);
debug!("Banning user {user} in room {room_id}...");
let mut req = ban_user::v3::Request::new(&room_id, user);
req.reason = reason.as_deref();
if let Err(e) = client.send_request(req).await {
Expand All @@ -49,13 +49,13 @@ pub async fn accept_invite(
client: &MatrixClient,
) -> anyhow::Result<()> {
let room_id = room_id.context("Accept invite message was not provided with room_id")?;
info!("Authorized user {} invited me to room {}", sender, room_id);
info!("Authorized user {sender} invited me to room {room_id}");
client
.send_request(join_room_by_id::v3::Request::new(&room_id))
.await
.context("Unable to join room")?;

info!("Successfully joined room {}", room_id);
info!("Successfully joined room {room_id}");
Ok(())
}

Expand All @@ -71,6 +71,6 @@ pub async fn reject_invite(
.await
.context("Unable to reject invite")?;

info!("Rejected invite from unathorized user {}", sender);
info!("Rejected invite from unathorized user {sender}");
Ok(())
}
18 changes: 9 additions & 9 deletions src/services/matrix/responder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl MatrixResponder {
},
m = self.recv.recv() => {
if let Err(e) = self.send_message_handler(m, &client).await {
error!("{}", e);
error!("{e}");
}
}
}
Expand All @@ -47,25 +47,25 @@ impl MatrixResponder {
match message {
Some(v) => match v.message {
MatrixMessageType::Response(m) => {
if let Err(e) = send_message(&client, v.room_id.unwrap(), m).await {
error!("{}", e);
if let Err(e) = send_message(client, v.room_id.unwrap(), m).await {
error!("{e}");
}
}
MatrixMessageType::Invite(m) => match m.kind {
MatrixInviteType::Accept => {
if let Err(e) = accept_invite(&m.sender, v.room_id, &client).await {
error!("{}", e);
if let Err(e) = accept_invite(&m.sender, v.room_id, client).await {
error!("{e}");
}
}
MatrixInviteType::Reject => {
if let Err(e) = reject_invite(&m.sender, v.room_id, &client).await {
error!("{}", e);
if let Err(e) = reject_invite(&m.sender, v.room_id, client).await {
error!("{e}");
}
}
},
MatrixMessageType::Ban(m) => {
if let Err(e) = send_ban_message(&m.user, m.reason, m.rooms, &client).await {
error!("{}", e);
if let Err(e) = send_ban_message(&m.user, m.reason, m.rooms, client).await {
error!("{e}");
}
}
},
Expand Down
4 changes: 1 addition & 3 deletions src/services/webhook/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,13 @@ impl WebhookListener {
.serve(app.into_make_service());

tokio::select! {
r = server => {
r = server => {
if let Err(_) = r {
error!("Unable to start webhook listener");
return;
}
},
_ = shutdown_rx.changed() => {
trace!("Received shutdown on webhook listener thread, exiting thread with code 0");
return;
}
}
}
Expand Down
Loading