| 1 | use chrono::{DateTime, Datelike, SecondsFormat, Utc}; |
| 2 | use serde_json::{Value, json}; |
| 3 | use session::{Method, PRESENCE, Request, Scope, Session}; |
| 4 | use uuid::Uuid; |
| 5 | |
| 6 | use crate::cards::{CardTransport, SessionCardTransport}; |
| 7 | use crate::error::{Error, Result}; |
| 8 | |
| 9 | mod lookup; |
| 10 | |
| 11 | pub use lookup::{MAX_PRESENCE_IDS, PresenceLookup, UserPresence}; |
| 12 | |
| 13 | const BASE_URL: &str = "https://presence.teams.microsoft.com/v1"; |
| 14 | const PRESENCE_SCOPE: &str = "user_impersonation"; |
| 15 | const CLIENT_VERSION: &str = "1415/26091712213"; |
| 16 | const ORGID_PREFIX: &str = "8:orgid:"; |
| 17 | const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>"; |
| 18 | const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z"; |
| 19 | const NEVER_YEAR: i32 = 9999; |
| 20 | const OFFLINE_ACTIVITY: &str = "OffWork"; |
| 21 | const DESKTOP_USER_AGENT: &str = "Teams-V2-Desktop"; |
| 22 | const WEB_USER_AGENT: &str = "Teams-V2-Web"; |
| 23 | const ENDPOINT_ID_HEADER: &str = "x-ms-endpoint-id"; |
| 24 | |
| 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 26 | pub enum ForcedKind { |
| 27 | Available, |
| 28 | Busy, |
| 29 | DoNotDisturb, |
| 30 | BeRightBack, |
| 31 | Away, |
| 32 | Offline, |
| 33 | } |
| 34 | |
| 35 | impl ForcedKind { |
| 36 | pub fn code(self) -> &'static str { |
| 37 | match self { |
| 38 | ForcedKind::Available => "Available", |
| 39 | ForcedKind::Busy => "Busy", |
| 40 | ForcedKind::DoNotDisturb => "DoNotDisturb", |
| 41 | ForcedKind::BeRightBack => "BeRightBack", |
| 42 | ForcedKind::Away => "Away", |
| 43 | ForcedKind::Offline => "Offline", |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub fn from_code(code: &str) -> Option<Self> { |
| 48 | match code { |
| 49 | "Available" => Some(ForcedKind::Available), |
| 50 | "Busy" => Some(ForcedKind::Busy), |
| 51 | "DoNotDisturb" => Some(ForcedKind::DoNotDisturb), |
| 52 | "BeRightBack" => Some(ForcedKind::BeRightBack), |
| 53 | "Away" => Some(ForcedKind::Away), |
| 54 | "Offline" => Some(ForcedKind::Offline), |
| 55 | _ => None, |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 61 | pub enum ActivityReporting { |
| 62 | Transport, |
| 63 | Direct, |
| 64 | } |
| 65 | |
| 66 | impl ActivityReporting { |
| 67 | fn code(self) -> &'static str { |
| 68 | match self { |
| 69 | ActivityReporting::Transport => "Transport", |
| 70 | ActivityReporting::Direct => "Direct", |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 76 | pub struct ForcedAvailability { |
| 77 | pub kind: ForcedKind, |
| 78 | pub expires_at: Option<DateTime<Utc>>, |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 82 | pub struct StatusNote { |
| 83 | pub text: String, |
| 84 | pub show_when_messaged: bool, |
| 85 | pub expires_at: Option<DateTime<Utc>>, |
| 86 | } |
| 87 | |
| 88 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 89 | pub enum WorkLocationKind { |
| 90 | Office, |
| 91 | Remote, |
| 92 | } |
| 93 | |
| 94 | impl WorkLocationKind { |
| 95 | fn code(self) -> u8 { |
| 96 | match self { |
| 97 | WorkLocationKind::Office => 1, |
| 98 | WorkLocationKind::Remote => 2, |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 104 | pub enum WorkLocationSource { |
| 105 | Set, |
| 106 | Scheduled, |
| 107 | Verified, |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 111 | pub struct WorkLocation { |
| 112 | pub kind: WorkLocationKind, |
| 113 | pub source: WorkLocationSource, |
| 114 | } |
| 115 | |
| 116 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 117 | pub struct PresenceStatus { |
| 118 | pub availability: String, |
| 119 | pub activity: Option<String>, |
| 120 | pub forced: Option<ForcedAvailability>, |
| 121 | pub note: Option<StatusNote>, |
| 122 | pub out_of_office: bool, |
| 123 | pub out_of_office_note: Option<String>, |
| 124 | pub work_location: Option<WorkLocation>, |
| 125 | } |
| 126 | |
| 127 | pub struct PresenceService<T: CardTransport = SessionCardTransport> { |
| 128 | transport: T, |
| 129 | } |
| 130 | |
| 131 | impl PresenceService<SessionCardTransport> { |
| 132 | pub fn new(session: &Session) -> Self { |
| 133 | PresenceService::with_transport(SessionCardTransport::new(session)) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | impl<T: CardTransport> PresenceService<T> { |
| 138 | pub fn with_transport(transport: T) -> Self { |
| 139 | PresenceService { transport } |
| 140 | } |
| 141 | |
| 142 | pub async fn set_availability(&self, forced: Option<&ForcedAvailability>) -> Result<()> { |
| 143 | let url = format!("{BASE_URL}/me/forceavailability/"); |
| 144 | let request = match forced { |
| 145 | Some(forced) => Request::with_body(Method::Put, &url, availability_body(forced)), |
| 146 | None => Request { |
| 147 | method: Method::Put, |
| 148 | ..Request::get(&url) |
| 149 | }, |
| 150 | }; |
| 151 | self.send(request, &url).await.map(drop) |
| 152 | } |
| 153 | |
| 154 | pub async fn register_endpoint( |
| 155 | &self, |
| 156 | endpoint_id: &str, |
| 157 | reporting: ActivityReporting, |
| 158 | ) -> Result<()> { |
| 159 | let url = format!("{BASE_URL}/me/endpoints/"); |
| 160 | let mut request = |
| 161 | Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting)); |
| 162 | request.headers = endpoint_headers(endpoint_id); |
| 163 | self.send(request, &url).await.map(drop) |
| 164 | } |
| 165 | |
| 166 | pub async fn unregister_endpoint(&self, endpoint_id: &str) -> Result<()> { |
| 167 | let url = format!("{BASE_URL}/me/endpoints/{endpoint_id}"); |
| 168 | let mut request = Request { |
| 169 | method: Method::Delete, |
| 170 | ..Request::get(&url) |
| 171 | }; |
| 172 | request.headers = endpoint_headers(endpoint_id); |
| 173 | self.send(request, &url).await.map(drop) |
| 174 | } |
| 175 | |
| 176 | pub async fn report_activity(&self, endpoint_id: &str, active: bool) -> Result<()> { |
| 177 | let url = format!("{BASE_URL}/me/reportmyactivity/"); |
| 178 | let body = json!({"endpointId": endpoint_id, "isActive": active}); |
| 179 | let mut request = Request::with_body(Method::Post, &url, body); |
| 180 | request.headers = endpoint_headers(endpoint_id); |
| 181 | self.send(request, &url).await.map(drop) |
| 182 | } |
| 183 | |
| 184 | pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> { |
| 185 | let url = format!("{BASE_URL}/me/publishnote"); |
| 186 | let body = note.map_or_else(|| json!({"message": ""}), note_body); |
| 187 | self.send(Request::with_body(Method::Put, &url, body), &url) |
| 188 | .await |
| 189 | .map(drop) |
| 190 | } |
| 191 | |
| 192 | pub async fn set_work_location( |
| 193 | &self, |
| 194 | location: Option<(WorkLocationKind, DateTime<Utc>)>, |
| 195 | ) -> Result<()> { |
| 196 | let url = format!("{BASE_URL}/me/workLocation/"); |
| 197 | let body = match location { |
| 198 | Some((kind, expires_at)) => json!({ |
| 199 | "location": kind.code(), |
| 200 | "expirationTime": format_expiry(Some(expires_at)), |
| 201 | }), |
| 202 | None => json!({"location": 0}), |
| 203 | }; |
| 204 | self.send(Request::with_body(Method::Put, &url, body), &url) |
| 205 | .await |
| 206 | .map(drop) |
| 207 | } |
| 208 | |
| 209 | pub async fn status(&self, user_id: &str) -> Result<PresenceStatus> { |
| 210 | let url = format!("{BASE_URL}/presence/getpresence/"); |
| 211 | let mri = format!("{ORGID_PREFIX}{user_id}"); |
| 212 | let body = json!([{ "mri": mri }]); |
| 213 | let answer = self |
| 214 | .send(Request::with_body(Method::Post, &url, body), &url) |
| 215 | .await?; |
| 216 | parse_status(&answer, &mri, Utc::now()) |
| 217 | } |
| 218 | |
| 219 | async fn send(&self, mut request: Request, url: &str) -> Result<Value> { |
| 220 | if request.headers.is_empty() { |
| 221 | request.headers = service_headers(WEB_USER_AGENT); |
| 222 | } |
| 223 | let answer = self |
| 224 | .transport |
| 225 | .send(request, Scope::new(PRESENCE, PRESENCE_SCOPE)) |
| 226 | .await?; |
| 227 | if !answer.is_success() { |
| 228 | return Err(Error::Session(session::Error::api( |
| 229 | answer.status, |
| 230 | url, |
| 231 | answer.body, |
| 232 | ))); |
| 233 | } |
| 234 | Ok(answer.body) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | pub fn error_status(error: &Error) -> Option<u16> { |
| 239 | match error { |
| 240 | Error::Session(session::Error::Api { status, .. }) => Some(*status), |
| 241 | _ => None, |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | pub fn is_endpoint_missing(error: &Error) -> bool { |
| 246 | error_status(error) == Some(404) |
| 247 | } |
| 248 | |
| 249 | fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value { |
| 250 | json!({ |
| 251 | "id": endpoint_id, |
| 252 | "availability": "Available", |
| 253 | "activity": "Available", |
| 254 | "activityReporting": reporting.code(), |
| 255 | "deviceType": "Desktop", |
| 256 | }) |
| 257 | } |
| 258 | |
| 259 | fn endpoint_headers(endpoint_id: &str) -> Vec<(String, String)> { |
| 260 | let mut headers = service_headers(DESKTOP_USER_AGENT); |
| 261 | headers.insert(1, (ENDPOINT_ID_HEADER.into(), endpoint_id.to_owned())); |
| 262 | headers |
| 263 | } |
| 264 | |
| 265 | fn service_headers(user_agent: &str) -> Vec<(String, String)> { |
| 266 | vec![ |
| 267 | ("x-ms-client-user-agent".into(), user_agent.into()), |
| 268 | ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()), |
| 269 | ("x-ms-client-version".into(), CLIENT_VERSION.into()), |
| 270 | ] |
| 271 | } |
| 272 | |
| 273 | pub fn format_expiry(expires_at: Option<DateTime<Utc>>) -> String { |
| 274 | match expires_at { |
| 275 | Some(expires_at) => expires_at.to_rfc3339_opts(SecondsFormat::Millis, true), |
| 276 | None => NEVER_EXPIRES.to_owned(), |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | fn availability_body(forced: &ForcedAvailability) -> Value { |
| 281 | let mut body = json!({"availability": forced.kind.code()}); |
| 282 | if forced.kind == ForcedKind::Offline { |
| 283 | body["activity"] = json!(OFFLINE_ACTIVITY); |
| 284 | } |
| 285 | if let Some(expires_at) = forced.expires_at { |
| 286 | body["desiredExpirationTime"] = json!(format_expiry(Some(expires_at))); |
| 287 | } |
| 288 | body |
| 289 | } |
| 290 | |
| 291 | fn note_body(note: &StatusNote) -> Value { |
| 292 | let suffix = if note.show_when_messaged { |
| 293 | PINNED_NOTE_SUFFIX |
| 294 | } else { |
| 295 | "" |
| 296 | }; |
| 297 | json!({ |
| 298 | "message": format!("{}{suffix}", escape_text(¬e.text)), |
| 299 | "expiry": format_expiry(note.expires_at), |
| 300 | }) |
| 301 | } |
| 302 | |
| 303 | fn escape_text(text: &str) -> String { |
| 304 | text.replace('&', "&") |
| 305 | .replace('<', "<") |
| 306 | .replace('>', ">") |
| 307 | .replace('"', """) |
| 308 | .replace('\'', "'") |
| 309 | } |
| 310 | |
| 311 | fn unescape_text(text: &str) -> String { |
| 312 | text.replace("<", "<") |
| 313 | .replace(">", ">") |
| 314 | .replace(""", "\"") |
| 315 | .replace("'", "'") |
| 316 | .replace("&", "&") |
| 317 | } |
| 318 | |
| 319 | fn plain_text(message: &str) -> Option<String> { |
| 320 | let mut text = String::with_capacity(message.len()); |
| 321 | let mut inside_tag = false; |
| 322 | for character in message.chars() { |
| 323 | match character { |
| 324 | '<' => inside_tag = true, |
| 325 | '>' if inside_tag => inside_tag = false, |
| 326 | _ if !inside_tag => text.push(character), |
| 327 | _ => {} |
| 328 | } |
| 329 | } |
| 330 | let text = unescape_text(&text); |
| 331 | let text = text.trim(); |
| 332 | (!text.is_empty()).then(|| text.to_owned()) |
| 333 | } |
| 334 | |
| 335 | fn split_pinned(message: &str) -> (String, bool) { |
| 336 | let pinned = message |
| 337 | .find(PINNED_NOTE_SUFFIX) |
| 338 | .is_some_and(|index| index > 0); |
| 339 | (message.replace(PINNED_NOTE_SUFFIX, ""), pinned) |
| 340 | } |
| 341 | |
| 342 | fn parse_expiry(value: Option<&Value>) -> Option<DateTime<Utc>> { |
| 343 | let parsed = DateTime::parse_from_rfc3339(value?.as_str()?) |
| 344 | .ok()? |
| 345 | .with_timezone(&Utc); |
| 346 | (parsed.year() < NEVER_YEAR).then_some(parsed) |
| 347 | } |
| 348 | |
| 349 | fn parse_forced(forced: &Value) -> Option<ForcedAvailability> { |
| 350 | Some(ForcedAvailability { |
| 351 | kind: ForcedKind::from_code(forced.get("availability")?.as_str()?)?, |
| 352 | expires_at: parse_expiry(forced.get("expiry")), |
| 353 | }) |
| 354 | } |
| 355 | |
| 356 | fn parse_note(note: &Value, now: DateTime<Utc>) -> Option<StatusNote> { |
| 357 | let (message, show_when_messaged) = split_pinned(note.get("message")?.as_str()?); |
| 358 | let text = plain_text(&message)?; |
| 359 | let expires_at = parse_expiry(note.get("expiry")); |
| 360 | let expired = expires_at.is_some_and(|expires_at| expires_at <= now); |
| 361 | (!expired).then_some(StatusNote { |
| 362 | text, |
| 363 | show_when_messaged, |
| 364 | expires_at, |
| 365 | }) |
| 366 | } |
| 367 | |
| 368 | fn parse_work_location(location: &Value, now: DateTime<Utc>) -> Option<WorkLocation> { |
| 369 | let kind = match location.get("location")?.as_str()? { |
| 370 | "Office" => WorkLocationKind::Office, |
| 371 | "Remote" => WorkLocationKind::Remote, |
| 372 | _ => return None, |
| 373 | }; |
| 374 | let expired = parse_expiry(location.get("expiry")).is_some_and(|expires_at| expires_at <= now); |
| 375 | (!expired).then(|| WorkLocation { |
| 376 | kind, |
| 377 | source: match location.get("locationSource").and_then(Value::as_str) { |
| 378 | Some("ScheduledLocation") => WorkLocationSource::Scheduled, |
| 379 | Some("VerifiedLocation") => WorkLocationSource::Verified, |
| 380 | _ => WorkLocationSource::Set, |
| 381 | }, |
| 382 | }) |
| 383 | } |
| 384 | |
| 385 | pub fn parse_status(body: &Value, mri: &str, now: DateTime<Utc>) -> Result<PresenceStatus> { |
| 386 | let entries = body |
| 387 | .as_array() |
| 388 | .ok_or_else(|| Error::UnexpectedAnswer("no presence list".into()))?; |
| 389 | let presence = entries |
| 390 | .iter() |
| 391 | .find(|entry| entry.get("mri").and_then(Value::as_str) == Some(mri)) |
| 392 | .or_else(|| entries.first()) |
| 393 | .and_then(|entry| entry.get("presence")) |
| 394 | .ok_or_else(|| Error::UnexpectedAnswer("no own presence".into()))?; |
| 395 | Ok(PresenceStatus { |
| 396 | availability: presence |
| 397 | .get("availability") |
| 398 | .and_then(Value::as_str) |
| 399 | .unwrap_or_default() |
| 400 | .to_owned(), |
| 401 | activity: presence |
| 402 | .get("activity") |
| 403 | .and_then(Value::as_str) |
| 404 | .map(str::to_owned), |
| 405 | forced: presence.get("forcedAvailability").and_then(parse_forced), |
| 406 | note: presence.get("note").and_then(|note| parse_note(note, now)), |
| 407 | out_of_office: presence |
| 408 | .pointer("/calendarData/isOutOfOffice") |
| 409 | .and_then(Value::as_bool) |
| 410 | .unwrap_or(false), |
| 411 | out_of_office_note: presence |
| 412 | .pointer("/calendarData/outOfOfficeNote/message") |
| 413 | .and_then(Value::as_str) |
| 414 | .and_then(plain_text), |
| 415 | work_location: presence |
| 416 | .get("workLocation") |
| 417 | .and_then(|location| parse_work_location(location, now)), |
| 418 | }) |
| 419 | } |
| 420 | |
| 421 | #[cfg(test)] |
| 422 | mod tests { |
| 423 | use std::sync::Mutex; |
| 424 | |
| 425 | use chrono::TimeZone; |
| 426 | use session::{ApiResponse, Method}; |
| 427 | |
| 428 | use super::*; |
| 429 | |
| 430 | struct Recorder { |
| 431 | status: u16, |
| 432 | body: Value, |
| 433 | sent: Mutex<Vec<(Request, Scope)>>, |
| 434 | } |
| 435 | |
| 436 | impl CardTransport for Recorder { |
| 437 | async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> { |
| 438 | self.sent.lock().unwrap().push((request, scope)); |
| 439 | Ok(ApiResponse { |
| 440 | status: self.status, |
| 441 | body: self.body.clone(), |
| 442 | retry_after: None, |
| 443 | }) |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fn service(status: u16, body: Value) -> PresenceService<Recorder> { |
| 448 | PresenceService::with_transport(Recorder { |
| 449 | status, |
| 450 | body, |
| 451 | sent: Mutex::new(Vec::new()), |
| 452 | }) |
| 453 | } |
| 454 | |
| 455 | fn only_request(service: &PresenceService<Recorder>) -> (Request, Scope) { |
| 456 | let mut sent = service.transport.sent.lock().unwrap(); |
| 457 | assert_eq!(sent.len(), 1); |
| 458 | sent.remove(0) |
| 459 | } |
| 460 | |
| 461 | fn at(hour: u32, minute: u32) -> DateTime<Utc> { |
| 462 | Utc.with_ymd_and_hms(2026, 10, 9, hour, minute, 0).unwrap() |
| 463 | } |
| 464 | |
| 465 | #[tokio::test] |
| 466 | async fn busy_with_expiry_puts_availability_and_desired_expiration() { |
| 467 | let service = service(200, Value::Null); |
| 468 | let forced = ForcedAvailability { |
| 469 | kind: ForcedKind::Busy, |
| 470 | expires_at: Some(at(15, 30)), |
| 471 | }; |
| 472 | service.set_availability(Some(&forced)).await.unwrap(); |
| 473 | let (request, scope) = only_request(&service); |
| 474 | assert_eq!(request.method, Method::Put); |
| 475 | assert_eq!( |
| 476 | request.url, |
| 477 | "https://presence.teams.microsoft.com/v1/me/forceavailability/" |
| 478 | ); |
| 479 | assert_eq!( |
| 480 | request.body, |
| 481 | Some(json!({ |
| 482 | "availability": "Busy", |
| 483 | "desiredExpirationTime": "2026-10-09T15:30:00.000Z", |
| 484 | })) |
| 485 | ); |
| 486 | assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation")); |
| 487 | let names: Vec<&str> = request |
| 488 | .headers |
| 489 | .iter() |
| 490 | .map(|(name, _)| name.as_str()) |
| 491 | .collect(); |
| 492 | assert_eq!( |
| 493 | names, |
| 494 | [ |
| 495 | "x-ms-client-user-agent", |
| 496 | "x-ms-correlation-id", |
| 497 | "x-ms-client-version" |
| 498 | ] |
| 499 | ); |
| 500 | } |
| 501 | |
| 502 | fn header_pairs(request: &Request) -> Vec<(&str, &str)> { |
| 503 | request |
| 504 | .headers |
| 505 | .iter() |
| 506 | .filter(|(name, _)| name != "x-ms-correlation-id") |
| 507 | .map(|(name, value)| (name.as_str(), value.as_str())) |
| 508 | .collect() |
| 509 | } |
| 510 | |
| 511 | #[tokio::test] |
| 512 | async fn register_endpoint_puts_the_transport_endpoint_as_desktop() { |
| 513 | let service = service(200, Value::Null); |
| 514 | service |
| 515 | .register_endpoint("epid-1", ActivityReporting::Transport) |
| 516 | .await |
| 517 | .unwrap(); |
| 518 | let (request, scope) = only_request(&service); |
| 519 | assert_eq!(request.method, Method::Put); |
| 520 | assert_eq!( |
| 521 | request.url, |
| 522 | "https://presence.teams.microsoft.com/v1/me/endpoints/" |
| 523 | ); |
| 524 | assert_eq!( |
| 525 | request.body, |
| 526 | Some(json!({ |
| 527 | "id": "epid-1", |
| 528 | "availability": "Available", |
| 529 | "activity": "Available", |
| 530 | "activityReporting": "Transport", |
| 531 | "deviceType": "Desktop", |
| 532 | })) |
| 533 | ); |
| 534 | assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation")); |
| 535 | assert_eq!( |
| 536 | header_pairs(&request), |
| 537 | [ |
| 538 | ("x-ms-client-user-agent", "Teams-V2-Desktop"), |
| 539 | ("x-ms-endpoint-id", "epid-1"), |
| 540 | ("x-ms-client-version", CLIENT_VERSION), |
| 541 | ] |
| 542 | ); |
| 543 | } |
| 544 | |
| 545 | #[tokio::test] |
| 546 | async fn register_endpoint_can_switch_to_direct_reporting() { |
| 547 | let service = service(200, Value::Null); |
| 548 | service |
| 549 | .register_endpoint("epid-1", ActivityReporting::Direct) |
| 550 | .await |
| 551 | .unwrap(); |
| 552 | let (request, _) = only_request(&service); |
| 553 | assert_eq!(request.body.unwrap()["activityReporting"], "Direct"); |
| 554 | } |
| 555 | |
| 556 | #[tokio::test] |
| 557 | async fn unregister_endpoint_deletes_by_id_without_body() { |
| 558 | let service = service(200, Value::Null); |
| 559 | service.unregister_endpoint("epid-1").await.unwrap(); |
| 560 | let (request, _) = only_request(&service); |
| 561 | assert_eq!(request.method, Method::Delete); |
| 562 | assert_eq!( |
| 563 | request.url, |
| 564 | "https://presence.teams.microsoft.com/v1/me/endpoints/epid-1" |
| 565 | ); |
| 566 | assert_eq!(request.body, None); |
| 567 | assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1"))); |
| 568 | } |
| 569 | |
| 570 | #[tokio::test] |
| 571 | async fn report_activity_posts_the_state_for_the_endpoint() { |
| 572 | let service = service(200, Value::Null); |
| 573 | service.report_activity("epid-1", false).await.unwrap(); |
| 574 | let (request, _) = only_request(&service); |
| 575 | assert_eq!(request.method, Method::Post); |
| 576 | assert_eq!( |
| 577 | request.url, |
| 578 | "https://presence.teams.microsoft.com/v1/me/reportmyactivity/" |
| 579 | ); |
| 580 | assert_eq!( |
| 581 | request.body, |
| 582 | Some(json!({"endpointId": "epid-1", "isActive": false})) |
| 583 | ); |
| 584 | assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1"))); |
| 585 | } |
| 586 | |
| 587 | #[tokio::test] |
| 588 | async fn not_found_marks_the_endpoint_as_missing() { |
| 589 | let service = service(404, Value::Null); |
| 590 | let error = service.report_activity("epid-1", true).await.unwrap_err(); |
| 591 | assert!(is_endpoint_missing(&error)); |
| 592 | let service = self::service(500, Value::Null); |
| 593 | let error = service.report_activity("epid-1", true).await.unwrap_err(); |
| 594 | assert!(!is_endpoint_missing(&error)); |
| 595 | } |
| 596 | |
| 597 | #[tokio::test] |
| 598 | async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() { |
| 599 | let service = service(200, Value::Null); |
| 600 | let forced = ForcedAvailability { |
| 601 | kind: ForcedKind::Offline, |
| 602 | expires_at: None, |
| 603 | }; |
| 604 | service.set_availability(Some(&forced)).await.unwrap(); |
| 605 | let (request, _) = only_request(&service); |
| 606 | assert_eq!( |
| 607 | request.body, |
| 608 | Some(json!({"availability": "Offline", "activity": "OffWork"})) |
| 609 | ); |
| 610 | } |
| 611 | |
| 612 | #[tokio::test] |
| 613 | async fn reset_is_a_put_without_body() { |
| 614 | let service = service(200, Value::Null); |
| 615 | service.set_availability(None).await.unwrap(); |
| 616 | let (request, _) = only_request(&service); |
| 617 | assert_eq!(request.method, Method::Put); |
| 618 | assert_eq!(request.body, None); |
| 619 | assert!(request.url.ends_with("/v1/me/forceavailability/")); |
| 620 | } |
| 621 | |
| 622 | #[tokio::test] |
| 623 | async fn note_with_pin_marker_and_escaped_text() { |
| 624 | let service = service(200, Value::Null); |
| 625 | let note = StatusNote { |
| 626 | text: "Out <b> & about".into(), |
| 627 | show_when_messaged: true, |
| 628 | expires_at: Some(at(18, 0)), |
| 629 | }; |
| 630 | service.set_note(Some(¬e)).await.unwrap(); |
| 631 | let (request, _) = only_request(&service); |
| 632 | assert_eq!(request.method, Method::Put); |
| 633 | assert_eq!( |
| 634 | request.url, |
| 635 | "https://presence.teams.microsoft.com/v1/me/publishnote" |
| 636 | ); |
| 637 | assert_eq!( |
| 638 | request.body, |
| 639 | Some(json!({ |
| 640 | "message": "Out <b> & about<pinnednote></pinnednote>", |
| 641 | "expiry": "2026-10-09T18:00:00.000Z", |
| 642 | })) |
| 643 | ); |
| 644 | } |
| 645 | |
| 646 | #[tokio::test] |
| 647 | async fn note_without_pin_and_never_expiring() { |
| 648 | let service = service(200, Value::Null); |
| 649 | let note = StatusNote { |
| 650 | text: "Focus".into(), |
| 651 | show_when_messaged: false, |
| 652 | expires_at: None, |
| 653 | }; |
| 654 | service.set_note(Some(¬e)).await.unwrap(); |
| 655 | let (request, _) = only_request(&service); |
| 656 | assert_eq!( |
| 657 | request.body, |
| 658 | Some(json!({"message": "Focus", "expiry": "9999-12-31T23:59:59.999Z"})) |
| 659 | ); |
| 660 | } |
| 661 | |
| 662 | #[tokio::test] |
| 663 | async fn clearing_the_note_sends_an_empty_message_only() { |
| 664 | let service = service(200, Value::Null); |
| 665 | service.set_note(None).await.unwrap(); |
| 666 | let (request, _) = only_request(&service); |
| 667 | assert_eq!(request.body, Some(json!({"message": ""}))); |
| 668 | } |
| 669 | |
| 670 | #[tokio::test] |
| 671 | async fn failures_surface_as_errors() { |
| 672 | let service = service(400, json!({"message": "bad"})); |
| 673 | assert!(service.set_note(None).await.is_err()); |
| 674 | } |
| 675 | |
| 676 | #[tokio::test] |
| 677 | async fn reads_own_presence_by_mri() { |
| 678 | let body = json!([{ |
| 679 | "mri": "8:orgid:me", |
| 680 | "presence": {"availability": "Available", "activity": "Available"} |
| 681 | }]); |
| 682 | let service = service(200, body); |
| 683 | let status = service.status("me").await.unwrap(); |
| 684 | assert_eq!(status.availability, "Available"); |
| 685 | let (request, _) = only_request(&service); |
| 686 | assert_eq!(request.method, Method::Post); |
| 687 | assert_eq!( |
| 688 | request.url, |
| 689 | "https://presence.teams.microsoft.com/v1/presence/getpresence/" |
| 690 | ); |
| 691 | assert_eq!(request.body, Some(json!([{"mri": "8:orgid:me"}]))); |
| 692 | } |
| 693 | |
| 694 | #[test] |
| 695 | fn parses_forced_note_and_out_of_office() { |
| 696 | let body = json!([{ |
| 697 | "mri": "8:orgid:me", |
| 698 | "presence": { |
| 699 | "availability": "Busy", |
| 700 | "activity": "Busy", |
| 701 | "forcedAvailability": { |
| 702 | "availability": "Busy", |
| 703 | "expiry": "2026-10-09T15:30:00Z", |
| 704 | "publishTime": "2026-10-09T15:00:00Z" |
| 705 | }, |
| 706 | "note": { |
| 707 | "message": "In <focus><pinnednote></pinnednote>", |
| 708 | "expiry": "2026-10-09T18:00:00Z" |
| 709 | }, |
| 710 | "calendarData": {"isOutOfOffice": true} |
| 711 | } |
| 712 | }]); |
| 713 | let status = parse_status(&body, "8:orgid:me", at(12, 0)).unwrap(); |
| 714 | assert_eq!(status.availability, "Busy"); |
| 715 | assert_eq!( |
| 716 | status.forced, |
| 717 | Some(ForcedAvailability { |
| 718 | kind: ForcedKind::Busy, |
| 719 | expires_at: Some(at(15, 30)), |
| 720 | }) |
| 721 | ); |
| 722 | assert_eq!( |
| 723 | status.note, |
| 724 | Some(StatusNote { |
| 725 | text: "In <focus>".into(), |
| 726 | show_when_messaged: true, |
| 727 | expires_at: Some(at(18, 0)), |
| 728 | }) |
| 729 | ); |
| 730 | assert!(status.out_of_office); |
| 731 | } |
| 732 | |
| 733 | #[test] |
| 734 | fn never_expiry_reads_back_as_none() { |
| 735 | let body = json!([{ |
| 736 | "mri": "8:orgid:me", |
| 737 | "presence": { |
| 738 | "availability": "Available", |
| 739 | "note": {"message": "Hi", "expiry": "9999-12-31T23:59:59.9999999Z"} |
| 740 | } |
| 741 | }]); |
| 742 | let status = parse_status(&body, "8:orgid:me", at(12, 0)).unwrap(); |
| 743 | let note = status.note.unwrap(); |
| 744 | assert_eq!(note.expires_at, None); |
| 745 | assert!(!note.show_when_messaged); |
| 746 | } |
| 747 | |
| 748 | #[test] |
| 749 | fn expired_and_empty_notes_are_dropped() { |
| 750 | let expired = json!([{"mri": "m", "presence": { |
| 751 | "availability": "Available", |
| 752 | "note": {"message": "Old", "expiry": "2026-10-09T08:00:00Z"} |
| 753 | }}]); |
| 754 | let empty = json!([{"mri": "m", "presence": { |
| 755 | "availability": "Available", |
| 756 | "note": {"message": "", "expiry": "9999-12-31T23:59:59.9999999Z"} |
| 757 | }}]); |
| 758 | assert_eq!(parse_status(&expired, "m", at(12, 0)).unwrap().note, None); |
| 759 | assert_eq!(parse_status(&empty, "m", at(12, 0)).unwrap().note, None); |
| 760 | } |
| 761 | |
| 762 | #[test] |
| 763 | fn pin_marker_at_the_start_does_not_count() { |
| 764 | let (text, pinned) = split_pinned("<pinnednote></pinnednote>"); |
| 765 | assert_eq!(text, ""); |
| 766 | assert!(!pinned); |
| 767 | } |
| 768 | |
| 769 | #[test] |
| 770 | fn unknown_forced_availability_is_ignored() { |
| 771 | let body = json!([{"mri": "m", "presence": { |
| 772 | "availability": "Away", |
| 773 | "forcedAvailability": {"availability": "Mystery"} |
| 774 | }}]); |
| 775 | assert_eq!(parse_status(&body, "m", at(12, 0)).unwrap().forced, None); |
| 776 | } |
| 777 | |
| 778 | #[test] |
| 779 | fn missing_presence_is_unexpected() { |
| 780 | assert!(matches!( |
| 781 | parse_status(&json!({}), "m", at(12, 0)), |
| 782 | Err(Error::UnexpectedAnswer(_)) |
| 783 | )); |
| 784 | } |
| 785 | |
| 786 | #[tokio::test] |
| 787 | async fn work_location_puts_numbers_and_end_of_day_expiry() { |
| 788 | let service = service(200, Value::Null); |
| 789 | service |
| 790 | .set_work_location(Some((WorkLocationKind::Remote, at(21, 59)))) |
| 791 | .await |
| 792 | .unwrap(); |
| 793 | let (request, scope) = only_request(&service); |
| 794 | assert_eq!(request.method, Method::Put); |
| 795 | assert_eq!( |
| 796 | request.url, |
| 797 | "https://presence.teams.microsoft.com/v1/me/workLocation/" |
| 798 | ); |
| 799 | assert_eq!( |
| 800 | request.body, |
| 801 | Some(json!({"location": 2, "expirationTime": "2026-10-09T21:59:00.000Z"})) |
| 802 | ); |
| 803 | assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation")); |
| 804 | service |
| 805 | .set_work_location(Some((WorkLocationKind::Office, at(21, 59)))) |
| 806 | .await |
| 807 | .unwrap(); |
| 808 | let (request, _) = only_request(&service); |
| 809 | assert_eq!(request.body.unwrap()["location"], json!(1)); |
| 810 | } |
| 811 | |
| 812 | #[tokio::test] |
| 813 | async fn clearing_the_work_location_sends_zero_without_expiry() { |
| 814 | let service = service(200, Value::Null); |
| 815 | service.set_work_location(None).await.unwrap(); |
| 816 | let (request, _) = only_request(&service); |
| 817 | assert_eq!(request.body, Some(json!({"location": 0}))); |
| 818 | } |
| 819 | |
| 820 | #[test] |
| 821 | fn parses_work_location_and_hides_unknown_or_expired() { |
| 822 | let read = |location: Value| { |
| 823 | let body = json!([{"mri": "m", "presence": { |
| 824 | "availability": "Available", "workLocation": location |
| 825 | }}]); |
| 826 | parse_status(&body, "m", at(12, 0)).unwrap().work_location |
| 827 | }; |
| 828 | assert_eq!( |
| 829 | read( |
| 830 | json!({"location": "Remote", "expiry": "2026-10-09T21:59:59.9999999Z", |
| 831 | "isForced": true, "locationSource": "ForcedLocation"}) |
| 832 | ), |
| 833 | Some(WorkLocation { |
| 834 | kind: WorkLocationKind::Remote, |
| 835 | source: WorkLocationSource::Set |
| 836 | }) |
| 837 | ); |
| 838 | assert_eq!( |
| 839 | read( |
| 840 | json!({"location": "Office", "locationSource": "ScheduledLocation", |
| 841 | "expiry": "2026-10-09T21:59:59Z"}) |
| 842 | ), |
| 843 | Some(WorkLocation { |
| 844 | kind: WorkLocationKind::Office, |
| 845 | source: WorkLocationSource::Scheduled |
| 846 | }) |
| 847 | ); |
| 848 | assert_eq!( |
| 849 | read(json!({"location": "Office", "locationSource": "VerifiedLocation"})) |
| 850 | .map(|found| found.source), |
| 851 | Some(WorkLocationSource::Verified) |
| 852 | ); |
| 853 | assert_eq!(read(json!({"location": "Unknown"})), None); |
| 854 | assert_eq!(read(json!({"location": "TimeOff"})), None); |
| 855 | assert_eq!( |
| 856 | read(json!({"location": "Office", "expiry": "2026-10-09T08:00:00Z"})), |
| 857 | None |
| 858 | ); |
| 859 | } |
| 860 | |
| 861 | #[test] |
| 862 | fn note_text_is_unescaped_and_the_pin_marker_stripped() { |
| 863 | let body = json!([{"mri": "m", "presence": { |
| 864 | "availability": "Busy", |
| 865 | "note": { |
| 866 | "message": "Back at 3 & later<pinnednote></pinnednote>", |
| 867 | "expiry": "9999-12-31T23:59:59.9999999Z" |
| 868 | }, |
| 869 | "calendarData": {"isOutOfOffice": false} |
| 870 | }}]); |
| 871 | let status = parse_status(&body, "m", at(12, 0)).unwrap(); |
| 872 | assert_eq!(status.note.unwrap().text, "Back at 3 & later"); |
| 873 | assert!(!status.out_of_office); |
| 874 | assert_eq!(status.out_of_office_note, None); |
| 875 | } |
| 876 | |
| 877 | #[test] |
| 878 | fn out_of_office_carries_its_plain_text() { |
| 879 | let read = |calendar: Value| { |
| 880 | let body = json!([{"mri": "m", "presence": { |
| 881 | "availability": "Away", "calendarData": calendar |
| 882 | }}]); |
| 883 | parse_status(&body, "m", at(12, 0)).unwrap() |
| 884 | }; |
| 885 | let with_text = read( |
| 886 | json!({"isOutOfOffice": true, "outOfOfficeNote": {"message": "<p>On & leave</p>"}}), |
| 887 | ); |
| 888 | assert!(with_text.out_of_office); |
| 889 | assert_eq!(with_text.out_of_office_note.as_deref(), Some("On & leave")); |
| 890 | let bare = read(json!({"isOutOfOffice": true})); |
| 891 | assert!(bare.out_of_office); |
| 892 | assert_eq!(bare.out_of_office_note, None); |
| 893 | } |
| 894 | |
| 895 | #[test] |
| 896 | fn expiry_formats_to_milliseconds_utc() { |
| 897 | assert_eq!(format_expiry(Some(at(15, 30))), "2026-10-09T15:30:00.000Z"); |
| 898 | assert_eq!(format_expiry(None), "9999-12-31T23:59:59.999Z"); |
| 899 | } |
| 900 | } |