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