BlueGit

ict rusty-teams

Files

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

signaling.rs

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