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