BlueGit

ict rusty-teams

Files

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

signaling.rs

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