BlueGit

ict rusty-teams

Files

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

signaling.rs

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