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