| @@ -1,3 +1,4 @@ |
| |
1 | use std::collections::HashMap; |
| 1 | use std::convert::TryFrom; |
2 | use std::convert::TryFrom; |
| 2 | use std::fmt::{Debug, Formatter}; |
3 | use std::fmt::{Debug, Formatter}; |
| 3 | use std::fs::File; |
4 | use std::fs::File; |
| @@ -5,12 +6,12 @@ use std::io::BufWriter; |
| 5 | use std::str::FromStr; |
6 | use std::str::FromStr; |
| 6 | use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; |
7 | use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; |
| 7 | use std::sync::Arc; |
8 | use std::sync::Arc; |
| 8 | use std::time::Duration; |
9 | use std::time::{Duration, Instant}; |
| 9 | |
10 | |
| 10 | use gethostname::gethostname; |
11 | use gethostname::gethostname; |
| 11 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; |
12 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; |
| 12 | use tokio::task::JoinHandle; |
13 | use tokio::task::JoinHandle; |
| 13 | use tracing::error; |
14 | use tracing::{error, warn}; |
| 14 | |
15 | |
| 15 | use matrix_sdk::{ |
16 | use matrix_sdk::{ |
| 16 | config::{RequestConfig, StoreConfig, SyncSettings}, |
17 | config::{RequestConfig, StoreConfig, SyncSettings}, |
| @@ -44,6 +45,7 @@ use matrix_sdk::{ |
| 44 | tag::Tags, |
45 | tag::Tags, |
| 45 | typing::SyncTypingEvent, |
46 | typing::SyncTypingEvent, |
| 46 | AnyInitialStateEvent, |
47 | AnyInitialStateEvent, |
| |
48 | AnyMessageLikeEvent, |
| 47 | AnyTimelineEvent, |
49 | AnyTimelineEvent, |
| 48 | EmptyStateKey, |
50 | EmptyStateKey, |
| 49 | InitialStateEvent, |
51 | InitialStateEvent, |
| @@ -56,6 +58,7 @@ use matrix_sdk::{ |
| 56 | OwnedRoomId, |
58 | OwnedRoomId, |
| 57 | OwnedRoomOrAliasId, |
59 | OwnedRoomOrAliasId, |
| 58 | OwnedUserId, |
60 | OwnedUserId, |
| |
61 | RoomId, |
| 59 | RoomVersionId, |
62 | RoomVersionId, |
| 60 | }, |
63 | }, |
| 61 | Client, |
64 | Client, |
| @@ -68,12 +71,14 @@ use modalkit::editing::action::{EditInfo, InfoMessage, UIError}; |
| 68 | use crate::{ |
71 | use crate::{ |
| 69 | base::{ |
72 | base::{ |
| 70 | AsyncProgramStore, |
73 | AsyncProgramStore, |
| |
74 | ChatStore, |
| 71 | CreateRoomFlags, |
75 | CreateRoomFlags, |
| 72 | CreateRoomType, |
76 | CreateRoomType, |
| 73 | EventLocation, |
77 | EventLocation, |
| 74 | IambError, |
78 | IambError, |
| 75 | IambResult, |
79 | IambResult, |
| 76 | Receipts, |
80 | Receipts, |
| |
81 | RoomFetchStatus, |
| 77 | VerifyAction, |
82 | VerifyAction, |
| 78 | }, |
83 | }, |
| 79 | message::MessageFetchResult, |
84 | message::MessageFetchResult, |
| @@ -82,6 +87,7 @@ use crate::{ |
| 82 | |
87 | |
| 83 | const IAMB_DEVICE_NAME: &str = "iamb"; |
88 | const IAMB_DEVICE_NAME: &str = "iamb"; |
| 84 | const IAMB_USER_AGENT: &str = "iamb"; |
89 | const IAMB_USER_AGENT: &str = "iamb"; |
| |
90 | const MIN_MSG_LOAD: u32 = 50; |
| 85 | |
91 | |
| 86 | fn initial_devname() -> String { |
92 | fn initial_devname() -> String { |
| 87 | format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy()) |
93 | format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy()) |
| @@ -158,6 +164,113 @@ pub async fn create_room( |
| 158 | return Ok(resp.room_id); |
164 | return Ok(resp.room_id); |
| 159 | } |
165 | } |
| 160 | |
166 | |
| |
167 | async fn load_plan(store: &AsyncProgramStore) -> HashMap<OwnedRoomId, Option<String>> { |
| |
168 | let mut locked = store.lock().await; |
| |
169 | let ChatStore { need_load, rooms, .. } = &mut locked.application; |
| |
170 | let mut plan = HashMap::new(); |
| |
171 | |
| |
172 | for room_id in std::mem::take(need_load).into_iter() { |
| |
173 | let info = rooms.get_or_default(room_id.clone()); |
| |
174 | |
| |
175 | if info.recently_fetched() || info.fetching { |
| |
176 | need_load.insert(room_id); |
| |
177 | continue; |
| |
178 | } else { |
| |
179 | info.fetch_last = Instant::now().into(); |
| |
180 | info.fetching = true; |
| |
181 | } |
| |
182 | |
| |
183 | let fetch_id = match &info.fetch_id { |
| |
184 | RoomFetchStatus::Done => continue, |
| |
185 | RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()), |
| |
186 | RoomFetchStatus::NotStarted => None, |
| |
187 | }; |
| |
188 | |
| |
189 | plan.insert(room_id, fetch_id); |
| |
190 | } |
| |
191 | |
| |
192 | return plan; |
| |
193 | } |
| |
194 | |
| |
195 | async fn load_older_one( |
| |
196 | client: Client, |
| |
197 | room_id: &RoomId, |
| |
198 | fetch_id: Option<String>, |
| |
199 | limit: u32, |
| |
200 | ) -> MessageFetchResult { |
| |
201 | if let Some(room) = client.get_room(room_id) { |
| |
202 | let mut opts = match &fetch_id { |
| |
203 | Some(id) => MessagesOptions::backward().from(id.as_str()), |
| |
204 | None => MessagesOptions::backward(), |
| |
205 | }; |
| |
206 | opts.limit = limit.into(); |
| |
207 | |
| |
208 | let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?; |
| |
209 | |
| |
210 | let msgs = chunk.into_iter().filter_map(|ev| { |
| |
211 | match ev.event.deserialize() { |
| |
212 | Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg), |
| |
213 | Ok(AnyTimelineEvent::State(_)) => None, |
| |
214 | Err(_) => None, |
| |
215 | } |
| |
216 | }); |
| |
217 | |
| |
218 | Ok((end, msgs.collect())) |
| |
219 | } else { |
| |
220 | Err(IambError::UnknownRoom(room_id.to_owned()).into()) |
| |
221 | } |
| |
222 | } |
| |
223 | |
| |
224 | async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) { |
| |
225 | let mut locked = store.lock().await; |
| |
226 | let ChatStore { need_load, presences, rooms, .. } = &mut locked.application; |
| |
227 | let info = rooms.get_or_default(room_id.clone()); |
| |
228 | info.fetching = false; |
| |
229 | |
| |
230 | match res { |
| |
231 | Ok((fetch_id, msgs)) => { |
| |
232 | for msg in msgs.into_iter() { |
| |
233 | let sender = msg.sender().to_owned(); |
| |
234 | let _ = presences.get_or_default(sender); |
| |
235 | |
| |
236 | match msg { |
| |
237 | AnyMessageLikeEvent::RoomMessage(msg) => { |
| |
238 | info.insert(msg); |
| |
239 | }, |
| |
240 | AnyMessageLikeEvent::Reaction(ev) => { |
| |
241 | info.insert_reaction(ev); |
| |
242 | }, |
| |
243 | _ => continue, |
| |
244 | } |
| |
245 | } |
| |
246 | |
| |
247 | info.fetch_id = fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore); |
| |
248 | }, |
| |
249 | Err(e) => { |
| |
250 | warn!(room_id = room_id.as_str(), err = e.to_string(), "Failed to load older messages"); |
| |
251 | |
| |
252 | // Wait and try again. |
| |
253 | need_load.insert(room_id); |
| |
254 | }, |
| |
255 | } |
| |
256 | } |
| |
257 | |
| |
258 | async fn load_older(client: &Client, store: &AsyncProgramStore) { |
| |
259 | let limit = MIN_MSG_LOAD; |
| |
260 | let plan = load_plan(store).await; |
| |
261 | |
| |
262 | // Fetch each room separately, so they don't block each other. |
| |
263 | for (room_id, fetch_id) in plan.into_iter() { |
| |
264 | let client = client.clone(); |
| |
265 | let store = store.clone(); |
| |
266 | |
| |
267 | tokio::spawn(async move { |
| |
268 | let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await; |
| |
269 | load_insert(room_id, res, store).await; |
| |
270 | }); |
| |
271 | } |
| |
272 | } |
| |
273 | |
| 161 | #[derive(Debug)] |
274 | #[derive(Debug)] |
| 162 | pub enum LoginStyle { |
275 | pub enum LoginStyle { |
| 163 | SessionRestore(Session), |
276 | SessionRestore(Session), |
| @@ -216,7 +329,6 @@ pub enum WorkerTask { |
| 216 | ActiveRooms(ClientReply<Vec<FetchedRoom>>), |
329 | ActiveRooms(ClientReply<Vec<FetchedRoom>>), |
| 217 | DirectMessages(ClientReply<Vec<FetchedRoom>>), |
330 | DirectMessages(ClientReply<Vec<FetchedRoom>>), |
| 218 | Init(AsyncProgramStore, ClientReply<()>), |
331 | Init(AsyncProgramStore, ClientReply<()>), |
| 219 | LoadOlder(OwnedRoomId, Option<String>, u32, ClientReply<MessageFetchResult>), |
| |
| 220 | Login(LoginStyle, ClientReply<IambResult<EditInfo>>), |
332 | Login(LoginStyle, ClientReply<IambResult<EditInfo>>), |
| 221 | GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>), |
333 | GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>), |
| 222 | GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>), |
334 | GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>), |
| @@ -246,14 +358,6 @@ impl Debug for WorkerTask { |
| 246 | .field(&format_args!("_")) |
358 | .field(&format_args!("_")) |
| 247 | .finish() |
359 | .finish() |
| 248 | }, |
360 | }, |
| 249 | WorkerTask::LoadOlder(room_id, from, n, _) => { |
| |
| 250 | f.debug_tuple("WorkerTask::LoadOlder") |
| |
| 251 | .field(room_id) |
| |
| 252 | .field(from) |
| |
| 253 | .field(n) |
| |
| 254 | .field(&format_args!("_")) |
| |
| 255 | .finish() |
| |
| 256 | }, |
| |
| 257 | WorkerTask::Login(style, _) => { |
361 | WorkerTask::Login(style, _) => { |
| 258 | f.debug_tuple("WorkerTask::Login") |
362 | f.debug_tuple("WorkerTask::Login") |
| 259 | .field(style) |
363 | .field(style) |
| @@ -325,21 +429,6 @@ impl Requester { |
| 325 | return response.recv(); |
429 | return response.recv(); |
| 326 | } |
430 | } |
| 327 | |
431 | |
| 328 | pub fn load_older( |
| |
| 329 | &self, |
| |
| 330 | room_id: OwnedRoomId, |
| |
| 331 | fetch_id: Option<String>, |
| |
| 332 | limit: u32, |
| |
| 333 | ) -> MessageFetchResult { |
| |
| 334 | let (reply, response) = oneshot(); |
| |
| 335 | |
| |
| 336 | self.tx |
| |
| 337 | .send(WorkerTask::LoadOlder(room_id, fetch_id, limit, reply)) |
| |
| 338 | .unwrap(); |
| |
| 339 | |
| |
| 340 | return response.recv(); |
| |
| 341 | } |
| |
| 342 | |
| |
| 343 | pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> { |
432 | pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> { |
| 344 | let (reply, response) = oneshot(); |
433 | let (reply, response) = oneshot(); |
| 345 | |
434 | |
| @@ -437,8 +526,9 @@ pub struct ClientWorker { |
| 437 | initialized: bool, |
526 | initialized: bool, |
| 438 | settings: ApplicationSettings, |
527 | settings: ApplicationSettings, |
| 439 | client: Client, |
528 | client: Client, |
| 440 | sync_handle: Option<JoinHandle<()>>, |
529 | load_handle: Option<JoinHandle<()>>, |
| 441 | rcpt_handle: Option<JoinHandle<()>>, |
530 | rcpt_handle: Option<JoinHandle<()>>, |
| |
531 | sync_handle: Option<JoinHandle<()>>, |
| 442 | } |
532 | } |
| 443 | |
533 | |
| 444 | impl ClientWorker { |
534 | impl ClientWorker { |
| @@ -476,8 +566,9 @@ impl ClientWorker { |
| 476 | initialized: false, |
566 | initialized: false, |
| 477 | settings, |
567 | settings, |
| 478 | client: client.clone(), |
568 | client: client.clone(), |
| 479 | sync_handle: None, |
569 | load_handle: None, |
| 480 | rcpt_handle: None, |
570 | rcpt_handle: None, |
| |
571 | sync_handle: None, |
| 481 | }; |
572 | }; |
| 482 | |
573 | |
| 483 | tokio::spawn(async move { |
574 | tokio::spawn(async move { |
| @@ -535,10 +626,6 @@ impl ClientWorker { |
| 535 | assert!(self.initialized); |
626 | assert!(self.initialized); |
| 536 | reply.send(self.active_rooms().await); |
627 | reply.send(self.active_rooms().await); |
| 537 | }, |
628 | }, |
| 538 | WorkerTask::LoadOlder(room_id, fetch_id, limit, reply) => { |
| |
| 539 | assert!(self.initialized); |
| |
| 540 | reply.send(self.load_older(room_id, fetch_id, limit).await); |
| |
| 541 | }, |
| |
| 542 | WorkerTask::Login(style, reply) => { |
629 | WorkerTask::Login(style, reply) => { |
| 543 | assert!(self.initialized); |
630 | assert!(self.initialized); |
| 544 | reply.send(self.login_and_sync(style).await); |
631 | reply.send(self.login_and_sync(style).await); |
| @@ -811,17 +898,34 @@ impl ClientWorker { |
| 811 | }, |
898 | }, |
| 812 | ); |
899 | ); |
| 813 | |
900 | |
| 814 | let client = self.client.clone(); |
901 | self.rcpt_handle = tokio::spawn({ |
| |
902 | let store = store.clone(); |
| |
903 | let client = self.client.clone(); |
| 815 | |
904 | |
| 816 | self.rcpt_handle = tokio::spawn(async move { |
905 | async move { |
| 817 | // Update the displayed read receipts ever 5 seconds. |
906 | // Update the displayed read receipts every 5 seconds. |
| 818 | let mut interval = tokio::time::interval(Duration::from_secs(5)); |
907 | let mut interval = tokio::time::interval(Duration::from_secs(5)); |
| 819 | |
908 | |
| 820 | loop { |
909 | loop { |
| 821 | interval.tick().await; |
910 | interval.tick().await; |
| |
911 | |
| |
912 | let receipts = update_receipts(&client).await; |
| |
913 | store.lock().await.application.set_receipts(receipts).await; |
| |
914 | } |
| |
915 | } |
| |
916 | }) |
| |
917 | .into(); |
| |
918 | |
| |
919 | self.load_handle = tokio::spawn({ |
| |
920 | let client = self.client.clone(); |
| 822 | |
921 | |
| 823 | let receipts = update_receipts(&client).await; |
922 | async move { |
| 824 | store.lock().await.application.set_receipts(receipts).await; |
923 | // Load older messages every 2 seconds. |
| |
924 | let mut interval = tokio::time::interval(Duration::from_secs(2)); |
| |
925 | loop { |
| |
926 | interval.tick().await; |
| |
927 | load_older(&client, &store).await; |
| |
928 | } |
| 825 | } |
929 | } |
| 826 | }) |
930 | }) |
| 827 | .into(); |
931 | .into(); |
| @@ -991,35 +1095,6 @@ impl ClientWorker { |
| 991 | return rooms; |
1095 | return rooms; |
| 992 | } |
1096 | } |
| 993 | |
1097 | |
| 994 | async fn load_older( |
| |
| 995 | &mut self, |
| |
| 996 | room_id: OwnedRoomId, |
| |
| 997 | fetch_id: Option<String>, |
| |
| 998 | limit: u32, |
| |
| 999 | ) -> MessageFetchResult { |
| |
| 1000 | if let Some(room) = self.client.get_room(room_id.as_ref()) { |
| |
| 1001 | let mut opts = match &fetch_id { |
| |
| 1002 | Some(id) => MessagesOptions::backward().from(id.as_str()), |
| |
| 1003 | None => MessagesOptions::backward(), |
| |
| 1004 | }; |
| |
| 1005 | opts.limit = limit.into(); |
| |
| 1006 | |
| |
| 1007 | let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?; |
| |
| 1008 | |
| |
| 1009 | let msgs = chunk.into_iter().filter_map(|ev| { |
| |
| 1010 | match ev.event.deserialize() { |
| |
| 1011 | Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg), |
| |
| 1012 | Ok(AnyTimelineEvent::State(_)) => None, |
| |
| 1013 | Err(_) => None, |
| |
| 1014 | } |
| |
| 1015 | }); |
| |
| 1016 | |
| |
| 1017 | Ok((end, msgs.collect())) |
| |
| 1018 | } else { |
| |
| 1019 | Err(IambError::UnknownRoom(room_id).into()) |
| |
| 1020 | } |
| |
| 1021 | } |
| |
| 1022 | |
| |
| 1023 | async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> { |
1098 | async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> { |
| 1024 | if let Some(room) = self.client.get_room(room_id.as_ref()) { |
1099 | if let Some(room) = self.client.get_room(room_id.as_ref()) { |
| 1025 | Ok(room.active_members().await.map_err(IambError::from)?) |
1100 | Ok(room.active_members().await.map_err(IambError::from)?) |