BlueGit

ict rusty-teams

Files

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

presence.rs

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