| 1 | use std::sync::Arc; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind}; |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use graph::Graph; |
| 7 | use session::{Session, SessionConfig, Transport}; |
| 8 | use store::Store; |
| 9 | use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine}; |
| 10 | use tokio::sync::mpsc; |
| 11 | |
| 12 | pub type Engine = SyncEngine<Graph>; |
| 13 | |
| 14 | const CONNECT_RETRY: Duration = Duration::from_secs(8); |
| 15 | const REFRESH_INTERVAL: Duration = Duration::from_secs(120); |
| 16 | const REFRESH_SETTLE: Duration = Duration::from_secs(2); |
| 17 | const PINS_INTERVAL: Duration = Duration::from_secs(90); |
| 18 | const REALTIME_RETRY: Duration = Duration::from_secs(15); |
| 19 | const MAX_ERROR_CHARS: usize = 120; |
| 20 | const IMAGE_DIRECTORY: &str = "images"; |
| 21 | const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024; |
| 22 | |
| 23 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 24 | pub enum ConnectionState { |
| 25 | Connecting, |
| 26 | Online, |
| 27 | NoBrowser, |
| 28 | NoAppTab, |
| 29 | LoginRequired, |
| 30 | Failed(String), |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum LiveState { |
| 35 | Off, |
| 36 | Connecting, |
| 37 | Live, |
| 38 | Reconnecting, |
| 39 | MessageLoss, |
| 40 | Failed, |
| 41 | } |
| 42 | |
| 43 | pub enum BackendEvent { |
| 44 | Connection(ConnectionState), |
| 45 | Engine(Arc<Engine>), |
| 46 | Core(CoreEvent), |
| 47 | Live(LiveState), |
| 48 | Favorites(Vec<String>), |
| 49 | Synced(DateTime<Utc>), |
| 50 | } |
| 51 | |
| 52 | type EventSender = mpsc::UnboundedSender<BackendEvent>; |
| 53 | |
| 54 | pub fn classify_session_error(error: &session::Error) -> ConnectionState { |
| 55 | match error { |
| 56 | session::Error::NoBrowser { .. } => ConnectionState::NoBrowser, |
| 57 | session::Error::NoAppTab => ConnectionState::NoAppTab, |
| 58 | session::Error::LoginRequired(_) | session::Error::NoFreshToken { .. } => { |
| 59 | ConnectionState::LoginRequired |
| 60 | } |
| 61 | other => ConnectionState::Failed(shorten(&other.to_string())), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | pub fn classify_core_error(error: &teams_core::Error) -> ConnectionState { |
| 66 | match error { |
| 67 | teams_core::Error::Graph(graph::Error::Session(inner)) => classify_session_error(inner), |
| 68 | other => ConnectionState::Failed(shorten(&other.to_string())), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn image_directory() -> Option<std::path::PathBuf> { |
| 73 | directories::ProjectDirs::from("", "", store::DATA_DIR_NAME) |
| 74 | .map(|directories| directories.data_local_dir().join(IMAGE_DIRECTORY)) |
| 75 | } |
| 76 | |
| 77 | fn shorten(text: &str) -> String { |
| 78 | text.chars().take(MAX_ERROR_CHARS).collect() |
| 79 | } |
| 80 | |
| 81 | pub fn live_state_for(kind: StatusKind) -> LiveState { |
| 82 | match kind { |
| 83 | StatusKind::Connected => LiveState::Live, |
| 84 | StatusKind::Disconnected => LiveState::Reconnecting, |
| 85 | StatusKind::MessageLoss => LiveState::MessageLoss, |
| 86 | StatusKind::Error => LiveState::Failed, |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | pub fn start(store: Arc<Store>, transport: Arc<dyn Transport>) -> mpsc::UnboundedReceiver<BackendEvent> { |
| 91 | let (sender, receiver) = mpsc::unbounded_channel(); |
| 92 | crate::runtime::handle().spawn(supervise(store, transport, sender)); |
| 93 | receiver |
| 94 | } |
| 95 | |
| 96 | async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: EventSender) { |
| 97 | let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting)); |
| 98 | let session = loop { |
| 99 | match Session::with_transport(transport.clone(), SessionConfig::default()).await { |
| 100 | Ok(session) => break session, |
| 101 | Err(error) => { |
| 102 | let _ = events.send(BackendEvent::Connection(classify_session_error(&error))); |
| 103 | tokio::time::sleep(CONNECT_RETRY).await; |
| 104 | } |
| 105 | } |
| 106 | }; |
| 107 | let build = || { |
| 108 | SyncEngine::new(Graph::new(session.clone()), store.clone()) |
| 109 | .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session))) |
| 110 | }; |
| 111 | let engine = image_directory() |
| 112 | .and_then(|directory| { |
| 113 | build() |
| 114 | .with_image_dir(&directory, IMAGE_CACHE_MAX_BYTES) |
| 115 | .ok() |
| 116 | }) |
| 117 | .unwrap_or_else(build); |
| 118 | let engine = Arc::new(engine); |
| 119 | let _ = events.send(BackendEvent::Engine(engine.clone())); |
| 120 | tokio::spawn(forward_core_events(engine.clone(), events.clone())); |
| 121 | let (nudge, nudges) = mpsc::unbounded_channel(); |
| 122 | tokio::spawn(realtime_loop( |
| 123 | session.clone(), |
| 124 | engine.clone(), |
| 125 | events.clone(), |
| 126 | nudge, |
| 127 | )); |
| 128 | tokio::spawn(pins_loop(session, events.clone())); |
| 129 | refresh_loop(engine, events, nudges).await; |
| 130 | } |
| 131 | |
| 132 | async fn forward_core_events(engine: Arc<Engine>, events: EventSender) { |
| 133 | let mut receiver = engine.subscribe(); |
| 134 | loop { |
| 135 | let event = match receiver.recv().await { |
| 136 | Ok(event) => event, |
| 137 | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => CoreEvent::SidebarChanged, |
| 138 | Err(tokio::sync::broadcast::error::RecvError::Closed) => return, |
| 139 | }; |
| 140 | if events.send(BackendEvent::Core(event)).is_err() { |
| 141 | return; |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | async fn refresh_loop( |
| 147 | engine: Arc<Engine>, |
| 148 | events: EventSender, |
| 149 | mut nudges: mpsc::UnboundedReceiver<()>, |
| 150 | ) { |
| 151 | let mut interval = tokio::time::interval(REFRESH_INTERVAL); |
| 152 | loop { |
| 153 | tokio::select! { |
| 154 | _ = interval.tick() => {} |
| 155 | nudge = nudges.recv() => { |
| 156 | if nudge.is_none() { |
| 157 | return; |
| 158 | } |
| 159 | tokio::time::sleep(REFRESH_SETTLE).await; |
| 160 | while nudges.try_recv().is_ok() {} |
| 161 | } |
| 162 | } |
| 163 | match engine.refresh_sidebar().await { |
| 164 | Ok(_) => { |
| 165 | let _ = engine.refresh_folders().await; |
| 166 | let _ = events.send(BackendEvent::Connection(ConnectionState::Online)); |
| 167 | let _ = events.send(BackendEvent::Synced(Utc::now())); |
| 168 | } |
| 169 | Err(error) => { |
| 170 | let _ = events.send(BackendEvent::Connection(classify_core_error(&error))); |
| 171 | tokio::time::sleep(CONNECT_RETRY).await; |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | async fn realtime_loop( |
| 178 | session: Session, |
| 179 | engine: Arc<Engine>, |
| 180 | events: EventSender, |
| 181 | nudge: mpsc::UnboundedSender<()>, |
| 182 | ) { |
| 183 | loop { |
| 184 | let _ = events.send(BackendEvent::Live(LiveState::Connecting)); |
| 185 | match Realtime::start(&session).await { |
| 186 | Ok(mut realtime) => { |
| 187 | while let Some(event) = realtime.recv().await { |
| 188 | match event { |
| 189 | RealtimeEvent::Message(message) => { |
| 190 | let _ = events.send(BackendEvent::Live(LiveState::Live)); |
| 191 | let receipt_engine = engine.clone(); |
| 192 | let receipt_event = message.clone(); |
| 193 | tokio::spawn(async move { |
| 194 | receipt_engine.handle_receipt_event(&receipt_event).await |
| 195 | }); |
| 196 | tokio::spawn(handle_message_event( |
| 197 | engine.clone(), |
| 198 | nudge.clone(), |
| 199 | message, |
| 200 | )); |
| 201 | } |
| 202 | RealtimeEvent::Status(status) => { |
| 203 | let _ = events.send(BackendEvent::Live(live_state_for(status.kind))); |
| 204 | let receipt_engine = engine.clone(); |
| 205 | let receipt_status = status.clone(); |
| 206 | tokio::spawn(async move { |
| 207 | receipt_engine.handle_receipt_status(&receipt_status).await |
| 208 | }); |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | let _ = events.send(BackendEvent::Live(LiveState::Reconnecting)); |
| 213 | } |
| 214 | Err(_) => { |
| 215 | let _ = events.send(BackendEvent::Live(LiveState::Failed)); |
| 216 | } |
| 217 | } |
| 218 | tokio::time::sleep(REALTIME_RETRY).await; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> { |
| 223 | let conversation_id = event.conversation_id.clone()?; |
| 224 | match event.kind { |
| 225 | EventKind::MessageUpdate => Some(match event.message_id.clone() { |
| 226 | Some(message_id) => RefreshPlan::Message { |
| 227 | conversation_id, |
| 228 | message_id, |
| 229 | }, |
| 230 | None => RefreshPlan::Newer { conversation_id }, |
| 231 | }), |
| 232 | EventKind::NewMessage => Some(RefreshPlan::Newer { conversation_id }), |
| 233 | _ => None, |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 238 | pub enum RefreshPlan { |
| 239 | Newer { |
| 240 | conversation_id: String, |
| 241 | }, |
| 242 | Message { |
| 243 | conversation_id: String, |
| 244 | message_id: String, |
| 245 | }, |
| 246 | } |
| 247 | |
| 248 | async fn handle_message_event( |
| 249 | engine: Arc<Engine>, |
| 250 | nudge: mpsc::UnboundedSender<()>, |
| 251 | event: MessageEvent, |
| 252 | ) { |
| 253 | let Some(plan) = refresh_plan(&event) else { |
| 254 | return; |
| 255 | }; |
| 256 | let outcome = match &plan { |
| 257 | RefreshPlan::Newer { conversation_id } => { |
| 258 | engine.fetch_newer(conversation_id).await.map(|_| ()) |
| 259 | } |
| 260 | RefreshPlan::Message { |
| 261 | conversation_id, |
| 262 | message_id, |
| 263 | } => engine |
| 264 | .refresh_message(conversation_id, message_id) |
| 265 | .await |
| 266 | .map(|_| ()), |
| 267 | }; |
| 268 | let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_))); |
| 269 | if unknown || event.kind == EventKind::NewMessage { |
| 270 | let _ = nudge.send(()); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | async fn pins_loop(session: Session, events: EventSender) { |
| 275 | let pins = Pins::new(&session); |
| 276 | let mut chat_ids: Vec<String> = Vec::new(); |
| 277 | let mut channel_ids: Vec<String> = Vec::new(); |
| 278 | let mut interval = tokio::time::interval(PINS_INTERVAL); |
| 279 | loop { |
| 280 | interval.tick().await; |
| 281 | if let Ok(pinned) = pins.pinned_chats().await { |
| 282 | chat_ids = pinned.chat_ids; |
| 283 | } |
| 284 | if let Ok(pinned) = pins.pinned_channels().await { |
| 285 | channel_ids = pinned.channel_ids; |
| 286 | } |
| 287 | let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect(); |
| 288 | if events.send(BackendEvent::Favorites(combined)).is_err() { |
| 289 | return; |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | #[cfg(test)] |
| 295 | mod tests { |
| 296 | use super::*; |
| 297 | |
| 298 | fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent { |
| 299 | MessageEvent { |
| 300 | resource_type: "x".into(), |
| 301 | kind, |
| 302 | conversation_id: conversation.map(str::to_owned), |
| 303 | message_id: message.map(str::to_owned), |
| 304 | received_at: Utc::now(), |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn new_message_fetches_newer() { |
| 310 | assert_eq!( |
| 311 | refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))), |
| 312 | Some(RefreshPlan::Newer { |
| 313 | conversation_id: "c".into() |
| 314 | }) |
| 315 | ); |
| 316 | } |
| 317 | |
| 318 | #[test] |
| 319 | fn update_refreshes_one_message() { |
| 320 | assert_eq!( |
| 321 | refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))), |
| 322 | Some(RefreshPlan::Message { |
| 323 | conversation_id: "c".into(), |
| 324 | message_id: "m".into() |
| 325 | }) |
| 326 | ); |
| 327 | assert_eq!( |
| 328 | refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)), |
| 329 | Some(RefreshPlan::Newer { |
| 330 | conversation_id: "c".into() |
| 331 | }) |
| 332 | ); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn typing_and_missing_conversation_are_ignored() { |
| 337 | assert_eq!( |
| 338 | refresh_plan(&event(EventKind::Typing, Some("c"), None)), |
| 339 | None |
| 340 | ); |
| 341 | assert_eq!( |
| 342 | refresh_plan(&event(EventKind::NewMessage, None, None)), |
| 343 | None |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn session_errors_map_to_states() { |
| 349 | assert_eq!( |
| 350 | classify_session_error(&session::Error::NoAppTab), |
| 351 | ConnectionState::NoAppTab |
| 352 | ); |
| 353 | assert_eq!( |
| 354 | classify_session_error(&session::Error::LoginRequired("x".into())), |
| 355 | ConnectionState::LoginRequired |
| 356 | ); |
| 357 | assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live); |
| 358 | } |
| 359 | } |