2020-10-15 16:52:08 +00:00
|
|
|
use crate::commands::execute_command;
|
2020-09-28 21:35:05 +00:00
|
|
|
use crate::config::*;
|
2020-10-15 16:52:08 +00:00
|
|
|
use crate::context::Context;
|
|
|
|
use crate::db::Database;
|
2020-09-28 21:35:05 +00:00
|
|
|
use crate::error::BotError;
|
2020-10-17 13:30:07 +00:00
|
|
|
use crate::state::DiceBotState;
|
|
|
|
use async_trait::async_trait;
|
2020-08-26 21:09:50 +00:00
|
|
|
use dirs;
|
2020-11-05 23:03:22 +00:00
|
|
|
use log::{debug, error, info, warn};
|
2020-10-31 13:19:13 +00:00
|
|
|
use matrix_sdk::Error as MatrixError;
|
2020-08-26 21:09:50 +00:00
|
|
|
use matrix_sdk::{
|
|
|
|
self,
|
|
|
|
events::{
|
2020-08-27 23:50:32 +00:00
|
|
|
room::member::MemberEventContent,
|
2020-08-26 21:09:50 +00:00
|
|
|
room::message::{MessageEventContent, NoticeMessageEventContent, TextMessageEventContent},
|
2020-08-27 23:50:32 +00:00
|
|
|
AnyMessageEventContent, StrippedStateEvent, SyncMessageEvent,
|
2020-08-26 21:09:50 +00:00
|
|
|
},
|
2020-10-22 19:54:48 +00:00
|
|
|
Client, ClientConfig, EventEmitter, JsonStore, Room, SyncRoom, SyncSettings,
|
2020-08-26 21:09:50 +00:00
|
|
|
};
|
2020-10-17 13:30:07 +00:00
|
|
|
//use matrix_sdk_common_macros::async_trait;
|
2020-09-27 00:24:07 +00:00
|
|
|
use std::clone::Clone;
|
2020-09-26 14:47:23 +00:00
|
|
|
use std::ops::Sub;
|
2020-09-28 21:35:05 +00:00
|
|
|
use std::path::PathBuf;
|
2020-10-17 13:30:07 +00:00
|
|
|
use std::sync::{Arc, RwLock};
|
2020-09-26 14:47:23 +00:00
|
|
|
use std::time::{Duration, SystemTime};
|
2020-08-26 21:09:50 +00:00
|
|
|
use url::Url;
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
/// The DiceBot struct represents an active dice bot. The bot is not
|
|
|
|
/// connected to Matrix until its run() function is called.
|
2020-04-17 22:53:27 +00:00
|
|
|
pub struct DiceBot {
|
2020-09-27 00:24:07 +00:00
|
|
|
/// A reference to the configuration read in on application start.
|
2020-10-03 20:31:42 +00:00
|
|
|
config: Arc<Config>,
|
2020-09-27 00:24:07 +00:00
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
/// The matrix client.
|
2020-04-17 22:53:27 +00:00
|
|
|
client: Client,
|
2020-09-27 00:24:07 +00:00
|
|
|
|
2020-10-17 13:30:07 +00:00
|
|
|
/// State of the dicebot
|
|
|
|
state: Arc<RwLock<DiceBotState>>,
|
2020-10-15 16:52:08 +00:00
|
|
|
|
|
|
|
/// Active database layer
|
|
|
|
db: Database,
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
fn cache_dir() -> Result<PathBuf, BotError> {
|
|
|
|
let mut dir = dirs::cache_dir().ok_or(BotError::NoCacheDirectoryError)?;
|
|
|
|
dir.push("matrix-dicebot");
|
|
|
|
Ok(dir)
|
2020-09-27 00:24:07 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
/// Creates the matrix client.
|
|
|
|
fn create_client(config: &Config) -> Result<Client, BotError> {
|
|
|
|
let cache_dir = cache_dir()?;
|
|
|
|
let store = JsonStore::open(&cache_dir)?;
|
|
|
|
let client_config = ClientConfig::new().state_store(Box::new(store));
|
2020-10-03 20:31:42 +00:00
|
|
|
let homeserver_url = Url::parse(&config.matrix_homeserver())?;
|
2020-09-28 21:35:05 +00:00
|
|
|
|
|
|
|
Ok(Client::new_with_config(homeserver_url, client_config)?)
|
2020-09-27 00:24:07 +00:00
|
|
|
}
|
|
|
|
|
2020-10-31 13:19:13 +00:00
|
|
|
/// Extracts more detailed error messages out of a matrix SDK error.
|
|
|
|
fn extract_error_message(error: MatrixError) -> String {
|
|
|
|
use matrix_sdk::Error::RumaResponse;
|
|
|
|
match error {
|
|
|
|
RumaResponse(ruma_error) => ruma_error.to_string(),
|
|
|
|
_ => error.to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
impl DiceBot {
|
|
|
|
/// Create a new dicebot with the given configuration and state
|
|
|
|
/// actor. This function returns a Result because it is possible
|
|
|
|
/// for client creation to fail for some reason (e.g. invalid
|
|
|
|
/// homeserver URL).
|
2020-10-17 13:30:07 +00:00
|
|
|
pub fn new(
|
|
|
|
config: &Arc<Config>,
|
|
|
|
state: &Arc<RwLock<DiceBotState>>,
|
|
|
|
db: &Database,
|
|
|
|
) -> Result<Self, BotError> {
|
2020-09-28 21:35:05 +00:00
|
|
|
Ok(DiceBot {
|
|
|
|
client: create_client(&config)?,
|
|
|
|
config: config.clone(),
|
2020-10-17 13:30:07 +00:00
|
|
|
state: state.clone(),
|
2020-10-15 16:52:08 +00:00
|
|
|
db: db.clone(),
|
2020-09-28 21:35:05 +00:00
|
|
|
})
|
2020-09-27 00:24:07 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
/// Logs the bot into Matrix and listens for events until program
|
|
|
|
/// terminated, or a panic occurs. Originally adapted from the
|
|
|
|
/// matrix-rust-sdk command bot example.
|
|
|
|
pub async fn run(self) -> Result<(), BotError> {
|
2020-10-03 20:31:42 +00:00
|
|
|
let username = &self.config.matrix_username();
|
|
|
|
let password = &self.config.matrix_password();
|
2020-09-28 21:35:05 +00:00
|
|
|
|
|
|
|
//TODO provide a device id from config.
|
|
|
|
let mut client = self.client.clone();
|
|
|
|
client
|
|
|
|
.login(username, password, None, Some("matrix dice bot"))
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
info!("Logged in as {}", username);
|
|
|
|
|
|
|
|
//If the local json store has not been created yet, we need to do a single initial sync.
|
|
|
|
//It stores data under username's localpart.
|
|
|
|
let should_sync = {
|
|
|
|
let mut cache = cache_dir()?;
|
|
|
|
cache.push(username);
|
|
|
|
!cache.exists()
|
|
|
|
};
|
|
|
|
|
|
|
|
if should_sync {
|
|
|
|
info!("Performing initial sync");
|
|
|
|
self.client.sync(SyncSettings::default()).await?;
|
2020-09-27 00:24:07 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
//Attach event handler.
|
|
|
|
client.add_event_emitter(Box::new(self)).await;
|
|
|
|
info!("Listening for commands");
|
2020-09-26 14:47:23 +00:00
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
let token = client
|
|
|
|
.sync_token()
|
|
|
|
.await
|
|
|
|
.ok_or(BotError::SyncTokenRequired)?;
|
2020-09-26 21:33:51 +00:00
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
let settings = SyncSettings::default().token(token);
|
|
|
|
|
|
|
|
//this keeps state from the server streaming in to the dice bot via the EventEmitter trait
|
|
|
|
//TODO somehow figure out how to "sync_until" instead of sync_forever... copy code and modify?
|
|
|
|
client.sync_forever(settings, |_| async {}).await;
|
|
|
|
Ok(())
|
|
|
|
}
|
2020-10-22 19:54:48 +00:00
|
|
|
|
|
|
|
async fn execute_commands(&self, room: &Room, sender_username: &str, msg_body: &str) {
|
|
|
|
let room_name = room.display_name().clone();
|
|
|
|
let room_id = room.room_id.clone();
|
|
|
|
|
|
|
|
let mut results = Vec::with_capacity(msg_body.lines().count());
|
|
|
|
|
|
|
|
for command in msg_body.lines() {
|
2020-11-05 23:03:22 +00:00
|
|
|
if !command.is_empty() {
|
|
|
|
let ctx = Context::new(&self.db, &room_id.as_str(), &sender_username, &command);
|
|
|
|
if let Some(cmd_result) = execute_command(&ctx).await {
|
|
|
|
results.push(cmd_result);
|
|
|
|
}
|
2020-10-22 19:54:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-01 12:20:45 +00:00
|
|
|
if results.len() >= 1 {
|
|
|
|
if results.len() == 1 {
|
|
|
|
let cmd_result = &results[0];
|
|
|
|
let response = AnyMessageEventContent::RoomMessage(MessageEventContent::Notice(
|
|
|
|
NoticeMessageEventContent::html(
|
|
|
|
cmd_result.plain.clone(),
|
|
|
|
cmd_result.html.clone(),
|
|
|
|
),
|
|
|
|
));
|
|
|
|
|
|
|
|
let result = self.client.room_send(&room_id, response, None).await;
|
|
|
|
if let Err(e) = result {
|
|
|
|
let message = extract_error_message(e);
|
|
|
|
error!("Error sending message: {}", message);
|
|
|
|
};
|
|
|
|
} else if results.len() > 1 {
|
|
|
|
let message = format!("{}: Executed {} commands", sender_username, results.len());
|
|
|
|
let response = AnyMessageEventContent::RoomMessage(MessageEventContent::Notice(
|
|
|
|
NoticeMessageEventContent::html(&message, &message),
|
|
|
|
));
|
|
|
|
|
|
|
|
let result = self.client.room_send(&room_id, response, None).await;
|
|
|
|
if let Err(e) = result {
|
|
|
|
let message = extract_error_message(e);
|
|
|
|
error!("Error sending message: {}", message);
|
|
|
|
};
|
|
|
|
}
|
2020-10-22 19:54:48 +00:00
|
|
|
|
2020-11-01 12:20:45 +00:00
|
|
|
info!("[{}] {} executed: {}", room_name, sender_username, msg_body);
|
|
|
|
}
|
2020-10-22 19:54:48 +00:00
|
|
|
}
|
2020-09-26 21:33:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if a message is recent enough to actually process. If the
|
|
|
|
/// message is within "oldest_message_age" seconds, this function
|
|
|
|
/// returns true. If it's older than that, it returns false and logs a
|
|
|
|
/// debug message.
|
2020-09-26 14:47:23 +00:00
|
|
|
fn check_message_age(
|
|
|
|
event: &SyncMessageEvent<MessageEventContent>,
|
2020-09-26 21:33:51 +00:00
|
|
|
oldest_message_age: u64,
|
2020-09-26 14:47:23 +00:00
|
|
|
) -> bool {
|
|
|
|
let sending_time = event.origin_server_ts;
|
2020-09-26 21:33:51 +00:00
|
|
|
let oldest_timestamp = SystemTime::now().sub(Duration::new(oldest_message_age, 0));
|
2020-09-26 14:47:23 +00:00
|
|
|
|
|
|
|
if sending_time > oldest_timestamp {
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
let age = match oldest_timestamp.duration_since(sending_time) {
|
|
|
|
Ok(n) => format!("{} seconds too old", n.as_secs()),
|
|
|
|
Err(_) => "before the UNIX epoch".to_owned(),
|
|
|
|
};
|
|
|
|
|
|
|
|
debug!("Ignoring message because it is {}: {:?}", age, event);
|
|
|
|
false
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
}
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-10-15 16:52:08 +00:00
|
|
|
async fn should_process<'a>(
|
2020-10-03 20:31:42 +00:00
|
|
|
bot: &DiceBot,
|
|
|
|
event: &SyncMessageEvent<MessageEventContent>,
|
|
|
|
) -> Result<(String, String), BotError> {
|
|
|
|
//Ignore messages that are older than configured duration.
|
|
|
|
if !check_message_age(event, bot.config.oldest_message_age()) {
|
2020-10-17 13:30:07 +00:00
|
|
|
let state_check = bot.state.read().unwrap();
|
|
|
|
if !((*state_check).logged_skipped_old_messages()) {
|
|
|
|
drop(state_check);
|
|
|
|
let mut state = bot.state.write().unwrap();
|
|
|
|
(*state).skipped_old_messages();
|
|
|
|
}
|
2020-10-03 20:31:42 +00:00
|
|
|
|
|
|
|
return Err(BotError::ShouldNotProcessError);
|
|
|
|
}
|
|
|
|
|
|
|
|
let (msg_body, sender_username) = if let SyncMessageEvent {
|
|
|
|
content: MessageEventContent::Text(TextMessageEventContent { body, .. }),
|
|
|
|
sender,
|
|
|
|
..
|
|
|
|
} = event
|
|
|
|
{
|
|
|
|
(
|
|
|
|
body.clone(),
|
|
|
|
format!("@{}:{}", sender.localpart(), sender.server_name()),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
(String::new(), String::new())
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok((msg_body, sender_username))
|
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// This event emitter listens for messages with dice rolling commands.
|
2020-09-26 14:47:23 +00:00
|
|
|
/// Originally adapted from the matrix-rust-sdk examples.
|
2020-08-26 21:09:50 +00:00
|
|
|
#[async_trait]
|
|
|
|
impl EventEmitter for DiceBot {
|
2020-08-27 23:50:32 +00:00
|
|
|
async fn on_stripped_state_member(
|
|
|
|
&self,
|
|
|
|
room: SyncRoom,
|
|
|
|
room_member: &StrippedStateEvent<MemberEventContent>,
|
|
|
|
_: Option<MemberEventContent>,
|
|
|
|
) {
|
|
|
|
if let SyncRoom::Invited(room) = room {
|
|
|
|
if let Some(user_id) = self.client.user_id().await {
|
|
|
|
if room_member.state_key != user_id {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let room = room.read().await;
|
2020-08-28 00:13:01 +00:00
|
|
|
info!("Autojoining room {}", room.display_name());
|
2020-08-27 23:50:32 +00:00
|
|
|
|
2020-10-03 20:31:42 +00:00
|
|
|
if let Err(e) = self.client.join_room_by_id(&room.room_id).await {
|
|
|
|
warn!("Could not join room: {}", e.to_string())
|
2020-08-27 23:50:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
async fn on_room_message(&self, room: SyncRoom, event: &SyncMessageEvent<MessageEventContent>) {
|
|
|
|
if let SyncRoom::Joined(room) = room {
|
2020-10-03 20:31:42 +00:00
|
|
|
let (msg_body, sender_username) =
|
|
|
|
if let Ok((msg_body, sender_username)) = should_process(self, &event).await {
|
|
|
|
(msg_body, sender_username)
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
};
|
2020-09-27 00:24:07 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
//we clone here to hold the lock for as little time as possible.
|
2020-10-22 19:54:48 +00:00
|
|
|
let real_room = room.read().await.clone();
|
2020-10-15 16:52:08 +00:00
|
|
|
|
2020-10-22 19:54:48 +00:00
|
|
|
self.execute_commands(&real_room, &sender_username, &msg_body)
|
|
|
|
.await;
|
2020-04-18 23:09:55 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
}
|