BlueGit

ict rusty-teams

Files

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

push.rs

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