BlueGit

ict rusty-teams

Files

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

outgoing.rs

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