1use std::collections::HashMap;
29
30use html5gum::{DefaultEmitter, Token, Tokenizer};
31use reqwest::Url;
32use tokio::sync::mpsc;
33
34use crate::http;
35use crate::requests::Requests;
36use crate::youtube;
37
38const MAX_HEAD_BYTES: usize = 2 * 1024 * 1024;
42
43const MAX_ABOUT_BYTES: usize = 64 * 1024;
46
47const MAX_IN_FLIGHT: usize = 4;
50const REQUEST_QUEUE: usize = 32;
51
52const TITLE_MAX_CHARS: usize = 200;
55const DESCRIPTION_MAX_CHARS: usize = 300;
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Linked {
60 Page(LinkPreview),
62 Video,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct LinkPreview {
69 pub title: String,
71 pub description: Option<String>,
73 pub image: Option<String>,
76 pub site: String,
78}
79
80fn one_line(text: &str, max_chars: usize) -> Option<String> {
85 if text.contains(char::REPLACEMENT_CHARACTER) {
86 return None;
87 }
88 let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
89 let line = if line.chars().count() > max_chars {
90 let head: String = line.chars().take(max_chars).collect();
91 format!("{}\u{2026}", head.trim_end())
92 } else {
93 line
94 };
95 (!line.is_empty()).then_some(line)
96}
97
98#[derive(Default)]
102struct Said {
103 title: Option<(u8, String)>,
104 description: Option<(u8, String)>,
105 image: Option<(u8, String)>,
106}
107
108impl Said {
109 fn keep(slot: &mut Option<(u8, String)>, rank: u8, value: String) {
111 if slot.as_ref().is_none_or(|(kept, _)| rank < *kept) {
112 *slot = Some((rank, value));
113 }
114 }
115
116 fn meta(&mut self, key: &str, content: String) {
118 match key {
119 "og:title" => Self::keep(&mut self.title, 0, content),
120 "twitter:title" => Self::keep(&mut self.title, 1, content),
121 "og:description" => Self::keep(&mut self.description, 0, content),
122 "twitter:description" => Self::keep(&mut self.description, 1, content),
123 "description" => Self::keep(&mut self.description, 2, content),
124 "og:image:secure_url" => Self::keep(&mut self.image, 0, content),
125 "og:image" | "og:image:url" => Self::keep(&mut self.image, 1, content),
126 "twitter:image" | "twitter:image:src" => Self::keep(&mut self.image, 2, content),
127 _ => {}
128 }
129 }
130}
131
132pub fn parse(html: &str, url: &Url) -> Option<LinkPreview> {
136 let mut said = Said::default();
137 let mut title: Option<String> = None;
139
140 let mut emitter = DefaultEmitter::default();
143 emitter.naively_switch_states(true);
144 for Ok(token) in Tokenizer::new_with_emitter(html, emitter) {
145 match token {
146 Token::StartTag(tag) => match tag.name.as_slice() {
147 b"meta" => {
148 let value =
149 |name: &str| tag.attributes.get(name.as_bytes()).map(|value| String::from_utf8_lossy(value).into_owned());
150 if let (Some(key), Some(content)) = (value("property").or_else(|| value("name")), value("content")) {
153 said.meta(key.trim().to_ascii_lowercase().as_str(), content);
154 }
155 }
156 b"title" => title = Some(String::new()),
157 b"body" => break,
158 _ => {}
159 },
160 Token::String(text) => {
161 if let Some(title) = &mut title {
162 title.push_str(&String::from_utf8_lossy(&text));
163 }
164 }
165 Token::EndTag(tag) => match tag.name.as_slice() {
166 b"title" => {
167 if let Some(title) = title.take() {
168 Said::keep(&mut said.title, 2, title);
169 }
170 }
171 b"head" => break,
172 _ => {}
173 },
174 _ => {}
175 }
176 }
177
178 let host = url.host_str().unwrap_or_default();
179 Some(LinkPreview {
180 title: said.title.and_then(|(_, title)| one_line(&title, TITLE_MAX_CHARS))?,
181 description: said.description.and_then(|(_, description)| one_line(&description, DESCRIPTION_MAX_CHARS)),
182 image: said
185 .image
186 .and_then(|(_, image)| url.join(image.trim()).ok())
187 .filter(|image| image.scheme() == "https")
188 .map(String::from),
189 site: host.strip_prefix("www.").unwrap_or(host).to_string(),
190 })
191}
192
193pub async fn fetch(http: reqwest::Client, url: String) -> Result<Linked, String> {
196 if let Some(video) = youtube::video_at(&url) {
197 let answer = http::get(&http, &video.about(), MAX_ABOUT_BYTES).await?;
198 let title = youtube::title(&answer).and_then(|title| one_line(&title, TITLE_MAX_CHARS));
199 let title = title.ok_or_else(|| "YouTube does not say what it is called".to_string())?;
200 return Ok(Linked::Page(LinkPreview { title, description: None, image: None, site: "youtube.com".to_string() }));
201 }
202 match http::get_page_head(&http, &url, MAX_HEAD_BYTES).await? {
203 http::Linked::Video => Ok(Linked::Video),
204 http::Linked::Page(head) => parse(&String::from_utf8_lossy(&head.bytes), &head.url)
205 .map(Linked::Page)
206 .ok_or_else(|| "it gives itself no title".to_string()),
207 }
208}
209
210#[derive(Debug, PartialEq, Eq)]
212pub enum PreviewState<'a> {
213 Ready(&'a LinkPreview),
214 Video,
216 Loading,
218 Nothing,
221}
222
223pub struct PreviewStore {
226 known: HashMap<String, Option<Linked>>,
228 requests: Requests<String>,
230}
231
232impl PreviewStore {
233 pub fn new() -> (Self, mpsc::Receiver<String>) {
235 let (requests, receiver) = Requests::new(REQUEST_QUEUE, MAX_IN_FLIGHT);
236 (Self { known: HashMap::new(), requests }, receiver)
237 }
238
239 pub fn get(&self, url: &str) -> PreviewState<'_> {
242 match self.known.get(url) {
243 Some(Some(Linked::Page(preview))) => PreviewState::Ready(preview),
244 Some(Some(Linked::Video)) => PreviewState::Video,
245 Some(None) => PreviewState::Nothing,
246 None => {
247 self.requests.ask(&url.to_string());
248 PreviewState::Loading
249 }
250 }
251 }
252
253 pub fn begin(&mut self, url: &String) -> bool {
257 let wanted = !self.known.contains_key(url);
258 self.requests.begin(url, wanted)
259 }
260
261 pub fn finish(&mut self, url: String, found: Option<Linked>) {
264 self.requests.end(&url);
265 self.known.insert(url, found);
266 }
267}
268
269#[cfg(test)]
270mod tests {
271 use super::{LinkPreview, Linked, PreviewState, PreviewStore, parse};
272 use reqwest::Url;
273
274 fn read(html: &str) -> Option<LinkPreview> {
275 parse(html, &Url::parse("https://www.example.com/a/page?x=1").unwrap())
276 }
277
278 #[test]
279 fn a_page_is_shown_as_it_says_it_wants_to_be_shared() {
280 let preview = read(
281 r#"<!doctype html><html><head>
282 <meta charset="utf-8">
283 <title>Lastbook</title>
284 <meta name="description" content="For search engines.">
285 <meta property="og:title" content="Lastbook — Everything you need to survive & rebuild society.">
286 <meta property="og:description" content="Free, open-source survival library.
287 Works offline.">
288 <meta property="og:image" content="https://cdn.example.com/card.png">
289 </head><body><h1>Not this</h1></body></html>"#,
290 )
291 .unwrap();
292
293 assert_eq!(
294 preview,
295 LinkPreview {
296 title: "Lastbook — Everything you need to survive & rebuild society.".into(),
297 description: Some("Free, open-source survival library. Works offline.".into()),
298 image: Some("https://cdn.example.com/card.png".into()),
299 site: "example.com".into(),
300 }
301 );
302 }
303
304 #[test]
305 fn what_is_meant_for_sharing_is_taken_before_what_is_not_wherever_it_stands() {
306 let preview = read(
307 r#"<head>
308 <meta name="twitter:title" content="For Twitter">
309 <meta name="twitter:image" content="/twitter.png">
310 <meta property="og:title" content="For sharing">
311 <meta property="og:title" content="For sharing, again">
312 <title>For the tab</title>
313 <meta name="twitter:description" content="About it, for Twitter">
314 </head>"#,
315 )
316 .unwrap();
317
318 assert_eq!(preview.title, "For sharing", "Open Graph first, and the first of it");
319 assert_eq!(preview.description.as_deref(), Some("About it, for Twitter"));
320 assert_eq!(preview.image.as_deref(), Some("https://www.example.com/twitter.png"), "relative to the page");
321 }
322
323 #[test]
324 fn a_page_with_only_a_title_is_called_by_it() {
325 let preview = read("<html><head><title>\n Just a\n title </title></head></html>").unwrap();
326 assert_eq!(
327 preview,
328 LinkPreview { title: "Just a title".into(), description: None, image: None, site: "example.com".into() }
329 );
330
331 assert_eq!(read(r#"<meta name="OG:Title" content="Mixed up">"#).unwrap().title, "Mixed up");
334 }
335
336 #[test]
337 fn a_page_that_gives_itself_no_title_has_no_preview() {
338 assert_eq!(read(""), None);
339 assert_eq!(read("<html><head><title> </title></head></html>"), None);
340 assert_eq!(read(r#"<head><meta property="og:description" content="About nothing"></head>"#), None);
341 assert_eq!(read("plain text, not a page at all"), None);
342 }
343
344 #[test]
345 fn only_the_head_is_read_and_what_is_written_in_a_script_is_not_a_tag() {
346 let preview = read(
347 r#"<head>
348 <script>var page = '<title>From a script</title><meta property="og:title" content="From a script">';</script>
349 <title>The page</title>
350 </head>
351 <body><svg><title>A drawing</title></svg><meta property="og:title" content="From the body"></body>"#,
352 )
353 .unwrap();
354 assert_eq!(preview.title, "The page");
355 }
356
357 #[test]
358 fn a_picture_that_would_not_be_fetched_is_left_out() {
359 let picture =
360 |address: &str| read(&format!(r#"<title>t</title><meta property="og:image" content="{address}">"#)).unwrap().image;
361 assert_eq!(picture("http://example.com/card.png"), None, "only https is fetched");
362 assert_eq!(picture("data:image/png;base64,AAAA"), None);
363 assert_eq!(picture("//cdn.example.com/card.png").as_deref(), Some("https://cdn.example.com/card.png"));
364 assert_eq!(picture("card.png").as_deref(), Some("https://www.example.com/a/card.png"));
365 }
366
367 #[test]
368 fn long_texts_are_cut_and_garbled_ones_dropped() {
369 let long = "word ".repeat(200);
370 let preview = read(&format!(r#"<title>{long}</title><meta name="description" content="{long}">"#)).unwrap();
371 assert_eq!(preview.title.chars().count(), 200);
372 assert!(preview.title.ends_with("word…"), "{}", preview.title);
373 assert!(preview.description.unwrap().chars().count() <= 301);
374
375 let garbled = String::from_utf8_lossy(b"<title>caf\xe9</title><meta name=description content='fine'>").into_owned();
377 assert_eq!(read(&garbled), None, "no title that can be read");
378 }
379
380 #[test]
381 fn a_page_is_asked_about_once_whatever_it_answers() {
382 let (mut store, mut requests) = PreviewStore::new();
383 let (answers, silent) = ("https://example.com/answers".to_string(), "https://example.com/silent".to_string());
384
385 for _ in 0..3 {
386 assert_eq!(store.get(&answers), PreviewState::Loading);
387 }
388 assert_eq!(requests.try_recv().ok().as_ref(), Some(&answers));
389 assert!(requests.try_recv().is_err(), "asked once");
390 assert!(store.begin(&answers));
391 assert!(!store.begin(&answers), "on its way");
392
393 let preview = LinkPreview { title: "Answers".into(), description: None, image: None, site: "example.com".into() };
394 store.finish(answers.clone(), Some(Linked::Page(preview.clone())));
395 assert_eq!(store.get(&answers), PreviewState::Ready(&preview));
396
397 let video = "https://example.com/video".to_string();
399 assert!(store.begin(&video));
400 store.finish(video.clone(), Some(Linked::Video));
401 assert_eq!(store.get(&video), PreviewState::Video);
402
403 assert_eq!(store.get(&silent), PreviewState::Loading);
404 assert!(store.begin(&silent));
405 store.finish(silent.clone(), None);
406 assert_eq!(store.get(&silent), PreviewState::Nothing);
407 assert!(!store.begin(&silent), "not asked again");
408 let _ = requests.try_recv();
409 assert!(requests.try_recv().is_err());
410 }
411}