refactor(presence): move presence lookup and subscriptions out of the graph crate
- presence.teams.microsoft.com getpresence and pubsub calls now live in chatsvc::presence::lookup - graph crate keeps only Graph calls; core maps UserPresence to the shared Presence model - graph live_data example drops its presence probe (graph cannot depend on chatsvc) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -59,8 +59,9 @@ pub use pins::{
59
59
PinnedMessage, Pins, TeamLayout,
60
60
};
61
61
pub use presence::{
62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
63
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,
63
PresenceStatus, StatusNote, UserPresence, WorkLocation, WorkLocationKind, WorkLocationSource,
64
error_status, is_endpoint_missing,
64
65
};
65
66
pub use reactions::{
66
67
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
@@ -59,8 +59,9 @@ pub use pins::{59
PinnedMessage, Pins, TeamLayout,59
PinnedMessage, Pins, TeamLayout,60
};60
};61
pub use presence::{61
pub use presence::{62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,63
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,63
PresenceStatus, StatusNote, UserPresence, WorkLocation, WorkLocationKind, WorkLocationSource,64
error_status, is_endpoint_missing,64
};65
};65
pub use reactions::{66
pub use reactions::{66
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,67
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,@@ -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
}@@ -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
}