| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | pub(crate) use chatsvc::graph_events::{attribute, unescape}; |
| 4 | |
| 5 | const MENTION_ITEMTYPE: &str = "schema.skype.com/Mention"; |
| 6 | const INPUT_EXTENSION_ITEMTYPE: &str = "schema.skype.com/InputExtension"; |
| 7 | const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward"; |
| 8 | const EMOTICON_CLASS: &str = "animated-emoticon"; |
| 9 | const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply"; |
| 10 | |
| 11 | /// A chat service body in the shape Graph serves it: `<at>` mentions and `<attachment>` markers. |
| 12 | #[derive(Debug, Default, PartialEq, Eq)] |
| 13 | pub(crate) struct GraphBody { |
| 14 | pub html: String, |
| 15 | pub mention_texts: HashMap<String, String>, |
| 16 | pub forwards: Vec<String>, |
| 17 | pub quotes: Vec<QuotedMessage>, |
| 18 | } |
| 19 | |
| 20 | /// A Teams reply quote, which Graph serves as a `messageReference` attachment. |
| 21 | #[derive(Debug, PartialEq, Eq)] |
| 22 | pub(crate) struct QuotedMessage { |
| 23 | pub message_id: String, |
| 24 | pub sender_mri: Option<String>, |
| 25 | pub sender_name: Option<String>, |
| 26 | pub preview: String, |
| 27 | } |
| 28 | |
| 29 | /// `forward_ids` name the `<attachment>` that replaces each forward quote, in order. |
| 30 | pub(crate) fn graph_body(content: &str, forward_ids: &[String]) -> GraphBody { |
| 31 | let mut body = GraphBody::default(); |
| 32 | let mut rest = content; |
| 33 | while let Some(start) = rest.find('<') { |
| 34 | body.html.push_str(&rest[..start]); |
| 35 | rest = &rest[start..]; |
| 36 | let Some(element) = Element::open_at(rest) else { |
| 37 | body.html.push('<'); |
| 38 | rest = &rest[1..]; |
| 39 | continue; |
| 40 | }; |
| 41 | let itemtype = attribute(element.tag, "itemtype").unwrap_or_default(); |
| 42 | let class = attribute(element.tag, "class").unwrap_or_default(); |
| 43 | let Some(rewrite) = Rewrite::of(element.name, itemtype, class) else { |
| 44 | body.html.push_str(element.tag); |
| 45 | rest = &rest[element.tag.len()..]; |
| 46 | continue; |
| 47 | }; |
| 48 | let Some((inner, after)) = element.inner_and_rest(rest) else { |
| 49 | body.html.push_str(element.tag); |
| 50 | rest = &rest[element.tag.len()..]; |
| 51 | continue; |
| 52 | }; |
| 53 | let item_id = attribute(element.tag, "itemid").unwrap_or_default(); |
| 54 | match rewrite { |
| 55 | Rewrite::Mention => { |
| 56 | let text = plain_text(inner); |
| 57 | body.mention_texts.insert(item_id.to_owned(), text); |
| 58 | body.html |
| 59 | .push_str(&format!("<at id=\"{item_id}\">{inner}</at>")); |
| 60 | } |
| 61 | Rewrite::Emoticon => match emoji_tag(inner) { |
| 62 | Some(tag) => body.html.push_str(&tag), |
| 63 | None => body.html.push_str(&rest[..rest.len() - after.len()]), |
| 64 | }, |
| 65 | Rewrite::Reply if !item_id.is_empty() => { |
| 66 | body.html |
| 67 | .push_str(&format!("<attachment id=\"{item_id}\"></attachment>")); |
| 68 | body.quotes.push(quoted_message(item_id, inner)); |
| 69 | } |
| 70 | Rewrite::Reply => body.html.push_str(&rest[..rest.len() - after.len()]), |
| 71 | Rewrite::Card => body |
| 72 | .html |
| 73 | .push_str(&format!("<attachment id=\"{item_id}\"></attachment>")), |
| 74 | Rewrite::Forward => { |
| 75 | match forward_ids.get(body.forwards.len()) { |
| 76 | Some(id) => body |
| 77 | .html |
| 78 | .push_str(&format!("<attachment id=\"{id}\"></attachment>")), |
| 79 | None => body.html.push_str(&rest[..rest.len() - after.len()]), |
| 80 | } |
| 81 | body.forwards.push(inner.to_owned()); |
| 82 | } |
| 83 | } |
| 84 | rest = after; |
| 85 | } |
| 86 | body.html.push_str(rest); |
| 87 | body |
| 88 | } |
| 89 | |
| 90 | #[derive(Clone, Copy)] |
| 91 | enum Rewrite { |
| 92 | Mention, |
| 93 | Emoticon, |
| 94 | Reply, |
| 95 | Card, |
| 96 | Forward, |
| 97 | } |
| 98 | |
| 99 | impl Rewrite { |
| 100 | fn of(name: &str, itemtype: &str, class: &str) -> Option<Rewrite> { |
| 101 | match name { |
| 102 | "span" if itemtype.contains(MENTION_ITEMTYPE) => Some(Rewrite::Mention), |
| 103 | "span" if class.contains(EMOTICON_CLASS) => Some(Rewrite::Emoticon), |
| 104 | "span" if itemtype.contains(INPUT_EXTENSION_ITEMTYPE) => Some(Rewrite::Card), |
| 105 | "blockquote" if itemtype.contains(FORWARD_ITEMTYPE) => Some(Rewrite::Forward), |
| 106 | "blockquote" if itemtype.contains(REPLY_ITEMTYPE) => Some(Rewrite::Reply), |
| 107 | _ => None, |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | struct Element<'a> { |
| 113 | name: &'a str, |
| 114 | tag: &'a str, |
| 115 | } |
| 116 | |
| 117 | impl<'a> Element<'a> { |
| 118 | fn open_at(text: &'a str) -> Option<Element<'a>> { |
| 119 | let end = text.find('>')? + 1; |
| 120 | let tag = &text[..end]; |
| 121 | let name_end = tag[1..].find(|character: char| { |
| 122 | character.is_whitespace() || character == '>' || character == '/' |
| 123 | })? + 1; |
| 124 | let name = &tag[1..name_end]; |
| 125 | (!name.is_empty() |
| 126 | && name |
| 127 | .chars() |
| 128 | .all(|character| character.is_ascii_alphanumeric())) |
| 129 | .then_some(Element { name, tag }) |
| 130 | } |
| 131 | |
| 132 | /// The text between this element's tags and what follows its closing tag, nested elements of the same name included. |
| 133 | fn inner_and_rest(&self, text: &'a str) -> Option<(&'a str, &'a str)> { |
| 134 | let open = format!("<{}", self.name); |
| 135 | let close = format!("</{}>", self.name); |
| 136 | let inner_start = self.tag.len(); |
| 137 | let mut depth = 1; |
| 138 | let mut position = inner_start; |
| 139 | while depth > 0 { |
| 140 | let next_close = text[position..].find(&close)? + position; |
| 141 | match text[position..].find(&open).map(|found| found + position) { |
| 142 | Some(next_open) |
| 143 | if next_open < next_close && opens_element(text, next_open, &open) => |
| 144 | { |
| 145 | depth += 1; |
| 146 | position = next_open + open.len(); |
| 147 | } |
| 148 | _ => { |
| 149 | depth -= 1; |
| 150 | if depth == 0 { |
| 151 | return Some(( |
| 152 | &text[inner_start..next_close], |
| 153 | &text[next_close + close.len()..], |
| 154 | )); |
| 155 | } |
| 156 | position = next_close + close.len(); |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | None |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | fn quoted_message(message_id: &str, inner: &str) -> QuotedMessage { |
| 165 | let property = |name: &str| -> Option<(&str, &str)> { |
| 166 | let marker = format!("itemprop=\"{name}\""); |
| 167 | let at = inner.find(&marker)?; |
| 168 | let tag_start = inner[..at].rfind('<')?; |
| 169 | let element = Element::open_at(&inner[tag_start..])?; |
| 170 | let (content, _) = element.inner_and_rest(&inner[tag_start..])?; |
| 171 | Some((element.tag, content)) |
| 172 | }; |
| 173 | let sender = property("mri"); |
| 174 | QuotedMessage { |
| 175 | message_id: message_id.to_owned(), |
| 176 | sender_mri: sender |
| 177 | .and_then(|(tag, _)| attribute(tag, "itemid")) |
| 178 | .filter(|mri| !mri.is_empty()) |
| 179 | .map(str::to_owned), |
| 180 | sender_name: sender |
| 181 | .map(|(_, content)| plain_text(content)) |
| 182 | .filter(|name| !name.is_empty()), |
| 183 | preview: property("preview") |
| 184 | .map(|(_, content)| plain_text(content)) |
| 185 | .unwrap_or_default(), |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// Graph's `<emoji>` for a Teams emoticon span, read from the emoji image inside it. |
| 190 | fn emoji_tag(inner: &str) -> Option<String> { |
| 191 | let start = inner.find("<img")?; |
| 192 | let end = inner[start..].find('>')? + start; |
| 193 | let image = &inner[start..end]; |
| 194 | let id = attribute(image, "itemid")?; |
| 195 | let alt = attribute(image, "alt").unwrap_or_default(); |
| 196 | let title = attribute(image, "title").unwrap_or_default(); |
| 197 | Some(format!( |
| 198 | "<emoji id=\"{id}\" alt=\"{alt}\" title=\"{title}\"></emoji>" |
| 199 | )) |
| 200 | } |
| 201 | |
| 202 | fn opens_element(text: &str, at: usize, open: &str) -> bool { |
| 203 | text[at + open.len()..] |
| 204 | .chars() |
| 205 | .next() |
| 206 | .is_some_and(|next| next.is_whitespace() || next == '>') |
| 207 | } |
| 208 | |
| 209 | pub(crate) fn plain_text(html: &str) -> String { |
| 210 | let mut text = String::new(); |
| 211 | let mut in_tag = false; |
| 212 | for character in html.chars() { |
| 213 | match character { |
| 214 | '<' => in_tag = true, |
| 215 | '>' => in_tag = false, |
| 216 | _ if !in_tag => text.push(character), |
| 217 | _ => {} |
| 218 | } |
| 219 | } |
| 220 | unescape(text.trim()) |
| 221 | } |
| 222 | |
| 223 | #[cfg(test)] |
| 224 | mod tests { |
| 225 | use super::*; |
| 226 | |
| 227 | #[test] |
| 228 | fn mention_spans_become_at_tags() { |
| 229 | let body = graph_body( |
| 230 | r#"<p>hi <span itemtype="http://schema.skype.com/Mention" itemscope="" itemid="0">Ada & Co</span>!</p>"#, |
| 231 | &[], |
| 232 | ); |
| 233 | assert_eq!(body.html, r#"<p>hi <at id="0">Ada & Co</at>!</p>"#); |
| 234 | assert_eq!(body.mention_texts["0"], "Ada & Co"); |
| 235 | } |
| 236 | |
| 237 | #[test] |
| 238 | fn emoticon_spans_stay_and_nested_spans_close_right() { |
| 239 | let html = r#"<p><span itemtype="http://schema.skype.com/Mention" itemid="1"><span>Bo</span></span> <span title="Smile" type="(smile)" class="animated-emoticon-20-smile" itemscope=""><img itemtype="http://schema.skype.com/Emoji" alt="🙂"></span></p>"#; |
| 240 | let body = graph_body(html, &[]); |
| 241 | assert!( |
| 242 | body.html |
| 243 | .starts_with(r#"<p><at id="1"><span>Bo</span></at> <span title="Smile""#) |
| 244 | ); |
| 245 | assert_eq!(body.mention_texts["1"], "Bo"); |
| 246 | } |
| 247 | |
| 248 | #[test] |
| 249 | fn emoticon_spans_become_graph_emoji() { |
| 250 | let html = r#"<p>ok<span title="Smile" type="(smile)" class="animated-emoticon-20-smile" itemscope=""><img itemscope="" itemtype="http://schema.skype.com/Emoji" itemid="smile" src="https://x/e.png" title="Smile" alt="🙂"></span></p>"#; |
| 251 | assert_eq!( |
| 252 | graph_body(html, &[]).html, |
| 253 | r#"<p>ok<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"# |
| 254 | ); |
| 255 | } |
| 256 | |
| 257 | #[test] |
| 258 | fn reply_quotes_become_message_references() { |
| 259 | let html = r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="1751975663649"><strong itemprop="mri" itemid="8:orgid:ann">Ann</strong><span itemprop="time" itemid="1751975663649"></span><p itemprop="preview">old & true</p></blockquote><p>new</p>"#; |
| 260 | let body = graph_body(html, &[]); |
| 261 | assert_eq!( |
| 262 | body.html, |
| 263 | r#"<attachment id="1751975663649"></attachment><p>new</p>"# |
| 264 | ); |
| 265 | assert_eq!( |
| 266 | body.quotes, |
| 267 | vec![QuotedMessage { |
| 268 | message_id: "1751975663649".into(), |
| 269 | sender_mri: Some("8:orgid:ann".into()), |
| 270 | sender_name: Some("Ann".into()), |
| 271 | preview: "old & true".into(), |
| 272 | }] |
| 273 | ); |
| 274 | } |
| 275 | |
| 276 | #[test] |
| 277 | fn card_placeholders_and_forwards_become_attachment_markers() { |
| 278 | let html = r#"<p>see</p><span itemid="card-1" itemscope="" itemtype="http://schema.skype.com/InputExtension"><span itemprop="cardId"></span></span><blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#; |
| 279 | let body = graph_body(html, &["m7".to_owned()]); |
| 280 | assert_eq!( |
| 281 | body.html, |
| 282 | r#"<p>see</p><attachment id="card-1"></attachment><attachment id="m7"></attachment>"# |
| 283 | ); |
| 284 | assert_eq!(body.forwards, vec!["<p>old</p>".to_owned()]); |
| 285 | } |
| 286 | |
| 287 | #[test] |
| 288 | fn a_forward_without_context_keeps_its_quote() { |
| 289 | let html = |
| 290 | r#"<blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#; |
| 291 | assert_eq!(graph_body(html, &[]).html, html); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn broken_markup_is_kept() { |
| 296 | assert_eq!( |
| 297 | graph_body("a < b <span itemtype=\"x\">", &[]).html, |
| 298 | "a < b <span itemtype=\"x\">" |
| 299 | ); |
| 300 | } |
| 301 | } |