| 1 | use chatsvc::{ |
| 2 | ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint, |
| 3 | WorkLocationKind, |
| 4 | }; |
| 5 | use graph::MAX_PRESENCE_IDS; |
| 6 | |
| 7 | use chrono::{DateTime, Utc}; |
| 8 | |
| 9 | use crate::engine::{META_USER_ID, SyncEngine}; |
| 10 | use crate::error::Result; |
| 11 | use crate::events::CoreEvent; |
| 12 | use crate::receipts::locked; |
| 13 | use crate::remote::Remote; |
| 14 | |
| 15 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 16 | pub enum Availability { |
| 17 | Available, |
| 18 | Busy, |
| 19 | DoNotDisturb, |
| 20 | Away, |
| 21 | Offline, |
| 22 | Unknown, |
| 23 | } |
| 24 | |
| 25 | impl Availability { |
| 26 | pub fn from_service(name: &str) -> Self { |
| 27 | match name { |
| 28 | "Available" | "AvailableIdle" => Availability::Available, |
| 29 | "Busy" | "BusyIdle" => Availability::Busy, |
| 30 | "DoNotDisturb" => Availability::DoNotDisturb, |
| 31 | "Away" | "BeRightBack" => Availability::Away, |
| 32 | "Offline" => Availability::Offline, |
| 33 | _ => Availability::Unknown, |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 39 | pub struct Presence { |
| 40 | pub availability: Availability, |
| 41 | pub in_call: bool, |
| 42 | } |
| 43 | |
| 44 | fn is_call_activity(activity: Option<&str>) -> bool { |
| 45 | matches!(activity, Some("InACall" | "InAConferenceCall")) |
| 46 | } |
| 47 | |
| 48 | impl<R: Remote> SyncEngine<R> { |
| 49 | pub fn presence(&self, user_id: &str) -> Option<Presence> { |
| 50 | self.presences |
| 51 | .lock() |
| 52 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 53 | .get(user_id) |
| 54 | .copied() |
| 55 | } |
| 56 | |
| 57 | pub async fn refresh_presence(&self, user_ids: &[String]) -> Result<()> { |
| 58 | let mut unique = user_ids.to_vec(); |
| 59 | unique.sort(); |
| 60 | unique.dedup(); |
| 61 | let mut changed = false; |
| 62 | for chunk in unique.chunks(MAX_PRESENCE_IDS) { |
| 63 | let found = self.remote.presences(chunk).await?; |
| 64 | changed |= self.record_presences(found.iter().map(|entry| { |
| 65 | ( |
| 66 | &entry.user_id, |
| 67 | entry.availability.as_str(), |
| 68 | entry.activity.as_deref(), |
| 69 | ) |
| 70 | })); |
| 71 | } |
| 72 | if changed { |
| 73 | let _ = self.events.send(CoreEvent::PresenceChanged); |
| 74 | } |
| 75 | Ok(()) |
| 76 | } |
| 77 | |
| 78 | pub fn apply_presence(&self, updates: &[PresenceUpdate]) { |
| 79 | let changed = self.record_presences(updates.iter().map(|update| { |
| 80 | ( |
| 81 | &update.user_id, |
| 82 | update.availability.as_str(), |
| 83 | update.activity.as_deref(), |
| 84 | ) |
| 85 | })); |
| 86 | if changed { |
| 87 | let _ = self.events.send(CoreEvent::PresenceChanged); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | pub fn concerns_me(&self, updates: &[PresenceUpdate]) -> bool { |
| 92 | let my_user_id = self.store.meta(META_USER_ID).ok().flatten(); |
| 93 | updates |
| 94 | .iter() |
| 95 | .any(|update| my_user_id.as_deref() == Some(update.user_id.as_str())) |
| 96 | } |
| 97 | |
| 98 | pub async fn refresh_own_status(&self) -> Result<PresenceStatus> { |
| 99 | let _ = self.ensure_display_name().await; |
| 100 | let my_user_id = self.my_user_id().await?; |
| 101 | let status = self.remote.own_status(&my_user_id).await?; |
| 102 | let changed = self.record_presences(std::iter::once(( |
| 103 | &my_user_id, |
| 104 | status.availability.as_str(), |
| 105 | status.activity.as_deref(), |
| 106 | ))); |
| 107 | let _ = self |
| 108 | .events |
| 109 | .send(CoreEvent::PresenceStatusChanged(status.clone())); |
| 110 | if changed { |
| 111 | let _ = self.events.send(CoreEvent::PresenceChanged); |
| 112 | } |
| 113 | Ok(status) |
| 114 | } |
| 115 | |
| 116 | pub async fn set_own_availability(&self, forced: Option<ForcedAvailability>) -> Result<()> { |
| 117 | self.remote.set_availability(forced.as_ref()).await?; |
| 118 | let _ = self.refresh_own_status().await; |
| 119 | Ok(()) |
| 120 | } |
| 121 | |
| 122 | pub async fn set_own_status_note(&self, note: Option<StatusNote>) -> Result<()> { |
| 123 | self.remote.set_status_note(note.as_ref()).await?; |
| 124 | let _ = self.refresh_own_status().await; |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | pub async fn set_own_work_location( |
| 129 | &self, |
| 130 | location: Option<(WorkLocationKind, DateTime<Utc>)>, |
| 131 | ) -> Result<()> { |
| 132 | self.remote.set_work_location(location).await?; |
| 133 | let _ = self.refresh_own_status().await; |
| 134 | Ok(()) |
| 135 | } |
| 136 | |
| 137 | pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> { |
| 138 | let _subscribing = self.presence_subscribing.lock().await; |
| 139 | let added = { |
| 140 | let mut watched = locked(&self.watched_presence); |
| 141 | let mut added: Vec<String> = user_ids |
| 142 | .iter() |
| 143 | .filter(|user_id| watched.insert((*user_id).clone())) |
| 144 | .cloned() |
| 145 | .collect(); |
| 146 | added.sort(); |
| 147 | added |
| 148 | }; |
| 149 | let endpoint = locked(&self.presence_endpoint).clone(); |
| 150 | let Some(endpoint) = endpoint.filter(|_| !added.is_empty()) else { |
| 151 | return Ok(()); |
| 152 | }; |
| 153 | let outcome = self |
| 154 | .remote |
| 155 | .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &added, false) |
| 156 | .await; |
| 157 | if outcome.is_err() { |
| 158 | let mut watched = locked(&self.watched_presence); |
| 159 | for user_id in &added { |
| 160 | watched.remove(user_id); |
| 161 | } |
| 162 | } |
| 163 | outcome |
| 164 | } |
| 165 | |
| 166 | /// No-op for the endpoint already subscribed; a failed subscribe forgets it so the next announcement retries. |
| 167 | pub async fn presence_endpoint(&self, endpoint: TrouterEndpoint) -> Result<()> { |
| 168 | let _subscribing = self.presence_subscribing.lock().await; |
| 169 | if locked(&self.presence_endpoint).as_ref() == Some(&endpoint) { |
| 170 | return Ok(()); |
| 171 | } |
| 172 | let outcome = self.subscribe_watched(&endpoint).await; |
| 173 | *locked(&self.presence_endpoint) = outcome.is_ok().then_some(endpoint); |
| 174 | outcome |
| 175 | } |
| 176 | |
| 177 | pub async fn resubscribe_presence(&self) -> Result<()> { |
| 178 | let _subscribing = self.presence_subscribing.lock().await; |
| 179 | let endpoint = locked(&self.presence_endpoint).clone(); |
| 180 | match endpoint { |
| 181 | Some(endpoint) => self.subscribe_watched(&endpoint).await, |
| 182 | None => Ok(()), |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | async fn subscribe_watched(&self, endpoint: &TrouterEndpoint) -> Result<()> { |
| 187 | let mut watched: Vec<String> = locked(&self.watched_presence).iter().cloned().collect(); |
| 188 | watched.sort(); |
| 189 | if watched.is_empty() { |
| 190 | return Ok(()); |
| 191 | } |
| 192 | self.remote |
| 193 | .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &watched, true) |
| 194 | .await |
| 195 | } |
| 196 | |
| 197 | fn record_presences<'a>( |
| 198 | &self, |
| 199 | found: impl Iterator<Item = (&'a String, &'a str, Option<&'a str>)>, |
| 200 | ) -> bool { |
| 201 | let mut known = locked(&self.presences); |
| 202 | let mut changed = false; |
| 203 | for (user_id, availability, activity) in found { |
| 204 | let presence = Presence { |
| 205 | availability: Availability::from_service(availability), |
| 206 | in_call: is_call_activity(activity), |
| 207 | }; |
| 208 | changed |= known.insert(user_id.clone(), presence) != Some(presence); |
| 209 | } |
| 210 | changed |
| 211 | } |
| 212 | } |