| 1 | use chatsvc::ConversationRef; |
| 2 | use chatsvc::ams::AmsImage; |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use graph::{FileReference, HostedImage, MessageExtras, OutgoingMention}; |
| 5 | use serde_json::{Value, json}; |
| 6 | |
| 7 | use crate::engine::SyncEngine; |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::remote::Remote; |
| 10 | use crate::teams_quote::{TeamsQuote, chatsvc_mention_html, message_properties}; |
| 11 | |
| 12 | const AMS_IMAGE_ITEMTYPE: &str = "http://schema.skype.com/AMSImage"; |
| 13 | const FILE_ITEMTYPE: &str = "http://schema.skype.com/File"; |
| 14 | const HOSTED_PREFIX: &str = "../hostedContents/"; |
| 15 | const HOSTED_SUFFIX: &str = "/$value"; |
| 16 | const SITE_SEGMENTS: [&str; 2] = ["/personal/", "/sites/"]; |
| 17 | |
| 18 | /// What was posted, in Graph form for the cache, and the html the cache keeps. |
| 19 | pub(crate) struct ChatsvcSent { |
| 20 | pub message: graph::Message, |
| 21 | pub html: String, |
| 22 | } |
| 23 | |
| 24 | impl<R: Remote> SyncEngine<R> { |
| 25 | /// Posts like Teams web: mention spans, AMS images and the `files` property; `quote` puts a reply quote first. |
| 26 | pub(crate) async fn send_via_chatsvc( |
| 27 | &self, |
| 28 | conversation: &ConversationRef, |
| 29 | root_id: Option<&str>, |
| 30 | html: &str, |
| 31 | mentions: &[OutgoingMention], |
| 32 | extras: &MessageExtras, |
| 33 | quote: Option<&TeamsQuote>, |
| 34 | ) -> Result<ChatsvcSent> { |
| 35 | let properties = message_properties( |
| 36 | quote, |
| 37 | mentions, |
| 38 | extras.importance, |
| 39 | &files_property(&extras.files), |
| 40 | ) |
| 41 | .ok_or(Error::Unsupported( |
| 42 | "a team, channel or tag mention in a chat", |
| 43 | ))?; |
| 44 | self.ensure_display_name().await?; |
| 45 | let me = self |
| 46 | .me() |
| 47 | .ok_or(Error::Unsupported("sending before sign-in"))?; |
| 48 | let conversation_id = conversation.conversation_id(); |
| 49 | let mut uploaded = Vec::new(); |
| 50 | for image in &extras.images { |
| 51 | uploaded.push( |
| 52 | self.remote |
| 53 | .upload_ams_image(&conversation_id, &image.bytes, &image_file_name(image)) |
| 54 | .await?, |
| 55 | ); |
| 56 | } |
| 57 | let body = with_ams_images(html, &uploaded); |
| 58 | let quote_html = quote.map(|quote| quote.html.as_str()).unwrap_or_default(); |
| 59 | let content = format!("{quote_html}{}", chatsvc_mention_html(&body, mentions)); |
| 60 | let message_id = self |
| 61 | .remote |
| 62 | .post_chatsvc_message(conversation, &content, &me.display_name, &properties) |
| 63 | .await?; |
| 64 | let created_at = message_id |
| 65 | .parse::<i64>() |
| 66 | .ok() |
| 67 | .and_then(DateTime::from_timestamp_millis) |
| 68 | .unwrap_or_else(Utc::now); |
| 69 | let cached_html = format!("{quote_html}{body}"); |
| 70 | let attachments: Vec<Value> = extras |
| 71 | .files |
| 72 | .iter() |
| 73 | .map(|file| { |
| 74 | json!({ |
| 75 | "id": file.attachment_id, |
| 76 | "contentType": "reference", |
| 77 | "contentUrl": file.content_url, |
| 78 | "name": file.name, |
| 79 | }) |
| 80 | }) |
| 81 | .collect(); |
| 82 | let message = serde_json::from_value(json!({ |
| 83 | "id": message_id, |
| 84 | "messageType": "message", |
| 85 | "createdDateTime": created_at.to_rfc3339(), |
| 86 | "replyToId": root_id, |
| 87 | "importance": extras.importance, |
| 88 | "from": {"user": {"id": me.user_id, "displayName": me.display_name}}, |
| 89 | "body": {"contentType": "html", "content": cached_html}, |
| 90 | "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(), |
| 91 | "attachments": attachments, |
| 92 | })) |
| 93 | .map_err(|_| Error::Unsupported("a chatsvc send without a message shape"))?; |
| 94 | Ok(ChatsvcSent { |
| 95 | message, |
| 96 | html: cached_html, |
| 97 | }) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fn image_file_name(image: &HostedImage) -> String { |
| 102 | let extension = image |
| 103 | .content_type |
| 104 | .rsplit('/') |
| 105 | .next() |
| 106 | .filter(|extension| !extension.is_empty()) |
| 107 | .unwrap_or("png"); |
| 108 | format!("image.{extension}") |
| 109 | } |
| 110 | |
| 111 | /// Swaps each Graph `../hostedContents/{n}/$value` image for its AMS upload; images not placed in the text go last. |
| 112 | fn with_ams_images(html: &str, uploaded: &[AmsImage]) -> String { |
| 113 | let mut body = html.to_owned(); |
| 114 | for (index, image) in uploaded.iter().enumerate() { |
| 115 | let tag = format!( |
| 116 | "<img itemtype=\"{AMS_IMAGE_ITEMTYPE}\" itemscope=\"\" src=\"{}\" itemid=\"{}\" alt=\"image\">", |
| 117 | image.url, image.object_id |
| 118 | ); |
| 119 | let placeholder = format!("{HOSTED_PREFIX}{}{HOSTED_SUFFIX}", index + 1); |
| 120 | match image_tag_around(&body, &placeholder) { |
| 121 | Some((start, end)) => body.replace_range(start..end, &tag), |
| 122 | None => body.push_str(&format!("<p>{tag}</p>")), |
| 123 | } |
| 124 | } |
| 125 | body |
| 126 | } |
| 127 | |
| 128 | fn image_tag_around(html: &str, source: &str) -> Option<(usize, usize)> { |
| 129 | let at = html.find(&format!("\"{source}\""))?; |
| 130 | let start = html[..at].rfind("<img")?; |
| 131 | let end = html[at..].find('>')? + at + 1; |
| 132 | Some((start, end)) |
| 133 | } |
| 134 | |
| 135 | /// The `files` property Teams writes for a shared OneDrive or SharePoint file. |
| 136 | fn files_property(files: &[FileReference]) -> Value { |
| 137 | Value::Array( |
| 138 | files |
| 139 | .iter() |
| 140 | .map(|file| { |
| 141 | let file_type = file |
| 142 | .name |
| 143 | .rsplit_once('.') |
| 144 | .map(|(_, extension)| extension.to_ascii_lowercase()) |
| 145 | .unwrap_or_default(); |
| 146 | json!({ |
| 147 | "@type": FILE_ITEMTYPE, |
| 148 | "version": 2, |
| 149 | "id": file.attachment_id, |
| 150 | "itemid": file.attachment_id, |
| 151 | "baseUrl": site_url(&file.content_url), |
| 152 | "type": file_type, |
| 153 | "fileType": file_type, |
| 154 | "title": file.name, |
| 155 | "fileName": file.name, |
| 156 | "state": "active", |
| 157 | "objectUrl": file.content_url, |
| 158 | "fileInfo": { |
| 159 | "itemId": null, |
| 160 | "fileUrl": file.content_url, |
| 161 | "siteUrl": site_url(&file.content_url), |
| 162 | "serverRelativeUrl": "", |
| 163 | "shareUrl": null, |
| 164 | "shareId": null, |
| 165 | }, |
| 166 | "fileChicletState": {"serviceName": "p2p", "state": "active"}, |
| 167 | "permissionScope": "users", |
| 168 | }) |
| 169 | }) |
| 170 | .collect(), |
| 171 | ) |
| 172 | } |
| 173 | |
| 174 | /// `https://tenant-my.sharepoint.com/personal/ann/` for a file under that site. |
| 175 | fn site_url(url: &str) -> String { |
| 176 | SITE_SEGMENTS |
| 177 | .iter() |
| 178 | .find_map(|segment| { |
| 179 | let start = url.find(segment)? + segment.len(); |
| 180 | let end = url[start..].find('/')? + start + 1; |
| 181 | Some(url[..end].to_owned()) |
| 182 | }) |
| 183 | .unwrap_or_default() |
| 184 | } |
| 185 | |
| 186 | #[cfg(test)] |
| 187 | mod tests { |
| 188 | use super::*; |
| 189 | |
| 190 | fn uploaded(object_id: &str) -> AmsImage { |
| 191 | AmsImage { |
| 192 | object_id: object_id.into(), |
| 193 | url: format!("https://ams.example/{object_id}"), |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn hosted_images_become_ams_images_in_place_or_last() { |
| 199 | let html = r#"<p>a<img src="../hostedContents/2/$value" width="20">b</p>"#; |
| 200 | let body = with_ams_images(html, &[uploaded("one"), uploaded("two")]); |
| 201 | assert_eq!( |
| 202 | body, |
| 203 | r#"<p>a<img itemtype="http://schema.skype.com/AMSImage" itemscope="" src="https://ams.example/two" itemid="two" alt="image">b</p><p><img itemtype="http://schema.skype.com/AMSImage" itemscope="" src="https://ams.example/one" itemid="one" alt="image"></p>"# |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | #[test] |
| 208 | fn a_file_names_its_site() { |
| 209 | let files = files_property(&[FileReference { |
| 210 | attachment_id: "guid-1".into(), |
| 211 | content_url: |
| 212 | "https://contoso-my.sharepoint.com/personal/ann_contoso_com/Documents/Plan.DOCX" |
| 213 | .into(), |
| 214 | name: "Plan.DOCX".into(), |
| 215 | }]); |
| 216 | assert_eq!( |
| 217 | files[0]["baseUrl"], |
| 218 | "https://contoso-my.sharepoint.com/personal/ann_contoso_com/" |
| 219 | ); |
| 220 | assert_eq!(files[0]["fileType"], "docx"); |
| 221 | assert_eq!( |
| 222 | files[0]["fileInfo"]["fileUrl"], |
| 223 | "https://contoso-my.sharepoint.com/personal/ann_contoso_com/Documents/Plan.DOCX" |
| 224 | ); |
| 225 | } |
| 226 | } |