| 1 | use std::collections::BTreeMap; |
| 2 | use std::io::Read; |
| 3 | |
| 4 | use base64::Engine; |
| 5 | use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder}; |
| 6 | use serde_json::Value; |
| 7 | |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::hold::offer_sends_video; |
| 10 | |
| 11 | pub const EVT_TEAMS_CALL: i64 = 107; |
| 12 | pub const EVT_GROUP_VIDEO_CALL: i64 = 109; |
| 13 | const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024; |
| 14 | const VIDEO_MODALITY: &str = "Video"; |
| 15 | |
| 16 | /// MRI-voorvoegsel van een telefoonnummer (PSTN), bijvoorbeeld `4:+31201234567`. |
| 17 | const PSTN_PREFIX: &str = "4:"; |
| 18 | |
| 19 | /// De naam die Teams meestuurt, of anders het telefoonnummer uit een PSTN-MRI. Een extern |
| 20 | /// nummer komt vaak zonder naam binnen; dan stond er niets in het belscherm (KVT issue #3). |
| 21 | pub fn name_or_number(mri: &str, name: &str) -> String { |
| 22 | let name = name.trim(); |
| 23 | if !name.is_empty() { |
| 24 | return name.to_owned(); |
| 25 | } |
| 26 | mri.strip_prefix(PSTN_PREFIX) |
| 27 | .map(str::trim) |
| 28 | .unwrap_or_default() |
| 29 | .to_owned() |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | pub struct Caller { |
| 34 | pub mri: String, |
| 35 | pub display_name: String, |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, PartialEq)] |
| 39 | pub struct CallNotification { |
| 40 | pub call_id: String, |
| 41 | pub participant_id: String, |
| 42 | pub caller: Caller, |
| 43 | pub links: BTreeMap<String, String>, |
| 44 | pub offer_sdp: Option<String>, |
| 45 | pub controller_name: Option<String>, |
| 46 | pub conversation_controller: Option<String>, |
| 47 | pub is_multi_party: bool, |
| 48 | pub subject: Option<String>, |
| 49 | pub thread_id: Option<String>, |
| 50 | pub video: bool, |
| 51 | } |
| 52 | |
| 53 | impl CallNotification { |
| 54 | pub fn dedupe_key(&self) -> (String, String) { |
| 55 | (self.call_id.clone(), self.participant_id.clone()) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug, Clone, PartialEq)] |
| 60 | pub enum PushEvent { |
| 61 | IncomingCall(Box<CallNotification>), |
| 62 | Other(i64), |
| 63 | } |
| 64 | |
| 65 | /// `body` is the raw Trouter request body: `{evt, gp}` or `{evt, cp}`. |
| 66 | pub fn decode_push(body: &str) -> Result<PushEvent> { |
| 67 | let push: Value = serde_json::from_str(body) |
| 68 | .map_err(|error| Error::Callback(format!("push is not JSON: {error}")))?; |
| 69 | let evt = push["evt"] |
| 70 | .as_i64() |
| 71 | .ok_or_else(|| Error::Callback("push without evt".into()))?; |
| 72 | if evt != EVT_TEAMS_CALL && evt != EVT_GROUP_VIDEO_CALL { |
| 73 | return Ok(PushEvent::Other(evt)); |
| 74 | } |
| 75 | let payload = payload_of(&push)?; |
| 76 | Ok(PushEvent::IncomingCall(Box::new(notification_from( |
| 77 | &payload, evt, |
| 78 | )?))) |
| 79 | } |
| 80 | |
| 81 | fn payload_of(push: &Value) -> Result<Value> { |
| 82 | if let Some(plain) = push["gp"].as_str() { |
| 83 | return serde_json::from_slice(&base64_bytes(plain)?) |
| 84 | .map_err(|error| Error::Callback(format!("gp is not JSON: {error}"))); |
| 85 | } |
| 86 | if let Some(compressed) = push["cp"].as_str() { |
| 87 | let bytes = base64_bytes(compressed)?; |
| 88 | return inflated_json(&bytes) |
| 89 | .ok_or_else(|| Error::Callback("cp is not deflated JSON".into())); |
| 90 | } |
| 91 | Err(Error::Callback("push has neither gp nor cp".into())) |
| 92 | } |
| 93 | |
| 94 | fn base64_bytes(text: &str) -> Result<Vec<u8>> { |
| 95 | base64::engine::general_purpose::STANDARD |
| 96 | .decode(text.trim()) |
| 97 | .map_err(|error| Error::Callback(format!("push payload is not base64: {error}"))) |
| 98 | } |
| 99 | |
| 100 | fn inflated_json(bytes: &[u8]) -> Option<Value> { |
| 101 | json_from(ZlibDecoder::new(bytes)) |
| 102 | .or_else(|| json_from(DeflateDecoder::new(bytes))) |
| 103 | .or_else(|| json_from(GzDecoder::new(bytes))) |
| 104 | } |
| 105 | |
| 106 | fn json_from(reader: impl Read) -> Option<Value> { |
| 107 | serde_json::from_str(&read_all(reader)?).ok() |
| 108 | } |
| 109 | |
| 110 | fn read_all(reader: impl Read) -> Option<String> { |
| 111 | let mut text = String::new(); |
| 112 | reader |
| 113 | .take(MAX_INFLATED_BYTES) |
| 114 | .read_to_string(&mut text) |
| 115 | .ok()?; |
| 116 | Some(text) |
| 117 | } |
| 118 | |
| 119 | fn text_of(value: &Value) -> Option<String> { |
| 120 | value |
| 121 | .as_str() |
| 122 | .filter(|text| !text.is_empty()) |
| 123 | .map(str::to_owned) |
| 124 | } |
| 125 | |
| 126 | fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> { |
| 127 | let notification = &payload["callNotification"]; |
| 128 | let caller_mri = text_of(¬ification["from"]["id"]) |
| 129 | .ok_or_else(|| Error::Callback("call notification without caller".into()))?; |
| 130 | let links: BTreeMap<String, String> = notification["links"] |
| 131 | .as_object() |
| 132 | .map(|links| { |
| 133 | links |
| 134 | .iter() |
| 135 | .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned()))) |
| 136 | .collect() |
| 137 | }) |
| 138 | .unwrap_or_default(); |
| 139 | let attach = links |
| 140 | .get("attach") |
| 141 | .ok_or_else(|| Error::Callback("call notification without attach link".into()))?; |
| 142 | let participant_id = text_of(&payload["debugContent"]["participantId"]) |
| 143 | .or_else(|| text_of(¬ification["to"]["participantId"])) |
| 144 | .unwrap_or_default(); |
| 145 | let call_id = text_of(&payload["debugContent"]["callId"]).unwrap_or_else(|| attach.clone()); |
| 146 | let modalities_have_video = notification["callModalities"] |
| 147 | .as_array() |
| 148 | .is_some_and(|items| { |
| 149 | items |
| 150 | .iter() |
| 151 | .any(|item| item.as_str() == Some(VIDEO_MODALITY)) |
| 152 | }); |
| 153 | let invitation = &payload["conversationInvitation"]; |
| 154 | let offer_sdp = text_of(¬ification["mediaContent"]["blob"]); |
| 155 | let offer_has_video = offer_sdp.as_deref().is_some_and(offer_sends_video); |
| 156 | Ok(CallNotification { |
| 157 | call_id, |
| 158 | participant_id, |
| 159 | caller: Caller { |
| 160 | display_name: name_or_number( |
| 161 | &caller_mri, |
| 162 | notification["from"]["displayName"] |
| 163 | .as_str() |
| 164 | .unwrap_or_default(), |
| 165 | ), |
| 166 | mri: caller_mri, |
| 167 | }, |
| 168 | links, |
| 169 | offer_sdp, |
| 170 | controller_name: text_of(¬ification["controllerName"]), |
| 171 | conversation_controller: text_of(&invitation["conversationController"]), |
| 172 | is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false), |
| 173 | subject: text_of(&invitation["subject"]), |
| 174 | thread_id: text_of(&payload["groupChat"]["threadId"]), |
| 175 | video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video || offer_has_video, |
| 176 | }) |
| 177 | } |
| 178 | |
| 179 | #[cfg(test)] |
| 180 | mod tests { |
| 181 | use std::io::Write; |
| 182 | |
| 183 | use flate2::Compression; |
| 184 | use flate2::write::{DeflateEncoder, ZlibEncoder}; |
| 185 | use serde_json::json; |
| 186 | |
| 187 | use super::*; |
| 188 | |
| 189 | fn payload() -> Value { |
| 190 | json!({ |
| 191 | "callNotification": { |
| 192 | "from": {"id": "8:orgid:caller", "displayName": "Cara"}, |
| 193 | "to": {"participantId": "to-participant"}, |
| 194 | "links": {"attach": "https://cc.skype.com/attach", "redirection": "https://cc.skype.com/redirect"}, |
| 195 | "controllerName": "mixer", |
| 196 | }, |
| 197 | "conversationInvitation": {"conversationController": "https://conv.skype.com/c", "isMultiParty": false}, |
| 198 | "groupChat": {"threadId": "19:a_b@unq.gbl.spaces"}, |
| 199 | "debugContent": {"callId": "call-1", "participantId": "participant-1"}, |
| 200 | }) |
| 201 | } |
| 202 | |
| 203 | fn base64_of(bytes: &[u8]) -> String { |
| 204 | base64::engine::general_purpose::STANDARD.encode(bytes) |
| 205 | } |
| 206 | |
| 207 | fn gp_body(payload: &Value) -> String { |
| 208 | json!({"evt": 107, "gp": base64_of(payload.to_string().as_bytes())}).to_string() |
| 209 | } |
| 210 | |
| 211 | fn incoming(body: &str) -> CallNotification { |
| 212 | match decode_push(body).unwrap() { |
| 213 | PushEvent::IncomingCall(notification) => *notification, |
| 214 | other => panic!("not a call: {other:?}"), |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[test] |
| 219 | fn an_external_number_without_a_name_shows_the_number() { |
| 220 | let mut call = payload(); |
| 221 | call["callNotification"]["from"] = json!({"id": "4:+31201234567", "displayName": ""}); |
| 222 | assert_eq!( |
| 223 | incoming(&gp_body(&call)).caller.display_name, |
| 224 | "+31201234567" |
| 225 | ); |
| 226 | call["callNotification"]["from"] = json!({"id": "4:+31201234567"}); |
| 227 | assert_eq!( |
| 228 | incoming(&gp_body(&call)).caller.display_name, |
| 229 | "+31201234567" |
| 230 | ); |
| 231 | call["callNotification"]["from"] = |
| 232 | json!({"id": "4:+31201234567", "displayName": "Bakkerij Jansen"}); |
| 233 | assert_eq!( |
| 234 | incoming(&gp_body(&call)).caller.display_name, |
| 235 | "Bakkerij Jansen" |
| 236 | ); |
| 237 | assert_eq!(name_or_number("8:orgid:someone", " "), ""); |
| 238 | } |
| 239 | |
| 240 | #[test] |
| 241 | fn a_plain_push_decodes_to_the_notification() { |
| 242 | let notification = incoming(&gp_body(&payload())); |
| 243 | assert_eq!( |
| 244 | notification.caller, |
| 245 | Caller { |
| 246 | mri: "8:orgid:caller".into(), |
| 247 | display_name: "Cara".into() |
| 248 | } |
| 249 | ); |
| 250 | assert_eq!(notification.call_id, "call-1"); |
| 251 | assert_eq!(notification.participant_id, "participant-1"); |
| 252 | assert_eq!(notification.links["attach"], "https://cc.skype.com/attach"); |
| 253 | assert_eq!( |
| 254 | notification.thread_id.as_deref(), |
| 255 | Some("19:a_b@unq.gbl.spaces") |
| 256 | ); |
| 257 | assert_eq!( |
| 258 | notification.conversation_controller.as_deref(), |
| 259 | Some("https://conv.skype.com/c") |
| 260 | ); |
| 261 | assert!(!notification.video && !notification.is_multi_party); |
| 262 | assert!(notification.offer_sdp.is_none()); |
| 263 | assert_eq!( |
| 264 | notification.dedupe_key(), |
| 265 | ("call-1".to_owned(), "participant-1".to_owned()) |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn compressed_pushes_decode_with_zlib_and_raw_deflate() { |
| 271 | let text = payload().to_string(); |
| 272 | let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default()); |
| 273 | zlib.write_all(text.as_bytes()).unwrap(); |
| 274 | let mut raw = DeflateEncoder::new(Vec::new(), Compression::default()); |
| 275 | raw.write_all(text.as_bytes()).unwrap(); |
| 276 | for compressed in [zlib.finish().unwrap(), raw.finish().unwrap()] { |
| 277 | let body = json!({"evt": 107, "cp": base64_of(&compressed)}).to_string(); |
| 278 | assert_eq!(incoming(&body).call_id, "call-1"); |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | #[test] |
| 283 | fn group_video_pushes_and_video_modalities_are_video_calls() { |
| 284 | let body = |
| 285 | json!({"evt": 109, "gp": base64_of(payload().to_string().as_bytes())}).to_string(); |
| 286 | assert!(incoming(&body).video); |
| 287 | let mut with_video = payload(); |
| 288 | with_video["callNotification"]["callModalities"] = json!(["Audio", "Video"]); |
| 289 | assert!(incoming(&gp_body(&with_video)).video); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn an_offer_that_sends_video_makes_a_video_call_even_without_the_modality() { |
| 294 | let mut with_video = payload(); |
| 295 | let offer = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=sendrecv\r\nm=video 1234 RTP/SAVP 102\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n"; |
| 296 | with_video["callNotification"]["mediaContent"] = json!({"blob": offer}); |
| 297 | assert!(incoming(&gp_body(&with_video)).video); |
| 298 | with_video["callNotification"]["mediaContent"] = json!({"blob": offer.replace("a=sendrecv\r\na=label:main-video", "a=inactive\r\na=label:main-video")}); |
| 299 | assert!(!incoming(&gp_body(&with_video)).video); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn an_offer_in_the_push_is_kept() { |
| 304 | let mut with_offer = payload(); |
| 305 | with_offer["callNotification"]["mediaContent"] = json!({"blob": "v=0\r\n"}); |
| 306 | assert_eq!( |
| 307 | incoming(&gp_body(&with_offer)).offer_sdp.as_deref(), |
| 308 | Some("v=0\r\n") |
| 309 | ); |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn other_events_are_passed_on_without_decoding() { |
| 314 | assert_eq!( |
| 315 | decode_push(r#"{"evt":115,"cp":"x"}"#).unwrap(), |
| 316 | PushEvent::Other(115) |
| 317 | ); |
| 318 | assert_eq!( |
| 319 | decode_push(r#"{"evt":116}"#).unwrap(), |
| 320 | PushEvent::Other(116) |
| 321 | ); |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn broken_pushes_are_errors() { |
| 326 | assert!(decode_push("garbage").is_err()); |
| 327 | assert!(decode_push(r#"{"gp":"x"}"#).is_err()); |
| 328 | assert!(decode_push(r#"{"evt":107}"#).is_err()); |
| 329 | assert!(decode_push(r#"{"evt":107,"gp":"!!"}"#).is_err()); |
| 330 | let mut without_attach = payload(); |
| 331 | without_attach["callNotification"]["links"] = json!({}); |
| 332 | assert!(decode_push(&gp_body(&without_attach)).is_err()); |
| 333 | let mut without_caller = payload(); |
| 334 | without_caller["callNotification"]["from"] = json!({}); |
| 335 | assert!(decode_push(&gp_body(&without_caller)).is_err()); |
| 336 | } |
| 337 | } |