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