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