BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / signaling.rs

signaling.rs

signaling.rs 37.0 KiB Download Raw
1use std::collections::BTreeMap;
2
3use serde_json::{Map, Value, json};
4use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5
6use crate::error::{Error, Result};
7use crate::relay::ic3_scope;
8use crate::timeline::Timeline;
9use crate::trouter_events::{CallbackLinks, acceptance_links};
10
11pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
12pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0";
13pub const CHATSVC_REGION: &str = "emea";
14const CLIENT_HEADER: &str = "SkypeSpaces/1415/26091712213/os=windows; osVer=NT 10.0; deviceType=computer; browser=chrome; browserVer=155.0.0.0/TsCallingVersion=2026.36.01.5/Ovb=97a9cc3f0dd74681da27f28dfcebcf05da30ef6e";
15const PLATFORM_NAME: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36";
16const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
17const ENDPOINT_CAPABILITIES: u64 = 73463;
18const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
19const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
20const BACKEND_SUFFIX: &str = ".skype.com";
21const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
22const CONVERSATION_LINK_NAMES: [&str; 9] = [
23 "conversationEnd",
24 "conversationUpdate",
25 "localParticipantUpdate",
26 "addParticipantSuccess",
27 "addParticipantFailure",
28 "addModalitySuccess",
29 "addModalityFailure",
30 "confirmUnmute",
31 "receiveMessage",
32];
33const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
34 "conversationEnd",
35 "conversationUpdate",
36 "localParticipantUpdate",
37 "addParticipantSuccess",
38 "addParticipantFailure",
39 "receiveMessage",
40];
41const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
42const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
43const MEETING_MESSAGE_ID: &str = "0";
44const CANCEL_CODE: i64 = 487;
45const DECLINE_CODE: i64 = 603;
46
47#[derive(Debug, Clone)]
48pub struct Participant {
49 pub mri: String,
50 pub display_name: String,
51 pub endpoint_id: String,
52 pub participant_id: String,
53 pub language_id: String,
54}
55
56impl Participant {
57 pub fn wire(&self) -> Value {
58 json!({
59 "id": self.mri,
60 "displayName": self.display_name,
61 "endpointId": self.endpoint_id,
62 "participantId": self.participant_id,
63 "languageId": self.language_id,
64 })
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Callee {
70 pub mri: String,
71 pub display_name: String,
72}
73
74#[derive(Debug, Clone, PartialEq)]
75pub struct MeetingTarget {
76 pub thread_id: String,
77 pub tenant_id: String,
78 pub organizer_id: String,
79 pub meeting_data: Option<Value>,
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub enum InviteTarget {
84 Echo,
85 People { callees: Vec<Callee>, thread_id: String },
86 Meeting(MeetingTarget),
87}
88
89#[derive(Debug, Clone)]
90pub struct TenantRouting {
91 pub region: String,
92 pub partition: String,
93 pub ring: String,
94}
95
96impl Default for TenantRouting {
97 fn default() -> Self {
98 TenantRouting {
99 region: "de".into(),
100 partition: "de01".into(),
101 ring: "general".into(),
102 }
103 }
104}
105
106#[derive(Debug, Clone)]
107pub struct Conversation {
108 pub controller: String,
109 pub links: BTreeMap<String, String>,
110}
111
112impl Conversation {
113 pub fn link(&self, name: &str) -> Result<&str> {
114 self.links
115 .get(name)
116 .map(String::as_str)
117 .ok_or_else(|| Error::Signaling(format!("conversation has no '{name}' link")))
118 }
119}
120
121fn host_of(url: &str) -> Result<&str> {
122 url.strip_prefix("https://")
123 .and_then(|rest| rest.split(['/', '?']).next())
124 .map(|authority| authority.split(':').next().unwrap_or(authority))
125 .ok_or_else(|| Error::Signaling("link is not https".into()))
126}
127
128/// Bearer requests only go to Teams hosts; links come from server answers.
129pub fn ensure_teams_url(url: &str) -> Result<()> {
130 let host = host_of(url)?;
131 if ALLOWED_HOST_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) || host == "teams.microsoft.com" {
132 Ok(())
133 } else {
134 Err(Error::Signaling(format!("refusing link to host {host}")))
135 }
136}
137
138fn is_backend_host(host: &str) -> bool {
139 host.len() > BACKEND_SUFFIX.len()
140 && host.ends_with(BACKEND_SUFFIX)
141 && !host.starts_with('.')
142 && !host.contains("..")
143 && host
144 .bytes()
145 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-')
146}
147
148/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
149pub fn routed_url(url: &str) -> Result<String> {
150 let host = host_of(url)?;
151 if !is_backend_host(host) {
152 ensure_teams_url(url)?;
153 return Ok(url.to_owned());
154 }
155 let rest = &url["https://".len()..];
156 let path = rest.find(['/', '?']).map_or("", |position| &rest[position..]);
157 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum LeaveReason {
162 Hangup,
163 Cancel,
164}
165
166pub struct Signaling {
167 session: Session,
168 poll_session: Session,
169 chain_id: String,
170 routing: TenantRouting,
171 timeline: Timeline,
172 endpoint_state_sequence: std::sync::atomic::AtomicU32,
173}
174
175pub struct Invitation<'a> {
176 pub from: &'a Participant,
177 pub offer_sdp: &'a str,
178 pub media_leg_id: &'a str,
179 pub callbacks: &'a CallbackLinks,
180 pub target: &'a InviteTarget,
181}
182
183pub struct Answer<'a> {
184 pub from: &'a Participant,
185 pub answer_sdp: &'a str,
186 pub media_leg_id: &'a str,
187 pub callbacks: &'a CallbackLinks,
188 pub modalities: &'a [String],
189}
190
191pub struct AttachRequest<'a> {
192 pub from: &'a Participant,
193 pub callbacks: &'a CallbackLinks,
194 pub controller: Option<&'a str>,
195 pub needs_media: bool,
196}
197
198#[derive(Debug, Clone)]
199pub struct Attached {
200 pub offer_sdp: Option<String>,
201 pub from_mixer: bool,
202 pub modalities: Vec<String>,
203 pub links: BTreeMap<String, String>,
204 pub conversation: Option<Conversation>,
205}
206
207impl Signaling {
208 /// `poll_session` is a second CDP connection so the broker long poll never blocks the call requests.
209 pub fn new(session: Session, poll_session: Session, routing: TenantRouting, timeline: Timeline) -> Self {
210 Signaling {
211 session,
212 poll_session,
213 chain_id: uuid::Uuid::new_v4().to_string(),
214 routing,
215 timeline,
216 endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2),
217 }
218 }
219
220 fn request(&self, method: Method, url: &str, body: Option<Value>) -> Request {
221 let mut request = match body {
222 Some(body) => Request::with_body(method, url, body),
223 None => Request { method, ..Request::get(url) },
224 };
225 request.headers = vec![
226 ("X-Microsoft-Skype-Chain-ID".into(), self.chain_id.clone()),
227 ("X-Microsoft-Skype-Message-ID".into(), uuid::Uuid::new_v4().to_string()),
228 ("X-Microsoft-Skype-Client".into(), CLIENT_HEADER.into()),
229 ("MS-Teams-Region".into(), self.routing.region.clone()),
230 ("MS-Teams-Partition".into(), self.routing.partition.clone()),
231 ("MS-Teams-Ring".into(), self.routing.ring.clone()),
232 ("X-MS-Migration".into(), "True".into()),
233 ("content-type".into(), "application/json".into()),
234 ];
235 request
236 }
237
238 async fn exchange(&self, session: &Session, label: &str, mut request: Request) -> Result<ApiResponse> {
239 request.url = routed_url(&request.url)?;
240 let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
241 self.timeline.record(label, format!("HTTP {}", response.status));
242 if !response.is_success() {
243 return Err(Error::Signaling(format!("{label} answered HTTP {}", response.status)));
244 }
245 Ok(response)
246 }
247
248 async fn send(&self, label: &str, method: Method, url: &str, body: Option<Value>) -> Result<ApiResponse> {
249 self.exchange(&self.session, label, self.request(method, url, body)).await
250 }
251
252 pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> {
253 self.send(label, Method::Post, url, Some(body)).await.map(|_| ())
254 }
255
256 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
257 self.send(label, Method::Post, url, None).await.map(|_| ())
258 }
259
260 pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result<Conversation> {
261 let response = self
262 .send("POST epconv", Method::Post, EPCONV_URL, Some(epconv_body(invitation)))
263 .await?;
264 conversation_from(&response.body)
265 }
266
267 pub async fn subscribe_meeting(
268 &self,
269 from: &Participant,
270 callbacks: &CallbackLinks,
271 meeting: &MeetingTarget,
272 ) -> Result<Conversation> {
273 let body = subscribe_body(from, callbacks, meeting);
274 let response = self.send("POST epconv subscribe", Method::Post, EPCONV_URL, Some(body)).await?;
275 conversation_from(&response.body)
276 }
277
278 /// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.
279 pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {
280 let response = self
281 .send("POST join", Method::Post, &subscribed.controller, Some(epconv_body(invitation)))
282 .await?;
283 let mut links = subscribed.links.clone();
284 if let Ok(joined) = conversation_from(&response.body) {
285 links.extend(joined.links);
286 }
287 Ok(Conversation {
288 controller: subscribed.controller.clone(),
289 links,
290 })
291 }
292
293 pub fn next_endpoint_sequence(&self) -> u32 {
294 self.endpoint_state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
295 }
296
297 pub async fn update_endpoint_state(&self, conversation: &Conversation, from: &Participant, muted: bool) -> Result<()> {
298 let body = json!({
299 "from": from.wire(),
300 "endpointState": {
301 "endpointStateSequenceNumber": self.next_endpoint_sequence(),
302 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
303 "state": {"isMuted": muted},
304 },
305 });
306 let url = conversation.link("updateEndpointState")?;
307 self.post_json("POST updateEndpointState", url, body).await
308 }
309
310 pub async fn add_echo_bot(
311 &self,
312 conversation: &Conversation,
313 from: &Participant,
314 thread_id: Option<&str>,
315 callbacks: &CallbackLinks,
316 ) -> Result<()> {
317 let body = json!({
318 "disableUnmute": false,
319 "participants": {
320 "from": from.wire(),
321 "to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
322 },
323 "participantInvitationData": {},
324 "replacementDetails": null,
325 "groupContext": null,
326 "groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),
327 "links": {
328 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
329 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
330 },
331 });
332 let url = conversation.link("addParticipantAndModality")?;
333 self.post_json("POST add (echo bot)", url, body).await
334 }
335
336 pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
337 let body = json!({
338 "participants": {"from": from.wire()},
339 "endpointMetadata": {"holographicCapabilities": 3},
340 });
341 let url = conversation.link("updateEndpointMetadata")?;
342 self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())
343 }
344
345 /// One broker long poll; answers the next subscribe URL.
346 pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {
347 let mut request = self.request(Method::Get, url, None);
348 request.headers.push(("X-UseBatching".into(), "1".into()));
349 let response = self.exchange(&self.poll_session, "GET broker subscribe", request).await?;
350 Ok(response.body["nextSubscribeUrl"].as_str().map(str::to_owned))
351 }
352
353 pub async fn leave(&self, conversation: &Conversation, from: &Participant, reason: LeaveReason) -> Result<()> {
354 let url = conversation.link("leave")?;
355 self.post_json("POST leave", url, leave_body(from, reason)).await
356 }
357
358 pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
359 self.send(
360 "DELETE conversation",
361 Method::Delete,
362 &conversation.controller,
363 Some(end_for_all_body(from)),
364 )
365 .await
366 .map(|_| ())
367 }
368
369 pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> {
370 let response = self
371 .send("POST attach", Method::Post, url, Some(attach_body(request)))
372 .await?;
373 attached_from(&response.body)
374 }
375
376 pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> {
377 self.post_json("POST progress", url, ringing_body(from)).await
378 }
379
380 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
381 self.post_json("POST acceptance", url, acceptance_body(answer)).await
382 }
383
384 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
385 self.send("DELETE callLeg (decline)", Method::Delete, call_leg_url, Some(decline_body()))
386 .await
387 .map(|_| ())
388 }
389
390 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
391 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
392 .await
393 }
394
395 pub async fn keep_conversation_alive(
396 &self,
397 conversation: &Conversation,
398 from: &Participant,
399 callbacks: &CallbackLinks,
400 ) -> Result<()> {
401 let url = conversation.link("notificationLinks")?;
402 self.post_json("POST notificationLinks", url, notification_links_body(from, callbacks)).await
403 }
404}
405
406fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
407 names
408 .iter()
409 .map(|name| ((*name).to_owned(), Value::String(make(name))))
410 .collect()
411}
412
413fn roster_request(callbacks: &CallbackLinks) -> Value {
414 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
415}
416
417fn conversation_properties() -> Value {
418 json!({
419 "allowConversationWithoutHost": true,
420 "enableGroupCallEventMessages": true,
421 "enableGroupCallUpgradeMessage": false,
422 "enableGroupCallMeetupGeneration": false,
423 })
424}
425
426fn endpoint_state() -> Value {
427 json!({
428 "endpointStateSequenceNumber": 2,
429 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
430 })
431}
432
433fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
434 let mut content = json!({
435 "contentType": SDP_CONTENT_TYPE,
436 "blob": sdp,
437 "clientLocation": "DE",
438 "mediaLegId": media_leg_id,
439 });
440 if with_descriptions {
441 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
442 }
443 content
444}
445
446fn media_controller_links(callbacks: &CallbackLinks) -> Value {
447 json!({
448 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
449 "csrcInfo": callbacks.call("csrcInfo"),
450 })
451}
452
453fn group_chat(target: &InviteTarget) -> Value {
454 match target {
455 InviteTarget::Echo => Value::Null,
456 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
457 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
458 }
459}
460
461fn callee_wire(callee: &Callee) -> Value {
462 json!({"id": callee.mri, "displayName": callee.display_name})
463}
464
465pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
466 let callbacks = invitation.callbacks;
467 let target = invitation.target;
468 let to: Vec<Value> = match target {
469 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
470 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
471 };
472 let mut request = json!({
473 "conversationType": null,
474 "subject": null,
475 "suppressDialout": true,
476 "roster": roster_request(callbacks),
477 "properties": conversation_properties(),
478 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
479 });
480 if matches!(target, InviteTarget::Echo) {
481 request["scenario"] = json!("UserInitiatedTestCall");
482 }
483 let (meeting_info, meeting_data) = match target {
484 InviteTarget::Meeting(meeting) => (
485 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
486 meeting.meeting_data.clone().unwrap_or(Value::Null),
487 ),
488 _ => (Value::Null, Value::Null),
489 };
490 json!({
491 "conversationRequest": request,
492 "contentSharing": null,
493 "participants": {"from": invitation.from.wire(), "to": to},
494 "capabilities": null,
495 "endpointCapabilities": ENDPOINT_CAPABILITIES,
496 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
497 "endpointMetadata": {"holographicCapabilities": 3},
498 "groupContext": null,
499 "groupChat": group_chat(target),
500 "meetingInfo": meeting_info,
501 "meetingData": meeting_data,
502 "endpointState": endpoint_state(),
503 "callInvitation": {
504 "callModalities": AUDIO_MODALITIES,
505 "replaces": null,
506 "transferor": null,
507 "clientTransferContext": null,
508 "customContext": null,
509 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
510 "clientContentForMediaController": media_controller_links(callbacks),
511 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
512 "emergencyContent": null,
513 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
514 },
515 })
516}
517
518pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
519 json!({
520 "conversationRequest": {
521 "roster": roster_request(callbacks),
522 "properties": conversation_properties(),
523 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
524 },
525 "participants": {"from": from.wire()},
526 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
527 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
528 "endpointState": endpoint_state(),
529 })
530}
531
532pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
533 let call_end = match reason {
534 LeaveReason::Hangup => json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}),
535 LeaveReason::Cancel => json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}),
536 };
537 json!({
538 "participants": {"from": from.wire()},
539 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
540 "callTransactionEnd": call_end,
541 })
542}
543
544pub fn end_for_all_body(from: &Participant) -> Value {
545 json!({
546 "participants": {"from": from.wire()},
547 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
548 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
549 })
550}
551
552pub fn decline_body() -> Value {
553 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
554}
555
556pub fn ringing_body(from: &Participant) -> Value {
557 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
558}
559
560pub fn attach_body(request: &AttachRequest<'_>) -> Value {
561 let callbacks = request.callbacks;
562 let mut body = json!({
563 "attach": {
564 "requireMediaContent": request.needs_media,
565 "links": {"end": callbacks.call("end")},
566 },
567 "capabilities": null,
568 "endpointCapabilities": ENDPOINT_CAPABILITIES,
569 });
570 if let Some(controller) = request.controller {
571 body["additionalActions"] = json!([{
572 "name": "join",
573 "url": controller,
574 "waitForResponse": true,
575 "input": {
576 "conversationRequest": {
577 "roster": roster_request(callbacks),
578 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
579 },
580 "participants": {"from": request.from.wire()},
581 "endpointMetadata": {"holographicCapabilities": 3},
582 "endpointCapabilities": ENDPOINT_CAPABILITIES,
583 },
584 }]);
585 }
586 body
587}
588
589pub fn acceptance_body(answer: &Answer<'_>) -> Value {
590 let callbacks = answer.callbacks;
591 json!({
592 "callAcceptance": {
593 "acceptedBy": answer.from.wire(),
594 "acceptedCallModalities": answer.modalities,
595 "endpointCapabilities": ENDPOINT_CAPABILITIES,
596 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
597 "links": acceptance_links(callbacks),
598 "clientContentForMediaController": media_controller_links(callbacks),
599 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
600 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
601 "callKeepAliveInterval": null,
602 },
603 })
604}
605
606pub fn renegotiation_body(
607 from: &Participant,
608 callbacks: &CallbackLinks,
609 offer_sdp: &str,
610 media_leg_id: &str,
611) -> Value {
612 json!({
613 "mediaNegotiation": {
614 "callModalities": AUDIO_MODALITIES,
615 "sender": from.wire(),
616 "links": {
617 "mediaAnswer": callbacks.call("mediaAnswer"),
618 "rejection": callbacks.call("rejection"),
619 },
620 "mediaContent": renegotiation_content(offer_sdp, media_leg_id),
621 },
622 })
623}
624
625fn renegotiation_content(sdp: &str, media_leg_id: &str) -> Value {
626 let mut content = media_content(sdp, media_leg_id, true);
627 content["newOffer"] = json!(true);
628 content
629}
630
631pub fn escalation_answer_body(
632 from: &Participant,
633 callbacks: &CallbackLinks,
634 answer_sdp: &str,
635 media_leg_id: &str,
636) -> Value {
637 json!({
638 "mediaAnswer": {
639 "callModalities": AUDIO_MODALITIES,
640 "sender": from.wire(),
641 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
642 "clientContentForMediaController": media_controller_links(callbacks),
643 "mediaContent": media_content(answer_sdp, media_leg_id, false),
644 },
645 })
646}
647
648pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
649 json!({
650 "participants": {"from": from.wire()},
651 "roster": roster_request(callbacks),
652 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
653 })
654}
655
656fn conversation_from(body: &Value) -> Result<Conversation> {
657 let controller = body["conversationController"]
658 .as_str()
659 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
660 .to_owned();
661 let links = body["links"]
662 .as_object()
663 .map(|links| {
664 links
665 .iter()
666 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
667 .collect()
668 })
669 .unwrap_or_default();
670 Ok(Conversation { controller, links })
671}
672
673fn attached_from(body: &Value) -> Result<Attached> {
674 let invitation = &body["callInvitation"];
675 if invitation.is_null() {
676 return Err(Error::Signaling("attach answer without callInvitation".into()));
677 }
678 let links = invitation["links"]
679 .as_object()
680 .map(|links| {
681 links
682 .iter()
683 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
684 .collect()
685 })
686 .unwrap_or_default();
687 let modalities = invitation["callModalities"]
688 .as_array()
689 .map(|items| items.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect())
690 .unwrap_or_default();
691 Ok(Attached {
692 offer_sdp: invitation["mediaContent"]["blob"].as_str().map(str::to_owned),
693 from_mixer: invitation["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
694 modalities,
695 links,
696 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
697 })
698}
699
700#[derive(Debug, Clone)]
701pub struct SelfIdentity {
702 pub object_id: String,
703 pub display_name: String,
704}
705
706pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {
707 let response = session
708 .request(
709 Method::Get,
710 &format!("{GRAPH}/v1.0/me?$select=id,displayName"),
711 &Scope::graph("User.Read"),
712 None,
713 )
714 .await?;
715 Ok(SelfIdentity {
716 object_id: response.body["id"]
717 .as_str()
718 .ok_or_else(|| Error::Signaling("graph /me without id".into()))?
719 .to_owned(),
720 display_name: response.body["displayName"].as_str().unwrap_or_default().to_owned(),
721 })
722}
723
724/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.
725pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<Option<String>> {
726 let bot_id = ECHO_BOT_MRI.trim_start_matches("28:");
727 for thread_id in [
728 format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
729 format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
730 ] {
731 let url = format!(
732 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
733 thread_id.replace(':', "%3A").replace('@', "%40")
734 );
735 let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);
736 if response.is_success() {
737 return Ok(Some(thread_id));
738 }
739 }
740 Ok(None)
741}
742
743#[cfg(test)]
744mod tests {
745 use super::*;
746
747 fn from() -> Participant {
748 Participant {
749 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
750 display_name: "Test".into(),
751 endpoint_id: "e".into(),
752 participant_id: "p".into(),
753 language_id: "en-gb".into(),
754 }
755 }
756
757 fn callbacks() -> CallbackLinks {
758 CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1")
759 }
760
761 fn body_for(target: &InviteTarget) -> Value {
762 let from = from();
763 let callbacks = callbacks();
764 epconv_body(&Invitation {
765 from: &from,
766 offer_sdp: "v=0\r\n",
767 media_leg_id: "AB",
768 callbacks: &callbacks,
769 target,
770 })
771 }
772
773 fn callee(mri: &str, name: &str) -> Callee {
774 Callee {
775 mri: mri.into(),
776 display_name: name.into(),
777 }
778 }
779
780 #[test]
781 fn only_teams_hosts_get_the_bearer() {
782 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
783 assert!(ensure_teams_url(EPCONV_URL).is_ok());
784 assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok());
785 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
786 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
787 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
788 }
789
790 #[test]
791 fn backend_links_go_through_flightproxy() {
792 assert_eq!(
793 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2").unwrap(),
794 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
795 );
796 assert_eq!(
797 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
798 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
799 );
800 assert!(routed_url("https://evil.skype.com.example/x").is_err());
801 assert!(routed_url("https://Evil.skype.com/x").is_err());
802 assert!(routed_url("https://user@cc.skype.com/x").is_err());
803 assert!(routed_url("http://cc.skype.com/x").is_err());
804 assert!(routed_url("https://.skype.com/x").is_err());
805 }
806
807 #[test]
808 fn echo_body_matches_the_captured_test_call_shape() {
809 let body = body_for(&InviteTarget::Echo);
810 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
811 assert_eq!(body["participants"]["to"], json!([]));
812 assert_eq!(body["groupChat"], Value::Null);
813 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
814 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
815 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
816 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 9);
817 }
818
819 #[test]
820 fn one_to_one_body_names_the_callee_and_the_chat() {
821 let target = InviteTarget::People {
822 callees: vec![callee("8:orgid:b", "Bea")],
823 thread_id: "19:a_b@unq.gbl.spaces".into(),
824 };
825 let body = body_for(&target);
826 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
827 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
828 assert!(body["conversationRequest"].get("scenario").is_none());
829 assert_eq!(body["meetingInfo"], Value::Null);
830 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
831 }
832
833 #[test]
834 fn group_body_invites_every_callee_on_the_group_thread() {
835 let target = InviteTarget::People {
836 callees: vec![callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di")],
837 thread_id: "19:group@thread.v2".into(),
838 };
839 let body = body_for(&target);
840 let to = body["participants"]["to"].as_array().unwrap();
841 assert_eq!(to.len(), 3);
842 assert_eq!(to[2]["id"], "8:orgid:d");
843 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
844 assert_eq!(body["groupChat"]["messageId"], Value::Null);
845 }
846
847 #[test]
848 fn meeting_join_body_carries_thread_and_meeting_info() {
849 let target = InviteTarget::Meeting(MeetingTarget {
850 thread_id: "19:meeting_x@thread.v2".into(),
851 tenant_id: "tenant".into(),
852 organizer_id: "organizer".into(),
853 meeting_data: Some(json!({"meetingCode": "123"})),
854 });
855 let body = body_for(&target);
856 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
857 assert_eq!(body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}));
858 assert_eq!(body["meetingData"]["meetingCode"], "123");
859 assert_eq!(body["participants"]["to"], json!([]));
860 assert!(body["conversationRequest"].get("scenario").is_none());
861 assert!(body["endpointState"]["endpointProperties"].get("preheatProperties").is_none());
862 }
863
864 #[test]
865 fn meeting_subscribe_is_roster_only() {
866 let meeting = MeetingTarget {
867 thread_id: "19:meeting_x@thread.v2".into(),
868 tenant_id: "tenant".into(),
869 organizer_id: "organizer".into(),
870 meeting_data: None,
871 };
872 let body = subscribe_body(&from(), &callbacks(), &meeting);
873 assert!(body.get("callInvitation").is_none());
874 assert!(body["participants"].get("to").is_none());
875 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 6);
876 assert_eq!(body["groupChat"]["messageId"], "0");
877 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
878 }
879
880 #[test]
881 fn leave_bodies_differ_by_reason() {
882 let hangup = leave_body(&from(), LeaveReason::Hangup);
883 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
884 let cancel = leave_body(&from(), LeaveReason::Cancel);
885 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
886 assert_eq!(cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
887 assert_eq!(cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected");
888 let end = end_for_all_body(&from());
889 assert_eq!(end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated");
890 }
891
892 #[test]
893 fn decline_uses_603() {
894 let body = decline_body();
895 assert_eq!(body["callEnd"]["code"], 603);
896 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
897 }
898
899 #[test]
900 fn attach_asks_for_media_and_joins_the_conversation() {
901 let from = from();
902 let callbacks = callbacks();
903 let body = attach_body(&AttachRequest {
904 from: &from,
905 callbacks: &callbacks,
906 controller: Some("https://conv/controller"),
907 needs_media: true,
908 });
909 assert_eq!(body["attach"]["requireMediaContent"], true);
910 assert!(body["attach"]["links"]["end"].as_str().unwrap().ends_with("/call/end/"));
911 let action = &body["additionalActions"][0];
912 assert_eq!(action["name"], "join");
913 assert_eq!(action["url"], "https://conv/controller");
914 assert_eq!(action["waitForResponse"], true);
915 assert_eq!(action["input"]["conversationRequest"]["links"].as_object().unwrap().len(), 6);
916 let without = attach_body(&AttachRequest {
917 from: &from,
918 callbacks: &callbacks,
919 controller: None,
920 needs_media: false,
921 });
922 assert!(without.get("additionalActions").is_none());
923 assert_eq!(without["attach"]["requireMediaContent"], false);
924 }
925
926 #[test]
927 fn attach_answer_yields_offer_links_and_conversation() {
928 let body = json!({
929 "callInvitation": {
930 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
931 "mediaContent": {"blob": "v=0\r\n"},
932 "callModalities": ["Audio"],
933 },
934 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
935 });
936 let attached = attached_from(&body).unwrap();
937 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
938 assert_eq!(attached.links["callLeg"], "https://cc/leg");
939 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
940 let conversation = attached.conversation.unwrap();
941 assert_eq!(conversation.controller, "https://conv/c");
942 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
943 assert!(attached_from(&json!({})).is_err());
944 }
945
946 #[test]
947 fn acceptance_carries_the_answer_and_callback_links() {
948 let from = from();
949 let callbacks = callbacks();
950 let modalities = vec!["Audio".to_owned()];
951 let body = acceptance_body(&Answer {
952 from: &from,
953 answer_sdp: "v=0\r\n",
954 media_leg_id: "AB",
955 callbacks: &callbacks,
956 modalities: &modalities,
957 });
958 let accepted = &body["callAcceptance"];
959 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
960 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
961 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
962 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
963 assert!(accepted["links"]["mediaRenegotiation"].as_str().unwrap().ends_with("/call/mediaRenegotiation/"));
964 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
965 }
966
967 #[test]
968 fn renegotiation_messages_name_their_reply_links() {
969 let from = from();
970 let callbacks = callbacks();
971 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB");
972 let negotiation = &offer["mediaNegotiation"];
973 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
974 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
975 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
976 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
977 assert!(answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
978 .as_str()
979 .unwrap()
980 .ends_with("/call/mediaAcknowledgement/"));
981 }
982
983 #[test]
984 fn ringing_progress_names_the_sender() {
985 let body = ringing_body(&from());
986 assert_eq!(body["callProgress"]["status"], "ringing");
987 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
988 }
989}