Merge remote-tracking branch 'origin/main' into fix/composer-toolbar
@@ -9,7 +9,7 @@ use teams_core::EmoticonTag;
9
9
pub use strip::{StripImages, StripLoader, StripSource, split_strip};
10
10
11
11
const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");
12
const ASSET_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";
12
const ASSET_BASE: &str = chatsvc::teams_cdn::EMOTICON_BASE_URL;
13
13
const ASSET_SIZE: u32 = 100;
14
14
const FRAMES_PER_SECOND: u64 = 24;
15
15
const VARIATION_SELECTOR: char = '\u{fe0f}';
@@ -9,7 +9,7 @@ use teams_core::EmoticonTag;9
pub use strip::{StripImages, StripLoader, StripSource, split_strip};9
pub use strip::{StripImages, StripLoader, StripSource, split_strip};10
10
11
const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");11
const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");12
const ASSET_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";12
const ASSET_BASE: &str = chatsvc::teams_cdn::EMOTICON_BASE_URL;13
const ASSET_SIZE: u32 = 100;13
const ASSET_SIZE: u32 = 100;14
const FRAMES_PER_SECOND: u64 = 24;14
const FRAMES_PER_SECOND: u64 = 24;15
const VARIATION_SELECTOR: char = '\u{fe0f}';15
const VARIATION_SELECTOR: char = '\u{fe0f}';@@ -8,8 +8,7 @@ use gpui_kit::App;
8
8
9
9
use super::platform;
10
10
11
pub const TEAMS_SOUND_BASE_URL: &str =
12
"https://statics.teams.cdn.office.net/evergreen-assets/audio/";
11
pub const TEAMS_SOUND_BASE_URL: &str = chatsvc::teams_cdn::SOUND_BASE_URL;
13
12
const SOUND_DIRECTORY: &str = "sounds";
14
13
const PARTIAL_SUFFIX: &str = ".partial";
15
14
@@ -8,8 +8,7 @@ use gpui_kit::App;8
8
9
use super::platform;9
use super::platform;10
10
11
pub const TEAMS_SOUND_BASE_URL: &str =11
pub const TEAMS_SOUND_BASE_URL: &str = chatsvc::teams_cdn::SOUND_BASE_URL;12
"https://statics.teams.cdn.office.net/evergreen-assets/audio/";13
const SOUND_DIRECTORY: &str = "sounds";12
const SOUND_DIRECTORY: &str = "sounds";14
const PARTIAL_SUFFIX: &str = ".partial";13
const PARTIAL_SUFFIX: &str = ".partial";15
14
@@ -1,7 +1,7 @@
1
1
use std::sync::OnceLock;
2
2
3
3
const CATALOG: &str = include_str!("../../app/assets/stickers.tsv");
4
const IMAGE_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";
4
const IMAGE_BASE: &str = chatsvc::teams_cdn::STICKER_BASE_URL;
5
5
const IMAGE_VERSION: u32 = 5;
6
6
const POPULAR_IDS: [&str; 6] = [
7
7
"Clippy_HelloThere",
@@ -1,7 +1,7 @@1
use std::sync::OnceLock;1
use std::sync::OnceLock;2
2
3
const CATALOG: &str = include_str!("../../app/assets/stickers.tsv");3
const CATALOG: &str = include_str!("../../app/assets/stickers.tsv");4
const IMAGE_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";4
const IMAGE_BASE: &str = chatsvc::teams_cdn::STICKER_BASE_URL;5
const IMAGE_VERSION: u32 = 5;5
const IMAGE_VERSION: u32 = 5;6
const POPULAR_IDS: [&str; 6] = [6
const POPULAR_IDS: [&str; 6] = [7
"Clippy_HelloThere",7
"Clippy_HelloThere",@@ -6,8 +6,8 @@ use session::{Request, Scope, Session};
6
6
7
7
use crate::error::{Error, Result};
8
8
9
pub const CATALOG_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";
10
pub const CDN_ROOT: &str = "https://statics.teams.cdn.office.net";
9
pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;
10
pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;
11
11
const FETCH_SCOPE: &str = "Chat.Read";
12
12
const MAX_SIDE: u32 = 1920;
13
13
const CATALOG_FILE: &str = "config.json";
@@ -6,8 +6,8 @@ use session::{Request, Scope, Session};6
6
7
use crate::error::{Error, Result};7
use crate::error::{Error, Result};8
8
9
pub const CATALOG_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";9
pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;10
pub const CDN_ROOT: &str = "https://statics.teams.cdn.office.net";10
pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;11
const FETCH_SCOPE: &str = "Chat.Read";11
const FETCH_SCOPE: &str = "Chat.Read";12
const MAX_SIDE: u32 = 1920;12
const MAX_SIDE: u32 = 1920;13
const CATALOG_FILE: &str = "config.json";13
const CATALOG_FILE: &str = "config.json";@@ -97,10 +97,7 @@ pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Optio
97
97
}
98
98
99
99
pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {
100
let url = format!(
101
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
102
thread_id.replace(':', "%3A").replace('@', "%40")
103
);
100
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, thread_id);
104
101
let response = session.send(Request::get(url), &ic3_scope()).await?;
105
102
let now = std::time::SystemTime::now()
106
103
.duration_since(std::time::UNIX_EPOCH)
@@ -97,10 +97,7 @@ pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Optio97
}97
}98
98
99
pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {99
pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {100
let url = format!(100
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, thread_id);101
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",102
thread_id.replace(':', "%3A").replace('@', "%40")103
);104
let response = session.send(Request::get(url), &ic3_scope()).await?;101
let response = session.send(Request::get(url), &ic3_scope()).await?;105
let now = std::time::SystemTime::now()102
let now = std::time::SystemTime::now()106
.duration_since(std::time::UNIX_EPOCH)103
.duration_since(std::time::UNIX_EPOCH)@@ -1062,10 +1062,7 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re
1062
1062
format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
1063
1063
format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
1064
1064
] {
1065
let url = format!(
1066
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
1067
thread_id.replace(':', "%3A").replace('@', "%40")
1068
);
1065
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id);
1069
1066
let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);
1070
1067
if response.is_success() {
1071
1068
return Ok(Some(thread_id));
@@ -1062,10 +1062,7 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re1062
format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),1062
format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),1063
format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),1063
format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),1064
] {1064
] {1065
let url = format!(1065
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id);1066
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",1067
thread_id.replace(':', "%3A").replace('@', "%40")1068
);1069
let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);1066
let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);1070
if response.is_success() {1067
if response.is_success() {1071
return Ok(Some(thread_id));1068
return Ok(Some(thread_id));@@ -118,6 +118,14 @@ impl<T: MessageTransport> Conversations<T> {
118
118
}
119
119
}
120
120
121
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122
pub fn thread_url(region: &str, thread_id: &str) -> String {
123
format!(
124
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
125
thread_id.replace(':', "%3A").replace('@', "%40")
126
)
127
}
128
121
129
fn backward_link(body: &Value) -> Option<String> {
122
130
body.pointer("/_metadata/backwardLink")
123
131
.and_then(Value::as_str)
@@ -208,6 +216,14 @@ mod tests {
208
216
209
217
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";
210
218
219
#[test]
220
fn thread_url_escapes_the_thread_id() {
221
assert_eq!(
222
thread_url("emea", "19:meeting_a@thread.v2"),
223
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Ameeting_a%40thread.v2?view=msnp24Equivalent"
224
);
225
}
226
211
227
#[tokio::test]
212
228
async fn mute_states_pair_every_conversation_with_its_flag() {
213
229
let transport = canned(vec![(
@@ -118,6 +118,14 @@ impl<T: MessageTransport> Conversations<T> {118
}118
}119
}119
}120
120
121
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.122
pub fn thread_url(region: &str, thread_id: &str) -> String {123
format!(124
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}?view=msnp24Equivalent",125
thread_id.replace(':', "%3A").replace('@', "%40")126
)127
}128
121
fn backward_link(body: &Value) -> Option<String> {129
fn backward_link(body: &Value) -> Option<String> {122
body.pointer("/_metadata/backwardLink")130
body.pointer("/_metadata/backwardLink")123
.and_then(Value::as_str)131
.and_then(Value::as_str)@@ -208,6 +216,14 @@ mod tests {208
216
209
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";217
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";210
218
219
#[test]220
fn thread_url_escapes_the_thread_id() {221
assert_eq!(222
thread_url("emea", "19:meeting_a@thread.v2"),223
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Ameeting_a%40thread.v2?view=msnp24Equivalent"224
);225
}226
211
#[tokio::test]227
#[tokio::test]212
async fn mute_states_pair_every_conversation_with_its_flag() {228
async fn mute_states_pair_every_conversation_with_its_flag() {213
let transport = canned(vec![(229
let transport = canned(vec![(@@ -27,6 +27,7 @@ pub mod settings;
27
27
pub mod sound_settings;
28
28
pub mod sounds;
29
29
pub mod substrate_search;
30
pub mod teams_cdn;
30
31
pub mod transcripts;
31
32
pub mod translate;
32
33
pub mod window;
@@ -59,8 +60,9 @@ pub use pins::{
59
60
PinnedMessage, Pins, TeamLayout,
60
61
};
61
62
pub use presence::{
62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
63
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
63
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,
64
PresenceStatus, StatusNote, UserPresence, WorkLocation, WorkLocationKind, WorkLocationSource,
65
error_status, is_endpoint_missing,
64
66
};
65
67
pub use reactions::{
66
68
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
@@ -27,6 +27,7 @@ pub mod settings;27
pub mod sound_settings;27
pub mod sound_settings;28
pub mod sounds;28
pub mod sounds;29
pub mod substrate_search;29
pub mod substrate_search;30
pub mod teams_cdn;30
pub mod transcripts;31
pub mod transcripts;31
pub mod translate;32
pub mod translate;32
pub mod window;33
pub mod window;@@ -59,8 +60,9 @@ pub use pins::{59
PinnedMessage, Pins, TeamLayout,60
PinnedMessage, Pins, TeamLayout,60
};61
};61
pub use presence::{62
pub use presence::{62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,63
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,63
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,64
PresenceStatus, StatusNote, UserPresence, WorkLocation, WorkLocationKind, WorkLocationSource,65
error_status, is_endpoint_missing,64
};66
};65
pub use reactions::{67
pub use reactions::{66
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,68
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,@@ -7,7 +7,7 @@ use crate::error::{Error, Result};
7
7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};
8
8
9
9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";
10
const IMAGE_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
10
pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11
11
const LIST_VIEW: &str = "msnp24Equivalent";
12
12
13
13
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -36,7 +36,7 @@ pub struct LinkImage {
36
36
pub fn is_link_image_url(url: &str) -> bool {
37
37
url.strip_prefix("https://")
38
38
.and_then(|rest| rest.split(['/', '?', '#']).next())
39
.is_some_and(|host| host.ends_with(IMAGE_HOST_SUFFIX))
39
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))
40
40
}
41
41
42
42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {
@@ -7,7 +7,7 @@ use crate::error::{Error, Result};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};8
8
9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";10
const IMAGE_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";10
pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";11
const LIST_VIEW: &str = "msnp24Equivalent";11
const LIST_VIEW: &str = "msnp24Equivalent";12
12
13
#[derive(Debug, Clone, PartialEq, Eq)]13
#[derive(Debug, Clone, PartialEq, Eq)]@@ -36,7 +36,7 @@ pub struct LinkImage {36
pub fn is_link_image_url(url: &str) -> bool {36
pub fn is_link_image_url(url: &str) -> bool {37
url.strip_prefix("https://")37
url.strip_prefix("https://")38
.and_then(|rest| rest.split(['/', '?', '#']).next())38
.and_then(|rest| rest.split(['/', '?', '#']).next())39
.is_some_and(|host| host.ends_with(IMAGE_HOST_SUFFIX))39
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))40
}40
}41
41
42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {@@ -6,6 +6,10 @@ use uuid::Uuid;
6
6
use crate::cards::{CardTransport, SessionCardTransport};
7
7
use crate::error::{Error, Result};
8
8
9
mod lookup;
10
11
pub use lookup::{MAX_PRESENCE_IDS, PresenceLookup, UserPresence};
12
9
13
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";
10
14
const PRESENCE_SCOPE: &str = "user_impersonation";
11
15
const CLIENT_VERSION: &str = "1415/26091712213";
@@ -6,6 +6,10 @@ use uuid::Uuid;6
use crate::cards::{CardTransport, SessionCardTransport};6
use crate::cards::{CardTransport, SessionCardTransport};7
use crate::error::{Error, Result};7
use crate::error::{Error, Result};8
8
9
mod lookup;10
11
pub use lookup::{MAX_PRESENCE_IDS, PresenceLookup, UserPresence};12
9
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";13
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";10
const PRESENCE_SCOPE: &str = "user_impersonation";14
const PRESENCE_SCOPE: &str = "user_impersonation";11
const CLIENT_VERSION: &str = "1415/26091712213";15
const CLIENT_VERSION: &str = "1415/26091712213";@@ -0,0 +1,187 @@
1
use serde_json::{Value, json};
2
use session::{Method, PRESENCE, Request, Scope, Session};
3
use uuid::Uuid;
4
5
use crate::error::Result;
6
7
pub const MAX_PRESENCE_IDS: usize = 650;
8
pub const MAX_SUBSCRIBE_IDS: usize = 200;
9
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
10
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
11
const PRESENCE_SUBSCRIBE_URL: &str =
12
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
13
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
14
const ORGID_PREFIX: &str = "8:orgid:";
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct UserPresence {
18
pub user_id: String,
19
pub availability: String,
20
pub activity: Option<String>,
21
}
22
23
pub struct PresenceLookup {
24
session: Session,
25
}
26
27
impl PresenceLookup {
28
pub fn new(session: &Session) -> Self {
29
PresenceLookup {
30
session: session.clone(),
31
}
32
}
33
34
/// Graph `Presence.Read.All` is not in the web app tokens.
35
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<UserPresence>> {
36
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
37
let mut presences = Vec::with_capacity(user_ids.len());
38
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {
39
let body: Vec<Value> = chunk
40
.iter()
41
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))
42
.collect();
43
let answer = self
44
.session
45
.request(
46
Method::Post,
47
PRESENCE_SERVICE_URL,
48
&scope,
49
Some(Value::Array(body)),
50
)
51
.await?;
52
presences.extend(parse_service_presences(&answer.body));
53
}
54
Ok(presences)
55
}
56
57
pub async fn subscribe(
58
&self,
59
endpoint_id: &str,
60
trouter_uri: &str,
61
user_ids: &[String],
62
purge: bool,
63
) -> Result<()> {
64
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
65
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
66
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
67
let request = Request {
68
method: Method::Post,
69
headers: subscribe_headers(endpoint_id),
70
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
71
..Request::get(url.clone())
72
};
73
let answer = self.session.send(request, &scope).await?;
74
if !(200..300).contains(&answer.status) {
75
return Err(session::Error::api(answer.status, &url, answer.body).into());
76
}
77
}
78
Ok(())
79
}
80
}
81
82
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.
83
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
84
vec![
85
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
86
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
87
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
88
("x-ms-endpoint-id".into(), endpoint_id.into()),
89
("x-ms-client-type".into(), "cdlworker".into()),
90
]
91
}
92
93
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
94
let additions: Vec<Value> = user_ids
95
.iter()
96
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
97
.collect();
98
json!({
99
"trouterUri": trouter_uri,
100
"shouldPurgePreviousSubscriptions": purge,
101
"subscriptionsToAdd": additions,
102
"subscriptionsToRemove": [],
103
})
104
}
105
106
fn parse_service_presences(body: &Value) -> Vec<UserPresence> {
107
body.as_array()
108
.into_iter()
109
.flatten()
110
.filter_map(|entry| {
111
let mri = entry.get("mri")?.as_str()?;
112
let presence = entry.get("presence")?;
113
Some(UserPresence {
114
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),
115
availability: presence.get("availability")?.as_str()?.to_owned(),
116
activity: if presence
117
.pointer("/calendarData/isOutOfOffice")
118
.and_then(Value::as_bool)
119
.unwrap_or(false)
120
{
121
Some("OutOfOffice".to_owned())
122
} else {
123
presence
124
.get("activity")
125
.and_then(Value::as_str)
126
.map(str::to_owned)
127
},
128
})
129
})
130
.collect()
131
}
132
133
#[cfg(test)]
134
mod tests {
135
use super::*;
136
137
#[test]
138
fn subscribe_body_carries_mris_and_purge_flag() {
139
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
140
assert_eq!(
141
body,
142
json!({
143
"trouterUri": "https://t/unifiedPresenceService",
144
"shouldPurgePreviousSubscriptions": true,
145
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
146
"subscriptionsToRemove": [],
147
})
148
);
149
}
150
151
#[test]
152
fn subscribe_headers_use_a_fresh_correlation_id() {
153
let correlation = |headers: &[(String, String)]| {
154
headers
155
.iter()
156
.find(|(name, _)| name == "x-ms-correlation-id")
157
.map(|(_, value)| value.clone())
158
};
159
let first = subscribe_headers("e");
160
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
161
assert!(
162
first
163
.iter()
164
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
165
);
166
}
167
168
#[test]
169
fn service_presences_strip_the_mri_prefix() {
170
let parsed = parse_service_presences(&json!([
171
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},
172
{"mri": "8:orgid:b"}
173
]));
174
assert_eq!(parsed.len(), 1);
175
assert_eq!(parsed[0].user_id, "a");
176
}
177
178
#[test]
179
fn out_of_office_from_the_calendar_becomes_the_activity() {
180
let parsed = parse_service_presences(&json!([
181
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},
182
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}
183
]));
184
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));
185
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));
186
}
187
}
@@ -0,0 +1,187 @@1
use serde_json::{Value, json};2
use session::{Method, PRESENCE, Request, Scope, Session};3
use uuid::Uuid;4
5
use crate::error::Result;6
7
pub const MAX_PRESENCE_IDS: usize = 650;8
pub const MAX_SUBSCRIBE_IDS: usize = 200;9
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";10
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";11
const PRESENCE_SUBSCRIBE_URL: &str =12
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";13
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";14
const ORGID_PREFIX: &str = "8:orgid:";15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct UserPresence {18
pub user_id: String,19
pub availability: String,20
pub activity: Option<String>,21
}22
23
pub struct PresenceLookup {24
session: Session,25
}26
27
impl PresenceLookup {28
pub fn new(session: &Session) -> Self {29
PresenceLookup {30
session: session.clone(),31
}32
}33
34
/// Graph `Presence.Read.All` is not in the web app tokens.35
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<UserPresence>> {36
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);37
let mut presences = Vec::with_capacity(user_ids.len());38
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {39
let body: Vec<Value> = chunk40
.iter()41
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))42
.collect();43
let answer = self44
.session45
.request(46
Method::Post,47
PRESENCE_SERVICE_URL,48
&scope,49
Some(Value::Array(body)),50
)51
.await?;52
presences.extend(parse_service_presences(&answer.body));53
}54
Ok(presences)55
}56
57
pub async fn subscribe(58
&self,59
endpoint_id: &str,60
trouter_uri: &str,61
user_ids: &[String],62
purge: bool,63
) -> Result<()> {64
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);65
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");66
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {67
let request = Request {68
method: Method::Post,69
headers: subscribe_headers(endpoint_id),70
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),71
..Request::get(url.clone())72
};73
let answer = self.session.send(request, &scope).await?;74
if !(200..300).contains(&answer.status) {75
return Err(session::Error::api(answer.status, &url, answer.body).into());76
}77
}78
Ok(())79
}80
}81
82
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.83
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {84
vec![85
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),86
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),87
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),88
("x-ms-endpoint-id".into(), endpoint_id.into()),89
("x-ms-client-type".into(), "cdlworker".into()),90
]91
}92
93
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {94
let additions: Vec<Value> = user_ids95
.iter()96
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))97
.collect();98
json!({99
"trouterUri": trouter_uri,100
"shouldPurgePreviousSubscriptions": purge,101
"subscriptionsToAdd": additions,102
"subscriptionsToRemove": [],103
})104
}105
106
fn parse_service_presences(body: &Value) -> Vec<UserPresence> {107
body.as_array()108
.into_iter()109
.flatten()110
.filter_map(|entry| {111
let mri = entry.get("mri")?.as_str()?;112
let presence = entry.get("presence")?;113
Some(UserPresence {114
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),115
availability: presence.get("availability")?.as_str()?.to_owned(),116
activity: if presence117
.pointer("/calendarData/isOutOfOffice")118
.and_then(Value::as_bool)119
.unwrap_or(false)120
{121
Some("OutOfOffice".to_owned())122
} else {123
presence124
.get("activity")125
.and_then(Value::as_str)126
.map(str::to_owned)127
},128
})129
})130
.collect()131
}132
133
#[cfg(test)]134
mod tests {135
use super::*;136
137
#[test]138
fn subscribe_body_carries_mris_and_purge_flag() {139
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);140
assert_eq!(141
body,142
json!({143
"trouterUri": "https://t/unifiedPresenceService",144
"shouldPurgePreviousSubscriptions": true,145
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],146
"subscriptionsToRemove": [],147
})148
);149
}150
151
#[test]152
fn subscribe_headers_use_a_fresh_correlation_id() {153
let correlation = |headers: &[(String, String)]| {154
headers155
.iter()156
.find(|(name, _)| name == "x-ms-correlation-id")157
.map(|(_, value)| value.clone())158
};159
let first = subscribe_headers("e");160
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));161
assert!(162
first163
.iter()164
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")165
);166
}167
168
#[test]169
fn service_presences_strip_the_mri_prefix() {170
let parsed = parse_service_presences(&json!([171
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},172
{"mri": "8:orgid:b"}173
]));174
assert_eq!(parsed.len(), 1);175
assert_eq!(parsed[0].user_id, "a");176
}177
178
#[test]179
fn out_of_office_from_the_calendar_becomes_the_activity() {180
let parsed = parse_service_presences(&json!([181
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},182
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}183
]));184
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));185
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));186
}187
}@@ -0,0 +1,29 @@
1
pub const HOST: &str = "statics.teams.cdn.office.net";
2
pub const ROOT: &str = "https://statics.teams.cdn.office.net";
3
pub const SOUND_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/audio/";
4
pub const STICKER_BASE_URL: &str =
5
"https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";
6
pub const EMOTICON_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";
7
pub const BACKGROUND_CATALOG_URL: &str =
8
"https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";
9
10
#[cfg(test)]
11
mod tests {
12
use super::*;
13
14
#[test]
15
fn every_url_lives_on_the_cdn_root() {
16
assert_eq!(ROOT, format!("https://{HOST}"));
17
for url in [
18
SOUND_BASE_URL,
19
STICKER_BASE_URL,
20
EMOTICON_BASE_URL,
21
BACKGROUND_CATALOG_URL,
22
] {
23
assert!(
24
url.starts_with(&format!("{ROOT}/evergreen-assets/")),
25
"{url}"
26
);
27
}
28
}
29
}
@@ -0,0 +1,29 @@1
pub const HOST: &str = "statics.teams.cdn.office.net";2
pub const ROOT: &str = "https://statics.teams.cdn.office.net";3
pub const SOUND_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/audio/";4
pub const STICKER_BASE_URL: &str =5
"https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";6
pub const EMOTICON_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";7
pub const BACKGROUND_CATALOG_URL: &str =8
"https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";9
10
#[cfg(test)]11
mod tests {12
use super::*;13
14
#[test]15
fn every_url_lives_on_the_cdn_root() {16
assert_eq!(ROOT, format!("https://{HOST}"));17
for url in [18
SOUND_BASE_URL,19
STICKER_BASE_URL,20
EMOTICON_BASE_URL,21
BACKGROUND_CATALOG_URL,22
] {23
assert!(24
url.starts_with(&format!("{ROOT}/evergreen-assets/")),25
"{url}"26
);27
}28
}29
}@@ -0,0 +1,123 @@
1
use std::fs;
2
use std::path::{Path, PathBuf};
3
4
const NON_GRAPH_HOSTS: &[&str] = &[
5
"cloud.microsoft",
6
"microsoft.com",
7
"office.com",
8
"office.net",
9
"skype.com",
10
"live.com",
11
"sharepoint.com",
12
"microsoftonline.com",
13
"microsoft365.com",
14
"giphy.com",
15
];
16
17
const NOT_A_SERVICE: &[&str] = &["graph.microsoft.com", "schema.skype.com"];
18
19
const ALLOWED_PATHS: &[(&str, &str)] = &[
20
("chatsvc/", "Teams service clients, one module per service"),
21
("calling/src/signaling.rs", "call signaling and flightproxy"),
22
("calling/src/relay.rs", "TURN relay tokens"),
23
("calling/src/meeting_options.rs", "meeting options MT"),
24
("calling/src/whiteboard.rs", "meeting whiteboard MT"),
25
("calling/src/breakout.rs", "breakout room join link parsing"),
26
("calling/assets/", "in-page caption bot command"),
27
(
28
"session/",
29
"sign-in, token refresh, page hosts, token audiences",
30
),
31
("browser/", "headless browser page targets"),
32
("webview/", "WebView2 page hosts"),
33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),
34
("core/src/links.rs", "link classification"),
35
("core/src/meeting_join.rs", "meeting join link parsing"),
36
("core/src/message_link.rs", "message link parsing"),
37
("core/src/call_event.rs", "recording link host check"),
38
("core/src/external_image.rs", "GIF host check"),
39
("app-call-model/src/agenda.rs", "demo join link"),
40
("app-call-model/src/demo.rs", "demo data"),
41
("app-state/src/demo.rs", "demo data"),
42
("app-base/src/demo_", "demo data"),
43
("app/src/layout_guard.rs", "layout test fixture"),
44
("graph/src/tabs.rs", "channel tab web links"),
45
];
46
47
#[test]
48
fn non_graph_hosts_stay_in_their_service_modules() {
49
let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
50
let mut files = Vec::new();
51
source_files(&crates_directory, &mut files);
52
let mut offenders = Vec::new();
53
for file in files {
54
let relative = file
55
.strip_prefix(&crates_directory)
56
.expect("file below crates")
57
.to_string_lossy()
58
.replace('\\', "/");
59
if ALLOWED_PATHS
60
.iter()
61
.any(|(prefix, _)| relative.starts_with(prefix))
62
{
63
continue;
64
}
65
let source = fs::read_to_string(&file).expect("read source file");
66
for (index, line) in production_lines(&source) {
67
if names_non_graph_host(line) {
68
offenders.push(format!("{relative}:{}: {}", index + 1, line.trim()));
69
}
70
}
71
}
72
assert!(
73
offenders.is_empty(),
74
"non-Graph hosts outside their service modules (move them or extend ALLOWED_PATHS and docs/research/internal-endpoints.md):\n{}",
75
offenders.join("\n")
76
);
77
}
78
79
fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
80
for entry in fs::read_dir(directory).expect("read source directory") {
81
let path = entry.expect("directory entry").path();
82
let name = path
83
.file_name()
84
.and_then(|name| name.to_str())
85
.unwrap_or("");
86
if path.is_dir() {
87
if !matches!(name, "tests" | "examples" | "target" | "benches") {
88
source_files(&path, files);
89
}
90
} else if (name.ends_with(".rs") || name.ends_with(".js")) && name != "tests.rs" {
91
files.push(path);
92
}
93
}
94
}
95
96
fn production_lines(source: &str) -> impl Iterator<Item = (usize, &str)> {
97
source
98
.lines()
99
.enumerate()
100
.take_while(|(_, line)| line.trim() != "#[cfg(test)]")
101
.filter(|(_, line)| !line.trim_start().starts_with("//"))
102
}
103
104
fn names_non_graph_host(line: &str) -> bool {
105
let mut cleaned = line.to_owned();
106
for host in NOT_A_SERVICE {
107
cleaned = cleaned.replace(host, "");
108
}
109
NON_GRAPH_HOSTS.iter().any(|host| cleaned.contains(host))
110
}
111
112
#[test]
113
fn host_check_ignores_graph_and_markup() {
114
assert!(!names_non_graph_host(
115
r#"const GRAPH: &str = "https://graph.microsoft.com";"#
116
));
117
assert!(!names_non_graph_host(
118
r#"itemtype="http://schema.skype.com/Mention""#
119
));
120
assert!(names_non_graph_host(
121
r#"format!("https://teams.cloud.microsoft/api/mt/{region}")"#
122
));
123
}
@@ -0,0 +1,123 @@1
use std::fs;2
use std::path::{Path, PathBuf};3
4
const NON_GRAPH_HOSTS: &[&str] = &[5
"cloud.microsoft",6
"microsoft.com",7
"office.com",8
"office.net",9
"skype.com",10
"live.com",11
"sharepoint.com",12
"microsoftonline.com",13
"microsoft365.com",14
"giphy.com",15
];16
17
const NOT_A_SERVICE: &[&str] = &["graph.microsoft.com", "schema.skype.com"];18
19
const ALLOWED_PATHS: &[(&str, &str)] = &[20
("chatsvc/", "Teams service clients, one module per service"),21
("calling/src/signaling.rs", "call signaling and flightproxy"),22
("calling/src/relay.rs", "TURN relay tokens"),23
("calling/src/meeting_options.rs", "meeting options MT"),24
("calling/src/whiteboard.rs", "meeting whiteboard MT"),25
("calling/src/breakout.rs", "breakout room join link parsing"),26
("calling/assets/", "in-page caption bot command"),27
(28
"session/",29
"sign-in, token refresh, page hosts, token audiences",30
),31
("browser/", "headless browser page targets"),32
("webview/", "WebView2 page hosts"),33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),34
("core/src/links.rs", "link classification"),35
("core/src/meeting_join.rs", "meeting join link parsing"),36
("core/src/message_link.rs", "message link parsing"),37
("core/src/call_event.rs", "recording link host check"),38
("core/src/external_image.rs", "GIF host check"),39
("app-call-model/src/agenda.rs", "demo join link"),40
("app-call-model/src/demo.rs", "demo data"),41
("app-state/src/demo.rs", "demo data"),42
("app-base/src/demo_", "demo data"),43
("app/src/layout_guard.rs", "layout test fixture"),44
("graph/src/tabs.rs", "channel tab web links"),45
];46
47
#[test]48
fn non_graph_hosts_stay_in_their_service_modules() {49
let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");50
let mut files = Vec::new();51
source_files(&crates_directory, &mut files);52
let mut offenders = Vec::new();53
for file in files {54
let relative = file55
.strip_prefix(&crates_directory)56
.expect("file below crates")57
.to_string_lossy()58
.replace('\\', "/");59
if ALLOWED_PATHS60
.iter()61
.any(|(prefix, _)| relative.starts_with(prefix))62
{63
continue;64
}65
let source = fs::read_to_string(&file).expect("read source file");66
for (index, line) in production_lines(&source) {67
if names_non_graph_host(line) {68
offenders.push(format!("{relative}:{}: {}", index + 1, line.trim()));69
}70
}71
}72
assert!(73
offenders.is_empty(),74
"non-Graph hosts outside their service modules (move them or extend ALLOWED_PATHS and docs/research/internal-endpoints.md):\n{}",75
offenders.join("\n")76
);77
}78
79
fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {80
for entry in fs::read_dir(directory).expect("read source directory") {81
let path = entry.expect("directory entry").path();82
let name = path83
.file_name()84
.and_then(|name| name.to_str())85
.unwrap_or("");86
if path.is_dir() {87
if !matches!(name, "tests" | "examples" | "target" | "benches") {88
source_files(&path, files);89
}90
} else if (name.ends_with(".rs") || name.ends_with(".js")) && name != "tests.rs" {91
files.push(path);92
}93
}94
}95
96
fn production_lines(source: &str) -> impl Iterator<Item = (usize, &str)> {97
source98
.lines()99
.enumerate()100
.take_while(|(_, line)| line.trim() != "#[cfg(test)]")101
.filter(|(_, line)| !line.trim_start().starts_with("//"))102
}103
104
fn names_non_graph_host(line: &str) -> bool {105
let mut cleaned = line.to_owned();106
for host in NOT_A_SERVICE {107
cleaned = cleaned.replace(host, "");108
}109
NON_GRAPH_HOSTS.iter().any(|host| cleaned.contains(host))110
}111
112
#[test]113
fn host_check_ignores_graph_and_markup() {114
assert!(!names_non_graph_host(115
r#"const GRAPH: &str = "https://graph.microsoft.com";"#116
));117
assert!(!names_non_graph_host(118
r#"itemtype="http://schema.skype.com/Mention""#119
));120
assert!(names_non_graph_host(121
r#"format!("https://teams.cloud.microsoft/api/mt/{region}")"#122
));123
}@@ -1,9 +1,9 @@
1
1
use url::Url;
2
2
3
3
const PROXY_PATH: &str = "/urlp/v1/url/content";
4
const PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
4
const PROXY_HOST_SUFFIX: &str = chatsvc::links::LINK_PROXY_HOST_SUFFIX;
5
5
const GIPHY_HOST: &str = "giphy.com";
6
const TEAMS_CDN_HOST: &str = "statics.teams.cdn.office.net";
6
const TEAMS_CDN_HOST: &str = chatsvc::teams_cdn::HOST;
7
7
8
8
/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.
9
9
pub fn external_image_url(src: &str) -> Option<String> {
@@ -1,9 +1,9 @@1
use url::Url;1
use url::Url;2
2
3
const PROXY_PATH: &str = "/urlp/v1/url/content";3
const PROXY_PATH: &str = "/urlp/v1/url/content";4
const PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";4
const PROXY_HOST_SUFFIX: &str = chatsvc::links::LINK_PROXY_HOST_SUFFIX;5
const GIPHY_HOST: &str = "giphy.com";5
const GIPHY_HOST: &str = "giphy.com";6
const TEAMS_CDN_HOST: &str = "statics.teams.cdn.office.net";6
const TEAMS_CDN_HOST: &str = chatsvc::teams_cdn::HOST;7
7
8
/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.8
/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.9
pub fn external_image_url(src: &str) -> Option<String> {9
pub fn external_image_url(src: &str) -> Option<String> {@@ -1,8 +1,8 @@
1
use chatsvc::presence::MAX_PRESENCE_IDS;
1
2
use chatsvc::{
2
3
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,
3
4
WorkLocationKind,
4
5
};
5
use graph::MAX_PRESENCE_IDS;
6
6
7
7
use chrono::{DateTime, Utc};
8
8
@@ -1,8 +1,8 @@1
use chatsvc::presence::MAX_PRESENCE_IDS;1
use chatsvc::{2
use chatsvc::{2
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,3
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,3
WorkLocationKind,4
WorkLocationKind,4
};5
};5
use graph::MAX_PRESENCE_IDS;6
6
7
use chrono::{DateTime, Utc};7
use chrono::{DateTime, Utc};8
8
@@ -1,16 +1,16 @@
1
use chatsvc::{
2
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState,
3
Conversations,
4
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
5
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
6
MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
7
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,
8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
9
};
10
1
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
11
2
use chatsvc::substrate_search::{
12
3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
13
4
};
5
use chatsvc::{
6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,
8
InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,
9
MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,
10
PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,
11
ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,
12
Translator, WindowDirection, WorkLocationKind,
13
};
14
14
use chrono::{DateTime, Utc};
15
15
use graph::{
16
16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
@@ -875,7 +875,17 @@ impl Remote for Graph {
875
875
}
876
876
877
877
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
878
Ok(Graph::presences(self, user_ids).await?)
878
let found = PresenceLookup::new(self.session())
879
.presences(user_ids)
880
.await?;
881
Ok(found
882
.into_iter()
883
.map(|presence| Presence {
884
user_id: presence.user_id,
885
availability: presence.availability,
886
activity: presence.activity,
887
})
888
.collect())
879
889
}
880
890
881
891
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {
@@ -893,7 +903,9 @@ impl Remote for Graph {
893
903
user_ids: &[String],
894
904
purge: bool,
895
905
) -> Result<()> {
896
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)
906
Ok(PresenceLookup::new(self.session())
907
.subscribe(endpoint_id, trouter_uri, user_ids, purge)
908
.await?)
897
909
}
898
910
899
911
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {
@@ -1032,7 +1044,11 @@ impl Remote for Graph {
1032
1044
page_size: usize,
1033
1045
) -> Result<Vec<MessageEmotions>> {
1034
1046
Ok(Messages::new(self.session())
1035
.message_emotions(&conversation.conversation_id(), newest_message_id, page_size)
1047
.message_emotions(
1048
&conversation.conversation_id(),
1049
newest_message_id,
1050
page_size,
1051
)
1036
1052
.await?)
1037
1053
}
1038
1054
@@ -1,16 +1,16 @@1
use chatsvc::{2
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState,3
Conversations,4
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,5
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,6
MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,7
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,9
};10
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};1
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};11
use chatsvc::substrate_search::{2
use chatsvc::substrate_search::{12
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,13
};4
};5
use chatsvc::{6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,8
InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,9
MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,10
PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,11
ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,12
Translator, WindowDirection, WorkLocationKind,13
};14
use chrono::{DateTime, Utc};14
use chrono::{DateTime, Utc};15
use graph::{15
use graph::{16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,@@ -875,7 +875,17 @@ impl Remote for Graph {875
}875
}876
876
877
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {877
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {878
Ok(Graph::presences(self, user_ids).await?)878
let found = PresenceLookup::new(self.session())879
.presences(user_ids)880
.await?;881
Ok(found882
.into_iter()883
.map(|presence| Presence {884
user_id: presence.user_id,885
availability: presence.availability,886
activity: presence.activity,887
})888
.collect())879
}889
}880
890
881
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {891
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {@@ -893,7 +903,9 @@ impl Remote for Graph {893
user_ids: &[String],903
user_ids: &[String],894
purge: bool,904
purge: bool,895
) -> Result<()> {905
) -> Result<()> {896
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)906
Ok(PresenceLookup::new(self.session())907
.subscribe(endpoint_id, trouter_uri, user_ids, purge)908
.await?)897
}909
}898
910
899
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {911
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {@@ -1032,7 +1044,11 @@ impl Remote for Graph {1032
page_size: usize,1044
page_size: usize,1033
) -> Result<Vec<MessageEmotions>> {1045
) -> Result<Vec<MessageEmotions>> {1034
Ok(Messages::new(self.session())1046
Ok(Messages::new(self.session())1035
.message_emotions(&conversation.conversation_id(), newest_message_id, page_size)1047
.message_emotions(1048
&conversation.conversation_id(),1049
newest_message_id,1050
page_size,1051
)1036
.await?)1052
.await?)1037
}1053
}1038
1054
@@ -69,22 +69,6 @@ async fn main() {
69
69
}
70
70
Err(error) => println!("photos failed: {}", status_of(&error)),
71
71
}
72
73
let started = Instant::now();
74
match graph.presences(&user_ids).await {
75
Ok(found) => {
76
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
77
for presence in &found {
78
*counts.entry(presence.availability.clone()).or_default() += 1;
79
}
80
println!(
81
"teams presence ok {} {counts:?} in {} ms",
82
found.len(),
83
started.elapsed().as_millis()
84
);
85
}
86
Err(error) => println!("teams presence failed: {}", status_of(&error)),
87
}
88
72
}
89
73
90
74
fn status_of(error: &graph::Error) -> String {
@@ -69,22 +69,6 @@ async fn main() {69
}69
}70
Err(error) => println!("photos failed: {}", status_of(&error)),70
Err(error) => println!("photos failed: {}", status_of(&error)),71
}71
}72
73
let started = Instant::now();74
match graph.presences(&user_ids).await {75
Ok(found) => {76
let mut counts: BTreeMap<String, usize> = BTreeMap::new();77
for presence in &found {78
*counts.entry(presence.availability.clone()).or_default() += 1;79
}80
println!(81
"teams presence ok {} {counts:?} in {} ms",82
found.len(),83
started.elapsed().as_millis()84
);85
}86
Err(error) => println!("teams presence failed: {}", status_of(&error)),87
}88
}72
}89
73
90
fn status_of(error: &graph::Error) -> String {74
fn status_of(error: &graph::Error) -> String {@@ -30,6 +30,5 @@ pub use outgoing::{
30
30
hosted_image_order,
31
31
};
32
32
pub use page::Page;
33
pub use people::MAX_PRESENCE_IDS;
34
33
pub use profile::{OrgPerson, ProfileDetails, UserProfile};
35
34
pub use target::MessageTarget;
@@ -30,6 +30,5 @@ pub use outgoing::{30
hosted_image_order,30
hosted_image_order,31
};31
};32
pub use page::Page;32
pub use page::Page;33
pub use people::MAX_PRESENCE_IDS;34
pub use profile::{OrgPerson, ProfileDetails, UserProfile};33
pub use profile::{OrgPerson, ProfileDetails, UserProfile};35
pub use target::MessageTarget;34
pub use target::MessageTarget;@@ -1,24 +1,14 @@
1
1
use base64::Engine as _;
2
2
use base64::engine::general_purpose::STANDARD;
3
3
use serde::Deserialize;
4
use serde_json::{Value, json};
5
use session::{ApiResponse, Method, PRESENCE, Request, Scope};
6
use uuid::Uuid;
4
use session::{ApiResponse, Request, Scope};
7
5
8
6
use crate::client::{BATCH_SIZE, Graph};
9
7
use crate::error::{Error, Result};
10
use crate::models::{Photo, Presence};
8
use crate::models::Photo;
11
9
use crate::urls;
12
10
13
pub const MAX_PRESENCE_IDS: usize = 650;
14
pub const MAX_SUBSCRIBE_IDS: usize = 200;
15
11
const PHOTO_SCOPE: &str = "User.ReadBasic.All";
16
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
17
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
18
const PRESENCE_SUBSCRIBE_URL: &str =
19
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
20
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
21
const ORGID_PREFIX: &str = "8:orgid:";
22
12
23
13
#[derive(Debug, Deserialize)]
24
14
struct BinaryBody {
@@ -47,77 +37,6 @@ impl Graph {
47
37
}
48
38
Ok(photos)
49
39
}
50
51
/// Teams presence service. Graph `Presence.Read.All` is not in the web app tokens.
52
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
53
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
54
let mut presences = Vec::with_capacity(user_ids.len());
55
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {
56
let body: Vec<Value> = chunk
57
.iter()
58
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))
59
.collect();
60
let answer = self
61
.session()
62
.request(
63
Method::Post,
64
PRESENCE_SERVICE_URL,
65
&scope,
66
Some(Value::Array(body)),
67
)
68
.await?;
69
presences.extend(parse_service_presences(&answer.body));
70
}
71
Ok(presences)
72
}
73
74
pub async fn subscribe_presence(
75
&self,
76
endpoint_id: &str,
77
trouter_uri: &str,
78
user_ids: &[String],
79
purge: bool,
80
) -> Result<()> {
81
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
82
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
83
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
84
let request = Request {
85
method: Method::Post,
86
headers: subscribe_headers(endpoint_id),
87
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
88
..Request::get(url.clone())
89
};
90
let answer = self.session().send(request, &scope).await?;
91
if !(200..300).contains(&answer.status) {
92
return Err(session::Error::api(answer.status, &url, answer.body).into());
93
}
94
}
95
Ok(())
96
}
97
}
98
99
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.
100
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
101
vec![
102
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
103
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
104
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
105
("x-ms-endpoint-id".into(), endpoint_id.into()),
106
("x-ms-client-type".into(), "cdlworker".into()),
107
]
108
}
109
110
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
111
let additions: Vec<Value> = user_ids
112
.iter()
113
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
114
.collect();
115
json!({
116
"trouterUri": trouter_uri,
117
"shouldPurgePreviousSubscriptions": purge,
118
"subscriptionsToAdd": additions,
119
"subscriptionsToRemove": [],
120
})
121
40
}
122
41
123
42
fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
@@ -143,35 +62,10 @@ pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {
143
62
}
144
63
}
145
64
146
fn parse_service_presences(body: &Value) -> Vec<Presence> {
147
body.as_array()
148
.into_iter()
149
.flatten()
150
.filter_map(|entry| {
151
let mri = entry.get("mri")?.as_str()?;
152
let presence = entry.get("presence")?;
153
Some(Presence {
154
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),
155
availability: presence.get("availability")?.as_str()?.to_owned(),
156
activity: if presence
157
.pointer("/calendarData/isOutOfOffice")
158
.and_then(Value::as_bool)
159
.unwrap_or(false)
160
{
161
Some("OutOfOffice".to_owned())
162
} else {
163
presence
164
.get("activity")
165
.and_then(Value::as_str)
166
.map(str::to_owned)
167
},
168
})
169
})
170
.collect()
171
}
172
173
65
#[cfg(test)]
174
66
mod tests {
67
use serde_json::{Value, json};
68
175
69
use super::*;
176
70
177
71
fn answer(status: u16, body: Value) -> ApiResponse {
@@ -195,55 +89,4 @@ mod tests {
195
89
assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());
196
90
assert!(parse_photo("u", answer(403, json!("x"))).is_err());
197
91
}
198
199
#[test]
200
fn subscribe_body_carries_mris_and_purge_flag() {
201
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
202
assert_eq!(
203
body,
204
json!({
205
"trouterUri": "https://t/unifiedPresenceService",
206
"shouldPurgePreviousSubscriptions": true,
207
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
208
"subscriptionsToRemove": [],
209
})
210
);
211
}
212
213
#[test]
214
fn subscribe_headers_use_a_fresh_correlation_id() {
215
let correlation = |headers: &[(String, String)]| {
216
headers
217
.iter()
218
.find(|(name, _)| name == "x-ms-correlation-id")
219
.map(|(_, value)| value.clone())
220
};
221
let first = subscribe_headers("e");
222
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
223
assert!(
224
first
225
.iter()
226
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
227
);
228
}
229
230
#[test]
231
fn service_presences_strip_the_mri_prefix() {
232
let parsed = parse_service_presences(&json!([
233
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},
234
{"mri": "8:orgid:b"}
235
]));
236
assert_eq!(parsed.len(), 1);
237
assert_eq!(parsed[0].user_id, "a");
238
}
239
240
#[test]
241
fn out_of_office_from_the_calendar_becomes_the_activity() {
242
let parsed = parse_service_presences(&json!([
243
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},
244
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}
245
]));
246
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));
247
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));
248
}
249
92
}
@@ -1,24 +1,14 @@1
use base64::Engine as _;1
use base64::Engine as _;2
use base64::engine::general_purpose::STANDARD;2
use base64::engine::general_purpose::STANDARD;3
use serde::Deserialize;3
use serde::Deserialize;4
use serde_json::{Value, json};4
use session::{ApiResponse, Request, Scope};5
use session::{ApiResponse, Method, PRESENCE, Request, Scope};6
use uuid::Uuid;7
5
8
use crate::client::{BATCH_SIZE, Graph};6
use crate::client::{BATCH_SIZE, Graph};9
use crate::error::{Error, Result};7
use crate::error::{Error, Result};10
use crate::models::{Photo, Presence};8
use crate::models::Photo;11
use crate::urls;9
use crate::urls;12
10
13
pub const MAX_PRESENCE_IDS: usize = 650;14
pub const MAX_SUBSCRIBE_IDS: usize = 200;15
const PHOTO_SCOPE: &str = "User.ReadBasic.All";11
const PHOTO_SCOPE: &str = "User.ReadBasic.All";16
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";17
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";18
const PRESENCE_SUBSCRIBE_URL: &str =19
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";20
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";21
const ORGID_PREFIX: &str = "8:orgid:";22
12
23
#[derive(Debug, Deserialize)]13
#[derive(Debug, Deserialize)]24
struct BinaryBody {14
struct BinaryBody {@@ -47,77 +37,6 @@ impl Graph {47
}37
}48
Ok(photos)38
Ok(photos)49
}39
}50
51
/// Teams presence service. Graph `Presence.Read.All` is not in the web app tokens.52
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {53
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);54
let mut presences = Vec::with_capacity(user_ids.len());55
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {56
let body: Vec<Value> = chunk57
.iter()58
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))59
.collect();60
let answer = self61
.session()62
.request(63
Method::Post,64
PRESENCE_SERVICE_URL,65
&scope,66
Some(Value::Array(body)),67
)68
.await?;69
presences.extend(parse_service_presences(&answer.body));70
}71
Ok(presences)72
}73
74
pub async fn subscribe_presence(75
&self,76
endpoint_id: &str,77
trouter_uri: &str,78
user_ids: &[String],79
purge: bool,80
) -> Result<()> {81
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);82
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");83
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {84
let request = Request {85
method: Method::Post,86
headers: subscribe_headers(endpoint_id),87
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),88
..Request::get(url.clone())89
};90
let answer = self.session().send(request, &scope).await?;91
if !(200..300).contains(&answer.status) {92
return Err(session::Error::api(answer.status, &url, answer.body).into());93
}94
}95
Ok(())96
}97
}98
99
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.100
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {101
vec![102
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),103
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),104
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),105
("x-ms-endpoint-id".into(), endpoint_id.into()),106
("x-ms-client-type".into(), "cdlworker".into()),107
]108
}109
110
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {111
let additions: Vec<Value> = user_ids112
.iter()113
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))114
.collect();115
json!({116
"trouterUri": trouter_uri,117
"shouldPurgePreviousSubscriptions": purge,118
"subscriptionsToAdd": additions,119
"subscriptionsToRemove": [],120
})121
}40
}122
41
123
fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {42
fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {@@ -143,35 +62,10 @@ pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {143
}62
}144
}63
}145
64
146
fn parse_service_presences(body: &Value) -> Vec<Presence> {147
body.as_array()148
.into_iter()149
.flatten()150
.filter_map(|entry| {151
let mri = entry.get("mri")?.as_str()?;152
let presence = entry.get("presence")?;153
Some(Presence {154
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),155
availability: presence.get("availability")?.as_str()?.to_owned(),156
activity: if presence157
.pointer("/calendarData/isOutOfOffice")158
.and_then(Value::as_bool)159
.unwrap_or(false)160
{161
Some("OutOfOffice".to_owned())162
} else {163
presence164
.get("activity")165
.and_then(Value::as_str)166
.map(str::to_owned)167
},168
})169
})170
.collect()171
}172
173
#[cfg(test)]65
#[cfg(test)]174
mod tests {66
mod tests {67
use serde_json::{Value, json};68
175
use super::*;69
use super::*;176
70
177
fn answer(status: u16, body: Value) -> ApiResponse {71
fn answer(status: u16, body: Value) -> ApiResponse {@@ -195,55 +89,4 @@ mod tests {195
assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());89
assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());196
assert!(parse_photo("u", answer(403, json!("x"))).is_err());90
assert!(parse_photo("u", answer(403, json!("x"))).is_err());197
}91
}198
199
#[test]200
fn subscribe_body_carries_mris_and_purge_flag() {201
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);202
assert_eq!(203
body,204
json!({205
"trouterUri": "https://t/unifiedPresenceService",206
"shouldPurgePreviousSubscriptions": true,207
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],208
"subscriptionsToRemove": [],209
})210
);211
}212
213
#[test]214
fn subscribe_headers_use_a_fresh_correlation_id() {215
let correlation = |headers: &[(String, String)]| {216
headers217
.iter()218
.find(|(name, _)| name == "x-ms-correlation-id")219
.map(|(_, value)| value.clone())220
};221
let first = subscribe_headers("e");222
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));223
assert!(224
first225
.iter()226
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")227
);228
}229
230
#[test]231
fn service_presences_strip_the_mri_prefix() {232
let parsed = parse_service_presences(&json!([233
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},234
{"mri": "8:orgid:b"}235
]));236
assert_eq!(parsed.len(), 1);237
assert_eq!(parsed[0].user_id, "a");238
}239
240
#[test]241
fn out_of_office_from_the_calendar_becomes_the_activity() {242
let parsed = parse_service_presences(&json!([243
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},244
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}245
]));246
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));247
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));248
}249
}92
}