Compare commits

...

4 Commits

Author SHA1 Message Date
projectmoon 68db038336 Properly avoid allocation for our_username in resync command.
continuous-integration/drone/push Build is passing Details
2020-11-23 19:54:20 +00:00
projectmoon 18352c8c19 Filter out our username when resyncing (with an allocation).
continuous-integration/drone/push Build was killed Details
2020-11-22 22:13:11 +00:00
projectmoon dda0d74f45 Implement resync command without filtering ourselves out.
continuous-integration/drone/push Build was killed Details
2020-11-22 21:30:24 +00:00
projectmoon f46b914239 Add matrix client to context. 2020-11-22 20:52:44 +00:00
11 changed files with 129 additions and 41 deletions

View File

@ -12,7 +12,15 @@ async fn main() -> Result<(), BotError> {
Err(e) => return Err(e),
};
let context = Context::new(&db, "roomid", "localuser", &input);
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,
};
println!("{}", command.execute(&context).await.plain());
Ok(())
}

View File

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

View File

@ -1,5 +1,7 @@
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::{
@ -9,11 +11,8 @@ use matrix_sdk::{
room::message::{MessageEventContent, TextMessageEventContent},
StrippedStateEvent, SyncMessageEvent, SyncStateEvent,
},
identifiers::RoomId,
Client, EventEmitter, SyncRoom,
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};
@ -93,19 +92,6 @@ 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]
@ -138,7 +124,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 = get_users_in_room(&self.client, &room.room_id).await;
let usernames = matrix::get_users_in_room(&self.client, &room.room_id).await;
usernames
.into_iter()
.filter(|username| username != &event.state_key)

View File

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

View File

@ -5,6 +5,7 @@ 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;
@ -80,7 +81,13 @@ mod tests {
#[tokio::test]
async fn unrecognized_command() {
let db = crate::db::Database::new_temp().unwrap();
let ctx = Context::new(&db, "myroomid", "@testuser:example.com", "!notacommand");
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("http://example.com").unwrap(),
room_id: "myroomid",
username: "myusername",
message_body: "!notacommand",
};
let result = execute_command(&ctx).await;
assert!(result.plain.contains("Error"));
}

View File

@ -0,0 +1,47 @@
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,6 +4,7 @@ use crate::commands::{
basic_rolling::RollCommand,
cofd::PoolRollCommand,
cthulhu::{CthAdvanceRoll, CthRoll},
management::ResyncCommand,
misc::HelpCommand,
variables::{
DeleteVariableCommand, GetAllVariablesCommand, GetVariableCommand, SetVariableCommand,
@ -78,6 +79,10 @@ 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)))
@ -124,6 +129,7 @@ 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,27 +1,13 @@
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,7 +380,14 @@ mod tests {
};
let db = Database::new_temp().unwrap();
let ctx = Context::new(&db, "roomid", "username", "message");
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("https://example.com").unwrap(),
room_id: "roomid",
username: "username",
message_body: "message",
};
let roll_with_ctx = DiceRollWithContext(&roll, &ctx);
let result = regular_roll(&roll_with_ctx).await;
assert!(result.is_err());

View File

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

15
src/matrix.rs Normal file
View File

@ -0,0 +1,15 @@
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![]
}
}