BlueGit

ict rusty-teams

Files

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

signaling.rs

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