| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::sync::{Arc, Mutex}; |
| 4 | |
| 5 | use chatsvc::{ChatApp, ConversationState, TrouterEndpoint}; |
| 6 | use chrono::{DateTime, Duration, Utc}; |
| 7 | use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message}; |
| 8 | use store::{ImageFileCache, MessageImportance, MessageRecord, Sidebar, Store, SyncState}; |
| 9 | use tokio::sync::{OnceCell, broadcast}; |
| 10 | |
| 11 | use crate::chat_paging::ChatPaging; |
| 12 | use crate::error::{Error, Result}; |
| 13 | use crate::events::CoreEvent; |
| 14 | use crate::folders::FolderSource; |
| 15 | use crate::links::{LinkPreview, has_stored_links}; |
| 16 | use crate::mapping::{flatten_thread, message_record}; |
| 17 | use crate::people::{DirectoryCache, TagCache}; |
| 18 | use crate::presence::Presence; |
| 19 | use crate::preview::OwnedPreview; |
| 20 | use crate::receipts::ReceiptCache; |
| 21 | use crate::remote::{Remote, RemotePage}; |
| 22 | use crate::roster_event::thread_activity_record; |
| 23 | use crate::scheduled::NOTES_CHAT_ID; |
| 24 | |
| 25 | const EVENT_CAPACITY: usize = 64; |
| 26 | pub(crate) const MEETING_CHAT_KIND: &str = "meeting"; |
| 27 | pub(crate) const META_USER_ID: &str = "me_user_id"; |
| 28 | const META_TENANT_ID: &str = "me_tenant_id"; |
| 29 | const META_DISPLAY_NAME: &str = "me_display_name"; |
| 30 | const META_EMAIL: &str = "me_email"; |
| 31 | |
| 32 | #[derive(Debug, Clone)] |
| 33 | pub struct SyncConfig { |
| 34 | pub chat_limit: usize, |
| 35 | pub chat_page_size: usize, |
| 36 | pub page_size: usize, |
| 37 | pub open_limit: usize, |
| 38 | pub max_catch_up_pages: usize, |
| 39 | pub max_delta_pages: usize, |
| 40 | pub teams_refresh_interval: Duration, |
| 41 | pub team_layout_refresh_interval: Duration, |
| 42 | pub full_chat_refresh_interval: Duration, |
| 43 | } |
| 44 | |
| 45 | impl Default for SyncConfig { |
| 46 | fn default() -> Self { |
| 47 | SyncConfig { |
| 48 | chat_limit: 200, |
| 49 | chat_page_size: 50, |
| 50 | page_size: MESSAGE_PAGE_SIZE, |
| 51 | open_limit: MESSAGE_PAGE_SIZE, |
| 52 | max_catch_up_pages: 10, |
| 53 | max_delta_pages: 20, |
| 54 | teams_refresh_interval: Duration::hours(6), |
| 55 | team_layout_refresh_interval: Duration::minutes(15), |
| 56 | full_chat_refresh_interval: Duration::days(7), |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 62 | pub struct SidebarSummary { |
| 63 | pub chats: usize, |
| 64 | pub chat_pages: usize, |
| 65 | pub full_chat_refresh: bool, |
| 66 | pub teams_refreshed: bool, |
| 67 | pub teams: usize, |
| 68 | pub channels: usize, |
| 69 | pub failed_teams: usize, |
| 70 | } |
| 71 | |
| 72 | #[derive(Debug, Clone, Default, PartialEq)] |
| 73 | pub struct Delta { |
| 74 | pub added: Vec<MessageRecord>, |
| 75 | pub updated: Vec<MessageRecord>, |
| 76 | } |
| 77 | |
| 78 | impl Delta { |
| 79 | pub(crate) fn merge(&mut self, other: Delta) { |
| 80 | for record in other.added { |
| 81 | if !self |
| 82 | .added |
| 83 | .iter() |
| 84 | .any(|known| known.message_id == record.message_id) |
| 85 | { |
| 86 | self.added.push(record); |
| 87 | } |
| 88 | } |
| 89 | for record in other.updated { |
| 90 | self.updated |
| 91 | .retain(|known| known.message_id != record.message_id); |
| 92 | self.updated.push(record); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn is_empty(&self) -> bool { |
| 97 | self.added.is_empty() && self.updated.is_empty() |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 102 | pub struct Me { |
| 103 | pub user_id: String, |
| 104 | pub display_name: String, |
| 105 | } |
| 106 | |
| 107 | pub(crate) enum Conversation { |
| 108 | Chat, |
| 109 | Channel { team_id: String }, |
| 110 | } |
| 111 | |
| 112 | pub struct SyncEngine<R: Remote = Graph> { |
| 113 | pub(crate) remote: R, |
| 114 | pub(crate) store: Arc<Store>, |
| 115 | pub(crate) config: SyncConfig, |
| 116 | pub(crate) events: broadcast::Sender<CoreEvent>, |
| 117 | my_user_id: OnceCell<String>, |
| 118 | my_tenant_id: OnceCell<String>, |
| 119 | pub(crate) folder_source: Option<Arc<dyn FolderSource>>, |
| 120 | pub(crate) presences: Mutex<HashMap<String, Presence>>, |
| 121 | pub(crate) watched_presence: Mutex<HashSet<String>>, |
| 122 | pub(crate) presence_endpoint: Mutex<Option<TrouterEndpoint>>, |
| 123 | pub(crate) presence_subscribing: tokio::sync::Mutex<()>, |
| 124 | pub(crate) avatars_in_flight: Mutex<HashSet<String>>, |
| 125 | pub(crate) images_in_flight: Mutex<HashSet<String>>, |
| 126 | pub(crate) image_files: Option<ImageFileCache>, |
| 127 | pub(crate) directory_cache: Mutex<DirectoryCache>, |
| 128 | pub(crate) tag_cache: Mutex<TagCache>, |
| 129 | preview_changed: AtomicBool, |
| 130 | pub(crate) receipts: ReceiptCache, |
| 131 | pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>, |
| 132 | pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>, |
| 133 | pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>, |
| 134 | pub(crate) links_backfilled: Mutex<HashSet<String>>, |
| 135 | pub(crate) forwards_healed: Mutex<HashSet<String>>, |
| 136 | pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>, |
| 137 | pub(crate) app_channel_horizon_ms: Mutex<i64>, |
| 138 | pub(crate) activity: Mutex<crate::activity_sync::ActivityState>, |
| 139 | pub(crate) chat_paging: Mutex<ChatPaging>, |
| 140 | pub(crate) locally_hidden_lock: Mutex<()>, |
| 141 | pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>, |
| 142 | } |
| 143 | |
| 144 | impl<R: Remote> SyncEngine<R> { |
| 145 | pub fn new(remote: R, store: Arc<Store>) -> Self { |
| 146 | Self::with_config(remote, store, SyncConfig::default()) |
| 147 | } |
| 148 | |
| 149 | pub fn with_config(remote: R, store: Arc<Store>, config: SyncConfig) -> Self { |
| 150 | let chat_paging = Mutex::new(crate::sidebar_sync::stored_chat_paging(&store)); |
| 151 | SyncEngine { |
| 152 | remote, |
| 153 | store, |
| 154 | config, |
| 155 | events: broadcast::channel(EVENT_CAPACITY).0, |
| 156 | my_user_id: OnceCell::new(), |
| 157 | my_tenant_id: OnceCell::new(), |
| 158 | folder_source: None, |
| 159 | presences: Mutex::new(HashMap::new()), |
| 160 | watched_presence: Mutex::new(HashSet::new()), |
| 161 | presence_endpoint: Mutex::new(None), |
| 162 | presence_subscribing: tokio::sync::Mutex::new(()), |
| 163 | avatars_in_flight: Mutex::new(HashSet::new()), |
| 164 | images_in_flight: Mutex::new(HashSet::new()), |
| 165 | image_files: None, |
| 166 | directory_cache: Mutex::new(DirectoryCache::new()), |
| 167 | tag_cache: Mutex::new(TagCache::default()), |
| 168 | preview_changed: AtomicBool::new(false), |
| 169 | receipts: ReceiptCache::default(), |
| 170 | channel_folders: Mutex::new(HashMap::new()), |
| 171 | chat_apps: Mutex::new(HashMap::new()), |
| 172 | link_previews: Mutex::new(HashMap::new()), |
| 173 | links_backfilled: Mutex::new(HashSet::new()), |
| 174 | forwards_healed: Mutex::new(HashSet::new()), |
| 175 | chat_states: Mutex::new(HashMap::new()), |
| 176 | app_channel_horizon_ms: Mutex::new(0), |
| 177 | activity: Mutex::new(crate::activity_sync::ActivityState::default()), |
| 178 | chat_paging, |
| 179 | locally_hidden_lock: Mutex::new(()), |
| 180 | bot_partners: Mutex::default(), |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | pub fn subscribe(&self) -> broadcast::Receiver<CoreEvent> { |
| 185 | self.events.subscribe() |
| 186 | } |
| 187 | |
| 188 | pub fn store(&self) -> &Arc<Store> { |
| 189 | &self.store |
| 190 | } |
| 191 | |
| 192 | pub fn remote(&self) -> &R { |
| 193 | &self.remote |
| 194 | } |
| 195 | |
| 196 | pub fn sidebar(&self) -> Result<Sidebar> { |
| 197 | Ok(self.store.sidebar()?) |
| 198 | } |
| 199 | |
| 200 | /// Cached page, newest messages last. Call `fetch_newer` afterwards for the network delta. |
| 201 | pub fn open_conversation(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> { |
| 202 | Ok(self |
| 203 | .store |
| 204 | .messages(conversation_id, None, self.config.open_limit)?) |
| 205 | } |
| 206 | |
| 207 | pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> { |
| 208 | let heal = async { |
| 209 | if self.heal_forwards(conversation_id).await { |
| 210 | self.announce(conversation_id, true); |
| 211 | } |
| 212 | }; |
| 213 | let fetch = async { |
| 214 | Ok::<_, Error>(match self.resolve(conversation_id).await? { |
| 215 | Conversation::Chat => self.fetch_newer_chat(conversation_id).await?, |
| 216 | Conversation::Channel { team_id } => { |
| 217 | self.fetch_newer_channel(&team_id, conversation_id).await? |
| 218 | } |
| 219 | }) |
| 220 | }; |
| 221 | let (fetched, ()) = tokio::join!(fetch, heal); |
| 222 | let mut delta = fetched?; |
| 223 | let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await |
| 224 | | self.backfill_links(conversation_id).await; |
| 225 | self.announce(conversation_id, !delta.is_empty() || cache_changed); |
| 226 | Ok(delta) |
| 227 | } |
| 228 | |
| 229 | pub async fn fetch_until_cached( |
| 230 | &self, |
| 231 | conversation_id: &str, |
| 232 | message_id: &str, |
| 233 | retry_delays: &[std::time::Duration], |
| 234 | ) -> Result<Delta> { |
| 235 | let mut delta = Delta::default(); |
| 236 | for delay in retry_delays { |
| 237 | if self.is_cached(conversation_id, message_id)? { |
| 238 | break; |
| 239 | } |
| 240 | tokio::time::sleep(*delay).await; |
| 241 | delta.merge(self.fetch_newer(conversation_id).await?); |
| 242 | } |
| 243 | Ok(delta) |
| 244 | } |
| 245 | |
| 246 | fn is_cached(&self, conversation_id: &str, message_id: &str) -> Result<bool> { |
| 247 | Ok(self |
| 248 | .store |
| 249 | .messages_by_id(conversation_id, &[message_id.to_owned()])? |
| 250 | .contains_key(message_id)) |
| 251 | } |
| 252 | |
| 253 | pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> { |
| 254 | let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else { |
| 255 | return Err(Error::Unsupported("refreshing a thread of a chat")); |
| 256 | }; |
| 257 | let delta = self |
| 258 | .refresh_channel_thread(&team_id, conversation_id, root_id) |
| 259 | .await?; |
| 260 | self.announce(conversation_id, !delta.is_empty()); |
| 261 | Ok(delta) |
| 262 | } |
| 263 | |
| 264 | pub async fn load_older(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> { |
| 265 | let conversation = self.resolve(conversation_id).await?; |
| 266 | if self.store.sync_state(conversation_id)?.is_none() { |
| 267 | self.fetch_newer(conversation_id).await?; |
| 268 | } |
| 269 | let state = self.store.sync_state(conversation_id)?.unwrap_or_default(); |
| 270 | if !state.has_more { |
| 271 | return Ok(Vec::new()); |
| 272 | } |
| 273 | let records = match conversation { |
| 274 | Conversation::Chat => self.load_older_chat(conversation_id, state).await?, |
| 275 | Conversation::Channel { .. } => self.load_older_channel(conversation_id, state).await?, |
| 276 | }; |
| 277 | self.announce(conversation_id, !records.is_empty()); |
| 278 | Ok(records) |
| 279 | } |
| 280 | |
| 281 | /// Known after the first sidebar refresh. |
| 282 | pub fn me(&self) -> Option<Me> { |
| 283 | Some(Me { |
| 284 | user_id: self.store.meta(META_USER_ID).ok()??, |
| 285 | display_name: self.store.meta(META_DISPLAY_NAME).ok()??, |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | /// Cached chat messages from others after the last read time, at least 1 for an unread chat. |
| 290 | pub fn unread_count(&self, conversation_id: &str) -> u32 { |
| 291 | let unread_count = || -> Result<usize> { |
| 292 | if let Some(channel) = self.store.channel(conversation_id)? { |
| 293 | return Ok(usize::from(channel.unread)); |
| 294 | } |
| 295 | let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else { |
| 296 | return Ok(0); |
| 297 | }; |
| 298 | let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default(); |
| 299 | let cached = |
| 300 | self.store |
| 301 | .count_messages_after(conversation_id, chat.last_read_at, &my_user_id)?; |
| 302 | Ok(cached.max(1)) |
| 303 | }; |
| 304 | unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX)) |
| 305 | } |
| 306 | |
| 307 | pub fn unread_importance(&self, conversation_id: &str) -> MessageImportance { |
| 308 | let importance = || -> Result<MessageImportance> { |
| 309 | let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else { |
| 310 | return Ok(MessageImportance::Normal); |
| 311 | }; |
| 312 | let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default(); |
| 313 | self.store |
| 314 | .unread_last_message_importance(conversation_id, chat.last_read_at, &my_user_id) |
| 315 | .map_err(Into::into) |
| 316 | }; |
| 317 | importance().unwrap_or_default() |
| 318 | } |
| 319 | |
| 320 | pub(crate) async fn my_user_id(&self) -> Result<String> { |
| 321 | let id = self |
| 322 | .my_user_id |
| 323 | .get_or_try_init(|| async { |
| 324 | if let Some(cached) = self.store.meta(META_USER_ID)? { |
| 325 | return Ok::<_, Error>(cached); |
| 326 | } |
| 327 | self.remember_me().await |
| 328 | }) |
| 329 | .await?; |
| 330 | Ok(id.clone()) |
| 331 | } |
| 332 | |
| 333 | pub(crate) async fn ensure_display_name(&self) -> Result<()> { |
| 334 | if self.store.meta(META_DISPLAY_NAME)?.is_none() || self.store.meta(META_EMAIL)?.is_none() { |
| 335 | self.remember_me().await?; |
| 336 | } |
| 337 | Ok(()) |
| 338 | } |
| 339 | |
| 340 | async fn remember_me(&self) -> Result<String> { |
| 341 | let user = self.remote.me().await?; |
| 342 | self.store.set_meta(META_USER_ID, &user.id)?; |
| 343 | if let Some(name) = user.display_name.as_deref() { |
| 344 | self.store.set_meta(META_DISPLAY_NAME, name)?; |
| 345 | } |
| 346 | let email = user.mail.as_deref().or(user.user_principal_name.as_deref()); |
| 347 | self.store.set_meta(META_EMAIL, email.unwrap_or_default())?; |
| 348 | Ok(user.id) |
| 349 | } |
| 350 | |
| 351 | pub(crate) async fn my_tenant_id(&self, chat_id: &str) -> Result<String> { |
| 352 | if chat_id == NOTES_CHAT_ID { |
| 353 | return self.my_tenant_id_from_any_chat().await; |
| 354 | } |
| 355 | self.my_tenant_id_from(chat_id).await |
| 356 | } |
| 357 | |
| 358 | async fn my_tenant_id_from(&self, chat_id: &str) -> Result<String> { |
| 359 | let tenant = self |
| 360 | .my_tenant_id |
| 361 | .get_or_try_init(|| async { |
| 362 | if let Some(cached) = self.store.meta(META_TENANT_ID)? { |
| 363 | return Ok::<_, Error>(cached); |
| 364 | } |
| 365 | let my_user_id = self.my_user_id().await?; |
| 366 | let members = self.remote.chat_members(chat_id).await?; |
| 367 | let tenant = members |
| 368 | .iter() |
| 369 | .find(|member| member.user_id.as_deref() == Some(my_user_id.as_str())) |
| 370 | .and_then(|member| member.tenant_id.clone()) |
| 371 | .ok_or(Error::Unsupported("a chat without my tenant id"))?; |
| 372 | self.store.set_meta(META_TENANT_ID, &tenant)?; |
| 373 | Ok(tenant) |
| 374 | }) |
| 375 | .await?; |
| 376 | Ok(tenant.clone()) |
| 377 | } |
| 378 | |
| 379 | pub(crate) async fn my_tenant_id_from_any_chat(&self) -> Result<String> { |
| 380 | if let Some(tenant) = self.my_tenant_id.get() { |
| 381 | return Ok(tenant.clone()); |
| 382 | } |
| 383 | if let Some(cached) = self.store.meta(META_TENANT_ID)? { |
| 384 | return Ok(cached); |
| 385 | } |
| 386 | let any_chat_id = self |
| 387 | .store |
| 388 | .sidebar()? |
| 389 | .chats |
| 390 | .into_iter() |
| 391 | .map(|chat| chat.id) |
| 392 | .find(|chat_id| chat_id != NOTES_CHAT_ID) |
| 393 | .ok_or(Error::Unsupported("a tenant id without a known chat"))?; |
| 394 | self.my_tenant_id_from(&any_chat_id).await |
| 395 | } |
| 396 | |
| 397 | pub async fn meeting_join_url(&self, chat_id: &str) -> Result<Option<String>> { |
| 398 | let chat = self.remote.chat(chat_id).await?; |
| 399 | Ok(chat |
| 400 | .online_meeting_info |
| 401 | .and_then(|info| info.join_web_url) |
| 402 | .filter(|url| !url.is_empty())) |
| 403 | } |
| 404 | |
| 405 | pub(crate) async fn resolve(&self, conversation_id: &str) -> Result<Conversation> { |
| 406 | match self.resolve_stored(conversation_id) { |
| 407 | Err(Error::UnknownConversation(_)) => self.fetch_unknown_chat(conversation_id).await, |
| 408 | resolved => resolved, |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | async fn fetch_unknown_chat(&self, conversation_id: &str) -> Result<Conversation> { |
| 413 | let chat = match self.remote.chat(conversation_id).await { |
| 414 | Ok(chat) => chat, |
| 415 | Err(Error::Graph(graph::Error::Session(session::Error::Api { |
| 416 | status: 403 | 404, |
| 417 | .. |
| 418 | }))) => { |
| 419 | return Err(Error::UnknownConversation(conversation_id.to_owned())); |
| 420 | } |
| 421 | Err(error) => return Err(error), |
| 422 | }; |
| 423 | let my_user_id = self.my_user_id().await?; |
| 424 | self.resolve_bot_partners(std::slice::from_ref(&chat), &my_user_id) |
| 425 | .await; |
| 426 | self.store |
| 427 | .upsert_chats(&[self.partner_chat_record(&chat, &my_user_id)])?; |
| 428 | let _ = self.events.send(CoreEvent::SidebarChanged); |
| 429 | Ok(Conversation::Chat) |
| 430 | } |
| 431 | |
| 432 | pub(crate) fn resolve_stored(&self, conversation_id: &str) -> Result<Conversation> { |
| 433 | if conversation_id == NOTES_CHAT_ID { |
| 434 | return Ok(Conversation::Chat); |
| 435 | } |
| 436 | if let Some(channel) = self.store.channel(conversation_id)? { |
| 437 | return Ok(Conversation::Channel { |
| 438 | team_id: channel.team_id, |
| 439 | }); |
| 440 | } |
| 441 | if self.store.chat(conversation_id)?.is_some() { |
| 442 | return Ok(Conversation::Chat); |
| 443 | } |
| 444 | Err(Error::UnknownConversation(conversation_id.to_owned())) |
| 445 | } |
| 446 | |
| 447 | async fn fetch_newer_chat(&self, conversation_id: &str) -> Result<Delta> { |
| 448 | let previous = self.store.sync_state(conversation_id)?.unwrap_or_default(); |
| 449 | let mut collected = Vec::new(); |
| 450 | let mut before = None; |
| 451 | let mut oldest_fetched: Option<DateTime<Utc>> = None; |
| 452 | let mut reached_known = false; |
| 453 | let mut has_next = false; |
| 454 | for _ in 0..self.config.max_catch_up_pages.max(1) { |
| 455 | let page = self |
| 456 | .remote |
| 457 | .chat_messages(conversation_id, before, self.config.page_size) |
| 458 | .await?; |
| 459 | let page_oldest = oldest_created(&page); |
| 460 | has_next = page.next_link.is_some(); |
| 461 | collected.extend( |
| 462 | page.items |
| 463 | .iter() |
| 464 | .filter_map(|message| message_record(conversation_id, message)), |
| 465 | ); |
| 466 | oldest_fetched = [oldest_fetched, page_oldest].into_iter().flatten().min(); |
| 467 | let Some(known) = previous.newest_seen else { |
| 468 | break; |
| 469 | }; |
| 470 | reached_known = !has_next || page_oldest.is_none_or(|oldest| oldest <= known); |
| 471 | if reached_known { |
| 472 | break; |
| 473 | } |
| 474 | before = page_oldest; |
| 475 | } |
| 476 | let newest_fetched = collected.iter().map(|record| record.created_at).max(); |
| 477 | let state = match previous.newest_seen { |
| 478 | None => SyncState { |
| 479 | newest_seen: newest_fetched, |
| 480 | oldest_loaded: oldest_fetched, |
| 481 | has_more: has_next, |
| 482 | older_cursor: None, |
| 483 | delta_link: None, |
| 484 | }, |
| 485 | Some(known) if reached_known => SyncState { |
| 486 | newest_seen: Some(known.max(newest_fetched.unwrap_or(known))), |
| 487 | ..previous |
| 488 | }, |
| 489 | Some(known) => SyncState { |
| 490 | newest_seen: Some(known.max(newest_fetched.unwrap_or(known))), |
| 491 | oldest_loaded: oldest_fetched, |
| 492 | has_more: true, |
| 493 | older_cursor: None, |
| 494 | delta_link: None, |
| 495 | }, |
| 496 | }; |
| 497 | let mut collected = collected; |
| 498 | self.apply_chat_emotions(conversation_id, &mut collected) |
| 499 | .await; |
| 500 | let covered_from = oldest_fetched.filter(|_| has_next); |
| 501 | collected.extend(self.meeting_activities(conversation_id, covered_from).await); |
| 502 | let delta = self.ingest(conversation_id, collected)?; |
| 503 | self.store.set_sync_state(conversation_id, &state)?; |
| 504 | Ok(delta) |
| 505 | } |
| 506 | |
| 507 | async fn load_older_chat( |
| 508 | &self, |
| 509 | conversation_id: &str, |
| 510 | state: SyncState, |
| 511 | ) -> Result<Vec<MessageRecord>> { |
| 512 | let page = self |
| 513 | .remote |
| 514 | .chat_messages(conversation_id, state.oldest_loaded, self.config.page_size) |
| 515 | .await?; |
| 516 | let page_oldest = oldest_created(&page); |
| 517 | let has_more = page.next_link.is_some() && page_oldest.is_some(); |
| 518 | let mut records: Vec<_> = page |
| 519 | .items |
| 520 | .iter() |
| 521 | .filter_map(|message| message_record(conversation_id, message)) |
| 522 | .collect(); |
| 523 | self.apply_chat_emotions(conversation_id, &mut records) |
| 524 | .await; |
| 525 | let covered_from = page_oldest.filter(|_| has_more); |
| 526 | records.extend( |
| 527 | self.meeting_activities(conversation_id, covered_from) |
| 528 | .await |
| 529 | .into_iter() |
| 530 | .filter(|record| state.oldest_loaded.is_none_or(|oldest| record.created_at < oldest)), |
| 531 | ); |
| 532 | self.ingest(conversation_id, records.clone())?; |
| 533 | self.store.set_sync_state( |
| 534 | conversation_id, |
| 535 | &SyncState { |
| 536 | oldest_loaded: page_oldest.or(state.oldest_loaded), |
| 537 | has_more, |
| 538 | ..state |
| 539 | }, |
| 540 | )?; |
| 541 | Ok(sorted(records)) |
| 542 | } |
| 543 | |
| 544 | /// Graph leaves meeting chat system events out; chatsvc has them. |
| 545 | async fn meeting_activities( |
| 546 | &self, |
| 547 | conversation_id: &str, |
| 548 | covered_from: Option<DateTime<Utc>>, |
| 549 | ) -> Vec<MessageRecord> { |
| 550 | let is_meeting = self |
| 551 | .store |
| 552 | .chat(conversation_id) |
| 553 | .ok() |
| 554 | .flatten() |
| 555 | .is_some_and(|chat| chat.kind == MEETING_CHAT_KIND); |
| 556 | if !is_meeting { |
| 557 | return Vec::new(); |
| 558 | } |
| 559 | let Ok(activities) = self.remote.chat_thread_activities(conversation_id).await else { |
| 560 | return Vec::new(); |
| 561 | }; |
| 562 | activities |
| 563 | .iter() |
| 564 | .filter(|activity| covered_from.is_none_or(|from| activity.created_at >= from)) |
| 565 | .map(|activity| thread_activity_record(conversation_id, activity)) |
| 566 | .collect() |
| 567 | } |
| 568 | |
| 569 | pub(crate) fn ingest( |
| 570 | &self, |
| 571 | conversation_id: &str, |
| 572 | mut records: Vec<MessageRecord>, |
| 573 | ) -> Result<Delta> { |
| 574 | let ids: Vec<String> = records |
| 575 | .iter() |
| 576 | .map(|record| record.message_id.clone()) |
| 577 | .collect(); |
| 578 | let existing = self.store.messages_by_id(conversation_id, &ids)?; |
| 579 | for record in &mut records { |
| 580 | if let Some(cached) = existing.get(&record.message_id) |
| 581 | && !has_stored_links(&record.links_json) |
| 582 | { |
| 583 | record.links_json.clone_from(&cached.links_json); |
| 584 | } |
| 585 | } |
| 586 | self.store.upsert_messages(&records)?; |
| 587 | self.update_chat_preview(&records)?; |
| 588 | let mut delta = Delta::default(); |
| 589 | for record in sorted(records) { |
| 590 | match existing.get(&record.message_id) { |
| 591 | None => delta.added.push(record), |
| 592 | Some(cached) if *cached != record => delta.updated.push(record), |
| 593 | Some(_) => {} |
| 594 | } |
| 595 | } |
| 596 | Ok(delta) |
| 597 | } |
| 598 | |
| 599 | /// A call keeps the older line but moves the chat time to the call, like Teams. |
| 600 | pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> { |
| 601 | let (calls, lines): (Vec<&MessageRecord>, Vec<&MessageRecord>) = records |
| 602 | .iter() |
| 603 | .filter(|record| crate::preview::moves_the_chat(record)) |
| 604 | .partition(|record| crate::preview::keeps_previous_line(record)); |
| 605 | let mut changed = false; |
| 606 | if let Some(newest) = lines.into_iter().max_by_key(|record| record.created_at) { |
| 607 | let preview = OwnedPreview::from_record(newest); |
| 608 | changed |= self.store.update_chat_preview( |
| 609 | &newest.conversation_id, |
| 610 | newest.created_at, |
| 611 | &preview.as_store(), |
| 612 | )?; |
| 613 | } |
| 614 | if let Some(call) = calls.into_iter().max_by_key(|record| record.created_at) { |
| 615 | changed |= self |
| 616 | .store |
| 617 | .touch_chat_time(&call.conversation_id, call.created_at)?; |
| 618 | } |
| 619 | if changed { |
| 620 | self.preview_changed.store(true, Ordering::SeqCst); |
| 621 | } |
| 622 | Ok(()) |
| 623 | } |
| 624 | |
| 625 | pub(crate) fn announce(&self, conversation_id: &str, changed: bool) { |
| 626 | if changed { |
| 627 | let _ = self.events.send(CoreEvent::MessagesChanged { |
| 628 | conversation_id: conversation_id.to_owned(), |
| 629 | }); |
| 630 | } |
| 631 | if self.preview_changed.swap(false, Ordering::SeqCst) { |
| 632 | let _ = self.events.send(CoreEvent::SidebarChanged); |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | pub(crate) fn announce_stored_late(&self, conversation_id: &str, delta: &Delta) { |
| 637 | if delta.added.is_empty() { |
| 638 | return; |
| 639 | } |
| 640 | let _ = self.events.send(CoreEvent::MessagesStoredLate { |
| 641 | conversation_id: conversation_id.to_owned(), |
| 642 | message_ids: delta |
| 643 | .added |
| 644 | .iter() |
| 645 | .map(|record| record.message_id.clone()) |
| 646 | .collect(), |
| 647 | }); |
| 648 | } |
| 649 | |
| 650 | pub(crate) fn report(&self, message: String) { |
| 651 | let _ = self.events.send(CoreEvent::Error { message }); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | fn oldest_created(page: &RemotePage) -> Option<DateTime<Utc>> { |
| 656 | page.items |
| 657 | .iter() |
| 658 | .filter_map(|message| message.created_date_time) |
| 659 | .min() |
| 660 | } |
| 661 | |
| 662 | pub(crate) fn thread_records(channel_id: &str, threads: &[Message]) -> Vec<MessageRecord> { |
| 663 | threads |
| 664 | .iter() |
| 665 | .flat_map(|thread| flatten_thread(channel_id, thread)) |
| 666 | .collect() |
| 667 | } |
| 668 | |
| 669 | pub(crate) fn sorted(mut records: Vec<MessageRecord>) -> Vec<MessageRecord> { |
| 670 | records.sort_by(|left, right| { |
| 671 | left.created_at |
| 672 | .cmp(&right.created_at) |
| 673 | .then_with(|| left.message_id.cmp(&right.message_id)) |
| 674 | }); |
| 675 | records |
| 676 | } |