BlueGit

ict rusty-teams

Files

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

signaling.rs

signaling.rs 52.9 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 remove_participant(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {
429 let body = organizer::remove_participant_body(from.wire(), target, callbacks);
430 self.send("POST removeParticipant", Method::Post, conversation.link("removeParticipant")?, Some(body)).await.map(|response| response.status)
431 }
432
433 pub async fn mute_participant(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {
434 let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]);
435 self.send("POST mute", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)
436 }
437
438 pub async fn mute_everyone(&self, conversation: &Conversation, from: &Participant, others: &[String]) -> Result<u16> {
439 let body = organizer::mute_everyone_body(from.wire(), others);
440 self.send("POST mute (all)", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)
441 }
442
443 pub async fn spotlight(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {
444 let body = organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri);
445 self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
446 }
447
448 pub async fn set_lock(&self, conversation: &Conversation, from: &Participant, locked: bool) -> Result<u16> {
449 let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence());
450 self.send("PUT updateMeetingSettings", Method::Put, conversation.link("updateMeetingSettings")?, Some(body)).await.map(|response| response.status)
451 }
452
453 pub async fn change_role(&self, conversation: &Conversation, from: &Participant, mri: &str, role: MeetingRole) -> Result<u16> {
454 let body = organizer::role_body(from.wire(), mri, role);
455 self.send("POST updateParticipantRole", Method::Post, conversation.link("updateParticipantRole")?, Some(body)).await.map(|response| response.status)
456 }
457
458 pub async fn publish_attendee_state(&self, conversation: &Conversation, from: &Participant, state_type: &str, mri: &str) -> Result<u16> {
459 let body = organizer::attendee_state_body(from.wire(), state_type, self.next_state_sequence(), mri);
460 self.send("POST publishState (attendee)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
461 }
462
463 pub async fn add_participants(
464 &self,
465 conversation: &Conversation,
466 from: &Participant,
467 callees: &[Callee],
468 group_thread: Option<&str>,
469 meeting: Option<&MeetingTarget>,
470 callbacks: &CallbackLinks,
471 ) -> Result<u16> {
472 let invitees: Vec<Invitee> = callees
473 .iter()
474 .map(|callee| Invitee { callee: callee.clone(), participant_id: uuid::Uuid::new_v4().to_string() })
475 .collect();
476 let group_chat = group_thread.map_or(Value::Null, |thread_id| organizer::group_chat_for(thread_id, meeting.is_some()));
477 let body = organizer::add_participants_body(from.wire(), &invitees, group_chat, meeting, callbacks);
478 let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?;
479 self.send("POST add (invite)", Method::Post, url, Some(body)).await.map(|response| response.status)
480 }
481
482 pub async fn add_caption_bot(
483 &self,
484 conversation: &Conversation,
485 from: &Participant,
486 thread_id: &str,
487 callbacks: &CallbackLinks,
488 ) -> Result<u16> {
489 let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);
490 let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));
491 request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
492 self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)
493 }
494
495 pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {
496 ensure_teams_url(command_url)?;
497 let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
498 let body = captions::command_body(action, &from.mri, &from.participant_id, &timestamp);
499 self.bot_command(command_url, body, "caption command").await.map(|_| ())
500 }
501
502 pub async fn caption_language_command(&self, command_url: &str, from: &Participant, language_tag: &str) -> Result<()> {
503 ensure_teams_url(command_url)?;
504 let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
505 let body = captions::language_body(&from.mri, &from.participant_id, &timestamp, language_tag);
506 self.bot_command(command_url, body, "caption language command").await.map(|_| ())
507 }
508
509 async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
510 let arguments = json!({
511 "url": command_url,
512 "body": body,
513 "recorderResource": captions::RECORDER_RESOURCE,
514 "recorderScope": captions::RECORDER_SCOPE,
515 "requestId": uuid::Uuid::new_v4().to_string(),
516 "chainId": self.chain_id,
517 });
518 let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;
519 let status = answer["status"].as_u64().unwrap_or_default();
520 self.timeline.record(format!("POST {label}"), format!("HTTP {status}"));
521 if (200..300).contains(&status) {
522 return Ok(status as u16);
523 }
524 let reason = answer["error"].as_str().unwrap_or("no answer");
525 Err(Error::Signaling(format!("{label} answered HTTP {status} {reason}")))
526 }
527
528 pub async fn recording_command(&self, command_url: &str, command: RecordingCommand, from: &Participant, title: &str) -> Result<u16> {
529 ensure_teams_url(command_url)?;
530 let now = chrono::Utc::now();
531 let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
532 let file_name = recording::file_name(title, now);
533 let correlation_id = uuid::Uuid::new_v4().to_string();
534 let details = StartDetails {
535 own_mri: &from.mri,
536 participant_leg_id: &from.participant_id,
537 timestamp: &timestamp,
538 file_name: &file_name,
539 meeting_title: title,
540 organizer_name: &from.display_name,
541 correlation_id: &correlation_id,
542 };
543 self.bot_command(command_url, recording::command_body(command, details), "recording command").await
544 }
545
546 pub async fn consent_to_recording(&self, conversation: &Conversation, from: &Participant, consent: Consent) -> Result<u16> {
547 let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent);
548 self.send("POST publishState (recording consent)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
549 }
550
551 pub async fn transfer(&self, transfer_url: &str, from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks) -> Result<()> {
552 let body = transfer::transfer_body(from, target, callbacks);
553 self.post_json("POST transfer", transfer_url, body).await
554 }
555
556 /// One broker long poll; answers the next subscribe URL.
557 pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {
558 let mut request = self.request(Method::Get, url, None);
559 request.headers.push(("X-UseBatching".into(), "1".into()));
560 let response = self.exchange(&self.poll_session, "GET broker subscribe", request).await?;
561 Ok(response.body["nextSubscribeUrl"].as_str().map(str::to_owned))
562 }
563
564 pub async fn leave(&self, conversation: &Conversation, from: &Participant, reason: LeaveReason) -> Result<()> {
565 let url = conversation.link("leave")?;
566 self.post_json("POST leave", url, leave_body(from, reason)).await
567 }
568
569 pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
570 self.send(
571 "DELETE conversation",
572 Method::Delete,
573 &conversation.controller,
574 Some(end_for_all_body(from)),
575 )
576 .await
577 .map(|_| ())
578 }
579
580 pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> {
581 let response = self
582 .send("POST attach", Method::Post, url, Some(attach_body(request)))
583 .await?;
584 attached_from(&response.body)
585 }
586
587 pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> {
588 self.post_json("POST progress", url, ringing_body(from)).await
589 }
590
591 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
592 self.post_json("POST acceptance", url, acceptance_body(answer)).await
593 }
594
595 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
596 self.send("DELETE callLeg (decline)", Method::Delete, call_leg_url, Some(decline_body()))
597 .await
598 .map(|_| ())
599 }
600
601 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
602 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
603 .await
604 }
605
606 pub async fn keep_conversation_alive(
607 &self,
608 conversation: &Conversation,
609 from: &Participant,
610 callbacks: &CallbackLinks,
611 ) -> Result<()> {
612 let url = conversation.link("notificationLinks")?;
613 self.post_json("POST notificationLinks", url, notification_links_body(from, callbacks)).await
614 }
615}
616
617fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
618 names
619 .iter()
620 .map(|name| ((*name).to_owned(), Value::String(make(name))))
621 .collect()
622}
623
624fn roster_request(callbacks: &CallbackLinks) -> Value {
625 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
626}
627
628fn conversation_properties() -> Value {
629 json!({
630 "allowConversationWithoutHost": true,
631 "enableGroupCallEventMessages": true,
632 "enableGroupCallUpgradeMessage": false,
633 "enableGroupCallMeetupGeneration": false,
634 })
635}
636
637pub(crate) fn endpoint_state() -> Value {
638 json!({
639 "endpointStateSequenceNumber": 2,
640 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
641 })
642}
643
644fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
645 let mut content = json!({
646 "contentType": SDP_CONTENT_TYPE,
647 "blob": sdp,
648 "clientLocation": "DE",
649 "mediaLegId": media_leg_id,
650 });
651 if with_descriptions {
652 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
653 }
654 content
655}
656
657fn media_controller_links(callbacks: &CallbackLinks) -> Value {
658 json!({
659 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
660 "csrcInfo": callbacks.call("csrcInfo"),
661 })
662}
663
664fn group_chat(target: &InviteTarget) -> Value {
665 match target {
666 InviteTarget::Echo => Value::Null,
667 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
668 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
669 }
670}
671
672fn callee_wire(callee: &Callee) -> Value {
673 json!({"id": callee.mri, "displayName": callee.display_name})
674}
675
676pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
677 let callbacks = invitation.callbacks;
678 let target = invitation.target;
679 let to: Vec<Value> = match target {
680 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
681 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
682 };
683 let mut request = json!({
684 "conversationType": null,
685 "subject": null,
686 "suppressDialout": to.is_empty(),
687 "roster": roster_request(callbacks),
688 "properties": conversation_properties(),
689 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
690 });
691 if matches!(target, InviteTarget::Echo) {
692 request["scenario"] = json!("UserInitiatedTestCall");
693 }
694 let (meeting_info, meeting_data) = match target {
695 InviteTarget::Meeting(meeting) => (
696 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
697 meeting.meeting_data.clone().unwrap_or(Value::Null),
698 ),
699 _ => (Value::Null, Value::Null),
700 };
701 json!({
702 "conversationRequest": request,
703 "contentSharing": null,
704 "participants": {"from": invitation.from.wire(), "to": to},
705 "capabilities": null,
706 "endpointCapabilities": ENDPOINT_CAPABILITIES,
707 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
708 "endpointMetadata": {"holographicCapabilities": 3},
709 "groupContext": null,
710 "groupChat": group_chat(target),
711 "meetingInfo": meeting_info,
712 "meetingData": meeting_data,
713 "endpointState": endpoint_state(),
714 "callInvitation": {
715 "callModalities": invitation.modalities,
716 "replaces": null,
717 "transferor": null,
718 "clientTransferContext": null,
719 "customContext": null,
720 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
721 "clientContentForMediaController": media_controller_links(callbacks),
722 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
723 "emergencyContent": null,
724 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
725 },
726 })
727}
728
729pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value {
730 json!({
731 "roster": roster_request(callbacks),
732 "properties": conversation_properties(),
733 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
734 })
735}
736
737pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
738 json!({
739 "conversationRequest": subscribe_request(callbacks),
740 "participants": {"from": from.wire()},
741 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
742 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
743 "endpointState": endpoint_state(),
744 })
745}
746
747pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
748 let call_end = match reason {
749 LeaveReason::Hangup => json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}),
750 LeaveReason::Cancel => json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}),
751 };
752 json!({
753 "participants": {"from": from.wire()},
754 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
755 "callTransactionEnd": call_end,
756 })
757}
758
759pub fn end_for_all_body(from: &Participant) -> Value {
760 json!({
761 "participants": {"from": from.wire()},
762 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
763 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
764 })
765}
766
767pub fn decline_body() -> Value {
768 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
769}
770
771pub fn ringing_body(from: &Participant) -> Value {
772 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
773}
774
775pub fn attach_body(request: &AttachRequest<'_>) -> Value {
776 let callbacks = request.callbacks;
777 let mut body = json!({
778 "attach": {
779 "requireMediaContent": request.needs_media,
780 "links": {"end": callbacks.call("end")},
781 },
782 "capabilities": null,
783 "endpointCapabilities": ENDPOINT_CAPABILITIES,
784 });
785 if let Some(controller) = request.controller {
786 body["additionalActions"] = json!([{
787 "name": "join",
788 "url": controller,
789 "waitForResponse": true,
790 "input": {
791 "conversationRequest": {
792 "roster": roster_request(callbacks),
793 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
794 },
795 "participants": {"from": request.from.wire()},
796 "endpointMetadata": {"holographicCapabilities": 3},
797 "endpointCapabilities": ENDPOINT_CAPABILITIES,
798 },
799 }]);
800 }
801 body
802}
803
804pub fn acceptance_body(answer: &Answer<'_>) -> Value {
805 let callbacks = answer.callbacks;
806 json!({
807 "callAcceptance": {
808 "acceptedBy": answer.from.wire(),
809 "acceptedCallModalities": answer.modalities,
810 "endpointCapabilities": ENDPOINT_CAPABILITIES,
811 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
812 "links": acceptance_links(callbacks),
813 "clientContentForMediaController": media_controller_links(callbacks),
814 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
815 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
816 "callKeepAliveInterval": null,
817 },
818 })
819}
820
821pub fn renegotiation_body(
822 from: &Participant,
823 callbacks: &CallbackLinks,
824 offer_sdp: &str,
825 media_leg_id: &str,
826 modalities: &[String],
827 new_offer: bool,
828) -> Value {
829 json!({
830 "mediaNegotiation": {
831 "callModalities": modalities,
832 "sender": from.wire(),
833 "links": {
834 "mediaAnswer": callbacks.call("mediaAnswer"),
835 "rejection": callbacks.call("rejection"),
836 },
837 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer),
838 },
839 })
840}
841
842fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool) -> Value {
843 let mut content = media_content(sdp, media_leg_id, true);
844 content["newOffer"] = json!(new_offer);
845 content
846}
847
848pub fn escalation_answer_body(
849 from: &Participant,
850 callbacks: &CallbackLinks,
851 answer_sdp: &str,
852 media_leg_id: &str,
853) -> Value {
854 json!({
855 "mediaAnswer": {
856 "callModalities": AUDIO_MODALITIES,
857 "sender": from.wire(),
858 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
859 "clientContentForMediaController": media_controller_links(callbacks),
860 "mediaContent": media_content(answer_sdp, media_leg_id, false),
861 },
862 })
863}
864
865pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
866 json!({
867 "participants": {"from": from.wire()},
868 "roster": roster_request(callbacks),
869 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
870 })
871}
872
873fn conversation_from(body: &Value) -> Result<Conversation> {
874 let controller = body["conversationController"]
875 .as_str()
876 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
877 .to_owned();
878 let links = body["links"]
879 .as_object()
880 .map(|links| {
881 links
882 .iter()
883 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
884 .collect()
885 })
886 .unwrap_or_default();
887 Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })
888}
889
890#[derive(Debug, Clone, PartialEq, Eq)]
891pub struct HandReceipt {
892 pub state_id: Option<String>,
893 pub rank: u64,
894}
895
896pub fn hand_receipt_from(body: &Value) -> HandReceipt {
897 let published = &body["publishStateResponse"];
898 HandReceipt {
899 state_id: published["stateId"].as_str().map(str::to_owned),
900 rank: published["typeRank"].as_u64().unwrap_or(u64::MAX),
901 }
902}
903
904pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
905 json!({
906 "from": from,
907 "publishedState": {
908 "stateType": RAISE_HANDS,
909 "level": "user",
910 "content": {"skinTone": DEFAULT_SKIN_TONE},
911 "sequenceNumber": sequence_number,
912 },
913 })
914}
915
916pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value {
917 json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids})
918}
919
920pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value {
921 json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS})
922}
923
924pub fn chat_thread_id(body: &Value) -> Option<String> {
925 body["activeModalities"]["groupChat"]["threadId"].as_str().map(str::to_owned)
926}
927
928fn attached_from(body: &Value) -> Result<Attached> {
929 let invitation = &body["callInvitation"];
930 if invitation.is_null() {
931 return Err(Error::Signaling("attach answer without callInvitation".into()));
932 }
933 let links = invitation["links"]
934 .as_object()
935 .map(|links| {
936 links
937 .iter()
938 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
939 .collect()
940 })
941 .unwrap_or_default();
942 let modalities = invitation["callModalities"]
943 .as_array()
944 .map(|items| items.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect())
945 .unwrap_or_default();
946 Ok(Attached {
947 offer_sdp: invitation["mediaContent"]["blob"].as_str().map(str::to_owned),
948 from_mixer: invitation["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
949 modalities,
950 links,
951 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
952 })
953}
954
955#[derive(Debug, Clone)]
956pub struct SelfIdentity {
957 pub object_id: String,
958 pub display_name: String,
959}
960
961pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {
962 let response = session
963 .request(
964 Method::Get,
965 &format!("{GRAPH}/v1.0/me?$select=id,displayName"),
966 &Scope::graph("User.Read"),
967 None,
968 )
969 .await?;
970 Ok(SelfIdentity {
971 object_id: response.body["id"]
972 .as_str()
973 .ok_or_else(|| Error::Signaling("graph /me without id".into()))?
974 .to_owned(),
975 display_name: response.body["displayName"].as_str().unwrap_or_default().to_owned(),
976 })
977}
978
979/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.
980pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<Option<String>> {
981 let bot_id = ECHO_BOT_MRI.trim_start_matches("28:");
982 for thread_id in [
983 format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
984 format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
985 ] {
986 let url = format!(
987 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
988 thread_id.replace(':', "%3A").replace('@', "%40")
989 );
990 let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);
991 if response.is_success() {
992 return Ok(Some(thread_id));
993 }
994 }
995 Ok(None)
996}
997
998#[cfg(test)]
999mod tests {
1000 use super::*;
1001
1002 #[test]
1003 fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() {
1004 let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4);
1005 assert_eq!(raised["publishedState"]["stateType"], "raiseHands");
1006 assert_eq!(raised["publishedState"]["level"], "user");
1007 assert_eq!(raised["publishedState"]["sequenceNumber"], 4);
1008 let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]);
1009 assert_eq!(lowered["scope"], "specified");
1010 assert_eq!(lowered["stateIds"][0], "s-1");
1011 let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6);
1012 assert_eq!(all["scope"], "all");
1013 assert_eq!(all["stateType"], "raiseHands");
1014 }
1015
1016 #[test]
1017 fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() {
1018 let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}});
1019 assert_eq!(hand_receipt_from(&body), HandReceipt { state_id: Some("s-9".to_owned()), rank: 3 });
1020 assert_eq!(hand_receipt_from(&json!({})), HandReceipt { state_id: None, rank: u64::MAX });
1021 }
1022
1023 #[test]
1024 fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
1025 let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
1026 assert_eq!(chat_thread_id(&body).as_deref(), Some("19:meeting_abc@thread.v2"));
1027 assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None);
1028 }
1029
1030 fn from() -> Participant {
1031 Participant {
1032 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
1033 display_name: "Test".into(),
1034 endpoint_id: "e".into(),
1035 participant_id: "p".into(),
1036 language_id: "en-gb".into(),
1037 }
1038 }
1039
1040 fn callbacks() -> CallbackLinks {
1041 CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1")
1042 }
1043
1044 fn body_for(target: &InviteTarget) -> Value {
1045 let from = from();
1046 let callbacks = callbacks();
1047 epconv_body(&Invitation {
1048 from: &from,
1049 offer_sdp: "v=0\r\n",
1050 media_leg_id: "AB",
1051 callbacks: &callbacks,
1052 target,
1053 modalities: &["Audio".to_owned()],
1054 })
1055 }
1056
1057 fn callee(mri: &str, name: &str) -> Callee {
1058 Callee {
1059 mri: mri.into(),
1060 display_name: name.into(),
1061 }
1062 }
1063
1064 #[test]
1065 fn only_teams_hosts_get_the_bearer() {
1066 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
1067 assert!(ensure_teams_url(EPCONV_URL).is_ok());
1068 assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok());
1069 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1070 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1071 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1072 }
1073
1074 #[test]
1075 fn backend_links_go_through_flightproxy() {
1076 assert_eq!(
1077 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2").unwrap(),
1078 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
1079 );
1080 assert_eq!(
1081 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
1082 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1083 );
1084 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1085 assert!(routed_url("https://Evil.skype.com/x").is_err());
1086 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1087 assert!(routed_url("http://cc.skype.com/x").is_err());
1088 assert!(routed_url("https://.skype.com/x").is_err());
1089 }
1090
1091 #[test]
1092 fn echo_body_matches_the_captured_test_call_shape() {
1093 let body = body_for(&InviteTarget::Echo);
1094 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
1095 assert_eq!(body["participants"]["to"], json!([]));
1096 assert_eq!(body["groupChat"], Value::Null);
1097 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1098 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
1099 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
1100 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 11);
1101 }
1102
1103 #[test]
1104 fn one_to_one_body_names_the_callee_and_the_chat() {
1105 let target = InviteTarget::People {
1106 callees: vec![callee("8:orgid:b", "Bea")],
1107 thread_id: "19:a_b@unq.gbl.spaces".into(),
1108 };
1109 let body = body_for(&target);
1110 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
1111 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
1112 assert!(body["conversationRequest"].get("scenario").is_none());
1113 assert_eq!(body["meetingInfo"], Value::Null);
1114 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1115 }
1116
1117 #[test]
1118 fn group_body_invites_every_callee_on_the_group_thread() {
1119 let target = InviteTarget::People {
1120 callees: vec![callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di")],
1121 thread_id: "19:group@thread.v2".into(),
1122 };
1123 let body = body_for(&target);
1124 let to = body["participants"]["to"].as_array().unwrap();
1125 assert_eq!(to.len(), 3);
1126 assert_eq!(to[2]["id"], "8:orgid:d");
1127 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1128 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1129 }
1130
1131 #[test]
1132 fn meeting_join_body_carries_thread_and_meeting_info() {
1133 let target = InviteTarget::Meeting(MeetingTarget {
1134 thread_id: "19:meeting_x@thread.v2".into(),
1135 tenant_id: "tenant".into(),
1136 organizer_id: "organizer".into(),
1137 meeting_data: Some(json!({"meetingCode": "123"})),
1138 });
1139 let body = body_for(&target);
1140 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
1141 assert_eq!(body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}));
1142 assert_eq!(body["meetingData"]["meetingCode"], "123");
1143 assert_eq!(body["participants"]["to"], json!([]));
1144 assert!(body["conversationRequest"].get("scenario").is_none());
1145 assert!(body["endpointState"]["endpointProperties"].get("preheatProperties").is_none());
1146 }
1147
1148 #[test]
1149 fn meeting_subscribe_is_roster_only() {
1150 let meeting = MeetingTarget {
1151 thread_id: "19:meeting_x@thread.v2".into(),
1152 tenant_id: "tenant".into(),
1153 organizer_id: "organizer".into(),
1154 meeting_data: None,
1155 };
1156 let body = subscribe_body(&from(), &callbacks(), &meeting);
1157 assert!(body.get("callInvitation").is_none());
1158 assert!(body["participants"].get("to").is_none());
1159 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 6);
1160 assert_eq!(body["groupChat"]["messageId"], "0");
1161 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
1162 }
1163
1164 #[test]
1165 fn leave_bodies_differ_by_reason() {
1166 let hangup = leave_body(&from(), LeaveReason::Hangup);
1167 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
1168 let cancel = leave_body(&from(), LeaveReason::Cancel);
1169 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
1170 assert_eq!(cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
1171 assert_eq!(cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected");
1172 let end = end_for_all_body(&from());
1173 assert_eq!(end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated");
1174 }
1175
1176 #[test]
1177 fn decline_uses_603() {
1178 let body = decline_body();
1179 assert_eq!(body["callEnd"]["code"], 603);
1180 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1181 }
1182
1183 #[test]
1184 fn attach_asks_for_media_and_joins_the_conversation() {
1185 let from = from();
1186 let callbacks = callbacks();
1187 let body = attach_body(&AttachRequest {
1188 from: &from,
1189 callbacks: &callbacks,
1190 controller: Some("https://conv/controller"),
1191 needs_media: true,
1192 });
1193 assert_eq!(body["attach"]["requireMediaContent"], true);
1194 assert!(body["attach"]["links"]["end"].as_str().unwrap().ends_with("/call/end/"));
1195 let action = &body["additionalActions"][0];
1196 assert_eq!(action["name"], "join");
1197 assert_eq!(action["url"], "https://conv/controller");
1198 assert_eq!(action["waitForResponse"], true);
1199 assert_eq!(action["input"]["conversationRequest"]["links"].as_object().unwrap().len(), 6);
1200 let without = attach_body(&AttachRequest {
1201 from: &from,
1202 callbacks: &callbacks,
1203 controller: None,
1204 needs_media: false,
1205 });
1206 assert!(without.get("additionalActions").is_none());
1207 assert_eq!(without["attach"]["requireMediaContent"], false);
1208 }
1209
1210 #[test]
1211 fn attach_answer_yields_offer_links_and_conversation() {
1212 let body = json!({
1213 "callInvitation": {
1214 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
1215 "mediaContent": {"blob": "v=0\r\n"},
1216 "callModalities": ["Audio"],
1217 },
1218 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
1219 });
1220 let attached = attached_from(&body).unwrap();
1221 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
1222 assert_eq!(attached.links["callLeg"], "https://cc/leg");
1223 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
1224 let conversation = attached.conversation.unwrap();
1225 assert_eq!(conversation.controller, "https://conv/c");
1226 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
1227 assert!(attached_from(&json!({})).is_err());
1228 }
1229
1230 #[test]
1231 fn acceptance_carries_the_answer_and_callback_links() {
1232 let from = from();
1233 let callbacks = callbacks();
1234 let modalities = vec!["Audio".to_owned()];
1235 let body = acceptance_body(&Answer {
1236 from: &from,
1237 answer_sdp: "v=0\r\n",
1238 media_leg_id: "AB",
1239 callbacks: &callbacks,
1240 modalities: &modalities,
1241 });
1242 let accepted = &body["callAcceptance"];
1243 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
1244 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
1245 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
1246 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
1247 assert!(accepted["links"]["mediaRenegotiation"].as_str().unwrap().ends_with("/call/mediaRenegotiation/"));
1248 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1249 }
1250
1251 #[test]
1252 fn renegotiation_messages_name_their_reply_links() {
1253 let from = from();
1254 let callbacks = callbacks();
1255 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true);
1256 let negotiation = &offer["mediaNegotiation"];
1257 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1258 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1259 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false);
1260 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1261 assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1262 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1263 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
1264 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
1265 assert!(answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
1266 .as_str()
1267 .unwrap()
1268 .ends_with("/call/mediaAcknowledgement/"));
1269 }
1270
1271 #[test]
1272 fn a_video_call_invites_with_audio_and_video() {
1273 let from = from();
1274 let callbacks = callbacks();
1275 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1276 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1277 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities });
1278 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1279 }
1280
1281 #[test]
1282 fn people_calls_dial_out_and_echo_does_not() {
1283 let people = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1284 assert_eq!(body_for(&people)["conversationRequest"]["suppressDialout"], false);
1285 assert_eq!(body_for(&InviteTarget::Echo)["conversationRequest"]["suppressDialout"], true);
1286 }
1287
1288 #[test]
1289 fn ringing_progress_names_the_sender() {
1290 let body = ringing_body(&from());
1291 assert_eq!(body["callProgress"]["status"], "ringing");
1292 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
1293 }
1294}