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