BlueGit

ict rusty-teams

Files

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

trouter_events.rs

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