BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / backend.rs

backend.rs

backend.rs 28.6 KiB Download Raw
1use std::sync::Arc;
2use std::time::Duration;
3
4use calling::EngineEvent;
5use chatsvc::{
6 Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig,
7 RealtimeEvent, StatusKind, TypingEvent,
8};
9use chrono::{DateTime, Local, Offset, Utc};
10use graph::Graph;
11use session::{Session, SessionConfig, Transport};
12use store::Store;
13use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
14use tokio::sync::{Notify, mpsc, watch};
15
16use crate::browser_sign_in::BrowserSignInState;
17use crate::call::{CallLauncher, fetch_window};
18use crate::presence_link::{self, LinkSignal};
19
20pub type Engine = SyncEngine<Graph>;
21
22const FORWARD_HEAL_PAUSE: Duration = Duration::from_secs(2);
23const CONNECT_RETRY: Duration = Duration::from_secs(8);
24const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
25const REFRESH_SETTLE: Duration = Duration::from_secs(2);
26const PINS_INTERVAL: Duration = Duration::from_secs(90);
27const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
28const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
29const ORG_LIST_ATTEMPTS: usize = 5;
30const REALTIME_RETRY: Duration = Duration::from_secs(15);
31const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [
32 Duration::from_secs(1),
33 Duration::from_secs(3),
34 Duration::from_secs(8),
35];
36const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
37const MAX_ERROR_CHARS: usize = 120;
38const IMAGE_DIRECTORY: &str = "images";
39const IMAGE_CACHE_MAX_BYTES: u64 = 200 * 1024 * 1024;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum ConnectionState {
43 Connecting,
44 Online,
45 NoBrowser,
46 NoAppTab,
47 LoginRequired,
48 Failed(String),
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum LiveState {
53 Off,
54 Connecting,
55 Live,
56 Reconnecting,
57 MessageLoss,
58 Failed,
59}
60
61pub enum BackendEvent {
62 Connection(ConnectionState),
63 BrowserSignIn(BrowserSignInState),
64 Engine(Arc<Engine>),
65 Calls(Arc<CallLauncher>),
66 Calendar(Vec<CalendarEvent>),
67 CalendarNudge(mpsc::UnboundedSender<()>),
68 Ring(EngineEvent),
69 ThreadChanged(String),
70 Core(CoreEvent),
71 Live(LiveState),
72 Typing(TypingEvent),
73 Favorites(Vec<String>),
74 Synced(DateTime<Utc>),
75 LiveRetry(Arc<Notify>),
76 Orgs(Vec<app_base::orgs::Org>),
77 OrgMessage(crate::org_watch::OrgMessage),
78}
79
80impl BackendEvent {
81 pub fn kind(&self) -> String {
82 match self {
83 BackendEvent::Connection(_) => "Connection".into(),
84 BackendEvent::BrowserSignIn(_) => "BrowserSignIn".into(),
85 BackendEvent::Engine(_) => "Engine".into(),
86 BackendEvent::Calls(_) => "Calls".into(),
87 BackendEvent::Calendar(_) => "Calendar".into(),
88 BackendEvent::CalendarNudge(_) => "CalendarNudge".into(),
89 BackendEvent::Ring(_) => "Ring".into(),
90 BackendEvent::ThreadChanged(_) => "ThreadChanged".into(),
91 BackendEvent::Core(event) => {
92 let debug = format!("{event:?}");
93 let name = debug.split(['{', '(', ' ']).next().unwrap_or_default();
94 format!("Core::{name}")
95 }
96 BackendEvent::Live(_) => "Live".into(),
97 BackendEvent::Typing(_) => "Typing".into(),
98 BackendEvent::Favorites(_) => "Favorites".into(),
99 BackendEvent::Synced(_) => "Synced".into(),
100 BackendEvent::LiveRetry(_) => "LiveRetry".into(),
101 BackendEvent::Orgs(_) => "Orgs".into(),
102 BackendEvent::OrgMessage(_) => "OrgMessage".into(),
103 }
104 }
105}
106
107type EventSender = mpsc::UnboundedSender<BackendEvent>;
108
109pub fn classify_session_error(error: &session::Error) -> ConnectionState {
110 match error {
111 session::Error::NoBrowser { .. } => ConnectionState::NoBrowser,
112 session::Error::NoAppTab => ConnectionState::NoAppTab,
113 session::Error::LoginRequired(_) | session::Error::NoFreshToken { .. } => {
114 ConnectionState::LoginRequired
115 }
116 other => ConnectionState::Failed(shorten(&other.to_string())),
117 }
118}
119
120pub fn classify_core_error(error: &teams_core::Error) -> ConnectionState {
121 match error {
122 teams_core::Error::Graph(graph::Error::Session(inner)) => classify_session_error(inner),
123 other => ConnectionState::Failed(shorten(&other.to_string())),
124 }
125}
126
127fn image_directory() -> Option<std::path::PathBuf> {
128 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
129 .map(|directories| directories.data_local_dir().join(IMAGE_DIRECTORY))
130}
131
132fn shorten(text: &str) -> String {
133 text.chars().take(MAX_ERROR_CHARS).collect()
134}
135
136pub fn live_state_for(kind: StatusKind) -> LiveState {
137 match kind {
138 StatusKind::Connected => LiveState::Live,
139 StatusKind::Disconnected => LiveState::Reconnecting,
140 StatusKind::MessageLoss => LiveState::MessageLoss,
141 StatusKind::Error => LiveState::Failed,
142 }
143}
144
145fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {
146 match kind {
147 StatusKind::Connected => Some(LinkSignal::Connected),
148 StatusKind::Disconnected => Some(LinkSignal::Disconnected),
149 StatusKind::MessageLoss | StatusKind::Error => None,
150 }
151}
152
153pub fn start(
154 store: Arc<Store>,
155 transport: Arc<dyn Transport>,
156 ringable: bool,
157 activity: watch::Receiver<bool>,
158 guest_tenant: Option<String>,
159) -> mpsc::UnboundedReceiver<BackendEvent> {
160 let (sender, receiver) = mpsc::unbounded_channel();
161 crate::runtime::handle().spawn(supervise(
162 store,
163 transport,
164 ringable,
165 activity,
166 guest_tenant,
167 sender,
168 ));
169 receiver
170}
171
172async fn supervise(
173 store: Arc<Store>,
174 transport: Arc<dyn Transport>,
175 ringable: bool,
176 activity: watch::Receiver<bool>,
177 guest_tenant: Option<String>,
178 events: EventSender,
179) {
180 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
181 let home = loop {
182 match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {
183 Ok(session) => break session,
184 Err(error) => {
185 let _ = events.send(BackendEvent::Connection(classify_session_error(&error)));
186 tokio::time::sleep(CONNECT_RETRY).await;
187 }
188 }
189 };
190 tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
191 tokio::spawn(msal_key_loop(home.clone()));
192 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
193 // Chat files of a guest org go to the home OneDrive: the guest tenant has none.
194 let (session, home_drive) = match &guest_tenant {
195 Some(tenant) => (home.in_tenant(tenant), Some(home.clone())),
196 None => (home.clone(), None),
197 };
198 let build = || {
199 let graph = Graph::new(session.clone());
200 let graph = match &home_drive {
201 Some(home) => graph.with_home_drive(home.clone()),
202 None => graph,
203 };
204 SyncEngine::new(graph, store.clone())
205 .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
206 };
207 let engine = image_directory()
208 .and_then(|directory| {
209 build()
210 .with_image_dir(&directory, IMAGE_CACHE_MAX_BYTES)
211 .ok()
212 })
213 .unwrap_or_else(build);
214 let engine = Arc::new(engine);
215 let _ = events.send(BackendEvent::Engine(engine.clone()));
216 let ring_events = events.clone();
217 let launcher = CallLauncher::start(transport, ringable, move |event| {
218 let _ = ring_events.send(BackendEvent::Ring(event));
219 });
220 let _ = events.send(BackendEvent::Calls(launcher));
221 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
222 let (nudge, nudges) = mpsc::unbounded_channel();
223 let resend = Arc::new(Notify::new());
224 let link = presence_link::start(&session, activity.clone(), resend.clone());
225 let live_retry = Arc::new(Notify::new());
226 let _ = events.send(BackendEvent::LiveRetry(live_retry.clone()));
227 tokio::spawn(realtime_loop(
228 session.clone(),
229 engine.clone(),
230 events.clone(),
231 nudge,
232 activity,
233 resend,
234 link,
235 live_retry,
236 ));
237 // A guest has no mailbox in the org it visits, so Outlook is read from the home tenant.
238 tokio::spawn(calendar_loop(home, store.clone(), events.clone()));
239 tokio::spawn(pins_loop(session, events.clone()));
240 tokio::spawn(presence_resubscribe_loop(engine.clone()));
241 refresh_loop(engine, events, nudges).await;
242}
243
244/// Gives the MSAL cache key an expiry once the page is signed in, so the next start can read the
245/// token cache. WebView2 drops session cookies with the process just like Chromium does. One
246/// success is enough: the expiry is renewed on the next start, and repeated CDP calls would wake a
247/// parked WebView2.
248async fn msal_key_loop(session: Session) {
249 if !session.can_persist_msal_key() {
250 return;
251 }
252 let mut wait = Duration::from_secs(5);
253 loop {
254 tokio::time::sleep(wait).await;
255 let outcome =
256 tokio::time::timeout(Duration::from_secs(10), session.persist_msal_key()).await;
257 match outcome {
258 Ok(Ok(true)) => {
259 crate::diagnostics::record("msal: key cookie persisted");
260 return;
261 }
262 Ok(Ok(false)) => {
263 wait = (wait * 2).min(Duration::from_secs(300));
264 }
265 Ok(Err(error)) => {
266 crate::diagnostics::record(format!("msal: key cookie not persisted: {error}"));
267 wait = (wait * 2).min(Duration::from_secs(300));
268 }
269 Err(_) => {
270 crate::diagnostics::record("msal: key cookie persistence timed out");
271 wait = (wait * 2).min(Duration::from_secs(300));
272 }
273 }
274 }
275}
276
277/// Fetches the account's organizations once per start, retried a few times while sign-in settles,
278/// and keeps every org that is not open live for notifications.
279async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {
280 for _ in 0..ORG_LIST_ATTEMPTS {
281 match chatsvc::list_tenants(&home).await {
282 Ok(tenants) => {
283 let mut orgs = Vec::with_capacity(tenants.len());
284 for tenant in tenants {
285 let org = app_base::orgs::Org {
286 id: tenant.id,
287 name: tenant.name,
288 guest: tenant.guest,
289 };
290 let open = match &open_guest {
291 Some(open) => *open == org.id,
292 None => !org.guest,
293 };
294 if !open {
295 let session = if org.guest {
296 home.in_tenant(&org.id)
297 } else {
298 home.clone()
299 };
300 tokio::spawn(crate::org_watch::watch(
301 session,
302 org.clone(),
303 tenant.user_id,
304 events.clone(),
305 ));
306 }
307 orgs.push(org);
308 }
309 let _ = events.send(BackendEvent::Orgs(orgs));
310 return;
311 }
312 Err(error) => {
313 crate::diagnostics::record(format!("orgs: tenant list not loaded: {error}"));
314 tokio::time::sleep(CONNECT_RETRY).await;
315 }
316 }
317 }
318}
319
320async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {
321 let mut receiver = engine.subscribe();
322 loop {
323 let event = match receiver.recv().await {
324 Ok(event) => event,
325 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => CoreEvent::SidebarChanged,
326 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
327 };
328 if events.send(BackendEvent::Core(event)).is_err() {
329 return;
330 }
331 }
332}
333
334async fn refresh_loop(
335 engine: Arc<Engine>,
336 events: EventSender,
337 mut nudges: mpsc::UnboundedReceiver<()>,
338) {
339 let mut interval = tokio::time::interval(REFRESH_INTERVAL);
340 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
341 let mut forwards_healing = false;
342 loop {
343 tokio::select! {
344 _ = interval.tick() => {}
345 nudge = nudges.recv() => {
346 if nudge.is_none() {
347 return;
348 }
349 tokio::time::sleep(REFRESH_SETTLE).await;
350 while nudges.try_recv().is_ok() {}
351 }
352 }
353 match engine.refresh_sidebar().await {
354 Ok(_) => {
355 if !std::mem::replace(&mut forwards_healing, true) {
356 let engine = engine.clone();
357 tokio::spawn(async move { engine.heal_all_forwards(FORWARD_HEAL_PAUSE).await });
358 }
359 if let Err(error) = engine.refresh_folders().await {
360 crate::diagnostics::record(format!(
361 "sync: chat folders and channel layout not refreshed: {error}"
362 ));
363 }
364 let _ = events.send(BackendEvent::Connection(ConnectionState::Online));
365 let _ = events.send(BackendEvent::Synced(Utc::now()));
366 }
367 Err(error) => {
368 let _ = events.send(BackendEvent::Connection(classify_core_error(&error)));
369 tokio::time::sleep(CONNECT_RETRY).await;
370 }
371 }
372 }
373}
374
375async fn realtime_loop(
376 session: Session,
377 engine: Arc<Engine>,
378 events: EventSender,
379 nudge: mpsc::UnboundedSender<()>,
380 mut activity: watch::Receiver<bool>,
381 resend: Arc<Notify>,
382 link: mpsc::UnboundedSender<LinkSignal>,
383 live_retry: Arc<Notify>,
384) {
385 loop {
386 let _ = events.send(BackendEvent::Live(LiveState::Connecting));
387 let config = RealtimeConfig {
388 initially_active: *activity.borrow(),
389 retry: Some(live_retry.clone()),
390 ..RealtimeConfig::default()
391 };
392 match Realtime::start_with(&session, config).await {
393 Ok(mut realtime) => {
394 loop {
395 let event = tokio::select! {
396 event = realtime.recv() => event,
397 Ok(()) = activity.changed() => {
398 realtime.set_activity(*activity.borrow_and_update());
399 continue;
400 }
401 _ = resend.notified() => {
402 realtime.resend_activity();
403 continue;
404 }
405 };
406 let Some(event) = event else { break };
407 match event {
408 RealtimeEvent::Message(message) => {
409 let _ = events.send(BackendEvent::Live(LiveState::Live));
410 if let Some(conversation_id) = thread_signal(&message) {
411 let _ = events.send(BackendEvent::ThreadChanged(conversation_id));
412 }
413 let receipt_engine = engine.clone();
414 let receipt_event = message.clone();
415 engine.handle_pin_event(&message);
416 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID)
417 {
418 let activity_engine = engine.clone();
419 tokio::spawn(
420 async move { activity_engine.refresh_activity().await },
421 );
422 }
423 tokio::spawn(async move {
424 receipt_engine.handle_receipt_event(&receipt_event).await
425 });
426 tokio::spawn(handle_message_event(
427 engine.clone(),
428 nudge.clone(),
429 message,
430 ));
431 }
432 RealtimeEvent::Typing(typing) => {
433 let _ = events.send(BackendEvent::Typing(typing));
434 }
435 RealtimeEvent::Status(status) => {
436 if status.kind != StatusKind::Connected {
437 crate::diagnostics::record(format!(
438 "live: {:?} {}",
439 status.kind, status.detail
440 ));
441 }
442 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
443 if let Some(signal) = link_signal_for(status.kind) {
444 let _ = link.send(signal);
445 }
446 let receipt_engine = engine.clone();
447 let receipt_status = status.clone();
448 tokio::spawn(async move {
449 receipt_engine.handle_receipt_status(&receipt_status).await
450 });
451 }
452 RealtimeEvent::Presence(updates) => {
453 engine.apply_presence(&updates);
454 if engine.concerns_me(&updates) {
455 let engine = engine.clone();
456 tokio::spawn(async move { engine.refresh_own_status().await });
457 }
458 }
459 RealtimeEvent::Endpoint(endpoint) => {
460 let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
461 let engine = engine.clone();
462 tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
463 }
464 }
465 }
466 let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
467 let _ = link.send(LinkSignal::Disconnected);
468 }
469 Err(error) => {
470 crate::diagnostics::record(format!("live: start failed: {error}"));
471 let _ = events.send(BackendEvent::Live(LiveState::Failed));
472 let _ = link.send(LinkSignal::Disconnected);
473 }
474 }
475 tokio::select! {
476 _ = tokio::time::sleep(REALTIME_RETRY) => {}
477 _ = live_retry.notified() => {}
478 }
479 }
480}
481
482async fn presence_resubscribe_loop(engine: Arc<Engine>) {
483 let mut interval = tokio::time::interval(PRESENCE_RESUBSCRIBE);
484 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
485 interval.tick().await;
486 loop {
487 interval.tick().await;
488 let _ = engine.resubscribe_presence().await;
489 }
490}
491
492/// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message).
493pub fn thread_signal(event: &MessageEvent) -> Option<String> {
494 match event.kind {
495 EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(),
496 _ => None,
497 }
498}
499
500pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
501 let conversation_id = event.conversation_id.clone()?;
502 match event.kind {
503 EventKind::MessageUpdate => Some(match event.message_id.clone() {
504 Some(message_id) => RefreshPlan::Message {
505 conversation_id,
506 message_id,
507 },
508 None => RefreshPlan::Newer { conversation_id },
509 }),
510 EventKind::NewMessage => Some(match event.message_id.clone() {
511 Some(message_id) => RefreshPlan::Arrival {
512 conversation_id,
513 message_id,
514 },
515 None => RefreshPlan::Newer { conversation_id },
516 }),
517 _ => None,
518 }
519}
520
521#[derive(Debug, Clone, PartialEq, Eq)]
522pub enum RefreshPlan {
523 Newer {
524 conversation_id: String,
525 },
526 Arrival {
527 conversation_id: String,
528 message_id: String,
529 },
530 Message {
531 conversation_id: String,
532 message_id: String,
533 },
534}
535
536async fn handle_message_event(
537 engine: Arc<Engine>,
538 nudge: mpsc::UnboundedSender<()>,
539 event: MessageEvent,
540) {
541 let Some(plan) = refresh_plan(&event) else {
542 return;
543 };
544 let outcome = match &plan {
545 RefreshPlan::Newer { conversation_id }
546 | RefreshPlan::Arrival {
547 conversation_id, ..
548 } => engine.fetch_newer(conversation_id).await.map(|_| ()),
549 RefreshPlan::Message {
550 conversation_id,
551 message_id,
552 } => engine
553 .refresh_message(conversation_id, message_id)
554 .await
555 .map(|_| ()),
556 };
557 let unknown = matches!(outcome, Err(teams_core::Error::UnknownConversation(_)));
558 if unknown || event.kind == EventKind::NewMessage {
559 let _ = nudge.send(());
560 }
561 if let (
562 Ok(()),
563 RefreshPlan::Arrival {
564 conversation_id,
565 message_id,
566 },
567 ) = (outcome, &plan)
568 {
569 let _ = engine
570 .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
571 .await;
572 }
573}
574
575async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender) {
576 let calendar = Calendar::new(&session);
577 let (nudge, mut nudges) = mpsc::unbounded_channel();
578 let _ = events.send(BackendEvent::CalendarNudge(nudge));
579 let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
580 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
581 let mut last_fetch: Option<tokio::time::Instant> = None;
582 let mut deferred_fetch: Option<tokio::time::Instant> = None;
583 loop {
584 tokio::select! {
585 _ = interval.tick() => {}
586 _ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {}
587 nudge = nudges.recv() => {
588 if nudge.is_none() {
589 return;
590 }
591 while nudges.try_recv().is_ok() {}
592 if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
593 deferred_fetch = Some(fetched + CALENDAR_MIN_GAP);
594 continue;
595 }
596 }
597 }
598 deferred_fetch = None;
599 last_fetch = Some(tokio::time::Instant::now());
600 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
601 let accounts = store::load_calendar_accounts(&store);
602 let mut fetched_accounts = accounts.clone();
603 let mut combined = Vec::new();
604 let mut outlook_failed = false;
605 if accounts.outlook_selected {
606 match calendar.calendar_view(start, end).await {
607 Ok(fetched) => combined.extend(fetched),
608 Err(error) => {
609 outlook_failed = true;
610 crate::diagnostics::record(format!(
611 "calls: outlook calendar not loaded: {}",
612 shorten(&error.to_string())
613 ));
614 }
615 }
616 }
617 match crate::google_calendar_sync::fetch_google_events(
618 &store,
619 &mut fetched_accounts,
620 start,
621 end,
622 )
623 .await
624 {
625 Ok((google_events, account_errors)) => {
626 // Only refreshed tokens: a calendar toggle made during the fetch stays.
627 let _ = store::merge_google_tokens(&store, &fetched_accounts);
628 combined.extend(google_events);
629 for message in account_errors {
630 crate::diagnostics::record(format!(
631 "calls: google account not loaded: {}",
632 shorten(&message)
633 ));
634 }
635 }
636 Err(error) => crate::diagnostics::record(format!(
637 "calls: google calendar not loaded: {}",
638 shorten(&error)
639 )),
640 }
641 if combined.is_empty() && outlook_failed && !accounts.has_google() {
642 continue;
643 }
644 let home = {
645 use store::CalendarProvider;
646 let source = match accounts.home.provider {
647 CalendarProvider::Outlook => chatsvc::CalendarSource::Outlook,
648 CalendarProvider::Google => chatsvc::CalendarSource::Google,
649 CalendarProvider::CalDav => chatsvc::CalendarSource::CalDav,
650 };
651 Some(chatsvc::HomeCalendar {
652 source,
653 account_id: accounts.home.account_id.as_str(),
654 calendar_id: accounts.home.calendar_id.as_str(),
655 })
656 };
657 let merged = chatsvc::merge_calendar_events(combined, home);
658 if events.send(BackendEvent::Calendar(merged)).is_err() {
659 return;
660 }
661 }
662}
663
664async fn pins_loop(session: Session, events: EventSender) {
665 let pins = Pins::new(&session);
666 let mut chat_ids: Vec<String> = Vec::new();
667 let mut channel_ids: Vec<String> = Vec::new();
668 let mut interval = tokio::time::interval(PINS_INTERVAL);
669 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
670 loop {
671 interval.tick().await;
672 if let Ok(pinned) = pins.pinned_chats().await {
673 chat_ids = pinned.chat_ids;
674 }
675 if let Ok(pinned) = pins.pinned_channels().await {
676 channel_ids = pinned.channel_ids;
677 }
678 let combined = chat_ids.iter().chain(channel_ids.iter()).cloned().collect();
679 if events.send(BackendEvent::Favorites(combined)).is_err() {
680 return;
681 }
682 }
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688
689 fn event(kind: EventKind, conversation: Option<&str>, message: Option<&str>) -> MessageEvent {
690 MessageEvent {
691 resource_type: "x".into(),
692 kind,
693 conversation_id: conversation.map(str::to_owned),
694 message_id: message.map(str::to_owned),
695 received_at: Utc::now(),
696 }
697 }
698
699 #[test]
700 fn new_message_waits_for_its_arrival() {
701 assert_eq!(
702 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
703 Some(RefreshPlan::Arrival {
704 conversation_id: "c".into(),
705 message_id: "m".into()
706 })
707 );
708 assert_eq!(
709 refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
710 Some(RefreshPlan::Newer {
711 conversation_id: "c".into()
712 })
713 );
714 }
715
716 #[test]
717 fn update_refreshes_one_message() {
718 assert_eq!(
719 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), Some("m"))),
720 Some(RefreshPlan::Message {
721 conversation_id: "c".into(),
722 message_id: "m".into()
723 })
724 );
725 assert_eq!(
726 refresh_plan(&event(EventKind::MessageUpdate, Some("c"), None)),
727 Some(RefreshPlan::Newer {
728 conversation_id: "c".into()
729 })
730 );
731 }
732
733 #[test]
734 fn thread_updates_and_new_messages_signal_a_possible_meeting_change() {
735 assert_eq!(
736 thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(),
737 Some("c")
738 );
739 assert_eq!(
740 thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
741 Some("c")
742 );
743 assert_eq!(
744 thread_signal(&event(EventKind::Typing, Some("c"), None)),
745 None
746 );
747 assert_eq!(
748 thread_signal(&event(EventKind::ThreadUpdate, None, None)),
749 None
750 );
751 }
752
753 #[test]
754 fn typing_and_missing_conversation_are_ignored() {
755 assert_eq!(
756 refresh_plan(&event(EventKind::Typing, Some("c"), None)),
757 None
758 );
759 assert_eq!(
760 refresh_plan(&event(EventKind::NewMessage, None, None)),
761 None
762 );
763 }
764
765 #[test]
766 fn session_errors_map_to_states() {
767 assert_eq!(
768 classify_session_error(&session::Error::NoAppTab),
769 ConnectionState::NoAppTab
770 );
771 assert_eq!(
772 classify_session_error(&session::Error::LoginRequired("x".into())),
773 ConnectionState::LoginRequired
774 );
775 assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
776 }
777
778 #[test]
779 fn only_connect_and_disconnect_move_the_link() {
780 assert_eq!(
781 link_signal_for(StatusKind::Connected),
782 Some(LinkSignal::Connected)
783 );
784 assert_eq!(
785 link_signal_for(StatusKind::Disconnected),
786 Some(LinkSignal::Disconnected)
787 );
788 assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
789 assert_eq!(link_signal_for(StatusKind::Error), None);
790 }
791}