| @@ -12,9 +12,10 @@ use gethostname::gethostname; |
| 12 | use matrix_sdk::OwnedServerName; |
12 | use matrix_sdk::OwnedServerName; |
| 13 | use matrix_sdk::authentication::matrix::MatrixSession; |
13 | use matrix_sdk::authentication::matrix::MatrixSession; |
| 14 | use matrix_sdk::config::{RequestConfig, SyncSettings}; |
14 | use matrix_sdk::config::{RequestConfig, SyncSettings}; |
| |
15 | use matrix_sdk::deserialized_responses::{TimelineEvent, TimelineEventKind}; |
| 15 | use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings}; |
16 | use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings}; |
| 16 | use matrix_sdk::event_handler::Ctx; |
17 | use matrix_sdk::event_handler::Ctx; |
| 17 | use matrix_sdk::room::{Messages as MatrixMessages, MessagesOptions, RoomMember}; |
18 | use matrix_sdk::room::RoomMember; |
| 18 | use matrix_sdk::ruma::OwnedRoomAliasId; |
19 | use matrix_sdk::ruma::OwnedRoomAliasId; |
| 19 | use matrix_sdk::ruma::api::client::filter::{ |
20 | use matrix_sdk::ruma::api::client::filter::{ |
| 20 | FilterDefinition, |
21 | FilterDefinition, |
| @@ -65,6 +66,7 @@ use matrix_sdk::ruma::events::{ |
| 65 | SyncMessageLikeEvent, |
66 | SyncMessageLikeEvent, |
| 66 | SyncStateEvent, |
67 | SyncStateEvent, |
| 67 | }; |
68 | }; |
| |
69 | use matrix_sdk::ruma::presence::PresenceState; |
| 68 | use matrix_sdk::ruma::room::RoomType; |
70 | use matrix_sdk::ruma::room::RoomType; |
| 69 | use matrix_sdk::ruma::serde::Raw; |
71 | use matrix_sdk::ruma::serde::Raw; |
| 70 | use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate}; |
72 | use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate}; |
| @@ -76,6 +78,7 @@ use matrix_sdk::{ |
| 76 | reqwest, |
78 | reqwest, |
| 77 | }; |
79 | }; |
| 78 | use matrix_sdk_base::RoomStateFilter; |
80 | use matrix_sdk_base::RoomStateFilter; |
| |
81 | use modalkit::editing::completion::CompletionMap; |
| 79 | use ratatui_image::picker::Picker; |
82 | use ratatui_image::picker::Picker; |
| 80 | use tokio::sync::Semaphore; |
83 | use tokio::sync::Semaphore; |
| 81 | use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; |
84 | use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; |
| @@ -83,11 +86,12 @@ use tokio::task::JoinHandle; |
| 83 | use tokio_stream::wrappers::UnboundedReceiverStream; |
86 | use tokio_stream::wrappers::UnboundedReceiverStream; |
| 84 | use tracing::{Instrument as _, error, warn}; |
87 | use tracing::{Instrument as _, error, warn}; |
| 85 | |
88 | |
| 86 | use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed, RoomFetchStatus}; |
89 | use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed}; |
| 87 | use crate::config::ProxyUrl; |
90 | use crate::config::ProxyUrl; |
| 88 | use crate::message::MessageId; |
91 | use crate::message::MessageId; |
| 89 | use crate::notifications::register_notifications; |
92 | use crate::notifications::register_notifications; |
| 90 | use crate::prelude::*; |
93 | use crate::prelude::*; |
| |
94 | use crate::preview::{PreviewKind, PreviewManager}; |
| 91 | use crate::verifications; |
95 | use crate::verifications; |
| 92 | |
96 | |
| 93 | const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings { |
97 | const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings { |
| @@ -98,7 +102,7 @@ const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings { |
| 98 | |
102 | |
| 99 | const IAMB_DEVICE_NAME: &str = "iamb"; |
103 | const IAMB_DEVICE_NAME: &str = "iamb"; |
| 100 | const IAMB_USER_AGENT: &str = "iamb"; |
104 | const IAMB_USER_AGENT: &str = "iamb"; |
| 101 | const MIN_MSG_LOAD: u32 = 50; |
105 | const MIN_MSG_LOAD: u16 = 50; |
| 102 | |
106 | |
| 103 | /// How long to wait before retrying receipts that we failed to send. |
107 | /// How long to wait before retrying receipts that we failed to send. |
| 104 | const RECEIPT_RETRY_INTERVAL: Duration = Duration::from_secs(2); |
108 | const RECEIPT_RETRY_INTERVAL: Duration = Duration::from_secs(2); |
| @@ -106,7 +110,7 @@ const RECEIPT_RETRY_INTERVAL: Duration = Duration::from_secs(2); |
| 106 | type ReceiptKey = (OwnedRoomId, ReceiptThread, ReceiptType); |
110 | type ReceiptKey = (OwnedRoomId, ReceiptThread, ReceiptType); |
| 107 | type ReceiptUpdate = (OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId); |
111 | type ReceiptUpdate = (OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId); |
| 108 | |
112 | |
| 109 | type MessageFetchResult = IambResult<(Option<String>, Vec<(AnyTimelineEvent, Vec<OwnedUserId>)>)>; |
113 | type MessageFetchResult = IambResult<(bool, Vec<(AnyTimelineEvent, Vec<OwnedUserId>)>)>; |
| 110 | |
114 | |
| 111 | fn initial_devname() -> String { |
115 | fn initial_devname() -> String { |
| 112 | format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy()) |
116 | format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy()) |
| @@ -178,7 +182,7 @@ async fn update_event_receipts(info: &mut RoomInfo, room: &MatrixRoom, event_id: |
| 178 | |
182 | |
| 179 | #[derive(Debug)] |
183 | #[derive(Debug)] |
| 180 | enum Plan { |
184 | enum Plan { |
| 181 | Messages(OwnedRoomId, Option<String>, Vec<MessageNeed>), |
185 | Messages(OwnedRoomId, Vec<MessageNeed>), |
| 182 | Members(OwnedRoomId), |
186 | Members(OwnedRoomId), |
| 183 | Pinned(OwnedRoomId, Vec<OwnedEventId>), |
187 | Pinned(OwnedRoomId, Vec<OwnedEventId>), |
| 184 | } |
188 | } |
| @@ -203,13 +207,11 @@ async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> { |
| 203 | info.fetch_last = Instant::now().into(); |
207 | info.fetch_last = Instant::now().into(); |
| 204 | info.fetching = true; |
208 | info.fetching = true; |
| 205 | |
209 | |
| 206 | let fetch_id = match &info.fetch_id { |
210 | if info.reached_timeline_start { |
| 207 | RoomFetchStatus::Done => continue, |
211 | continue; |
| 208 | RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()), |
212 | } |
| 209 | RoomFetchStatus::NotStarted => None, |
| |
| 210 | }; |
| |
| 211 | |
213 | |
| 212 | plan.push(Plan::Messages(room_id.to_owned(), fetch_id, message_need)); |
214 | plan.push(Plan::Messages(room_id.to_owned(), message_need)); |
| 213 | } |
215 | } |
| 214 | } |
216 | } |
| 215 | if need.members { |
217 | if need.members { |
| @@ -220,14 +222,21 @@ async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> { |
| 220 | return plan; |
222 | return plan; |
| 221 | } |
223 | } |
| 222 | |
224 | |
| 223 | async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan, permits: &Semaphore) { |
225 | async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan) { |
| 224 | let permit = permits.acquire().await; |
| |
| 225 | match plan { |
226 | match plan { |
| 226 | Plan::Messages(room_id, fetch_id, message_need) => { |
227 | Plan::Messages(room_id, message_need) => { |
| 227 | let limit = MIN_MSG_LOAD; |
228 | let Some(room) = client.get_room(&room_id) else { |
| 228 | let client = client.clone(); |
229 | warn!(room_id = room_id.as_str(), "Room not found in cache"); |
| |
230 | store |
| |
231 | .lock() |
| |
232 | .await |
| |
233 | .application |
| |
234 | .need_load |
| |
235 | .need_messages_all(room_id, message_need); |
| |
236 | return; |
| |
237 | }; |
| 229 | |
238 | |
| 230 | let res = load_older_one(&client, &room_id, fetch_id, limit).await; |
239 | let res = load_older_one(&room).await; |
| 231 | let mut locked = store.lock().await; |
240 | let mut locked = store.lock().await; |
| 232 | load_insert(room_id, res, locked.deref_mut(), message_need); |
241 | load_insert(room_id, res, locked.deref_mut(), message_need); |
| 233 | }, |
242 | }, |
| @@ -246,7 +255,6 @@ async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan, permit |
| 246 | } |
255 | } |
| 247 | }, |
256 | }, |
| 248 | } |
257 | } |
| 249 | drop(permit); |
| |
| 250 | } |
258 | } |
| 251 | |
259 | |
| 252 | async fn pinned_load( |
260 | async fn pinned_load( |
| @@ -290,51 +298,161 @@ async fn pinned_load_one( |
| 290 | Some(msg) |
298 | Some(msg) |
| 291 | } |
299 | } |
| 292 | |
300 | |
| 293 | async fn load_older_one( |
301 | async fn get_receipts_for_timeline_events( |
| 294 | client: &Client, |
302 | room: &MatrixRoom, |
| 295 | room_id: &RoomId, |
303 | events: Vec<TimelineEvent>, |
| 296 | fetch_id: Option<String>, |
304 | ) -> Vec<(AnyTimelineEvent, Vec<OwnedUserId>)> { |
| 297 | limit: u32, |
305 | let mut msgs = vec![]; |
| 298 | ) -> MessageFetchResult { |
| |
| 299 | if let Some(room) = client.get_room(room_id) { |
| |
| 300 | // Update cached encryption state. This is a noop if the state is already cached. |
| |
| 301 | let _ = room.request_encryption_state().await; |
| |
| 302 | |
306 | |
| 303 | let mut opts = match &fetch_id { |
307 | for ev in events.into_iter() { |
| 304 | Some(id) => MessagesOptions::backward().from(id.as_str()), |
308 | let event_id = ev.event_id(); |
| 305 | None => MessagesOptions::backward(), |
309 | let msg = match ev.kind { |
| |
310 | TimelineEventKind::Decrypted(event) => { |
| |
311 | match event.event.deserialize() { |
| |
312 | Ok(event) => event, |
| |
313 | Err(err) => { |
| |
314 | warn!( |
| |
315 | err = %err, |
| |
316 | room_id = room.room_id().as_str(), |
| |
317 | ?event_id, |
| |
318 | "Failed to deserialize event" |
| |
319 | ); |
| |
320 | continue; |
| |
321 | }, |
| |
322 | } |
| |
323 | }, |
| |
324 | TimelineEventKind::UnableToDecrypt { utd_info, .. } => { |
| |
325 | warn!( |
| |
326 | ?utd_info, |
| |
327 | room_id = room.room_id().as_str(), |
| |
328 | ?event_id, |
| |
329 | "Failed to decrypt event" |
| |
330 | ); |
| |
331 | continue; |
| |
332 | }, |
| |
333 | TimelineEventKind::PlainText { event } => { |
| |
334 | let event = match event.deserialize() { |
| |
335 | Ok(event) => event, |
| |
336 | Err(err) => { |
| |
337 | warn!( |
| |
338 | err = %err, |
| |
339 | room_id = room.room_id().as_str(), |
| |
340 | ?event_id, |
| |
341 | "Failed to deserialize event" |
| |
342 | ); |
| |
343 | continue; |
| |
344 | }, |
| |
345 | }; |
| |
346 | event.into_full_event(room.room_id().to_owned()) |
| |
347 | }, |
| 306 | }; |
348 | }; |
| 307 | opts.limit = limit.into(); |
| |
| 308 | |
349 | |
| 309 | let MatrixMessages { end, chunk, .. } = |
350 | let event_id = msg.event_id(); |
| 310 | room.messages(opts).await.map_err(IambError::from)?; |
351 | let receipts = match room |
| |
352 | .load_event_receipts(ReceiptType::Read, ReceiptThread::Main, event_id) |
| |
353 | .await |
| |
354 | { |
| |
355 | Ok(receipts) => receipts.into_iter().map(|(u, _)| u).collect(), |
| |
356 | Err(e) => { |
| |
357 | tracing::warn!(?event_id, "failed to get event receipts: {e}"); |
| |
358 | vec![] |
| |
359 | }, |
| |
360 | }; |
| 311 | |
361 | |
| 312 | let mut msgs = vec![]; |
362 | msgs.push((msg, receipts)); |
| |
363 | } |
| 313 | |
364 | |
| 314 | for ev in chunk.into_iter() { |
365 | msgs |
| 315 | let Ok(msg) = ev.into_raw().deserialize() else { |
366 | } |
| 316 | continue; |
| |
| 317 | }; |
| |
| 318 | |
367 | |
| 319 | let event_id = msg.event_id(); |
368 | async fn load_older_one(room: &MatrixRoom) -> MessageFetchResult { |
| 320 | let receipts = match room |
369 | // Update cached encryption state. This is a noop if the state is already cached. |
| 321 | .load_event_receipts(ReceiptType::Read, ReceiptThread::Main, event_id) |
370 | let _ = room.request_encryption_state().await; |
| 322 | .await |
371 | |
| 323 | { |
372 | let (cache, _drop_handle) = room.event_cache().await.map_err(IambError::from)?; |
| 324 | Ok(receipts) => receipts.into_iter().map(|(u, _)| u).collect(), |
373 | |
| 325 | Err(e) => { |
374 | let outcome = cache |
| 326 | tracing::warn!(?event_id, "failed to get event receipts: {e}"); |
375 | .pagination() |
| 327 | vec![] |
376 | .run_backwards_until(MIN_MSG_LOAD) |
| 328 | }, |
377 | .await |
| 329 | }; |
378 | .map_err(IambError::from)?; |
| |
379 | |
| |
380 | let msgs = get_receipts_for_timeline_events(room, outcome.events).await; |
| 330 | |
381 | |
| 331 | let msg = msg.into_full_event(room_id.to_owned()); |
382 | Ok((outcome.reached_start, msgs)) |
| 332 | msgs.push((msg, receipts)); |
383 | } |
| |
384 | |
| |
385 | fn insert_msgs_and_receipts( |
| |
386 | msgs: Vec<(AnyTimelineEvent, Vec<OwnedUserId>)>, |
| |
387 | info: &mut RoomInfo, |
| |
388 | presences: &mut CompletionMap<OwnedUserId, PresenceState>, |
| |
389 | previews: &mut PreviewManager, |
| |
390 | settings: &ApplicationSettings, |
| |
391 | ) { |
| |
392 | for (msg, receipts) in msgs { |
| |
393 | let sender = msg.sender().to_owned(); |
| |
394 | let _ = presences.get_or_default(sender); |
| |
395 | |
| |
396 | for user_id in receipts { |
| |
397 | info.set_receipt(ReceiptThread::Main, user_id, msg.event_id().to_owned()); |
| 333 | } |
398 | } |
| 334 | |
399 | |
| 335 | Ok((end, msgs)) |
400 | match msg { |
| 336 | } else { |
401 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomEncrypted(msg)) => { |
| 337 | Err(IambError::UnknownRoom(room_id.to_owned()).into()) |
402 | info.insert_encrypted(msg); |
| |
403 | }, |
| |
404 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => { |
| |
405 | info.insert_with_preview(msg, settings, previews); |
| |
406 | }, |
| |
407 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { |
| |
408 | info.insert_reaction_with_preview(ev, settings, previews); |
| |
409 | }, |
| |
410 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { |
| |
411 | info.insert_sticker_with_preview(ev, settings, previews); |
| |
412 | }, |
| |
413 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomRedaction(..)) => { |
| |
414 | // ignoring redaction events because we get them bundled with the redacted event |
| |
415 | }, |
| |
416 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::PollStart(ev)) => { |
| |
417 | info.insert_poll_start(ev); |
| |
418 | }, |
| |
419 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::UnstablePollStart(ev)) => { |
| |
420 | info.insert_unstable_poll_start(ev); |
| |
421 | }, |
| |
422 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::PollResponse(ev)) => { |
| |
423 | if let MessageLikeEvent::Original(ev) = ev { |
| |
424 | info.insert_poll_relation(ev.into()); |
| |
425 | } |
| |
426 | }, |
| |
427 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::UnstablePollResponse(ev)) => { |
| |
428 | if let MessageLikeEvent::Original(ev) = ev { |
| |
429 | info.insert_unstable_poll_relation(ev.into()); |
| |
430 | } |
| |
431 | }, |
| |
432 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::PollEnd(ev)) => { |
| |
433 | if let MessageLikeEvent::Original(ev) = ev { |
| |
434 | info.insert_poll_relation(ev.into()); |
| |
435 | } |
| |
436 | }, |
| |
437 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::UnstablePollEnd(ev)) => { |
| |
438 | if let MessageLikeEvent::Original(ev) = ev { |
| |
439 | info.insert_unstable_poll_relation(ev.into()); |
| |
440 | } |
| |
441 | }, |
| |
442 | AnyTimelineEvent::MessageLike(ev) => { |
| |
443 | tracing::trace!( |
| |
444 | event_id = ev.event_id().as_str(), |
| |
445 | "Ignoring unimplemented event type {}", |
| |
446 | ev.event_type() |
| |
447 | ); |
| |
448 | continue; |
| |
449 | }, |
| |
450 | AnyTimelineEvent::State(msg) => { |
| |
451 | if settings.tunables.state_event_display { |
| |
452 | info.insert_any_state(msg.into()); |
| |
453 | } |
| |
454 | }, |
| |
455 | } |
| 338 | } |
456 | } |
| 339 | } |
457 | } |
| 340 | |
458 | |
| @@ -349,68 +467,10 @@ fn load_insert( |
| 349 | info.fetching = false; |
467 | info.fetching = false; |
| 350 | |
468 | |
| 351 | match res { |
469 | match res { |
| 352 | Ok((fetch_id, msgs)) => { |
470 | Ok((reached_start, msgs)) => { |
| 353 | for (msg, receipts) in msgs.into_iter() { |
471 | insert_msgs_and_receipts(msgs, info, presences, previews, settings); |
| 354 | let sender = msg.sender().to_owned(); |
| |
| 355 | let _ = presences.get_or_default(sender); |
| |
| 356 | |
472 | |
| 357 | for user_id in receipts { |
473 | info.reached_timeline_start = reached_start; |
| 358 | info.set_receipt(ReceiptThread::Main, user_id, msg.event_id().to_owned()); |
| |
| 359 | } |
| |
| 360 | |
| |
| 361 | match msg { |
| |
| 362 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomEncrypted(msg)) => { |
| |
| 363 | info.insert_encrypted(msg); |
| |
| 364 | }, |
| |
| 365 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => { |
| |
| 366 | info.insert_with_preview(msg, settings, previews); |
| |
| 367 | }, |
| |
| 368 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { |
| |
| 369 | info.insert_reaction_with_preview(ev, settings, previews); |
| |
| 370 | }, |
| |
| 371 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { |
| |
| 372 | info.insert_sticker_with_preview(ev, settings, previews); |
| |
| 373 | }, |
| |
| 374 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::PollStart(ev)) => { |
| |
| 375 | info.insert_poll_start(ev); |
| |
| 376 | }, |
| |
| 377 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::UnstablePollStart(ev)) => { |
| |
| 378 | info.insert_unstable_poll_start(ev); |
| |
| 379 | }, |
| |
| 380 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::PollResponse(ev)) => { |
| |
| 381 | if let MessageLikeEvent::Original(ev) = ev { |
| |
| 382 | info.insert_poll_relation(ev.into()); |
| |
| 383 | } |
| |
| 384 | }, |
| |
| 385 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::UnstablePollResponse( |
| |
| 386 | ev, |
| |
| 387 | )) => { |
| |
| 388 | if let MessageLikeEvent::Original(ev) = ev { |
| |
| 389 | info.insert_unstable_poll_relation(ev.into()); |
| |
| 390 | } |
| |
| 391 | }, |
| |
| 392 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::PollEnd(ev)) => { |
| |
| 393 | if let MessageLikeEvent::Original(ev) = ev { |
| |
| 394 | info.insert_poll_relation(ev.into()); |
| |
| 395 | } |
| |
| 396 | }, |
| |
| 397 | AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::UnstablePollEnd(ev)) => { |
| |
| 398 | if let MessageLikeEvent::Original(ev) = ev { |
| |
| 399 | info.insert_unstable_poll_relation(ev.into()); |
| |
| 400 | } |
| |
| 401 | }, |
| |
| 402 | AnyTimelineEvent::MessageLike(_) => { |
| |
| 403 | continue; |
| |
| 404 | }, |
| |
| 405 | AnyTimelineEvent::State(msg) => { |
| |
| 406 | if settings.tunables.state_event_display { |
| |
| 407 | info.insert_any_state(msg.into()); |
| |
| 408 | } |
| |
| 409 | }, |
| |
| 410 | } |
| |
| 411 | } |
| |
| 412 | |
| |
| 413 | info.fetch_id = fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore); |
| |
| 414 | |
474 | |
| 415 | // check if more are needed |
475 | // check if more are needed |
| 416 | let needs: Vec<_> = message_needs |
476 | let needs: Vec<_> = message_needs |
| @@ -435,19 +495,11 @@ fn load_insert( |
| 435 | } |
495 | } |
| 436 | |
496 | |
| 437 | async fn load_older(client: &Client, store: &AsyncProgramStore) -> usize { |
497 | async fn load_older(client: &Client, store: &AsyncProgramStore) -> usize { |
| 438 | // This is an arbitrary limit on how much work we do in parallel to avoid |
| |
| 439 | // spawning too many tasks at startup and overwhelming the client. We |
| |
| 440 | // should normally only surpass this limit at startup when doing an initial. |
| |
| 441 | // fetch for each room. |
| |
| 442 | const LIMIT: usize = 15; |
| |
| 443 | |
| |
| 444 | // Plans are run in parallel. Any room *may* have several plans. |
| |
| 445 | let plans = load_plans(store).await; |
498 | let plans = load_plans(store).await; |
| 446 | let permits = Semaphore::new(LIMIT); |
| |
| 447 | |
499 | |
| 448 | plans |
500 | plans |
| 449 | .into_iter() |
501 | .into_iter() |
| 450 | .map(|plan| run_plan(client, store, plan, &permits)) |
502 | .map(|plan| run_plan(client, store, plan)) |
| 451 | .collect::<FuturesUnordered<_>>() |
503 | .collect::<FuturesUnordered<_>>() |
| 452 | .count() |
504 | .count() |
| 453 | .await |
505 | .await |
| @@ -488,6 +540,80 @@ fn members_insert( |
| 488 | // else ??? |
540 | // else ??? |
| 489 | } |
541 | } |
| 490 | |
542 | |
| |
543 | async fn load_initial_messages(client: Client, store: AsyncProgramStore) { |
| |
544 | let rooms = client.joined_rooms(); |
| |
545 | let mut need_load = vec![]; |
| |
546 | |
| |
547 | // load initial cache |
| |
548 | for room in rooms.iter().filter(|room| !room.is_space()) { |
| |
549 | let cache = match room.event_cache().await { |
| |
550 | Ok((c, _)) => c, |
| |
551 | Err(e) => { |
| |
552 | // we got the room id from the client and have subscribed to the event cache, |
| |
553 | // so this should only error on IO errors. Skipping here just means that we |
| |
554 | // don't get any events from the cache and will fetch them from the homeserver |
| |
555 | // later on when viewing the room. |
| |
556 | tracing::error!(err = %e, "failed to load events from room cache"); |
| |
557 | continue; |
| |
558 | }, |
| |
559 | }; |
| |
560 | |
| |
561 | let events = match cache.events().await { |
| |
562 | Ok(events) => events, |
| |
563 | Err(e) => { |
| |
564 | tracing::warn!(room_id = ?room.room_id(), "failed to load cached events: {e}"); |
| |
565 | continue; |
| |
566 | }, |
| |
567 | }; |
| |
568 | |
| |
569 | if events.len() < MIN_MSG_LOAD as usize { |
| |
570 | need_load.push(room); |
| |
571 | } |
| |
572 | |
| |
573 | let msgs = get_receipts_for_timeline_events(room, events).await; |
| |
574 | |
| |
575 | let mut locked = store.lock().await; |
| |
576 | let ChatStore { presences, rooms, previews, settings, .. } = &mut locked.application; |
| |
577 | let info = rooms.get_or_default(room.room_id().to_owned()); |
| |
578 | insert_msgs_and_receipts(msgs, info, presences, previews, settings); |
| |
579 | } |
| |
580 | |
| |
581 | // This is an arbitrary limit on how much work we do in parallel to avoid |
| |
582 | // spawning too many tasks at startup and overwhelming the client. We |
| |
583 | // should normally only surpass this limit at startup when doing an initial |
| |
584 | // fetch for each room. |
| |
585 | const LIMIT: usize = 15; |
| |
586 | let permits = Semaphore::new(LIMIT); |
| |
587 | |
| |
588 | // paginate backwards to get more events in the rooms |
| |
589 | need_load |
| |
590 | .into_iter() |
| |
591 | .map(|room| { |
| |
592 | async { |
| |
593 | let permit = permits.acquire().await; |
| |
594 | |
| |
595 | let (reached_start, msgs) = match load_older_one(room).await { |
| |
596 | Ok(v) => v, |
| |
597 | Err(e) => { |
| |
598 | tracing::warn!(room_id = ?room.room_id(), "failed to paginate cached events: {e}"); |
| |
599 | return; |
| |
600 | }, |
| |
601 | }; |
| |
602 | |
| |
603 | let mut locked = store.lock().await; |
| |
604 | let ChatStore { presences, rooms, previews, settings, .. } = |
| |
605 | &mut locked.application; |
| |
606 | let info = rooms.get_or_default(room.room_id().to_owned()); |
| |
607 | info.reached_timeline_start = reached_start; |
| |
608 | insert_msgs_and_receipts(msgs, info, presences, previews, settings); |
| |
609 | drop(permit); |
| |
610 | } |
| |
611 | }) |
| |
612 | .collect::<FuturesUnordered<_>>() |
| |
613 | .count() |
| |
614 | .await; |
| |
615 | } |
| |
616 | |
| 491 | async fn load_older_forever(client: &Client, store: &AsyncProgramStore) { |
617 | async fn load_older_forever(client: &Client, store: &AsyncProgramStore) { |
| 492 | // Load any pending older messages or members every 2 seconds. |
618 | // Load any pending older messages or members every 2 seconds. |
| 493 | let mut interval = tokio::time::interval(Duration::from_secs(2)); |
619 | let mut interval = tokio::time::interval(Duration::from_secs(2)); |
| @@ -794,19 +920,7 @@ pub async fn do_first_sync(client: &Client, store: &AsyncProgramStore) -> Result |
| 794 | // Populate sync_info with our initial set of rooms/dms/spaces. |
920 | // Populate sync_info with our initial set of rooms/dms/spaces. |
| 795 | refresh_rooms(client, store, true).await; |
921 | refresh_rooms(client, store, true).await; |
| 796 | |
922 | |
| 797 | // Insert Need::Messages to fetch accurate recent timestamps in the background. |
923 | tokio::spawn(load_initial_messages(client.clone(), store.clone())); |
| 798 | let mut locked = store.lock().await; |
| |
| 799 | let ChatStore { sync_info, need_load, .. } = &mut locked.application; |
| |
| 800 | |
| |
| 801 | for room in sync_info.rooms.iter() { |
| |
| 802 | let room_id = room.room_id().to_owned(); |
| |
| 803 | need_load.need_messages(room_id); |
| |
| 804 | } |
| |
| 805 | |
| |
| 806 | for room in sync_info.dms.iter() { |
| |
| 807 | let room_id = room.room_id().to_owned(); |
| |
| 808 | need_load.need_messages(room_id); |
| |
| 809 | } |
| |
| 810 | |
924 | |
| 811 | Ok(()) |
925 | Ok(()) |
| 812 | } |
926 | } |