BlueGit

ict rusty-teams

Files

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

signaling.rs

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