BlueGit

ict rusty-teams

Files

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

outgoing.rs

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