use std::sync::Arc; use std::time::Duration; use calling::EngineEvent; use chatsvc::{ Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent, }; use chrono::{DateTime, Local, Offset, Utc}; use graph::Graph; use session::{Session, SessionConfig, Transport}; use store::Store; use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine}; use tokio::sync::{Notify, mpsc, watch}; use crate::call::{CallLauncher, fetch_window}; use crate::presence_link::{self, LinkSignal}; pub type Engine = SyncEngine; const CONNECT_RETRY: Duration = Duration::from_secs(8); const REFRESH_INTERVAL: Duration = Duration::from_secs(120); const REFRESH_SETTLE: Duration = Duration::from_secs(2); const PINS_INTERVAL: Duration = Duration::from_secs(90); const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60); const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30); const REALTIME_RETRY: Duration = Duration::from_secs(15); const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [ Duration::from_secs(1), Duration::from_secs(3), Duration::from_secs(8), ]; const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60); const MAX_ERROR_CHARS: usize = 120; const IMAGE_DIRECTORY: &str = "images"; const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ConnectionState { Connecting, Online, NoBrowser, NoAppTab, LoginRequired, Failed(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LiveState { Off, Connecting, Live, Reconnecting, MessageLoss, Failed, } pub enum BackendEvent { Connection(ConnectionState), Engine(Arc), Calls(Arc), Calendar(Vec), CalendarNudge(mpsc::UnboundedSender<()>), Ring(EngineEvent), ThreadChanged(String), Core(CoreEvent), Live(LiveState), Typing(TypingEvent), Favorites(Vec), Synced(DateTime), } type EventSender = mpsc::UnboundedSender; pub fn classify_session_error(error: &session::Error) -> ConnectionState { match error { session::Error::NoBrowser { .. } => ConnectionState::NoBrowser, session::Error::NoAppTab => ConnectionState::NoAppTab, session::Error::LoginRequired(_) | session::Error::NoFreshToken { .. } => { ConnectionState::LoginRequired } other => ConnectionState::Failed(shorten(&other.to_string())), } } pub fn classify_core_error(error: &teams_core::Error) -> ConnectionState { match error { teams_core::Error::Graph(graph::Error::Session(inner)) => classify_session_error(inner), other => ConnectionState::Failed(shorten(&other.to_string())), } } fn image_directory() -> Option { directories::ProjectDirs::from("", "", store::DATA_DIR_NAME) .map(|directories| directories.data_local_dir().join(IMAGE_DIRECTORY)) } fn shorten(text: &str) -> String { text.chars().take(MAX_ERROR_CHARS).collect() } pub fn live_state_for(kind: StatusKind) -> LiveState { match kind { StatusKind::Connected => LiveState::Live, StatusKind::Disconnected => LiveState::Reconnecting, StatusKind::MessageLoss => LiveState::MessageLoss, StatusKind::Error => LiveState::Failed, } } fn link_signal_for(kind: StatusKind) -> Option { match kind { StatusKind::Connected => Some(LinkSignal::Connected), StatusKind::Disconnected => Some(LinkSignal::Disconnected), StatusKind::MessageLoss | StatusKind::Error => None, } } pub fn start( store: Arc, transport: Arc, ringable: bool, activity: watch::Receiver, ) -> mpsc::UnboundedReceiver { let (sender, receiver) = mpsc::unbounded_channel(); crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender)); receiver } async fn supervise( store: Arc, transport: Arc, ringable: bool, activity: watch::Receiver, events: EventSender, ) { let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting)); let session = loop { match Session::with_transport(transport.clone(), SessionConfig::default()).await { Ok(session) => break session, Err(error) => { let _ = events.send(BackendEvent::Connection(classify_session_error(&error))); tokio::time::sleep(CONNECT_RETRY).await; } } }; let build = || { SyncEngine::new(Graph::new(session.clone()), store.clone()) .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session))) }; let engine = image_directory() .and_then(|directory| { build() .with_image_dir(&directory, IMAGE_CACHE_MAX_BYTES) .ok() }) .unwrap_or_else(build); let engine = Arc::new(engine); let _ = events.send(BackendEvent::Engine(engine.clone())); let ring_events = events.clone(); let launcher = CallLauncher::start(transport, ringable, move |event| { let _ = ring_events.send(BackendEvent::Ring(event)); }); let _ = events.send(BackendEvent::Calls(launcher)); tokio::spawn(forward_core_events(engine.clone(), events.clone())); let (nudge, nudges) = mpsc::unbounded_channel(); let resend = Arc::new(Notify::new()); let link = presence_link::start(&session, activity.clone(), resend.clone()); tokio::spawn(realtime_loop( session.clone(), engine.clone(), events.clone(), nudge, activity, resend, link, )); tokio::spawn(calendar_loop(session.clone(), events.clone())); tokio::spawn(pins_loop(session, events.clone())); tokio::spawn(presence_resubscribe_loop(engine.clone())); refresh_loop(engine, events, nudges).await; } async fn forward_core_events(engine: Arc, events: EventSender) { let mut receiver = engine.subscribe(); loop { let event = match receiver.recv().await { Ok(event) => event, Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => CoreEvent::SidebarChanged, Err(tokio::sync::broadcast::error::RecvError::Closed) => return, }; if events.send(BackendEvent::Core(event)).is_err() { return; } } } async fn refresh_loop( engine: Arc, events: EventSender, mut nudges: mpsc::UnboundedReceiver<()>, ) { let mut interval = tokio::time::interval(REFRESH_INTERVAL); loop { tokio::select! { _ = interval.tick() => {} nudge = nudges.recv() => { if nudge.is_none() { return; } tokio::time::sleep(REFRESH_SETTLE).await; while nudges.try_recv().is_ok() {} } } match engine.refresh_sidebar().await { Ok(_) => { if let Err(error) = engine.refresh_folders().await { crate::diagnostics::record(format!( "sync: chat folders and channel layout not refreshed: {error}" )); } let _ = events.send(BackendEvent::Connection(ConnectionState::Online)); let _ = events.send(BackendEvent::Synced(Utc::now())); } Err(error) => { let _ = events.send(BackendEvent::Connection(classify_core_error(&error))); tokio::time::sleep(CONNECT_RETRY).await; } } } } async fn realtime_loop( session: Session, engine: Arc, events: EventSender, nudge: mpsc::UnboundedSender<()>, mut activity: watch::Receiver, resend: Arc, link: mpsc::UnboundedSender, ) { loop { let _ = events.send(BackendEvent::Live(LiveState::Connecting)); let config = RealtimeConfig { initially_active: *activity.borrow(), ..RealtimeConfig::default() }; match Realtime::start_with(&session, config).await { Ok(mut realtime) => { loop { let event = tokio::select! { event = realtime.recv() => event, Ok(()) = activity.changed() => { realtime.set_activity(*activity.borrow_and_update()); continue; } _ = resend.notified() => { realtime.resend_activity(); continue; } }; let Some(event) = event else { break }; match event { RealtimeEvent::Message(message) => { let _ = events.send(BackendEvent::Live(LiveState::Live)); if let Some(conversation_id) = thread_signal(&message) { let _ = events.send(BackendEvent::ThreadChanged(conversation_id)); } let receipt_engine = engine.clone(); let receipt_event = message.clone(); engine.handle_pin_event(&message); tokio::spawn(async move { receipt_engine.handle_receipt_event(&receipt_event).await }); tokio::spawn(handle_message_event( engine.clone(), nudge.clone(), message, )); } RealtimeEvent::Typing(typing) => { let _ = events.send(BackendEvent::Typing(typing)); } RealtimeEvent::Status(status) => { let _ = events.send(BackendEvent::Live(live_state_for(status.kind))); if let Some(signal) = link_signal_for(status.kind) { let _ = link.send(signal); } let receipt_engine = engine.clone(); let receipt_status = status.clone(); tokio::spawn(async move { receipt_engine.handle_receipt_status(&receipt_status).await }); } RealtimeEvent::Presence(updates) => { engine.apply_presence(&updates); if engine.concerns_me(&updates) { let engine = engine.clone(); tokio::spawn(async move { engine.refresh_own_status().await }); } } RealtimeEvent::Endpoint(endpoint) => { let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone())); let engine = engine.clone(); tokio::spawn(async move { engine.presence_endpoint(endpoint).await }); } } } let _ = events.send(BackendEvent::Live(LiveState::Reconnecting)); let _ = link.send(LinkSignal::Disconnected); } Err(_) => { let _ = events.send(BackendEvent::Live(LiveState::Failed)); let _ = link.send(LinkSignal::Disconnected); } } tokio::time::sleep(REALTIME_RETRY).await; } } async fn presence_resubscribe_loop(engine: Arc) { let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE); interval.tick().await; loop { interval.tick().await; let _ = engine.resubscribe_presence().await; } } /// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message). pub fn thread_signal(event: &MessageEvent) -> Option { match event.kind { EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(), _ => None, } } pub fn refresh_plan(event: &MessageEvent) -> Option { let conversation_id = event.conversation_id.clone()?; match event.kind { EventKind::MessageUpdate => Some(match event.message_id.clone() { Some(message_id) => RefreshPlan::Message { conversation_id, message_id, }, None => RefreshPlan::Newer { conversation_id }, }), EventKind::NewMessage => Some(match event.message_id.clone() { Some(message_id) => RefreshPlan::Arrival { conversation_id, message_id, }, None => RefreshPlan::Newer { conversation_id }, }), _ => None, } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum RefreshPlan { Newer { conversation_id: String, }, Arrival { conversation_id: String, message_id: String, }, Message { conversation_id: String, message_id: String, }, } async fn handle_message_event( engine: Arc, nudge: mpsc::UnboundedSender<()>, event: MessageEvent, ) { let Some(plan) = refresh_plan(&event) else { return; }; let outcome = match &plan { RefreshPlan::Newer { conversation_id } | RefreshPlan::Arrival { conversation_id, .. } => engine.fetch_newer(conversation_id).await.map(|_| ()), RefreshPlan::Message { conversation_id, message_id, } => engine .refresh_message(conversation_id, message_id) .await .map(|_| ()), }; let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_))); if unknown || event.kind == EventKind::NewMessage { let _ = nudge.send(()); } if let ( Ok(()), RefreshPlan::Arrival { conversation_id, message_id, }, ) = (outcome, &plan) { let _ = engine .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS) .await; } } async fn calendar_loop(session: Session, events: EventSender) { let calendar = Calendar::new(&session); let (nudge, mut nudges) = mpsc::unbounded_channel(); let _ = events.send(BackendEvent::CalendarNudge(nudge)); let mut interval = tokio::time::interval(CALENDAR_INTERVAL); let mut last_fetch: Option = None; let mut deferred_fetch: Option = None; loop { tokio::select! { _ = interval.tick() => {} _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {} nudge = nudges.recv() => { if nudge.is_none() { return; } while nudges.try_recv().is_ok() {} if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) { deferred_fetch = Some(fetched + CALENDAR_MIN_GAP); continue; } } } deferred_fetch = None; last_fetch = Some(tokio::time::Instant::now()); let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix()); match calendar.calendar_view(start, end).await { Ok(fetched) => { if events.send(BackendEvent::Calendar(fetched)).is_err() { return; } } Err(error) => crate::diagnostics::record(format!( "calls: calendar not loaded: {}", shorten(&error.to_string()) )), } } } async fn pins_loop(session: Session, events: EventSender) { let pins = Pins::new(&session); let mut chat_ids: Vec = Vec::new(); let mut channel_ids: Vec = Vec::new(); let mut interval = tokio::time::interval(PINS_INTERVAL); loop { interval.tick().await; if let Ok(pinned) = pins.pinned_chats().await { chat_ids = pinned.chat_ids; } if let Ok(pinned) = pins.pinned_channels().await { channel_ids = pinned.channel_ids; } let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect(); if events.send(BackendEvent::Favorites(combined)).is_err() { return; } } } #[cfg(test)] mod tests { use super::*; fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent { MessageEvent { resource_type: "x".into(), kind, conversation_id: conversation.map(str::to_owned), message_id: message.map(str::to_owned), received_at: Utc::now(), } } #[test] fn new_message_waits_for_its_arrival() { assert_eq!( refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))), Some(RefreshPlan::Arrival { conversation_id: "c".into(), message_id: "m".into() }) ); assert_eq!( refresh_plan(&event(EventKind::NewMessage, Some("c"), None)), Some(RefreshPlan::Newer { conversation_id: "c".into() }) ); } #[test] fn update_refreshes_one_message() { assert_eq!( refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))), Some(RefreshPlan::Message { conversation_id: "c".into(), message_id: "m".into() }) ); assert_eq!( refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)), Some(RefreshPlan::Newer { conversation_id: "c".into() }) ); } #[test] fn thread_updates_and_new_messages_signal_a_possible_meeting_change() { assert_eq!( thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(), Some("c") ); assert_eq!( thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(), Some("c") ); assert_eq!( thread_signal(&event(EventKind::Typing, Some("c"), None)), None ); assert_eq!( thread_signal(&event(EventKind::ThreadUpdate, None, None)), None ); } #[test] fn typing_and_missing_conversation_are_ignored() { assert_eq!( refresh_plan(&event(EventKind::Typing, Some("c"), None)), None ); assert_eq!( refresh_plan(&event(EventKind::NewMessage, None, None)), None ); } #[test] fn session_errors_map_to_states() { assert_eq!( classify_session_error(&session::Error::NoAppTab), ConnectionState::NoAppTab ); assert_eq!( classify_session_error(&session::Error::LoginRequired("x".into())), ConnectionState::LoginRequired ); assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live); } #[test] fn only_connect_and_disconnect_move_the_link() { assert_eq!( link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected) ); assert_eq!( link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected) ); assert_eq!(link_signal_for(StatusKind::MessageLoss), None); assert_eq!(link_signal_for(StatusKind::Error), None); } }