| 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(|| { |
| 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 | |
| 51 | pub 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 | |
| 68 | fn 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)] |
| 81 | pub struct CallEnd { |
| 82 | pub code: i64, |
| 83 | pub sub_code: i64, |
| 84 | pub phrase: String, |
| 85 | pub accepted_elsewhere_by: Option<String>, |
| 86 | } |
| 87 | |
| 88 | impl CallEnd { |
| 89 | pub fn kind(&self) -> EndKind { |
| 90 | classify_end(self.code, self.sub_code) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 95 | pub 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)] |
| 105 | pub struct AcceptedBy { |
| 106 | pub mri: String, |
| 107 | pub display_name: String, |
| 108 | } |
| 109 | |
| 110 | impl Acceptance { |
| 111 | pub fn in_lobby(&self) -> bool { |
| 112 | self.controller_name.as_deref() == Some(LOBBY_CONTROLLER) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | pub const LOBBY_CONTROLLER: &str = "lobby"; |
| 117 | |
| 118 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 119 | pub enum ProgressStatus { |
| 120 | Ringing, |
| 121 | Forwarded, |
| 122 | Other(String), |
| 123 | } |
| 124 | |
| 125 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 126 | pub 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)] |
| 134 | pub 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, Eq)] |
| 142 | pub struct MediaAcknowledgement { |
| 143 | pub links: BTreeMap<String, String>, |
| 144 | pub keys: String, |
| 145 | } |
| 146 | |
| 147 | #[derive(Debug, Clone, PartialEq)] |
| 148 | pub enum CallEvent { |
| 149 | ConversationUpdate(Value), |
| 150 | RosterUpdate(Value), |
| 151 | Acceptance(Acceptance), |
| 152 | Progress(ProgressStatus), |
| 153 | MediaAnswer(MediaAnswer), |
| 154 | MediaAcknowledgement(MediaAcknowledgement), |
| 155 | MediaRenegotiation(Renegotiation), |
| 156 | Speakers(Vec<u32>), |
| 157 | ControlVideoStreaming(Value), |
| 158 | AddParticipantSuccess(Value), |
| 159 | AddParticipantFailure(Value), |
| 160 | ConversationEnd(Value), |
| 161 | Rejection(Value), |
| 162 | RetargetCompletion(Value), |
| 163 | Reactions(Vec<ReactionEvent>), |
| 164 | LocalParticipantUpdate(Value), |
| 165 | Replacement(Value), |
| 166 | ContentShareUpdate(Value), |
| 167 | ContentShareEnd(Value), |
| 168 | Transfer(TransferEvent), |
| 169 | End(CallEnd), |
| 170 | Other { scope: String, event: String }, |
| 171 | } |
| 172 | |
| 173 | impl CallEvent { |
| 174 | pub fn name(&self) -> String { |
| 175 | match self { |
| 176 | CallEvent::ConversationUpdate(_) => "conversation/conversationUpdate".into(), |
| 177 | CallEvent::RosterUpdate(_) => "conversation/rosterUpdate".into(), |
| 178 | CallEvent::Acceptance(_) => "call/acceptance".into(), |
| 179 | CallEvent::Progress(_) => "call/progress".into(), |
| 180 | CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(), |
| 181 | CallEvent::MediaAcknowledgement(_) => "call/mediaAcknowledgement".into(), |
| 182 | CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(), |
| 183 | CallEvent::Speakers(_) => "call/speakers".into(), |
| 184 | CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(), |
| 185 | CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(), |
| 186 | CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(), |
| 187 | CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(), |
| 188 | CallEvent::Rejection(_) => "call/rejection".into(), |
| 189 | CallEvent::RetargetCompletion(_) => "call/retargetCompletion".into(), |
| 190 | CallEvent::Reactions(_) => "conversation/receiveMessage".into(), |
| 191 | CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(), |
| 192 | CallEvent::Replacement(_) => "call/replacement".into(), |
| 193 | CallEvent::ContentShareUpdate(_) => "conversation/contentSharingUpdate".into(), |
| 194 | CallEvent::ContentShareEnd(_) => "conversation/contentSharingEnd".into(), |
| 195 | CallEvent::Transfer(_) => "call/transfer".into(), |
| 196 | CallEvent::End(_) => "call/end".into(), |
| 197 | CallEvent::Other { scope, event } => format!("{scope}/{event}"), |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /// `path` is `callAgent/<callId>/<tag>/<call|conversation>/<event>/`. |
| 203 | pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> { |
| 204 | let (call_id, scope, event) = split_callback_path(path)?; |
| 205 | let event = match (scope.as_str(), event.as_str()) { |
| 206 | ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body), |
| 207 | ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body), |
| 208 | ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body), |
| 209 | ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)), |
| 210 | ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body), |
| 211 | ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body), |
| 212 | ("call", "rejection") => CallEvent::Rejection(body), |
| 213 | ("call", "retargetCompletion") => CallEvent::RetargetCompletion(body), |
| 214 | ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body), |
| 215 | ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body), |
| 216 | ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body), |
| 217 | ("call", "replacement") => CallEvent::Replacement(body), |
| 218 | ("call", "transferAcceptance") => CallEvent::Transfer(TransferEvent::Accepted), |
| 219 | ("call", "transferCompletion") => CallEvent::Transfer(completion(&body)), |
| 220 | ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?), |
| 221 | ("call", "progress") => CallEvent::Progress(progress(&body)), |
| 222 | ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?), |
| 223 | ("call", "mediaAcknowledgement") => CallEvent::MediaAcknowledgement(MediaAcknowledgement { |
| 224 | links: nested_links(&body), |
| 225 | keys: object_keys(&body), |
| 226 | }), |
| 227 | ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?), |
| 228 | ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)), |
| 229 | ("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body), |
| 230 | ("call", "end") => CallEvent::End(call_end(&body)), |
| 231 | (scope, event) => CallEvent::Other { |
| 232 | scope: scope.to_owned(), |
| 233 | event: event.to_owned(), |
| 234 | }, |
| 235 | }; |
| 236 | Ok((call_id, event)) |
| 237 | } |
| 238 | |
| 239 | pub fn callback_call_id(path: &str) -> Option<String> { |
| 240 | split_callback_path(path) |
| 241 | .ok() |
| 242 | .map(|(call_id, _, _)| call_id) |
| 243 | } |
| 244 | |
| 245 | pub fn is_acceptance_callback(path: &str) -> bool { |
| 246 | matches!(split_callback_path(path), Ok((_, scope, event)) if scope == "call" && event == "acceptance") |
| 247 | } |
| 248 | |
| 249 | fn split_callback_path(path: &str) -> Result<(String, String, String)> { |
| 250 | let rest = path |
| 251 | .strip_prefix(CALLBACK_ROOT) |
| 252 | .ok_or_else(|| Error::Callback(format!("not a call callback: {path}")))?; |
| 253 | let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect(); |
| 254 | let [call_id, _tag, scope, event] = parts.as_slice() else { |
| 255 | return Err(Error::Callback(format!( |
| 256 | "unexpected callback path shape ({} parts)", |
| 257 | parts.len() |
| 258 | ))); |
| 259 | }; |
| 260 | Ok(( |
| 261 | (*call_id).to_owned(), |
| 262 | (*scope).to_owned(), |
| 263 | (*event).to_owned(), |
| 264 | )) |
| 265 | } |
| 266 | |
| 267 | pub fn callback_tag(path_or_url: &str) -> Option<String> { |
| 268 | let start = path_or_url.find(CALLBACK_ROOT)?; |
| 269 | split_callback_path(&path_or_url[start..]).ok()?; |
| 270 | path_or_url[start + CALLBACK_ROOT.len()..] |
| 271 | .split('/') |
| 272 | .nth(1) |
| 273 | .map(str::to_owned) |
| 274 | } |
| 275 | |
| 276 | pub fn acknowledgement_links(body: &Value) -> BTreeMap<String, String> { |
| 277 | string_links(&body["callAcceptanceAcknowledgement"]["links"]) |
| 278 | } |
| 279 | |
| 280 | const LEG_LINK_NAMES: &[&str] = &[ |
| 281 | "mediaAnswer", |
| 282 | "rejection", |
| 283 | "mediaAcknowledgement", |
| 284 | "acknowledgement", |
| 285 | "updateMediaDescriptions", |
| 286 | "applyChannelParameters", |
| 287 | "controlVideoStreaming", |
| 288 | "callLeg", |
| 289 | "retargetCompletion", |
| 290 | "mediaRenegotiation", |
| 291 | "transfer", |
| 292 | "replacement", |
| 293 | "balanceUpdate", |
| 294 | ]; |
| 295 | |
| 296 | fn link_url(value: &Value) -> Option<String> { |
| 297 | value |
| 298 | .as_str() |
| 299 | .map(str::to_owned) |
| 300 | .or_else(|| value.get("href").and_then(Value::as_str).map(str::to_owned)) |
| 301 | } |
| 302 | |
| 303 | fn string_links(value: &Value) -> BTreeMap<String, String> { |
| 304 | value |
| 305 | .as_object() |
| 306 | .map(|links| { |
| 307 | links |
| 308 | .iter() |
| 309 | .filter_map(|(name, url)| Some((name.clone(), link_url(url)?))) |
| 310 | .collect() |
| 311 | }) |
| 312 | .unwrap_or_default() |
| 313 | } |
| 314 | |
| 315 | /// Every call-leg `links` object in the payload. Escalation offers often put |
| 316 | /// `updateMediaDescriptions` next to the media holder, not inside it; keeping |
| 317 | /// only the holder's `mediaAnswer` left us posting at the ended leg. |
| 318 | pub fn nested_links(value: &Value) -> BTreeMap<String, String> { |
| 319 | let mut links = BTreeMap::new(); |
| 320 | collect_leg_links(value, 0, &mut links); |
| 321 | links |
| 322 | } |
| 323 | |
| 324 | fn collect_leg_links(value: &Value, depth: usize, out: &mut BTreeMap<String, String>) { |
| 325 | if depth > 8 { |
| 326 | return; |
| 327 | } |
| 328 | match value { |
| 329 | Value::Object(map) => { |
| 330 | if let Some(links) = map.get("links") { |
| 331 | let parsed = string_links(links); |
| 332 | if parsed |
| 333 | .keys() |
| 334 | .any(|name| LEG_LINK_NAMES.contains(&name.as_str())) |
| 335 | { |
| 336 | out.extend(parsed); |
| 337 | } |
| 338 | } |
| 339 | for child in map.values() { |
| 340 | collect_leg_links(child, depth + 1, out); |
| 341 | } |
| 342 | } |
| 343 | Value::Array(items) => { |
| 344 | for item in items { |
| 345 | collect_leg_links(item, depth + 1, out); |
| 346 | } |
| 347 | } |
| 348 | _ => {} |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | pub fn object_keys(value: &Value) -> String { |
| 353 | let Some(map) = value.as_object() else { |
| 354 | return String::new(); |
| 355 | }; |
| 356 | let mut keys: Vec<&str> = map.keys().map(String::as_str).collect(); |
| 357 | keys.sort_unstable(); |
| 358 | keys.join(",") |
| 359 | } |
| 360 | |
| 361 | fn acceptance(body: &Value) -> Result<Acceptance> { |
| 362 | let accepted = &body["callAcceptance"]; |
| 363 | let media = &accepted["mediaContent"]; |
| 364 | let sdp = media["blob"] |
| 365 | .as_str() |
| 366 | .ok_or_else(|| Error::Callback("acceptance without mediaContent.blob".into()))? |
| 367 | .to_owned(); |
| 368 | Ok(Acceptance { |
| 369 | sdp, |
| 370 | from_mixer: media["fromMixer"].as_bool().unwrap_or(false), |
| 371 | links: string_links(&accepted["links"]), |
| 372 | controller_name: accepted["controllerName"].as_str().map(str::to_owned), |
| 373 | keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(), |
| 374 | accepted_by: accepted["acceptedBy"]["id"].as_str().map(|mri| AcceptedBy { |
| 375 | mri: mri.to_owned(), |
| 376 | display_name: accepted["acceptedBy"]["displayName"] |
| 377 | .as_str() |
| 378 | .unwrap_or_default() |
| 379 | .to_owned(), |
| 380 | }), |
| 381 | }) |
| 382 | } |
| 383 | |
| 384 | fn progress(body: &Value) -> ProgressStatus { |
| 385 | match body["callProgress"]["status"] |
| 386 | .as_str() |
| 387 | .map(str::to_ascii_lowercase) |
| 388 | .as_deref() |
| 389 | { |
| 390 | Some("ringing") => ProgressStatus::Ringing, |
| 391 | Some("forwarded") => ProgressStatus::Forwarded, |
| 392 | other => ProgressStatus::Other(other.unwrap_or_default().to_owned()), |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | fn media_answer(body: &Value) -> Result<MediaAnswer> { |
| 397 | let answer = &body["mediaAnswer"]; |
| 398 | let sdp = answer["mediaContent"]["blob"] |
| 399 | .as_str() |
| 400 | .ok_or_else(|| Error::Callback("mediaAnswer without mediaContent.blob".into()))? |
| 401 | .to_owned(); |
| 402 | Ok(MediaAnswer { |
| 403 | sdp, |
| 404 | from_mixer: answer["mediaContent"]["fromMixer"] |
| 405 | .as_bool() |
| 406 | .unwrap_or(false), |
| 407 | no_ring_back: answer["noRingBack"].as_bool().unwrap_or(false), |
| 408 | links: string_links(&answer["links"]), |
| 409 | }) |
| 410 | } |
| 411 | |
| 412 | /// The renegotiation message nests its offer under a key the captures do not show, so any object holding `mediaContent` counts. |
| 413 | fn media_holder(body: &Value) -> Option<&Value> { |
| 414 | if body.get("mediaContent").is_some() { |
| 415 | return Some(body); |
| 416 | } |
| 417 | body.as_object()? |
| 418 | .values() |
| 419 | .find(|value| value.get("mediaContent").is_some()) |
| 420 | } |
| 421 | |
| 422 | fn renegotiation(body: &Value) -> Result<Renegotiation> { |
| 423 | let holder = media_holder(body) |
| 424 | .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent".into()))?; |
| 425 | let media = &holder["mediaContent"]; |
| 426 | let sdp = media["blob"] |
| 427 | .as_str() |
| 428 | .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))? |
| 429 | .to_owned(); |
| 430 | let mut links = nested_links(body); |
| 431 | links.extend(string_links(&holder["links"])); |
| 432 | Ok(Renegotiation { |
| 433 | sdp, |
| 434 | new_offer: media["newOffer"].as_bool().unwrap_or(false), |
| 435 | escalation: media["escalationOccurring"].as_bool().unwrap_or(false) |
| 436 | || media["isTwoPartyToMultiPartyEscalation"] |
| 437 | .as_bool() |
| 438 | .unwrap_or(false), |
| 439 | links, |
| 440 | }) |
| 441 | } |
| 442 | |
| 443 | /// Speaker lists come as arrays of source ids under keys the captures do not show. |
| 444 | pub fn speaker_sources(body: &Value) -> Vec<u32> { |
| 445 | let mut sources = Vec::new(); |
| 446 | collect_sources(body, 0, &mut sources); |
| 447 | sources.sort_unstable(); |
| 448 | sources.dedup(); |
| 449 | sources |
| 450 | } |
| 451 | |
| 452 | fn collect_sources(value: &Value, depth: usize, sources: &mut Vec<u32>) { |
| 453 | if depth > MAX_SPEAKER_DEPTH { |
| 454 | return; |
| 455 | } |
| 456 | match value { |
| 457 | Value::Object(map) => { |
| 458 | for (key, child) in map { |
| 459 | if SPEAKER_KEYS.contains(&key.as_str()) { |
| 460 | push_ids(child, sources); |
| 461 | } else { |
| 462 | collect_sources(child, depth + 1, sources); |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | Value::Array(items) => items |
| 467 | .iter() |
| 468 | .for_each(|item| collect_sources(item, depth + 1, sources)), |
| 469 | _ => {} |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | fn push_ids(value: &Value, sources: &mut Vec<u32>) { |
| 474 | match value { |
| 475 | Value::Number(number) => { |
| 476 | sources.extend(number.as_u64().and_then(|id| u32::try_from(id).ok())) |
| 477 | } |
| 478 | Value::Array(items) => items.iter().for_each(|item| push_ids(item, sources)), |
| 479 | Value::Object(map) => { |
| 480 | if let Some(id) = map.get("sourceId") { |
| 481 | push_ids(id, sources); |
| 482 | } |
| 483 | } |
| 484 | _ => {} |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | fn call_end(body: &Value) -> CallEnd { |
| 489 | let end = &body["callEnd"]; |
| 490 | CallEnd { |
| 491 | code: end["code"].as_i64().unwrap_or_default(), |
| 492 | sub_code: end["subCode"].as_i64().unwrap_or_default(), |
| 493 | phrase: end["phrase"].as_str().unwrap_or_default().to_owned(), |
| 494 | accepted_elsewhere_by: end["acceptedElsewhereBy"]["displayName"] |
| 495 | .as_str() |
| 496 | .or_else(|| end["acceptedElsewhereBy"]["id"].as_str()) |
| 497 | .map(str::to_owned), |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | /// Callback URLs the client invents under its Trouter `surl`; Trouter routes them to the socket without registration. |
| 502 | #[derive(Debug, Clone)] |
| 503 | pub struct CallbackLinks { |
| 504 | base: String, |
| 505 | call_id: String, |
| 506 | } |
| 507 | |
| 508 | impl CallbackLinks { |
| 509 | pub fn new(surl: &str, call_id: &str) -> Self { |
| 510 | let mut base = surl.to_owned(); |
| 511 | if !base.ends_with('/') { |
| 512 | base.push('/'); |
| 513 | } |
| 514 | CallbackLinks { |
| 515 | base, |
| 516 | call_id: call_id.to_owned(), |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | pub fn call_id(&self) -> &str { |
| 521 | &self.call_id |
| 522 | } |
| 523 | |
| 524 | pub fn link(&self, scope: &str, event: &str) -> String { |
| 525 | let tag = &uuid::Uuid::new_v4().simple().to_string()[..8]; |
| 526 | format!( |
| 527 | "{}{CALLBACK_ROOT}{}/{tag}/{scope}/{event}/", |
| 528 | self.base, self.call_id |
| 529 | ) |
| 530 | } |
| 531 | |
| 532 | pub fn conversation(&self, event: &str) -> String { |
| 533 | self.link("conversation", event) |
| 534 | } |
| 535 | |
| 536 | pub fn call(&self, event: &str) -> String { |
| 537 | self.link("call", event) |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value { |
| 542 | json!({"callAcceptanceAcknowledgement": {"links": acceptance_links(links)}}) |
| 543 | } |
| 544 | |
| 545 | pub fn acceptance_links(links: &CallbackLinks) -> serde_json::Map<String, Value> { |
| 546 | let names = [ |
| 547 | "mediaRenegotiation", |
| 548 | "transfer", |
| 549 | "replacement", |
| 550 | "balanceUpdate", |
| 551 | "retargetCompletion", |
| 552 | "controlVideoStreaming", |
| 553 | "updateMediaDescriptions", |
| 554 | ]; |
| 555 | names |
| 556 | .into_iter() |
| 557 | .map(|name| (name.to_owned(), Value::String(links.call(name)))) |
| 558 | .collect() |
| 559 | } |
| 560 | |
| 561 | #[cfg(test)] |
| 562 | mod tests { |
| 563 | use std::io::Write; |
| 564 | |
| 565 | use flate2::Compression; |
| 566 | use flate2::write::GzEncoder; |
| 567 | |
| 568 | use super::*; |
| 569 | |
| 570 | fn gzip_base64(text: &str) -> String { |
| 571 | let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); |
| 572 | encoder.write_all(text.as_bytes()).unwrap(); |
| 573 | base64::engine::general_purpose::STANDARD.encode(encoder.finish().unwrap()) |
| 574 | } |
| 575 | |
| 576 | fn callback(path: &str, body: &str, gzip: bool) -> TrouterCallback { |
| 577 | TrouterCallback { |
| 578 | request_id: 1, |
| 579 | path: path.into(), |
| 580 | content_encoding: gzip.then(|| "gzip".into()), |
| 581 | body: if gzip { gzip_base64(body) } else { body.into() }, |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | #[test] |
| 586 | fn gzip_base64_bodies_decode_to_json() { |
| 587 | let body = |
| 588 | r#"{"callEnd":{"code":0,"subCode":0,"phrase":"CallEndReasonLocalUserInitiated"}}"#; |
| 589 | let decoded = decode_body(&callback("callAgent/c/1/call/end/", body, true)).unwrap(); |
| 590 | assert_eq!( |
| 591 | decoded["callEnd"]["phrase"], |
| 592 | "CallEndReasonLocalUserInitiated" |
| 593 | ); |
| 594 | let plain = decode_body(&callback("callAgent/c/1/call/end/", body, false)).unwrap(); |
| 595 | assert_eq!(plain, decoded); |
| 596 | } |
| 597 | |
| 598 | #[test] |
| 599 | fn classifies_acceptance_with_sdp_and_links() { |
| 600 | let body = json!({"callAcceptance": {"mediaContent": {"blob": "v=0\r\n", "fromMixer": true}, |
| 601 | "links": {"acknowledgement": "https://cc/ack", "callLeg": "https://cc/leg"}}}); |
| 602 | let (call_id, event) = classify("callAgent/abc/dbea1786/call/acceptance/", body).unwrap(); |
| 603 | assert_eq!(call_id, "abc"); |
| 604 | let CallEvent::Acceptance(acceptance) = event else { |
| 605 | panic!("not acceptance") |
| 606 | }; |
| 607 | assert_eq!(acceptance.sdp, "v=0\r\n"); |
| 608 | assert!(acceptance.from_mixer); |
| 609 | assert_eq!(acceptance.links["callLeg"], "https://cc/leg"); |
| 610 | } |
| 611 | |
| 612 | #[test] |
| 613 | fn classifies_the_events_of_the_last_features() { |
| 614 | let (_, update) = classify( |
| 615 | "callAgent/abc/1/conversation/localParticipantUpdate/", |
| 616 | json!({"breakoutDetails": {}}), |
| 617 | ) |
| 618 | .unwrap(); |
| 619 | assert!(matches!(update, CallEvent::LocalParticipantUpdate(_))); |
| 620 | let (_, replacement) = classify( |
| 621 | "callAgent/abc/1/call/replacement/", |
| 622 | json!({"callNotification": {}}), |
| 623 | ) |
| 624 | .unwrap(); |
| 625 | assert_eq!(replacement.name(), "call/replacement"); |
| 626 | let (_, share) = classify( |
| 627 | "callAgent/abc/1/conversation/contentSharingUpdate/", |
| 628 | json!({"sessionState": {}}), |
| 629 | ) |
| 630 | .unwrap(); |
| 631 | assert!(matches!(share, CallEvent::ContentShareUpdate(_))); |
| 632 | let (_, ended) = classify( |
| 633 | "callAgent/abc/1/conversation/contentSharingEnd/", |
| 634 | Value::Null, |
| 635 | ) |
| 636 | .unwrap(); |
| 637 | assert!(matches!(ended, CallEvent::ContentShareEnd(_))); |
| 638 | let (_, control) = classify( |
| 639 | "callAgent/abc/1/call/controlVideoStreaming/", |
| 640 | json!({"controlVideoStreaming": {}}), |
| 641 | ) |
| 642 | .unwrap(); |
| 643 | assert_eq!(control.name(), "call/controlVideoStreaming"); |
| 644 | let (_, accepted) = |
| 645 | classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap(); |
| 646 | assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted)); |
| 647 | let (_, completed) = classify( |
| 648 | "callAgent/abc/1/call/transferCompletion/", |
| 649 | json!({"transferCompletion": {"code": 0}}), |
| 650 | ) |
| 651 | .unwrap(); |
| 652 | assert!(matches!(completed, CallEvent::Transfer(event) if event.succeeded())); |
| 653 | } |
| 654 | |
| 655 | #[test] |
| 656 | fn classifies_end_and_unknown_events() { |
| 657 | let (_, end) = classify( |
| 658 | "callAgent/abc/1/call/end/", |
| 659 | json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}}), |
| 660 | ) |
| 661 | .unwrap(); |
| 662 | assert_eq!( |
| 663 | end, |
| 664 | CallEvent::End(CallEnd { |
| 665 | code: 0, |
| 666 | sub_code: 5, |
| 667 | phrase: "x".into(), |
| 668 | accepted_elsewhere_by: None |
| 669 | }) |
| 670 | ); |
| 671 | let (_, other) = |
| 672 | classify("callAgent/abc/1/call/updateMediaDescriptions", Value::Null).unwrap(); |
| 673 | assert_eq!(other.name(), "call/updateMediaDescriptions"); |
| 674 | assert!(classify("unifiedPresenceService", Value::Null).is_err()); |
| 675 | } |
| 676 | |
| 677 | #[test] |
| 678 | fn links_live_under_the_socket_url() { |
| 679 | let links = CallbackLinks::new( |
| 680 | "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc", |
| 681 | "call-1", |
| 682 | ); |
| 683 | let link = links.call("acceptance"); |
| 684 | assert!(link.starts_with( |
| 685 | "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/callAgent/call-1/" |
| 686 | )); |
| 687 | assert!(link.ends_with("/call/acceptance/")); |
| 688 | let acknowledgement = acceptance_acknowledgement(&links); |
| 689 | assert!( |
| 690 | acknowledgement["callAcceptanceAcknowledgement"]["links"]["mediaRenegotiation"] |
| 691 | .as_str() |
| 692 | .unwrap() |
| 693 | .ends_with("/call/mediaRenegotiation/") |
| 694 | ); |
| 695 | } |
| 696 | #[test] |
| 697 | fn progress_reports_ringing_and_forwarding() { |
| 698 | let ringing = |
| 699 | json!({"callProgress": {"sender": "x", "status": "ringing", "phrase": "ringing"}}); |
| 700 | let (_, event) = classify("callAgent/abc/1/call/progress/", ringing).unwrap(); |
| 701 | assert_eq!(event, CallEvent::Progress(ProgressStatus::Ringing)); |
| 702 | let forwarded = json!({"callProgress": {"status": "forwarded"}}); |
| 703 | let (_, event) = classify("callAgent/abc/1/call/progress/", forwarded).unwrap(); |
| 704 | assert_eq!(event, CallEvent::Progress(ProgressStatus::Forwarded)); |
| 705 | let (_, other) = classify("callAgent/abc/1/call/progress/", json!({})).unwrap(); |
| 706 | assert_eq!( |
| 707 | other, |
| 708 | CallEvent::Progress(ProgressStatus::Other(String::new())) |
| 709 | ); |
| 710 | } |
| 711 | |
| 712 | #[test] |
| 713 | fn provisional_answers_carry_sdp_and_links() { |
| 714 | let body = json!({"mediaAnswer": {"sender": "x", "mediaContent": {"blob": "v=0\r\n"}, |
| 715 | "links": {"mediaAcknowledgement": "https://cc/ack"}}}); |
| 716 | let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap(); |
| 717 | let CallEvent::MediaAnswer(answer) = event else { |
| 718 | panic!("not a media answer") |
| 719 | }; |
| 720 | assert_eq!(answer.sdp, "v=0\r\n"); |
| 721 | assert_eq!(answer.links["mediaAcknowledgement"], "https://cc/ack"); |
| 722 | assert!(classify("callAgent/abc/1/call/mediaAnswer/", json!({})).is_err()); |
| 723 | } |
| 724 | |
| 725 | #[test] |
| 726 | fn renegotiation_finds_its_offer_under_any_key() { |
| 727 | let nested = json!({"mediaNegotiation": {"mediaContent": {"blob": "v=0\r\n", "newOffer": true, |
| 728 | "escalationOccurring": true}, "links": {"mediaAnswer": "https://cc/answer"}}}); |
| 729 | let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", nested).unwrap(); |
| 730 | let CallEvent::MediaRenegotiation(renegotiation) = event else { |
| 731 | panic!("not a renegotiation") |
| 732 | }; |
| 733 | assert!(renegotiation.new_offer && renegotiation.escalation); |
| 734 | assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer"); |
| 735 | let flat = |
| 736 | json!({"mediaContent": {"blob": "v=0\r\n", "isTwoPartyToMultiPartyEscalation": true}}); |
| 737 | let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", flat).unwrap(); |
| 738 | let CallEvent::MediaRenegotiation(renegotiation) = event else { |
| 739 | panic!("not a renegotiation") |
| 740 | }; |
| 741 | assert!(!renegotiation.new_offer && renegotiation.escalation); |
| 742 | assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err()); |
| 743 | } |
| 744 | |
| 745 | #[test] |
| 746 | fn renegotiation_keeps_leg_links_that_sit_beside_the_offer() { |
| 747 | let body = json!({ |
| 748 | "mediaRenegotiation": { |
| 749 | "mediaContent": {"blob": "v=0\r\n", "newOffer": true, "escalationOccurring": true}, |
| 750 | "links": {"mediaAnswer": "https://cc/answer", "rejection": "https://cc/reject"} |
| 751 | }, |
| 752 | "links": { |
| 753 | "updateMediaDescriptions": {"href": "https://cc/new/update"}, |
| 754 | "applyChannelParameters": "https://cc/new/apply", |
| 755 | "callLeg": "https://cc/new/leg" |
| 756 | } |
| 757 | }); |
| 758 | let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", body).unwrap(); |
| 759 | let CallEvent::MediaRenegotiation(renegotiation) = event else { |
| 760 | panic!("not a renegotiation") |
| 761 | }; |
| 762 | assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer"); |
| 763 | assert_eq!( |
| 764 | renegotiation.links["updateMediaDescriptions"], |
| 765 | "https://cc/new/update" |
| 766 | ); |
| 767 | assert_eq!( |
| 768 | renegotiation.links["applyChannelParameters"], |
| 769 | "https://cc/new/apply" |
| 770 | ); |
| 771 | assert_eq!(renegotiation.links["callLeg"], "https://cc/new/leg"); |
| 772 | } |
| 773 | |
| 774 | #[test] |
| 775 | fn media_acknowledgement_harvests_new_mixer_leg_links() { |
| 776 | let body = json!({ |
| 777 | "mediaAcknowledgement": { |
| 778 | "links": { |
| 779 | "updateMediaDescriptions": "https://cc/leg2/update", |
| 780 | "applyChannelParameters": "https://cc/leg2/apply", |
| 781 | "callLeg": "https://cc/leg2" |
| 782 | } |
| 783 | } |
| 784 | }); |
| 785 | let (_, event) = classify("callAgent/abc/1/call/mediaAcknowledgement/", body).unwrap(); |
| 786 | let CallEvent::MediaAcknowledgement(ack) = event else { |
| 787 | panic!("not a media acknowledgement") |
| 788 | }; |
| 789 | assert_eq!( |
| 790 | ack.links["updateMediaDescriptions"], |
| 791 | "https://cc/leg2/update" |
| 792 | ); |
| 793 | assert_eq!(ack.links["applyChannelParameters"], "https://cc/leg2/apply"); |
| 794 | assert_eq!(ack.links["callLeg"], "https://cc/leg2"); |
| 795 | } |
| 796 | |
| 797 | #[test] |
| 798 | fn speaker_sources_come_from_known_list_keys() { |
| 799 | assert_eq!( |
| 800 | speaker_sources(&json!({"csrcInfo": {"csrcs": [201, 205, 201]}})), |
| 801 | vec![201, 205] |
| 802 | ); |
| 803 | assert_eq!( |
| 804 | speaker_sources(&json!({"dominantSpeakers": [{"sourceId": 7}]})), |
| 805 | vec![7] |
| 806 | ); |
| 807 | assert!(speaker_sources(&json!({"other": [1, 2]})).is_empty()); |
| 808 | let (_, event) = |
| 809 | classify("callAgent/abc/1/call/csrcInfo/", json!({"sources": [3]})).unwrap(); |
| 810 | assert_eq!(event, CallEvent::Speakers(vec![3])); |
| 811 | } |
| 812 | |
| 813 | #[test] |
| 814 | fn end_names_who_answered_elsewhere() { |
| 815 | let body = json!({"callEnd": {"code": 450, "subCode": 0, "phrase": "x", |
| 816 | "acceptedElsewhereBy": {"id": "8:orgid:1", "displayName": "Daniel"}}}); |
| 817 | let (_, event) = classify("callAgent/abc/1/call/end/", body).unwrap(); |
| 818 | let CallEvent::End(end) = event else { |
| 819 | panic!("not an end") |
| 820 | }; |
| 821 | assert_eq!(end.kind(), EndKind::AnsweredElsewhere); |
| 822 | assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel")); |
| 823 | } |
| 824 | |
| 825 | #[test] |
| 826 | fn a_direct_acceptance_names_who_took_the_call() { |
| 827 | let body = json!({"callAcceptance": {"acceptedBy": {"id": "8:orgid:bea", "displayName": "Bea", "endpointId": "e"}, |
| 828 | "mediaContent": {"blob": "v=0\r\n", "fromMixer": false}}}); |
| 829 | let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap(); |
| 830 | let CallEvent::Acceptance(acceptance) = event else { |
| 831 | panic!("not acceptance") |
| 832 | }; |
| 833 | assert_eq!( |
| 834 | acceptance.accepted_by, |
| 835 | Some(AcceptedBy { |
| 836 | mri: "8:orgid:bea".into(), |
| 837 | display_name: "Bea".into() |
| 838 | }) |
| 839 | ); |
| 840 | } |
| 841 | |
| 842 | #[test] |
| 843 | fn acceptance_in_the_lobby_is_flagged() { |
| 844 | let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700, |
| 845 | "mediaContent": {"blob": "v=0\r\n"}}}); |
| 846 | let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap(); |
| 847 | let CallEvent::Acceptance(acceptance) = event else { |
| 848 | panic!("not acceptance") |
| 849 | }; |
| 850 | assert!(acceptance.in_lobby()); |
| 851 | assert_eq!(acceptance.keep_alive_seconds, Some(2700)); |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn call_ids_come_from_the_path_alone() { |
| 856 | assert_eq!( |
| 857 | callback_call_id("callAgent/abc/1/call/end/").as_deref(), |
| 858 | Some("abc") |
| 859 | ); |
| 860 | assert_eq!(callback_call_id("unifiedPresenceService"), None); |
| 861 | assert_eq!(callback_call_id(""), None); |
| 862 | } |
| 863 | |
| 864 | #[test] |
| 865 | fn the_tag_names_the_offer_an_answer_belongs_to() { |
| 866 | let links = CallbackLinks::new("https://trouter.example/", "abc"); |
| 867 | let url = links.call("mediaAnswer"); |
| 868 | let tag = callback_tag(&url).unwrap(); |
| 869 | assert_eq!(tag.len(), 8); |
| 870 | assert_eq!( |
| 871 | callback_tag(&format!("callAgent/abc/{tag}/call/mediaAnswer/")), |
| 872 | Some(tag) |
| 873 | ); |
| 874 | assert_eq!(callback_tag("unifiedPresenceService"), None); |
| 875 | } |
| 876 | |
| 877 | #[test] |
| 878 | fn a_media_answer_says_whether_the_mixer_sent_it() { |
| 879 | let body = json!({"mediaAnswer": {"mediaContent": {"blob": "v=0\r\n", "fromMixer": true}, "links": {}}}); |
| 880 | let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap(); |
| 881 | let CallEvent::MediaAnswer(answer) = event else { |
| 882 | panic!("not a media answer") |
| 883 | }; |
| 884 | assert!(answer.from_mixer); |
| 885 | let (_, retarget) = classify( |
| 886 | "callAgent/abc/1/call/retargetCompletion/", |
| 887 | json!({"retargetCompleted": {"code": 0}}), |
| 888 | ) |
| 889 | .unwrap(); |
| 890 | assert!(matches!(retarget, CallEvent::RetargetCompletion(_))); |
| 891 | } |
| 892 | |
| 893 | #[test] |
| 894 | fn only_the_acceptance_callback_gets_the_acknowledgement() { |
| 895 | assert!(is_acceptance_callback("callAgent/abc/1/call/acceptance/")); |
| 896 | assert!(!is_acceptance_callback("callAgent/abc/1/call/mediaAnswer/")); |
| 897 | assert!(!is_acceptance_callback( |
| 898 | "callAgent/abc/1/conversation/rosterUpdate/" |
| 899 | )); |
| 900 | assert!(!is_acceptance_callback("unifiedPresenceService")); |
| 901 | } |
| 902 | } |