| 1 | use std::net::Ipv4Addr; |
| 2 | |
| 3 | use chatsvc::{LinkInfo, is_link_image_url}; |
| 4 | use scraper::{Html, Selector}; |
| 5 | use serde_json::{Value, json}; |
| 6 | use store::MessageRecord; |
| 7 | |
| 8 | use crate::stored::ImageRef; |
| 9 | |
| 10 | pub const EMPTY_LINKS: &str = "[]"; |
| 11 | |
| 12 | const HYPERLINK_TYPE: &str = "http://schema.skype.com/HyperLink"; |
| 13 | const INTERNAL_HOSTS: [&str; 8] = [ |
| 14 | "sharepoint.com", |
| 15 | "onedrive.com", |
| 16 | "1drv.ms", |
| 17 | "teams.microsoft.com", |
| 18 | "teams.cloud.microsoft", |
| 19 | "teams.live.com", |
| 20 | "office.com", |
| 21 | "microsoft365.com", |
| 22 | ]; |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 25 | pub struct LinkPreview { |
| 26 | pub url: String, |
| 27 | pub title: Option<String>, |
| 28 | pub description: Option<String>, |
| 29 | pub image_url: Option<String>, |
| 30 | pub image_width: Option<u32>, |
| 31 | pub image_height: Option<u32>, |
| 32 | } |
| 33 | |
| 34 | impl LinkPreview { |
| 35 | pub fn from_info(url: &str, info: &LinkInfo) -> Option<LinkPreview> { |
| 36 | let preview = LinkPreview { |
| 37 | url: url.to_owned(), |
| 38 | title: info.title.clone(), |
| 39 | description: info.description.clone(), |
| 40 | image_url: info |
| 41 | .thumbnail |
| 42 | .clone() |
| 43 | .filter(|thumbnail| is_link_image_url(thumbnail)), |
| 44 | image_width: info.thumbnail_width, |
| 45 | image_height: info.thumbnail_height, |
| 46 | }; |
| 47 | preview.is_showable().then_some(preview) |
| 48 | } |
| 49 | |
| 50 | pub fn domain(&self) -> String { |
| 51 | let host = link_host(&self.url).unwrap_or_default(); |
| 52 | host.strip_prefix("www.").unwrap_or(&host).to_owned() |
| 53 | } |
| 54 | |
| 55 | pub fn image(&self) -> Option<ImageRef> { |
| 56 | Some(ImageRef { |
| 57 | id: String::new(), |
| 58 | url: self.image_url.clone()?, |
| 59 | width: self.image_width, |
| 60 | height: self.image_height, |
| 61 | }) |
| 62 | } |
| 63 | |
| 64 | pub fn links_json(&self) -> String { |
| 65 | let mut preview = serde_json::Map::new(); |
| 66 | if let Some(image_url) = &self.image_url { |
| 67 | preview.insert("previewurl".into(), json!(image_url)); |
| 68 | } |
| 69 | if let Some((width, height)) = self.image_width.zip(self.image_height) { |
| 70 | preview.insert( |
| 71 | "previewmeta".into(), |
| 72 | json!({"height": height, "width": width}), |
| 73 | ); |
| 74 | } |
| 75 | if let Some(title) = &self.title { |
| 76 | preview.insert("title".into(), json!(title)); |
| 77 | } |
| 78 | if let Some(description) = &self.description { |
| 79 | preview.insert("description".into(), json!(description)); |
| 80 | } |
| 81 | json!([{ |
| 82 | "@type": HYPERLINK_TYPE, |
| 83 | "itemid": "0", |
| 84 | "url": self.url, |
| 85 | "preview": preview, |
| 86 | "previewenabled": true, |
| 87 | }]) |
| 88 | .to_string() |
| 89 | } |
| 90 | |
| 91 | fn is_showable(&self) -> bool { |
| 92 | self.title.is_some() || self.image_url.is_some() |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn has_links_markup(record: &MessageRecord) -> bool { |
| 97 | !record.deleted && record.body_html.contains("<a ") |
| 98 | } |
| 99 | |
| 100 | pub fn has_stored_links(links_json: &str) -> bool { |
| 101 | !matches!(links_json, "" | EMPTY_LINKS) |
| 102 | } |
| 103 | |
| 104 | pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> { |
| 105 | if record.deleted { |
| 106 | return None; |
| 107 | } |
| 108 | select_preview(&record.links_json) |
| 109 | } |
| 110 | |
| 111 | pub fn select_preview(links_json: &str) -> Option<LinkPreview> { |
| 112 | let entries: Vec<Value> = serde_json::from_str(links_json).ok()?; |
| 113 | entries.iter().find_map(entry_preview) |
| 114 | } |
| 115 | |
| 116 | fn entry_preview(entry: &Value) -> Option<LinkPreview> { |
| 117 | if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) { |
| 118 | return None; |
| 119 | } |
| 120 | let url = entry.get("url")?.as_str()?; |
| 121 | if !is_public_link(url) { |
| 122 | return None; |
| 123 | } |
| 124 | let preview = entry.get("preview").filter(|preview| preview.is_object())?; |
| 125 | let text = |key: &str| { |
| 126 | preview |
| 127 | .get(key) |
| 128 | .and_then(Value::as_str) |
| 129 | .map(str::trim) |
| 130 | .filter(|value| !value.is_empty()) |
| 131 | .map(str::to_owned) |
| 132 | }; |
| 133 | let meta = ["previewmeta", "previewMetadata"] |
| 134 | .into_iter() |
| 135 | .find_map(|key| preview.get(key).filter(|meta| meta.is_object())); |
| 136 | let size = |key: &str| { |
| 137 | meta.and_then(|meta| meta.get(key)) |
| 138 | .and_then(Value::as_u64) |
| 139 | .and_then(|value| u32::try_from(value).ok()) |
| 140 | .filter(|value| *value > 0) |
| 141 | }; |
| 142 | let candidate = LinkPreview { |
| 143 | url: url.to_owned(), |
| 144 | title: text("title"), |
| 145 | description: text("description"), |
| 146 | image_url: text("previewurl").filter(|image_url| is_link_image_url(image_url)), |
| 147 | image_width: size("width"), |
| 148 | image_height: size("height"), |
| 149 | }; |
| 150 | candidate.is_showable().then_some(candidate) |
| 151 | } |
| 152 | |
| 153 | pub fn first_public_link(html: &str) -> Option<String> { |
| 154 | let selector = Selector::parse("a[href]").ok()?; |
| 155 | Html::parse_fragment(html) |
| 156 | .select(&selector) |
| 157 | .filter_map(|anchor| anchor.value().attr("href")) |
| 158 | .find(|href| is_public_link(href)) |
| 159 | .map(str::to_owned) |
| 160 | } |
| 161 | |
| 162 | pub fn is_public_link(url: &str) -> bool { |
| 163 | let lower = url.to_ascii_lowercase(); |
| 164 | if !(lower.starts_with("http://") || lower.starts_with("https://")) { |
| 165 | return false; |
| 166 | } |
| 167 | let Some(host) = link_host(url) else { |
| 168 | return false; |
| 169 | }; |
| 170 | if host.starts_with('[') || host == "localhost" || !host.contains('.') { |
| 171 | return false; |
| 172 | } |
| 173 | if INTERNAL_HOSTS |
| 174 | .iter() |
| 175 | .any(|internal| host == *internal || host.ends_with(&format!(".{internal}"))) |
| 176 | { |
| 177 | return false; |
| 178 | } |
| 179 | host.parse::<Ipv4Addr>().map_or(true, |address| { |
| 180 | !(address.is_private() |
| 181 | || address.is_loopback() |
| 182 | || address.is_link_local() |
| 183 | || address.is_unspecified()) |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | fn link_host(url: &str) -> Option<String> { |
| 188 | let (_, rest) = url.split_once("://")?; |
| 189 | let authority = rest.split(['/', '?', '#']).next()?; |
| 190 | let host_port = authority |
| 191 | .rsplit_once('@') |
| 192 | .map_or(authority, |(_, host)| host); |
| 193 | let host = if host_port.starts_with('[') { |
| 194 | host_port |
| 195 | } else { |
| 196 | host_port.split(':').next()? |
| 197 | }; |
| 198 | let host = host.trim_end_matches('.').to_ascii_lowercase(); |
| 199 | (!host.is_empty()).then_some(host) |
| 200 | } |
| 201 | |
| 202 | #[cfg(test)] |
| 203 | mod tests { |
| 204 | use super::*; |
| 205 | |
| 206 | const THUMBNAIL: &str = |
| 207 | "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x"; |
| 208 | |
| 209 | fn links(entries: Value) -> String { |
| 210 | entries.to_string() |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn picks_the_first_public_link_with_a_title() { |
| 215 | let preview = select_preview(&links(json!([ |
| 216 | {"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true}, |
| 217 | {"url": "https://a.example/x", "preview": {}, "previewenabled": true}, |
| 218 | {"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}}, |
| 219 | {"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true}, |
| 220 | ]))) |
| 221 | .unwrap(); |
| 222 | assert_eq!(preview.url, "https://b.example/y"); |
| 223 | assert_eq!(preview.title.as_deref(), Some("B")); |
| 224 | assert_eq!(preview.description.as_deref(), Some("About B")); |
| 225 | assert_eq!(preview.domain(), "b.example"); |
| 226 | } |
| 227 | |
| 228 | #[test] |
| 229 | fn an_image_alone_is_enough() { |
| 230 | let preview = select_preview(&links(json!([ |
| 231 | {"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null}, |
| 232 | ]))) |
| 233 | .unwrap(); |
| 234 | assert_eq!(preview.title, None); |
| 235 | assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL)); |
| 236 | assert_eq!( |
| 237 | (preview.image_width, preview.image_height), |
| 238 | (Some(320), Some(160)) |
| 239 | ); |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn reads_the_camel_case_meta_and_null_meta() { |
| 244 | let preview = select_preview(&links(json!([ |
| 245 | {"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}}, |
| 246 | {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}}, |
| 247 | ]))) |
| 248 | .unwrap(); |
| 249 | assert_eq!( |
| 250 | (preview.image_width, preview.image_height), |
| 251 | (Some(20), Some(10)) |
| 252 | ); |
| 253 | let second = select_preview(&links(json!([ |
| 254 | {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}}, |
| 255 | ]))) |
| 256 | .unwrap(); |
| 257 | assert_eq!(second.image_width, None); |
| 258 | } |
| 259 | |
| 260 | #[test] |
| 261 | fn a_removed_preview_is_not_shown() { |
| 262 | assert_eq!( |
| 263 | select_preview(&links(json!([ |
| 264 | {"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false}, |
| 265 | ]))), |
| 266 | None |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn images_outside_the_preview_service_are_dropped() { |
| 272 | assert_eq!( |
| 273 | select_preview(&links(json!([ |
| 274 | {"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}}, |
| 275 | ]))), |
| 276 | None |
| 277 | ); |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn garbage_and_empty_lists_have_no_preview() { |
| 282 | assert_eq!(select_preview("[]"), None); |
| 283 | assert_eq!(select_preview(""), None); |
| 284 | assert_eq!(select_preview("{}"), None); |
| 285 | assert_eq!(select_preview("[{\"url\": 3}]"), None); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn internal_and_private_hosts_are_skipped() { |
| 290 | for url in [ |
| 291 | "https://contoso.sharepoint.com/a", |
| 292 | "https://contoso-my.sharepoint.com/a", |
| 293 | "https://onedrive.com/a", |
| 294 | "https://1drv.ms/a", |
| 295 | "https://teams.microsoft.com/l/x", |
| 296 | "https://teams.cloud.microsoft/x", |
| 297 | "https://teams.live.com/x", |
| 298 | "https://www.office.com/x", |
| 299 | "https://m365.microsoft365.com/x", |
| 300 | "https://localhost/x", |
| 301 | "https://intranet/x", |
| 302 | "http://192.168.1.2/x", |
| 303 | "http://127.0.0.1:8080/x", |
| 304 | "ftp://a.example/x", |
| 305 | "mailto:a@b.example", |
| 306 | ] { |
| 307 | assert!(!is_public_link(url), "{url}"); |
| 308 | } |
| 309 | for url in [ |
| 310 | "https://github.com/rust-lang/rust", |
| 311 | "http://a.example:8080/x", |
| 312 | "https://notsharepoint.com/x", |
| 313 | "https://user@example.org/x", |
| 314 | ] { |
| 315 | assert!(is_public_link(url), "{url}"); |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn finds_the_first_public_anchor_in_html() { |
| 321 | let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \ |
| 322 | <a href=\"https://a.example/?q=1&r=2\">a</a> <a href=\"https://b.example\">b</a></p>"; |
| 323 | assert_eq!( |
| 324 | first_public_link(html).as_deref(), |
| 325 | Some("https://a.example/?q=1&r=2") |
| 326 | ); |
| 327 | assert_eq!(first_public_link("<p>no link</p>"), None); |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn outgoing_json_reads_back_as_the_same_preview() { |
| 332 | let preview = LinkPreview { |
| 333 | url: "https://github.com/rust-lang/rust".into(), |
| 334 | title: Some("Rust".into()), |
| 335 | description: Some("Empowering".into()), |
| 336 | image_url: Some(THUMBNAIL.into()), |
| 337 | image_width: Some(320), |
| 338 | image_height: Some(160), |
| 339 | }; |
| 340 | let json: Value = serde_json::from_str(&preview.links_json()).unwrap(); |
| 341 | assert_eq!(json[0]["@type"], HYPERLINK_TYPE); |
| 342 | assert_eq!(json[0]["itemid"], "0"); |
| 343 | assert_eq!(json[0]["previewenabled"], true); |
| 344 | assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL); |
| 345 | assert_eq!(select_preview(&preview.links_json()), Some(preview)); |
| 346 | } |
| 347 | |
| 348 | #[test] |
| 349 | fn info_without_title_or_usable_image_makes_no_preview() { |
| 350 | let info = LinkInfo { |
| 351 | url: "https://a.example".into(), |
| 352 | description: Some("only text".into()), |
| 353 | thumbnail: Some("https://evil.example/i.png".into()), |
| 354 | ..LinkInfo::default() |
| 355 | }; |
| 356 | assert_eq!(LinkPreview::from_info("https://a.example", &info), None); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn deleted_messages_show_no_preview() { |
| 361 | let record = MessageRecord { |
| 362 | deleted: true, |
| 363 | links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])), |
| 364 | ..MessageRecord::default() |
| 365 | }; |
| 366 | assert_eq!(link_preview(&record), None); |
| 367 | } |
| 368 | } |