BlueGit

ict rusty-teams

Files

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

trouter_events.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
trouter_events.rs 27.4 KiB Download Raw
1use std::collections::BTreeMap;
2use std::io::Read;
3
4use base64::Engine;
5use chatsvc::TrouterCallback;
6use flate2::read::GzDecoder;
7use serde_json::{Value, json};
8
9use crate::end::{EndKind, classify_end};
10use crate::error::{Error, Result};
11use crate::reaction::{ReactionEvent, parse_reactions};
12use crate::transfer::{TransferEvent, completion};
13
14const CALLBACK_ROOT: &str = "callAgent/";
15const GZIP_ENCODING: &str = "gzip";
16const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024;
17const SPEAKER_KEYS: [&str; 7] = [
18 "csrcs",
19 "csrc",
20 "sources",
21 "sourceIds",
22 "dominantSpeakers",
23 "activeSpeakers",
24 "speakers",
25];
26const MAX_SPEAKER_DEPTH: usize = 4;
27
28const MAX_FIND_DEPTH: usize = 6;
29
30/// First value under `key` anywhere in `value`; Teams nests the same field at different depths.
31pub(crate) fn find_key<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
32 find_key_within(value, key, 0)
33}
34
35fn find_key_within<'a>(value: &'a Value, key: &str, depth: usize) -> Option<&'a Value> {
36 if depth > MAX_FIND_DEPTH {
37 return None;
38 }
39 match value {
40 Value::Object(map) => map.get(key).or_else(|| {
41 map.values()
42 .find_map(|child| find_key_within(child, key, depth + 1))
43 }),
44 Value::Array(items) => items
45 .iter()
46 .find_map(|item| find_key_within(item, key, depth + 1)),
47 _ => None,
48 }
49}
50
51pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {
52 let text = if callback
53 .content_encoding
54 .as_deref()
55 .is_some_and(|encoding| encoding.eq_ignore_ascii_case(GZIP_ENCODING))
56 {
57 inflate(&callback.body)?
58 } else {
59 callback.body.clone()
60 };
61 if text.trim().is_empty() {
62 return Ok(Value::Null);
63 }
64 serde_json::from_str(&text)
65 .map_err(|error| Error::Callback(format!("body is not JSON: {error}")))
66}
67
68fn inflate(body: &str) -> Result<String> {
69 let compressed = base64::engine::general_purpose::STANDARD
70 .decode(body.trim())
71 .map_err(|error| Error::Callback(format!("body is not base64: {error}")))?;
72 let mut text = String::new();
73 GzDecoder::new(compressed.as_slice())
74 .take(MAX_INFLATED_BYTES)
75 .read_to_string(&mut text)
76 .map_err(|error| Error::Callback(format!("body is not gzip: {error}")))?;
77 Ok(text)
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct CallEnd {
82 pub code: i64,
83 pub sub_code: i64,
84 pub phrase: String,
85 pub accepted_elsewhere_by: Option<String>,
86}
87
88impl CallEnd {
89 pub fn kind(&self) -> EndKind {
90 classify_end(self.code, self.sub_code)
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct Acceptance {
96 pub sdp: String,
97 pub from_mixer: bool,
98 pub links: BTreeMap<String, String>,
99 pub controller_name: Option<String>,
100 pub keep_alive_seconds: Option<u64>,
101 pub accepted_by: Option<AcceptedBy>,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct AcceptedBy {
106 pub mri: String,
107 pub display_name: String,
108}
109
110impl Acceptance {
111 pub fn in_lobby(&self) -> bool {
112 self.controller_name.as_deref() == Some(LOBBY_CONTROLLER)
113 }
114}
115
116pub const LOBBY_CONTROLLER: &str = "lobby";
117
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub enum ProgressStatus {
120 Ringing,
121 Forwarded,
122 Other(String),
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct MediaAnswer {
127 pub sdp: String,
128 pub from_mixer: bool,
129 pub no_ring_back: bool,
130 pub links: BTreeMap<String, String>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Renegotiation {
135 pub sdp: String,
136 pub new_offer: bool,
137 pub escalation: bool,
138 pub links: BTreeMap<String, String>,
139}
140
141#[derive(Debug, Clone, PartialEq)]
142pub enum CallEvent {
143 ConversationUpdate(Value),
144 RosterUpdate(Value),
145 Acceptance(Acceptance),
146 Progress(ProgressStatus),
147 MediaAnswer(MediaAnswer),
148 MediaRenegotiation(Renegotiation),
149 Speakers(Vec<u32>),
150 ControlVideoStreaming(Value),
151 AddParticipantSuccess(Value),
152 AddParticipantFailure(Value),
153 ConversationEnd(Value),
154 Rejection(Value),
155 RetargetCompletion(Value),
156 Reactions(Vec<ReactionEvent>),
157 LocalParticipantUpdate(Value),
158 Replacement(Value),
159 ContentShareUpdate(Value),
160 ContentShareEnd(Value),
161 Transfer(TransferEvent),
162 End(CallEnd),
163 Other { scope: String, event: String },
164}
165
166impl CallEvent {
167 pub fn name(&self) -> String {
168 match self {
169 CallEvent::ConversationUpdate(_) => "conversation/conversationUpdate".into(),
170 CallEvent::RosterUpdate(_) => "conversation/rosterUpdate".into(),
171 CallEvent::Acceptance(_) => "call/acceptance".into(),
172 CallEvent::Progress(_) => "call/progress".into(),
173 CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
174 CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
175 CallEvent::Speakers(_) => "call/speakers".into(),
176 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
177 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
178 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
179 CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(),
180 CallEvent::Rejection(_) => "call/rejection".into(),
181 CallEvent::RetargetCompletion(_) => "call/retargetCompletion".into(),
182 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
183 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
184 CallEvent::Replacement(_) => "call/replacement".into(),
185 CallEvent::ContentShareUpdate(_) => "conversation/contentSharingUpdate".into(),
186 CallEvent::ContentShareEnd(_) => "conversation/contentSharingEnd".into(),
187 CallEvent::Transfer(_) => "call/transfer".into(),
188 CallEvent::End(_) => "call/end".into(),
189 CallEvent::Other { scope, event } => format!("{scope}/{event}"),
190 }
191 }
192}
193
194/// `path` is `callAgent/<callId>/<tag>/<call|conversation>/<event>/`.
195pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
196 let (call_id, scope, event) = split_callback_path(path)?;
197 let event = match (scope.as_str(), event.as_str()) {
198 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
199 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
200 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
201 ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
202 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
203 ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body),
204 ("call", "rejection") => CallEvent::Rejection(body),
205 ("call", "retargetCompletion") => CallEvent::RetargetCompletion(body),
206 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
207 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
208 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
209 ("call", "replacement") => CallEvent::Replacement(body),
210 ("call", "transferAcceptance") => CallEvent::Transfer(TransferEvent::Accepted),
211 ("call", "transferCompletion") => CallEvent::Transfer(completion(&body)),
212 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
213 ("call", "progress") => CallEvent::Progress(progress(&body)),
214 ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
215 ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
216 ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
217 ("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body),
218 ("call", "end") => CallEvent::End(call_end(&body)),
219 (scope, event) => CallEvent::Other {
220 scope: scope.to_owned(),
221 event: event.to_owned(),
222 },
223 };
224 Ok((call_id, event))
225}
226
227pub fn callback_call_id(path: &str) -> Option<String> {
228 split_callback_path(path)
229 .ok()
230 .map(|(call_id, _, _)| call_id)
231}
232
233pub fn is_acceptance_callback(path: &str) -> bool {
234 matches!(split_callback_path(path), Ok((_, scope, event)) if scope == "call" && event == "acceptance")
235}
236
237fn split_callback_path(path: &str) -> Result<(String, String, String)> {
238 let rest = path
239 .strip_prefix(CALLBACK_ROOT)
240 .ok_or_else(|| Error::Callback(format!("not a call callback: {path}")))?;
241 let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
242 let [call_id, _tag, scope, event] = parts.as_slice() else {
243 return Err(Error::Callback(format!(
244 "unexpected callback path shape ({} parts)",
245 parts.len()
246 )));
247 };
248 Ok((
249 (*call_id).to_owned(),
250 (*scope).to_owned(),
251 (*event).to_owned(),
252 ))
253}
254
255pub fn callback_tag(path_or_url: &str) -> Option<String> {
256 let start = path_or_url.find(CALLBACK_ROOT)?;
257 split_callback_path(&path_or_url[start..]).ok()?;
258 path_or_url[start + CALLBACK_ROOT.len()..]
259 .split('/')
260 .nth(1)
261 .map(str::to_owned)
262}
263
264pub fn acknowledgement_links(body: &Value) -> BTreeMap<String, String> {
265 string_links(&body["callAcceptanceAcknowledgement"]["links"])
266}
267
268fn string_links(value: &Value) -> BTreeMap<String, String> {
269 value
270 .as_object()
271 .map(|links| {
272 links
273 .iter()
274 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
275 .collect()
276 })
277 .unwrap_or_default()
278}
279
280fn acceptance(body: &Value) -> Result<Acceptance> {
281 let accepted = &body["callAcceptance"];
282 let media = &accepted["mediaContent"];
283 let sdp = media["blob"]
284 .as_str()
285 .ok_or_else(|| Error::Callback("acceptance without mediaContent.blob".into()))?
286 .to_owned();
287 Ok(Acceptance {
288 sdp,
289 from_mixer: media["fromMixer"].as_bool().unwrap_or(false),
290 links: string_links(&accepted["links"]),
291 controller_name: accepted["controllerName"].as_str().map(str::to_owned),
292 keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(),
293 accepted_by: accepted["acceptedBy"]["id"].as_str().map(|mri| AcceptedBy {
294 mri: mri.to_owned(),
295 display_name: accepted["acceptedBy"]["displayName"]
296 .as_str()
297 .unwrap_or_default()
298 .to_owned(),
299 }),
300 })
301}
302
303fn progress(body: &Value) -> ProgressStatus {
304 match body["callProgress"]["status"]
305 .as_str()
306 .map(str::to_ascii_lowercase)
307 .as_deref()
308 {
309 Some("ringing") => ProgressStatus::Ringing,
310 Some("forwarded") => ProgressStatus::Forwarded,
311 other => ProgressStatus::Other(other.unwrap_or_default().to_owned()),
312 }
313}
314
315fn media_answer(body: &Value) -> Result<MediaAnswer> {
316 let answer = &body["mediaAnswer"];
317 let sdp = answer["mediaContent"]["blob"]
318 .as_str()
319 .ok_or_else(|| Error::Callback("mediaAnswer without mediaContent.blob".into()))?
320 .to_owned();
321 Ok(MediaAnswer {
322 sdp,
323 from_mixer: answer["mediaContent"]["fromMixer"]
324 .as_bool()
325 .unwrap_or(false),
326 no_ring_back: answer["noRingBack"].as_bool().unwrap_or(false),
327 links: string_links(&answer["links"]),
328 })
329}
330
331/// The renegotiation message nests its offer under a key the captures do not show, so any object holding `mediaContent` counts.
332fn media_holder(body: &Value) -> Option<&Value> {
333 if body.get("mediaContent").is_some() {
334 return Some(body);
335 }
336 body.as_object()?
337 .values()
338 .find(|value| value.get("mediaContent").is_some())
339}
340
341fn renegotiation(body: &Value) -> Result<Renegotiation> {
342 let holder = media_holder(body)
343 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent".into()))?;
344 let media = &holder["mediaContent"];
345 let sdp = media["blob"]
346 .as_str()
347 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))?
348 .to_owned();
349 Ok(Renegotiation {
350 sdp,
351 new_offer: media["newOffer"].as_bool().unwrap_or(false),
352 escalation: media["escalationOccurring"].as_bool().unwrap_or(false)
353 || media["isTwoPartyToMultiPartyEscalation"]
354 .as_bool()
355 .unwrap_or(false),
356 links: string_links(&holder["links"]),
357 })
358}
359
360/// Speaker lists come as arrays of source ids under keys the captures do not show.
361pub fn speaker_sources(body: &Value) -> Vec<u32> {
362 let mut sources = Vec::new();
363 collect_sources(body, 0, &mut sources);
364 sources.sort_unstable();
365 sources.dedup();
366 sources
367}
368
369fn collect_sources(value: &Value, depth: usize, sources: &mut Vec<u32>) {
370 if depth > MAX_SPEAKER_DEPTH {
371 return;
372 }
373 match value {
374 Value::Object(map) => {
375 for (key, child) in map {
376 if SPEAKER_KEYS.contains(&key.as_str()) {
377 push_ids(child, sources);
378 } else {
379 collect_sources(child, depth + 1, sources);
380 }
381 }
382 }
383 Value::Array(items) => items
384 .iter()
385 .for_each(|item| collect_sources(item, depth + 1, sources)),
386 _ => {}
387 }
388}
389
390fn push_ids(value: &Value, sources: &mut Vec<u32>) {
391 match value {
392 Value::Number(number) => {
393 sources.extend(number.as_u64().and_then(|id| u32::try_from(id).ok()))
394 }
395 Value::Array(items) => items.iter().for_each(|item| push_ids(item, sources)),
396 Value::Object(map) => {
397 if let Some(id) = map.get("sourceId") {
398 push_ids(id, sources);
399 }
400 }
401 _ => {}
402 }
403}
404
405fn call_end(body: &Value) -> CallEnd {
406 let end = &body["callEnd"];
407 CallEnd {
408 code: end["code"].as_i64().unwrap_or_default(),
409 sub_code: end["subCode"].as_i64().unwrap_or_default(),
410 phrase: end["phrase"].as_str().unwrap_or_default().to_owned(),
411 accepted_elsewhere_by: end["acceptedElsewhereBy"]["displayName"]
412 .as_str()
413 .or_else(|| end["acceptedElsewhereBy"]["id"].as_str())
414 .map(str::to_owned),
415 }
416}
417
418/// Callback URLs the client invents under its Trouter `surl`; Trouter routes them to the socket without registration.
419#[derive(Debug, Clone)]
420pub struct CallbackLinks {
421 base: String,
422 call_id: String,
423}
424
425impl CallbackLinks {
426 pub fn new(surl: &str, call_id: &str) -> Self {
427 let mut base = surl.to_owned();
428 if !base.ends_with('/') {
429 base.push('/');
430 }
431 CallbackLinks {
432 base,
433 call_id: call_id.to_owned(),
434 }
435 }
436
437 pub fn call_id(&self) -> &str {
438 &self.call_id
439 }
440
441 pub fn link(&self, scope: &str, event: &str) -> String {
442 let tag = &uuid::Uuid::new_v4().simple().to_string()[..8];
443 format!(
444 "{}{CALLBACK_ROOT}{}/{tag}/{scope}/{event}/",
445 self.base, self.call_id
446 )
447 }
448
449 pub fn conversation(&self, event: &str) -> String {
450 self.link("conversation", event)
451 }
452
453 pub fn call(&self, event: &str) -> String {
454 self.link("call", event)
455 }
456}
457
458pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value {
459 json!({"callAcceptanceAcknowledgement": {"links": acceptance_links(links)}})
460}
461
462pub fn acceptance_links(links: &CallbackLinks) -> serde_json::Map<String, Value> {
463 let names = [
464 "mediaRenegotiation",
465 "transfer",
466 "replacement",
467 "balanceUpdate",
468 "retargetCompletion",
469 "controlVideoStreaming",
470 "updateMediaDescriptions",
471 ];
472 names
473 .into_iter()
474 .map(|name| (name.to_owned(), Value::String(links.call(name))))
475 .collect()
476}
477
478#[cfg(test)]
479mod tests {
480 use std::io::Write;
481
482 use flate2::Compression;
483 use flate2::write::GzEncoder;
484
485 use super::*;
486
487 fn gzip_base64(text: &str) -> String {
488 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
489 encoder.write_all(text.as_bytes()).unwrap();
490 base64::engine::general_purpose::STANDARD.encode(encoder.finish().unwrap())
491 }
492
493 fn callback(path: &str, body: &str, gzip: bool) -> TrouterCallback {
494 TrouterCallback {
495 request_id: 1,
496 path: path.into(),
497 content_encoding: gzip.then(|| "gzip".into()),
498 body: if gzip { gzip_base64(body) } else { body.into() },
499 }
500 }
501
502 #[test]
503 fn gzip_base64_bodies_decode_to_json() {
504 let body =
505 r#"{"callEnd":{"code":0,"subCode":0,"phrase":"CallEndReasonLocalUserInitiated"}}"#;
506 let decoded = decode_body(&callback("callAgent/c/1/call/end/", body, true)).unwrap();
507 assert_eq!(
508 decoded["callEnd"]["phrase"],
509 "CallEndReasonLocalUserInitiated"
510 );
511 let plain = decode_body(&callback("callAgent/c/1/call/end/", body, false)).unwrap();
512 assert_eq!(plain, decoded);
513 }
514
515 #[test]
516 fn classifies_acceptance_with_sdp_and_links() {
517 let body = json!({"callAcceptance": {"mediaContent": {"blob": "v=0\r\n", "fromMixer": true},
518 "links": {"acknowledgement": "https://cc/ack", "callLeg": "https://cc/leg"}}});
519 let (call_id, event) = classify("callAgent/abc/dbea1786/call/acceptance/", body).unwrap();
520 assert_eq!(call_id, "abc");
521 let CallEvent::Acceptance(acceptance) = event else {
522 panic!("not acceptance")
523 };
524 assert_eq!(acceptance.sdp, "v=0\r\n");
525 assert!(acceptance.from_mixer);
526 assert_eq!(acceptance.links["callLeg"], "https://cc/leg");
527 }
528
529 #[test]
530 fn classifies_the_events_of_the_last_features() {
531 let (_, update) = classify(
532 "callAgent/abc/1/conversation/localParticipantUpdate/",
533 json!({"breakoutDetails": {}}),
534 )
535 .unwrap();
536 assert!(matches!(update, CallEvent::LocalParticipantUpdate(_)));
537 let (_, replacement) = classify(
538 "callAgent/abc/1/call/replacement/",
539 json!({"callNotification": {}}),
540 )
541 .unwrap();
542 assert_eq!(replacement.name(), "call/replacement");
543 let (_, share) = classify(
544 "callAgent/abc/1/conversation/contentSharingUpdate/",
545 json!({"sessionState": {}}),
546 )
547 .unwrap();
548 assert!(matches!(share, CallEvent::ContentShareUpdate(_)));
549 let (_, ended) = classify(
550 "callAgent/abc/1/conversation/contentSharingEnd/",
551 Value::Null,
552 )
553 .unwrap();
554 assert!(matches!(ended, CallEvent::ContentShareEnd(_)));
555 let (_, control) = classify(
556 "callAgent/abc/1/call/controlVideoStreaming/",
557 json!({"controlVideoStreaming": {}}),
558 )
559 .unwrap();
560 assert_eq!(control.name(), "call/controlVideoStreaming");
561 let (_, accepted) =
562 classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap();
563 assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted));
564 let (_, completed) = classify(
565 "callAgent/abc/1/call/transferCompletion/",
566 json!({"transferCompletion": {"code": 0}}),
567 )
568 .unwrap();
569 assert!(matches!(completed, CallEvent::Transfer(event) if event.succeeded()));
570 }
571
572 #[test]
573 fn classifies_end_and_unknown_events() {
574 let (_, end) = classify(
575 "callAgent/abc/1/call/end/",
576 json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}}),
577 )
578 .unwrap();
579 assert_eq!(
580 end,
581 CallEvent::End(CallEnd {
582 code: 0,
583 sub_code: 5,
584 phrase: "x".into(),
585 accepted_elsewhere_by: None
586 })
587 );
588 let (_, other) =
589 classify("callAgent/abc/1/call/updateMediaDescriptions", Value::Null).unwrap();
590 assert_eq!(other.name(), "call/updateMediaDescriptions");
591 assert!(classify("unifiedPresenceService", Value::Null).is_err());
592 }
593
594 #[test]
595 fn links_live_under_the_socket_url() {
596 let links = CallbackLinks::new(
597 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc",
598 "call-1",
599 );
600 let link = links.call("acceptance");
601 assert!(link.starts_with(
602 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/callAgent/call-1/"
603 ));
604 assert!(link.ends_with("/call/acceptance/"));
605 let acknowledgement = acceptance_acknowledgement(&links);
606 assert!(
607 acknowledgement["callAcceptanceAcknowledgement"]["links"]["mediaRenegotiation"]
608 .as_str()
609 .unwrap()
610 .ends_with("/call/mediaRenegotiation/")
611 );
612 }
613 #[test]
614 fn progress_reports_ringing_and_forwarding() {
615 let ringing =
616 json!({"callProgress": {"sender": "x", "status": "ringing", "phrase": "ringing"}});
617 let (_, event) = classify("callAgent/abc/1/call/progress/", ringing).unwrap();
618 assert_eq!(event, CallEvent::Progress(ProgressStatus::Ringing));
619 let forwarded = json!({"callProgress": {"status": "forwarded"}});
620 let (_, event) = classify("callAgent/abc/1/call/progress/", forwarded).unwrap();
621 assert_eq!(event, CallEvent::Progress(ProgressStatus::Forwarded));
622 let (_, other) = classify("callAgent/abc/1/call/progress/", json!({})).unwrap();
623 assert_eq!(
624 other,
625 CallEvent::Progress(ProgressStatus::Other(String::new()))
626 );
627 }
628
629 #[test]
630 fn provisional_answers_carry_sdp_and_links() {
631 let body = json!({"mediaAnswer": {"sender": "x", "mediaContent": {"blob": "v=0\r\n"},
632 "links": {"mediaAcknowledgement": "https://cc/ack"}}});
633 let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap();
634 let CallEvent::MediaAnswer(answer) = event else {
635 panic!("not a media answer")
636 };
637 assert_eq!(answer.sdp, "v=0\r\n");
638 assert_eq!(answer.links["mediaAcknowledgement"], "https://cc/ack");
639 assert!(classify("callAgent/abc/1/call/mediaAnswer/", json!({})).is_err());
640 }
641
642 #[test]
643 fn renegotiation_finds_its_offer_under_any_key() {
644 let nested = json!({"mediaNegotiation": {"mediaContent": {"blob": "v=0\r\n", "newOffer": true,
645 "escalationOccurring": true}, "links": {"mediaAnswer": "https://cc/answer"}}});
646 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", nested).unwrap();
647 let CallEvent::MediaRenegotiation(renegotiation) = event else {
648 panic!("not a renegotiation")
649 };
650 assert!(renegotiation.new_offer && renegotiation.escalation);
651 assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer");
652 let flat =
653 json!({"mediaContent": {"blob": "v=0\r\n", "isTwoPartyToMultiPartyEscalation": true}});
654 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", flat).unwrap();
655 let CallEvent::MediaRenegotiation(renegotiation) = event else {
656 panic!("not a renegotiation")
657 };
658 assert!(!renegotiation.new_offer && renegotiation.escalation);
659 assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err());
660 }
661
662 #[test]
663 fn speaker_sources_come_from_known_list_keys() {
664 assert_eq!(
665 speaker_sources(&json!({"csrcInfo": {"csrcs": [201, 205, 201]}})),
666 vec![201, 205]
667 );
668 assert_eq!(
669 speaker_sources(&json!({"dominantSpeakers": [{"sourceId": 7}]})),
670 vec![7]
671 );
672 assert!(speaker_sources(&json!({"other": [1, 2]})).is_empty());
673 let (_, event) =
674 classify("callAgent/abc/1/call/csrcInfo/", json!({"sources": [3]})).unwrap();
675 assert_eq!(event, CallEvent::Speakers(vec![3]));
676 }
677
678 #[test]
679 fn end_names_who_answered_elsewhere() {
680 let body = json!({"callEnd": {"code": 450, "subCode": 0, "phrase": "x",
681 "acceptedElsewhereBy": {"id": "8:orgid:1", "displayName": "Daniel"}}});
682 let (_, event) = classify("callAgent/abc/1/call/end/", body).unwrap();
683 let CallEvent::End(end) = event else {
684 panic!("not an end")
685 };
686 assert_eq!(end.kind(), EndKind::AnsweredElsewhere);
687 assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel"));
688 }
689
690 #[test]
691 fn a_direct_acceptance_names_who_took_the_call() {
692 let body = json!({"callAcceptance": {"acceptedBy": {"id": "8:orgid:bea", "displayName": "Bea", "endpointId": "e"},
693 "mediaContent": {"blob": "v=0\r\n", "fromMixer": false}}});
694 let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap();
695 let CallEvent::Acceptance(acceptance) = event else {
696 panic!("not acceptance")
697 };
698 assert_eq!(
699 acceptance.accepted_by,
700 Some(AcceptedBy {
701 mri: "8:orgid:bea".into(),
702 display_name: "Bea".into()
703 })
704 );
705 }
706
707 #[test]
708 fn acceptance_in_the_lobby_is_flagged() {
709 let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700,
710 "mediaContent": {"blob": "v=0\r\n"}}});
711 let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap();
712 let CallEvent::Acceptance(acceptance) = event else {
713 panic!("not acceptance")
714 };
715 assert!(acceptance.in_lobby());
716 assert_eq!(acceptance.keep_alive_seconds, Some(2700));
717 }
718
719 #[test]
720 fn call_ids_come_from_the_path_alone() {
721 assert_eq!(
722 callback_call_id("callAgent/abc/1/call/end/").as_deref(),
723 Some("abc")
724 );
725 assert_eq!(callback_call_id("unifiedPresenceService"), None);
726 assert_eq!(callback_call_id(""), None);
727 }
728
729 #[test]
730 fn the_tag_names_the_offer_an_answer_belongs_to() {
731 let links = CallbackLinks::new("https://trouter.example/", "abc");
732 let url = links.call("mediaAnswer");
733 let tag = callback_tag(&url).unwrap();
734 assert_eq!(tag.len(), 8);
735 assert_eq!(
736 callback_tag(&format!("callAgent/abc/{tag}/call/mediaAnswer/")),
737 Some(tag)
738 );
739 assert_eq!(callback_tag("unifiedPresenceService"), None);
740 }
741
742 #[test]
743 fn a_media_answer_says_whether_the_mixer_sent_it() {
744 let body = json!({"mediaAnswer": {"mediaContent": {"blob": "v=0\r\n", "fromMixer": true}, "links": {}}});
745 let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap();
746 let CallEvent::MediaAnswer(answer) = event else {
747 panic!("not a media answer")
748 };
749 assert!(answer.from_mixer);
750 let (_, retarget) = classify(
751 "callAgent/abc/1/call/retargetCompletion/",
752 json!({"retargetCompleted": {"code": 0}}),
753 )
754 .unwrap();
755 assert!(matches!(retarget, CallEvent::RetargetCompletion(_)));
756 }
757
758 #[test]
759 fn only_the_acceptance_callback_gets_the_acknowledgement() {
760 assert!(is_acceptance_callback("callAgent/abc/1/call/acceptance/"));
761 assert!(!is_acceptance_callback("callAgent/abc/1/call/mediaAnswer/"));
762 assert!(!is_acceptance_callback(
763 "callAgent/abc/1/conversation/rosterUpdate/"
764 ));
765 assert!(!is_acceptance_callback("unifiedPresenceService"));
766 }
767}