BlueGit

ict rusty-teams

Files

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

links.rs

links.rs 13.7 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 alt: None,
62 })
63 }
64
65 pub fn links_json(&self) -> String {
66 let mut preview = serde_json::Map::new();
67 if let Some(image_url) = &self.image_url {
68 preview.insert("previewurl".into(), json!(image_url));
69 }
70 if let Some((width, height)) = self.image_width.zip(self.image_height) {
71 preview.insert(
72 "previewmeta".into(),
73 json!({"height": height, "width": width}),
74 );
75 }
76 if let Some(title) = &self.title {
77 preview.insert("title".into(), json!(title));
78 }
79 if let Some(description) = &self.description {
80 preview.insert("description".into(), json!(description));
81 }
82 json!([{
83 "@type": HYPERLINK_TYPE,
84 "itemid": "0",
85 "url": self.url,
86 "preview": preview,
87 "previewenabled": true,
88 }])
89 .to_string()
90 }
91
92 fn is_showable(&self) -> bool {
93 self.title.is_some() || self.image_url.is_some()
94 }
95}
96
97pub fn has_links_markup(record: &MessageRecord) -> bool {
98 !record.deleted && record.body_html.contains("<a ")
99}
100
101pub fn has_stored_links(links_json: &str) -> bool {
102 !matches!(links_json, "" | EMPTY_LINKS)
103}
104
105pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {
106 if record.deleted {
107 return None;
108 }
109 select_preview(&record.links_json)
110}
111
112pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
113 let entries: Vec<Value> = serde_json::from_str(links_json).ok()?;
114 entries.iter().find_map(entry_preview)
115}
116
117fn entry_preview(entry: &Value) -> Option<LinkPreview> {
118 if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {
119 return None;
120 }
121 let url = entry.get("url")?.as_str()?;
122 if !is_public_link(url) {
123 return None;
124 }
125 let preview = entry.get("preview").filter(|preview| preview.is_object())?;
126 let text = |key: &str| {
127 preview
128 .get(key)
129 .and_then(Value::as_str)
130 .map(str::trim)
131 .filter(|value| !value.is_empty())
132 .map(str::to_owned)
133 };
134 let meta = ["previewmeta", "previewMetadata"]
135 .into_iter()
136 .find_map(|key| preview.get(key).filter(|meta| meta.is_object()));
137 let size = |key: &str| {
138 meta.and_then(|meta| meta.get(key))
139 .and_then(Value::as_u64)
140 .and_then(|value| u32::try_from(value).ok())
141 .filter(|value| *value > 0)
142 };
143 let candidate = LinkPreview {
144 url: url.to_owned(),
145 title: text("title"),
146 description: text("description"),
147 image_url: text("previewurl").filter(|image_url| is_link_image_url(image_url)),
148 image_width: size("width"),
149 image_height: size("height"),
150 };
151 candidate.is_showable().then_some(candidate)
152}
153
154pub fn first_public_link(html: &str) -> Option<String> {
155 let selector = Selector::parse("a[href]").ok()?;
156 Html::parse_fragment(html)
157 .select(&selector)
158 .filter_map(|anchor| anchor.value().attr("href"))
159 .find(|href| is_public_link(href))
160 .map(str::to_owned)
161}
162
163pub fn public_links(record: &MessageRecord) -> Vec<String> {
164 let Ok(selector) = Selector::parse("a[href]") else {
165 return Vec::new();
166 };
167 if record.deleted {
168 return Vec::new();
169 }
170 let mut links: Vec<String> = Vec::new();
171 for anchor in Html::parse_fragment(&record.body_html).select(&selector) {
172 let Some(href) = anchor
173 .value()
174 .attr("href")
175 .filter(|href| is_public_link(href))
176 else {
177 continue;
178 };
179 if !links.iter().any(|known| known == href) {
180 links.push(href.to_owned());
181 }
182 }
183 links
184}
185
186pub fn is_public_link(url: &str) -> bool {
187 let lower = url.to_ascii_lowercase();
188 if !(lower.starts_with("http://") || lower.starts_with("https://")) {
189 return false;
190 }
191 let Some(host) = link_host(url) else {
192 return false;
193 };
194 if host.starts_with('[') || host == "localhost" || !host.contains('.') {
195 return false;
196 }
197 if INTERNAL_HOSTS
198 .iter()
199 .any(|internal| host == *internal || host.ends_with(&format!(".{internal}")))
200 {
201 return false;
202 }
203 host.parse::<Ipv4Addr>().map_or(true, |address| {
204 !(address.is_private()
205 || address.is_loopback()
206 || address.is_link_local()
207 || address.is_unspecified())
208 })
209}
210
211fn link_host(url: &str) -> Option<String> {
212 let (_, rest) = url.split_once("://")?;
213 let authority = rest.split(['/', '?', '#']).next()?;
214 let host_port = authority
215 .rsplit_once('@')
216 .map_or(authority, |(_, host)| host);
217 let host = if host_port.starts_with('[') {
218 host_port
219 } else {
220 host_port.split(':').next()?
221 };
222 let host = host.trim_end_matches('.').to_ascii_lowercase();
223 (!host.is_empty()).then_some(host)
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 const THUMBNAIL: &str =
231 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x";
232
233 fn links(entries: Value) -> String {
234 entries.to_string()
235 }
236
237 #[test]
238 fn public_links_lists_each_external_link_once() {
239 let record = MessageRecord {
240 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(),
241 ..demo_record()
242 };
243 assert_eq!(
244 public_links(&record),
245 ["https://a.example/x", "https://b.example"]
246 );
247 }
248
249 fn demo_record() -> MessageRecord {
250 MessageRecord {
251 conversation_id: "c".to_owned(),
252 message_id: "m".to_owned(),
253 reply_to_id: None,
254 sender_id: None,
255 sender_name: None,
256 created_at: chrono::Utc::now(),
257 edited_at: None,
258 deleted: false,
259 body_html: String::new(),
260 attachments_json: "[]".to_owned(),
261 reactions_json: "[]".to_owned(),
262 mentions_json: "[]".to_owned(),
263 sender_application_id: None,
264 links_json: "[]".to_owned(),
265 subject: None,
266 call_event_json: None,
267 importance: Default::default(),
268 }
269 }
270
271 #[test]
272 fn picks_the_first_public_link_with_a_title() {
273 let preview = select_preview(&links(json!([
274 {"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},
275 {"url": "https://a.example/x", "preview": {}, "previewenabled": true},
276 {"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},
277 {"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},
278 ])))
279 .unwrap();
280 assert_eq!(preview.url, "https://b.example/y");
281 assert_eq!(preview.title.as_deref(), Some("B"));
282 assert_eq!(preview.description.as_deref(), Some("About B"));
283 assert_eq!(preview.domain(), "b.example");
284 }
285
286 #[test]
287 fn an_image_alone_is_enough() {
288 let preview = select_preview(&links(json!([
289 {"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},
290 ])))
291 .unwrap();
292 assert_eq!(preview.title, None);
293 assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL));
294 assert_eq!(
295 (preview.image_width, preview.image_height),
296 (Some(320), Some(160))
297 );
298 }
299
300 #[test]
301 fn reads_the_camel_case_meta_and_null_meta() {
302 let preview = select_preview(&links(json!([
303 {"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},
304 {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
305 ])))
306 .unwrap();
307 assert_eq!(
308 (preview.image_width, preview.image_height),
309 (Some(20), Some(10))
310 );
311 let second = select_preview(&links(json!([
312 {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
313 ])))
314 .unwrap();
315 assert_eq!(second.image_width, None);
316 }
317
318 #[test]
319 fn a_removed_preview_is_not_shown() {
320 assert_eq!(
321 select_preview(&links(json!([
322 {"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false},
323 ]))),
324 None
325 );
326 }
327
328 #[test]
329 fn images_outside_the_preview_service_are_dropped() {
330 assert_eq!(
331 select_preview(&links(json!([
332 {"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}},
333 ]))),
334 None
335 );
336 }
337
338 #[test]
339 fn garbage_and_empty_lists_have_no_preview() {
340 assert_eq!(select_preview("[]"), None);
341 assert_eq!(select_preview(""), None);
342 assert_eq!(select_preview("{}"), None);
343 assert_eq!(select_preview("[{\"url\": 3}]"), None);
344 }
345
346 #[test]
347 fn internal_and_private_hosts_are_skipped() {
348 for url in [
349 "https://contoso.sharepoint.com/a",
350 "https://contoso-my.sharepoint.com/a",
351 "https://onedrive.com/a",
352 "https://1drv.ms/a",
353 "https://teams.microsoft.com/l/x",
354 "https://teams.cloud.microsoft/x",
355 "https://teams.live.com/x",
356 "https://www.office.com/x",
357 "https://m365.microsoft365.com/x",
358 "https://localhost/x",
359 "https://intranet/x",
360 "http://192.168.1.2/x",
361 "http://127.0.0.1:8080/x",
362 "ftp://a.example/x",
363 "mailto:a@b.example",
364 ] {
365 assert!(!is_public_link(url), "{url}");
366 }
367 for url in [
368 "https://github.com/rust-lang/rust",
369 "http://a.example:8080/x",
370 "https://notsharepoint.com/x",
371 "https://user@example.org/x",
372 ] {
373 assert!(is_public_link(url), "{url}");
374 }
375 }
376
377 #[test]
378 fn finds_the_first_public_anchor_in_html() {
379 let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \
380 <a href=\"https://a.example/?q=1&amp;r=2\">a</a> <a href=\"https://b.example\">b</a></p>";
381 assert_eq!(
382 first_public_link(html).as_deref(),
383 Some("https://a.example/?q=1&r=2")
384 );
385 assert_eq!(first_public_link("<p>no link</p>"), None);
386 }
387
388 #[test]
389 fn outgoing_json_reads_back_as_the_same_preview() {
390 let preview = LinkPreview {
391 url: "https://github.com/rust-lang/rust".into(),
392 title: Some("Rust".into()),
393 description: Some("Empowering".into()),
394 image_url: Some(THUMBNAIL.into()),
395 image_width: Some(320),
396 image_height: Some(160),
397 };
398 let json: Value = serde_json::from_str(&preview.links_json()).unwrap();
399 assert_eq!(json[0]["@type"], HYPERLINK_TYPE);
400 assert_eq!(json[0]["itemid"], "0");
401 assert_eq!(json[0]["previewenabled"], true);
402 assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL);
403 assert_eq!(select_preview(&preview.links_json()), Some(preview));
404 }
405
406 #[test]
407 fn info_without_title_or_usable_image_makes_no_preview() {
408 let info = LinkInfo {
409 url: "https://a.example".into(),
410 description: Some("only text".into()),
411 thumbnail: Some("https://evil.example/i.png".into()),
412 ..LinkInfo::default()
413 };
414 assert_eq!(LinkPreview::from_info("https://a.example", &info), None);
415 }
416
417 #[test]
418 fn deleted_messages_show_no_preview() {
419 let record = MessageRecord {
420 deleted: true,
421 links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),
422 ..MessageRecord::default()
423 };
424 assert_eq!(link_preview(&record), None);
425 }
426}