BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / links.rs

links.rs

links.rs 13.6 KiB Download Raw
1use std::net::Ipv4Addr;
2
3use chatsvc::{LinkInfo, is_link_image_url};
4use scraper::{Html, Selector};
5use serde_json::{Value, json};
6use store::MessageRecord;
7
8use crate::stored::ImageRef;
9
10pub const EMPTY_LINKS: &str = "[]";
11
12const HYPERLINK_TYPE: &str = "http://schema.skype.com/HyperLink";
13const 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)]
25pub 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
34impl 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
96pub fn has_links_markup(record: &MessageRecord) -> bool {
97 !record.deleted && record.body_html.contains("<a ")
98}
99
100pub fn has_stored_links(links_json: &str) -> bool {
101 !matches!(links_json, "" | EMPTY_LINKS)
102}
103
104pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {
105 if record.deleted {
106 return None;
107 }
108 select_preview(&record.links_json)
109}
110
111pub 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
116fn 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
153pub 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
162pub fn public_links(record: &MessageRecord) -> Vec<String> {
163 let Ok(selector) = Selector::parse("a[href]") else {
164 return Vec::new();
165 };
166 if record.deleted {
167 return Vec::new();
168 }
169 let mut links: Vec<String> = Vec::new();
170 for anchor in Html::parse_fragment(&record.body_html).select(&selector) {
171 let Some(href) = anchor
172 .value()
173 .attr("href")
174 .filter(|href| is_public_link(href))
175 else {
176 continue;
177 };
178 if !links.iter().any(|known| known == href) {
179 links.push(href.to_owned());
180 }
181 }
182 links
183}
184
185pub fn is_public_link(url: &str) -> bool {
186 let lower = url.to_ascii_lowercase();
187 if !(lower.starts_with("http://") || lower.starts_with("https://")) {
188 return false;
189 }
190 let Some(host) = link_host(url) else {
191 return false;
192 };
193 if host.starts_with('[') || host == "localhost" || !host.contains('.') {
194 return false;
195 }
196 if INTERNAL_HOSTS
197 .iter()
198 .any(|internal| host == *internal || host.ends_with(&format!(".{internal}")))
199 {
200 return false;
201 }
202 host.parse::<Ipv4Addr>().map_or(true, |address| {
203 !(address.is_private()
204 || address.is_loopback()
205 || address.is_link_local()
206 || address.is_unspecified())
207 })
208}
209
210fn link_host(url: &str) -> Option<String> {
211 let (_, rest) = url.split_once("://")?;
212 let authority = rest.split(['/', '?', '#']).next()?;
213 let host_port = authority
214 .rsplit_once('@')
215 .map_or(authority, |(_, host)| host);
216 let host = if host_port.starts_with('[') {
217 host_port
218 } else {
219 host_port.split(':').next()?
220 };
221 let host = host.trim_end_matches('.').to_ascii_lowercase();
222 (!host.is_empty()).then_some(host)
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 const THUMBNAIL: &str =
230 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x";
231
232 fn links(entries: Value) -> String {
233 entries.to_string()
234 }
235
236 #[test]
237 fn public_links_lists_each_external_link_once() {
238 let record = MessageRecord {
239 body_html: "<p><a href=\"https://a.example/x\">x</a> <a href=\"https://contoso.sharepoint.com/f\">f</a> <a href=\"https://a.example/x\">again</a> <a href=\"https://b.example\">b</a></p>".to_owned(),
240 ..demo_record()
241 };
242 assert_eq!(
243 public_links(&record),
244 ["https://a.example/x", "https://b.example"]
245 );
246 }
247
248 fn demo_record() -> MessageRecord {
249 MessageRecord {
250 conversation_id: "c".to_owned(),
251 message_id: "m".to_owned(),
252 reply_to_id: None,
253 sender_id: None,
254 sender_name: None,
255 created_at: chrono::Utc::now(),
256 edited_at: None,
257 deleted: false,
258 body_html: String::new(),
259 attachments_json: "[]".to_owned(),
260 reactions_json: "[]".to_owned(),
261 mentions_json: "[]".to_owned(),
262 sender_application_id: None,
263 links_json: "[]".to_owned(),
264 subject: None,
265 }
266 }
267
268 #[test]
269 fn picks_the_first_public_link_with_a_title() {
270 let preview = select_preview(&links(json!([
271 {"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},
272 {"url": "https://a.example/x", "preview": {}, "previewenabled": true},
273 {"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},
274 {"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},
275 ])))
276 .unwrap();
277 assert_eq!(preview.url, "https://b.example/y");
278 assert_eq!(preview.title.as_deref(), Some("B"));
279 assert_eq!(preview.description.as_deref(), Some("About B"));
280 assert_eq!(preview.domain(), "b.example");
281 }
282
283 #[test]
284 fn an_image_alone_is_enough() {
285 let preview = select_preview(&links(json!([
286 {"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},
287 ])))
288 .unwrap();
289 assert_eq!(preview.title, None);
290 assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL));
291 assert_eq!(
292 (preview.image_width, preview.image_height),
293 (Some(320), Some(160))
294 );
295 }
296
297 #[test]
298 fn reads_the_camel_case_meta_and_null_meta() {
299 let preview = select_preview(&links(json!([
300 {"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},
301 {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
302 ])))
303 .unwrap();
304 assert_eq!(
305 (preview.image_width, preview.image_height),
306 (Some(20), Some(10))
307 );
308 let second = select_preview(&links(json!([
309 {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
310 ])))
311 .unwrap();
312 assert_eq!(second.image_width, None);
313 }
314
315 #[test]
316 fn a_removed_preview_is_not_shown() {
317 assert_eq!(
318 select_preview(&links(json!([
319 {"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false},
320 ]))),
321 None
322 );
323 }
324
325 #[test]
326 fn images_outside_the_preview_service_are_dropped() {
327 assert_eq!(
328 select_preview(&links(json!([
329 {"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}},
330 ]))),
331 None
332 );
333 }
334
335 #[test]
336 fn garbage_and_empty_lists_have_no_preview() {
337 assert_eq!(select_preview("[]"), None);
338 assert_eq!(select_preview(""), None);
339 assert_eq!(select_preview("{}"), None);
340 assert_eq!(select_preview("[{\"url\": 3}]"), None);
341 }
342
343 #[test]
344 fn internal_and_private_hosts_are_skipped() {
345 for url in [
346 "https://contoso.sharepoint.com/a",
347 "https://contoso-my.sharepoint.com/a",
348 "https://onedrive.com/a",
349 "https://1drv.ms/a",
350 "https://teams.microsoft.com/l/x",
351 "https://teams.cloud.microsoft/x",
352 "https://teams.live.com/x",
353 "https://www.office.com/x",
354 "https://m365.microsoft365.com/x",
355 "https://localhost/x",
356 "https://intranet/x",
357 "http://192.168.1.2/x",
358 "http://127.0.0.1:8080/x",
359 "ftp://a.example/x",
360 "mailto:a@b.example",
361 ] {
362 assert!(!is_public_link(url), "{url}");
363 }
364 for url in [
365 "https://github.com/rust-lang/rust",
366 "http://a.example:8080/x",
367 "https://notsharepoint.com/x",
368 "https://user@example.org/x",
369 ] {
370 assert!(is_public_link(url), "{url}");
371 }
372 }
373
374 #[test]
375 fn finds_the_first_public_anchor_in_html() {
376 let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \
377 <a href=\"https://a.example/?q=1&amp;r=2\">a</a> <a href=\"https://b.example\">b</a></p>";
378 assert_eq!(
379 first_public_link(html).as_deref(),
380 Some("https://a.example/?q=1&r=2")
381 );
382 assert_eq!(first_public_link("<p>no link</p>"), None);
383 }
384
385 #[test]
386 fn outgoing_json_reads_back_as_the_same_preview() {
387 let preview = LinkPreview {
388 url: "https://github.com/rust-lang/rust".into(),
389 title: Some("Rust".into()),
390 description: Some("Empowering".into()),
391 image_url: Some(THUMBNAIL.into()),
392 image_width: Some(320),
393 image_height: Some(160),
394 };
395 let json: Value = serde_json::from_str(&preview.links_json()).unwrap();
396 assert_eq!(json[0]["@type"], HYPERLINK_TYPE);
397 assert_eq!(json[0]["itemid"], "0");
398 assert_eq!(json[0]["previewenabled"], true);
399 assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL);
400 assert_eq!(select_preview(&preview.links_json()), Some(preview));
401 }
402
403 #[test]
404 fn info_without_title_or_usable_image_makes_no_preview() {
405 let info = LinkInfo {
406 url: "https://a.example".into(),
407 description: Some("only text".into()),
408 thumbnail: Some("https://evil.example/i.png".into()),
409 ..LinkInfo::default()
410 };
411 assert_eq!(LinkPreview::from_info("https://a.example", &info), None);
412 }
413
414 #[test]
415 fn deleted_messages_show_no_preview() {
416 let record = MessageRecord {
417 deleted: true,
418 links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),
419 ..MessageRecord::default()
420 };
421 assert_eq!(link_preview(&record), None);
422 }
423}