BlueGit

ict rusty-teams

Files

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

signaling.rs

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