| 1 | use std::sync::Arc; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use calling::EngineEvent; |
| 5 | use chatsvc::{ |
| 6 | Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, |
| 7 | RealtimeEvent, StatusKind, TypingEvent, |
| 8 | }; |
| 9 | use chrono::{DateTime, Local, Offset, Utc}; |
| 10 | use graph::Graph; |
| 11 | use session::{Session, SessionConfig, Transport}; |
| 12 | use store::Store; |
| 13 | use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine}; |
| 14 | use tokio::sync::{Notify, mpsc, watch}; |
| 15 | |
| 16 | use crate::browser_sign_in::BrowserSignInState; |
| 17 | use crate::call::{CallLauncher, fetch_window}; |
| 18 | use crate::presence_link::{self, LinkSignal}; |
| 19 | |
| 20 | pub type Engine = SyncEngine<Graph>; |
| 21 | |
| 22 | const FORWARD_HEAL_PAUSE: Duration = Duration::from_secs(2); |
| 23 | const CONNECT_RETRY: Duration = Duration::from_secs(8); |
| 24 | const REFRESH_INTERVAL: Duration = Duration::from_secs(120); |
| 25 | const REFRESH_SETTLE: Duration = Duration::from_secs(2); |
| 26 | const PINS_INTERVAL: Duration = Duration::from_secs(90); |
| 27 | const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60); |
| 28 | const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30); |
| 29 | const ORG_LIST_ATTEMPTS: usize = 5; |
| 30 | const REALTIME_RETRY: Duration = Duration::from_secs(15); |
| 31 | const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [ |
| 32 | Duration::from_secs(1), |
| 33 | Duration::from_secs(3), |
| 34 | Duration::from_secs(8), |
| 35 | ]; |
| 36 | const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60); |
| 37 | const MAX_ERROR_CHARS: usize = 120; |
| 38 | const IMAGE_DIRECTORY: &str = "images"; |
| 39 | const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024; |
| 40 | |
| 41 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 42 | pub enum ConnectionState { |
| 43 | Connecting, |
| 44 | Online, |
| 45 | NoBrowser, |
| 46 | NoAppTab, |
| 47 | LoginRequired, |
| 48 | Failed(String), |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 52 | pub enum LiveState { |
| 53 | Off, |
| 54 | Connecting, |
| 55 | Live, |
| 56 | Reconnecting, |
| 57 | MessageLoss, |
| 58 | Failed, |
| 59 | } |
| 60 | |
| 61 | pub enum BackendEvent { |
| 62 | Connection(ConnectionState), |
| 63 | BrowserSignIn(BrowserSignInState), |
| 64 | Engine(Arc<Engine>), |
| 65 | Calls(Arc<CallLauncher>), |
| 66 | Calendar(Vec<CalendarEvent>), |
| 67 | CalendarNudge(mpsc::UnboundedSender<()>), |
| 68 | Ring(EngineEvent), |
| 69 | ThreadChanged(String), |
| 70 | Core(CoreEvent), |
| 71 | Live(LiveState), |
| 72 | Typing(TypingEvent), |
| 73 | Favorites(Vec<String>), |
| 74 | Synced(DateTime<Utc>), |
| 75 | LiveRetry(Arc<Notify>), |
| 76 | Orgs(Vec<app_base::orgs::Org>), |
| 77 | OrgMessage(crate::org_watch::OrgMessage), |
| 78 | } |
| 79 | |
| 80 | impl BackendEvent { |
| 81 | pub fn kind(&self) -> String { |
| 82 | match self { |
| 83 | BackendEvent::Connection(_) => "Connection".into(), |
| 84 | BackendEvent::BrowserSignIn(_) => "BrowserSignIn".into(), |
| 85 | BackendEvent::Engine(_) => "Engine".into(), |
| 86 | BackendEvent::Calls(_) => "Calls".into(), |
| 87 | BackendEvent::Calendar(_) => "Calendar".into(), |
| 88 | BackendEvent::CalendarNudge(_) => "CalendarNudge".into(), |
| 89 | BackendEvent::Ring(_) => "Ring".into(), |
| 90 | BackendEvent::ThreadChanged(_) => "ThreadChanged".into(), |
| 91 | BackendEvent::Core(event) => { |
| 92 | let debug = format!("{event:?}"); |
| 93 | let name = debug.split(['{', '(', ' ']).next().unwrap_or_default(); |
| 94 | format!("Core::{name}") |
| 95 | } |
| 96 | BackendEvent::Live(_) => "Live".into(), |
| 97 | BackendEvent::Typing(_) => "Typing".into(), |
| 98 | BackendEvent::Favorites(_) => "Favorites".into(), |
| 99 | BackendEvent::Synced(_) => "Synced".into(), |
| 100 | BackendEvent::LiveRetry(_) => "LiveRetry".into(), |
| 101 | BackendEvent::Orgs(_) => "Orgs".into(), |
| 102 | BackendEvent::OrgMessage(_) => "OrgMessage".into(), |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | type EventSender = mpsc::UnboundedSender<BackendEvent>; |
| 108 | |
| 109 | pub fn classify_session_error(error: &session::Error) -> ConnectionState { |
| 110 | match error { |
| 111 | session::Error::NoBrowser { .. } => ConnectionState::NoBrowser, |
| 112 | session::Error::NoAppTab => ConnectionState::NoAppTab, |
| 113 | session::Error::LoginRequired(_) | session::Error::NoFreshToken { .. } => { |
| 114 | ConnectionState::LoginRequired |
| 115 | } |
| 116 | other => ConnectionState::Failed(shorten(&other.to_string())), |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | pub fn classify_core_error(error: &teams_core::Error) -> ConnectionState { |
| 121 | match error { |
| 122 | teams_core::Error::Graph(graph::Error::Session(inner)) => classify_session_error(inner), |
| 123 | other => ConnectionState::Failed(shorten(&other.to_string())), |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn image_directory() -> Option<std::path::PathBuf> { |
| 128 | directories::ProjectDirs::from("", "", store::DATA_DIR_NAME) |
| 129 | .map(|directories| directories.data_local_dir().join(IMAGE_DIRECTORY)) |
| 130 | } |
| 131 | |
| 132 | fn shorten(text: &str) -> String { |
| 133 | text.chars().take(MAX_ERROR_CHARS).collect() |
| 134 | } |
| 135 | |
| 136 | pub fn live_state_for(kind: StatusKind) -> LiveState { |
| 137 | match kind { |
| 138 | StatusKind::Connected => LiveState::Live, |
| 139 | StatusKind::Disconnected => LiveState::Reconnecting, |
| 140 | StatusKind::MessageLoss => LiveState::MessageLoss, |
| 141 | StatusKind::Error => LiveState::Failed, |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> { |
| 146 | match kind { |
| 147 | StatusKind::Connected => Some(LinkSignal::Connected), |
| 148 | StatusKind::Disconnected => Some(LinkSignal::Disconnected), |
| 149 | StatusKind::MessageLoss | StatusKind::Error => None, |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | pub fn start( |
| 154 | store: Arc<Store>, |
| 155 | transport: Arc<dyn Transport>, |
| 156 | ringable: bool, |
| 157 | activity: watch::Receiver<bool>, |
| 158 | guest_tenant: Option<String>, |
| 159 | ) -> mpsc::UnboundedReceiver<BackendEvent> { |
| 160 | let (sender, receiver) = mpsc::unbounded_channel(); |
| 161 | crate::runtime::handle().spawn(supervise( |
| 162 | store, |
| 163 | transport, |
| 164 | ringable, |
| 165 | activity, |
| 166 | guest_tenant, |
| 167 | sender, |
| 168 | )); |
| 169 | receiver |
| 170 | } |
| 171 | |
| 172 | async fn supervise( |
| 173 | store: Arc<Store>, |
| 174 | transport: Arc<dyn Transport>, |
| 175 | ringable: bool, |
| 176 | activity: watch::Receiver<bool>, |
| 177 | guest_tenant: Option<String>, |
| 178 | events: EventSender, |
| 179 | ) { |
| 180 | let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting)); |
| 181 | let home = loop { |
| 182 | match Session::with_transport(transport.clone(), SessionConfig::for_app()).await { |
| 183 | Ok(session) => break session, |
| 184 | Err(error) => { |
| 185 | let _ = events.send(BackendEvent::Connection(classify_session_error(&error))); |
| 186 | tokio::time::sleep(CONNECT_RETRY).await; |
| 187 | } |
| 188 | } |
| 189 | }; |
| 190 | tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone())); |
| 191 | // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open. |
| 192 | // Chat files of a guest org go to the home OneDrive: the guest tenant has none. |
| 193 | let (session, home_drive) = match &guest_tenant { |
| 194 | Some(tenant) => (home.in_tenant(tenant), Some(home.clone())), |
| 195 | None => (home.clone(), None), |
| 196 | }; |
| 197 | let build = || { |
| 198 | let graph = Graph::new(session.clone()); |
| 199 | let graph = match &home_drive { |
| 200 | Some(home) => graph.with_home_drive(home.clone()), |
| 201 | None => graph, |
| 202 | }; |
| 203 | SyncEngine::new(graph, store.clone()) |
| 204 | .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session))) |
| 205 | }; |
| 206 | let engine = image_directory() |
| 207 | .and_then(|directory| { |
| 208 | build() |
| 209 | .with_image_dir(&directory, IMAGE_CACHE_MAX_BYTES) |
| 210 | .ok() |
| 211 | }) |
| 212 | .unwrap_or_else(build); |
| 213 | let engine = Arc::new(engine); |
| 214 | let _ = events.send(BackendEvent::Engine(engine.clone())); |
| 215 | let ring_events = events.clone(); |
| 216 | let launcher = CallLauncher::start(transport, ringable, move |event| { |
| 217 | let _ = ring_events.send(BackendEvent::Ring(event)); |
| 218 | }); |
| 219 | let _ = events.send(BackendEvent::Calls(launcher)); |
| 220 | tokio::spawn(forward_core_events(engine.clone(), events.clone())); |
| 221 | let (nudge, nudges) = mpsc::unbounded_channel(); |
| 222 | let resend = Arc::new(Notify::new()); |
| 223 | let link = presence_link::start(&session, activity.clone(), resend.clone()); |
| 224 | let live_retry = Arc::new(Notify::new()); |
| 225 | let _ = events.send(BackendEvent::LiveRetry(live_retry.clone())); |
| 226 | tokio::spawn(realtime_loop( |
| 227 | session.clone(), |
| 228 | engine.clone(), |
| 229 | events.clone(), |
| 230 | nudge, |
| 231 | activity, |
| 232 | resend, |
| 233 | link, |
| 234 | live_retry, |
| 235 | )); |
| 236 | // A guest has no mailbox in the org it visits, so Outlook is read from the home tenant. |
| 237 | tokio::spawn(calendar_loop(home, store.clone(), events.clone())); |
| 238 | tokio::spawn(pins_loop(session, events.clone())); |
| 239 | tokio::spawn(presence_resubscribe_loop(engine.clone())); |
| 240 | refresh_loop(engine, events, nudges).await; |
| 241 | } |
| 242 | |
| 243 | /// Fetches the account's organizations once per start, retried a few times while sign-in settles, |
| 244 | /// and keeps every org that is not open live for notifications. |
| 245 | async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) { |
| 246 | for _ in 0..ORG_LIST_ATTEMPTS { |
| 247 | match chatsvc::list_tenants(&home).await { |
| 248 | Ok(tenants) => { |
| 249 | let mut orgs = Vec::with_capacity(tenants.len()); |
| 250 | for tenant in tenants { |
| 251 | let org = app_base::orgs::Org { |
| 252 | id: tenant.id, |
| 253 | name: tenant.name, |
| 254 | guest: tenant.guest, |
| 255 | }; |
| 256 | let open = match &open_guest { |
| 257 | Some(open) => *open == org.id, |
| 258 | None => !org.guest, |
| 259 | }; |
| 260 | if !open { |
| 261 | let session = if org.guest { |
| 262 | home.in_tenant(&org.id) |
| 263 | } else { |
| 264 | home.clone() |
| 265 | }; |
| 266 | tokio::spawn(crate::org_watch::watch( |
| 267 | session, |
| 268 | org.clone(), |
| 269 | tenant.user_id, |
| 270 | events.clone(), |
| 271 | )); |
| 272 | } |
| 273 | orgs.push(org); |
| 274 | } |
| 275 | let _ = events.send(BackendEvent::Orgs(orgs)); |
| 276 | return; |
| 277 | } |
| 278 | Err(error) => { |
| 279 | crate::diagnostics::record(format!("orgs: tenant list not loaded: {error}")); |
| 280 | tokio::time::sleep(CONNECT_RETRY).await; |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | async fn forward_core_events(engine: Arc<Engine>, events: EventSender) { |
| 287 | let mut receiver = engine.subscribe(); |
| 288 | loop { |
| 289 | let event = match receiver.recv().await { |
| 290 | Ok(event) => event, |
| 291 | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => CoreEvent::SidebarChanged, |
| 292 | Err(tokio::sync::broadcast::error::RecvError::Closed) => return, |
| 293 | }; |
| 294 | if events.send(BackendEvent::Core(event)).is_err() { |
| 295 | return; |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | async fn refresh_loop( |
| 301 | engine: Arc<Engine>, |
| 302 | events: EventSender, |
| 303 | mut nudges: mpsc::UnboundedReceiver<()>, |
| 304 | ) { |
| 305 | let mut interval = tokio::time::interval(REFRESH_INTERVAL); |
| 306 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 307 | let mut forwards_healing = false; |
| 308 | loop { |
| 309 | tokio::select! { |
| 310 | _ = interval.tick() => {} |
| 311 | nudge = nudges.recv() => { |
| 312 | if nudge.is_none() { |
| 313 | return; |
| 314 | } |
| 315 | tokio::time::sleep(REFRESH_SETTLE).await; |
| 316 | while nudges.try_recv().is_ok() {} |
| 317 | } |
| 318 | } |
| 319 | match engine.refresh_sidebar().await { |
| 320 | Ok(_) => { |
| 321 | if !std::mem::replace(&mut forwards_healing, true) { |
| 322 | let engine = engine.clone(); |
| 323 | tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await }); |
| 324 | } |
| 325 | if let Err(error) = engine.refresh_folders().await { |
| 326 | crate::diagnostics::record(format!( |
| 327 | "sync: chat folders and channel layout not refreshed: {error}" |
| 328 | )); |
| 329 | } |
| 330 | let _ = events.send(BackendEvent::Connection(ConnectionState::Online)); |
| 331 | let _ = events.send(BackendEvent::Synced(Utc::now())); |
| 332 | } |
| 333 | Err(error) => { |
| 334 | let _ = events.send(BackendEvent::Connection(classify_core_error(&error))); |
| 335 | tokio::time::sleep(CONNECT_RETRY).await; |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | async fn realtime_loop( |
| 342 | session: Session, |
| 343 | engine: Arc<Engine>, |
| 344 | events: EventSender, |
| 345 | nudge: mpsc::UnboundedSender<()>, |
| 346 | mut activity: watch::Receiver<bool>, |
| 347 | resend: Arc<Notify>, |
| 348 | link: mpsc::UnboundedSender<LinkSignal>, |
| 349 | live_retry: Arc<Notify>, |
| 350 | ) { |
| 351 | loop { |
| 352 | let _ = events.send(BackendEvent::Live(LiveState::Connecting)); |
| 353 | let config = RealtimeConfig { |
| 354 | initially_active: *activity.borrow(), |
| 355 | ..RealtimeConfig::default() |
| 356 | }; |
| 357 | match Realtime::start_with(&session, config).await { |
| 358 | Ok(mut realtime) => { |
| 359 | loop { |
| 360 | let event = tokio::select! { |
| 361 | event = realtime.recv() => event, |
| 362 | Ok(()) = activity.changed() => { |
| 363 | realtime.set_activity(*activity.borrow_and_update()); |
| 364 | continue; |
| 365 | } |
| 366 | _ = resend.notified() => { |
| 367 | realtime.resend_activity(); |
| 368 | continue; |
| 369 | } |
| 370 | }; |
| 371 | let Some(event) = event else { break }; |
| 372 | match event { |
| 373 | RealtimeEvent::Message(message) => { |
| 374 | let _ = events.send(BackendEvent::Live(LiveState::Live)); |
| 375 | if let Some(conversation_id) = thread_signal(&message) { |
| 376 | let _ = events.send(BackendEvent::ThreadChanged(conversation_id)); |
| 377 | } |
| 378 | let receipt_engine = engine.clone(); |
| 379 | let receipt_event = message.clone(); |
| 380 | engine.handle_pin_event(&message); |
| 381 | if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) |
| 382 | { |
| 383 | let activity_engine = engine.clone(); |
| 384 | tokio::spawn( |
| 385 | async move { activity_engine.refresh_activity().await }, |
| 386 | ); |
| 387 | } |
| 388 | tokio::spawn(async move { |
| 389 | receipt_engine.handle_receipt_event(&receipt_event).await |
| 390 | }); |
| 391 | tokio::spawn(handle_message_event( |
| 392 | engine.clone(), |
| 393 | nudge.clone(), |
| 394 | message, |
| 395 | )); |
| 396 | } |
| 397 | RealtimeEvent::Typing(typing) => { |
| 398 | let _ = events.send(BackendEvent::Typing(typing)); |
| 399 | } |
| 400 | RealtimeEvent::Status(status) => { |
| 401 | let _ = events.send(BackendEvent::Live(live_state_for(status.kind))); |
| 402 | if let Some(signal) = link_signal_for(status.kind) { |
| 403 | let _ = link.send(signal); |
| 404 | } |
| 405 | let receipt_engine = engine.clone(); |
| 406 | let receipt_status = status.clone(); |
| 407 | tokio::spawn(async move { |
| 408 | receipt_engine.handle_receipt_status(&receipt_status).await |
| 409 | }); |
| 410 | } |
| 411 | RealtimeEvent::Presence(updates) => { |
| 412 | engine.apply_presence(&updates); |
| 413 | if engine.concerns_me(&updates) { |
| 414 | let engine = engine.clone(); |
| 415 | tokio::spawn(async move { engine.refresh_own_status().await }); |
| 416 | } |
| 417 | } |
| 418 | RealtimeEvent::Endpoint(endpoint) => { |
| 419 | let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone())); |
| 420 | let engine = engine.clone(); |
| 421 | tokio::spawn(async move { engine.presence_endpoint(endpoint).await }); |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 | let _ = events.send(BackendEvent::Live(LiveState::Reconnecting)); |
| 426 | let _ = link.send(LinkSignal::Disconnected); |
| 427 | } |
| 428 | Err(_) => { |
| 429 | let _ = events.send(BackendEvent::Live(LiveState::Failed)); |
| 430 | let _ = link.send(LinkSignal::Disconnected); |
| 431 | } |
| 432 | } |
| 433 | tokio::select! { |
| 434 | _ = tokio::time::sleep(REALTIME_RETRY) => {} |
| 435 | _ = live_retry.notified() => {} |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | async fn presence_resubscribe_loop(engine: Arc<Engine>) { |
| 441 | let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE); |
| 442 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 443 | interval.tick().await; |
| 444 | loop { |
| 445 | interval.tick().await; |
| 446 | let _ = engine.resubscribe_presence().await; |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | /// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message). |
| 451 | pub fn thread_signal(event: &MessageEvent) -> Option<String> { |
| 452 | match event.kind { |
| 453 | EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(), |
| 454 | _ => None, |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> { |
| 459 | let conversation_id = event.conversation_id.clone()?; |
| 460 | match event.kind { |
| 461 | EventKind::MessageUpdate => Some(match event.message_id.clone() { |
| 462 | Some(message_id) => RefreshPlan::Message { |
| 463 | conversation_id, |
| 464 | message_id, |
| 465 | }, |
| 466 | None => RefreshPlan::Newer { conversation_id }, |
| 467 | }), |
| 468 | EventKind::NewMessage => Some(match event.message_id.clone() { |
| 469 | Some(message_id) => RefreshPlan::Arrival { |
| 470 | conversation_id, |
| 471 | message_id, |
| 472 | }, |
| 473 | None => RefreshPlan::Newer { conversation_id }, |
| 474 | }), |
| 475 | _ => None, |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 480 | pub enum RefreshPlan { |
| 481 | Newer { |
| 482 | conversation_id: String, |
| 483 | }, |
| 484 | Arrival { |
| 485 | conversation_id: String, |
| 486 | message_id: String, |
| 487 | }, |
| 488 | Message { |
| 489 | conversation_id: String, |
| 490 | message_id: String, |
| 491 | }, |
| 492 | } |
| 493 | |
| 494 | async fn handle_message_event( |
| 495 | engine: Arc<Engine>, |
| 496 | nudge: mpsc::UnboundedSender<()>, |
| 497 | event: MessageEvent, |
| 498 | ) { |
| 499 | let Some(plan) = refresh_plan(&event) else { |
| 500 | return; |
| 501 | }; |
| 502 | let outcome = match &plan { |
| 503 | RefreshPlan::Newer { conversation_id } |
| 504 | | RefreshPlan::Arrival { |
| 505 | conversation_id, .. |
| 506 | } => engine.fetch_newer(conversation_id).await.map(|_| ()), |
| 507 | RefreshPlan::Message { |
| 508 | conversation_id, |
| 509 | message_id, |
| 510 | } => engine |
| 511 | .refresh_message(conversation_id, message_id) |
| 512 | .await |
| 513 | .map(|_| ()), |
| 514 | }; |
| 515 | let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_))); |
| 516 | if unknown || event.kind == EventKind::NewMessage { |
| 517 | let _ = nudge.send(()); |
| 518 | } |
| 519 | if let ( |
| 520 | Ok(()), |
| 521 | RefreshPlan::Arrival { |
| 522 | conversation_id, |
| 523 | message_id, |
| 524 | }, |
| 525 | ) = (outcome, &plan) |
| 526 | { |
| 527 | let _ = engine |
| 528 | .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS) |
| 529 | .await; |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender) { |
| 534 | let calendar = Calendar::new(&session); |
| 535 | let (nudge, mut nudges) = mpsc::unbounded_channel(); |
| 536 | let _ = events.send(BackendEvent::CalendarNudge(nudge)); |
| 537 | let mut interval = tokio::time::interval(CALENDAR_INTERVAL); |
| 538 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 539 | let mut last_fetch: Option<tokio::time::Instant> = None; |
| 540 | let mut deferred_fetch: Option<tokio::time::Instant> = None; |
| 541 | loop { |
| 542 | tokio::select! { |
| 543 | _ = interval.tick() => {} |
| 544 | _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {} |
| 545 | nudge = nudges.recv() => { |
| 546 | if nudge.is_none() { |
| 547 | return; |
| 548 | } |
| 549 | while nudges.try_recv().is_ok() {} |
| 550 | if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) { |
| 551 | deferred_fetch = Some(fetched + CALENDAR_MIN_GAP); |
| 552 | continue; |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | deferred_fetch = None; |
| 557 | last_fetch = Some(tokio::time::Instant::now()); |
| 558 | let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix()); |
| 559 | let accounts = store::load_calendar_accounts(&store); |
| 560 | let mut fetched_accounts = accounts.clone(); |
| 561 | let mut combined = Vec::new(); |
| 562 | let mut outlook_failed = false; |
| 563 | if accounts.outlook_selected { |
| 564 | match calendar.calendar_view(start, end).await { |
| 565 | Ok(fetched) => combined.extend(fetched), |
| 566 | Err(error) => { |
| 567 | outlook_failed = true; |
| 568 | crate::diagnostics::record(format!( |
| 569 | "calls: outlook calendar not loaded: {}", |
| 570 | shorten(&error.to_string()) |
| 571 | )); |
| 572 | } |
| 573 | } |
| 574 | } |
| 575 | match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end) |
| 576 | .await |
| 577 | { |
| 578 | Ok((google_events, account_errors)) => { |
| 579 | // Only refreshed tokens: a calendar toggle made during the fetch stays. |
| 580 | let _ = store::merge_google_tokens(&store, &fetched_accounts); |
| 581 | combined.extend(google_events); |
| 582 | for message in account_errors { |
| 583 | crate::diagnostics::record(format!( |
| 584 | "calls: google account not loaded: {}", |
| 585 | shorten(&message) |
| 586 | )); |
| 587 | } |
| 588 | } |
| 589 | Err(error) => crate::diagnostics::record(format!( |
| 590 | "calls: google calendar not loaded: {}", |
| 591 | shorten(&error) |
| 592 | )), |
| 593 | } |
| 594 | if combined.is_empty() && outlook_failed && !accounts.has_google() { |
| 595 | continue; |
| 596 | } |
| 597 | let home = { |
| 598 | use store::CalendarProvider; |
| 599 | let source = match accounts.home.provider { |
| 600 | CalendarProvider::Outlook => chatsvc::CalendarSource::Outlook, |
| 601 | CalendarProvider::Google => chatsvc::CalendarSource::Google, |
| 602 | CalendarProvider::CalDav => chatsvc::CalendarSource::CalDav, |
| 603 | }; |
| 604 | Some(chatsvc::HomeCalendar { |
| 605 | source, |
| 606 | account_id: accounts.home.account_id.as_str(), |
| 607 | calendar_id: accounts.home.calendar_id.as_str(), |
| 608 | }) |
| 609 | }; |
| 610 | let merged = chatsvc::merge_calendar_events(combined, home); |
| 611 | if events.send(BackendEvent::Calendar(merged)).is_err() { |
| 612 | return; |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | async fn pins_loop(session: Session, events: EventSender) { |
| 618 | let pins = Pins::new(&session); |
| 619 | let mut chat_ids: Vec<String> = Vec::new(); |
| 620 | let mut channel_ids: Vec<String> = Vec::new(); |
| 621 | let mut interval = tokio::time::interval(PINS_INTERVAL); |
| 622 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 623 | loop { |
| 624 | interval.tick().await; |
| 625 | if let Ok(pinned) = pins.pinned_chats().await { |
| 626 | chat_ids = pinned.chat_ids; |
| 627 | } |
| 628 | if let Ok(pinned) = pins.pinned_channels().await { |
| 629 | channel_ids = pinned.channel_ids; |
| 630 | } |
| 631 | let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect(); |
| 632 | if events.send(BackendEvent::Favorites(combined)).is_err() { |
| 633 | return; |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | #[cfg(test)] |
| 639 | mod tests { |
| 640 | use super::*; |
| 641 | |
| 642 | fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent { |
| 643 | MessageEvent { |
| 644 | resource_type: "x".into(), |
| 645 | kind, |
| 646 | conversation_id: conversation.map(str::to_owned), |
| 647 | message_id: message.map(str::to_owned), |
| 648 | received_at: Utc::now(), |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | #[test] |
| 653 | fn new_message_waits_for_its_arrival() { |
| 654 | assert_eq!( |
| 655 | refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))), |
| 656 | Some(RefreshPlan::Arrival { |
| 657 | conversation_id: "c".into(), |
| 658 | message_id: "m".into() |
| 659 | }) |
| 660 | ); |
| 661 | assert_eq!( |
| 662 | refresh_plan(&event(EventKind::NewMessage, Some("c"), None)), |
| 663 | Some(RefreshPlan::Newer { |
| 664 | conversation_id: "c".into() |
| 665 | }) |
| 666 | ); |
| 667 | } |
| 668 | |
| 669 | #[test] |
| 670 | fn update_refreshes_one_message() { |
| 671 | assert_eq!( |
| 672 | refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))), |
| 673 | Some(RefreshPlan::Message { |
| 674 | conversation_id: "c".into(), |
| 675 | message_id: "m".into() |
| 676 | }) |
| 677 | ); |
| 678 | assert_eq!( |
| 679 | refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)), |
| 680 | Some(RefreshPlan::Newer { |
| 681 | conversation_id: "c".into() |
| 682 | }) |
| 683 | ); |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn thread_updates_and_new_messages_signal_a_possible_meeting_change() { |
| 688 | assert_eq!( |
| 689 | thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(), |
| 690 | Some("c") |
| 691 | ); |
| 692 | assert_eq!( |
| 693 | thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(), |
| 694 | Some("c") |
| 695 | ); |
| 696 | assert_eq!( |
| 697 | thread_signal(&event(EventKind::Typing, Some("c"), None)), |
| 698 | None |
| 699 | ); |
| 700 | assert_eq!( |
| 701 | thread_signal(&event(EventKind::ThreadUpdate, None, None)), |
| 702 | None |
| 703 | ); |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn typing_and_missing_conversation_are_ignored() { |
| 708 | assert_eq!( |
| 709 | refresh_plan(&event(EventKind::Typing, Some("c"), None)), |
| 710 | None |
| 711 | ); |
| 712 | assert_eq!( |
| 713 | refresh_plan(&event(EventKind::NewMessage, None, None)), |
| 714 | None |
| 715 | ); |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn session_errors_map_to_states() { |
| 720 | assert_eq!( |
| 721 | classify_session_error(&session::Error::NoAppTab), |
| 722 | ConnectionState::NoAppTab |
| 723 | ); |
| 724 | assert_eq!( |
| 725 | classify_session_error(&session::Error::LoginRequired("x".into())), |
| 726 | ConnectionState::LoginRequired |
| 727 | ); |
| 728 | assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live); |
| 729 | } |
| 730 | |
| 731 | #[test] |
| 732 | fn only_connect_and_disconnect_move_the_link() { |
| 733 | assert_eq!( |
| 734 | link_signal_for(StatusKind::Connected), |
| 735 | Some(LinkSignal::Connected) |
| 736 | ); |
| 737 | assert_eq!( |
| 738 | link_signal_for(StatusKind::Disconnected), |
| 739 | Some(LinkSignal::Disconnected) |
| 740 | ); |
| 741 | assert_eq!(link_signal_for(StatusKind::MessageLoss), None); |
| 742 | assert_eq!(link_signal_for(StatusKind::Error), None); |
| 743 | } |
| 744 | } |