BlueGit

ict rusty-teams

Files

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

signaling.rs

signaling.rs 53.3 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::recording::{self, Consent, RecordingCommand, StartDetails};
8use crate::transfer::{self, TransferTarget};
9use crate::error::{Error, Result};
10use crate::organizer::{self, Invitee, Target};
11use crate::roster::MeetingRole;
12use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
13use crate::relay::ic3_scope;
14use crate::timeline::Timeline;
15use crate::trouter_events::{CallbackLinks, acceptance_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 CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
26const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
27const BACKEND_SUFFIX: &str = ".skype.com";
28const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
29const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
30const CONVERSATION_LINK_NAMES: [&str; 11] = [
31 "conversationEnd",
32 "conversationUpdate",
33 "localParticipantUpdate",
34 "addParticipantSuccess",
35 "addParticipantFailure",
36 "addModalitySuccess",
37 "addModalityFailure",
38 "confirmUnmute",
39 "receiveMessage",
40 "contentSharingUpdate",
41 "contentSharingEnd",
42];
43const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
44 "conversationEnd",
45 "conversationUpdate",
46 "localParticipantUpdate",
47 "addParticipantSuccess",
48 "addParticipantFailure",
49 "receiveMessage",
50];
51const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
52const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
53pub(crate) const MEETING_MESSAGE_ID: &str = "0";
54const RAISE_HANDS: &str = "raiseHands";
55const CANCEL_CODE: i64 = 487;
56const DECLINE_CODE: i64 = 603;
57
58#[derive(Debug, Clone)]
59pub struct Participant {
60 pub mri: String,
61 pub display_name: String,
62 pub endpoint_id: String,
63 pub participant_id: String,
64 pub language_id: String,
65}
66
67impl Participant {
68 pub fn wire(&self) -> Value {
69 json!({
70 "id": self.mri,
71 "displayName": self.display_name,
72 "endpointId": self.endpoint_id,
73 "participantId": self.participant_id,
74 "languageId": self.language_id,
75 })
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct Callee {
81 pub mri: String,
82 pub display_name: String,
83}
84
85#[derive(Debug, Clone, PartialEq)]
86pub struct MeetingTarget {
87 pub thread_id: String,
88 pub tenant_id: String,
89 pub organizer_id: String,
90 pub meeting_data: Option<Value>,
91}
92
93#[derive(Debug, Clone, PartialEq)]
94pub enum InviteTarget {
95 Echo,
96 People { callees: Vec<Callee>, thread_id: String },
97 Meeting(MeetingTarget),
98}
99
100#[derive(Debug, Clone)]
101pub struct TenantRouting {
102 pub region: String,
103 pub partition: String,
104 pub ring: String,
105}
106
107impl Default for TenantRouting {
108 fn default() -> Self {
109 TenantRouting {
110 region: "de".into(),
111 partition: "de01".into(),
112 ring: "general".into(),
113 }
114 }
115}
116
117#[derive(Debug, Clone)]
118pub struct Conversation {
119 pub controller: String,
120 pub links: BTreeMap<String, String>,
121 pub chat_thread: Option<String>,
122}
123
124impl Conversation {
125 pub fn link(&self, name: &str) -> Result<&str> {
126 self.links
127 .get(name)
128 .map(String::as_str)
129 .ok_or_else(|| Error::Signaling(format!("conversation has no '{name}' link")))
130 }
131}
132
133fn host_of(url: &str) -> Result<&str> {
134 url.strip_prefix("https://")
135 .and_then(|rest| rest.split(['/', '?']).next())
136 .map(|authority| authority.split(':').next().unwrap_or(authority))
137 .ok_or_else(|| Error::Signaling("link is not https".into()))
138}
139
140/// Bearer requests only go to Teams hosts; links come from server answers.
141pub fn ensure_teams_url(url: &str) -> Result<()> {
142 let host = host_of(url)?;
143 if ALLOWED_HOST_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) || host == "teams.microsoft.com" {
144 Ok(())
145 } else {
146 Err(Error::Signaling(format!("refusing link to host {host}")))
147 }
148}
149
150fn is_backend_host(host: &str) -> bool {
151 host.len() > BACKEND_SUFFIX.len()
152 && host.ends_with(BACKEND_SUFFIX)
153 && !host.starts_with('.')
154 && !host.contains("..")
155 && host
156 .bytes()
157 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-')
158}
159
160/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
161pub fn routed_url(url: &str) -> Result<String> {
162 let host = host_of(url)?;
163 if !is_backend_host(host) {
164 ensure_teams_url(url)?;
165 return Ok(url.to_owned());
166 }
167 let rest = &url["https://".len()..];
168 let path = rest.find(['/', '?']).map_or("", |position| &rest[position..]);
169 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
170}
171
172const FAILURE_BODY_CHARS: usize = 240;
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum LeaveReason {
176 Hangup,
177 Cancel,
178}
179
180fn spaces_scope() -> Scope {
181 Scope::new(SPACES, AUTHZ_SCOPE_NAME)
182}
183
184pub struct Signaling {
185 session: Session,
186 poll_session: Session,
187 chain_id: String,
188 routing: TenantRouting,
189 timeline: Timeline,
190 endpoint_state_sequence: std::sync::atomic::AtomicU32,
191 state_sequence: std::sync::atomic::AtomicU32,
192}
193
194pub struct Invitation<'a> {
195 pub from: &'a Participant,
196 pub offer_sdp: &'a str,
197 pub media_leg_id: &'a str,
198 pub callbacks: &'a CallbackLinks,
199 pub target: &'a InviteTarget,
200 pub modalities: &'a [String],
201}
202
203pub struct Answer<'a> {
204 pub from: &'a Participant,
205 pub answer_sdp: &'a str,
206 pub media_leg_id: &'a str,
207 pub callbacks: &'a CallbackLinks,
208 pub modalities: &'a [String],
209}
210
211pub struct AttachRequest<'a> {
212 pub from: &'a Participant,
213 pub callbacks: &'a CallbackLinks,
214 pub controller: Option<&'a str>,
215 pub needs_media: bool,
216}
217
218#[derive(Debug, Clone)]
219pub struct Attached {
220 pub offer_sdp: Option<String>,
221 pub from_mixer: bool,
222 pub modalities: Vec<String>,
223 pub links: BTreeMap<String, String>,
224 pub conversation: Option<Conversation>,
225}
226
227impl Signaling {
228 /// `poll_session` is a second CDP connection so the broker long poll never blocks the call requests.
229 pub fn new(session: Session, poll_session: Session, routing: TenantRouting, timeline: Timeline) -> Self {
230 Signaling {
231 session,
232 poll_session,
233 chain_id: uuid::Uuid::new_v4().to_string(),
234 routing,
235 timeline,
236 endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2),
237 state_sequence: std::sync::atomic::AtomicU32::new(0),
238 }
239 }
240
241 fn request(&self, method: Method, url: &str, body: Option<Value>) -> Request {
242 let mut request = match body {
243 Some(body) => Request::with_body(method, url, body),
244 None => Request { method, ..Request::get(url) },
245 };
246 request.headers = vec![
247 ("X-Microsoft-Skype-Chain-ID".into(), self.chain_id.clone()),
248 ("X-Microsoft-Skype-Message-ID".into(), uuid::Uuid::new_v4().to_string()),
249 ("X-Microsoft-Skype-Client".into(), CLIENT_HEADER.into()),
250 ("MS-Teams-Region".into(), self.routing.region.clone()),
251 ("MS-Teams-Partition".into(), self.routing.partition.clone()),
252 ("MS-Teams-Ring".into(), self.routing.ring.clone()),
253 ("X-MS-Migration".into(), "True".into()),
254 ("content-type".into(), "application/json".into()),
255 ];
256 request
257 }
258
259 async fn exchange(&self, session: &Session, label: &str, mut request: Request) -> Result<ApiResponse> {
260 request.url = routed_url(&request.url)?;
261 let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
262 self.timeline.record(label, format!("HTTP {}", response.status));
263 if !response.is_success() {
264 let reason: String = response.body.to_string().chars().take(FAILURE_BODY_CHARS).collect();
265 return Err(Error::Signaling(format!("{label} answered HTTP {} {reason}", response.status)));
266 }
267 Ok(response)
268 }
269
270 async fn send(&self, label: &str, method: Method, url: &str, body: Option<Value>) -> Result<ApiResponse> {
271 self.exchange(&self.session, label, self.request(method, url, body)).await
272 }
273
274 pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> {
275 self.send(label, Method::Post, url, Some(body)).await.map(|_| ())
276 }
277
278 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
279 self.send(label, Method::Post, url, None).await.map(|_| ())
280 }
281
282 pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result<Conversation> {
283 let response = self
284 .send("POST epconv", Method::Post, EPCONV_URL, Some(epconv_body(invitation)))
285 .await?;
286 conversation_from(&response.body)
287 }
288
289 pub async fn subscribe_meeting(
290 &self,
291 from: &Participant,
292 callbacks: &CallbackLinks,
293 meeting: &MeetingTarget,
294 ) -> Result<Conversation> {
295 let body = subscribe_body(from, callbacks, meeting);
296 let response = self.send("POST epconv subscribe", Method::Post, EPCONV_URL, Some(body)).await?;
297 conversation_from(&response.body)
298 }
299
300 /// Opens a roster-only conversation for the meeting ID; the caller leaves it once the target is read.
301 pub async fn resolve_meeting(
302 &self,
303 from: &Participant,
304 callbacks: &CallbackLinks,
305 meeting_data: &Value,
306 ) -> Result<(MeetingTarget, Conversation)> {
307 let body = crate::join::resolve_body(from, callbacks, meeting_data);
308 let response = self.send("POST epconv resolve", Method::Post, EPCONV_URL, Some(body)).await?;
309 let target = crate::join::target_from_answer(&response.body, meeting_data)?;
310 Ok((target, conversation_from(&response.body)?))
311 }
312
313 /// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.
314 pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {
315 let response = self
316 .send("POST join", Method::Post, &subscribed.controller, Some(epconv_body(invitation)))
317 .await?;
318 let mut links = subscribed.links.clone();
319 if let Ok(joined) = conversation_from(&response.body) {
320 links.extend(joined.links);
321 }
322 Ok(Conversation {
323 controller: subscribed.controller.clone(),
324 links,
325 chat_thread: subscribed.chat_thread.clone(),
326 })
327 }
328
329 pub fn next_endpoint_sequence(&self) -> u32 {
330 self.endpoint_state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
331 }
332
333 pub async fn update_endpoint_state(&self, conversation: &Conversation, from: &Participant, muted: bool) -> Result<()> {
334 let body = json!({
335 "from": from.wire(),
336 "endpointState": {
337 "endpointStateSequenceNumber": self.next_endpoint_sequence(),
338 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
339 "state": {"isMuted": muted},
340 },
341 });
342 let url = conversation.link("updateEndpointState")?;
343 self.post_json("POST updateEndpointState", url, body).await
344 }
345
346 fn next_state_sequence(&self) -> u32 {
347 self.state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
348 }
349
350 pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<HandReceipt> {
351 let body = raise_hand_body(from.wire(), self.next_state_sequence());
352 let response = self.send("POST publishState", Method::Post, conversation.link("publishState")?, Some(body)).await?;
353 Ok(hand_receipt_from(&response.body))
354 }
355
356 pub async fn lower_hands(&self, conversation: &Conversation, from: &Participant, state_ids: &[String]) -> Result<()> {
357 let body = remove_states_body(from.wire(), self.next_state_sequence(), state_ids);
358 self.post_json("POST removeState", conversation.link("removeState")?, body).await
359 }
360
361 pub async fn lower_all_hands(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
362 let body = remove_all_hands_body(from.wire(), self.next_state_sequence());
363 self.post_json("POST removeState", conversation.link("removeState")?, body).await
364 }
365
366 pub async fn send_reaction(&self, conversation: &Conversation, from: &Participant, reaction: Reaction) -> Result<()> {
367 let body = reaction_message(from.wire(), reaction, &uuid::Uuid::new_v4().to_string(), &uuid::Uuid::new_v4().to_string());
368 self.post_json("POST sendMessage", conversation.link("sendMessage")?, body).await
369 }
370
371 pub async fn update_media_descriptions(&self, url: &str, descriptions: &[MediaDescription], request_id: u32) -> Result<()> {
372 let body = json!({
373 "UpdateMediaDescriptions": {
374 "mediaDescriptions": {
375 "descriptions": descriptions.iter().map(MediaDescription::wire).collect::<Vec<_>>(),
376 "requestId": request_id,
377 },
378 },
379 });
380 self.post_json("POST updateMediaDescriptions", url, body).await
381 }
382
383 pub async fn add_echo_bot(
384 &self,
385 conversation: &Conversation,
386 from: &Participant,
387 thread_id: Option<&str>,
388 callbacks: &CallbackLinks,
389 ) -> Result<()> {
390 let body = json!({
391 "disableUnmute": false,
392 "participants": {
393 "from": from.wire(),
394 "to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
395 },
396 "participantInvitationData": {},
397 "replacementDetails": null,
398 "groupContext": null,
399 "groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})),
400 "links": {
401 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
402 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
403 },
404 });
405 let url = conversation.link("addParticipantAndModality")?;
406 self.post_json("POST add (echo bot)", url, body).await
407 }
408
409 pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
410 self.put_endpoint_metadata(conversation, from, json!({"holographicCapabilities": 3})).await
411 }
412
413 pub async fn set_caption_preference(&self, conversation: &Conversation, from: &Participant, captions: bool) -> Result<()> {
414 self.put_endpoint_metadata(conversation, from, captions::endpoint_metadata(captions)).await
415 }
416
417 async fn put_endpoint_metadata(&self, conversation: &Conversation, from: &Participant, metadata: Value) -> Result<()> {
418 let body = json!({"participants": {"from": from.wire()}, "endpointMetadata": metadata});
419 let url = conversation.link("updateEndpointMetadata")?;
420 self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())
421 }
422
423 pub async fn admit(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {
424 let body = organizer::admit_body(from.wire(), target, callbacks, &uuid::Uuid::new_v4().to_string());
425 self.send("POST admit", Method::Post, conversation.link("admit")?, Some(body)).await.map(|response| response.status)
426 }
427
428 pub async fn admit_all(&self, conversation: &Conversation, from: &Participant, callbacks: &CallbackLinks) -> Result<u16> {
429 let body = organizer::admit_all_body(from.wire(), callbacks, &uuid::Uuid::new_v4().to_string());
430 self.send("POST admitAll", Method::Post, conversation.link("admitAll")?, Some(body)).await.map(|response| response.status)
431 }
432
433 pub async fn remove_participant(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {
434 let body = organizer::remove_participant_body(from.wire(), target, callbacks);
435 self.send("POST removeParticipant", Method::Post, conversation.link("removeParticipant")?, Some(body)).await.map(|response| response.status)
436 }
437
438 pub async fn mute_participant(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {
439 let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]);
440 self.send("POST mute", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)
441 }
442
443 pub async fn mute_everyone(&self, conversation: &Conversation, from: &Participant, others: &[String]) -> Result<u16> {
444 let body = organizer::mute_everyone_body(from.wire(), others);
445 self.send("POST mute (all)", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)
446 }
447
448 pub async fn spotlight(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {
449 let body = organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri);
450 self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
451 }
452
453 pub async fn set_lock(&self, conversation: &Conversation, from: &Participant, locked: bool) -> Result<u16> {
454 let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence());
455 self.send("PUT updateMeetingSettings", Method::Put, conversation.link("updateMeetingSettings")?, Some(body)).await.map(|response| response.status)
456 }
457
458 pub async fn change_role(&self, conversation: &Conversation, from: &Participant, mri: &str, role: MeetingRole) -> Result<u16> {
459 let body = organizer::role_body(from.wire(), mri, role);
460 self.send("POST updateParticipantRole", Method::Post, conversation.link("updateParticipantRole")?, Some(body)).await.map(|response| response.status)
461 }
462
463 pub async fn publish_attendee_state(&self, conversation: &Conversation, from: &Participant, state_type: &str, mri: &str) -> Result<u16> {
464 let body = organizer::attendee_state_body(from.wire(), state_type, self.next_state_sequence(), mri);
465 self.send("POST publishState (attendee)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
466 }
467
468 pub async fn add_participants(
469 &self,
470 conversation: &Conversation,
471 from: &Participant,
472 callees: &[Callee],
473 group_thread: Option<&str>,
474 meeting: Option<&MeetingTarget>,
475 callbacks: &CallbackLinks,
476 ) -> Result<u16> {
477 let invitees: Vec<Invitee> = callees
478 .iter()
479 .map(|callee| Invitee { callee: callee.clone(), participant_id: uuid::Uuid::new_v4().to_string() })
480 .collect();
481 let group_chat = group_thread.map_or(Value::Null, |thread_id| organizer::group_chat_for(thread_id, meeting.is_some()));
482 let body = organizer::add_participants_body(from.wire(), &invitees, group_chat, meeting, callbacks);
483 let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?;
484 self.send("POST add (invite)", Method::Post, url, Some(body)).await.map(|response| response.status)
485 }
486
487 pub async fn add_caption_bot(
488 &self,
489 conversation: &Conversation,
490 from: &Participant,
491 thread_id: &str,
492 callbacks: &CallbackLinks,
493 ) -> Result<u16> {
494 let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);
495 let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));
496 request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
497 self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)
498 }
499
500 pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {
501 ensure_teams_url(command_url)?;
502 let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
503 let body = captions::command_body(action, &from.mri, &from.participant_id, &timestamp);
504 self.bot_command(command_url, body, "caption command").await.map(|_| ())
505 }
506
507 pub async fn caption_language_command(&self, command_url: &str, from: &Participant, language_tag: &str) -> Result<()> {
508 ensure_teams_url(command_url)?;
509 let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
510 let body = captions::language_body(&from.mri, &from.participant_id, &timestamp, language_tag);
511 self.bot_command(command_url, body, "caption language command").await.map(|_| ())
512 }
513
514 async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
515 let arguments = json!({
516 "url": command_url,
517 "body": body,
518 "recorderResource": captions::RECORDER_RESOURCE,
519 "recorderScope": captions::RECORDER_SCOPE,
520 "requestId": uuid::Uuid::new_v4().to_string(),
521 "chainId": self.chain_id,
522 });
523 let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;
524 let status = answer["status"].as_u64().unwrap_or_default();
525 self.timeline.record(format!("POST {label}"), format!("HTTP {status}"));
526 if (200..300).contains(&status) {
527 return Ok(status as u16);
528 }
529 let reason = answer["error"].as_str().unwrap_or("no answer");
530 Err(Error::Signaling(format!("{label} answered HTTP {status} {reason}")))
531 }
532
533 pub async fn recording_command(&self, command_url: &str, command: RecordingCommand, from: &Participant, title: &str) -> Result<u16> {
534 ensure_teams_url(command_url)?;
535 let now = chrono::Utc::now();
536 let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
537 let file_name = recording::file_name(title, now);
538 let correlation_id = uuid::Uuid::new_v4().to_string();
539 let details = StartDetails {
540 own_mri: &from.mri,
541 participant_leg_id: &from.participant_id,
542 timestamp: &timestamp,
543 file_name: &file_name,
544 meeting_title: title,
545 organizer_name: &from.display_name,
546 correlation_id: &correlation_id,
547 };
548 self.bot_command(command_url, recording::command_body(command, details), "recording command").await
549 }
550
551 pub async fn consent_to_recording(&self, conversation: &Conversation, from: &Participant, consent: Consent) -> Result<u16> {
552 let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent);
553 self.send("POST publishState (recording consent)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
554 }
555
556 pub async fn transfer(&self, transfer_url: &str, from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks) -> Result<()> {
557 let body = transfer::transfer_body(from, target, callbacks);
558 self.post_json("POST transfer", transfer_url, body).await
559 }
560
561 /// One broker long poll; answers the next subscribe URL.
562 pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {
563 let mut request = self.request(Method::Get, url, None);
564 request.headers.push(("X-UseBatching".into(), "1".into()));
565 let response = self.exchange(&self.poll_session, "GET broker subscribe", request).await?;
566 Ok(response.body["nextSubscribeUrl"].as_str().map(str::to_owned))
567 }
568
569 pub async fn leave(&self, conversation: &Conversation, from: &Participant, reason: LeaveReason) -> Result<()> {
570 let url = conversation.link("leave")?;
571 self.post_json("POST leave", url, leave_body(from, reason)).await
572 }
573
574 pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
575 self.send(
576 "DELETE conversation",
577 Method::Delete,
578 &conversation.controller,
579 Some(end_for_all_body(from)),
580 )
581 .await
582 .map(|_| ())
583 }
584
585 pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> {
586 let response = self
587 .send("POST attach", Method::Post, url, Some(attach_body(request)))
588 .await?;
589 attached_from(&response.body)
590 }
591
592 pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> {
593 self.post_json("POST progress", url, ringing_body(from)).await
594 }
595
596 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
597 self.post_json("POST acceptance", url, acceptance_body(answer)).await
598 }
599
600 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
601 self.send("DELETE callLeg (decline)", Method::Delete, call_leg_url, Some(decline_body()))
602 .await
603 .map(|_| ())
604 }
605
606 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
607 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
608 .await
609 }
610
611 pub async fn keep_conversation_alive(
612 &self,
613 conversation: &Conversation,
614 from: &Participant,
615 callbacks: &CallbackLinks,
616 ) -> Result<()> {
617 let url = conversation.link("notificationLinks")?;
618 self.post_json("POST notificationLinks", url, notification_links_body(from, callbacks)).await
619 }
620}
621
622fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
623 names
624 .iter()
625 .map(|name| ((*name).to_owned(), Value::String(make(name))))
626 .collect()
627}
628
629fn roster_request(callbacks: &CallbackLinks) -> Value {
630 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
631}
632
633fn conversation_properties() -> Value {
634 json!({
635 "allowConversationWithoutHost": true,
636 "enableGroupCallEventMessages": true,
637 "enableGroupCallUpgradeMessage": false,
638 "enableGroupCallMeetupGeneration": false,
639 })
640}
641
642pub(crate) fn endpoint_state() -> Value {
643 json!({
644 "endpointStateSequenceNumber": 2,
645 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
646 })
647}
648
649fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
650 let mut content = json!({
651 "contentType": SDP_CONTENT_TYPE,
652 "blob": sdp,
653 "clientLocation": "DE",
654 "mediaLegId": media_leg_id,
655 });
656 if with_descriptions {
657 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
658 }
659 content
660}
661
662fn media_controller_links(callbacks: &CallbackLinks) -> Value {
663 json!({
664 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
665 "csrcInfo": callbacks.call("csrcInfo"),
666 })
667}
668
669fn group_chat(target: &InviteTarget) -> Value {
670 match target {
671 InviteTarget::Echo => Value::Null,
672 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
673 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
674 }
675}
676
677fn callee_wire(callee: &Callee) -> Value {
678 json!({"id": callee.mri, "displayName": callee.display_name})
679}
680
681pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
682 let callbacks = invitation.callbacks;
683 let target = invitation.target;
684 let to: Vec<Value> = match target {
685 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
686 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
687 };
688 let mut request = json!({
689 "conversationType": null,
690 "subject": null,
691 "suppressDialout": to.is_empty(),
692 "roster": roster_request(callbacks),
693 "properties": conversation_properties(),
694 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
695 });
696 if matches!(target, InviteTarget::Echo) {
697 request["scenario"] = json!("UserInitiatedTestCall");
698 }
699 let (meeting_info, meeting_data) = match target {
700 InviteTarget::Meeting(meeting) => (
701 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
702 meeting.meeting_data.clone().unwrap_or(Value::Null),
703 ),
704 _ => (Value::Null, Value::Null),
705 };
706 json!({
707 "conversationRequest": request,
708 "contentSharing": null,
709 "participants": {"from": invitation.from.wire(), "to": to},
710 "capabilities": null,
711 "endpointCapabilities": ENDPOINT_CAPABILITIES,
712 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
713 "endpointMetadata": {"holographicCapabilities": 3},
714 "groupContext": null,
715 "groupChat": group_chat(target),
716 "meetingInfo": meeting_info,
717 "meetingData": meeting_data,
718 "endpointState": endpoint_state(),
719 "callInvitation": {
720 "callModalities": invitation.modalities,
721 "replaces": null,
722 "transferor": null,
723 "clientTransferContext": null,
724 "customContext": null,
725 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
726 "clientContentForMediaController": media_controller_links(callbacks),
727 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
728 "emergencyContent": null,
729 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
730 },
731 })
732}
733
734pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value {
735 json!({
736 "roster": roster_request(callbacks),
737 "properties": conversation_properties(),
738 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
739 })
740}
741
742pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
743 json!({
744 "conversationRequest": subscribe_request(callbacks),
745 "participants": {"from": from.wire()},
746 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
747 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
748 "endpointState": endpoint_state(),
749 })
750}
751
752pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
753 let call_end = match reason {
754 LeaveReason::Hangup => json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}),
755 LeaveReason::Cancel => json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}),
756 };
757 json!({
758 "participants": {"from": from.wire()},
759 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
760 "callTransactionEnd": call_end,
761 })
762}
763
764pub fn end_for_all_body(from: &Participant) -> Value {
765 json!({
766 "participants": {"from": from.wire()},
767 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
768 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
769 })
770}
771
772pub fn decline_body() -> Value {
773 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
774}
775
776pub fn ringing_body(from: &Participant) -> Value {
777 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
778}
779
780pub fn attach_body(request: &AttachRequest<'_>) -> Value {
781 let callbacks = request.callbacks;
782 let mut body = json!({
783 "attach": {
784 "requireMediaContent": request.needs_media,
785 "links": {"end": callbacks.call("end")},
786 },
787 "capabilities": null,
788 "endpointCapabilities": ENDPOINT_CAPABILITIES,
789 });
790 if let Some(controller) = request.controller {
791 body["additionalActions"] = json!([{
792 "name": "join",
793 "url": controller,
794 "waitForResponse": true,
795 "input": {
796 "conversationRequest": {
797 "roster": roster_request(callbacks),
798 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
799 },
800 "participants": {"from": request.from.wire()},
801 "endpointMetadata": {"holographicCapabilities": 3},
802 "endpointCapabilities": ENDPOINT_CAPABILITIES,
803 },
804 }]);
805 }
806 body
807}
808
809pub fn acceptance_body(answer: &Answer<'_>) -> Value {
810 let callbacks = answer.callbacks;
811 json!({
812 "callAcceptance": {
813 "acceptedBy": answer.from.wire(),
814 "acceptedCallModalities": answer.modalities,
815 "endpointCapabilities": ENDPOINT_CAPABILITIES,
816 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
817 "links": acceptance_links(callbacks),
818 "clientContentForMediaController": media_controller_links(callbacks),
819 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
820 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
821 "callKeepAliveInterval": null,
822 },
823 })
824}
825
826pub fn renegotiation_body(
827 from: &Participant,
828 callbacks: &CallbackLinks,
829 offer_sdp: &str,
830 media_leg_id: &str,
831 modalities: &[String],
832 new_offer: bool,
833) -> Value {
834 json!({
835 "mediaNegotiation": {
836 "callModalities": modalities,
837 "sender": from.wire(),
838 "links": {
839 "mediaAnswer": callbacks.call("mediaAnswer"),
840 "rejection": callbacks.call("rejection"),
841 },
842 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer),
843 },
844 })
845}
846
847fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool) -> Value {
848 let mut content = media_content(sdp, media_leg_id, true);
849 content["newOffer"] = json!(new_offer);
850 content
851}
852
853pub fn escalation_answer_body(
854 from: &Participant,
855 callbacks: &CallbackLinks,
856 answer_sdp: &str,
857 media_leg_id: &str,
858) -> Value {
859 json!({
860 "mediaAnswer": {
861 "callModalities": AUDIO_MODALITIES,
862 "sender": from.wire(),
863 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
864 "clientContentForMediaController": media_controller_links(callbacks),
865 "mediaContent": media_content(answer_sdp, media_leg_id, false),
866 },
867 })
868}
869
870pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
871 json!({
872 "participants": {"from": from.wire()},
873 "roster": roster_request(callbacks),
874 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
875 })
876}
877
878fn conversation_from(body: &Value) -> Result<Conversation> {
879 let controller = body["conversationController"]
880 .as_str()
881 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
882 .to_owned();
883 let links = body["links"]
884 .as_object()
885 .map(|links| {
886 links
887 .iter()
888 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
889 .collect()
890 })
891 .unwrap_or_default();
892 Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })
893}
894
895#[derive(Debug, Clone, PartialEq, Eq)]
896pub struct HandReceipt {
897 pub state_id: Option<String>,
898 pub rank: u64,
899}
900
901pub fn hand_receipt_from(body: &Value) -> HandReceipt {
902 let published = &body["publishStateResponse"];
903 HandReceipt {
904 state_id: published["stateId"].as_str().map(str::to_owned),
905 rank: published["typeRank"].as_u64().unwrap_or(u64::MAX),
906 }
907}
908
909pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
910 json!({
911 "from": from,
912 "publishedState": {
913 "stateType": RAISE_HANDS,
914 "level": "user",
915 "content": {"skinTone": DEFAULT_SKIN_TONE},
916 "sequenceNumber": sequence_number,
917 },
918 })
919}
920
921pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value {
922 json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids})
923}
924
925pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value {
926 json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS})
927}
928
929pub fn chat_thread_id(body: &Value) -> Option<String> {
930 body["activeModalities"]["groupChat"]["threadId"].as_str().map(str::to_owned)
931}
932
933fn attached_from(body: &Value) -> Result<Attached> {
934 let invitation = &body["callInvitation"];
935 if invitation.is_null() {
936 return Err(Error::Signaling("attach answer without callInvitation".into()));
937 }
938 let links = invitation["links"]
939 .as_object()
940 .map(|links| {
941 links
942 .iter()
943 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
944 .collect()
945 })
946 .unwrap_or_default();
947 let modalities = invitation["callModalities"]
948 .as_array()
949 .map(|items| items.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect())
950 .unwrap_or_default();
951 Ok(Attached {
952 offer_sdp: invitation["mediaContent"]["blob"].as_str().map(str::to_owned),
953 from_mixer: invitation["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
954 modalities,
955 links,
956 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
957 })
958}
959
960#[derive(Debug, Clone)]
961pub struct SelfIdentity {
962 pub object_id: String,
963 pub display_name: String,
964}
965
966pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {
967 let response = session
968 .request(
969 Method::Get,
970 &format!("{GRAPH}/v1.0/me?$select=id,displayName"),
971 &Scope::graph("User.Read"),
972 None,
973 )
974 .await?;
975 Ok(SelfIdentity {
976 object_id: response.body["id"]
977 .as_str()
978 .ok_or_else(|| Error::Signaling("graph /me without id".into()))?
979 .to_owned(),
980 display_name: response.body["displayName"].as_str().unwrap_or_default().to_owned(),
981 })
982}
983
984/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.
985pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<Option<String>> {
986 let bot_id = ECHO_BOT_MRI.trim_start_matches("28:");
987 for thread_id in [
988 format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
989 format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
990 ] {
991 let url = format!(
992 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
993 thread_id.replace(':', "%3A").replace('@', "%40")
994 );
995 let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);
996 if response.is_success() {
997 return Ok(Some(thread_id));
998 }
999 }
1000 Ok(None)
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005 use super::*;
1006
1007 #[test]
1008 fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() {
1009 let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4);
1010 assert_eq!(raised["publishedState"]["stateType"], "raiseHands");
1011 assert_eq!(raised["publishedState"]["level"], "user");
1012 assert_eq!(raised["publishedState"]["sequenceNumber"], 4);
1013 let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]);
1014 assert_eq!(lowered["scope"], "specified");
1015 assert_eq!(lowered["stateIds"][0], "s-1");
1016 let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6);
1017 assert_eq!(all["scope"], "all");
1018 assert_eq!(all["stateType"], "raiseHands");
1019 }
1020
1021 #[test]
1022 fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() {
1023 let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}});
1024 assert_eq!(hand_receipt_from(&body), HandReceipt { state_id: Some("s-9".to_owned()), rank: 3 });
1025 assert_eq!(hand_receipt_from(&json!({})), HandReceipt { state_id: None, rank: u64::MAX });
1026 }
1027
1028 #[test]
1029 fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
1030 let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
1031 assert_eq!(chat_thread_id(&body).as_deref(), Some("19:meeting_abc@thread.v2"));
1032 assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None);
1033 }
1034
1035 fn from() -> Participant {
1036 Participant {
1037 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
1038 display_name: "Test".into(),
1039 endpoint_id: "e".into(),
1040 participant_id: "p".into(),
1041 language_id: "en-gb".into(),
1042 }
1043 }
1044
1045 fn callbacks() -> CallbackLinks {
1046 CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1")
1047 }
1048
1049 fn body_for(target: &InviteTarget) -> Value {
1050 let from = from();
1051 let callbacks = callbacks();
1052 epconv_body(&Invitation {
1053 from: &from,
1054 offer_sdp: "v=0\r\n",
1055 media_leg_id: "AB",
1056 callbacks: &callbacks,
1057 target,
1058 modalities: &["Audio".to_owned()],
1059 })
1060 }
1061
1062 fn callee(mri: &str, name: &str) -> Callee {
1063 Callee {
1064 mri: mri.into(),
1065 display_name: name.into(),
1066 }
1067 }
1068
1069 #[test]
1070 fn only_teams_hosts_get_the_bearer() {
1071 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
1072 assert!(ensure_teams_url(EPCONV_URL).is_ok());
1073 assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok());
1074 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1075 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1076 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1077 }
1078
1079 #[test]
1080 fn backend_links_go_through_flightproxy() {
1081 assert_eq!(
1082 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2").unwrap(),
1083 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
1084 );
1085 assert_eq!(
1086 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
1087 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1088 );
1089 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1090 assert!(routed_url("https://Evil.skype.com/x").is_err());
1091 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1092 assert!(routed_url("http://cc.skype.com/x").is_err());
1093 assert!(routed_url("https://.skype.com/x").is_err());
1094 }
1095
1096 #[test]
1097 fn echo_body_matches_the_captured_test_call_shape() {
1098 let body = body_for(&InviteTarget::Echo);
1099 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
1100 assert_eq!(body["participants"]["to"], json!([]));
1101 assert_eq!(body["groupChat"], Value::Null);
1102 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1103 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
1104 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
1105 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 11);
1106 }
1107
1108 #[test]
1109 fn one_to_one_body_names_the_callee_and_the_chat() {
1110 let target = InviteTarget::People {
1111 callees: vec![callee("8:orgid:b", "Bea")],
1112 thread_id: "19:a_b@unq.gbl.spaces".into(),
1113 };
1114 let body = body_for(&target);
1115 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
1116 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
1117 assert!(body["conversationRequest"].get("scenario").is_none());
1118 assert_eq!(body["meetingInfo"], Value::Null);
1119 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1120 }
1121
1122 #[test]
1123 fn group_body_invites_every_callee_on_the_group_thread() {
1124 let target = InviteTarget::People {
1125 callees: vec![callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di")],
1126 thread_id: "19:group@thread.v2".into(),
1127 };
1128 let body = body_for(&target);
1129 let to = body["participants"]["to"].as_array().unwrap();
1130 assert_eq!(to.len(), 3);
1131 assert_eq!(to[2]["id"], "8:orgid:d");
1132 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1133 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1134 }
1135
1136 #[test]
1137 fn meeting_join_body_carries_thread_and_meeting_info() {
1138 let target = InviteTarget::Meeting(MeetingTarget {
1139 thread_id: "19:meeting_x@thread.v2".into(),
1140 tenant_id: "tenant".into(),
1141 organizer_id: "organizer".into(),
1142 meeting_data: Some(json!({"meetingCode": "123"})),
1143 });
1144 let body = body_for(&target);
1145 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
1146 assert_eq!(body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}));
1147 assert_eq!(body["meetingData"]["meetingCode"], "123");
1148 assert_eq!(body["participants"]["to"], json!([]));
1149 assert!(body["conversationRequest"].get("scenario").is_none());
1150 assert!(body["endpointState"]["endpointProperties"].get("preheatProperties").is_none());
1151 }
1152
1153 #[test]
1154 fn meeting_subscribe_is_roster_only() {
1155 let meeting = MeetingTarget {
1156 thread_id: "19:meeting_x@thread.v2".into(),
1157 tenant_id: "tenant".into(),
1158 organizer_id: "organizer".into(),
1159 meeting_data: None,
1160 };
1161 let body = subscribe_body(&from(), &callbacks(), &meeting);
1162 assert!(body.get("callInvitation").is_none());
1163 assert!(body["participants"].get("to").is_none());
1164 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 6);
1165 assert_eq!(body["groupChat"]["messageId"], "0");
1166 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
1167 }
1168
1169 #[test]
1170 fn leave_bodies_differ_by_reason() {
1171 let hangup = leave_body(&from(), LeaveReason::Hangup);
1172 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
1173 let cancel = leave_body(&from(), LeaveReason::Cancel);
1174 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
1175 assert_eq!(cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
1176 assert_eq!(cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected");
1177 let end = end_for_all_body(&from());
1178 assert_eq!(end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated");
1179 }
1180
1181 #[test]
1182 fn decline_uses_603() {
1183 let body = decline_body();
1184 assert_eq!(body["callEnd"]["code"], 603);
1185 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1186 }
1187
1188 #[test]
1189 fn attach_asks_for_media_and_joins_the_conversation() {
1190 let from = from();
1191 let callbacks = callbacks();
1192 let body = attach_body(&AttachRequest {
1193 from: &from,
1194 callbacks: &callbacks,
1195 controller: Some("https://conv/controller"),
1196 needs_media: true,
1197 });
1198 assert_eq!(body["attach"]["requireMediaContent"], true);
1199 assert!(body["attach"]["links"]["end"].as_str().unwrap().ends_with("/call/end/"));
1200 let action = &body["additionalActions"][0];
1201 assert_eq!(action["name"], "join");
1202 assert_eq!(action["url"], "https://conv/controller");
1203 assert_eq!(action["waitForResponse"], true);
1204 assert_eq!(action["input"]["conversationRequest"]["links"].as_object().unwrap().len(), 6);
1205 let without = attach_body(&AttachRequest {
1206 from: &from,
1207 callbacks: &callbacks,
1208 controller: None,
1209 needs_media: false,
1210 });
1211 assert!(without.get("additionalActions").is_none());
1212 assert_eq!(without["attach"]["requireMediaContent"], false);
1213 }
1214
1215 #[test]
1216 fn attach_answer_yields_offer_links_and_conversation() {
1217 let body = json!({
1218 "callInvitation": {
1219 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
1220 "mediaContent": {"blob": "v=0\r\n"},
1221 "callModalities": ["Audio"],
1222 },
1223 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
1224 });
1225 let attached = attached_from(&body).unwrap();
1226 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
1227 assert_eq!(attached.links["callLeg"], "https://cc/leg");
1228 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
1229 let conversation = attached.conversation.unwrap();
1230 assert_eq!(conversation.controller, "https://conv/c");
1231 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
1232 assert!(attached_from(&json!({})).is_err());
1233 }
1234
1235 #[test]
1236 fn acceptance_carries_the_answer_and_callback_links() {
1237 let from = from();
1238 let callbacks = callbacks();
1239 let modalities = vec!["Audio".to_owned()];
1240 let body = acceptance_body(&Answer {
1241 from: &from,
1242 answer_sdp: "v=0\r\n",
1243 media_leg_id: "AB",
1244 callbacks: &callbacks,
1245 modalities: &modalities,
1246 });
1247 let accepted = &body["callAcceptance"];
1248 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
1249 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
1250 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
1251 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
1252 assert!(accepted["links"]["mediaRenegotiation"].as_str().unwrap().ends_with("/call/mediaRenegotiation/"));
1253 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1254 }
1255
1256 #[test]
1257 fn renegotiation_messages_name_their_reply_links() {
1258 let from = from();
1259 let callbacks = callbacks();
1260 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true);
1261 let negotiation = &offer["mediaNegotiation"];
1262 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1263 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1264 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false);
1265 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1266 assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1267 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1268 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
1269 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
1270 assert!(answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
1271 .as_str()
1272 .unwrap()
1273 .ends_with("/call/mediaAcknowledgement/"));
1274 }
1275
1276 #[test]
1277 fn a_video_call_invites_with_audio_and_video() {
1278 let from = from();
1279 let callbacks = callbacks();
1280 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1281 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1282 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities });
1283 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1284 }
1285
1286 #[test]
1287 fn people_calls_dial_out_and_echo_does_not() {
1288 let people = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1289 assert_eq!(body_for(&people)["conversationRequest"]["suppressDialout"], false);
1290 assert_eq!(body_for(&InviteTarget::Echo)["conversationRequest"]["suppressDialout"], true);
1291 }
1292
1293 #[test]
1294 fn ringing_progress_names_the_sender() {
1295 let body = ringing_body(&from());
1296 assert_eq!(body["callProgress"]["status"], "ringing");
1297 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
1298 }
1299}