BlueGit

ict rusty-teams

Files

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

outgoing.rs

outgoing.rs 11.2 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(crate) fn message_body(
105 html: &str,
106 mentions: &[OutgoingMention],
107 extras: &MessageExtras,
108) -> Value {
109 let mut body = json!({"body": {"contentType": "html", "content": extras_html(html, extras)}});
110 if !mentions.is_empty() {
111 body["mentions"] = Value::Array(mentions.iter().map(OutgoingMention::to_json).collect());
112 }
113 if !extras.images.is_empty() {
114 body["hostedContents"] = Value::Array(
115 extras
116 .images
117 .iter()
118 .enumerate()
119 .map(|(index, image)| {
120 json!({
121 "@microsoft.graph.temporaryId": (index + 1).to_string(),
122 "contentBytes": STANDARD.encode(image.bytes.as_slice()),
123 "contentType": image.content_type,
124 })
125 })
126 .collect(),
127 );
128 }
129 if !extras.files.is_empty() || !extras.kept.is_empty() {
130 let kept = extras.kept.iter().map(|kept| {
131 json!({
132 "id": kept.id,
133 "contentType": kept.content_type,
134 "content": kept.content,
135 "contentUrl": kept.content_url,
136 "name": kept.name,
137 })
138 });
139 let files = extras.files.iter().map(|file| {
140 json!({
141 "id": file.attachment_id,
142 "contentType": "reference",
143 "contentUrl": file.content_url,
144 "name": file.name,
145 })
146 });
147 body["attachments"] = Value::Array(kept.chain(files).collect());
148 }
149 body
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 fn mention(id: u32, text: &str, target: MentionTarget) -> OutgoingMention {
157 OutgoingMention {
158 id,
159 text: text.to_owned(),
160 target,
161 }
162 }
163
164 #[test]
165 fn user_mention_matches_the_documented_payload() {
166 let value = mention(
167 0,
168 "Ada",
169 MentionTarget::User {
170 user_id: "u1".into(),
171 },
172 )
173 .to_json();
174 assert_eq!(
175 value,
176 json!({"id": 0, "mentionText": "Ada", "mentioned": {"user": {"id": "u1", "displayName": "Ada", "userIdentityType": "aadUser"}}})
177 );
178 }
179
180 #[test]
181 fn channel_and_team_mentions_use_conversation_identity() {
182 let channel = mention(
183 1,
184 "General",
185 MentionTarget::Channel {
186 channel_id: "19:c".into(),
187 },
188 )
189 .to_json();
190 let team = mention(
191 2,
192 "Squad",
193 MentionTarget::Team {
194 team_id: "t".into(),
195 },
196 )
197 .to_json();
198 assert_eq!(
199 channel["mentioned"]["conversation"]["conversationIdentityType"],
200 "channel"
201 );
202 assert_eq!(
203 team["mentioned"]["conversation"]["conversationIdentityType"],
204 "team"
205 );
206 assert_eq!(team["mentioned"]["conversation"]["id"], "t");
207 }
208
209 #[test]
210 fn body_without_mentions_has_no_mentions_key() {
211 let none = MessageExtras::default();
212 assert!(
213 message_body("<p>x</p>", &[], &none)
214 .get("mentions")
215 .is_none()
216 );
217 let with = message_body(
218 "<at id=\"0\">A</at>",
219 &[mention(
220 0,
221 "A",
222 MentionTarget::User {
223 user_id: "u".into(),
224 },
225 )],
226 &none,
227 );
228 assert_eq!(with["mentions"].as_array().unwrap().len(), 1);
229 }
230
231 fn image(content_type: &str, bytes: &[u8]) -> HostedImage {
232 HostedImage {
233 content_type: content_type.to_owned(),
234 bytes: Arc::new(bytes.to_vec()),
235 }
236 }
237
238 #[test]
239 fn plain_body_has_no_hosted_contents_or_attachments() {
240 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
241 assert_eq!(
242 body,
243 json!({"body": {"contentType": "html", "content": "<p>x</p>"}})
244 );
245 }
246
247 #[test]
248 fn images_go_after_the_text_with_matching_temporary_ids() {
249 let extras = MessageExtras {
250 kept: Vec::new(),
251 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
252 files: Vec::new(),
253 };
254 let body = message_body("<p>hi</p>", &[], &extras);
255 assert_eq!(
256 body["body"]["content"],
257 "<p>hi</p><p><img src=\"../hostedContents/1/$value\"></p><p><img src=\"../hostedContents/2/$value\"></p>"
258 );
259 assert_eq!(
260 body["hostedContents"],
261 json!([
262 {"@microsoft.graph.temporaryId": "1", "contentBytes": "AQID", "contentType": "image/png"},
263 {"@microsoft.graph.temporaryId": "2", "contentBytes": "BA==", "contentType": "image/jpeg"},
264 ])
265 );
266 assert!(body.get("attachments").is_none());
267 }
268
269 #[test]
270 fn images_already_placed_in_the_text_are_not_appended_again() {
271 let extras = MessageExtras {
272 kept: Vec::new(),
273 images: vec![image("image/png", &[1]), image("image/png", &[2])],
274 files: Vec::new(),
275 };
276 let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
277 assert_eq!(
278 body["body"]["content"],
279 "a <img src=\"../hostedContents/2/$value\"> b<p><img src=\"../hostedContents/1/$value\"></p>"
280 );
281 assert_eq!(body["hostedContents"].as_array().unwrap().len(), 2);
282 }
283
284 #[test]
285 fn an_edit_keeps_the_original_files_and_image_elements() {
286 let extras = MessageExtras {
287 kept: Vec::new(),
288 images: Vec::new(),
289 files: vec![FileReference {
290 attachment_id: "G1".into(),
291 content_url: "https://x/a.pdf".into(),
292 name: "a.pdf".into(),
293 }],
294 };
295 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
296 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
297 assert_eq!(
298 body["body"]["content"],
299 format!("<p>new</p>{original_image}<attachment id=\"G1\"></attachment>")
300 );
301 assert_eq!(body["attachments"][0]["id"], "G1");
302 assert!(body.get("hostedContents").is_none());
303 }
304
305 #[test]
306 fn an_edit_sends_the_quote_back_unchanged_before_the_text() {
307 let extras = MessageExtras {
308 images: Vec::new(),
309 files: Vec::new(),
310 kept: vec![KeptAttachment {
311 id: "Q1".into(),
312 content_type: Some("messageReference".into()),
313 content: Some("{\"messageId\":\"Q1\"}".into()),
314 content_url: None,
315 name: None,
316 }],
317 };
318 let body = message_body("<p>new</p>", &[], &extras);
319 assert_eq!(
320 body["body"]["content"],
321 "<attachment id=\"Q1\"></attachment><p>new</p>"
322 );
323 assert_eq!(body["attachments"][0]["contentType"], "messageReference");
324 assert_eq!(body["attachments"][0]["content"], "{\"messageId\":\"Q1\"}");
325 }
326
327 #[test]
328 fn files_become_reference_attachments_with_a_tag_in_the_html() {
329 let extras = MessageExtras {
330 kept: Vec::new(),
331 images: Vec::new(),
332 files: vec![FileReference {
333 attachment_id: "AAAA-1111".into(),
334 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
335 name: "Plan.docx".into(),
336 }],
337 };
338 let body = message_body("", &[], &extras);
339 assert_eq!(
340 body["body"]["content"],
341 "<attachment id=\"AAAA-1111\"></attachment>"
342 );
343 assert_eq!(
344 body["attachments"],
345 json!([{
346 "id": "AAAA-1111",
347 "contentType": "reference",
348 "contentUrl": "https://contoso.sharepoint.com/Plan.docx",
349 "name": "Plan.docx",
350 }])
351 );
352 assert!(body.get("hostedContents").is_none());
353 }
354}