BlueGit

ict rusty-teams

Files

rusty-teams / crates / graph / src / outgoing.rs

outgoing.rs

outgoing.rs 12.6 KiB Download Raw
1use std::sync::Arc;
2
3use base64::Engine as _;
4use base64::engine::general_purpose::STANDARD;
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9pub enum MentionTarget {
10 User { user_id: String },
11 Channel { channel_id: String },
12 Team { team_id: String },
13}
14
15/// `id` matches the `<at id="n">` tag in the html body.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct OutgoingMention {
18 pub id: u32,
19 pub text: String,
20 pub target: MentionTarget,
21}
22
23impl OutgoingMention {
24 pub fn to_json(&self) -> Value {
25 let mentioned = match &self.target {
26 MentionTarget::User { user_id } => json!({
27 "user": {"id": user_id, "displayName": self.text, "userIdentityType": "aadUser"}
28 }),
29 MentionTarget::Channel { channel_id } => json!({
30 "conversation": {"id": channel_id, "displayName": self.text, "conversationIdentityType": "channel"}
31 }),
32 MentionTarget::Team { team_id } => json!({
33 "conversation": {"id": team_id, "displayName": self.text, "conversationIdentityType": "team"}
34 }),
35 };
36 json!({"id": self.id, "mentionText": self.text, "mentioned": mentioned})
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct HostedImage {
42 pub content_type: String,
43 pub bytes: Arc<Vec<u8>>,
44}
45
46/// `attachment_id` is the GUID inside the file's eTag; it matches the `<attachment id>` tag in the html body.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct FileReference {
49 pub attachment_id: String,
50 pub content_url: String,
51 pub name: String,
52}
53
54/// A quote or card attachment of an edited message, sent back unchanged.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct KeptAttachment {
57 pub id: String,
58 pub content_type: Option<String>,
59 pub content: Option<String>,
60 pub content_url: Option<String>,
61 pub name: Option<String>,
62}
63
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct MessageExtras {
66 pub images: Vec<HostedImage>,
67 pub files: Vec<FileReference>,
68 pub kept: Vec<KeptAttachment>,
69}
70
71impl MessageExtras {
72 pub fn is_empty(&self) -> bool {
73 self.images.is_empty() && self.files.is_empty() && self.kept.is_empty()
74 }
75
76 pub fn kept_html(&self) -> String {
77 self.kept
78 .iter()
79 .map(|kept| format!("<attachment id=\"{}\"></attachment>", kept.id))
80 .collect()
81 }
82
83 pub fn files_html(&self) -> String {
84 self.files
85 .iter()
86 .map(|file| format!("<attachment id=\"{}\"></attachment>", file.attachment_id))
87 .collect()
88 }
89}
90
91fn extras_html(html: &str, extras: &MessageExtras) -> String {
92 let mut content = extras.kept_html();
93 content.push_str(html);
94 for index in 1..=extras.images.len() {
95 let tag = format!("<img src=\"../hostedContents/{index}/$value\">");
96 if !html.contains(&tag) {
97 content.push_str(&format!("<p>{tag}</p>"));
98 }
99 }
100 content.push_str(&extras.files_html());
101 content
102}
103
104pub fn hosted_image_order(html: &str, extras: &MessageExtras) -> Vec<usize> {
105 const PREFIX: &str = "../hostedContents/";
106 const SUFFIX: &str = "/$value";
107 let content = extras_html(html, extras);
108 content
109 .match_indices(PREFIX)
110 .filter_map(|(position, _)| {
111 let rest = &content[position + PREFIX.len()..];
112 let (digits, tail) =
113 rest.split_at(rest.find(|character: char| !character.is_ascii_digit())?);
114 if !tail.starts_with(SUFFIX) {
115 return None;
116 }
117 let index = digits.parse::<usize>().ok()?;
118 (1..=extras.images.len())
119 .contains(&index)
120 .then(|| index - 1)
121 })
122 .collect()
123}
124
125pub(crate) fn message_body(
126 html: &str,
127 mentions: &[OutgoingMention],
128 extras: &MessageExtras,
129) -> Value {
130 let mut body = json!({"body": {"contentType": "html", "content": extras_html(html, extras)}});
131 if !mentions.is_empty() {
132 body["mentions"] = Value::Array(mentions.iter().map(OutgoingMention::to_json).collect());
133 }
134 if !extras.images.is_empty() {
135 body["hostedContents"] = Value::Array(
136 extras
137 .images
138 .iter()
139 .enumerate()
140 .map(|(index, image)| {
141 json!({
142 "@microsoft.graph.temporaryId": (index + 1).to_string(),
143 "contentBytes": STANDARD.encode(image.bytes.as_slice()),
144 "contentType": image.content_type,
145 })
146 })
147 .collect(),
148 );
149 }
150 if !extras.files.is_empty() || !extras.kept.is_empty() {
151 let kept = extras.kept.iter().map(|kept| {
152 json!({
153 "id": kept.id,
154 "contentType": kept.content_type,
155 "content": kept.content,
156 "contentUrl": kept.content_url,
157 "name": kept.name,
158 })
159 });
160 let files = extras.files.iter().map(|file| {
161 json!({
162 "id": file.attachment_id,
163 "contentType": "reference",
164 "contentUrl": file.content_url,
165 "name": file.name,
166 })
167 });
168 body["attachments"] = Value::Array(kept.chain(files).collect());
169 }
170 body
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 fn mention(id: u32, text: &str, target: MentionTarget) -> OutgoingMention {
178 OutgoingMention {
179 id,
180 text: text.to_owned(),
181 target,
182 }
183 }
184
185 #[test]
186 fn user_mention_matches_the_documented_payload() {
187 let value = mention(
188 0,
189 "Ada",
190 MentionTarget::User {
191 user_id: "u1".into(),
192 },
193 )
194 .to_json();
195 assert_eq!(
196 value,
197 json!({"id": 0, "mentionText": "Ada", "mentioned": {"user": {"id": "u1", "displayName": "Ada", "userIdentityType": "aadUser"}}})
198 );
199 }
200
201 #[test]
202 fn channel_and_team_mentions_use_conversation_identity() {
203 let channel = mention(
204 1,
205 "General",
206 MentionTarget::Channel {
207 channel_id: "19:c".into(),
208 },
209 )
210 .to_json();
211 let team = mention(
212 2,
213 "Squad",
214 MentionTarget::Team {
215 team_id: "t".into(),
216 },
217 )
218 .to_json();
219 assert_eq!(
220 channel["mentioned"]["conversation"]["conversationIdentityType"],
221 "channel"
222 );
223 assert_eq!(
224 team["mentioned"]["conversation"]["conversationIdentityType"],
225 "team"
226 );
227 assert_eq!(team["mentioned"]["conversation"]["id"], "t");
228 }
229
230 #[test]
231 fn body_without_mentions_has_no_mentions_key() {
232 let none = MessageExtras::default();
233 assert!(
234 message_body("<p>x</p>", &[], &none)
235 .get("mentions")
236 .is_none()
237 );
238 let with = message_body(
239 "<at id=\"0\">A</at>",
240 &[mention(
241 0,
242 "A",
243 MentionTarget::User {
244 user_id: "u".into(),
245 },
246 )],
247 &none,
248 );
249 assert_eq!(with["mentions"].as_array().unwrap().len(), 1);
250 }
251
252 fn image(content_type: &str, bytes: &[u8]) -> HostedImage {
253 HostedImage {
254 content_type: content_type.to_owned(),
255 bytes: Arc::new(bytes.to_vec()),
256 }
257 }
258
259 #[test]
260 fn plain_body_has_no_hosted_contents_or_attachments() {
261 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
262 assert_eq!(
263 body,
264 json!({"body": {"contentType": "html", "content": "<p>x</p>"}})
265 );
266 }
267
268 #[test]
269 fn images_go_after_the_text_with_matching_temporary_ids() {
270 let extras = MessageExtras {
271 kept: Vec::new(),
272 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
273 files: Vec::new(),
274 };
275 let body = message_body("<p>hi</p>", &[], &extras);
276 assert_eq!(
277 body["body"]["content"],
278 "<p>hi</p><p><img src=\"../hostedContents/1/$value\"></p><p><img src=\"../hostedContents/2/$value\"></p>"
279 );
280 assert_eq!(
281 body["hostedContents"],
282 json!([
283 {"@microsoft.graph.temporaryId": "1", "contentBytes": "AQID", "contentType": "image/png"},
284 {"@microsoft.graph.temporaryId": "2", "contentBytes": "BA==", "contentType": "image/jpeg"},
285 ])
286 );
287 assert!(body.get("attachments").is_none());
288 }
289
290 #[test]
291 fn hosted_image_order_follows_the_body_and_skips_other_images() {
292 let extras = MessageExtras {
293 kept: Vec::new(),
294 images: vec![
295 image("image/png", &[1]),
296 image("image/png", &[2]),
297 image("image/png", &[3]),
298 ],
299 files: Vec::new(),
300 };
301 let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
302 assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
303 assert_eq!(hosted_image_order("<p>none</p>", &extras), vec![0, 1, 2]);
304 }
305
306 #[test]
307 fn images_already_placed_in_the_text_are_not_appended_again() {
308 let extras = MessageExtras {
309 kept: Vec::new(),
310 images: vec![image("image/png", &[1]), image("image/png", &[2])],
311 files: Vec::new(),
312 };
313 let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
314 assert_eq!(
315 body["body"]["content"],
316 "a <img src=\"../hostedContents/2/$value\"> b<p><img src=\"../hostedContents/1/$value\"></p>"
317 );
318 assert_eq!(body["hostedContents"].as_array().unwrap().len(), 2);
319 }
320
321 #[test]
322 fn an_edit_keeps_the_original_files_and_image_elements() {
323 let extras = MessageExtras {
324 kept: Vec::new(),
325 images: Vec::new(),
326 files: vec![FileReference {
327 attachment_id: "G1".into(),
328 content_url: "https://x/a.pdf".into(),
329 name: "a.pdf".into(),
330 }],
331 };
332 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
333 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
334 assert_eq!(
335 body["body"]["content"],
336 format!("<p>new</p>{original_image}<attachment id=\"G1\"></attachment>")
337 );
338 assert_eq!(body["attachments"][0]["id"], "G1");
339 assert!(body.get("hostedContents").is_none());
340 }
341
342 #[test]
343 fn an_edit_sends_the_quote_back_unchanged_before_the_text() {
344 let extras = MessageExtras {
345 images: Vec::new(),
346 files: Vec::new(),
347 kept: vec![KeptAttachment {
348 id: "Q1".into(),
349 content_type: Some("messageReference".into()),
350 content: Some("{\"messageId\":\"Q1\"}".into()),
351 content_url: None,
352 name: None,
353 }],
354 };
355 let body = message_body("<p>new</p>", &[], &extras);
356 assert_eq!(
357 body["body"]["content"],
358 "<attachment id=\"Q1\"></attachment><p>new</p>"
359 );
360 assert_eq!(body["attachments"][0]["contentType"], "messageReference");
361 assert_eq!(body["attachments"][0]["content"], "{\"messageId\":\"Q1\"}");
362 }
363
364 #[test]
365 fn files_become_reference_attachments_with_a_tag_in_the_html() {
366 let extras = MessageExtras {
367 kept: Vec::new(),
368 images: Vec::new(),
369 files: vec![FileReference {
370 attachment_id: "AAAA-1111".into(),
371 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
372 name: "Plan.docx".into(),
373 }],
374 };
375 let body = message_body("", &[], &extras);
376 assert_eq!(
377 body["body"]["content"],
378 "<attachment id=\"AAAA-1111\"></attachment>"
379 );
380 assert_eq!(
381 body["attachments"],
382 json!([{
383 "id": "AAAA-1111",
384 "contentType": "reference",
385 "contentUrl": "https://contoso.sharepoint.com/Plan.docx",
386 "name": "Plan.docx",
387 }])
388 );
389 assert!(body.get("hostedContents").is_none());
390 }
391}