BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / presence.rs

presence.rs

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