BlueGit

ict rusty-teams

Files

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

signaling.rs

signaling.rs 56.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, 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 keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
607 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
608 .await
609 }
610
611 pub async fn keep_conversation_alive(
612 &self,
613 conversation: &Conversation,
614 from: &Participant,
615 callbacks: &CallbackLinks,
616 ) -> Result<()> {
617 let url = conversation.link("notificationLinks")?;
618 self.post_json("POST notificationLinks", url, notification_links_body(from, callbacks)).await
619 }
620}
621
622fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
623 names
624 .iter()
625 .map(|name| ((*name).to_owned(), Value::String(make(name))))
626 .collect()
627}
628
629fn roster_request(callbacks: &CallbackLinks) -> Value {
630 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
631}
632
633fn conversation_properties() -> Value {
634 json!({
635 "allowConversationWithoutHost": true,
636 "enableGroupCallEventMessages": true,
637 "enableGroupCallUpgradeMessage": false,
638 "enableGroupCallMeetupGeneration": false,
639 })
640}
641
642pub(crate) fn endpoint_state() -> Value {
643 json!({
644 "endpointStateSequenceNumber": 2,
645 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
646 })
647}
648
649fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
650 let mut content = json!({
651 "contentType": SDP_CONTENT_TYPE,
652 "blob": sdp,
653 "clientLocation": "DE",
654 "mediaLegId": media_leg_id,
655 });
656 if with_descriptions {
657 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
658 }
659 content
660}
661
662fn media_controller_links(callbacks: &CallbackLinks) -> Value {
663 json!({
664 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
665 "csrcInfo": callbacks.call("csrcInfo"),
666 })
667}
668
669impl InviteTarget {
670 pub fn is_one_to_one(&self) -> bool {
671 match self {
672 InviteTarget::People { callees, thread_id } => callees.len() == 1 && thread_id.ends_with(ONE_TO_ONE_THREAD_SUFFIX),
673 InviteTarget::Echo | InviteTarget::Meeting(_) => false,
674 }
675 }
676}
677
678fn invitation_media(invitation: &Invitation<'_>) -> Value {
679 if !invitation.is_direct() {
680 return media_content(invitation.offer_sdp, invitation.media_leg_id, true);
681 }
682 let mut content = media_content(invitation.offer_sdp, invitation.media_leg_id, false);
683 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
684 content
685}
686
687fn group_chat(invitation: &Invitation<'_>) -> Value {
688 if invitation.is_direct() {
689 return Value::Null;
690 }
691 match invitation.target {
692 InviteTarget::Echo => Value::Null,
693 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
694 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
695 }
696}
697
698fn callee_wire(callee: &Callee) -> Value {
699 json!({"id": callee.mri, "displayName": callee.display_name})
700}
701
702pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
703 let callbacks = invitation.callbacks;
704 let target = invitation.target;
705 let to: Vec<Value> = match target {
706 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
707 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
708 };
709 let mut request = json!({
710 "conversationType": null,
711 "subject": null,
712 "suppressDialout": to.is_empty(),
713 "roster": roster_request(callbacks),
714 "properties": conversation_properties(),
715 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
716 });
717 if matches!(target, InviteTarget::Echo) {
718 request["scenario"] = json!("UserInitiatedTestCall");
719 }
720 let (meeting_info, meeting_data) = match target {
721 InviteTarget::Meeting(meeting) => (
722 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
723 meeting.meeting_data.clone().unwrap_or(Value::Null),
724 ),
725 _ => (Value::Null, Value::Null),
726 };
727 json!({
728 "conversationRequest": request,
729 "contentSharing": null,
730 "participants": {"from": invitation.from.wire(), "to": to},
731 "capabilities": null,
732 "endpointCapabilities": ENDPOINT_CAPABILITIES,
733 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
734 "endpointMetadata": {"holographicCapabilities": 3},
735 "groupContext": null,
736 "groupChat": group_chat(invitation),
737 "meetingInfo": meeting_info,
738 "meetingData": meeting_data,
739 "endpointState": endpoint_state(),
740 "callInvitation": {
741 "callModalities": invitation.modalities,
742 "replaces": null,
743 "transferor": null,
744 "clientTransferContext": null,
745 "customContext": null,
746 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
747 "clientContentForMediaController": media_controller_links(callbacks),
748 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
749 "emergencyContent": null,
750 "mediaContent": invitation_media(invitation),
751 },
752 })
753}
754
755pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value {
756 json!({
757 "roster": roster_request(callbacks),
758 "properties": conversation_properties(),
759 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
760 })
761}
762
763pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
764 json!({
765 "conversationRequest": subscribe_request(callbacks),
766 "participants": {"from": from.wire()},
767 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
768 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
769 "endpointState": endpoint_state(),
770 })
771}
772
773pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
774 let call_end = match reason {
775 LeaveReason::Hangup => json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}),
776 LeaveReason::Cancel => json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}),
777 };
778 json!({
779 "participants": {"from": from.wire()},
780 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
781 "callTransactionEnd": call_end,
782 })
783}
784
785pub fn end_for_all_body(from: &Participant) -> Value {
786 json!({
787 "participants": {"from": from.wire()},
788 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
789 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
790 })
791}
792
793pub fn decline_body() -> Value {
794 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
795}
796
797pub fn ringing_body(from: &Participant) -> Value {
798 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
799}
800
801pub fn attach_body(request: &AttachRequest<'_>) -> Value {
802 let callbacks = request.callbacks;
803 let mut body = json!({
804 "attach": {
805 "requireMediaContent": request.needs_media,
806 "links": {"end": callbacks.call("end")},
807 },
808 "capabilities": null,
809 "endpointCapabilities": ENDPOINT_CAPABILITIES,
810 });
811 if let Some(controller) = request.controller {
812 body["additionalActions"] = json!([{
813 "name": "join",
814 "url": controller,
815 "waitForResponse": true,
816 "input": {
817 "conversationRequest": {
818 "roster": roster_request(callbacks),
819 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
820 },
821 "participants": {"from": request.from.wire()},
822 "endpointMetadata": {"holographicCapabilities": 3},
823 "endpointCapabilities": ENDPOINT_CAPABILITIES,
824 },
825 }]);
826 }
827 body
828}
829
830pub fn acceptance_body(answer: &Answer<'_>) -> Value {
831 let callbacks = answer.callbacks;
832 json!({
833 "callAcceptance": {
834 "acceptedBy": answer.from.wire(),
835 "acceptedCallModalities": answer.modalities,
836 "endpointCapabilities": ENDPOINT_CAPABILITIES,
837 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
838 "links": acceptance_links(callbacks),
839 "clientContentForMediaController": media_controller_links(callbacks),
840 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
841 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
842 "callKeepAliveInterval": null,
843 },
844 })
845}
846
847pub fn renegotiation_body(
848 from: &Participant,
849 callbacks: &CallbackLinks,
850 offer_sdp: &str,
851 media_leg_id: &str,
852 modalities: &[String],
853 new_offer: bool,
854 direct: bool,
855) -> Value {
856 json!({
857 "mediaNegotiation": {
858 "callModalities": modalities,
859 "sender": from.wire(),
860 "links": {
861 "mediaAnswer": callbacks.call("mediaAnswer"),
862 "rejection": callbacks.call("rejection"),
863 },
864 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer, direct),
865 },
866 })
867}
868
869fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool, direct: bool) -> Value {
870 let mut content = media_content(sdp, media_leg_id, !direct);
871 if direct {
872 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
873 }
874 content["newOffer"] = json!(new_offer);
875 content
876}
877
878pub fn escalation_answer_body(
879 from: &Participant,
880 callbacks: &CallbackLinks,
881 answer_sdp: &str,
882 media_leg_id: &str,
883) -> Value {
884 json!({
885 "mediaAnswer": {
886 "callModalities": AUDIO_MODALITIES,
887 "sender": from.wire(),
888 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
889 "clientContentForMediaController": media_controller_links(callbacks),
890 "mediaContent": media_content(answer_sdp, media_leg_id, false),
891 },
892 })
893}
894
895pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
896 json!({
897 "participants": {"from": from.wire()},
898 "roster": roster_request(callbacks),
899 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
900 })
901}
902
903fn conversation_from(body: &Value) -> Result<Conversation> {
904 let controller = body["conversationController"]
905 .as_str()
906 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
907 .to_owned();
908 let links = body["links"]
909 .as_object()
910 .map(|links| {
911 links
912 .iter()
913 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
914 .collect()
915 })
916 .unwrap_or_default();
917 let roster = Some(&body["roster"]).filter(|roster| roster.is_object()).cloned();
918 Ok(Conversation { controller, links, chat_thread: chat_thread_id(body), roster })
919}
920
921fn joined_conversation(subscribed: &Conversation, answer: &Value) -> Conversation {
922 let Ok(joined) = conversation_from(answer) else {
923 return subscribed.clone();
924 };
925 let mut links = subscribed.links.clone();
926 links.extend(joined.links);
927 Conversation {
928 controller: joined.controller,
929 links,
930 chat_thread: joined.chat_thread.or_else(|| subscribed.chat_thread.clone()),
931 roster: joined.roster.or_else(|| subscribed.roster.clone()),
932 }
933}
934
935#[derive(Debug, Clone, PartialEq, Eq)]
936pub struct HandReceipt {
937 pub state_id: Option<String>,
938 pub rank: u64,
939}
940
941pub fn hand_receipt_from(body: &Value) -> HandReceipt {
942 let published = &body["publishStateResponse"];
943 HandReceipt {
944 state_id: published["stateId"].as_str().map(str::to_owned),
945 rank: published["typeRank"].as_u64().unwrap_or(u64::MAX),
946 }
947}
948
949pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
950 json!({
951 "from": from,
952 "publishedState": {
953 "stateType": RAISE_HANDS,
954 "level": "user",
955 "content": {"skinTone": DEFAULT_SKIN_TONE},
956 "sequenceNumber": sequence_number,
957 },
958 })
959}
960
961pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value {
962 json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids})
963}
964
965pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value {
966 json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS})
967}
968
969pub fn chat_thread_id(body: &Value) -> Option<String> {
970 body["activeModalities"]["groupChat"]["threadId"].as_str().map(str::to_owned)
971}
972
973fn attached_from(body: &Value) -> Result<Attached> {
974 let invitation = &body["callInvitation"];
975 if invitation.is_null() {
976 return Err(Error::Signaling("attach answer without callInvitation".into()));
977 }
978 let links = invitation["links"]
979 .as_object()
980 .map(|links| {
981 links
982 .iter()
983 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
984 .collect()
985 })
986 .unwrap_or_default();
987 let modalities = invitation["callModalities"]
988 .as_array()
989 .map(|items| items.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect())
990 .unwrap_or_default();
991 Ok(Attached {
992 offer_sdp: invitation["mediaContent"]["blob"].as_str().map(str::to_owned),
993 from_mixer: invitation["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
994 modalities,
995 links,
996 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
997 })
998}
999
1000#[derive(Debug, Clone)]
1001pub struct SelfIdentity {
1002 pub object_id: String,
1003 pub display_name: String,
1004}
1005
1006pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> {
1007 let response = session
1008 .request(
1009 Method::Get,
1010 &format!("{GRAPH}/v1.0/me?$select=id,displayName"),
1011 &Scope::graph("User.Read"),
1012 None,
1013 )
1014 .await?;
1015 Ok(SelfIdentity {
1016 object_id: response.body["id"]
1017 .as_str()
1018 .ok_or_else(|| Error::Signaling("graph /me without id".into()))?
1019 .to_owned(),
1020 display_name: response.body["displayName"].as_str().unwrap_or_default().to_owned(),
1021 })
1022}
1023
1024/// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot.
1025pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<Option<String>> {
1026 let bot_id = ECHO_BOT_MRI.trim_start_matches("28:");
1027 for thread_id in [
1028 format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
1029 format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
1030 ] {
1031 let url = format!(
1032 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
1033 thread_id.replace(':', "%3A").replace('@', "%40")
1034 );
1035 let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);
1036 if response.is_success() {
1037 return Ok(Some(thread_id));
1038 }
1039 }
1040 Ok(None)
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045 use super::*;
1046
1047 #[test]
1048 fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() {
1049 let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4);
1050 assert_eq!(raised["publishedState"]["stateType"], "raiseHands");
1051 assert_eq!(raised["publishedState"]["level"], "user");
1052 assert_eq!(raised["publishedState"]["sequenceNumber"], 4);
1053 let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]);
1054 assert_eq!(lowered["scope"], "specified");
1055 assert_eq!(lowered["stateIds"][0], "s-1");
1056 let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6);
1057 assert_eq!(all["scope"], "all");
1058 assert_eq!(all["stateType"], "raiseHands");
1059 }
1060
1061 #[test]
1062 fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() {
1063 let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}});
1064 assert_eq!(hand_receipt_from(&body), HandReceipt { state_id: Some("s-9".to_owned()), rank: 3 });
1065 assert_eq!(hand_receipt_from(&json!({})), HandReceipt { state_id: None, rank: u64::MAX });
1066 }
1067
1068 #[test]
1069 fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
1070 let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
1071 assert_eq!(chat_thread_id(&body).as_deref(), Some("19:meeting_abc@thread.v2"));
1072 assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None);
1073 }
1074
1075 fn from() -> Participant {
1076 Participant {
1077 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
1078 display_name: "Test".into(),
1079 endpoint_id: "e".into(),
1080 participant_id: "p".into(),
1081 language_id: "en-gb".into(),
1082 }
1083 }
1084
1085 fn callbacks() -> CallbackLinks {
1086 CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1")
1087 }
1088
1089 fn body_for(target: &InviteTarget) -> Value {
1090 let from = from();
1091 let callbacks = callbacks();
1092 epconv_body(&Invitation {
1093 from: &from,
1094 offer_sdp: "v=0\r\n",
1095 media_leg_id: "AB",
1096 callbacks: &callbacks,
1097 target,
1098 modalities: &["Audio".to_owned()],
1099 direct: true,
1100 })
1101 }
1102
1103 fn callee(mri: &str, name: &str) -> Callee {
1104 Callee {
1105 mri: mri.into(),
1106 display_name: name.into(),
1107 }
1108 }
1109
1110 #[test]
1111 fn only_teams_hosts_get_the_bearer() {
1112 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
1113 assert!(ensure_teams_url(EPCONV_URL).is_ok());
1114 assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok());
1115 assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1116 assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1117 assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1118 }
1119
1120 #[test]
1121 fn backend_links_go_through_flightproxy() {
1122 assert_eq!(
1123 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2").unwrap(),
1124 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
1125 );
1126 assert_eq!(
1127 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
1128 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1129 );
1130 assert!(routed_url("https://evil.skype.com.example/x").is_err());
1131 assert!(routed_url("https://Evil.skype.com/x").is_err());
1132 assert!(routed_url("https://user@cc.skype.com/x").is_err());
1133 assert!(routed_url("http://cc.skype.com/x").is_err());
1134 assert!(routed_url("https://.skype.com/x").is_err());
1135 }
1136
1137 #[test]
1138 fn echo_body_matches_the_captured_test_call_shape() {
1139 let body = body_for(&InviteTarget::Echo);
1140 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
1141 assert_eq!(body["participants"]["to"], json!([]));
1142 assert_eq!(body["groupChat"], Value::Null);
1143 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1144 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
1145 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
1146 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 11);
1147 }
1148
1149 #[test]
1150 fn one_to_one_body_names_the_callee_without_a_chat_thread() {
1151 let target = InviteTarget::People {
1152 callees: vec![callee("8:orgid:b", "Bea")],
1153 thread_id: "19:a_b@unq.gbl.spaces".into(),
1154 };
1155 let body = body_for(&target);
1156 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
1157 assert_eq!(body["groupChat"], Value::Null);
1158 let media = &body["callInvitation"]["mediaContent"];
1159 assert_eq!(media["requiredFeatures"], "nonByPass");
1160 assert!(media.get("mediaDescriptions").is_none());
1161 assert!(body["conversationRequest"].get("scenario").is_none());
1162 assert_eq!(body["meetingInfo"], Value::Null);
1163 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1164 }
1165
1166 #[test]
1167 fn a_one_to_one_call_that_may_not_go_direct_keeps_the_chat_thread() {
1168 let from = from();
1169 let callbacks = callbacks();
1170 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1171 let modalities = vec!["Audio".to_owned()];
1172 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 });
1173 assert_eq!(body["groupChat"]["threadId"], "19:a_b@unq.gbl.spaces");
1174 assert!(body["callInvitation"]["mediaContent"]["mediaDescriptions"].is_object());
1175 }
1176
1177 #[test]
1178 fn group_body_invites_every_callee_on_the_group_thread() {
1179 let target = InviteTarget::People {
1180 callees: vec![callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di")],
1181 thread_id: "19:group@thread.v2".into(),
1182 };
1183 let body = body_for(&target);
1184 let to = body["participants"]["to"].as_array().unwrap();
1185 assert_eq!(to.len(), 3);
1186 assert_eq!(to[2]["id"], "8:orgid:d");
1187 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1188 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1189 let media = &body["callInvitation"]["mediaContent"];
1190 assert!(media.get("requiredFeatures").is_none());
1191 assert!(media["mediaDescriptions"].is_object());
1192 }
1193
1194 #[test]
1195 fn meeting_join_body_carries_thread_and_meeting_info() {
1196 let target = InviteTarget::Meeting(MeetingTarget {
1197 thread_id: "19:meeting_x@thread.v2".into(),
1198 tenant_id: "tenant".into(),
1199 organizer_id: "organizer".into(),
1200 meeting_data: Some(json!({"meetingCode": "123"})),
1201 });
1202 let body = body_for(&target);
1203 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
1204 assert_eq!(body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}));
1205 assert_eq!(body["meetingData"]["meetingCode"], "123");
1206 assert_eq!(body["participants"]["to"], json!([]));
1207 assert!(body["conversationRequest"].get("scenario").is_none());
1208 assert!(body["endpointState"]["endpointProperties"].get("preheatProperties").is_none());
1209 }
1210
1211 #[test]
1212 fn meeting_subscribe_is_roster_only() {
1213 let meeting = MeetingTarget {
1214 thread_id: "19:meeting_x@thread.v2".into(),
1215 tenant_id: "tenant".into(),
1216 organizer_id: "organizer".into(),
1217 meeting_data: None,
1218 };
1219 let body = subscribe_body(&from(), &callbacks(), &meeting);
1220 assert!(body.get("callInvitation").is_none());
1221 assert!(body["participants"].get("to").is_none());
1222 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 6);
1223 assert_eq!(body["groupChat"]["messageId"], "0");
1224 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
1225 }
1226
1227 #[test]
1228 fn leave_bodies_differ_by_reason() {
1229 let hangup = leave_body(&from(), LeaveReason::Hangup);
1230 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
1231 let cancel = leave_body(&from(), LeaveReason::Cancel);
1232 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
1233 assert_eq!(cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
1234 assert_eq!(cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected");
1235 let end = end_for_all_body(&from());
1236 assert_eq!(end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated");
1237 }
1238
1239 #[test]
1240 fn decline_uses_603() {
1241 let body = decline_body();
1242 assert_eq!(body["callEnd"]["code"], 603);
1243 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1244 }
1245
1246 #[test]
1247 fn attach_asks_for_media_and_joins_the_conversation() {
1248 let from = from();
1249 let callbacks = callbacks();
1250 let body = attach_body(&AttachRequest {
1251 from: &from,
1252 callbacks: &callbacks,
1253 controller: Some("https://conv/controller"),
1254 needs_media: true,
1255 });
1256 assert_eq!(body["attach"]["requireMediaContent"], true);
1257 assert!(body["attach"]["links"]["end"].as_str().unwrap().ends_with("/call/end/"));
1258 let action = &body["additionalActions"][0];
1259 assert_eq!(action["name"], "join");
1260 assert_eq!(action["url"], "https://conv/controller");
1261 assert_eq!(action["waitForResponse"], true);
1262 assert_eq!(action["input"]["conversationRequest"]["links"].as_object().unwrap().len(), 6);
1263 let without = attach_body(&AttachRequest {
1264 from: &from,
1265 callbacks: &callbacks,
1266 controller: None,
1267 needs_media: false,
1268 });
1269 assert!(without.get("additionalActions").is_none());
1270 assert_eq!(without["attach"]["requireMediaContent"], false);
1271 }
1272
1273 #[test]
1274 fn attach_answer_yields_offer_links_and_conversation() {
1275 let body = json!({
1276 "callInvitation": {
1277 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
1278 "mediaContent": {"blob": "v=0\r\n"},
1279 "callModalities": ["Audio"],
1280 },
1281 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
1282 });
1283 let attached = attached_from(&body).unwrap();
1284 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
1285 assert_eq!(attached.links["callLeg"], "https://cc/leg");
1286 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
1287 let conversation = attached.conversation.unwrap();
1288 assert_eq!(conversation.controller, "https://conv/c");
1289 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
1290 assert!(attached_from(&json!({})).is_err());
1291 }
1292
1293 #[test]
1294 fn a_running_meeting_answers_from_its_owning_conversation_with_the_roster() {
1295 let subscribed = conversation_from(&json!({
1296 "conversationController": "https://conv/subscribed",
1297 "links": {"leave": "https://conv/subscribed/leave", "mute": "https://conv/subscribed/mute"},
1298 }))
1299 .unwrap();
1300 assert_eq!(subscribed.roster, None);
1301 let answer: Value = serde_json::from_str(include_str!("../tests/fixtures/meeting_join_answer.json")).unwrap();
1302 let joined = joined_conversation(&subscribed, &answer);
1303 assert_eq!(joined.controller, "https://conv.example/conv/joined");
1304 assert_eq!(joined.link("leave").unwrap(), "https://conv.example/conv/joined/leave");
1305 assert_eq!(joined.link("mute").unwrap(), "https://conv/subscribed/mute");
1306 assert_eq!(joined.roster.unwrap()["participants"].as_object().unwrap().len(), 4);
1307 assert_eq!(joined_conversation(&subscribed, &json!({})).controller, "https://conv/subscribed");
1308 }
1309
1310 #[test]
1311 fn acceptance_carries_the_answer_and_callback_links() {
1312 let from = from();
1313 let callbacks = callbacks();
1314 let modalities = vec!["Audio".to_owned()];
1315 let body = acceptance_body(&Answer {
1316 from: &from,
1317 answer_sdp: "v=0\r\n",
1318 media_leg_id: "AB",
1319 callbacks: &callbacks,
1320 modalities: &modalities,
1321 });
1322 let accepted = &body["callAcceptance"];
1323 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
1324 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
1325 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
1326 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
1327 assert!(accepted["links"]["mediaRenegotiation"].as_str().unwrap().ends_with("/call/mediaRenegotiation/"));
1328 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1329 }
1330
1331 #[test]
1332 fn renegotiation_messages_name_their_reply_links() {
1333 let from = from();
1334 let callbacks = callbacks();
1335 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true, false);
1336 let negotiation = &offer["mediaNegotiation"];
1337 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1338 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1339 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false, true);
1340 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1341 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["requiredFeatures"], "nonByPass");
1342 assert!(same_peer["mediaNegotiation"]["mediaContent"].get("mediaDescriptions").is_none());
1343 assert!(negotiation["mediaContent"]["mediaDescriptions"].is_object());
1344 assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1345 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1346 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
1347 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
1348 assert!(answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
1349 .as_str()
1350 .unwrap()
1351 .ends_with("/call/mediaAcknowledgement/"));
1352 }
1353
1354 #[test]
1355 fn a_video_call_invites_with_audio_and_video() {
1356 let from = from();
1357 let callbacks = callbacks();
1358 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1359 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1360 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 });
1361 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1362 }
1363
1364 #[test]
1365 fn people_calls_dial_out_and_echo_does_not() {
1366 let people = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1367 assert_eq!(body_for(&people)["conversationRequest"]["suppressDialout"], false);
1368 assert_eq!(body_for(&InviteTarget::Echo)["conversationRequest"]["suppressDialout"], true);
1369 }
1370
1371 #[test]
1372 fn ringing_progress_names_the_sender() {
1373 let body = ringing_body(&from());
1374 assert_eq!(body["callProgress"]["status"], "ringing");
1375 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
1376 }
1377}