| 1 | use chatsvc::presence::MAX_PRESENCE_IDS; |
| 2 | use chatsvc::{ |
| 3 | ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint, |
| 4 | WorkLocationKind, |
| 5 | }; |
| 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" => Availability::Available, |
| 29 | "Busy" | "BusyIdle" => Availability::Busy, |
| 30 | "DoNotDisturb" => Availability::DoNotDisturb, |
| 31 | "Away" | "BeRightBack" | "AvailableIdle" => Availability::Away, |
| 32 | "Offline" => Availability::Offline, |
| 33 | _ => Availability::Unknown, |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 39 | pub enum Activity { |
| 40 | InACall, |
| 41 | InAConferenceCall, |
| 42 | InAMeeting, |
| 43 | Presenting, |
| 44 | OutOfOffice, |
| 45 | } |
| 46 | |
| 47 | impl Activity { |
| 48 | pub fn from_service(name: &str) -> Option<Self> { |
| 49 | match name { |
| 50 | "InACall" => Some(Activity::InACall), |
| 51 | "InAConferenceCall" => Some(Activity::InAConferenceCall), |
| 52 | "InAMeeting" => Some(Activity::InAMeeting), |
| 53 | "Presenting" => Some(Activity::Presenting), |
| 54 | "OutOfOffice" => Some(Activity::OutOfOffice), |
| 55 | _ => None, |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn is_call(self) -> bool { |
| 60 | matches!(self, Activity::InACall | Activity::InAConferenceCall) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 65 | pub struct Presence { |
| 66 | pub availability: Availability, |
| 67 | pub activity: Option<Activity>, |
| 68 | } |
| 69 | |
| 70 | impl Presence { |
| 71 | pub fn in_call(&self) -> bool { |
| 72 | self.activity.is_some_and(Activity::is_call) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | impl<R: Remote> SyncEngine<R> { |
| 77 | pub fn presence(&self, user_id: &str) -> Option<Presence> { |
| 78 | self.presences |
| 79 | .lock() |
| 80 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 81 | .get(user_id) |
| 82 | .copied() |
| 83 | } |
| 84 | |
| 85 | pub async fn refresh_presence(&self, user_ids: &[String]) -> Result<()> { |
| 86 | let mut unique = user_ids.to_vec(); |
| 87 | unique.sort(); |
| 88 | unique.dedup(); |
| 89 | let mut changed = false; |
| 90 | for chunk in unique.chunks(MAX_PRESENCE_IDS) { |
| 91 | let found = self.remote.presences(chunk).await?; |
| 92 | changed |= self.record_presences(found.iter().map(|entry| { |
| 93 | ( |
| 94 | &entry.user_id, |
| 95 | entry.availability.as_str(), |
| 96 | entry.activity.as_deref(), |
| 97 | ) |
| 98 | })); |
| 99 | } |
| 100 | if changed { |
| 101 | let _ = self.events.send(CoreEvent::PresenceChanged); |
| 102 | } |
| 103 | Ok(()) |
| 104 | } |
| 105 | |
| 106 | pub fn apply_presence(&self, updates: &[PresenceUpdate]) { |
| 107 | let changed = self.record_presences(updates.iter().map(|update| { |
| 108 | ( |
| 109 | &update.user_id, |
| 110 | update.availability.as_str(), |
| 111 | update.activity.as_deref(), |
| 112 | ) |
| 113 | })); |
| 114 | if changed { |
| 115 | let _ = self.events.send(CoreEvent::PresenceChanged); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | pub fn concerns_me(&self, updates: &[PresenceUpdate]) -> bool { |
| 120 | let my_user_id = self.store.meta(META_USER_ID).ok().flatten(); |
| 121 | updates |
| 122 | .iter() |
| 123 | .any(|update| my_user_id.as_deref() == Some(update.user_id.as_str())) |
| 124 | } |
| 125 | |
| 126 | pub async fn refresh_own_status(&self) -> Result<PresenceStatus> { |
| 127 | let _ = self.ensure_display_name().await; |
| 128 | let my_user_id = self.my_user_id().await?; |
| 129 | let status = self.remote.own_status(&my_user_id).await?; |
| 130 | let changed = self.record_presences(std::iter::once(( |
| 131 | &my_user_id, |
| 132 | status.availability.as_str(), |
| 133 | status.activity.as_deref(), |
| 134 | ))); |
| 135 | let _ = self |
| 136 | .events |
| 137 | .send(CoreEvent::PresenceStatusChanged(status.clone())); |
| 138 | if changed { |
| 139 | let _ = self.events.send(CoreEvent::PresenceChanged); |
| 140 | } |
| 141 | Ok(status) |
| 142 | } |
| 143 | |
| 144 | pub async fn set_own_availability(&self, forced: Option<ForcedAvailability>) -> Result<()> { |
| 145 | self.remote.set_availability(forced.as_ref()).await?; |
| 146 | let _ = self.refresh_own_status().await; |
| 147 | Ok(()) |
| 148 | } |
| 149 | |
| 150 | pub async fn set_own_status_note(&self, note: Option<StatusNote>) -> Result<()> { |
| 151 | self.remote.set_status_note(note.as_ref()).await?; |
| 152 | let _ = self.refresh_own_status().await; |
| 153 | Ok(()) |
| 154 | } |
| 155 | |
| 156 | pub async fn set_own_work_location( |
| 157 | &self, |
| 158 | location: Option<(WorkLocationKind, DateTime<Utc>)>, |
| 159 | ) -> Result<()> { |
| 160 | self.remote.set_work_location(location).await?; |
| 161 | let _ = self.refresh_own_status().await; |
| 162 | Ok(()) |
| 163 | } |
| 164 | |
| 165 | pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> { |
| 166 | let _subscribing = self.presence_subscribing.lock().await; |
| 167 | let added = { |
| 168 | let mut watched = locked(&self.watched_presence); |
| 169 | let mut added: Vec<String> = user_ids |
| 170 | .iter() |
| 171 | .filter(|user_id| watched.insert((*user_id).clone())) |
| 172 | .cloned() |
| 173 | .collect(); |
| 174 | added.sort(); |
| 175 | added |
| 176 | }; |
| 177 | let endpoint = locked(&self.presence_endpoint).clone(); |
| 178 | let Some(endpoint) = endpoint.filter(|_| !added.is_empty()) else { |
| 179 | return Ok(()); |
| 180 | }; |
| 181 | let outcome = self |
| 182 | .remote |
| 183 | .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &added, false) |
| 184 | .await; |
| 185 | if outcome.is_err() { |
| 186 | let mut watched = locked(&self.watched_presence); |
| 187 | for user_id in &added { |
| 188 | watched.remove(user_id); |
| 189 | } |
| 190 | } |
| 191 | outcome |
| 192 | } |
| 193 | |
| 194 | /// No-op for the endpoint already subscribed; a failed subscribe forgets it so the next announcement retries. |
| 195 | pub async fn presence_endpoint(&self, endpoint: TrouterEndpoint) -> Result<()> { |
| 196 | let _subscribing = self.presence_subscribing.lock().await; |
| 197 | if locked(&self.presence_endpoint).as_ref() == Some(&endpoint) { |
| 198 | return Ok(()); |
| 199 | } |
| 200 | let outcome = self.subscribe_watched(&endpoint).await; |
| 201 | *locked(&self.presence_endpoint) = outcome.is_ok().then_some(endpoint); |
| 202 | outcome |
| 203 | } |
| 204 | |
| 205 | pub async fn resubscribe_presence(&self) -> Result<()> { |
| 206 | let _subscribing = self.presence_subscribing.lock().await; |
| 207 | let endpoint = locked(&self.presence_endpoint).clone(); |
| 208 | match endpoint { |
| 209 | Some(endpoint) => self.subscribe_watched(&endpoint).await, |
| 210 | None => Ok(()), |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | async fn subscribe_watched(&self, endpoint: &TrouterEndpoint) -> Result<()> { |
| 215 | let mut watched: Vec<String> = locked(&self.watched_presence).iter().cloned().collect(); |
| 216 | watched.sort(); |
| 217 | if watched.is_empty() { |
| 218 | return Ok(()); |
| 219 | } |
| 220 | self.remote |
| 221 | .subscribe_presence(&endpoint.endpoint_id, &endpoint.trouter_uri, &watched, true) |
| 222 | .await |
| 223 | } |
| 224 | |
| 225 | fn record_presences<'a>( |
| 226 | &self, |
| 227 | found: impl Iterator<Item = (&'a String, &'a str, Option<&'a str>)>, |
| 228 | ) -> bool { |
| 229 | let mut known = locked(&self.presences); |
| 230 | let mut changed = false; |
| 231 | for (user_id, availability, activity) in found { |
| 232 | let presence = Presence { |
| 233 | availability: Availability::from_service(availability), |
| 234 | activity: activity.and_then(Activity::from_service), |
| 235 | }; |
| 236 | changed |= known.insert(user_id.clone(), presence) != Some(presence); |
| 237 | } |
| 238 | changed |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | #[cfg(test)] |
| 243 | mod tests { |
| 244 | use super::*; |
| 245 | |
| 246 | #[test] |
| 247 | fn idle_available_shows_as_away_like_teams() { |
| 248 | assert_eq!( |
| 249 | Availability::from_service("AvailableIdle"), |
| 250 | Availability::Away |
| 251 | ); |
| 252 | assert_eq!(Availability::from_service("BusyIdle"), Availability::Busy); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn activity_names_map_and_unknown_is_none() { |
| 257 | assert_eq!(Activity::from_service("InACall"), Some(Activity::InACall)); |
| 258 | assert_eq!( |
| 259 | Activity::from_service("InAConferenceCall"), |
| 260 | Some(Activity::InAConferenceCall) |
| 261 | ); |
| 262 | assert_eq!( |
| 263 | Activity::from_service("InAMeeting"), |
| 264 | Some(Activity::InAMeeting) |
| 265 | ); |
| 266 | assert_eq!( |
| 267 | Activity::from_service("Presenting"), |
| 268 | Some(Activity::Presenting) |
| 269 | ); |
| 270 | assert_eq!( |
| 271 | Activity::from_service("OutOfOffice"), |
| 272 | Some(Activity::OutOfOffice) |
| 273 | ); |
| 274 | assert_eq!(Activity::from_service("Available"), None); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn only_call_activities_count_as_in_call() { |
| 279 | let presence = |activity| Presence { |
| 280 | availability: Availability::Busy, |
| 281 | activity, |
| 282 | }; |
| 283 | assert!(presence(Some(Activity::InACall)).in_call()); |
| 284 | assert!(presence(Some(Activity::InAConferenceCall)).in_call()); |
| 285 | assert!(!presence(Some(Activity::InAMeeting)).in_call()); |
| 286 | assert!(!presence(None).in_call()); |
| 287 | } |
| 288 | } |