2023-03-13 10:46:26 -07:00
|
|
|
use std::collections::HashMap;
|
2022-12-29 18:00:59 -08:00
|
|
|
use std::convert::TryFrom;
|
2023-01-10 19:59:30 -08:00
|
|
|
use std::fmt::{Debug, Formatter};
|
2022-12-29 18:00:59 -08:00
|
|
|
use std::fs::File;
|
|
|
|
use std::io::BufWriter;
|
|
|
|
use std::str::FromStr;
|
2023-01-10 19:59:30 -08:00
|
|
|
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
2022-12-29 18:00:59 -08:00
|
|
|
use std::sync::Arc;
|
2023-03-13 10:46:26 -07:00
|
|
|
use std::time::{Duration, Instant};
|
2022-12-29 18:00:59 -08:00
|
|
|
|
|
|
|
use gethostname::gethostname;
|
2023-01-10 19:59:30 -08:00
|
|
|
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
2022-12-29 18:00:59 -08:00
|
|
|
use tokio::task::JoinHandle;
|
2023-03-13 10:46:26 -07:00
|
|
|
use tracing::{error, warn};
|
2022-12-29 18:00:59 -08:00
|
|
|
|
|
|
|
use matrix_sdk::{
|
|
|
|
config::{RequestConfig, StoreConfig, SyncSettings},
|
|
|
|
encryption::verification::{SasVerification, Verification},
|
|
|
|
event_handler::Ctx,
|
|
|
|
reqwest,
|
2023-01-11 17:54:49 -08:00
|
|
|
room::{Invited, Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
|
2022-12-29 18:00:59 -08:00
|
|
|
ruma::{
|
|
|
|
api::client::{
|
2023-03-04 12:23:17 -08:00
|
|
|
room::create_room::v3::{CreationContent, Request as CreateRoomRequest, RoomPreset},
|
2022-12-29 18:00:59 -08:00
|
|
|
room::Visibility,
|
|
|
|
space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
|
|
|
|
},
|
2023-03-03 16:37:11 -08:00
|
|
|
assign,
|
2022-12-29 18:00:59 -08:00
|
|
|
events::{
|
|
|
|
key::verification::{
|
|
|
|
done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
|
|
|
|
key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent},
|
|
|
|
request::ToDeviceKeyVerificationRequestEvent,
|
|
|
|
start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
|
|
|
|
VerificationMethod,
|
|
|
|
},
|
2023-03-01 18:46:33 -08:00
|
|
|
presence::PresenceEvent,
|
2023-02-09 17:53:33 -08:00
|
|
|
reaction::ReactionEventContent,
|
2023-01-05 18:12:25 -08:00
|
|
|
room::{
|
2023-03-03 16:37:11 -08:00
|
|
|
encryption::RoomEncryptionEventContent,
|
2023-01-10 19:59:30 -08:00
|
|
|
message::{MessageType, RoomMessageEventContent},
|
2023-01-05 18:12:25 -08:00
|
|
|
name::RoomNameEventContent,
|
2023-01-13 17:53:54 -08:00
|
|
|
redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
|
2023-01-05 18:12:25 -08:00
|
|
|
},
|
2023-01-25 17:54:16 -08:00
|
|
|
tag::Tags,
|
2023-01-03 13:57:28 -08:00
|
|
|
typing::SyncTypingEvent,
|
2023-03-03 16:37:11 -08:00
|
|
|
AnyInitialStateEvent,
|
2023-03-13 10:46:26 -07:00
|
|
|
AnyMessageLikeEvent,
|
2022-12-29 18:00:59 -08:00
|
|
|
AnyTimelineEvent,
|
2023-03-03 16:37:11 -08:00
|
|
|
EmptyStateKey,
|
|
|
|
InitialStateEvent,
|
2022-12-29 18:00:59 -08:00
|
|
|
SyncMessageLikeEvent,
|
|
|
|
SyncStateEvent,
|
|
|
|
},
|
2023-03-04 12:23:17 -08:00
|
|
|
room::RoomType,
|
2023-03-03 16:37:11 -08:00
|
|
|
serde::Raw,
|
|
|
|
EventEncryptionAlgorithm,
|
2022-12-29 18:00:59 -08:00
|
|
|
OwnedRoomId,
|
|
|
|
OwnedRoomOrAliasId,
|
|
|
|
OwnedUserId,
|
2023-03-13 10:46:26 -07:00
|
|
|
RoomId,
|
2023-01-13 17:53:54 -08:00
|
|
|
RoomVersionId,
|
2022-12-29 18:00:59 -08:00
|
|
|
},
|
|
|
|
Client,
|
|
|
|
DisplayName,
|
|
|
|
Session,
|
|
|
|
};
|
|
|
|
|
|
|
|
use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
|
|
|
|
|
|
|
|
use crate::{
|
2023-03-03 16:37:11 -08:00
|
|
|
base::{
|
|
|
|
AsyncProgramStore,
|
2023-03-13 10:46:26 -07:00
|
|
|
ChatStore,
|
2023-03-03 16:37:11 -08:00
|
|
|
CreateRoomFlags,
|
|
|
|
CreateRoomType,
|
|
|
|
EventLocation,
|
|
|
|
IambError,
|
|
|
|
IambResult,
|
|
|
|
Receipts,
|
2023-03-13 10:46:26 -07:00
|
|
|
RoomFetchStatus,
|
2023-03-03 16:37:11 -08:00
|
|
|
VerifyAction,
|
|
|
|
},
|
2023-01-19 16:05:02 -08:00
|
|
|
message::MessageFetchResult,
|
2022-12-29 18:00:59 -08:00
|
|
|
ApplicationSettings,
|
|
|
|
};
|
|
|
|
|
|
|
|
const IAMB_DEVICE_NAME: &str = "iamb";
|
|
|
|
const IAMB_USER_AGENT: &str = "iamb";
|
2023-03-13 10:46:26 -07:00
|
|
|
const MIN_MSG_LOAD: u32 = 50;
|
2022-12-29 18:00:59 -08:00
|
|
|
|
|
|
|
fn initial_devname() -> String {
|
|
|
|
format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy())
|
|
|
|
}
|
|
|
|
|
2023-03-03 16:37:11 -08:00
|
|
|
pub async fn create_room(
|
|
|
|
client: &Client,
|
|
|
|
room_alias_name: Option<&str>,
|
|
|
|
rt: CreateRoomType,
|
|
|
|
flags: CreateRoomFlags,
|
|
|
|
) -> IambResult<OwnedRoomId> {
|
2023-03-04 12:23:17 -08:00
|
|
|
let mut creation_content = None;
|
2023-03-03 16:37:11 -08:00
|
|
|
let mut initial_state = vec![];
|
2023-03-04 12:23:17 -08:00
|
|
|
let mut is_direct = false;
|
|
|
|
let mut preset = None;
|
2023-03-03 16:37:11 -08:00
|
|
|
let mut invite = vec![];
|
|
|
|
|
|
|
|
let visibility = if flags.contains(CreateRoomFlags::PUBLIC) {
|
|
|
|
Visibility::Public
|
|
|
|
} else {
|
|
|
|
Visibility::Private
|
|
|
|
};
|
|
|
|
|
|
|
|
match rt {
|
|
|
|
CreateRoomType::Direct(user) => {
|
|
|
|
invite.push(user);
|
|
|
|
is_direct = true;
|
|
|
|
preset = Some(RoomPreset::TrustedPrivateChat);
|
|
|
|
},
|
2023-03-04 12:23:17 -08:00
|
|
|
CreateRoomType::Space => {
|
|
|
|
let mut cc = CreationContent::new();
|
|
|
|
cc.room_type = Some(RoomType::Space);
|
|
|
|
|
|
|
|
let raw_cc = Raw::new(&cc).map_err(IambError::from)?;
|
|
|
|
creation_content = Some(raw_cc);
|
|
|
|
},
|
|
|
|
CreateRoomType::Room => {},
|
2023-03-03 16:37:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set up encryption.
|
|
|
|
if flags.contains(CreateRoomFlags::ENCRYPTED) {
|
|
|
|
// XXX: Once matrix-sdk uses ruma 0.8, then this can skip the cast.
|
|
|
|
let algo = EventEncryptionAlgorithm::MegolmV1AesSha2;
|
|
|
|
let content = RoomEncryptionEventContent::new(algo);
|
|
|
|
let encr = InitialStateEvent { content, state_key: EmptyStateKey };
|
|
|
|
let encr_raw = Raw::new(&encr).map_err(IambError::from)?;
|
|
|
|
let encr_raw = encr_raw.cast::<AnyInitialStateEvent>();
|
|
|
|
initial_state.push(encr_raw);
|
|
|
|
}
|
|
|
|
|
|
|
|
let request = assign!(CreateRoomRequest::new(), {
|
|
|
|
room_alias_name,
|
|
|
|
creation_content,
|
|
|
|
initial_state: initial_state.as_slice(),
|
|
|
|
invite: invite.as_slice(),
|
|
|
|
is_direct,
|
|
|
|
visibility,
|
|
|
|
preset,
|
|
|
|
});
|
|
|
|
|
|
|
|
let resp = client.create_room(request).await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
if is_direct {
|
|
|
|
if let Some(room) = client.get_room(&resp.room_id) {
|
|
|
|
room.set_is_direct(true).await.map_err(IambError::from)?;
|
|
|
|
} else {
|
|
|
|
error!(
|
|
|
|
room_id = resp.room_id.as_str(),
|
|
|
|
"Couldn't set is_direct for new direct message room"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Ok(resp.room_id);
|
|
|
|
}
|
|
|
|
|
2023-03-13 10:46:26 -07:00
|
|
|
async fn load_plan(store: &AsyncProgramStore) -> HashMap<OwnedRoomId, Option<String>> {
|
|
|
|
let mut locked = store.lock().await;
|
|
|
|
let ChatStore { need_load, rooms, .. } = &mut locked.application;
|
|
|
|
let mut plan = HashMap::new();
|
|
|
|
|
|
|
|
for room_id in std::mem::take(need_load).into_iter() {
|
|
|
|
let info = rooms.get_or_default(room_id.clone());
|
|
|
|
|
|
|
|
if info.recently_fetched() || info.fetching {
|
|
|
|
need_load.insert(room_id);
|
|
|
|
continue;
|
|
|
|
} else {
|
|
|
|
info.fetch_last = Instant::now().into();
|
|
|
|
info.fetching = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
let fetch_id = match &info.fetch_id {
|
|
|
|
RoomFetchStatus::Done => continue,
|
|
|
|
RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
|
|
|
|
RoomFetchStatus::NotStarted => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
plan.insert(room_id, fetch_id);
|
|
|
|
}
|
|
|
|
|
|
|
|
return plan;
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn load_older_one(
|
|
|
|
client: Client,
|
|
|
|
room_id: &RoomId,
|
|
|
|
fetch_id: Option<String>,
|
|
|
|
limit: u32,
|
|
|
|
) -> MessageFetchResult {
|
|
|
|
if let Some(room) = client.get_room(room_id) {
|
|
|
|
let mut opts = match &fetch_id {
|
|
|
|
Some(id) => MessagesOptions::backward().from(id.as_str()),
|
|
|
|
None => MessagesOptions::backward(),
|
|
|
|
};
|
|
|
|
opts.limit = limit.into();
|
|
|
|
|
|
|
|
let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
let msgs = chunk.into_iter().filter_map(|ev| {
|
|
|
|
match ev.event.deserialize() {
|
|
|
|
Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg),
|
|
|
|
Ok(AnyTimelineEvent::State(_)) => None,
|
|
|
|
Err(_) => None,
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok((end, msgs.collect()))
|
|
|
|
} else {
|
|
|
|
Err(IambError::UnknownRoom(room_id.to_owned()).into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) {
|
|
|
|
let mut locked = store.lock().await;
|
|
|
|
let ChatStore { need_load, presences, rooms, .. } = &mut locked.application;
|
|
|
|
let info = rooms.get_or_default(room_id.clone());
|
|
|
|
info.fetching = false;
|
|
|
|
|
|
|
|
match res {
|
|
|
|
Ok((fetch_id, msgs)) => {
|
|
|
|
for msg in msgs.into_iter() {
|
|
|
|
let sender = msg.sender().to_owned();
|
|
|
|
let _ = presences.get_or_default(sender);
|
|
|
|
|
|
|
|
match msg {
|
|
|
|
AnyMessageLikeEvent::RoomMessage(msg) => {
|
|
|
|
info.insert(msg);
|
|
|
|
},
|
|
|
|
AnyMessageLikeEvent::Reaction(ev) => {
|
|
|
|
info.insert_reaction(ev);
|
|
|
|
},
|
|
|
|
_ => continue,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
info.fetch_id = fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
|
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
warn!(room_id = room_id.as_str(), err = e.to_string(), "Failed to load older messages");
|
|
|
|
|
|
|
|
// Wait and try again.
|
|
|
|
need_load.insert(room_id);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn load_older(client: &Client, store: &AsyncProgramStore) {
|
|
|
|
let limit = MIN_MSG_LOAD;
|
|
|
|
let plan = load_plan(store).await;
|
|
|
|
|
|
|
|
// Fetch each room separately, so they don't block each other.
|
|
|
|
for (room_id, fetch_id) in plan.into_iter() {
|
|
|
|
let client = client.clone();
|
|
|
|
let store = store.clone();
|
|
|
|
|
|
|
|
tokio::spawn(async move {
|
|
|
|
let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
|
|
|
|
load_insert(room_id, res, store).await;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-10 19:59:30 -08:00
|
|
|
#[derive(Debug)]
|
2022-12-29 18:00:59 -08:00
|
|
|
pub enum LoginStyle {
|
|
|
|
SessionRestore(Session),
|
|
|
|
Password(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ClientResponse<T>(Receiver<T>);
|
|
|
|
pub struct ClientReply<T>(SyncSender<T>);
|
|
|
|
|
|
|
|
impl<T> ClientResponse<T> {
|
|
|
|
fn recv(self) -> T {
|
|
|
|
self.0.recv().expect("failed to receive response from client thread")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ClientReply<T> {
|
|
|
|
fn send(self, t: T) {
|
|
|
|
self.0.send(t).unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn oneshot<T>() -> (ClientReply<T>, ClientResponse<T>) {
|
|
|
|
let (tx, rx) = sync_channel(1);
|
|
|
|
let reply = ClientReply(tx);
|
|
|
|
let response = ClientResponse(rx);
|
|
|
|
|
|
|
|
return (reply, response);
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:40:16 -08:00
|
|
|
async fn update_receipts(client: &Client) -> Vec<(OwnedRoomId, Receipts)> {
|
|
|
|
let mut rooms = vec![];
|
|
|
|
|
|
|
|
for room in client.joined_rooms() {
|
|
|
|
if let Ok(users) = room.active_members_no_sync().await {
|
|
|
|
let mut receipts = Receipts::new();
|
|
|
|
|
|
|
|
for member in users {
|
|
|
|
let res = room.user_read_receipt(member.user_id()).await;
|
|
|
|
|
|
|
|
if let Ok(Some((event_id, _))) = res {
|
|
|
|
let user_id = member.user_id().to_owned();
|
|
|
|
receipts.entry(event_id).or_default().push(user_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
rooms.push((room.room_id().to_owned(), receipts));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return rooms;
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
pub type FetchedRoom = (MatrixRoom, DisplayName, Option<Tags>);
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
pub enum WorkerTask {
|
2023-01-26 15:23:15 -08:00
|
|
|
ActiveRooms(ClientReply<Vec<FetchedRoom>>),
|
|
|
|
DirectMessages(ClientReply<Vec<FetchedRoom>>),
|
2022-12-29 18:00:59 -08:00
|
|
|
Init(AsyncProgramStore, ClientReply<()>),
|
|
|
|
Login(LoginStyle, ClientReply<IambResult<EditInfo>>),
|
2023-01-11 17:54:49 -08:00
|
|
|
GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>),
|
2023-01-26 15:23:15 -08:00
|
|
|
GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
|
2022-12-29 18:00:59 -08:00
|
|
|
JoinRoom(String, ClientReply<IambResult<OwnedRoomId>>),
|
2023-01-04 12:51:33 -08:00
|
|
|
Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
|
2022-12-29 18:00:59 -08:00
|
|
|
SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
|
|
|
|
Spaces(ClientReply<Vec<(MatrixRoom, DisplayName)>>),
|
2023-01-03 13:57:28 -08:00
|
|
|
TypingNotice(OwnedRoomId),
|
2022-12-29 18:00:59 -08:00
|
|
|
Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
|
|
|
|
VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
|
|
|
|
}
|
|
|
|
|
2023-01-10 19:59:30 -08:00
|
|
|
impl Debug for WorkerTask {
|
|
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
|
|
|
|
match self {
|
2023-01-11 17:54:49 -08:00
|
|
|
WorkerTask::ActiveRooms(_) => {
|
|
|
|
f.debug_tuple("WorkerTask::ActiveRooms").field(&format_args!("_")).finish()
|
|
|
|
},
|
2023-01-10 19:59:30 -08:00
|
|
|
WorkerTask::DirectMessages(_) => {
|
|
|
|
f.debug_tuple("WorkerTask::DirectMessages")
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::Init(_, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::Init")
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::Login(style, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::Login")
|
|
|
|
.field(style)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
2023-01-11 17:54:49 -08:00
|
|
|
WorkerTask::GetInviter(invite, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::GetInviter").field(invite).finish()
|
|
|
|
},
|
2023-01-10 19:59:30 -08:00
|
|
|
WorkerTask::GetRoom(room_id, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::GetRoom")
|
|
|
|
.field(room_id)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::JoinRoom(s, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::JoinRoom")
|
|
|
|
.field(s)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::Members(room_id, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::Members")
|
|
|
|
.field(room_id)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::SpaceMembers(room_id, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::SpaceMembers")
|
|
|
|
.field(room_id)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::Spaces(_) => {
|
|
|
|
f.debug_tuple("WorkerTask::Spaces").field(&format_args!("_")).finish()
|
|
|
|
},
|
|
|
|
WorkerTask::TypingNotice(room_id) => {
|
|
|
|
f.debug_tuple("WorkerTask::TypingNotice").field(room_id).finish()
|
|
|
|
},
|
|
|
|
WorkerTask::Verify(act, sasv1, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::Verify")
|
|
|
|
.field(act)
|
|
|
|
.field(sasv1)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
WorkerTask::VerifyRequest(user_id, _) => {
|
|
|
|
f.debug_tuple("WorkerTask::VerifyRequest")
|
|
|
|
.field(user_id)
|
|
|
|
.field(&format_args!("_"))
|
|
|
|
.finish()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Requester {
|
2023-01-10 19:59:30 -08:00
|
|
|
pub client: Client,
|
|
|
|
pub tx: UnboundedSender<WorkerTask>,
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Requester {
|
|
|
|
pub fn init(&self, store: AsyncProgramStore) {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::Init(store, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::Login(style, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
pub fn direct_messages(&self) -> Vec<FetchedRoom> {
|
2022-12-29 18:00:59 -08:00
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::DirectMessages(reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
pub fn get_inviter(&self, invite: Invited) -> IambResult<Option<RoomMember>> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::GetInviter(invite, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
pub fn get_room(&self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> {
|
2022-12-29 18:00:59 -08:00
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::GetRoom(room_id, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn join_room(&self, name: String) -> IambResult<OwnedRoomId> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::JoinRoom(name, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
pub fn active_rooms(&self) -> Vec<FetchedRoom> {
|
2022-12-29 18:00:59 -08:00
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
self.tx.send(WorkerTask::ActiveRooms(reply)).unwrap();
|
2022-12-29 18:00:59 -08:00
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2023-01-04 12:51:33 -08:00
|
|
|
pub fn members(&self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::Members(room_id, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
pub fn space_members(&self, space: OwnedRoomId) -> IambResult<Vec<OwnedRoomId>> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::SpaceMembers(space, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn spaces(&self) -> Vec<(MatrixRoom, DisplayName)> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::Spaces(reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
2023-01-03 13:57:28 -08:00
|
|
|
pub fn typing_notice(&self, room_id: OwnedRoomId) {
|
|
|
|
self.tx.send(WorkerTask::TypingNotice(room_id)).unwrap();
|
|
|
|
}
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
pub fn verify(&self, act: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::Verify(act, sas, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn verify_request(&self, user_id: OwnedUserId) -> IambResult<EditInfo> {
|
|
|
|
let (reply, response) = oneshot();
|
|
|
|
|
|
|
|
self.tx.send(WorkerTask::VerifyRequest(user_id, reply)).unwrap();
|
|
|
|
|
|
|
|
return response.recv();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ClientWorker {
|
|
|
|
initialized: bool,
|
|
|
|
settings: ApplicationSettings,
|
|
|
|
client: Client,
|
2023-03-13 10:46:26 -07:00
|
|
|
load_handle: Option<JoinHandle<()>>,
|
2023-01-30 13:51:32 -08:00
|
|
|
rcpt_handle: Option<JoinHandle<()>>,
|
2023-03-13 10:46:26 -07:00
|
|
|
sync_handle: Option<JoinHandle<()>>,
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ClientWorker {
|
2023-01-10 19:59:30 -08:00
|
|
|
pub async fn spawn(settings: ApplicationSettings) -> Requester {
|
|
|
|
let (tx, rx) = unbounded_channel();
|
|
|
|
let account = &settings.profile;
|
|
|
|
|
2023-03-12 15:43:13 -07:00
|
|
|
let req_timeout = Duration::from_secs(settings.tunables.request_timeout);
|
|
|
|
|
|
|
|
// Set up the HTTP client.
|
2023-01-10 19:59:30 -08:00
|
|
|
let http = reqwest::Client::builder()
|
|
|
|
.user_agent(IAMB_USER_AGENT)
|
2023-03-12 15:43:13 -07:00
|
|
|
.timeout(req_timeout)
|
2023-01-10 19:59:30 -08:00
|
|
|
.pool_idle_timeout(Duration::from_secs(60))
|
|
|
|
.pool_max_idle_per_host(10)
|
|
|
|
.tcp_keepalive(Duration::from_secs(10))
|
|
|
|
.build()
|
|
|
|
.unwrap();
|
2022-12-29 18:00:59 -08:00
|
|
|
|
2023-03-12 15:43:13 -07:00
|
|
|
let req_config = RequestConfig::new().timeout(req_timeout).retry_timeout(req_timeout);
|
|
|
|
|
2023-01-10 19:59:30 -08:00
|
|
|
// Set up the Matrix client for the selected profile.
|
|
|
|
let client = Client::builder()
|
|
|
|
.http_client(Arc::new(http))
|
|
|
|
.homeserver_url(account.url.clone())
|
|
|
|
.store_config(StoreConfig::default())
|
|
|
|
.sled_store(settings.matrix_dir.as_path(), None)
|
|
|
|
.expect("Failed to setup up sled store for Matrix SDK")
|
2023-03-12 15:43:13 -07:00
|
|
|
.request_config(req_config)
|
2023-01-10 19:59:30 -08:00
|
|
|
.build()
|
|
|
|
.await
|
|
|
|
.expect("Failed to instantiate Matrix client");
|
2022-12-29 18:00:59 -08:00
|
|
|
|
2023-01-10 19:59:30 -08:00
|
|
|
let mut worker = ClientWorker {
|
|
|
|
initialized: false,
|
|
|
|
settings,
|
|
|
|
client: client.clone(),
|
2023-03-13 10:46:26 -07:00
|
|
|
load_handle: None,
|
2023-01-30 13:51:32 -08:00
|
|
|
rcpt_handle: None,
|
2023-03-13 10:46:26 -07:00
|
|
|
sync_handle: None,
|
2023-01-10 19:59:30 -08:00
|
|
|
};
|
|
|
|
|
2023-01-30 13:51:32 -08:00
|
|
|
tokio::spawn(async move {
|
2022-12-29 18:00:59 -08:00
|
|
|
worker.work(rx).await;
|
|
|
|
});
|
|
|
|
|
2023-01-10 19:59:30 -08:00
|
|
|
return Requester { client, tx };
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
2023-01-10 19:59:30 -08:00
|
|
|
async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) {
|
2022-12-29 18:00:59 -08:00
|
|
|
loop {
|
2023-01-10 19:59:30 -08:00
|
|
|
let t = rx.recv().await;
|
2022-12-29 18:00:59 -08:00
|
|
|
|
|
|
|
match t {
|
2023-01-10 19:59:30 -08:00
|
|
|
Some(task) => self.run(task).await,
|
|
|
|
None => {
|
2022-12-29 18:00:59 -08:00
|
|
|
break;
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(handle) = self.sync_handle.take() {
|
|
|
|
handle.abort();
|
|
|
|
}
|
2023-01-30 13:51:32 -08:00
|
|
|
|
|
|
|
if let Some(handle) = self.rcpt_handle.take() {
|
|
|
|
handle.abort();
|
|
|
|
}
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn run(&mut self, task: WorkerTask) {
|
|
|
|
match task {
|
|
|
|
WorkerTask::DirectMessages(reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.direct_messages().await);
|
|
|
|
},
|
|
|
|
WorkerTask::Init(store, reply) => {
|
|
|
|
assert_eq!(self.initialized, false);
|
|
|
|
self.init(store).await;
|
|
|
|
reply.send(());
|
|
|
|
},
|
|
|
|
WorkerTask::JoinRoom(room_id, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.join_room(room_id).await);
|
|
|
|
},
|
2023-01-11 17:54:49 -08:00
|
|
|
WorkerTask::GetInviter(invited, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.get_inviter(invited).await);
|
|
|
|
},
|
2022-12-29 18:00:59 -08:00
|
|
|
WorkerTask::GetRoom(room_id, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.get_room(room_id).await);
|
|
|
|
},
|
2023-01-11 17:54:49 -08:00
|
|
|
WorkerTask::ActiveRooms(reply) => {
|
2022-12-29 18:00:59 -08:00
|
|
|
assert!(self.initialized);
|
2023-01-11 17:54:49 -08:00
|
|
|
reply.send(self.active_rooms().await);
|
2022-12-29 18:00:59 -08:00
|
|
|
},
|
|
|
|
WorkerTask::Login(style, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.login_and_sync(style).await);
|
|
|
|
},
|
2023-01-04 12:51:33 -08:00
|
|
|
WorkerTask::Members(room_id, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.members(room_id).await);
|
|
|
|
},
|
2022-12-29 18:00:59 -08:00
|
|
|
WorkerTask::SpaceMembers(space, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.space_members(space).await);
|
|
|
|
},
|
|
|
|
WorkerTask::Spaces(reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.spaces().await);
|
|
|
|
},
|
2023-01-03 13:57:28 -08:00
|
|
|
WorkerTask::TypingNotice(room_id) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
self.typing_notice(room_id).await;
|
|
|
|
},
|
2022-12-29 18:00:59 -08:00
|
|
|
WorkerTask::Verify(act, sas, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.verify(act, sas).await);
|
|
|
|
},
|
|
|
|
WorkerTask::VerifyRequest(user_id, reply) => {
|
|
|
|
assert!(self.initialized);
|
|
|
|
reply.send(self.verify_request(user_id).await);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn init(&mut self, store: AsyncProgramStore) {
|
2023-01-26 15:40:16 -08:00
|
|
|
self.client.add_event_handler_context(store.clone());
|
2022-12-29 18:00:59 -08:00
|
|
|
|
2023-01-03 13:57:28 -08:00
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: SyncTypingEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let room_id = room.room_id().to_owned();
|
|
|
|
let mut locked = store.lock().await;
|
|
|
|
|
|
|
|
let users = ev
|
|
|
|
.content
|
|
|
|
.user_ids
|
|
|
|
.into_iter()
|
|
|
|
.filter(|u| u != &locked.application.settings.profile.user_id)
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
locked.application.get_room_info(room_id).set_typing(users);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2023-03-01 18:46:33 -08:00
|
|
|
let _ =
|
|
|
|
self.client
|
|
|
|
.add_event_handler(|ev: PresenceEvent, store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let mut locked = store.lock().await;
|
|
|
|
locked.application.presences.insert(ev.sender, ev.content.presence);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: SyncStateEvent<RoomNameEventContent>,
|
|
|
|
room: MatrixRoom,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
if let SyncStateEvent::Original(ev) = ev {
|
|
|
|
if let Some(room_name) = ev.content.name {
|
|
|
|
let room_id = room.room_id().to_owned();
|
|
|
|
let room_name = Some(room_name.to_string());
|
|
|
|
let mut locked = store.lock().await;
|
2023-03-01 18:46:33 -08:00
|
|
|
let mut info = locked.application.rooms.get_or_default(room_id.clone());
|
2022-12-29 18:00:59 -08:00
|
|
|
info.name = room_name;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: SyncMessageLikeEvent<RoomMessageEventContent>,
|
|
|
|
room: MatrixRoom,
|
|
|
|
client: Client,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let room_id = room.room_id();
|
|
|
|
|
|
|
|
if let Some(msg) = ev.as_original() {
|
|
|
|
if let MessageType::VerificationRequest(_) = msg.content.msgtype {
|
|
|
|
if let Some(request) = client
|
|
|
|
.encryption()
|
|
|
|
.get_verification_request(ev.sender(), ev.event_id())
|
|
|
|
.await
|
|
|
|
{
|
|
|
|
request.accept().await.expect("Failed to accept request");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut locked = store.lock().await;
|
2023-03-01 18:46:33 -08:00
|
|
|
|
|
|
|
let sender = ev.sender().to_owned();
|
|
|
|
let _ = locked.application.presences.get_or_default(sender);
|
|
|
|
|
|
|
|
let info = locked.application.get_room_info(room_id.to_owned());
|
2023-01-19 16:05:02 -08:00
|
|
|
info.insert(ev.into_full_event(room_id.to_owned()));
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2023-02-09 17:53:33 -08:00
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: SyncMessageLikeEvent<ReactionEventContent>,
|
|
|
|
room: MatrixRoom,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let room_id = room.room_id();
|
|
|
|
|
|
|
|
let mut locked = store.lock().await;
|
2023-03-01 18:46:33 -08:00
|
|
|
|
|
|
|
let sender = ev.sender().to_owned();
|
|
|
|
let _ = locked.application.presences.get_or_default(sender);
|
|
|
|
|
2023-02-09 17:53:33 -08:00
|
|
|
let info = locked.application.get_room_info(room_id.to_owned());
|
|
|
|
info.insert_reaction(ev.into_full_event(room_id.to_owned()));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2023-01-13 17:53:54 -08:00
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: OriginalSyncRoomRedactionEvent,
|
|
|
|
room: MatrixRoom,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let room_id = room.room_id();
|
|
|
|
let room_info = room.clone_info();
|
|
|
|
let room_version = room_info.room_version().unwrap_or(&RoomVersionId::V1);
|
|
|
|
|
|
|
|
let mut locked = store.lock().await;
|
|
|
|
let info = locked.application.get_room_info(room_id.to_owned());
|
|
|
|
|
2023-02-09 17:53:33 -08:00
|
|
|
match info.keys.get(&ev.redacts) {
|
|
|
|
None => return,
|
|
|
|
Some(EventLocation::Message(key)) => {
|
|
|
|
if let Some(msg) = info.messages.get_mut(key) {
|
|
|
|
let ev = SyncRoomRedactionEvent::Original(ev);
|
|
|
|
msg.event.redact(ev, room_version);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Some(EventLocation::Reaction(event_id)) => {
|
|
|
|
if let Some(reactions) = info.reactions.get_mut(event_id) {
|
|
|
|
reactions.remove(&ev.redacts);
|
|
|
|
}
|
2023-01-13 17:53:54 -08:00
|
|
|
|
2023-02-09 17:53:33 -08:00
|
|
|
info.keys.remove(&ev.redacts);
|
|
|
|
},
|
2023-01-13 17:53:54 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: OriginalSyncKeyVerificationStartEvent,
|
|
|
|
client: Client,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let tx_id = ev.content.relates_to.event_id.as_ref();
|
|
|
|
|
|
|
|
if let Some(Verification::SasV1(sas)) =
|
|
|
|
client.encryption().get_verification(&ev.sender, tx_id).await
|
|
|
|
{
|
|
|
|
sas.accept().await.unwrap();
|
|
|
|
|
|
|
|
store.lock().await.application.insert_sas(sas)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: OriginalSyncKeyVerificationKeyEvent,
|
|
|
|
client: Client,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let tx_id = ev.content.relates_to.event_id.as_ref();
|
|
|
|
|
|
|
|
if let Some(Verification::SasV1(sas)) =
|
|
|
|
client.encryption().get_verification(&ev.sender, tx_id).await
|
|
|
|
{
|
|
|
|
store.lock().await.application.insert_sas(sas);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: OriginalSyncKeyVerificationDoneEvent,
|
|
|
|
client: Client,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let tx_id = ev.content.relates_to.event_id.as_ref();
|
|
|
|
|
|
|
|
if let Some(Verification::SasV1(sas)) =
|
|
|
|
client.encryption().get_verification(&ev.sender, tx_id).await
|
|
|
|
{
|
|
|
|
store.lock().await.application.insert_sas(sas);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: ToDeviceKeyVerificationRequestEvent, client: Client| {
|
|
|
|
async move {
|
|
|
|
let request = client
|
|
|
|
.encryption()
|
|
|
|
.get_verification_request(&ev.sender, &ev.content.transaction_id)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
request.accept().await.unwrap();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: ToDeviceKeyVerificationStartEvent,
|
|
|
|
client: Client,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let tx_id = ev.content.transaction_id;
|
|
|
|
|
|
|
|
if let Some(Verification::SasV1(sas)) =
|
|
|
|
client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
|
|
|
|
{
|
|
|
|
sas.accept().await.unwrap();
|
|
|
|
|
|
|
|
store.lock().await.application.insert_sas(sas);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: ToDeviceKeyVerificationKeyEvent, client: Client, store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let tx_id = ev.content.transaction_id;
|
|
|
|
|
|
|
|
if let Some(Verification::SasV1(sas)) =
|
|
|
|
client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
|
|
|
|
{
|
|
|
|
store.lock().await.application.insert_sas(sas);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let _ = self.client.add_event_handler(
|
|
|
|
|ev: ToDeviceKeyVerificationDoneEvent,
|
|
|
|
client: Client,
|
|
|
|
store: Ctx<AsyncProgramStore>| {
|
|
|
|
async move {
|
|
|
|
let tx_id = ev.content.transaction_id;
|
|
|
|
|
|
|
|
if let Some(Verification::SasV1(sas)) =
|
|
|
|
client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
|
|
|
|
{
|
|
|
|
store.lock().await.application.insert_sas(sas);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2023-03-13 10:46:26 -07:00
|
|
|
self.rcpt_handle = tokio::spawn({
|
|
|
|
let store = store.clone();
|
|
|
|
let client = self.client.clone();
|
2023-01-30 13:51:32 -08:00
|
|
|
|
2023-03-13 10:46:26 -07:00
|
|
|
async move {
|
|
|
|
// Update the displayed read receipts every 5 seconds.
|
|
|
|
let mut interval = tokio::time::interval(Duration::from_secs(5));
|
2023-01-26 15:40:16 -08:00
|
|
|
|
2023-03-13 10:46:26 -07:00
|
|
|
loop {
|
|
|
|
interval.tick().await;
|
2023-01-26 15:40:16 -08:00
|
|
|
|
2023-03-13 10:46:26 -07:00
|
|
|
let receipts = update_receipts(&client).await;
|
|
|
|
store.lock().await.application.set_receipts(receipts).await;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.into();
|
|
|
|
|
|
|
|
self.load_handle = tokio::spawn({
|
|
|
|
let client = self.client.clone();
|
|
|
|
|
|
|
|
async move {
|
|
|
|
// Load older messages every 2 seconds.
|
|
|
|
let mut interval = tokio::time::interval(Duration::from_secs(2));
|
|
|
|
loop {
|
|
|
|
interval.tick().await;
|
|
|
|
load_older(&client, &store).await;
|
|
|
|
}
|
2023-01-26 15:40:16 -08:00
|
|
|
}
|
2023-01-30 13:51:32 -08:00
|
|
|
})
|
|
|
|
.into();
|
2023-01-26 15:40:16 -08:00
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
self.initialized = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn login_and_sync(&mut self, style: LoginStyle) -> IambResult<EditInfo> {
|
|
|
|
let client = self.client.clone();
|
|
|
|
|
|
|
|
match style {
|
|
|
|
LoginStyle::SessionRestore(session) => {
|
|
|
|
client.restore_login(session).await.map_err(IambError::from)?;
|
|
|
|
},
|
|
|
|
LoginStyle::Password(password) => {
|
|
|
|
let resp = client
|
|
|
|
.login_username(&self.settings.profile.user_id, &password)
|
|
|
|
.initial_device_display_name(initial_devname().as_str())
|
|
|
|
.send()
|
|
|
|
.await
|
|
|
|
.map_err(IambError::from)?;
|
|
|
|
let file = File::create(self.settings.session_json.as_path())?;
|
|
|
|
let writer = BufWriter::new(file);
|
|
|
|
let session = Session::from(resp);
|
|
|
|
serde_json::to_writer(writer, &session).map_err(IambError::from)?;
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
let handle = tokio::spawn(async move {
|
|
|
|
loop {
|
|
|
|
let settings = SyncSettings::default();
|
|
|
|
|
|
|
|
let _ = client.sync(settings).await;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
self.sync_handle = Some(handle);
|
|
|
|
|
|
|
|
self.client
|
|
|
|
.sync_once(SyncSettings::default())
|
|
|
|
.await
|
|
|
|
.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
Ok(Some(InfoMessage::from("Successfully logged in!")))
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
async fn direct_message(&mut self, user: OwnedUserId) -> IambResult<FetchedRoom> {
|
|
|
|
for (room, name, tags) in self.direct_messages().await {
|
2022-12-29 18:00:59 -08:00
|
|
|
if room.get_member(user.as_ref()).await.map_err(IambError::from)?.is_some() {
|
2023-01-25 17:54:16 -08:00
|
|
|
return Ok((room, name, tags));
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-03 16:37:11 -08:00
|
|
|
let rt = CreateRoomType::Direct(user.clone());
|
|
|
|
let flags = CreateRoomFlags::ENCRYPTED;
|
2022-12-29 18:00:59 -08:00
|
|
|
|
2023-03-03 16:37:11 -08:00
|
|
|
match create_room(&self.client, None, rt, flags).await {
|
|
|
|
Ok(room_id) => self.get_room(room_id).await,
|
2022-12-29 18:00:59 -08:00
|
|
|
Err(e) => {
|
|
|
|
error!(
|
|
|
|
user_id = user.as_str(),
|
|
|
|
err = e.to_string(),
|
|
|
|
"Failed to create direct message room"
|
|
|
|
);
|
|
|
|
|
2023-01-30 13:51:32 -08:00
|
|
|
let msg = format!("Could not open a room with {user}");
|
2022-12-29 18:00:59 -08:00
|
|
|
let err = UIError::Failure(msg);
|
|
|
|
|
|
|
|
Err(err)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
async fn get_inviter(&mut self, invited: Invited) -> IambResult<Option<RoomMember>> {
|
|
|
|
let details = invited.invite_details().await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
Ok(details.inviter)
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
async fn get_room(&mut self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> {
|
2022-12-29 18:00:59 -08:00
|
|
|
if let Some(room) = self.client.get_room(&room_id) {
|
|
|
|
let name = room.display_name().await.map_err(IambError::from)?;
|
2023-01-25 17:54:16 -08:00
|
|
|
let tags = room.tags().await.map_err(IambError::from)?;
|
2022-12-29 18:00:59 -08:00
|
|
|
|
2023-01-25 17:54:16 -08:00
|
|
|
Ok((room, name, tags))
|
2022-12-29 18:00:59 -08:00
|
|
|
} else {
|
|
|
|
Err(IambError::UnknownRoom(room_id).into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn join_room(&mut self, name: String) -> IambResult<OwnedRoomId> {
|
|
|
|
if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) {
|
|
|
|
match self.client.join_room_by_id_or_alias(&alias_id, &[]).await {
|
|
|
|
Ok(resp) => Ok(resp.room_id),
|
|
|
|
Err(e) => {
|
|
|
|
let msg = e.to_string();
|
|
|
|
let err = UIError::Failure(msg);
|
|
|
|
|
|
|
|
return Err(err);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
} else if let Ok(user) = OwnedUserId::try_from(name.as_str()) {
|
|
|
|
let room = self.direct_message(user).await?.0;
|
|
|
|
|
|
|
|
return Ok(room.room_id().to_owned());
|
|
|
|
} else {
|
|
|
|
let msg = format!("{:?} is not a valid room or user name", name.as_str());
|
|
|
|
let err = UIError::Failure(msg);
|
|
|
|
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
async fn direct_messages(&self) -> Vec<FetchedRoom> {
|
2022-12-29 18:00:59 -08:00
|
|
|
let mut rooms = vec![];
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
for room in self.client.invited_rooms().into_iter() {
|
|
|
|
if !room.is_direct() {
|
2022-12-29 18:00:59 -08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
let name = room.display_name().await.unwrap_or(DisplayName::Empty);
|
2023-01-26 15:23:15 -08:00
|
|
|
let tags = room.tags().await.unwrap_or_default();
|
2023-01-11 17:54:49 -08:00
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
rooms.push((room.into(), name, tags));
|
2023-01-11 17:54:49 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
for room in self.client.joined_rooms().into_iter() {
|
|
|
|
if !room.is_direct() {
|
|
|
|
continue;
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
2023-01-11 17:54:49 -08:00
|
|
|
|
|
|
|
let name = room.display_name().await.unwrap_or(DisplayName::Empty);
|
2023-01-26 15:23:15 -08:00
|
|
|
let tags = room.tags().await.unwrap_or_default();
|
2023-01-11 17:54:49 -08:00
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
rooms.push((room.into(), name, tags));
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
return rooms;
|
|
|
|
}
|
|
|
|
|
2023-01-26 15:23:15 -08:00
|
|
|
async fn active_rooms(&self) -> Vec<FetchedRoom> {
|
2022-12-29 18:00:59 -08:00
|
|
|
let mut rooms = vec![];
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
for room in self.client.invited_rooms().into_iter() {
|
2022-12-29 18:00:59 -08:00
|
|
|
if room.is_space() || room.is_direct() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
let name = room.display_name().await.unwrap_or(DisplayName::Empty);
|
2023-01-25 17:54:16 -08:00
|
|
|
let tags = room.tags().await.unwrap_or_default();
|
2023-01-11 17:54:49 -08:00
|
|
|
|
2023-01-25 17:54:16 -08:00
|
|
|
rooms.push((room.into(), name, tags));
|
2023-01-11 17:54:49 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
for room in self.client.joined_rooms().into_iter() {
|
|
|
|
if room.is_space() || room.is_direct() {
|
|
|
|
continue;
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
2023-01-11 17:54:49 -08:00
|
|
|
|
|
|
|
let name = room.display_name().await.unwrap_or(DisplayName::Empty);
|
2023-01-25 17:54:16 -08:00
|
|
|
let tags = room.tags().await.unwrap_or_default();
|
2023-01-11 17:54:49 -08:00
|
|
|
|
2023-01-25 17:54:16 -08:00
|
|
|
rooms.push((room.into(), name, tags));
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
return rooms;
|
|
|
|
}
|
|
|
|
|
2023-01-04 12:51:33 -08:00
|
|
|
async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
|
|
|
|
if let Some(room) = self.client.get_room(room_id.as_ref()) {
|
|
|
|
Ok(room.active_members().await.map_err(IambError::from)?)
|
|
|
|
} else {
|
|
|
|
Err(IambError::UnknownRoom(room_id).into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
async fn space_members(&mut self, space: OwnedRoomId) -> IambResult<Vec<OwnedRoomId>> {
|
|
|
|
let mut req = SpaceHierarchyRequest::new(&space);
|
|
|
|
req.limit = Some(1000u32.into());
|
|
|
|
req.max_depth = Some(1u32.into());
|
|
|
|
|
|
|
|
let resp = self.client.send(req, None).await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
let rooms = resp.rooms.into_iter().map(|chunk| chunk.room_id).collect();
|
|
|
|
|
|
|
|
Ok(rooms)
|
|
|
|
}
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
async fn spaces(&self) -> Vec<(MatrixRoom, DisplayName)> {
|
2022-12-29 18:00:59 -08:00
|
|
|
let mut spaces = vec![];
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
for room in self.client.invited_rooms().into_iter() {
|
2022-12-29 18:00:59 -08:00
|
|
|
if !room.is_space() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-01-11 17:54:49 -08:00
|
|
|
let name = room.display_name().await.unwrap_or(DisplayName::Empty);
|
|
|
|
|
|
|
|
spaces.push((room.into(), name));
|
|
|
|
}
|
|
|
|
|
|
|
|
for room in self.client.joined_rooms().into_iter() {
|
|
|
|
if !room.is_space() {
|
|
|
|
continue;
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
2023-01-11 17:54:49 -08:00
|
|
|
|
|
|
|
let name = room.display_name().await.unwrap_or(DisplayName::Empty);
|
|
|
|
|
|
|
|
spaces.push((room.into(), name));
|
2022-12-29 18:00:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
return spaces;
|
|
|
|
}
|
|
|
|
|
2023-01-03 13:57:28 -08:00
|
|
|
async fn typing_notice(&mut self, room_id: OwnedRoomId) {
|
|
|
|
if let Some(room) = self.client.get_joined_room(room_id.as_ref()) {
|
|
|
|
let _ = room.typing_notice(true).await;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-29 18:00:59 -08:00
|
|
|
async fn verify(&self, action: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
|
|
|
|
match action {
|
|
|
|
VerifyAction::Accept => {
|
|
|
|
sas.accept().await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
Ok(Some(InfoMessage::from("Accepted verification request")))
|
|
|
|
},
|
|
|
|
VerifyAction::Confirm => {
|
|
|
|
if sas.is_done() || sas.is_cancelled() {
|
|
|
|
let msg = "Can only confirm in-progress verifications!";
|
|
|
|
let err = UIError::Failure(msg.into());
|
|
|
|
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
sas.confirm().await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
Ok(Some(InfoMessage::from("Confirmed verification")))
|
|
|
|
},
|
|
|
|
VerifyAction::Cancel => {
|
|
|
|
if sas.is_done() || sas.is_cancelled() {
|
|
|
|
let msg = "Can only cancel in-progress verifications!";
|
|
|
|
let err = UIError::Failure(msg.into());
|
|
|
|
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
sas.cancel().await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
Ok(Some(InfoMessage::from("Cancelled verification")))
|
|
|
|
},
|
|
|
|
VerifyAction::Mismatch => {
|
|
|
|
if sas.is_done() || sas.is_cancelled() {
|
|
|
|
let msg = "Can only cancel in-progress verifications!";
|
|
|
|
let err = UIError::Failure(msg.into());
|
|
|
|
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
sas.mismatch().await.map_err(IambError::from)?;
|
|
|
|
|
|
|
|
Ok(Some(InfoMessage::from("Cancelled verification")))
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn verify_request(&self, user_id: OwnedUserId) -> IambResult<EditInfo> {
|
|
|
|
let enc = self.client.encryption();
|
|
|
|
|
|
|
|
match enc.get_user_identity(user_id.as_ref()).await.map_err(IambError::from)? {
|
|
|
|
Some(identity) => {
|
|
|
|
let methods = vec![VerificationMethod::SasV1];
|
|
|
|
let request = identity.request_verification_with_methods(methods);
|
|
|
|
let _req = request.await.map_err(IambError::from)?;
|
2023-01-30 13:51:32 -08:00
|
|
|
let info = format!("Sent verification request to {user_id}");
|
2022-12-29 18:00:59 -08:00
|
|
|
|
|
|
|
Ok(InfoMessage::from(info).into())
|
|
|
|
},
|
|
|
|
None => {
|
2023-01-30 13:51:32 -08:00
|
|
|
let msg = format!("Could not find identity information for {user_id}");
|
2022-12-29 18:00:59 -08:00
|
|
|
let err = UIError::Failure(msg);
|
|
|
|
|
|
|
|
Err(err)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|