BlueGit

ict rusty-teams

Files

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

outgoing.rs

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