| 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 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct Caller { |
| 18 | pub mri: String, |
| 19 | pub display_name: String, |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Clone, PartialEq)] |
| 23 | pub struct CallNotification { |
| 24 | pub call_id: String, |
| 25 | pub participant_id: String, |
| 26 | pub caller: Caller, |
| 27 | pub links: BTreeMap<String, String>, |
| 28 | pub offer_sdp: Option<String>, |
| 29 | pub controller_name: Option<String>, |
| 30 | pub conversation_controller: Option<String>, |
| 31 | pub is_multi_party: bool, |
| 32 | pub subject: Option<String>, |
| 33 | pub thread_id: Option<String>, |
| 34 | pub video: bool, |
| 35 | } |
| 36 | |
| 37 | impl CallNotification { |
| 38 | pub fn dedupe_key(&self) -> (String, String) { |
| 39 | (self.call_id.clone(), self.participant_id.clone()) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[derive(Debug, Clone, PartialEq)] |
| 44 | pub enum PushEvent { |
| 45 | IncomingCall(Box<CallNotification>), |
| 46 | Other(i64), |
| 47 | } |
| 48 | |
| 49 | /// `body` is the raw Trouter request body: `{evt, gp}` or `{evt, cp}`. |
| 50 | pub fn decode_push(body: &str) -> Result<PushEvent> { |
| 51 | let push: Value = serde_json::from_str(body).map_err(|error| Error::Callback(format!("push is not JSON: {error}")))?; |
| 52 | let evt = push["evt"].as_i64().ok_or_else(|| Error::Callback("push without evt".into()))?; |
| 53 | if evt != EVT_TEAMS_CALL && evt != EVT_GROUP_VIDEO_CALL { |
| 54 | return Ok(PushEvent::Other(evt)); |
| 55 | } |
| 56 | let payload = payload_of(&push)?; |
| 57 | Ok(PushEvent::IncomingCall(Box::new(notification_from(&payload, evt)?))) |
| 58 | } |
| 59 | |
| 60 | fn payload_of(push: &Value) -> Result<Value> { |
| 61 | if let Some(plain) = push["gp"].as_str() { |
| 62 | return serde_json::from_slice(&base64_bytes(plain)?) |
| 63 | .map_err(|error| Error::Callback(format!("gp is not JSON: {error}"))); |
| 64 | } |
| 65 | if let Some(compressed) = push["cp"].as_str() { |
| 66 | let bytes = base64_bytes(compressed)?; |
| 67 | return inflated_json(&bytes).ok_or_else(|| Error::Callback("cp is not deflated JSON".into())); |
| 68 | } |
| 69 | Err(Error::Callback("push has neither gp nor cp".into())) |
| 70 | } |
| 71 | |
| 72 | fn base64_bytes(text: &str) -> Result<Vec<u8>> { |
| 73 | base64::engine::general_purpose::STANDARD |
| 74 | .decode(text.trim()) |
| 75 | .map_err(|error| Error::Callback(format!("push payload is not base64: {error}"))) |
| 76 | } |
| 77 | |
| 78 | fn inflated_json(bytes: &[u8]) -> Option<Value> { |
| 79 | json_from(ZlibDecoder::new(bytes)) |
| 80 | .or_else(|| json_from(DeflateDecoder::new(bytes))) |
| 81 | .or_else(|| json_from(GzDecoder::new(bytes))) |
| 82 | } |
| 83 | |
| 84 | fn json_from(reader: impl Read) -> Option<Value> { |
| 85 | serde_json::from_str(&read_all(reader)?).ok() |
| 86 | } |
| 87 | |
| 88 | fn read_all(reader: impl Read) -> Option<String> { |
| 89 | let mut text = String::new(); |
| 90 | reader.take(MAX_INFLATED_BYTES).read_to_string(&mut text).ok()?; |
| 91 | Some(text) |
| 92 | } |
| 93 | |
| 94 | fn text_of(value: &Value) -> Option<String> { |
| 95 | value.as_str().filter(|text| !text.is_empty()).map(str::to_owned) |
| 96 | } |
| 97 | |
| 98 | fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> { |
| 99 | let notification = &payload["callNotification"]; |
| 100 | let caller_mri = text_of(¬ification["from"]["id"]) |
| 101 | .ok_or_else(|| Error::Callback("call notification without caller".into()))?; |
| 102 | let links: BTreeMap<String, String> = notification["links"] |
| 103 | .as_object() |
| 104 | .map(|links| { |
| 105 | links |
| 106 | .iter() |
| 107 | .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned()))) |
| 108 | .collect() |
| 109 | }) |
| 110 | .unwrap_or_default(); |
| 111 | let attach = links |
| 112 | .get("attach") |
| 113 | .ok_or_else(|| Error::Callback("call notification without attach link".into()))?; |
| 114 | let participant_id = text_of(&payload["debugContent"]["participantId"]) |
| 115 | .or_else(|| text_of(¬ification["to"]["participantId"])) |
| 116 | .unwrap_or_default(); |
| 117 | let call_id = text_of(&payload["debugContent"]["callId"]).unwrap_or_else(|| attach.clone()); |
| 118 | let modalities_have_video = notification["callModalities"] |
| 119 | .as_array() |
| 120 | .is_some_and(|items| items.iter().any(|item| item.as_str() == Some(VIDEO_MODALITY))); |
| 121 | let invitation = &payload["conversationInvitation"]; |
| 122 | let offer_sdp = text_of(¬ification["mediaContent"]["blob"]); |
| 123 | let offer_has_video = offer_sdp.as_deref().is_some_and(offer_sends_video); |
| 124 | Ok(CallNotification { |
| 125 | call_id, |
| 126 | participant_id, |
| 127 | caller: Caller { |
| 128 | mri: caller_mri, |
| 129 | display_name: notification["from"]["displayName"].as_str().unwrap_or_default().to_owned(), |
| 130 | }, |
| 131 | links, |
| 132 | offer_sdp, |
| 133 | controller_name: text_of(¬ification["controllerName"]), |
| 134 | conversation_controller: text_of(&invitation["conversationController"]), |
| 135 | is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false), |
| 136 | subject: text_of(&invitation["subject"]), |
| 137 | thread_id: text_of(&payload["groupChat"]["threadId"]), |
| 138 | video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video || offer_has_video, |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | #[cfg(test)] |
| 143 | mod tests { |
| 144 | use std::io::Write; |
| 145 | |
| 146 | use flate2::Compression; |
| 147 | use flate2::write::{DeflateEncoder, ZlibEncoder}; |
| 148 | use serde_json::json; |
| 149 | |
| 150 | use super::*; |
| 151 | |
| 152 | fn payload() -> Value { |
| 153 | json!({ |
| 154 | "callNotification": { |
| 155 | "from": {"id": "8:orgid:caller", "displayName": "Cara"}, |
| 156 | "to": {"participantId": "to-participant"}, |
| 157 | "links": {"attach": "https://cc.skype.com/attach", "redirection": "https://cc.skype.com/redirect"}, |
| 158 | "controllerName": "mixer", |
| 159 | }, |
| 160 | "conversationInvitation": {"conversationController": "https://conv.skype.com/c", "isMultiParty": false}, |
| 161 | "groupChat": {"threadId": "19:a_b@unq.gbl.spaces"}, |
| 162 | "debugContent": {"callId": "call-1", "participantId": "participant-1"}, |
| 163 | }) |
| 164 | } |
| 165 | |
| 166 | fn base64_of(bytes: &[u8]) -> String { |
| 167 | base64::engine::general_purpose::STANDARD.encode(bytes) |
| 168 | } |
| 169 | |
| 170 | fn gp_body(payload: &Value) -> String { |
| 171 | json!({"evt": 107, "gp": base64_of(payload.to_string().as_bytes())}).to_string() |
| 172 | } |
| 173 | |
| 174 | fn incoming(body: &str) -> CallNotification { |
| 175 | match decode_push(body).unwrap() { |
| 176 | PushEvent::IncomingCall(notification) => *notification, |
| 177 | other => panic!("not a call: {other:?}"), |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | #[test] |
| 182 | fn a_plain_push_decodes_to_the_notification() { |
| 183 | let notification = incoming(&gp_body(&payload())); |
| 184 | assert_eq!(notification.caller, Caller { mri: "8:orgid:caller".into(), display_name: "Cara".into() }); |
| 185 | assert_eq!(notification.call_id, "call-1"); |
| 186 | assert_eq!(notification.participant_id, "participant-1"); |
| 187 | assert_eq!(notification.links["attach"], "https://cc.skype.com/attach"); |
| 188 | assert_eq!(notification.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces")); |
| 189 | assert_eq!(notification.conversation_controller.as_deref(), Some("https://conv.skype.com/c")); |
| 190 | assert!(!notification.video && !notification.is_multi_party); |
| 191 | assert!(notification.offer_sdp.is_none()); |
| 192 | assert_eq!(notification.dedupe_key(), ("call-1".to_owned(), "participant-1".to_owned())); |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn compressed_pushes_decode_with_zlib_and_raw_deflate() { |
| 197 | let text = payload().to_string(); |
| 198 | let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default()); |
| 199 | zlib.write_all(text.as_bytes()).unwrap(); |
| 200 | let mut raw = DeflateEncoder::new(Vec::new(), Compression::default()); |
| 201 | raw.write_all(text.as_bytes()).unwrap(); |
| 202 | for compressed in [zlib.finish().unwrap(), raw.finish().unwrap()] { |
| 203 | let body = json!({"evt": 107, "cp": base64_of(&compressed)}).to_string(); |
| 204 | assert_eq!(incoming(&body).call_id, "call-1"); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn group_video_pushes_and_video_modalities_are_video_calls() { |
| 210 | let body = json!({"evt": 109, "gp": base64_of(payload().to_string().as_bytes())}).to_string(); |
| 211 | assert!(incoming(&body).video); |
| 212 | let mut with_video = payload(); |
| 213 | with_video["callNotification"]["callModalities"] = json!(["Audio", "Video"]); |
| 214 | assert!(incoming(&gp_body(&with_video)).video); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn an_offer_that_sends_video_makes_a_video_call_even_without_the_modality() { |
| 219 | let mut with_video = payload(); |
| 220 | 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"; |
| 221 | with_video["callNotification"]["mediaContent"] = json!({"blob": offer}); |
| 222 | assert!(incoming(&gp_body(&with_video)).video); |
| 223 | with_video["callNotification"]["mediaContent"] = json!({"blob": offer.replace("a=sendrecv\r\na=label:main-video", "a=inactive\r\na=label:main-video")}); |
| 224 | assert!(!incoming(&gp_body(&with_video)).video); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn an_offer_in_the_push_is_kept() { |
| 229 | let mut with_offer = payload(); |
| 230 | with_offer["callNotification"]["mediaContent"] = json!({"blob": "v=0\r\n"}); |
| 231 | assert_eq!(incoming(&gp_body(&with_offer)).offer_sdp.as_deref(), Some("v=0\r\n")); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn other_events_are_passed_on_without_decoding() { |
| 236 | assert_eq!(decode_push(r#"{"evt":115,"cp":"x"}"#).unwrap(), PushEvent::Other(115)); |
| 237 | assert_eq!(decode_push(r#"{"evt":116}"#).unwrap(), PushEvent::Other(116)); |
| 238 | } |
| 239 | |
| 240 | #[test] |
| 241 | fn broken_pushes_are_errors() { |
| 242 | assert!(decode_push("garbage").is_err()); |
| 243 | assert!(decode_push(r#"{"gp":"x"}"#).is_err()); |
| 244 | assert!(decode_push(r#"{"evt":107}"#).is_err()); |
| 245 | assert!(decode_push(r#"{"evt":107,"gp":"!!"}"#).is_err()); |
| 246 | let mut without_attach = payload(); |
| 247 | without_attach["callNotification"]["links"] = json!({}); |
| 248 | assert!(decode_push(&gp_body(&without_attach)).is_err()); |
| 249 | let mut without_caller = payload(); |
| 250 | without_caller["callNotification"]["from"] = json!({}); |
| 251 | assert!(decode_push(&gp_body(&without_caller)).is_err()); |
| 252 | } |
| 253 | } |