2020-04-22 04:19:15 +00:00
|
|
|
use crate::commands::parse_command;
|
2020-08-26 21:09:50 +00:00
|
|
|
use dirs;
|
2020-09-26 14:47:23 +00:00
|
|
|
use log::{debug, error, info, trace, warn};
|
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
|
|
|
},
|
|
|
|
Client, ClientConfig, EventEmitter, JsonStore, SyncRoom, SyncSettings,
|
|
|
|
};
|
|
|
|
use matrix_sdk_common_macros::async_trait;
|
2020-04-19 22:07:33 +00:00
|
|
|
use serde::{self, Deserialize, Serialize};
|
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-27 09:06:57 +00:00
|
|
|
use std::sync::{Arc, Mutex};
|
2020-09-26 14:47:23 +00:00
|
|
|
use std::time::{Duration, SystemTime};
|
2020-08-26 21:09:50 +00:00
|
|
|
use thiserror::Error;
|
|
|
|
use url::Url;
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
//TODO move the config structs and read_config into their own file.
|
2020-04-18 23:09:55 +00:00
|
|
|
|
|
|
|
/// The "matrix" section of the config, which gives home server, login information, and etc.
|
2020-04-17 22:53:27 +00:00
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct MatrixConfig {
|
2020-04-18 23:09:55 +00:00
|
|
|
/// Your homeserver of choice, as an FQDN without scheme or path
|
|
|
|
pub home_server: String,
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Username to login as. Only the localpart.
|
|
|
|
pub username: String,
|
|
|
|
|
|
|
|
/// Bot account password.
|
|
|
|
pub password: String,
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
|
|
|
|
2020-09-27 00:24:07 +00:00
|
|
|
const DEFAULT_OLDEST_MESSAGE_AGE: u64 = 15 * 60;
|
2020-09-26 21:33:51 +00:00
|
|
|
|
2020-09-26 14:47:23 +00:00
|
|
|
/// The "bot" section of the config file, for bot settings.
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct BotConfig {
|
|
|
|
/// How far back from current time should we process a message?
|
2020-09-26 21:33:51 +00:00
|
|
|
oldest_message_age: Option<u64>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl BotConfig {
|
|
|
|
pub fn new() -> BotConfig {
|
|
|
|
BotConfig {
|
2020-09-27 00:24:07 +00:00
|
|
|
oldest_message_age: Some(DEFAULT_OLDEST_MESSAGE_AGE),
|
2020-09-26 21:33:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-27 00:24:07 +00:00
|
|
|
/// Determine the oldest allowable message age, in seconds. If the
|
|
|
|
/// setting is defined, use that value. If it is not defined, fall
|
|
|
|
/// back to DEFAULT_OLDEST_MESSAGE_AGE (15 minutes).
|
2020-09-26 21:33:51 +00:00
|
|
|
pub fn oldest_message_age(&self) -> u64 {
|
|
|
|
match self.oldest_message_age {
|
|
|
|
Some(seconds) => seconds,
|
2020-09-27 00:24:07 +00:00
|
|
|
None => DEFAULT_OLDEST_MESSAGE_AGE,
|
2020-09-26 21:33:51 +00:00
|
|
|
}
|
|
|
|
}
|
2020-09-26 14:47:23 +00:00
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Represents the toml config file for the dicebot.
|
2020-04-17 22:53:27 +00:00
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct Config {
|
2020-04-18 23:09:55 +00:00
|
|
|
pub matrix: MatrixConfig,
|
2020-09-26 21:33:51 +00:00
|
|
|
pub bot: Option<BotConfig>,
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// The DiceBot struct itself is the core of the program, essentially the entrypoint
|
|
|
|
/// to the bot.
|
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-09-26 14:47:23 +00:00
|
|
|
config: Config,
|
2020-09-27 00:24:07 +00:00
|
|
|
|
|
|
|
/// The matrix SDK client.
|
2020-04-17 22:53:27 +00:00
|
|
|
client: Client,
|
2020-09-27 00:24:07 +00:00
|
|
|
|
|
|
|
/// Current state of the dice bot. Held in an Arc because it
|
|
|
|
/// accessed by the multi-threaded matrix SDK event handlers.
|
2020-09-27 09:06:57 +00:00
|
|
|
state: Arc<Mutex<DiceBotState>>,
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl DiceBot {
|
2020-09-27 00:24:07 +00:00
|
|
|
/// Create a new dicebot with the given Matrix configuration and
|
|
|
|
/// client. The dice bot is iniitalized with a fresh state.
|
2020-09-26 14:47:23 +00:00
|
|
|
pub fn new(config: Config, client: Client) -> Self {
|
2020-09-27 00:24:07 +00:00
|
|
|
DiceBot {
|
|
|
|
config: config,
|
|
|
|
client: client,
|
2020-09-27 09:06:57 +00:00
|
|
|
state: Arc::new(Mutex::new(DiceBotState::new())),
|
2020-09-27 00:24:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Holds state of the dice bot, for anything requiring mutable
|
|
|
|
/// transitions. This is a simple mutable trait whose values represent
|
|
|
|
/// the current state of the dicebot. It provides mutable methods to
|
|
|
|
/// change state.
|
2020-09-27 09:06:57 +00:00
|
|
|
//#[derive(Clone, Copy)]
|
2020-09-27 00:24:07 +00:00
|
|
|
pub struct DiceBotState {
|
|
|
|
logged_skipped_old_message: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DiceBotState {
|
|
|
|
/// Create initial dice bot state.
|
|
|
|
fn new() -> DiceBotState {
|
|
|
|
DiceBotState {
|
|
|
|
logged_skipped_old_message: false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Log and record that we have skipped some old messages. This
|
|
|
|
/// method will log once, and then no-op from that point on.
|
2020-09-27 09:06:57 +00:00
|
|
|
fn skipped_old_messages(&mut self) {
|
2020-09-27 00:24:07 +00:00
|
|
|
if !self.logged_skipped_old_message {
|
2020-09-27 09:06:57 +00:00
|
|
|
info!("Skipped some messages received while offline because they are too old.");
|
2020-09-27 00:24:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.logged_skipped_old_message = true;
|
2020-09-26 14:47:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-27 00:24:07 +00:00
|
|
|
/// Figure out the allowed oldest message age, in seconds. This will
|
|
|
|
/// be the defined oldest message age in the bot config, if the bot
|
|
|
|
/// configuration and associated "oldest_message_age" setting are
|
|
|
|
/// defined. If the bot config or the message setting are not defined,
|
|
|
|
/// it will defualt to 15 minutes.
|
2020-09-26 21:33:51 +00:00
|
|
|
fn get_oldest_message_age(config: &Config) -> u64 {
|
|
|
|
let none_cfg;
|
|
|
|
let bot_cfg = match &config.bot {
|
|
|
|
Some(cfg) => cfg,
|
|
|
|
None => {
|
|
|
|
none_cfg = BotConfig::new();
|
|
|
|
&none_cfg
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
bot_cfg.oldest_message_age()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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-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
|
|
|
|
|
|
|
match self.client.join_room_by_id(&room.room_id).await {
|
2020-08-28 00:13:01 +00:00
|
|
|
Err(e) => 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-09-26 21:33:51 +00:00
|
|
|
let (msg_body, sender_username) = if let SyncMessageEvent {
|
2020-08-26 21:09:50 +00:00
|
|
|
content: MessageEventContent::Text(TextMessageEventContent { body, .. }),
|
|
|
|
sender,
|
|
|
|
..
|
|
|
|
} = event
|
|
|
|
{
|
|
|
|
(
|
|
|
|
body.clone(),
|
|
|
|
format!("@{}:{}", sender.localpart(), sender.server_name()),
|
|
|
|
)
|
|
|
|
} else {
|
2020-09-26 21:33:51 +00:00
|
|
|
(String::new(), String::new())
|
2020-08-26 21:09:50 +00:00
|
|
|
};
|
|
|
|
|
2020-08-31 23:33:46 +00:00
|
|
|
//Command parser can handle non-commands, but faster to
|
|
|
|
//not parse them.
|
|
|
|
if !msg_body.starts_with("!") {
|
|
|
|
trace!("Ignoring non-command: {}", msg_body);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-09-27 00:24:07 +00:00
|
|
|
//Ignore messages that are older than configured duration.
|
|
|
|
if !check_message_age(event, get_oldest_message_age(&self.config)) {
|
2020-09-27 09:22:09 +00:00
|
|
|
let mut state = match self.state.lock() {
|
|
|
|
Ok(state) => state,
|
|
|
|
Err(poisoned) => poisoned.into_inner(),
|
|
|
|
};
|
|
|
|
|
2020-09-27 09:06:57 +00:00
|
|
|
(*state).skipped_old_messages();
|
2020-09-27 00:24:07 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
let (plain, html) = match parse_command(&msg_body) {
|
|
|
|
Ok(Some(command)) => {
|
|
|
|
let command = command.execute();
|
|
|
|
(command.plain().into(), command.html().into())
|
|
|
|
}
|
2020-08-31 23:33:46 +00:00
|
|
|
Ok(None) => return, //Ignore non-commands.
|
2020-08-26 21:09:50 +00:00
|
|
|
Err(e) => {
|
|
|
|
let message = format!("Error parsing command: {}", e);
|
|
|
|
let html_message = format!("<p><strong>{}</strong></p>", message);
|
|
|
|
(message, html_message)
|
|
|
|
}
|
|
|
|
};
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
let plain = format!("{}\n{}", sender_username, plain);
|
|
|
|
let html = format!("<p>{}</p>\n{}", sender_username, html);
|
2020-08-27 00:05:19 +00:00
|
|
|
let content = AnyMessageEventContent::RoomMessage(MessageEventContent::Notice(
|
|
|
|
NoticeMessageEventContent::html(plain, html),
|
|
|
|
));
|
2020-08-26 21:09:50 +00:00
|
|
|
|
2020-08-28 00:13:01 +00:00
|
|
|
info!("{} executed: {}", sender_username, msg_body);
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
//we clone here to hold the lock for as little time as possible.
|
|
|
|
let room_id = room.read().await.room_id.clone();
|
|
|
|
let result = self.client.room_send(&room_id, content, None).await;
|
|
|
|
|
|
|
|
match result {
|
2020-08-28 00:13:01 +00:00
|
|
|
Err(e) => error!("Error sending message: {}", e.to_string()),
|
2020-08-26 21:09:50 +00:00
|
|
|
Ok(_) => (),
|
2020-04-18 23:09:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
}
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum BotError {
|
|
|
|
/// Sync token couldn't be found.
|
|
|
|
#[error("the sync token could not be retrieved")]
|
|
|
|
SyncTokenRequired,
|
|
|
|
}
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Run the matrix dice bot until program terminated, or a panic occurs.
|
|
|
|
/// Originally adapted from the matrix-rust-sdk command bot example.
|
2020-09-26 14:47:23 +00:00
|
|
|
pub async fn run_bot(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
let homeserver_url = &config.matrix.home_server;
|
|
|
|
let username = &config.matrix.username;
|
|
|
|
let password = &config.matrix.password;
|
2020-04-20 21:09:38 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
let mut cache_dir = dirs::cache_dir().expect("no cache directory found");
|
|
|
|
cache_dir.push("matrix-dicebot");
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
//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.clone();
|
|
|
|
cache.push(username.clone());
|
|
|
|
!cache.exists()
|
|
|
|
};
|
|
|
|
|
|
|
|
let store = JsonStore::open(&cache_dir)?;
|
|
|
|
let client_config = ClientConfig::new().state_store(Box::new(store));
|
|
|
|
|
2020-09-26 14:47:23 +00:00
|
|
|
let homeserver_url = Url::parse(homeserver_url).expect("Couldn't parse the homeserver URL");
|
2020-08-26 21:09:50 +00:00
|
|
|
let mut client = Client::new_with_config(homeserver_url, client_config).unwrap();
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
client
|
2020-09-26 14:47:23 +00:00
|
|
|
.login(username, password, None, Some("matrix dice bot"))
|
2020-08-26 21:09:50 +00:00
|
|
|
.await?;
|
|
|
|
|
2020-08-28 00:13:01 +00:00
|
|
|
info!("Logged in as {}", username);
|
2020-08-26 21:09:50 +00:00
|
|
|
|
|
|
|
if should_sync {
|
2020-08-28 00:13:01 +00:00
|
|
|
info!("Performing initial sync");
|
2020-08-26 21:09:50 +00:00
|
|
|
client.sync(SyncSettings::default()).await?;
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
|
|
|
|
//Attach event handler.
|
2020-09-27 00:24:07 +00:00
|
|
|
info!("Listening for commands");
|
|
|
|
info!(
|
|
|
|
"Oldest allowable message time is {} seconds ago",
|
|
|
|
get_oldest_message_age(&config)
|
|
|
|
);
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
client
|
2020-09-26 14:47:23 +00:00
|
|
|
.add_event_emitter(Box::new(DiceBot::new(config, client.clone())))
|
2020-08-26 21:09:50 +00:00
|
|
|
.await;
|
|
|
|
|
|
|
|
let token = client
|
|
|
|
.sync_token()
|
|
|
|
.await
|
|
|
|
.ok_or(BotError::SyncTokenRequired)?;
|
|
|
|
let settings = SyncSettings::default().token(token);
|
|
|
|
|
|
|
|
//this keeps state from the server streaming in to the dice bot via the EventEmitter trait
|
|
|
|
client.sync_forever(settings, |_| async {}).await;
|
|
|
|
|
|
|
|
Ok(())
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
2020-09-26 21:33:51 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn oldest_message_default_no_setting_test() {
|
|
|
|
let cfg = Config {
|
|
|
|
matrix: MatrixConfig {
|
|
|
|
home_server: "".to_owned(),
|
|
|
|
username: "".to_owned(),
|
|
|
|
password: "".to_owned(),
|
|
|
|
},
|
|
|
|
bot: Some(BotConfig {
|
|
|
|
oldest_message_age: None,
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
|
|
|
|
assert_eq!(15 * 60, get_oldest_message_age(&cfg));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn oldest_message_default_no_bot_config_test() {
|
|
|
|
let cfg = Config {
|
|
|
|
matrix: MatrixConfig {
|
|
|
|
home_server: "".to_owned(),
|
|
|
|
username: "".to_owned(),
|
|
|
|
password: "".to_owned(),
|
|
|
|
},
|
|
|
|
bot: None,
|
|
|
|
};
|
|
|
|
|
|
|
|
assert_eq!(15 * 60, get_oldest_message_age(&cfg));
|
|
|
|
}
|
|
|
|
}
|