BlueGit

ict rusty-teams

Files

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

push.rs

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