Skip to main content

cosmic_applet_avestruz/
previews.rs

1// SPDX-License-Identifier: MIT
2
3//! What a web page says of itself, for showing under a note that links to
4//! it: its title, a few words about it, and a picture.
5//!
6//! Pages say this in the `meta` tags of their head, most of them as Open
7//! Graph (`og:title`, `og:description`, `og:image`), which is what other
8//! clients and every chat program read. Only the head is fetched and read,
9//! with a tokenizer: nothing of the page is run, laid out or kept.
10//!
11//! A link that answers as a video, where a page was asked for, is one the
12//! address did not give away: the answer is [`Linked::Video`], and the
13//! row offers to play it (see [`crate::video`]).
14//!
15//! A YouTube video is asked what it is called the short way (see
16//! [`Video::about`](crate::youtube::Video::about)): its page says so too,
17//! most of a megabyte in.
18//!
19//! A view asks the [`PreviewStore`] for the preview of an address, as it
20//! asks for pictures (see [`Requests`]): the app hears of it as a
21//! [`Message::LoadPreview`](crate::messages::Message::LoadPreview). A page
22//! is asked once in a run, whatever it answers. There is no disk cache.
23//!
24//! Addresses come from whoever wrote a note. They are fetched as everything
25//! is (see [`crate::http`]): the page's server sees the request, as the
26//! server of a note's picture does.
27
28use 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
38/// How much of a page is read looking for the end of its head. Most heads
39/// end within a few thousand bytes; some sites put a megabyte of script
40/// before what they say of themselves.
41const MAX_HEAD_BYTES: usize = 2 * 1024 * 1024;
42
43/// How much of what YouTube answers about a video is read: it is a few
44/// hundred bytes.
45const MAX_ABOUT_BYTES: usize = 64 * 1024;
46
47/// How many pages may be on their way at once, and how many requests may
48/// wait between a view asking and the app answering.
49const MAX_IN_FLIGHT: usize = 4;
50const REQUEST_QUEUE: usize = 32;
51
52/// How many characters of a title and of a description are kept: more than
53/// a preview has room to show.
54const TITLE_MAX_CHARS: usize = 200;
55const DESCRIPTION_MAX_CHARS: usize = 300;
56
57/// What a link a note took for a page turned out to be.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Linked {
60    /// A page, and what it says of itself.
61    Page(LinkPreview),
62    /// A video: that is what its server calls it.
63    Video,
64}
65
66/// What a web page says of itself.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct LinkPreview {
69    /// What it is called.
70    pub title: String,
71    /// A few words about it, if it has any.
72    pub description: Option<String>,
73    /// The address of the picture it is shared with, if it has one that can
74    /// be fetched.
75    pub image: Option<String>,
76    /// The site it is on: its host, without a leading `www.`.
77    pub site: String,
78}
79
80/// `text` as one line: runs of blank space and line breaks made one space,
81/// none at either end, and `max_chars` characters at most. `None` if that
82/// leaves nothing, or if the text was not read as it was written: a page
83/// that is not in UTF-8 says nothing rather than something garbled.
84fn 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/// What the head of a page says of the page, as it was found: each thing
99/// said the way most trusted to be meant for sharing. A lower `rank` is
100/// more trusted, and among equals the first one said stands.
101#[derive(Default)]
102struct Said {
103    title: Option<(u8, String)>,
104    description: Option<(u8, String)>,
105    image: Option<(u8, String)>,
106}
107
108impl Said {
109    /// Keep `value` in `slot` if nothing as trusted is there.
110    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    /// Take in a `meta` tag that names `key` and says `content`.
117    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
132/// What the page at `url` says of itself in `html`, which is its head, or
133/// starts with it. `None` if it gives itself no title: there is nothing to
134/// call it by.
135pub fn parse(html: &str, url: &Url) -> Option<LinkPreview> {
136    let mut said = Said::default();
137    // The text between `<title>` and `</title>`, while between them.
138    let mut title: Option<String> = None;
139
140    // Told to treat what is in a `title` or a `script` as text, which is
141    // what a browser does: a tag written inside one is not a tag.
142    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                    // Open Graph says `property`, the rest say `name`, and
151                    // pages mix the two up.
152                    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        // Relative to the page, as pages write it; and fetched only if it
183        // is where anything is fetched from.
184        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
193/// Fetch the head of the page at `url` and read what the page says of
194/// itself; or hear that it is a video, and fetch none of it.
195pub 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/// What the store has to say about the preview of a page.
211#[derive(Debug, PartialEq, Eq)]
212pub enum PreviewState<'a> {
213    Ready(&'a LinkPreview),
214    /// Not a page at all, but a video.
215    Video,
216    /// Asked for, or about to be.
217    Loading,
218    /// The page could not be fetched or says nothing of itself, and won't
219    /// be asked again this run.
220    Nothing,
221}
222
223/// What the pages asked about so far say of themselves, by address. See the
224/// [module docs](self).
225pub struct PreviewStore {
226    /// The links that answered, and (`None`) those that had nothing to say.
227    known: HashMap<String, Option<Linked>>,
228    /// The asking for those not known.
229    requests: Requests<String>,
230}
231
232impl PreviewStore {
233    /// An empty store, and the receiving end of its requests.
234    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    /// What the page at `url` says of itself, if that is known; otherwise
240    /// ask for it.
241    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    /// A request reached the app. Returns whether to start fetching the
254    /// page: not if it is known or on its way already, and not while as
255    /// many as may be are.
256    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    /// The fetch of `url` ended: with what was found there, or with
262    /// nothing to show for it.
263    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 &mdash; Everything you need to survive &amp; 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        // Pages name what they say with `name` where `property` belongs,
332        // and in whatever case.
333        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        // Read as UTF-8 from a page written as something else.
376        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        // A link that turned out to be a video is known as one.
398        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}