2021-05-15 23:45:26 +00:00
|
|
|
use crate::db::sqlite::Database;
|
2021-05-21 22:01:52 +00:00
|
|
|
use crate::error::BotError;
|
2021-05-26 15:28:59 +00:00
|
|
|
use crate::models::Account;
|
2021-05-21 22:01:52 +00:00
|
|
|
use matrix_sdk::identifiers::{RoomId, UserId};
|
2021-03-15 20:10:42 +00:00
|
|
|
use matrix_sdk::room::Joined;
|
2020-11-22 20:52:44 +00:00
|
|
|
use matrix_sdk::Client;
|
2021-05-21 22:01:52 +00:00
|
|
|
use std::convert::TryFrom;
|
2020-10-15 16:52:08 +00:00
|
|
|
|
|
|
|
/// A context carried through the system providing access to things
|
|
|
|
/// like the database.
|
|
|
|
#[derive(Clone)]
|
2020-11-03 20:14:15 +00:00
|
|
|
pub struct Context<'a> {
|
2020-10-17 15:18:51 +00:00
|
|
|
pub db: Database,
|
2020-11-22 20:52:44 +00:00
|
|
|
pub matrix_client: &'a Client,
|
2021-01-29 22:35:07 +00:00
|
|
|
pub room: RoomContext<'a>,
|
2020-11-03 20:14:15 +00:00
|
|
|
pub username: &'a str,
|
|
|
|
pub message_body: &'a str,
|
2021-05-26 13:56:14 +00:00
|
|
|
pub account: Account,
|
2020-10-15 16:52:08 +00:00
|
|
|
}
|
2021-01-29 22:35:07 +00:00
|
|
|
|
2021-03-15 20:10:42 +00:00
|
|
|
impl Context<'_> {
|
|
|
|
pub fn room_id(&self) -> &RoomId {
|
|
|
|
self.room.id
|
|
|
|
}
|
2021-05-21 22:01:52 +00:00
|
|
|
|
|
|
|
pub fn is_secure(&self) -> bool {
|
|
|
|
self.room.secure
|
|
|
|
}
|
2021-03-15 20:10:42 +00:00
|
|
|
}
|
|
|
|
|
2021-01-29 22:35:07 +00:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct RoomContext<'a> {
|
|
|
|
pub id: &'a RoomId,
|
2021-05-21 22:01:52 +00:00
|
|
|
pub display_name: String,
|
|
|
|
pub secure: bool,
|
2021-01-29 22:35:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl RoomContext<'_> {
|
2021-05-21 22:01:52 +00:00
|
|
|
pub async fn new_with_name<'a>(
|
|
|
|
room: &'a Joined,
|
|
|
|
display_name: String,
|
|
|
|
sending_user: &str,
|
|
|
|
) -> Result<RoomContext<'a>, BotError> {
|
|
|
|
// TODO is_direct is a hack; should set rooms to Direct
|
|
|
|
// Message upon joining, if other contact has requested it.
|
|
|
|
// Waiting on SDK support.
|
|
|
|
let sending_user = UserId::try_from(sending_user)?;
|
|
|
|
let user_in_room = room.get_member(&sending_user).await.ok().is_some();
|
|
|
|
let is_direct = room.joined_members().await?.len() == 2;
|
|
|
|
|
|
|
|
Ok(RoomContext {
|
2021-01-29 22:35:07 +00:00
|
|
|
id: room.room_id(),
|
|
|
|
display_name,
|
2021-05-21 22:01:52 +00:00
|
|
|
secure: room.is_encrypted() && is_direct && user_in_room,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn new<'a>(
|
|
|
|
room: &'a Joined,
|
|
|
|
sending_user: &str,
|
|
|
|
) -> Result<RoomContext<'a>, BotError> {
|
|
|
|
Self::new_with_name(
|
|
|
|
&room,
|
|
|
|
room.display_name()
|
|
|
|
.await
|
|
|
|
.ok()
|
|
|
|
.unwrap_or_default()
|
|
|
|
.to_string(),
|
|
|
|
sending_user,
|
|
|
|
)
|
|
|
|
.await
|
2021-01-29 22:35:07 +00:00
|
|
|
}
|
|
|
|
}
|