BlueGit

ict rusty-teams

Files

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

outgoing.rs

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