Compare commits

..

No commits in common. "68db038336573d680b7fe7f8227b9cbbdbc2f131" and "f352c90b6b997f74052855c2f6aa114b5981646b" have entirely different histories.

11 changed files with 41 additions and 129 deletions

View File

@ -12,15 +12,7 @@ async fn main() -> Result<(), BotError> {
Err(e) => return Err(e),
};
let context = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("http://example.com")
.expect("Could not create matrix client"),
room_id: "roomid",
username: "@localuser:example.com",
message_body: &input,
};
let context = Context::new(&db, "roomid", "localuser", &input);
println!("{}", command.execute(&context).await.plain());
Ok(())
}

View File

@ -127,14 +127,7 @@ impl DiceBot {
let commands = msg_body.trim().lines().filter(|line| line.starts_with("!"));
for command in commands {
let ctx = Context {
db: self.db.clone(),
matrix_client: &self.client,
room_id: room_id.as_str(),
username: &sender_username,
message_body: &command,
};
let ctx = Context::new(&self.db, &room_id.as_str(), &sender_username, &command);
let cmd_result = execute_command(&ctx).await;
results.push(cmd_result);
}

View File

@ -1,7 +1,5 @@
use super::DiceBot;
use crate::db::Database;
use crate::error::BotError;
use crate::matrix;
use async_trait::async_trait;
use log::{debug, error, info, warn};
use matrix_sdk::{
@ -11,8 +9,11 @@ use matrix_sdk::{
room::message::{MessageEventContent, TextMessageEventContent},
StrippedStateEvent, SyncMessageEvent, SyncStateEvent,
},
EventEmitter, SyncRoom,
identifiers::RoomId,
Client, EventEmitter, SyncRoom,
};
//use matrix_sdk_common_macros::async_trait;
use super::DiceBot;
use std::clone::Clone;
use std::ops::Sub;
use std::time::{Duration, SystemTime};
@ -92,6 +93,19 @@ fn should_process_event(db: &Database, room_id: &str, event_id: &str) -> bool {
})
}
async fn get_users_in_room(client: &Client, room_id: &RoomId) -> Vec<String> {
if let Some(joined_room) = client.get_joined_room(room_id).await {
let joined_room: matrix_sdk::Room = joined_room.read().await.clone();
joined_room
.joined_members
.keys()
.map(|user_id| format!("@{}:{}", user_id.localpart(), user_id.server_name()))
.collect()
} else {
vec![]
}
}
/// This event emitter listens for messages with dice rolling commands.
/// Originally adapted from the matrix-rust-sdk examples.
#[async_trait]
@ -124,7 +138,7 @@ impl EventEmitter for DiceBot {
self.db.rooms.clear_info(room_id)
} else if event_affects_us && adding_user {
info!("Joined room {}; recording user information", room_id);
let usernames = matrix::get_users_in_room(&self.client, &room.room_id).await;
let usernames = get_users_in_room(&self.client, &room.room_id).await;
usernames
.into_iter()
.filter(|username| username != &event.state_key)

View File

@ -461,13 +461,7 @@ mod tests {
#[tokio::test]
async fn rejects_large_expression_test() {
let db = Database::new_temp().unwrap();
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("http://example.com").unwrap(),
room_id: "roomid",
username: "username",
message_body: "message",
};
let ctx = Context::new(&db, "roomid", "username", "message");
let mut amounts = vec![];
@ -492,13 +486,7 @@ mod tests {
#[tokio::test]
async fn converts_to_chance_die_test() {
let db = Database::new_temp().unwrap();
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("http://example.com").unwrap(),
room_id: "roomid",
username: "username",
message_body: "message",
};
let ctx = Context::new(&db, "roomid", "username", "message");
let mut amounts = vec![];
@ -520,13 +508,7 @@ mod tests {
#[tokio::test]
async fn can_resolve_variables_test() {
let db = Database::new_temp().unwrap();
let ctx = Context {
db: db.clone(),
matrix_client: &matrix_sdk::Client::new("http://example.com").unwrap(),
room_id: "roomid",
username: "username",
message_body: "message",
};
let ctx = Context::new(&db, "roomid", "username", "message");
let user_and_room = crate::db::variables::UserAndRoom(&ctx.username, &ctx.room_id);
db.variables

View File

@ -5,7 +5,6 @@ use thiserror::Error;
pub mod basic_rolling;
pub mod cofd;
pub mod cthulhu;
pub mod management;
pub mod misc;
pub mod parser;
pub mod variables;
@ -81,13 +80,7 @@ mod tests {
#[tokio::test]
async fn unrecognized_command() {
let db = crate::db::Database::new_temp().unwrap();
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("http://example.com").unwrap(),
room_id: "myroomid",
username: "myusername",
message_body: "!notacommand",
};
let ctx = Context::new(&db, "myroomid", "@testuser:example.com", "!notacommand");
let result = execute_command(&ctx).await;
assert!(result.plain.contains("Error"));
}

View File

@ -1,47 +0,0 @@
use super::{Command, Execution};
use crate::context::Context;
use crate::db::errors::DataError;
use crate::matrix;
use async_trait::async_trait;
use matrix_sdk::identifiers::{RoomId, UserId};
use std::convert::TryFrom;
pub struct ResyncCommand;
type ResyncResult = Result<(), DataError>;
#[async_trait]
impl Command for ResyncCommand {
fn name(&self) -> &'static str {
"resync room information"
}
async fn execute(&self, ctx: &Context<'_>) -> Execution {
let room_id = RoomId::try_from(ctx.room_id).expect("failed to decode room ID");
let our_username: Option<UserId> = ctx.matrix_client.user_id().await;
let our_username: &str = our_username.as_ref().map_or("", UserId::as_str);
let usernames = matrix::get_users_in_room(&ctx.matrix_client, &room_id).await;
let result: ResyncResult = usernames
.into_iter()
.filter(|username| username != our_username)
.map(|username| ctx.db.rooms.add_user_to_room(&username, room_id.as_str()))
.collect(); //Make use of collect impl on Result.
let (plain, html) = match result {
Ok(()) => {
let plain = "Room information resynced".to_string();
let html = "<p>Room information resynced.</p>".to_string();
(plain, html)
}
Err(e) => {
let plain = format!("Error: {}", e);
let html = format!("<p><strong>Error:</strong> {}</p>", e);
(plain, html)
}
};
Execution { plain, html }
}
}

View File

@ -4,7 +4,6 @@ use crate::commands::{
basic_rolling::RollCommand,
cofd::PoolRollCommand,
cthulhu::{CthAdvanceRoll, CthRoll},
management::ResyncCommand,
misc::HelpCommand,
variables::{
DeleteVariableCommand, GetAllVariablesCommand, GetVariableCommand, SetVariableCommand,
@ -79,10 +78,6 @@ fn get_all_variables() -> Result<Box<dyn Command>, BotError> {
Ok(Box::new(GetAllVariablesCommand))
}
fn parse_resync() -> Result<Box<dyn Command>, BotError> {
Ok(Box::new(ResyncCommand))
}
fn help(topic: &str) -> Result<Box<dyn Command>, BotError> {
let topic = parse_help_topic(topic);
Ok(Box::new(HelpCommand(topic)))
@ -129,7 +124,6 @@ pub fn parse_command(input: &str) -> Result<Box<dyn Command>, BotError> {
"get" => parse_get_variable_command(&cmd_input),
"set" => parse_set_variable_command(&cmd_input),
"del" => parse_delete_variable_command(&cmd_input),
"resync" => parse_resync(),
"r" | "roll" => parse_roll(&cmd_input),
"rp" | "pool" => parse_pool_roll(&cmd_input),
"cthroll" | "cthRoll" => parse_cth_roll(&cmd_input),

View File

@ -1,13 +1,27 @@
use crate::db::Database;
use matrix_sdk::Client;
/// A context carried through the system providing access to things
/// like the database.
#[derive(Clone)]
pub struct Context<'a> {
pub db: Database,
pub matrix_client: &'a Client,
pub room_id: &'a str,
pub username: &'a str,
pub message_body: &'a str,
}
impl<'a> Context<'a> {
pub fn new(
db: &Database,
room_id: &'a str,
username: &'a str,
message_body: &'a str,
) -> Context<'a> {
Context {
db: db.clone(),
room_id: room_id,
username: username,
message_body: message_body,
}
}
}

View File

@ -380,14 +380,7 @@ mod tests {
};
let db = Database::new_temp().unwrap();
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("https://example.com").unwrap(),
room_id: "roomid",
username: "username",
message_body: "message",
};
let ctx = Context::new(&db, "roomid", "username", "message");
let roll_with_ctx = DiceRollWithContext(&roll, &ctx);
let result = regular_roll(&roll_with_ctx).await;
assert!(result.is_err());

View File

@ -9,7 +9,6 @@ pub mod db;
pub mod dice;
pub mod error;
mod help;
pub mod matrix;
pub mod models;
mod parser;
pub mod state;

View File

@ -1,15 +0,0 @@
use matrix_sdk::{identifiers::RoomId, Client, Room};
/// Retrieve a list of users in a given room.
pub async fn get_users_in_room(client: &Client, room_id: &RoomId) -> Vec<String> {
if let Some(joined_room) = client.get_joined_room(room_id).await {
let joined_room: Room = joined_room.read().await.clone();
joined_room
.joined_members
.keys()
.map(|user_id| format!("@{}:{}", user_id.localpart(), user_id.server_name()))
.collect()
} else {
vec![]
}
}