BlueGit

ict rusty-teams

Files

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

signaling.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
signaling.rs 65.8 KiB Download Raw
1use std::collections::BTreeMap;
2
3use serde_json::{Map, Value, json};
4use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
5
6use crate::captions::{self, BotAction};
7use crate::error::{Error, Result};
8use crate::organizer::{self, Invitee, Target};
9use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
10use crate::recording::{self, Consent, RecordingCommand, StartDetails};
11use crate::relay::ic3_scope;
12use crate::roster::MeetingRole;
13use crate::timeline::Timeline;
14use crate::transfer::{self, TransferTarget};
15use crate::trouter_events::{CallbackLinks, acceptance_links, acknowledgement_links};
16use crate::video_layout::MediaDescription;
17
18pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
19pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0";
20pub const CHATSVC_REGION: &str = "emea";
21const 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";
22const 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";
23const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
24const ENDPOINT_CAPABILITIES: u64 = 73463;
25const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
26const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
27const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
28const ALLOWED_HOST_SUFFIXES: [&str; 2] =
29 [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
30const BACKEND_SUFFIX: &str = ".skype.com";
31const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
32const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
33const CONVERSATION_LINK_NAMES: [&str; 11] = [
34 "conversationEnd",
35 "conversationUpdate",
36 "localParticipantUpdate",
37 "addParticipantSuccess",
38 "addParticipantFailure",
39 "addModalitySuccess",
40 "addModalityFailure",
41 "confirmUnmute",
42 "receiveMessage",
43 "contentSharingUpdate",
44 "contentSharingEnd",
45];
46const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
47 "conversationEnd",
48 "conversationUpdate",
49 "localParticipantUpdate",
50 "addParticipantSuccess",
51 "addParticipantFailure",
52 "receiveMessage",
53];
54const CALL_LINK_NAMES: [&str; 5] = [
55 "progress",
56 "mediaAnswer",
57 "acceptance",
58 "redirection",
59 "end",
60];
61const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
62pub(crate) const MEETING_MESSAGE_ID: &str = "0";
63const RAISE_HANDS: &str = "raiseHands";
64const CANCEL_CODE: i64 = 487;
65const DECLINE_CODE: i64 = 603;
66
67#[derive(Debug, Clone)]
68pub struct Participant {
69 pub mri: String,
70 pub display_name: String,
71 pub endpoint_id: String,
72 pub participant_id: String,
73 pub language_id: String,
74}
75
76impl Participant {
77 pub fn wire(&self) -> Value {
78 json!({
79 "id": self.mri,
80 "displayName": self.display_name,
81 "endpointId": self.endpoint_id,
82 "participantId": self.participant_id,
83 "languageId": self.language_id,
84 })
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct Callee {
90 pub mri: String,
91 pub display_name: String,
92}
93
94#[derive(Debug, Clone, PartialEq)]
95pub struct MeetingTarget {
96 pub thread_id: String,
97 pub tenant_id: String,
98 pub organizer_id: String,
99 pub meeting_data: Option<Value>,
100}
101
102#[derive(Debug, Clone, PartialEq)]
103pub enum InviteTarget {
104 Echo,
105 People {
106 callees: Vec<Callee>,
107 thread_id: String,
108 },
109 Meeting(MeetingTarget),
110}
111
112#[derive(Debug, Clone)]
113pub struct TenantRouting {
114 pub region: String,
115 pub partition: String,
116 pub ring: String,
117}
118
119impl Default for TenantRouting {
120 fn default() -> Self {
121 TenantRouting {
122 region: "de".into(),
123 partition: "de01".into(),
124 ring: "general".into(),
125 }
126 }
127}
128
129#[derive(Debug, Clone)]
130pub struct Conversation {
131 pub controller: String,
132 pub links: BTreeMap<String, String>,
133 pub chat_thread: Option<String>,
134 pub roster: Option<Value>,
135}
136
137impl Conversation {
138 pub fn link(&self, name: &str) -> Result<&str> {
139 self.links
140 .get(name)
141 .map(String::as_str)
142 .ok_or_else(|| Error::Signaling(format!("conversation has no '{name}' link")))
143 }
144}
145
146fn host_of(url: &str) -> Result<&str> {
147 url.strip_prefix("https://")
148 .and_then(|rest| rest.split(['/', '?']).next())
149 .map(|authority| authority.split(':').next().unwrap_or(authority))
150 .ok_or_else(|| Error::Signaling("link is not https".into()))
151}
152
153/// Bearer requests only go to Teams hosts; links come from server answers.
154pub fn ensure_teams_url(url: &str) -> Result<()> {
155 let host = host_of(url)?;
156 if ALLOWED_HOST_SUFFIXES
157 .iter()
158 .any(|suffix| host.ends_with(suffix))
159 || host == "teams.microsoft.com"
160 {
161 Ok(())
162 } else {
163 Err(Error::Signaling(format!("refusing link to host {host}")))
164 }
165}
166
167fn is_backend_host(host: &str) -> bool {
168 host.len() > BACKEND_SUFFIX.len()
169 && host.ends_with(BACKEND_SUFFIX)
170 && !host.starts_with('.')
171 && !host.contains("..")
172 && host.bytes().all(|byte| {
173 byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-'
174 })
175}
176
177/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
178pub fn routed_url(url: &str) -> Result<String> {
179 let host = host_of(url)?;
180 if !is_backend_host(host) {
181 ensure_teams_url(url)?;
182 return Ok(url.to_owned());
183 }
184 let rest = &url["https://".len()..];
185 let path = rest
186 .find(['/', '?'])
187 .map_or("", |position| &rest[position..]);
188 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
189}
190
191const FAILURE_BODY_CHARS: usize = 240;
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum LeaveReason {
195 Hangup,
196 Cancel,
197}
198
199fn spaces_scope() -> Scope {
200 Scope::new(SPACES, AUTHZ_SCOPE_NAME)
201}
202
203pub struct Signaling {
204 session: Session,
205 poll_session: Session,
206 chain_id: String,
207 routing: TenantRouting,
208 timeline: Timeline,
209 endpoint_state_sequence: std::sync::atomic::AtomicU32,
210 state_sequence: std::sync::atomic::AtomicU32,
211}
212
213pub struct Invitation<'a> {
214 pub from: &'a Participant,
215 pub offer_sdp: &'a str,
216 pub media_leg_id: &'a str,
217 pub callbacks: &'a CallbackLinks,
218 pub target: &'a InviteTarget,
219 pub modalities: &'a [String],
220 pub direct: bool,
221}
222
223impl Invitation<'_> {
224 pub fn is_direct(&self) -> bool {
225 self.direct && self.target.is_one_to_one()
226 }
227}
228
229pub struct Answer<'a> {
230 pub from: &'a Participant,
231 pub answer_sdp: &'a str,
232 pub media_leg_id: &'a str,
233 pub callbacks: &'a CallbackLinks,
234 pub modalities: &'a [String],
235}
236
237pub struct AttachRequest<'a> {
238 pub from: &'a Participant,
239 pub callbacks: &'a CallbackLinks,
240 pub controller: Option<&'a str>,
241 pub needs_media: bool,
242}
243
244#[derive(Debug, Clone)]
245pub struct Attached {
246 pub offer_sdp: Option<String>,
247 pub from_mixer: bool,
248 pub modalities: Vec<String>,
249 pub links: BTreeMap<String, String>,
250 pub conversation: Option<Conversation>,
251}
252
253impl Signaling {
254 /// `poll_session` is a second CDP connection so the broker long poll never blocks the call requests.
255 pub fn new(
256 session: Session,
257 poll_session: Session,
258 routing: TenantRouting,
259 timeline: Timeline,
260 ) -> Self {
261 Signaling {
262 session,
263 poll_session,
264 chain_id: uuid::Uuid::new_v4().to_string(),
265 routing,
266 timeline,
267 endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2),
268 state_sequence: std::sync::atomic::AtomicU32::new(0),
269 }
270 }
271
272 fn request(&self, method: Method, url: &str, body: Option<Value>) -> Request {
273 let mut request = match body {
274 Some(body) => Request::with_body(method, url, body),
275 None => Request {
276 method,
277 ..Request::get(url)
278 },
279 };
280 request.headers = vec![
281 ("X-Microsoft-Skype-Chain-ID".into(), self.chain_id.clone()),
282 (
283 "X-Microsoft-Skype-Message-ID".into(),
284 uuid::Uuid::new_v4().to_string(),
285 ),
286 ("X-Microsoft-Skype-Client".into(), CLIENT_HEADER.into()),
287 ("MS-Teams-Region".into(), self.routing.region.clone()),
288 ("MS-Teams-Partition".into(), self.routing.partition.clone()),
289 ("MS-Teams-Ring".into(), self.routing.ring.clone()),
290 ("X-MS-Migration".into(), "True".into()),
291 ("content-type".into(), "application/json".into()),
292 ];
293 request
294 }
295
296 async fn exchange(
297 &self,
298 session: &Session,
299 label: &str,
300 mut request: Request,
301 ) -> Result<ApiResponse> {
302 request.url = routed_url(&request.url)?;
303 let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
304 self.timeline
305 .record(label, format!("HTTP {}", response.status));
306 if !response.is_success() {
307 let reason: String = response
308 .body
309 .to_string()
310 .chars()
311 .take(FAILURE_BODY_CHARS)
312 .collect();
313 return Err(Error::Signaling(format!(
314 "{label} answered HTTP {} {reason}",
315 response.status
316 )));
317 }
318 Ok(response)
319 }
320
321 async fn send(
322 &self,
323 label: &str,
324 method: Method,
325 url: &str,
326 body: Option<Value>,
327 ) -> Result<ApiResponse> {
328 self.exchange(&self.session, label, self.request(method, url, body))
329 .await
330 }
331
332 pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> {
333 self.send(label, Method::Post, url, Some(body))
334 .await
335 .map(|_| ())
336 }
337
338 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
339 self.send(label, Method::Post, url, None).await.map(|_| ())
340 }
341
342 pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result<Conversation> {
343 let response = self
344 .send(
345 "POST epconv",
346 Method::Post,
347 EPCONV_URL,
348 Some(epconv_body(invitation)),
349 )
350 .await?;
351 conversation_from(&response.body)
352 }
353
354 pub async fn subscribe_meeting(
355 &self,
356 from: &Participant,
357 callbacks: &CallbackLinks,
358 meeting: &MeetingTarget,
359 ) -> Result<Conversation> {
360 let body = subscribe_body(from, callbacks, meeting);
361 let response = self
362 .send(
363 "POST epconv subscribe",
364 Method::Post,
365 EPCONV_URL,
366 Some(body),
367 )
368 .await?;
369 conversation_from(&response.body)
370 }
371
372 /// Opens a roster-only conversation for the meeting ID; the caller leaves it once the target is read.
373 pub async fn resolve_meeting(
374 &self,
375 from: &Participant,
376 callbacks: &CallbackLinks,
377 meeting_data: &Value,
378 ) -> Result<(MeetingTarget, Conversation)> {
379 let body = crate::join::resolve_body(from, callbacks, meeting_data);
380 let response = self
381 .send("POST epconv resolve", Method::Post, EPCONV_URL, Some(body))
382 .await?;
383 let target = crate::join::target_from_answer(&response.body, meeting_data)?;
384 Ok((target, conversation_from(&response.body)?))
385 }
386
387 /// A running meeting answers from the conversation that owns it, so its controller and links replace the subscribed ones.
388 pub async fn join_meeting(
389 &self,
390 subscribed: &Conversation,
391 invitation: &Invitation<'_>,
392 ) -> Result<Conversation> {
393 let response = self
394 .send(
395 "POST join",
396 Method::Post,
397 &subscribed.controller,
398 Some(epconv_body(invitation)),
399 )
400 .await?;
401 Ok(joined_conversation(subscribed, &response.body))
402 }
403
404 pub fn next_endpoint_sequence(&self) -> u32 {
405 self.endpoint_state_sequence
406 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
407 + 1
408 }
409
410 pub async fn update_endpoint_state(
411 &self,
412 conversation: &Conversation,
413 from: &Participant,
414 muted: bool,
415 ) -> Result<()> {
416 let body = json!({
417 "from": from.wire(),
418 "endpointState": {
419 "endpointStateSequenceNumber": self.next_endpoint_sequence(),
420 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
421 "state": {"isMuted": muted},
422 },
423 });
424 let url = conversation.link("updateEndpointState")?;
425 self.post_json("POST updateEndpointState", url, body).await
426 }
427
428 fn next_state_sequence(&self) -> u32 {
429 self.state_sequence
430 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
431 + 1
432 }
433
434 pub async fn raise_hand(
435 &self,
436 conversation: &Conversation,
437 from: &Participant,
438 ) -> Result<HandReceipt> {
439 let body = raise_hand_body(from.wire(), self.next_state_sequence());
440 let response = self
441 .send(
442 "POST publishState",
443 Method::Post,
444 conversation.link("publishState")?,
445 Some(body),
446 )
447 .await?;
448 Ok(hand_receipt_from(&response.body))
449 }
450
451 pub async fn lower_hands(
452 &self,
453 conversation: &Conversation,
454 from: &Participant,
455 state_ids: &[String],
456 ) -> Result<()> {
457 let body = remove_states_body(from.wire(), self.next_state_sequence(), state_ids);
458 self.post_json("POST removeState", conversation.link("removeState")?, body)
459 .await
460 }
461
462 pub async fn lower_all_hands(
463 &self,
464 conversation: &Conversation,
465 from: &Participant,
466 ) -> Result<()> {
467 let body = remove_all_hands_body(from.wire(), self.next_state_sequence());
468 self.post_json("POST removeState", conversation.link("removeState")?, body)
469 .await
470 }
471
472 pub async fn send_reaction(
473 &self,
474 conversation: &Conversation,
475 from: &Participant,
476 reaction: Reaction,
477 ) -> Result<()> {
478 let body = reaction_message(
479 from.wire(),
480 reaction,
481 &uuid::Uuid::new_v4().to_string(),
482 &uuid::Uuid::new_v4().to_string(),
483 );
484 self.post_json("POST sendMessage", conversation.link("sendMessage")?, body)
485 .await
486 }
487
488 pub async fn update_media_descriptions(
489 &self,
490 url: &str,
491 descriptions: &[MediaDescription],
492 request_id: u32,
493 ) -> Result<()> {
494 let body = json!({
495 "UpdateMediaDescriptions": {
496 "mediaDescriptions": {
497 "descriptions": descriptions.iter().map(MediaDescription::wire).collect::<Vec<_>>(),
498 "requestId": request_id,
499 },
500 },
501 });
502 self.post_json("POST updateMediaDescriptions", url, body)
503 .await
504 }
505
506 pub async fn add_echo_bot(
507 &self,
508 conversation: &Conversation,
509 from: &Participant,
510 thread_id: Option<&str>,
511 callbacks: &CallbackLinks,
512 ) -> Result<()> {
513 let body = json!({
514 "disableUnmute": false,
515 "participants": {
516 "from": from.wire(),
517 "to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
518 },
519 "participantInvitationData": {},
520 "replacementDetails": null,
521 "groupContext": null,
522 "groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),
523 "links": {
524 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
525 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
526 },
527 });
528 let url = conversation.link("addParticipantAndModality")?;
529 self.post_json("POST add (echo bot)", url, body).await
530 }
531
532 pub async fn update_endpoint_metadata(
533 &self,
534 conversation: &Conversation,
535 from: &Participant,
536 ) -> Result<()> {
537 self.put_endpoint_metadata(conversation, from, json!({"holographicCapabilities": 3}))
538 .await
539 }
540
541 pub async fn set_caption_preference(
542 &self,
543 conversation: &Conversation,
544 from: &Participant,
545 captions: bool,
546 ) -> Result<()> {
547 self.put_endpoint_metadata(conversation, from, captions::endpoint_metadata(captions))
548 .await
549 }
550
551 async fn put_endpoint_metadata(
552 &self,
553 conversation: &Conversation,
554 from: &Participant,
555 metadata: Value,
556 ) -> Result<()> {
557 let body = json!({"participants": {"from": from.wire()}, "endpointMetadata": metadata});
558 let url = conversation.link("updateEndpointMetadata")?;
559 self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body))
560 .await
561 .map(|_| ())
562 }
563
564 pub async fn admit(
565 &self,
566 conversation: &Conversation,
567 from: &Participant,
568 target: Target<'_>,
569 callbacks: &CallbackLinks,
570 ) -> Result<u16> {
571 let body = organizer::admit_body(
572 from.wire(),
573 target,
574 callbacks,
575 &uuid::Uuid::new_v4().to_string(),
576 );
577 self.send(
578 "POST admit",
579 Method::Post,
580 conversation.link("admit")?,
581 Some(body),
582 )
583 .await
584 .map(|response| response.status)
585 }
586
587 pub async fn remove_participant(
588 &self,
589 conversation: &Conversation,
590 from: &Participant,
591 target: Target<'_>,
592 callbacks: &CallbackLinks,
593 ) -> Result<u16> {
594 let body = organizer::remove_participant_body(from.wire(), target, callbacks);
595 self.send(
596 "POST removeParticipant",
597 Method::Post,
598 conversation.link("removeParticipant")?,
599 Some(body),
600 )
601 .await
602 .map(|response| response.status)
603 }
604
605 pub async fn mute_participant(
606 &self,
607 conversation: &Conversation,
608 from: &Participant,
609 mri: &str,
610 ) -> Result<u16> {
611 let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]);
612 self.send(
613 "POST mute",
614 Method::Post,
615 conversation.link("mute")?,
616 Some(body),
617 )
618 .await
619 .map(|response| response.status)
620 }
621
622 pub async fn mute_everyone(
623 &self,
624 conversation: &Conversation,
625 from: &Participant,
626 others: &[String],
627 ) -> Result<u16> {
628 let body = organizer::mute_everyone_body(from.wire(), others);
629 self.send(
630 "POST mute (all)",
631 Method::Post,
632 conversation.link("mute")?,
633 Some(body),
634 )
635 .await
636 .map(|response| response.status)
637 }
638
639 pub async fn spotlight(
640 &self,
641 conversation: &Conversation,
642 from: &Participant,
643 mri: &str,
644 ) -> Result<u16> {
645 let body =
646 organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri);
647 self.send(
648 "POST publishState (spotlight)",
649 Method::Post,
650 conversation.link("publishState")?,
651 Some(body),
652 )
653 .await
654 .map(|response| response.status)
655 }
656
657 pub async fn set_lock(
658 &self,
659 conversation: &Conversation,
660 from: &Participant,
661 locked: bool,
662 ) -> Result<u16> {
663 let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence());
664 self.send(
665 "PUT updateMeetingSettings",
666 Method::Put,
667 conversation.link("updateMeetingSettings")?,
668 Some(body),
669 )
670 .await
671 .map(|response| response.status)
672 }
673
674 pub async fn change_role(
675 &self,
676 conversation: &Conversation,
677 from: &Participant,
678 mri: &str,
679 role: MeetingRole,
680 ) -> Result<u16> {
681 let body = organizer::role_body(from.wire(), mri, role);
682 self.send(
683 "POST updateParticipantRole",
684 Method::Post,
685 conversation.link("updateParticipantRole")?,
686 Some(body),
687 )
688 .await
689 .map(|response| response.status)
690 }
691
692 pub async fn publish_attendee_state(
693 &self,
694 conversation: &Conversation,
695 from: &Participant,
696 state_type: &str,
697 mri: &str,
698 ) -> Result<u16> {
699 let body = organizer::attendee_state_body(
700 from.wire(),
701 state_type,
702 self.next_state_sequence(),
703 mri,
704 );
705 self.send(
706 "POST publishState (attendee)",
707 Method::Post,
708 conversation.link("publishState")?,
709 Some(body),
710 )
711 .await
712 .map(|response| response.status)
713 }
714
715 pub async fn add_participants(
716 &self,
717 conversation: &Conversation,
718 from: &Participant,
719 callees: &[Callee],
720 group_thread: Option<&str>,
721 meeting: Option<&MeetingTarget>,
722 callbacks: &CallbackLinks,
723 ) -> Result<u16> {
724 let invitees: Vec<Invitee> = callees
725 .iter()
726 .map(|callee| Invitee {
727 callee: callee.clone(),
728 participant_id: uuid::Uuid::new_v4().to_string(),
729 })
730 .collect();
731 let group_chat = group_thread.map_or(Value::Null, |thread_id| {
732 organizer::group_chat_for(thread_id, meeting.is_some())
733 });
734 let body = organizer::add_participants_body(
735 from.wire(),
736 &invitees,
737 group_chat,
738 meeting,
739 callbacks,
740 );
741 let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?;
742 self.send("POST add (invite)", Method::Post, url, Some(body))
743 .await
744 .map(|response| response.status)
745 }
746
747 pub async fn add_caption_bot(
748 &self,
749 conversation: &Conversation,
750 from: &Participant,
751 thread_id: &str,
752 callbacks: &CallbackLinks,
753 threadless: bool,
754 ) -> Result<u16> {
755 let body = captions::add_bot_body(
756 from.wire(),
757 thread_id,
758 callbacks.call_id(),
759 &from.display_name,
760 callbacks,
761 threadless,
762 );
763 let link = if threadless {
764 "addParticipant"
765 } else {
766 "addParticipantAndModality"
767 };
768 let mut request = self.request(Method::Post, conversation.link(link)?, Some(body));
769 request = request.with_body_token(
770 captions::RECORDER_RESOURCE,
771 captions::RECORDER_SCOPE,
772 captions::INITIATOR_TOKEN_PLACEHOLDER,
773 );
774 self.exchange(&self.session, "POST add (caption bot)", request)
775 .await
776 .map(|response| response.status)
777 }
778
779 pub async fn caption_command(
780 &self,
781 command_url: &str,
782 action: BotAction,
783 from: &Participant,
784 ) -> Result<()> {
785 ensure_teams_url(command_url)?;
786 let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
787 let body = captions::command_body(action, &from.mri, &from.participant_id, &timestamp);
788 self.bot_command(command_url, body, "caption command")
789 .await
790 .map(|_| ())
791 }
792
793 pub async fn caption_language_command(
794 &self,
795 command_url: &str,
796 from: &Participant,
797 language_tag: &str,
798 ) -> Result<()> {
799 ensure_teams_url(command_url)?;
800 let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
801 let body =
802 captions::language_body(&from.mri, &from.participant_id, &timestamp, language_tag);
803 self.bot_command(command_url, body, "caption language command")
804 .await
805 .map(|_| ())
806 }
807
808 async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
809 let arguments = json!({
810 "url": command_url,
811 "body": body,
812 "recorderResource": captions::RECORDER_RESOURCE,
813 "recorderScope": captions::RECORDER_SCOPE,
814 "requestId": uuid::Uuid::new_v4().to_string(),
815 "chainId": self.chain_id,
816 });
817 let answer = self
818 .session
819 .run_with_token(
820 App::Teams,
821 &spaces_scope(),
822 captions::COMMAND_SCRIPT,
823 &arguments,
824 false,
825 )
826 .await?;
827 let status = answer["status"].as_u64().unwrap_or_default();
828 self.timeline
829 .record(format!("POST {label}"), format!("HTTP {status}"));
830 if (200..300).contains(&status) {
831 return Ok(status as u16);
832 }
833 let reason = answer["error"].as_str().unwrap_or("no answer");
834 Err(Error::Signaling(format!(
835 "{label} answered HTTP {status} {reason}"
836 )))
837 }
838
839 pub async fn recording_command(
840 &self,
841 command_url: &str,
842 command: RecordingCommand,
843 from: &Participant,
844 title: &str,
845 ) -> Result<u16> {
846 ensure_teams_url(command_url)?;
847 let now = chrono::Utc::now();
848 let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
849 let file_name = recording::file_name(title, now);
850 let correlation_id = uuid::Uuid::new_v4().to_string();
851 let details = StartDetails {
852 own_mri: &from.mri,
853 participant_leg_id: &from.participant_id,
854 timestamp: &timestamp,
855 file_name: &file_name,
856 meeting_title: title,
857 organizer_name: &from.display_name,
858 correlation_id: &correlation_id,
859 };
860 self.bot_command(
861 command_url,
862 recording::command_body(command, details),
863 "recording command",
864 )
865 .await
866 }
867
868 pub async fn consent_to_recording(
869 &self,
870 conversation: &Conversation,
871 from: &Participant,
872 consent: Consent,
873 ) -> Result<u16> {
874 let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent);
875 self.send(
876 "POST publishState (recording consent)",
877 Method::Post,
878 conversation.link("publishState")?,
879 Some(body),
880 )
881 .await
882 .map(|response| response.status)
883 }
884
885 pub async fn transfer(
886 &self,
887 transfer_url: &str,
888 from: &Participant,
889 target: TransferTarget<'_>,
890 callbacks: &CallbackLinks,
891 ) -> Result<()> {
892 let body = transfer::transfer_body(from, target, callbacks);
893 self.post_json("POST transfer", transfer_url, body).await
894 }
895
896 /// One broker long poll; answers the next subscribe URL.
897 pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {
898 let mut request = self.request(Method::Get, url, None);
899 request.headers.push(("X-UseBatching".into(), "1".into()));
900 let response = self
901 .exchange(&self.poll_session, "GET broker subscribe", request)
902 .await?;
903 Ok(response.body["nextSubscribeUrl"]
904 .as_str()
905 .map(str::to_owned))
906 }
907
908 pub async fn leave(
909 &self,
910 conversation: &Conversation,
911 from: &Participant,
912 reason: LeaveReason,
913 ) -> Result<()> {
914 let url = conversation.link("leave")?;
915 self.post_json("POST leave", url, leave_body(from, reason))
916 .await
917 }
918
919 pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
920 self.send(
921 "DELETE conversation",
922 Method::Delete,
923 &conversation.controller,
924 Some(end_for_all_body(from)),
925 )
926 .await
927 .map(|_| ())
928 }
929
930 pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> {
931 let response = self
932 .send("POST attach", Method::Post, url, Some(attach_body(request)))
933 .await?;
934 attached_from(&response.body)
935 }
936
937 pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> {
938 self.post_json("POST progress", url, ringing_body(from))
939 .await
940 }
941
942 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<BTreeMap<String, String>> {
943 let response = self
944 .send(
945 "POST acceptance",
946 Method::Post,
947 url,
948 Some(acceptance_body(answer)),
949 )
950 .await?;
951 Ok(acknowledgement_links(&response.body))
952 }
953
954 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
955 self.send(
956 "DELETE callLeg (decline)",
957 Method::Delete,
958 call_leg_url,
959 Some(decline_body()),
960 )
961 .await
962 .map(|_| ())
963 }
964
965 pub async fn reject_renegotiation(
966 &self,
967 url: &str,
968 from: &Participant,
969 call_id: &str,
970 failure: NegotiationFailure,
971 ) -> Result<()> {
972 self.post_json(
973 "POST rejection (renegotiation)",
974 url,
975 negotiation_failure_body(from, call_id, failure),
976 )
977 .await
978 }
979
980 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
981 self.post_json(
982 "POST callLeg keep-alive",
983 call_leg_url,
984 json!({"callParticipantUpdate": {}}),
985 )
986 .await
987 }
988
989 pub async fn keep_conversation_alive(
990 &self,
991 conversation: &Conversation,
992 from: &Participant,
993 callbacks: &CallbackLinks,
994 ) -> Result<()> {
995 let url = conversation.link("notificationLinks")?;
996 self.post_json(
997 "POST notificationLinks",
998 url,
999 notification_links_body(from, callbacks),
1000 )
1001 .await
1002 }
1003}
1004
1005fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
1006 names
1007 .iter()
1008 .map(|name| ((*name).to_owned(), Value::String(make(name))))
1009 .collect()
1010}
1011
1012fn roster_request(callbacks: &CallbackLinks) -> Value {
1013 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
1014}
1015
1016fn conversation_properties() -> Value {
1017 json!({
1018 "allowConversationWithoutHost": true,
1019 "enableGroupCallEventMessages": true,
1020 "enableGroupCallUpgradeMessage": false,
1021 "enableGroupCallMeetupGeneration": false,
1022 })
1023}
1024
1025pub(crate) fn endpoint_state() -> Value {
1026 json!({
1027 "endpointStateSequenceNumber": 2,
1028 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
1029 })
1030}
1031
1032fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
1033 let mut content = json!({
1034 "contentType": SDP_CONTENT_TYPE,
1035 "blob": sdp,
1036 "clientLocation": "DE",
1037 "mediaLegId": media_leg_id,
1038 });
1039 if with_descriptions {
1040 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
1041 }
1042 content
1043}
1044
1045fn media_controller_links(callbacks: &CallbackLinks) -> Value {
1046 json!({
1047 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
1048 "csrcInfo": callbacks.call("csrcInfo"),
1049 })
1050}
1051
1052/// The 1:1 chat of two people: both object ids sorted as plain strings.
1053pub fn one_to_one_thread(own_object_id: &str, peer_mri: &str) -> Option<String> {
1054 let peer = peer_mri.strip_prefix("8:orgid:")?;
1055 let (first, second) = if own_object_id <= peer {
1056 (own_object_id, peer)
1057 } else {
1058 (peer, own_object_id)
1059 };
1060 Some(format!("19:{first}_{second}{ONE_TO_ONE_THREAD_SUFFIX}"))
1061}
1062
1063impl InviteTarget {
1064 pub fn is_one_to_one(&self) -> bool {
1065 match self {
1066 InviteTarget::People { callees, thread_id } => {
1067 callees.len() == 1 && thread_id.ends_with(ONE_TO_ONE_THREAD_SUFFIX)
1068 }
1069 InviteTarget::Echo | InviteTarget::Meeting(_) => false,
1070 }
1071 }
1072}
1073
1074fn invitation_media(invitation: &Invitation<'_>) -> Value {
1075 if !invitation.is_direct() {
1076 return media_content(invitation.offer_sdp, invitation.media_leg_id, true);
1077 }
1078 let mut content = media_content(invitation.offer_sdp, invitation.media_leg_id, false);
1079 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
1080 content
1081}
1082
1083fn group_chat(invitation: &Invitation<'_>) -> Value {
1084 if invitation.is_direct() {
1085 return Value::Null;
1086 }
1087 match invitation.target {
1088 InviteTarget::Echo => Value::Null,
1089 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
1090 InviteTarget::Meeting(meeting) => {
1091 json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID})
1092 }
1093 }
1094}
1095
1096fn callee_wire(callee: &Callee) -> Value {
1097 json!({"id": callee.mri, "displayName": callee.display_name})
1098}
1099
1100pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
1101 let callbacks = invitation.callbacks;
1102 let target = invitation.target;
1103 let to: Vec<Value> = match target {
1104 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
1105 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
1106 };
1107 let mut request = json!({
1108 "conversationType": null,
1109 "subject": null,
1110 "suppressDialout": to.is_empty(),
1111 "roster": roster_request(callbacks),
1112 "properties": conversation_properties(),
1113 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
1114 });
1115 if matches!(target, InviteTarget::Echo) {
1116 request["scenario"] = json!("UserInitiatedTestCall");
1117 }
1118 let (meeting_info, meeting_data) = match target {
1119 InviteTarget::Meeting(meeting) => (
1120 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
1121 meeting.meeting_data.clone().unwrap_or(Value::Null),
1122 ),
1123 _ => (Value::Null, Value::Null),
1124 };
1125 json!({
1126 "conversationRequest": request,
1127 "contentSharing": null,
1128 "participants": {"from": invitation.from.wire(), "to": to},
1129 "capabilities": null,
1130 "endpointCapabilities": ENDPOINT_CAPABILITIES,
1131 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
1132 "endpointMetadata": {"holographicCapabilities": 3},
1133 "groupContext": null,
1134 "groupChat": group_chat(invitation),
1135 "meetingInfo": meeting_info,
1136 "meetingData": meeting_data,
1137 "endpointState": endpoint_state(),
1138 "callInvitation": {
1139 "callModalities": invitation.modalities,
1140 "replaces": null,
1141 "transferor": null,
1142 "clientTransferContext": null,
1143 "customContext": null,
1144 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
1145 "clientContentForMediaController": media_controller_links(callbacks),
1146 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
1147 "emergencyContent": null,
1148 "mediaContent": invitation_media(invitation),
1149 },
1150 })
1151}
1152
1153pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value {
1154 json!({
1155 "roster": roster_request(callbacks),
1156 "properties": conversation_properties(),
1157 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
1158 })
1159}
1160
1161pub fn subscribe_body(
1162 from: &Participant,
1163 callbacks: &CallbackLinks,
1164 meeting: &MeetingTarget,
1165) -> Value {
1166 json!({
1167 "conversationRequest": subscribe_request(callbacks),
1168 "participants": {"from": from.wire()},
1169 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
1170 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
1171 "endpointState": endpoint_state(),
1172 })
1173}
1174
1175pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
1176 let call_end = match reason {
1177 LeaveReason::Hangup => {
1178 json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]})
1179 }
1180 LeaveReason::Cancel => {
1181 json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"})
1182 }
1183 };
1184 json!({
1185 "participants": {"from": from.wire()},
1186 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
1187 "callTransactionEnd": call_end,
1188 })
1189}
1190
1191pub fn end_for_all_body(from: &Participant) -> Value {
1192 json!({
1193 "participants": {"from": from.wire()},
1194 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
1195 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
1196 })
1197}
1198
1199pub fn decline_body() -> Value {
1200 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
1201}
1202
1203pub fn ringing_body(from: &Participant) -> Value {
1204 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
1205}
1206
1207pub fn attach_body(request: &AttachRequest<'_>) -> Value {
1208 let callbacks = request.callbacks;
1209 let mut body = json!({
1210 "attach": {
1211 "requireMediaContent": request.needs_media,
1212 "links": {"end": callbacks.call("end")},
1213 },
1214 "capabilities": null,
1215 "endpointCapabilities": ENDPOINT_CAPABILITIES,
1216 });
1217 if let Some(controller) = request.controller {
1218 body["additionalActions"] = json!([{
1219 "name": "join",
1220 "url": controller,
1221 "waitForResponse": true,
1222 "input": {
1223 "conversationRequest": {
1224 "roster": roster_request(callbacks),
1225 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
1226 },
1227 "participants": {"from": request.from.wire()},
1228 "endpointMetadata": {"holographicCapabilities": 3},
1229 "endpointCapabilities": ENDPOINT_CAPABILITIES,
1230 },
1231 }]);
1232 }
1233 body
1234}
1235
1236pub fn acceptance_body(answer: &Answer<'_>) -> Value {
1237 let callbacks = answer.callbacks;
1238 json!({
1239 "callAcceptance": {
1240 "acceptedBy": answer.from.wire(),
1241 "acceptedCallModalities": answer.modalities,
1242 "endpointCapabilities": ENDPOINT_CAPABILITIES,
1243 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
1244 "links": acceptance_links(callbacks),
1245 "clientContentForMediaController": media_controller_links(callbacks),
1246 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
1247 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
1248 "callKeepAliveInterval": null,
1249 },
1250 })
1251}
1252
1253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1254pub enum NegotiationFailure {
1255 InProgress,
1256 AnswerError,
1257}
1258
1259impl NegotiationFailure {
1260 fn wire(self) -> (u16, u32, &'static str) {
1261 match self {
1262 NegotiationFailure::InProgress => (491, 3118, "NegotiationIsInProgress"),
1263 NegotiationFailure::AnswerError => (488, 3102, "CallEndReasonMediaAnswerError"),
1264 }
1265 }
1266}
1267
1268pub fn negotiation_failure_body(
1269 from: &Participant,
1270 call_id: &str,
1271 failure: NegotiationFailure,
1272) -> Value {
1273 let (code, sub_code, phrase) = failure.wire();
1274 json!({
1275 "mediaNegotiationFailure": {"sender": from.wire(), "code": code, "subCode": sub_code, "phrase": phrase},
1276 "debugContent": {"callId": call_id, "endpointId": from.endpoint_id},
1277 })
1278}
1279
1280pub fn renegotiation_body(
1281 from: &Participant,
1282 callbacks: &CallbackLinks,
1283 offer_sdp: &str,
1284 media_leg_id: &str,
1285 modalities: &[String],
1286 new_offer: bool,
1287 direct: bool,
1288) -> Value {
1289 json!({
1290 "mediaNegotiation": {
1291 "callModalities": modalities,
1292 "sender": from.wire(),
1293 "links": {
1294 "mediaAnswer": callbacks.call("mediaAnswer"),
1295 "rejection": callbacks.call("rejection"),
1296 },
1297 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer, direct),
1298 },
1299 })
1300}
1301
1302fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool, direct: bool) -> Value {
1303 let mut content = media_content(sdp, media_leg_id, !direct);
1304 if direct {
1305 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
1306 }
1307 content["newOffer"] = json!(new_offer);
1308 content
1309}
1310
1311pub fn escalation_answer_body(
1312 from: &Participant,
1313 callbacks: &CallbackLinks,
1314 answer_sdp: &str,
1315 media_leg_id: &str,
1316) -> Value {
1317 json!({
1318 "mediaAnswer": {
1319 "callModalities": AUDIO_MODALITIES,
1320 "sender": from.wire(),
1321 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
1322 "clientContentForMediaController": media_controller_links(callbacks),
1323 "mediaContent": media_content(answer_sdp, media_leg_id, false),
1324 },
1325 })
1326}
1327
1328pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
1329 json!({
1330 "participants": {"from": from.wire()},
1331 "roster": roster_request(callbacks),
1332 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
1333 })
1334}
1335
1336fn conversation_from(body: &Value) -> Result<Conversation> {
1337 let controller = body["conversationController"]
1338 .as_str()
1339 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
1340 .to_owned();
1341 let links = body["links"]
1342 .as_object()
1343 .map(|links| {
1344 links
1345 .iter()
1346 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
1347 .collect()
1348 })
1349 .unwrap_or_default();
1350 let roster = Some(&body["roster"])
1351 .filter(|roster| roster.is_object())
1352 .cloned();
1353 Ok(Conversation {
1354 controller,
1355 links,
1356 chat_thread: chat_thread_id(body),
1357 roster,
1358 })
1359}
1360
1361fn joined_conversation(subscribed: &Conversation, answer: &Value) -> Conversation {
1362 let Ok(joined) = conversation_from(answer) else {
1363 return subscribed.clone();
1364 };
1365 let mut links = subscribed.links.clone();
1366 links.extend(joined.links);
1367 Conversation {
1368 controller: joined.controller,
1369 links,
1370 chat_thread: joined
1371 .chat_thread
1372 .or_else(|| subscribed.chat_thread.clone()),
1373 roster: joined.roster.or_else(|| subscribed.roster.clone()),
1374 }
1375}
1376
1377#[derive(Debug, Clone, PartialEq, Eq)]
1378pub struct HandReceipt {
1379 pub state_id: Option<String>,
1380 pub rank: u64,
1381}
1382
1383pub fn hand_receipt_from(body: &Value) -> HandReceipt {
1384 let published = &body["publishStateResponse"];
1385 HandReceipt {
1386 state_id: published["stateId"].as_str().map(str::to_owned),
1387 rank: published["typeRank"].as_u64().unwrap_or(u64::MAX),
1388 }
1389}
1390
1391pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
1392 json!({
1393 "from": from,
1394 "publishedState": {
1395 "stateType": RAISE_HANDS,
1396 "level": "user",
1397 "content": {"skinTone": DEFAULT_SKIN_TONE},
1398 "sequenceNumber": sequence_number,
1399 },
1400 })
1401}
1402
1403pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value {
1404 json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids})
1405}
1406
1407pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value {
1408 json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS})
1409}
1410
1411pub fn chat_thread_id(body: &Value) -> Option<String> {
1412 body["activeModalities"]["groupChat"]["threadId"]
1413 .as_str()
1414 .map(str::to_owned)
1415}
1416
1417fn attached_from(body: &Value) -> Result<Attached> {
1418 let invitation = &body["callInvitation"];
1419 if invitation.is_null() {
1420 return Err(Error::Signaling(
1421 "attach answer without callInvitation".into(),
1422 ));
1423 }
1424 let links = invitation["links"]
1425 .as_object()
1426 .map(|links| {
1427 links
1428 .iter()
1429 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
1430 .collect()
1431 })
1432 .unwrap_or_default();
1433 let modalities = invitation["callModalities"]
1434 .as_array()
1435 .map(|items| {
1436 items
1437 .iter()
1438 .filter_map(|item| item.as_str().map(str::to_owned))
1439 .collect()
1440 })
1441 .unwrap_or_default();
1442 Ok(Attached {
1443 offer_sdp: invitation["mediaContent"]["blob"]
1444 .as_str()
1445 .map(str::to_owned),
1446 from_mixer: invitation["mediaContent"]["fromMixer"]
1447 .as_bool()
1448 .unwrap_or(false),
1449 modalities,
1450 links,
1451 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
1452 })
1453}
1454
1455#[derive(Debug, Clone)]
1456pub struct SelfIdentity {
1457 pub object_id: String,
1458 pub display_name: String,
1459}
1460
1461pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {
1462 let response = session
1463 .request(
1464 Method::Get,
1465 &format!("{GRAPH}/v1.0/me?$select=id,displayName"),
1466 &Scope::graph("User.Read"),
1467 None,
1468 )
1469 .await?;
1470 Ok(SelfIdentity {
1471 object_id: response.body["id"]
1472 .as_str()
1473 .ok_or_else(|| Error::Signaling("graph /me without id".into()))?
1474 .to_owned(),
1475 display_name: response.body["displayName"]
1476 .as_str()
1477 .unwrap_or_default()
1478 .to_owned(),
1479 })
1480}
1481
1482/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.
1483pub async fn find_echo_bot_thread(
1484 session: &Session,
1485 self_object_id: &str,
1486) -> Result<Option<String>> {
1487 let bot_id = ECHO_BOT_MRI.trim_start_matches("28:");
1488 for thread_id in [
1489 format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
1490 format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
1491 ] {
1492 let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id);
1493 let response = session
1494 .batch(&[Request::get(url)], &ic3_scope())
1495 .await?
1496 .remove(0);
1497 if response.is_success() {
1498 return Ok(Some(thread_id));
1499 }
1500 }
1501 Ok(None)
1502}
1503
1504#[cfg(test)]
1505mod tests {
1506 use super::*;
1507
1508 #[test]
1509 fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() {
1510 let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4);
1511 assert_eq!(raised["publishedState"]["stateType"], "raiseHands");
1512 assert_eq!(raised["publishedState"]["level"], "user");
1513 assert_eq!(raised["publishedState"]["sequenceNumber"], 4);
1514 let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]);
1515 assert_eq!(lowered["scope"], "specified");
1516 assert_eq!(lowered["stateIds"][0], "s-1");
1517 let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6);
1518 assert_eq!(all["scope"], "all");
1519 assert_eq!(all["stateType"], "raiseHands");
1520 }
1521
1522 #[test]
1523 fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() {
1524 let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}});
1525 assert_eq!(
1526 hand_receipt_from(&body),
1527 HandReceipt {
1528 state_id: Some("s-9".to_owned()),
1529 rank: 3
1530 }
1531 );
1532 assert_eq!(
1533 hand_receipt_from(&json!({})),
1534 HandReceipt {
1535 state_id: None,
1536 rank: u64::MAX
1537 }
1538 );
1539 }
1540
1541 #[test]
1542 fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
1543 let body =
1544 json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
1545 assert_eq!(
1546 chat_thread_id(&body).as_deref(),
1547 Some("19:meeting_abc@thread.v2")
1548 );
1549 assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None);
1550 }
1551
1552 fn from() -> Participant {
1553 Participant {
1554 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
1555 display_name: "Test".into(),
1556 endpoint_id: "e".into(),
1557 participant_id: "p".into(),
1558 language_id: "en-gb".into(),
1559 }
1560 }
1561
1562 fn callbacks() -> CallbackLinks {
1563 CallbackLinks::new(
1564 "https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/",
1565 "call-1",
1566 )
1567 }
1568
1569 fn body_for(target: &InviteTarget) -> Value {
1570 let from = from();
1571 let callbacks = callbacks();
1572 epconv_body(&Invitation {
1573 from: &from,
1574 offer_sdp: "v=0\r\n",
1575 media_leg_id: "AB",
1576 callbacks: &callbacks,
1577 target,
1578 modalities: &["Audio".to_owned()],
1579 direct: true,
1580 })
1581 }
1582
1583 fn callee(mri: &str, name: &str) -> Callee {
1584 Callee {
1585 mri: mri.into(),
1586 display_name: name.into(),
1587 }
1588 }
1589
1590 #[test]
1591 fn only_teams_hosts_get_the_bearer() {
1592 assert!(
1593 ensure_teams_url(
1594 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1"
1595 )
1596 .is_ok()
1597 );
1598 assert!(ensure_teams_url(EPCONV_URL).is_ok());
1599 assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok());
1600 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1601 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1602 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1603 }
1604
1605 #[test]
1606 fn backend_links_go_through_flightproxy() {
1607 assert_eq!(
1608 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2")
1609 .unwrap(),
1610 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
1611 );
1612 assert_eq!(
1613 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
1614 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1615 );
1616 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1617 assert!(routed_url("https://Evil.skype.com/x").is_err());
1618 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1619 assert!(routed_url("http://cc.skype.com/x").is_err());
1620 assert!(routed_url("https://.skype.com/x").is_err());
1621 }
1622
1623 #[test]
1624 fn echo_body_matches_the_captured_test_call_shape() {
1625 let body = body_for(&InviteTarget::Echo);
1626 assert_eq!(
1627 body["conversationRequest"]["scenario"],
1628 "UserInitiatedTestCall"
1629 );
1630 assert_eq!(body["participants"]["to"], json!([]));
1631 assert_eq!(body["groupChat"], Value::Null);
1632 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1633 assert_eq!(
1634 body["callInvitation"]["mediaContent"]["contentType"],
1635 SDP_CONTENT_TYPE
1636 );
1637 assert!(
1638 body["callInvitation"]["links"]["acceptance"]
1639 .as_str()
1640 .unwrap()
1641 .ends_with("/call/acceptance/")
1642 );
1643 assert_eq!(
1644 body["conversationRequest"]["links"]
1645 .as_object()
1646 .unwrap()
1647 .len(),
1648 11
1649 );
1650 }
1651
1652 #[test]
1653 fn one_to_one_body_names_the_callee_without_a_chat_thread() {
1654 let target = InviteTarget::People {
1655 callees: vec![callee("8:orgid:b", "Bea")],
1656 thread_id: "19:a_b@unq.gbl.spaces".into(),
1657 };
1658 let body = body_for(&target);
1659 assert_eq!(
1660 body["participants"]["to"],
1661 json!([{"id": "8:orgid:b", "displayName": "Bea"}])
1662 );
1663 assert_eq!(body["groupChat"], Value::Null);
1664 let media = &body["callInvitation"]["mediaContent"];
1665 assert_eq!(media["requiredFeatures"], "nonByPass");
1666 assert!(media.get("mediaDescriptions").is_none());
1667 assert!(body["conversationRequest"].get("scenario").is_none());
1668 assert_eq!(body["meetingInfo"], Value::Null);
1669 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1670 }
1671
1672 #[test]
1673 fn a_one_to_one_call_that_may_not_go_direct_keeps_the_chat_thread() {
1674 let from = from();
1675 let callbacks = callbacks();
1676 let target = InviteTarget::People {
1677 callees: vec![callee("8:orgid:b", "Bea")],
1678 thread_id: "19:a_b@unq.gbl.spaces".into(),
1679 };
1680 let modalities = vec!["Audio".to_owned()];
1681 let body = epconv_body(&Invitation {
1682 from: &from,
1683 offer_sdp: "v=0\r\n",
1684 media_leg_id: "AB",
1685 callbacks: &callbacks,
1686 target: &target,
1687 modalities: &modalities,
1688 direct: false,
1689 });
1690 assert_eq!(body["groupChat"]["threadId"], "19:a_b@unq.gbl.spaces");
1691 assert!(body["callInvitation"]["mediaContent"]["mediaDescriptions"].is_object());
1692 }
1693
1694 #[test]
1695 fn group_body_invites_every_callee_on_the_group_thread() {
1696 let target = InviteTarget::People {
1697 callees: vec![
1698 callee("8:orgid:b", "Bea"),
1699 callee("8:orgid:c", "Cy"),
1700 callee("8:orgid:d", "Di"),
1701 ],
1702 thread_id: "19:group@thread.v2".into(),
1703 };
1704 let body = body_for(&target);
1705 let to = body["participants"]["to"].as_array().unwrap();
1706 assert_eq!(to.len(), 3);
1707 assert_eq!(to[2]["id"], "8:orgid:d");
1708 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1709 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1710 let media = &body["callInvitation"]["mediaContent"];
1711 assert!(media.get("requiredFeatures").is_none());
1712 assert!(media["mediaDescriptions"].is_object());
1713 }
1714
1715 #[test]
1716 fn meeting_join_body_carries_thread_and_meeting_info() {
1717 let target = InviteTarget::Meeting(MeetingTarget {
1718 thread_id: "19:meeting_x@thread.v2".into(),
1719 tenant_id: "tenant".into(),
1720 organizer_id: "organizer".into(),
1721 meeting_data: Some(json!({"meetingCode": "123"})),
1722 });
1723 let body = body_for(&target);
1724 assert_eq!(
1725 body["groupChat"],
1726 json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"})
1727 );
1728 assert_eq!(
1729 body["meetingInfo"],
1730 json!({"tenantId": "tenant", "organizerId": "organizer"})
1731 );
1732 assert_eq!(body["meetingData"]["meetingCode"], "123");
1733 assert_eq!(body["participants"]["to"], json!([]));
1734 assert!(body["conversationRequest"].get("scenario").is_none());
1735 assert!(
1736 body["endpointState"]["endpointProperties"]
1737 .get("preheatProperties")
1738 .is_none()
1739 );
1740 }
1741
1742 #[test]
1743 fn meeting_subscribe_is_roster_only() {
1744 let meeting = MeetingTarget {
1745 thread_id: "19:meeting_x@thread.v2".into(),
1746 tenant_id: "tenant".into(),
1747 organizer_id: "organizer".into(),
1748 meeting_data: None,
1749 };
1750 let body = subscribe_body(&from(), &callbacks(), &meeting);
1751 assert!(body.get("callInvitation").is_none());
1752 assert!(body["participants"].get("to").is_none());
1753 assert_eq!(
1754 body["conversationRequest"]["links"]
1755 .as_object()
1756 .unwrap()
1757 .len(),
1758 6
1759 );
1760 assert_eq!(body["groupChat"]["messageId"], "0");
1761 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
1762 }
1763
1764 #[test]
1765 fn leave_bodies_differ_by_reason() {
1766 let hangup = leave_body(&from(), LeaveReason::Hangup);
1767 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
1768 let cancel = leave_body(&from(), LeaveReason::Cancel);
1769 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
1770 assert_eq!(
1771 cancel["callTransactionEnd"]["phrase"],
1772 "CallEndReasonLocalUserInitiated"
1773 );
1774 assert_eq!(
1775 cancel["conversationTransactionEnd"]["phrase"],
1776 "ConversationEndNoModalityConnected"
1777 );
1778 let end = end_for_all_body(&from());
1779 assert_eq!(
1780 end["conversationTransactionEnd"]["phrase"],
1781 "ConversationEndForAllInitiated"
1782 );
1783 }
1784
1785 #[test]
1786 fn decline_uses_603() {
1787 let body = decline_body();
1788 assert_eq!(body["callEnd"]["code"], 603);
1789 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1790 }
1791
1792 #[test]
1793 fn attach_asks_for_media_and_joins_the_conversation() {
1794 let from = from();
1795 let callbacks = callbacks();
1796 let body = attach_body(&AttachRequest {
1797 from: &from,
1798 callbacks: &callbacks,
1799 controller: Some("https://conv/controller"),
1800 needs_media: true,
1801 });
1802 assert_eq!(body["attach"]["requireMediaContent"], true);
1803 assert!(
1804 body["attach"]["links"]["end"]
1805 .as_str()
1806 .unwrap()
1807 .ends_with("/call/end/")
1808 );
1809 let action = &body["additionalActions"][0];
1810 assert_eq!(action["name"], "join");
1811 assert_eq!(action["url"], "https://conv/controller");
1812 assert_eq!(action["waitForResponse"], true);
1813 assert_eq!(
1814 action["input"]["conversationRequest"]["links"]
1815 .as_object()
1816 .unwrap()
1817 .len(),
1818 6
1819 );
1820 let without = attach_body(&AttachRequest {
1821 from: &from,
1822 callbacks: &callbacks,
1823 controller: None,
1824 needs_media: false,
1825 });
1826 assert!(without.get("additionalActions").is_none());
1827 assert_eq!(without["attach"]["requireMediaContent"], false);
1828 }
1829
1830 #[test]
1831 fn attach_answer_yields_offer_links_and_conversation() {
1832 let body = json!({
1833 "callInvitation": {
1834 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
1835 "mediaContent": {"blob": "v=0\r\n"},
1836 "callModalities": ["Audio"],
1837 },
1838 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
1839 });
1840 let attached = attached_from(&body).unwrap();
1841 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
1842 assert_eq!(attached.links["callLeg"], "https://cc/leg");
1843 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
1844 let conversation = attached.conversation.unwrap();
1845 assert_eq!(conversation.controller, "https://conv/c");
1846 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
1847 assert!(attached_from(&json!({})).is_err());
1848 }
1849
1850 #[test]
1851 fn a_running_meeting_answers_from_its_owning_conversation_with_the_roster() {
1852 let subscribed = conversation_from(&json!({
1853 "conversationController": "https://conv/subscribed",
1854 "links": {"leave": "https://conv/subscribed/leave", "mute": "https://conv/subscribed/mute"},
1855 }))
1856 .unwrap();
1857 assert_eq!(subscribed.roster, None);
1858 let answer: Value =
1859 serde_json::from_str(include_str!("../tests/fixtures/meeting_join_answer.json"))
1860 .unwrap();
1861 let joined = joined_conversation(&subscribed, &answer);
1862 assert_eq!(joined.controller, "https://conv.example/conv/joined");
1863 assert_eq!(
1864 joined.link("leave").unwrap(),
1865 "https://conv.example/conv/joined/leave"
1866 );
1867 assert_eq!(joined.link("mute").unwrap(), "https://conv/subscribed/mute");
1868 assert_eq!(
1869 joined.roster.unwrap()["participants"]
1870 .as_object()
1871 .unwrap()
1872 .len(),
1873 4
1874 );
1875 assert_eq!(
1876 joined_conversation(&subscribed, &json!({})).controller,
1877 "https://conv/subscribed"
1878 );
1879 }
1880
1881 #[test]
1882 fn acceptance_carries_the_answer_and_callback_links() {
1883 let from = from();
1884 let callbacks = callbacks();
1885 let modalities = vec!["Audio".to_owned()];
1886 let body = acceptance_body(&Answer {
1887 from: &from,
1888 answer_sdp: "v=0\r\n",
1889 media_leg_id: "AB",
1890 callbacks: &callbacks,
1891 modalities: &modalities,
1892 });
1893 let accepted = &body["callAcceptance"];
1894 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
1895 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
1896 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
1897 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
1898 assert!(
1899 accepted["links"]["mediaRenegotiation"]
1900 .as_str()
1901 .unwrap()
1902 .ends_with("/call/mediaRenegotiation/")
1903 );
1904 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1905 }
1906
1907 #[test]
1908 fn the_one_to_one_chat_sorts_both_ids() {
1909 assert_eq!(
1910 one_to_one_thread("f74e", "8:orgid:a1b2").as_deref(),
1911 Some("19:a1b2_f74e@unq.gbl.spaces")
1912 );
1913 assert_eq!(
1914 one_to_one_thread("a1b2", "8:orgid:f74e").as_deref(),
1915 Some("19:a1b2_f74e@unq.gbl.spaces")
1916 );
1917 assert_eq!(one_to_one_thread("a1b2", "28:bot"), None);
1918 }
1919
1920 #[test]
1921 fn a_refused_offer_says_why() {
1922 let body = negotiation_failure_body(&from(), "call-1", NegotiationFailure::InProgress);
1923 assert_eq!(body["mediaNegotiationFailure"]["code"], 491);
1924 assert_eq!(body["mediaNegotiationFailure"]["subCode"], 3118);
1925 assert_eq!(
1926 body["mediaNegotiationFailure"]["phrase"],
1927 "NegotiationIsInProgress"
1928 );
1929 assert_eq!(body["debugContent"]["callId"], "call-1");
1930 assert_eq!(
1931 negotiation_failure_body(&from(), "c", NegotiationFailure::AnswerError)["mediaNegotiationFailure"]
1932 ["code"],
1933 488
1934 );
1935 }
1936
1937 #[test]
1938 fn renegotiation_messages_name_their_reply_links() {
1939 let from = from();
1940 let callbacks = callbacks();
1941 let offer = renegotiation_body(
1942 &from,
1943 &callbacks,
1944 "v=0\r\n",
1945 "AB",
1946 &["Audio".to_owned()],
1947 true,
1948 false,
1949 );
1950 let negotiation = &offer["mediaNegotiation"];
1951 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1952 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1953 let same_peer = renegotiation_body(
1954 &from,
1955 &callbacks,
1956 "v=0\r\n",
1957 "AB",
1958 &["Audio".to_owned(), "Video".to_owned()],
1959 false,
1960 true,
1961 );
1962 assert_eq!(
1963 same_peer["mediaNegotiation"]["mediaContent"]["newOffer"],
1964 false
1965 );
1966 assert_eq!(
1967 same_peer["mediaNegotiation"]["mediaContent"]["requiredFeatures"],
1968 "nonByPass"
1969 );
1970 assert!(
1971 same_peer["mediaNegotiation"]["mediaContent"]
1972 .get("mediaDescriptions")
1973 .is_none()
1974 );
1975 assert!(negotiation["mediaContent"]["mediaDescriptions"].is_object());
1976 assert_eq!(
1977 same_peer["mediaNegotiation"]["callModalities"],
1978 json!(["Audio", "Video"])
1979 );
1980 assert!(
1981 negotiation["links"]["mediaAnswer"]
1982 .as_str()
1983 .unwrap()
1984 .ends_with("/call/mediaAnswer/")
1985 );
1986 assert!(
1987 negotiation["links"]["rejection"]
1988 .as_str()
1989 .unwrap()
1990 .ends_with("/call/rejection/")
1991 );
1992 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
1993 assert!(
1994 answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
1995 .as_str()
1996 .unwrap()
1997 .ends_with("/call/mediaAcknowledgement/")
1998 );
1999 }
2000
2001 #[test]
2002 fn a_video_call_invites_with_audio_and_video() {
2003 let from = from();
2004 let callbacks = callbacks();
2005 let target = InviteTarget::People {
2006 callees: vec![callee("8:orgid:b", "Bea")],
2007 thread_id: "19:a_b@unq.gbl.spaces".into(),
2008 };
2009 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
2010 let body = epconv_body(&Invitation {
2011 from: &from,
2012 offer_sdp: "v=0\r\n",
2013 media_leg_id: "AB",
2014 callbacks: &callbacks,
2015 target: &target,
2016 modalities: &modalities,
2017 direct: true,
2018 });
2019 assert_eq!(
2020 body["callInvitation"]["callModalities"],
2021 json!(["Audio", "Video"])
2022 );
2023 }
2024
2025 #[test]
2026 fn people_calls_dial_out_and_echo_does_not() {
2027 let people = InviteTarget::People {
2028 callees: vec![callee("8:orgid:b", "Bea")],
2029 thread_id: "19:a_b@unq.gbl.spaces".into(),
2030 };
2031 assert_eq!(
2032 body_for(&people)["conversationRequest"]["suppressDialout"],
2033 false
2034 );
2035 assert_eq!(
2036 body_for(&InviteTarget::Echo)["conversationRequest"]["suppressDialout"],
2037 true
2038 );
2039 }
2040
2041 #[test]
2042 fn ringing_progress_names_the_sender() {
2043 let body = ringing_body(&from());
2044 assert_eq!(body["callProgress"]["status"], "ringing");
2045 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
2046 }
2047}