2021-01-30 22:13:06 +00:00
|
|
|
use crate::commands::{execute_command, CommandResult, ExecutionError, ResponseExtractor};
|
2020-09-28 21:35:05 +00:00
|
|
|
use crate::config::*;
|
2021-01-29 22:35:07 +00:00
|
|
|
use crate::context::{Context, RoomContext};
|
2020-10-15 16:52:08 +00:00
|
|
|
use crate::db::Database;
|
2020-09-28 21:35:05 +00:00
|
|
|
use crate::error::BotError;
|
2021-01-31 14:06:25 +00:00
|
|
|
use crate::matrix;
|
2020-10-17 13:30:07 +00:00
|
|
|
use crate::state::DiceBotState;
|
2020-08-26 21:09:50 +00:00
|
|
|
use dirs;
|
2021-02-02 21:41:16 +00:00
|
|
|
use futures::stream::{self, StreamExt};
|
2021-01-31 14:06:25 +00:00
|
|
|
use log::info;
|
|
|
|
use matrix_sdk::{self, identifiers::RoomId, Client, ClientConfig, JoinedRoom, SyncSettings};
|
2020-09-27 00:24:07 +00:00
|
|
|
use std::clone::Clone;
|
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-08-26 21:09:50 +00:00
|
|
|
use url::Url;
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-11-07 14:37:56 +00:00
|
|
|
pub mod event_handlers;
|
|
|
|
|
2021-02-02 21:41:16 +00:00
|
|
|
/// How many commands can be in one message. If the amount is higher
|
|
|
|
/// than this, we reject execution.
|
|
|
|
const MAX_COMMANDS_PER_MESSAGE: usize = 50;
|
|
|
|
|
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()?;
|
2021-01-29 22:35:07 +00:00
|
|
|
//let store = JsonStore::open(&cache_dir)?;
|
|
|
|
let client_config = ClientConfig::new().store_path(cache_dir);
|
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
|
|
|
}
|
|
|
|
|
2021-01-30 22:13:06 +00:00
|
|
|
/// Handle responding to a single command being executed. Wil print
|
|
|
|
/// out the full result of that command.
|
|
|
|
async fn handle_single_result(
|
|
|
|
client: &Client,
|
|
|
|
cmd_result: &CommandResult,
|
|
|
|
respond_to: &str,
|
|
|
|
room_id: &RoomId,
|
|
|
|
) {
|
|
|
|
let html = cmd_result.message_html(respond_to);
|
2021-01-31 14:06:25 +00:00
|
|
|
matrix::send_message(client, room_id, &html).await;
|
2021-01-30 22:13:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Handle responding to multiple commands being executed. Will print
|
|
|
|
/// out how many commands succeeded and failed (if any failed).
|
|
|
|
async fn handle_multiple_results(
|
|
|
|
client: &Client,
|
2021-01-31 08:15:22 +00:00
|
|
|
results: &[(&str, CommandResult)],
|
2021-01-30 22:13:06 +00:00
|
|
|
respond_to: &str,
|
|
|
|
room_id: &RoomId,
|
|
|
|
) {
|
2021-01-31 08:15:22 +00:00
|
|
|
let errors: Vec<(&str, &ExecutionError)> = results
|
|
|
|
.into_iter()
|
|
|
|
.filter_map(|(cmd, result)| match result {
|
|
|
|
Err(e) => Some((*cmd, e)),
|
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
.collect();
|
2021-01-30 22:13:06 +00:00
|
|
|
|
|
|
|
let message = if errors.len() == 0 {
|
2021-01-31 08:15:22 +00:00
|
|
|
format!("{}: Executed {} commands", respond_to, results.len())
|
2021-01-30 22:13:06 +00:00
|
|
|
} else {
|
2021-01-31 08:15:22 +00:00
|
|
|
let failures: String = errors
|
|
|
|
.iter()
|
2021-01-31 14:06:25 +00:00
|
|
|
.map(|&(cmd, err)| format!("<strong>{}:</strong> {}", cmd, err))
|
2021-01-31 08:15:22 +00:00
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.join("\n");
|
|
|
|
|
2021-01-30 22:13:06 +00:00
|
|
|
format!(
|
2021-01-31 08:15:22 +00:00
|
|
|
"{}: Executed {} commands ({} failed)\n\nFailures:\n{}",
|
2021-01-30 22:13:06 +00:00
|
|
|
respond_to,
|
|
|
|
results.len(),
|
2021-01-31 08:15:22 +00:00
|
|
|
errors.len(),
|
|
|
|
failures
|
2021-01-30 22:13:06 +00:00
|
|
|
)
|
2021-01-31 14:06:25 +00:00
|
|
|
.replace("\n", "<br/>")
|
2021-01-30 22:13:06 +00:00
|
|
|
};
|
|
|
|
|
2021-01-31 14:06:25 +00:00
|
|
|
matrix::send_message(client, room_id, &message).await;
|
2021-01-30 22:13:06 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-02-07 14:21:28 +00:00
|
|
|
/// Logs in to matrix and potentially records a new device ID. If
|
|
|
|
/// no device ID is found in the database, a new one will be
|
|
|
|
/// generated by the matrix SDK, and we will store it.
|
|
|
|
async fn login(&self, client: &Client) -> Result<(), BotError> {
|
|
|
|
let username = self.config.matrix_username();
|
|
|
|
let password = self.config.matrix_password();
|
|
|
|
|
|
|
|
// Pull device ID from database, if it exists. Then write it
|
|
|
|
// to DB if the library generated one for us.
|
|
|
|
let device_id: Option<String> = self.db.state.get_device_id()?;
|
|
|
|
let device_id: Option<&str> = device_id.as_deref();
|
2020-09-28 21:35:05 +00:00
|
|
|
|
|
|
|
client
|
2021-02-07 14:21:28 +00:00
|
|
|
.login(username, password, device_id, Some("matrix dice bot"))
|
2020-09-28 21:35:05 +00:00
|
|
|
.await?;
|
|
|
|
|
2021-02-07 14:21:28 +00:00
|
|
|
if device_id.is_none() {
|
|
|
|
let device_id = client.device_id().await.ok_or(BotError::NoDeviceIdFound)?;
|
|
|
|
self.db.state.set_device_id(device_id.as_str())?;
|
|
|
|
info!("Recorded new device ID: {}", device_id.as_str());
|
|
|
|
} else {
|
|
|
|
info!("Using existing device ID: {}", device_id.unwrap());
|
|
|
|
}
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
info!("Logged in as {}", username);
|
2021-02-07 14:21:28 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Logs the bot in to 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> {
|
|
|
|
let client = self.client.clone();
|
|
|
|
self.login(&client).await?;
|
2020-09-28 21:35:05 +00:00
|
|
|
|
2020-11-08 21:43:18 +00:00
|
|
|
// Initial sync without event handler prevents responding to
|
|
|
|
// messages received while bot was offline. TODO: selectively
|
|
|
|
// respond to old messages? e.g. comands missed while offline.
|
|
|
|
self.client.sync_once(SyncSettings::default()).await?;
|
|
|
|
|
2020-09-28 21:35:05 +00:00
|
|
|
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);
|
|
|
|
|
2020-11-08 21:43:18 +00:00
|
|
|
// TODO replace with sync_with_callback for cleaner shutdown
|
|
|
|
// process.
|
|
|
|
client.sync(settings).await;
|
2020-09-28 21:35:05 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2020-10-22 19:54:48 +00:00
|
|
|
|
2021-01-29 22:35:07 +00:00
|
|
|
async fn execute_commands(&self, room: &JoinedRoom, sender_username: &str, msg_body: &str) {
|
2021-02-02 21:41:16 +00:00
|
|
|
let room_name: &str = &room.display_name().await.ok().unwrap_or_default();
|
2021-01-29 22:35:07 +00:00
|
|
|
let room_id = room.room_id().clone();
|
2020-10-22 19:54:48 +00:00
|
|
|
|
2021-02-02 21:41:16 +00:00
|
|
|
let commands: Vec<&str> = msg_body
|
|
|
|
.lines()
|
|
|
|
.filter(|line| line.starts_with("!"))
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
//Up to 50 commands allowed, otherwise we send back an error.
|
|
|
|
let results: Vec<(&str, CommandResult)> = if commands.len() < MAX_COMMANDS_PER_MESSAGE {
|
|
|
|
stream::iter(commands)
|
|
|
|
.then(|command| async move {
|
|
|
|
let ctx = Context {
|
|
|
|
db: self.db.clone(),
|
|
|
|
matrix_client: &self.client,
|
|
|
|
room: RoomContext::new_with_name(&room, room_name),
|
|
|
|
username: &sender_username,
|
|
|
|
message_body: &command,
|
|
|
|
};
|
|
|
|
|
|
|
|
let cmd_result = execute_command(&ctx).await;
|
|
|
|
(command, cmd_result)
|
|
|
|
})
|
|
|
|
.collect()
|
|
|
|
.await
|
|
|
|
} else {
|
|
|
|
vec![("", Err(ExecutionError(BotError::MessageTooLarge)))]
|
|
|
|
};
|
2020-10-22 19:54:48 +00:00
|
|
|
|
2020-11-01 12:20:45 +00:00
|
|
|
if results.len() >= 1 {
|
|
|
|
if results.len() == 1 {
|
2021-01-31 08:15:22 +00:00
|
|
|
handle_single_result(&self.client, &results[0].1, sender_username, &room_id).await;
|
2020-11-01 12:20:45 +00:00
|
|
|
} else if results.len() > 1 {
|
2021-01-30 22:13:06 +00:00
|
|
|
handle_multiple_results(&self.client, &results, sender_username, &room_id).await;
|
2020-11-01 12:20:45 +00:00
|
|
|
}
|
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
|
|
|
}
|