| 1 | use std::sync::Arc; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use calling::EngineEvent; |
| 5 | use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent}; |
| 6 | use chrono::{DateTime, Local, Offset, Utc}; |
| 7 | use graph::Graph; |
| 8 | use session::{Session, SessionConfig, Transport}; |
| 9 | use store::Store; |
| 10 | use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine}; |
| 11 | use tokio::sync::{Notify, mpsc, watch}; |
| 12 | |
| 13 | use crate::call::{CallLauncher, fetch_window}; |
| 14 | use crate::presence_link::{self, LinkSignal}; |
| 15 | |
| 16 | pub type Engine = SyncEngine<Graph>; |
| 17 | |
| 18 | const CONNECT_RETRY: Duration = Duration::from_secs(8); |
| 19 | const REFRESH_INTERVAL: Duration = Duration::from_secs(120); |
| 20 | const REFRESH_SETTLE: Duration = Duration::from_secs(2); |
| 21 | const PINS_INTERVAL: Duration = Duration::from_secs(90); |
| 22 | const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60); |
| 23 | const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30); |
| 24 | const REALTIME_RETRY: Duration = Duration::from_secs(15); |
| 25 | const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60); |
| 26 | const MAX_ERROR_CHARS: usize = 120; |
| 27 | const IMAGE_DIRECTORY: &str = "images"; |
| 28 | const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub enum ConnectionState { |
| 32 | Connecting, |
| 33 | Online, |
| 34 | NoBrowser, |
| 35 | NoAppTab, |
| 36 | LoginRequired, |
| 37 | Failed(String), |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 41 | pub enum LiveState { |
| 42 | Off, |
| 43 | Connecting, |
| 44 | Live, |
| 45 | Reconnecting, |
| 46 | MessageLoss, |
| 47 | Failed, |
| 48 | } |
| 49 | |
| 50 | pub enum BackendEvent { |
| 51 | Connection(ConnectionState), |
| 52 | Engine(Arc<Engine>), |
| 53 | Calls(Arc<CallLauncher>), |
| 54 | Calendar(Vec<CalendarEvent>), |
| 55 | CalendarNudge(mpsc::UnboundedSender<()>), |
| 56 | Ring(EngineEvent), |
| 57 | ThreadChanged(String), |
| 58 | Core(CoreEvent), |
| 59 | Live(LiveState), |
| 60 | Typing(TypingEvent), |
| 61 | Favorites(Vec<String>), |
| 62 | Synced(DateTime<Utc>), |
| 63 | } |
| 64 | |
| 65 | type EventSender = mpsc::UnboundedSender<BackendEvent>; |
| 66 | |
| 67 | pub fn classify_session_error(error: &session::Error) -> ConnectionState { |
| 68 | match error { |
| 69 | session::Error::NoBrowser { .. } => ConnectionState::NoBrowser, |
| 70 | session::Error::NoAppTab => ConnectionState::NoAppTab, |
| 71 | session::Error::LoginRequired(_) | session::Error::NoFreshToken { .. } => { |
| 72 | ConnectionState::LoginRequired |
| 73 | } |
| 74 | other => ConnectionState::Failed(shorten(&other.to_string())), |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | pub fn classify_core_error(error: &teams_core::Error) -> ConnectionState { |
| 79 | match error { |
| 80 | teams_core::Error::Graph(graph::Error::Session(inner)) => classify_session_error(inner), |
| 81 | other => ConnectionState::Failed(shorten(&other.to_string())), |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | fn image_directory() -> Option<std::path::PathBuf> { |
| 86 | directories::ProjectDirs::from("", "", store::DATA_DIR_NAME) |
| 87 | .map(|directories| directories.data_local_dir().join(IMAGE_DIRECTORY)) |
| 88 | } |
| 89 | |
| 90 | fn shorten(text: &str) -> String { |
| 91 | text.chars().take(MAX_ERROR_CHARS).collect() |
| 92 | } |
| 93 | |
| 94 | pub fn live_state_for(kind: StatusKind) -> LiveState { |
| 95 | match kind { |
| 96 | StatusKind::Connected => LiveState::Live, |
| 97 | StatusKind::Disconnected => LiveState::Reconnecting, |
| 98 | StatusKind::MessageLoss => LiveState::MessageLoss, |
| 99 | StatusKind::Error => LiveState::Failed, |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> { |
| 104 | match kind { |
| 105 | StatusKind::Connected => Some(LinkSignal::Connected), |
| 106 | StatusKind::Disconnected => Some(LinkSignal::Disconnected), |
| 107 | StatusKind::MessageLoss | StatusKind::Error => None, |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | pub fn start( |
| 112 | store: Arc<Store>, |
| 113 | transport: Arc<dyn Transport>, |
| 114 | ringable: bool, |
| 115 | activity: watch::Receiver<bool>, |
| 116 | ) -> mpsc::UnboundedReceiver<BackendEvent> { |
| 117 | let (sender, receiver) = mpsc::unbounded_channel(); |
| 118 | crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender)); |
| 119 | receiver |
| 120 | } |
| 121 | |
| 122 | async fn supervise( |
| 123 | store: Arc<Store>, |
| 124 | transport: Arc<dyn Transport>, |
| 125 | ringable: bool, |
| 126 | activity: watch::Receiver<bool>, |
| 127 | events: EventSender, |
| 128 | ) { |
| 129 | let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting)); |
| 130 | let session = loop { |
| 131 | match Session::with_transport(transport.clone(), SessionConfig::default()).await { |
| 132 | Ok(session) => break session, |
| 133 | Err(error) => { |
| 134 | let _ = events.send(BackendEvent::Connection(classify_session_error(&error))); |
| 135 | tokio::time::sleep(CONNECT_RETRY).await; |
| 136 | } |
| 137 | } |
| 138 | }; |
| 139 | let build = || { |
| 140 | SyncEngine::new(Graph::new(session.clone()), store.clone()) |
| 141 | .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session))) |
| 142 | }; |
| 143 | let engine = image_directory() |
| 144 | .and_then(|directory| { |
| 145 | build() |
| 146 | .with_image_dir(&directory, IMAGE_CACHE_MAX_BYTES) |
| 147 | .ok() |
| 148 | }) |
| 149 | .unwrap_or_else(build); |
| 150 | let engine = Arc::new(engine); |
| 151 | let _ = events.send(BackendEvent::Engine(engine.clone())); |
| 152 | let ring_events = events.clone(); |
| 153 | let launcher = CallLauncher::start(transport, ringable, move |event| { |
| 154 | let _ = ring_events.send(BackendEvent::Ring(event)); |
| 155 | }); |
| 156 | let _ = events.send(BackendEvent::Calls(launcher)); |
| 157 | tokio::spawn(forward_core_events(engine.clone(), events.clone())); |
| 158 | let (nudge, nudges) = mpsc::unbounded_channel(); |
| 159 | let resend = Arc::new(Notify::new()); |
| 160 | let link = presence_link::start(&session, activity.clone(), resend.clone()); |
| 161 | tokio::spawn(realtime_loop( |
| 162 | session.clone(), |
| 163 | engine.clone(), |
| 164 | events.clone(), |
| 165 | nudge, |
| 166 | activity, |
| 167 | resend, |
| 168 | link, |
| 169 | )); |
| 170 | tokio::spawn(calendar_loop(session.clone(), events.clone())); |
| 171 | tokio::spawn(pins_loop(session, events.clone())); |
| 172 | tokio::spawn(presence_resubscribe_loop(engine.clone())); |
| 173 | refresh_loop(engine, events, nudges).await; |
| 174 | } |
| 175 | |
| 176 | async fn forward_core_events(engine: Arc<Engine>, events: EventSender) { |
| 177 | let mut receiver = engine.subscribe(); |
| 178 | loop { |
| 179 | let event = match receiver.recv().await { |
| 180 | Ok(event) => event, |
| 181 | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => CoreEvent::SidebarChanged, |
| 182 | Err(tokio::sync::broadcast::error::RecvError::Closed) => return, |
| 183 | }; |
| 184 | if events.send(BackendEvent::Core(event)).is_err() { |
| 185 | return; |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | async fn refresh_loop( |
| 191 | engine: Arc<Engine>, |
| 192 | events: EventSender, |
| 193 | mut nudges: mpsc::UnboundedReceiver<()>, |
| 194 | ) { |
| 195 | let mut interval = tokio::time::interval(REFRESH_INTERVAL); |
| 196 | loop { |
| 197 | tokio::select! { |
| 198 | _ = interval.tick() => {} |
| 199 | nudge = nudges.recv() => { |
| 200 | if nudge.is_none() { |
| 201 | return; |
| 202 | } |
| 203 | tokio::time::sleep(REFRESH_SETTLE).await; |
| 204 | while nudges.try_recv().is_ok() {} |
| 205 | } |
| 206 | } |
| 207 | match engine.refresh_sidebar().await { |
| 208 | Ok(_) => { |
| 209 | if let Err(error) = engine.refresh_folders().await { |
| 210 | crate::diagnostics::record(format!( |
| 211 | "sync: chat folders and channel layout not refreshed: {error}" |
| 212 | )); |
| 213 | } |
| 214 | let _ = events.send(BackendEvent::Connection(ConnectionState::Online)); |
| 215 | let _ = events.send(BackendEvent::Synced(Utc::now())); |
| 216 | } |
| 217 | Err(error) => { |
| 218 | let _ = events.send(BackendEvent::Connection(classify_core_error(&error))); |
| 219 | tokio::time::sleep(CONNECT_RETRY).await; |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | async fn realtime_loop( |
| 226 | session: Session, |
| 227 | engine: Arc<Engine>, |
| 228 | events: EventSender, |
| 229 | nudge: mpsc::UnboundedSender<()>, |
| 230 | mut activity: watch::Receiver<bool>, |
| 231 | resend: Arc<Notify>, |
| 232 | link: mpsc::UnboundedSender<LinkSignal>, |
| 233 | ) { |
| 234 | loop { |
| 235 | let _ = events.send(BackendEvent::Live(LiveState::Connecting)); |
| 236 | let config = RealtimeConfig { |
| 237 | initially_active: *activity.borrow(), |
| 238 | ..RealtimeConfig::default() |
| 239 | }; |
| 240 | match Realtime::start_with(&session, config).await { |
| 241 | Ok(mut realtime) => { |
| 242 | loop { |
| 243 | let event = tokio::select! { |
| 244 | event = realtime.recv() => event, |
| 245 | Ok(()) = activity.changed() => { |
| 246 | realtime.set_activity(*activity.borrow_and_update()); |
| 247 | continue; |
| 248 | } |
| 249 | _ = resend.notified() => { |
| 250 | realtime.resend_activity(); |
| 251 | continue; |
| 252 | } |
| 253 | }; |
| 254 | let Some(event) = event else { break }; |
| 255 | match event { |
| 256 | RealtimeEvent::Message(message) => { |
| 257 | let _ = events.send(BackendEvent::Live(LiveState::Live)); |
| 258 | if let Some(conversation_id) = thread_signal(&message) { |
| 259 | let _ = events.send(BackendEvent::ThreadChanged(conversation_id)); |
| 260 | } |
| 261 | let receipt_engine = engine.clone(); |
| 262 | let receipt_event = message.clone(); |
| 263 | engine.handle_pin_event(&message); |
| 264 | tokio::spawn(async move { |
| 265 | receipt_engine.handle_receipt_event(&receipt_event).await |
| 266 | }); |
| 267 | tokio::spawn(handle_message_event( |
| 268 | engine.clone(), |
| 269 | nudge.clone(), |
| 270 | message, |
| 271 | )); |
| 272 | } |
| 273 | RealtimeEvent::Typing(typing) => { |
| 274 | let _ = events.send(BackendEvent::Typing(typing)); |
| 275 | } |
| 276 | RealtimeEvent::Status(status) => { |
| 277 | let _ = events.send(BackendEvent::Live(live_state_for(status.kind))); |
| 278 | if let Some(signal) = link_signal_for(status.kind) { |
| 279 | let _ = link.send(signal); |
| 280 | } |
| 281 | let receipt_engine = engine.clone(); |
| 282 | let receipt_status = status.clone(); |
| 283 | tokio::spawn(async move { |
| 284 | receipt_engine.handle_receipt_status(&receipt_status).await |
| 285 | }); |
| 286 | } |
| 287 | RealtimeEvent::Presence(updates) => { |
| 288 | engine.apply_presence(&updates); |
| 289 | if engine.concerns_me(&updates) { |
| 290 | let engine = engine.clone(); |
| 291 | tokio::spawn(async move { engine.refresh_own_status().await }); |
| 292 | } |
| 293 | } |
| 294 | RealtimeEvent::Endpoint(endpoint) => { |
| 295 | let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone())); |
| 296 | let engine = engine.clone(); |
| 297 | tokio::spawn(async move { engine.presence_endpoint(endpoint).await }); |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | let _ = events.send(BackendEvent::Live(LiveState::Reconnecting)); |
| 302 | let _ = link.send(LinkSignal::Disconnected); |
| 303 | } |
| 304 | Err(_) => { |
| 305 | let _ = events.send(BackendEvent::Live(LiveState::Failed)); |
| 306 | let _ = link.send(LinkSignal::Disconnected); |
| 307 | } |
| 308 | } |
| 309 | tokio::time::sleep(REALTIME_RETRY).await; |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | async fn presence_resubscribe_loop(engine: Arc<Engine>) { |
| 314 | let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE); |
| 315 | interval.tick().await; |
| 316 | loop { |
| 317 | interval.tick().await; |
| 318 | let _ = engine.resubscribe_presence().await; |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message). |
| 323 | pub fn thread_signal(event: &MessageEvent) -> Option<String> { |
| 324 | match event.kind { |
| 325 | EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(), |
| 326 | _ => None, |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> { |
| 331 | let conversation_id = event.conversation_id.clone()?; |
| 332 | match event.kind { |
| 333 | EventKind::MessageUpdate => Some(match event.message_id.clone() { |
| 334 | Some(message_id) => RefreshPlan::Message { |
| 335 | conversation_id, |
| 336 | message_id, |
| 337 | }, |
| 338 | None => RefreshPlan::Newer { conversation_id }, |
| 339 | }), |
| 340 | EventKind::NewMessage => Some(RefreshPlan::Newer { conversation_id }), |
| 341 | _ => None, |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 346 | pub enum RefreshPlan { |
| 347 | Newer { |
| 348 | conversation_id: String, |
| 349 | }, |
| 350 | Message { |
| 351 | conversation_id: String, |
| 352 | message_id: String, |
| 353 | }, |
| 354 | } |
| 355 | |
| 356 | async fn handle_message_event( |
| 357 | engine: Arc<Engine>, |
| 358 | nudge: mpsc::UnboundedSender<()>, |
| 359 | event: MessageEvent, |
| 360 | ) { |
| 361 | let Some(plan) = refresh_plan(&event) else { |
| 362 | return; |
| 363 | }; |
| 364 | let outcome = match &plan { |
| 365 | RefreshPlan::Newer { conversation_id } => { |
| 366 | engine.fetch_newer(conversation_id).await.map(|_| ()) |
| 367 | } |
| 368 | RefreshPlan::Message { |
| 369 | conversation_id, |
| 370 | message_id, |
| 371 | } => engine |
| 372 | .refresh_message(conversation_id, message_id) |
| 373 | .await |
| 374 | .map(|_| ()), |
| 375 | }; |
| 376 | let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_))); |
| 377 | if unknown || event.kind == EventKind::NewMessage { |
| 378 | let _ = nudge.send(()); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | async fn calendar_loop(session: Session, events: EventSender) { |
| 383 | let calendar = Calendar::new(&session); |
| 384 | let (nudge, mut nudges) = mpsc::unbounded_channel(); |
| 385 | let _ = events.send(BackendEvent::CalendarNudge(nudge)); |
| 386 | let mut interval = tokio::time::interval(CALENDAR_INTERVAL); |
| 387 | let mut last_fetch: Option<tokio::time::Instant> = None; |
| 388 | let mut deferred_fetch: Option<tokio::time::Instant> = None; |
| 389 | loop { |
| 390 | tokio::select! { |
| 391 | _ = interval.tick() => {} |
| 392 | _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {} |
| 393 | nudge = nudges.recv() => { |
| 394 | if nudge.is_none() { |
| 395 | return; |
| 396 | } |
| 397 | while nudges.try_recv().is_ok() {} |
| 398 | if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) { |
| 399 | deferred_fetch = Some(fetched + CALENDAR_MIN_GAP); |
| 400 | continue; |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | deferred_fetch = None; |
| 405 | last_fetch = Some(tokio::time::Instant::now()); |
| 406 | let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix()); |
| 407 | match calendar.calendar_view(start, end).await { |
| 408 | Ok(fetched) => { |
| 409 | if events.send(BackendEvent::Calendar(fetched)).is_err() { |
| 410 | return; |
| 411 | } |
| 412 | } |
| 413 | Err(error) => crate::diagnostics::record(format!("calls: calendar not loaded: {}", shorten(&error.to_string()))), |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | async fn pins_loop(session: Session, events: EventSender) { |
| 419 | let pins = Pins::new(&session); |
| 420 | let mut chat_ids: Vec<String> = Vec::new(); |
| 421 | let mut channel_ids: Vec<String> = Vec::new(); |
| 422 | let mut interval = tokio::time::interval(PINS_INTERVAL); |
| 423 | loop { |
| 424 | interval.tick().await; |
| 425 | if let Ok(pinned) = pins.pinned_chats().await { |
| 426 | chat_ids = pinned.chat_ids; |
| 427 | } |
| 428 | if let Ok(pinned) = pins.pinned_channels().await { |
| 429 | channel_ids = pinned.channel_ids; |
| 430 | } |
| 431 | let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect(); |
| 432 | if events.send(BackendEvent::Favorites(combined)).is_err() { |
| 433 | return; |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | #[cfg(test)] |
| 439 | mod tests { |
| 440 | use super::*; |
| 441 | |
| 442 | fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent { |
| 443 | MessageEvent { |
| 444 | resource_type: "x".into(), |
| 445 | kind, |
| 446 | conversation_id: conversation.map(str::to_owned), |
| 447 | message_id: message.map(str::to_owned), |
| 448 | received_at: Utc::now(), |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | #[test] |
| 453 | fn new_message_fetches_newer() { |
| 454 | assert_eq!( |
| 455 | refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))), |
| 456 | Some(RefreshPlan::Newer { |
| 457 | conversation_id: "c".into() |
| 458 | }) |
| 459 | ); |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn update_refreshes_one_message() { |
| 464 | assert_eq!( |
| 465 | refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))), |
| 466 | Some(RefreshPlan::Message { |
| 467 | conversation_id: "c".into(), |
| 468 | message_id: "m".into() |
| 469 | }) |
| 470 | ); |
| 471 | assert_eq!( |
| 472 | refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)), |
| 473 | Some(RefreshPlan::Newer { |
| 474 | conversation_id: "c".into() |
| 475 | }) |
| 476 | ); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn thread_updates_and_new_messages_signal_a_possible_meeting_change() { |
| 481 | assert_eq!( |
| 482 | thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(), |
| 483 | Some("c") |
| 484 | ); |
| 485 | assert_eq!( |
| 486 | thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(), |
| 487 | Some("c") |
| 488 | ); |
| 489 | assert_eq!(thread_signal(&event(EventKind::Typing, Some("c"), None)), None); |
| 490 | assert_eq!(thread_signal(&event(EventKind::ThreadUpdate, None, None)), None); |
| 491 | } |
| 492 | |
| 493 | #[test] |
| 494 | fn typing_and_missing_conversation_are_ignored() { |
| 495 | assert_eq!( |
| 496 | refresh_plan(&event(EventKind::Typing, Some("c"), None)), |
| 497 | None |
| 498 | ); |
| 499 | assert_eq!( |
| 500 | refresh_plan(&event(EventKind::NewMessage, None, None)), |
| 501 | None |
| 502 | ); |
| 503 | } |
| 504 | |
| 505 | #[test] |
| 506 | fn session_errors_map_to_states() { |
| 507 | assert_eq!( |
| 508 | classify_session_error(&session::Error::NoAppTab), |
| 509 | ConnectionState::NoAppTab |
| 510 | ); |
| 511 | assert_eq!( |
| 512 | classify_session_error(&session::Error::LoginRequired("x".into())), |
| 513 | ConnectionState::LoginRequired |
| 514 | ); |
| 515 | assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live); |
| 516 | } |
| 517 | |
| 518 | #[test] |
| 519 | fn only_connect_and_disconnect_move_the_link() { |
| 520 | assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected)); |
| 521 | assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected)); |
| 522 | assert_eq!(link_signal_for(StatusKind::MessageLoss), None); |
| 523 | assert_eq!(link_signal_for(StatusKind::Error), None); |
| 524 | } |
| 525 | } |