Skip to main content

cosmic_applet_avestruz/nostr/
content.rs

1// SPDX-License-Identifier: MIT
2
3//! What a note says, taken apart for showing: plain text, links, mentions of
4//! people, hashtags, the images and the videos it carries, the notes it
5//! quotes, and the web page it is shown a preview of.
6//!
7//! Images, videos and quoted notes are set aside from the text: what stands
8//! for them in it is an address, and they are shown under it for what they
9//! are.
10//!
11//! What a link is is told by how its address ends, and by what the note
12//! says of it in a NIP-92 `imeta` tag (see [`Attachment`]): a link the note
13//! calls a video is one, whatever its address looks like. A link to a
14//! YouTube video is a video too (see [`crate::youtube`]), though what is
15//! at its address is a page.
16//!
17//! The text is split by `nostr`'s own parser, so what counts as a URL, a
18//! `nostr:` URI or a hashtag is what the rest of the ecosystem agrees on.
19//!
20//! Before that, what the note marks as Markdown is taken for what it is
21//! (see [`markdown`]): the text comes here as runs, each in one style,
22//! and each run is read for its links, mentions and hashtags. A note that
23//! marks nothing is one run, and is read as it always was.
24
25use nostr_sdk::prelude::{EventId, Nip21, NostrParser, PublicKey, RelayUrl, ToBech32, Token, Url};
26
27use crate::http;
28use crate::nostr::markdown::{self, Block, Run, Style};
29use crate::nostr::outbox::Whereabouts;
30use crate::youtube;
31
32/// How much of a note a feed row shows, in characters, until it is asked
33/// for the rest. A long note is cut here, and what it says in full is
34/// kept beside what is shown of it (see [`Content::whole`]).
35pub const FEED_NOTE_MAX_CHARS: usize = 600;
36
37/// How long a link's label may be before it is cut, as in Vega.
38const LINK_LABEL_MAX_CHARS: usize = 50;
39
40/// How many characters of a `note1…`/`naddr1…` stand for the whole of it.
41const REFERENCE_CHARS: usize = 12;
42
43/// How many of a note's images a feed row shows.
44const MAX_NOTE_IMAGES: usize = 4;
45
46/// How many of a note's videos a feed row gives room to.
47const MAX_NOTE_VIDEOS: usize = 4;
48
49/// How many of the notes a note quotes are shown under it.
50pub const MAX_NOTE_QUOTES: usize = 3;
51
52/// How many notes deep quoting is shown: a note in a note in the note of a
53/// row, and no further. A note quoted deeper than that shows as a link:
54/// quoting has no end of its own.
55pub const QUOTE_DEPTH: usize = 2;
56
57/// The file extensions of the pictures that can be decoded and shown.
58const IMAGE_EXTENSIONS: [&str; 6] = ["jpg", "jpeg", "png", "gif", "webp", "bmp"];
59
60/// The file extensions of the videos that are played in their row: files
61/// of pictures and sound, whatever is in them. Whether this machine can
62/// decode one is found out when it is played.
63const VIDEO_EXTENSIONS: [&str; 7] = ["mp4", "webm", "mov", "mkv", "m4v", "ogv", "avi"];
64
65/// The file extensions of what is plainly not a web page: nothing with a
66/// title to preview it by, and not worth asking.
67const FILE_EXTENSIONS: [&str; 16] =
68    ["svg", "avif", "heic", "tiff", "m3u8", "mp3", "m4a", "ogg", "opus", "wav", "flac", "pdf", "zip", "gz", "json", "txt"];
69
70/// How wide a mention is counted as, when counting what a note shows: about
71/// what a name takes, whoever it turns out to be.
72const MENTION_CHARS: usize = 16;
73
74/// How many characters of text four of code take the room of: its
75/// letters are all as wide as the widest.
76const CODE_CHARS_PER_FOUR: usize = 5;
77
78/// One piece of a note, in reading order.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Segment {
81    /// Plain text, line breaks included.
82    Text(String),
83    /// Text the note marks as something else than plain: bold, slanted,
84    /// struck out, code, or quoted (see [`markdown`]). Without its marks.
85    Styled { text: String, style: Style },
86    /// A web link: where it goes, and the shorter text that stands for it.
87    Link { url: String, label: String },
88    /// Someone mentioned by key (`nostr:npub1…`, `nostr:nprofile1…`). Shown
89    /// by name once their profile is known.
90    Mention(PublicKey),
91    /// A hashtag, without its `#`.
92    Hashtag(String),
93    /// An article or another addressable event (`naddr1…`), as the short
94    /// form of its address. Not something this client opens yet.
95    Reference(String),
96    /// What stands apart from the text, between what is before it and
97    /// what is after: lines of code, a rule, a table, whose cells are
98    /// pieces like these (see [`markdown`]).
99    Block(Block<Vec<Segment>>),
100}
101
102impl Segment {
103    /// What this piece says as plain words, `named` saying who a mention
104    /// is of. What stands apart has a space on either side.
105    pub fn words(&self, named: &dyn Fn(&PublicKey) -> String) -> String {
106        match self {
107            Self::Text(text) | Self::Styled { text, .. } => text.clone(),
108            Self::Link { label, .. } | Self::Reference(label) => label.clone(),
109            Self::Mention(person) => named(person),
110            Self::Hashtag(tag) => format!("#{tag}"),
111            Self::Block(Block::Code(code)) => format!(" {code} "),
112            Self::Block(Block::Rule) => " ".to_string(),
113            Self::Block(Block::Table(table)) => {
114                let cells =
115                    table.rows.iter().flatten().map(|cell| cell.iter().map(|piece| piece.words(named)).collect::<String>());
116                format!(" {} ", cells.collect::<Vec<_>>().join(" "))
117            }
118        }
119    }
120}
121
122/// Every piece of `segments` that stands in a line of text: those in the
123/// cells of its tables too, each where it stands.
124pub fn inline(segments: &[Segment]) -> impl Iterator<Item = &Segment> {
125    segments.iter().flat_map(|segment| -> Box<dyn Iterator<Item = &Segment>> {
126        match segment {
127            Segment::Block(Block::Table(table)) => Box::new(table.rows.iter().flatten().flatten()),
128            other => Box::new(std::iter::once(other)),
129        }
130    })
131}
132
133/// Another note a note quotes: one it names by its address in the text
134/// (`nostr:note1…`, `nevent1…`). Shown under the text, as the note it is
135/// when that is at hand, and as a link to it when it isn't.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Quote {
138    /// Which note.
139    pub id: EventId,
140    /// Who wrote it and a relay that has it, when the address says: what
141    /// finds a note that is not at hand.
142    pub author: Option<PublicKey>,
143    pub relay: Option<RelayUrl>,
144    /// The short form of its address, which stands for it where the note
145    /// itself can't.
146    pub label: String,
147}
148
149impl Quote {
150    /// Where the note is, as far as its address says, for looking where
151    /// the account's own relays don't have it.
152    pub fn whereabouts(&self) -> Whereabouts {
153        Whereabouts { author: self.author, relay: self.relay.clone() }
154    }
155}
156
157/// An image a note carries: a link to a picture, shown under the text
158/// rather than in it.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct NoteImage {
161    pub url: String,
162    /// The short text that stands for the address, if the picture can't be
163    /// shown.
164    pub label: String,
165    /// Its size in pixels, when the note says (NIP-92 `imeta`). Lets the row
166    /// keep room for it before it has loaded.
167    pub size: Option<(u32, u32)>,
168}
169
170/// A video a note carries: a link to one, played under the text rather
171/// than followed from it.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct NoteVideo {
174    pub url: String,
175    /// The short text that stands for the address, beside its play button.
176    pub label: String,
177    /// Its size in pixels, when the note says: the proportions of the room
178    /// it is given.
179    pub size: Option<(u32, u32)>,
180    /// The pictures that may stand for it until it plays, the likeliest
181    /// first: the one the note names, or those YouTube keeps. The first
182    /// that can be had does.
183    pub posters: Vec<String>,
184    /// It is a page that shows a video (YouTube's), not a file: what it
185    /// is called is the page's to say, and what there is to play of it
186    /// has to be found.
187    pub page: bool,
188}
189
190/// What a note says of something it links to, in a NIP-92 `imeta` tag:
191/// `["imeta", "url https://…", "m video/mp4", "dim 1920x1080", …]`.
192#[derive(Debug, Clone, Default, PartialEq, Eq)]
193pub struct Attachment {
194    /// The address it is said of, as it stands in the note.
195    pub url: String,
196    /// What kind of thing is there, as a media type (`m`).
197    pub kind: Option<String>,
198    /// Its size in pixels (`dim`).
199    pub size: Option<(u32, u32)>,
200    /// A picture that stands for it (`image`, or else `thumb`), if it is
201    /// one that would be fetched.
202    pub picture: Option<String>,
203}
204
205/// The text of a note that was cut, all of it: what its row shows once
206/// it is asked for the rest.
207#[derive(Debug, Clone, Default, PartialEq, Eq)]
208pub struct Whole {
209    pub segments: Vec<Segment>,
210    /// As [`Content::line_chars`], of all the text.
211    pub line_chars: Vec<usize>,
212}
213
214/// A note's content, parsed, and cut to what a feed row shows.
215#[derive(Debug, Clone, Default, PartialEq, Eq)]
216pub struct Content {
217    /// The text, cut if it is long.
218    pub segments: Vec<Segment>,
219    /// All of the text, if `segments` is cut. What is set aside from the
220    /// text is the same either way: none of it is cut.
221    pub whole: Option<Whole>,
222    /// The images, in the order they were linked. Their addresses are not in
223    /// `segments`.
224    pub images: Vec<NoteImage>,
225    /// The videos, likewise.
226    pub videos: Vec<NoteVideo>,
227    /// The notes it quotes, in the order they were named, each once. Their
228    /// addresses are not in `segments` either.
229    pub quotes: Vec<Quote>,
230    /// How many characters each line of the shown text has, links and
231    /// mentions counted as shown. What a row's height is estimated from
232    /// before it has been laid out.
233    pub line_chars: Vec<usize>,
234    /// The web page shown a preview of under the note: the last one it
235    /// links to, as in Jumble. Its link stays where it is in the text.
236    pub preview: Option<String>,
237    /// The first address it links to that is not a picture's: a video's,
238    /// or anything else on the web. What the key that plays a note's
239    /// video is for (see [`crate::handlers::keys`]): a picture is shown
240    /// where it is, and has no use for a key.
241    pub first_link: Option<String>,
242}
243
244/// The text that stands for a link: its host and path, without the scheme,
245/// the query or a leading `www.`, cut if it is still long.
246pub(crate) fn link_label(url: &Url) -> String {
247    let host = url.host_str().unwrap_or_default();
248    let host = host.strip_prefix("www.").unwrap_or(host);
249    let path = if url.path() == "/" { "" } else { url.path() };
250    let label = format!("{host}{path}");
251    match label.char_indices().nth(LINK_LABEL_MAX_CHARS) {
252        Some(_) => {
253            let head: String = label.chars().take(LINK_LABEL_MAX_CHARS - 1).collect();
254            format!("{head}\u{2026}")
255        }
256        None => label,
257    }
258}
259
260/// What stands for a link the note gives a `label` of its own: the
261/// label, and after it where the link goes, unless the label says so
262/// itself. A label can say anything, and a click on it opens the address:
263/// which site that is on is not left to the label. With no label, the
264/// address made short, as for any link.
265fn labelled(url: &Url, label: Option<&str>) -> String {
266    let Some(label) = label.map(str::trim).filter(|label| !label.is_empty()) else {
267        return link_label(url);
268    };
269    let host = url.host_str().unwrap_or_default();
270    let host = host.strip_prefix("www.").unwrap_or(host);
271    if label.to_lowercase().contains(&host.to_lowercase()) { label.to_string() } else { format!("{label} ({host})") }
272}
273
274/// Whether the path of `url` ends in one of `extensions`.
275fn has_extension(url: &Url, extensions: &[&str]) -> bool {
276    url.path().rsplit_once('.').is_some_and(|(_, extension)| extensions.iter().any(|known| extension.eq_ignore_ascii_case(known)))
277}
278
279/// Whether `url` is a picture this client can fetch and show: an `https`
280/// address (nothing else is fetched) whose path ends like a picture's.
281fn is_image(url: &Url) -> bool {
282    url.scheme() == "https" && has_extension(url, &IMAGE_EXTENSIONS)
283}
284
285/// Whether `url` is a video this client can fetch and play: an `https`
286/// address (nothing else is fetched) whose path ends like a video's, that
287/// the note calls one (`said`), or that is a YouTube video's.
288fn is_video(url: &Url, said: Option<&Attachment>) -> bool {
289    let called_one = said.and_then(|said| said.kind.as_deref()).is_some_and(http::is_video);
290    url.scheme() == "https" && (has_extension(url, &VIDEO_EXTENSIONS) || called_one || youtube::video(url).is_some())
291}
292
293/// Whether `url` may be a web page that can be asked what it says of
294/// itself: an `https` address (nothing else is fetched) whose path doesn't
295/// end like a file's.
296fn may_be_page(url: &Url) -> bool {
297    url.scheme() == "https"
298        && ![&IMAGE_EXTENSIONS[..], &VIDEO_EXTENSIONS, &FILE_EXTENSIONS].iter().any(|extensions| has_extension(url, extensions))
299}
300
301/// The first characters of a bech32 address, standing for all of it.
302fn short_reference(bech32: &str) -> String {
303    let head: String = bech32.chars().take(REFERENCE_CHARS).collect();
304    format!("{head}\u{2026}")
305}
306
307/// The note `id` as one quoted, written by `author` and to be found at
308/// `relay`, as far as its address says.
309fn quote(id: EventId, author: Option<PublicKey>, relay: Option<RelayUrl>) -> Quote {
310    // The note's address, as everywhere else: not the start of the longer
311    // `nevent1…`, which is the same note with hints.
312    let Ok(note) = id.to_bech32();
313    Quote { id, author, relay, label: short_reference(&note) }
314}
315
316/// What a `nostr:` URI stands for in a note.
317enum Named {
318    /// Something that shows in the text, where it was written.
319    Inline(Segment),
320    /// Another note, which shows under the text.
321    Quote(Quote),
322}
323
324/// What the `nostr:` URI `uri` stands for.
325fn named(uri: Nip21) -> Named {
326    match uri {
327        Nip21::Pubkey(public_key) => Named::Inline(Segment::Mention(public_key)),
328        Nip21::Profile(profile) => Named::Inline(Segment::Mention(profile.public_key)),
329        Nip21::EventId(id) => Named::Quote(quote(id, None, None)),
330        Nip21::Event(event) => Named::Quote(quote(event.event_id, event.author, event.relays.into_iter().next())),
331        Nip21::Coordinate(coordinate) => Named::Inline(Segment::Reference(
332            coordinate.to_bech32().map_or_else(|_| "naddr1\u{2026}".to_string(), |naddr| short_reference(&naddr)),
333        )),
334    }
335}
336
337/// Builds a [`Content`], counting what it shows and stopping at a limit.
338struct Builder<'a> {
339    content: Content,
340    /// What the note says of what it links to.
341    attached: &'a [Attachment],
342    /// Characters still allowed.
343    room: usize,
344    /// The limit was reached: nothing more is added.
345    full: bool,
346    /// Something was just set aside. The blank space after it closes the
347    /// gap it left, rather than adding to the blank space before it.
348    gap: bool,
349}
350
351impl<'a> Builder<'a> {
352    fn new(max_chars: usize, attached: &'a [Attachment]) -> Self {
353        Self {
354            content: Content { line_chars: vec![0], ..Content::default() },
355            attached,
356            room: max_chars,
357            full: false,
358            gap: false,
359        }
360    }
361
362    /// Whether `space`, the blank space or the line break that follows
363    /// something set aside, would only repeat what stands before it: the
364    /// text so far ends the same way, or there is none.
365    fn repeats(&self, space: char) -> bool {
366        match self.content.segments.last() {
367            Some(Segment::Text(before) | Segment::Styled { text: before, .. }) => before.ends_with(space),
368            Some(Segment::Block(_)) | None => true,
369            Some(_) => false,
370        }
371    }
372
373    /// What the note says of `url`, if it says anything.
374    fn said_of(&self, url: &Url) -> Option<&'a Attachment> {
375        self.attached.iter().find(|said| said.url == url.as_str())
376    }
377
378    /// Set an image aside. Images take none of the room text does, so a
379    /// picture at the end of a long note is still shown.
380    fn image(&mut self, url: &Url) {
381        if self.content.images.len() < MAX_NOTE_IMAGES {
382            let size = self.said_of(url).and_then(|said| said.size);
383            self.content.images.push(NoteImage { url: url.to_string(), label: link_label(url), size });
384        }
385    }
386
387    /// Set a video aside, as an image is.
388    fn video(&mut self, url: &Url) {
389        if self.content.videos.len() >= MAX_NOTE_VIDEOS {
390            return;
391        }
392        let (said, hosted) = (self.said_of(url), youtube::video(url));
393        let (url, label) = (url.to_string(), link_label(url));
394        self.content.videos.push(match hosted {
395            // What YouTube shows is YouTube's to describe.
396            Some(hosted) => NoteVideo { url, label, size: hosted.size, posters: hosted.posters(), page: true },
397            None => NoteVideo {
398                url,
399                label,
400                size: said.and_then(|said| said.size),
401                posters: said.and_then(|said| said.picture.clone()).into_iter().collect(),
402                page: false,
403            },
404        });
405    }
406
407    /// Set a quoted note aside, unless it is already. Like images, quotes
408    /// take none of the room text does.
409    fn quote(&mut self, quote: Quote) {
410        if !self.content.quotes.iter().any(|known| known.id == quote.id) {
411            self.content.quotes.push(quote);
412        }
413    }
414
415    /// The content, without the blank space the address of an image or of
416    /// a quoted note left at either end of the text.
417    fn finish(mut self) -> Content {
418        if let Some(Segment::Text(first)) = self.content.segments.first_mut() {
419            *first = first.trim_start().to_string();
420        }
421        if let Some(Segment::Text(last)) = self.content.segments.last_mut() {
422            last.truncate(last.trim_end().len());
423        }
424        self.content.segments.retain(|segment| !matches!(segment, Segment::Text(text) if text.is_empty()));
425        while self.content.line_chars.len() > 1 && self.content.line_chars.last() == Some(&0) {
426            self.content.line_chars.pop();
427        }
428        while self.content.line_chars.len() > 1 && self.content.line_chars.first() == Some(&0) {
429            self.content.line_chars.remove(0);
430        }
431        self.content
432    }
433
434    /// Count `chars` more characters on the current line.
435    fn count(&mut self, chars: usize) {
436        if let Some(line) = self.content.line_chars.last_mut() {
437            *line += chars;
438        }
439        self.room = self.room.saturating_sub(chars);
440    }
441
442    /// Add text in `style` to the last segment if that is text in the
443    /// same, or start one.
444    fn append(&mut self, text: &str, style: Style) {
445        match self.content.segments.last_mut() {
446            Some(Segment::Text(last)) if style.is_plain() => last.push_str(text),
447            Some(Segment::Styled { text: last, style: same }) if *same == style => last.push_str(text),
448            _ if style.is_plain() => self.content.segments.push(Segment::Text(text.to_string())),
449            _ => self.content.segments.push(Segment::Styled { text: text.to_string(), style }),
450        }
451    }
452
453    /// Mark the note as cut: an ellipsis, and nothing after it.
454    fn cut(&mut self) {
455        if let Some(Segment::Text(last)) = self.content.segments.last_mut() {
456            last.truncate(last.trim_end().len());
457        }
458        // Under a block, it is a line of its own.
459        if matches!(self.content.segments.last(), Some(Segment::Block(_))) {
460            self.count(1);
461        }
462        self.append("\u{2026}", Style::default());
463        self.full = true;
464    }
465
466    /// What one run of the note comes to.
467    fn run(&mut self, run: Run) {
468        match run {
469            Run::Text { text, style } => self.read(&text, style),
470            Run::Code { .. } if self.full => {}
471            Run::Code { text, style } => {
472                self.gap = false;
473                self.text(&text, style);
474            }
475            Run::Link { url, label } => self.link(url, Some(&label), Style::default()),
476            Run::Block(block) => self.block(block),
477        }
478    }
479
480    /// What stands apart from the text: a rule; lines of code, as many as
481    /// there is room for; a table, whole or not at all.
482    fn block(&mut self, block: Block<Vec<Run>>) {
483        self.gap = false;
484        let chars = |runs: &[Run]| -> usize {
485            runs.iter()
486                .map(|run| match run {
487                    Run::Text { text, .. } | Run::Code { text, .. } => text.chars().count(),
488                    Run::Link { label, .. } => label.chars().count(),
489                    Run::Block(_) => 0,
490                })
491                .sum()
492        };
493        match block {
494            Block::Rule if !self.full => self.stand_apart(Block::Rule),
495            Block::Code(code) if !self.full => {
496                let wanted = code.chars().count();
497                let fits: String = code.chars().take(self.room).collect();
498                let fits = fits.trim_end();
499                if !fits.is_empty() {
500                    self.stand_apart(Block::Code(fits.to_string()));
501                }
502                if wanted > self.room {
503                    self.cut();
504                }
505                self.room = self.room.saturating_sub(wanted);
506            }
507            Block::Rule | Block::Code(_) => {}
508            Block::Table(table) => {
509                let wanted: usize = table.rows.iter().flatten().map(|cell| chars(cell)).sum();
510                let fits = !self.full && wanted <= self.room;
511                if !fits && !self.full {
512                    self.cut();
513                }
514                // Its cells are read as the text is, for what is in them
515                // and what they set aside, with all the room they want:
516                // whether it fits was settled above.
517                let room = std::mem::replace(&mut self.room, usize::MAX);
518                let block = Block::Table(table).map(|cell| self.cell(cell));
519                self.room = room.saturating_sub(usize::MAX - self.room);
520                if fits {
521                    self.stand_apart(block);
522                }
523            }
524        }
525    }
526
527    /// The pieces the runs of one cell of a table come to. Past the cut,
528    /// none, and only what they set aside.
529    fn cell(&mut self, runs: Vec<Run>) -> Vec<Segment> {
530        let text = std::mem::take(&mut self.content.segments);
531        let lines = std::mem::replace(&mut self.content.line_chars, vec![0]);
532        self.gap = false;
533        for run in runs {
534            self.run(run);
535        }
536        self.gap = false;
537        self.content.line_chars = lines;
538        let mut cell = std::mem::replace(&mut self.content.segments, text);
539        if let Some(Segment::Text(first)) = cell.first_mut() {
540            *first = first.trim_start().to_string();
541        }
542        if let Some(Segment::Text(last)) = cell.last_mut() {
543            last.truncate(last.trim_end().len());
544        }
545        cell.retain(|piece| !matches!(piece, Segment::Text(text) if text.is_empty()));
546        cell
547    }
548
549    /// Set `block` down after the text so far, which ends where it
550    /// starts: the blank space before it is left out, and what follows it
551    /// starts a line of its own.
552    fn stand_apart(&mut self, block: Block<Vec<Segment>>) {
553        while let Some(Segment::Text(last) | Segment::Styled { text: last, .. }) = self.content.segments.last_mut() {
554            last.truncate(last.trim_end().len());
555            if !last.is_empty() {
556                break;
557            }
558            self.content.segments.pop();
559        }
560        while self.content.line_chars.len() > 1 && self.content.line_chars.last() == Some(&0) {
561            self.content.line_chars.pop();
562        }
563        self.content.segments.push(Segment::Block(block));
564        if self.content.line_chars.last().is_some_and(|chars| *chars > 0) {
565            self.content.line_chars.push(0);
566        }
567    }
568
569    /// Add text in `style`, as much of it as there is room for.
570    fn text(&mut self, text: &str, style: Style) {
571        for (index, line) in text.split('\n').enumerate() {
572            if index > 0 {
573                self.append("\n", style);
574                self.content.line_chars.push(0);
575            }
576            let chars = line.chars().count();
577            if chars > self.room {
578                let fits: String = line.chars().take(self.room).collect();
579                self.append(&fits, style);
580                self.count(self.room);
581                self.cut();
582                return;
583            }
584            self.append(line, style);
585            // Code is wider than it is long.
586            self.count(if style.code { (chars * CODE_CHARS_PER_FOUR).div_ceil(4) } else { chars });
587        }
588    }
589
590    /// Read a run of the note's text, set in `style`, for what is in it:
591    /// links, the people and the notes it names, hashtags, and the text
592    /// between them.
593    fn read(&mut self, text: &str, style: Style) {
594        for token in NostrParser::new().parse(text) {
595            let token = match token {
596                Token::Url(url) => {
597                    self.link(url, None, style);
598                    continue;
599                }
600                token => token,
601            };
602            // What is set aside leaves its place in the text empty: the
603            // space or the line breaks on either side of it are left once,
604            // not twice.
605            let was_gap = std::mem::take(&mut self.gap);
606            match token {
607                Token::Nostr(uri) => match named(uri) {
608                    Named::Quote(quote) => {
609                        self.quote(quote);
610                        self.gap = true;
611                    }
612                    // Past the cut, only what is set aside is still looked
613                    // for: images, videos, quoted notes, and the page to
614                    // preview.
615                    Named::Inline(_) if self.full => {}
616                    Named::Inline(segment) => {
617                        let chars = match &segment {
618                            Segment::Reference(label) => label.chars().count(),
619                            _ => MENTION_CHARS,
620                        };
621                        self.whole(segment, chars);
622                    }
623                },
624                _ if self.full => {}
625                Token::Whitespace if was_gap && self.repeats(' ') => self.gap = true,
626                Token::LineBreak if was_gap && self.repeats('\n') => self.gap = true,
627                Token::Text(text) => self.text(text, style),
628                Token::Whitespace => self.text(" ", style),
629                Token::LineBreak => self.text("\n", style),
630                Token::Hashtag(tag) => {
631                    let tag = tag.trim_start_matches('#');
632                    self.whole(Segment::Hashtag(tag.to_string()), tag.chars().count() + 1);
633                }
634                // Links were seen to above.
635                Token::Url(_) => {}
636            }
637        }
638    }
639
640    /// A link: to a video or a picture, which is set aside, or to
641    /// anywhere else, which stands in the text as its address made short,
642    /// or as the `label` the note gives it. Where it stands among text in
643    /// `style`, an address that is not followed is set so too.
644    fn link(&mut self, url: Url, label: Option<&str>, style: Style) {
645        let video = is_video(&url, self.said_of(&url));
646        // The last page linked to is the one previewed, wherever in the
647        // note it is.
648        if !video && may_be_page(&url) {
649            self.content.preview = Some(url.to_string());
650        }
651        // The first link is the first of all of the note, past where its
652        // text is cut too: a video, or what a link in the text may be.
653        if self.content.first_link.is_none() && (video || (!is_image(&url) && matches!(url.scheme(), "http" | "https"))) {
654            self.content.first_link = Some(url.to_string());
655        }
656        self.gap = false;
657        if video {
658            self.video(&url);
659            self.gap = true;
660        } else if is_image(&url) {
661            self.image(&url);
662            self.gap = true;
663        } else if self.full {
664        } else if matches!(url.scheme(), "http" | "https") {
665            let label = labelled(&url, label);
666            let chars = label.chars().count();
667            self.whole(Segment::Link { url: url.to_string(), label }, chars);
668        } else {
669            // Other schemes are not followed, so they are not dressed as links.
670            self.text(url.as_str(), style);
671        }
672    }
673
674    /// Add a segment that is shown whole or not at all: a link cut in half
675    /// would go somewhere else.
676    fn whole(&mut self, segment: Segment, chars: usize) {
677        if chars > self.room {
678            self.cut();
679        } else {
680            self.content.segments.push(segment);
681            self.count(chars);
682        }
683    }
684}
685
686/// Parse a note's `content`, cutting its text at `max_chars` characters of
687/// what it shows. Of a note that is cut, all of the text is kept as well.
688pub fn parse(content: &str, max_chars: usize) -> Content {
689    parse_attached(content, max_chars, &[])
690}
691
692/// As [`parse`], of a note that says `attached` of what it links to.
693pub fn parse_attached(content: &str, max_chars: usize, attached: &[Attachment]) -> Content {
694    let (mut cut, was_cut) = parse_up_to(content, max_chars, attached);
695    if was_cut {
696        // Read once more without a limit, for the text alone: what is
697        // set aside is found past the cut the first time already.
698        let (whole, _) = parse_up_to(content, usize::MAX, attached);
699        cut.whole = Some(Whole { segments: whole.segments, line_chars: whole.line_chars });
700    }
701    cut
702}
703
704/// `content`, with at most `max_chars` characters of its text, and
705/// whether there was more.
706fn parse_up_to(content: &str, max_chars: usize, attached: &[Attachment]) -> (Content, bool) {
707    let mut builder = Builder::new(max_chars, attached);
708    for run in markdown::runs(content.trim()) {
709        builder.run(run);
710    }
711    let was_cut = builder.full;
712    (builder.finish(), was_cut)
713}
714
715/// What an `imeta` tag's `dim` field says: `"1920x1080"`.
716fn parse_dimensions(dim: &str) -> Option<(u32, u32)> {
717    let (width, height) = dim.split_once('x')?;
718    Some((width.parse().ok()?, height.parse().ok()?)).filter(|(width, height)| *width > 0 && *height > 0)
719}
720
721/// What one NIP-92 `imeta` tag says, and of which address. `None` if it is
722/// not such a tag, or names no address.
723pub fn imeta(tag: &[String]) -> Option<Attachment> {
724    let mut fields = tag.iter();
725    if fields.next().map(String::as_str) != Some("imeta") {
726        return None;
727    }
728    let https = |value: &str| Url::parse(value.trim()).ok().filter(|url| url.scheme() == "https").map(String::from);
729    let (mut url, mut said, mut thumb) = (None, Attachment::default(), None);
730    for field in fields {
731        match field.split_once(' ') {
732            Some(("url", value)) => url = Url::parse(value.trim()).ok(),
733            Some(("m", value)) => said.kind = Some(value.trim().to_string()),
734            Some(("dim", value)) => said.size = parse_dimensions(value.trim()),
735            Some(("image", value)) => said.picture = https(value),
736            Some(("thumb", value)) => thumb = https(value),
737            _ => {}
738        }
739    }
740    Some(Attachment { url: url?.to_string(), picture: said.picture.or(thumb), ..said })
741}
742
743impl Content {
744    /// The text and how long its lines are: all of it if `in_full`, and
745    /// as a row first shows it otherwise.
746    pub fn text(&self, in_full: bool) -> (&[Segment], &[usize]) {
747        match &self.whole {
748            Some(whole) if in_full => (&whole.segments, &whole.line_chars),
749            _ => (&self.segments, &self.line_chars),
750        }
751    }
752
753    /// The people mentioned, in order, possibly more than once: in all of
754    /// the text, so that the rest of a note that was cut names them too
755    /// once it is shown.
756    pub fn mentions(&self) -> impl Iterator<Item = PublicKey> + '_ {
757        inline(self.text(true).0).filter_map(|segment| match segment {
758            Segment::Mention(public_key) => Some(*public_key),
759            _ => None,
760        })
761    }
762}
763
764#[cfg(test)]
765mod tests {
766    use super::{Attachment, Content, FEED_NOTE_MAX_CHARS, NoteImage, NoteVideo, Quote, Segment, imeta, parse, parse_attached};
767    use crate::nostr::markdown::{Block, Style};
768    use nostr_sdk::prelude::{EventId, Keys, Nip19Event, Nip19Profile, RelayUrl, ToBech32};
769
770    fn text(text: &str) -> Segment {
771        Segment::Text(text.to_string())
772    }
773
774    fn link(url: &str, label: &str) -> Segment {
775        Segment::Link { url: url.to_string(), label: label.to_string() }
776    }
777
778    fn segments(content: &str) -> Vec<Segment> {
779        parse(content, 10_000).segments
780    }
781
782    #[test]
783    fn plain_text_stays_one_piece_with_its_line_breaks() {
784        let content = parse("  gm nostr\n\nhow is everyone?  ", 10_000);
785        assert_eq!(content.segments, [text("gm nostr\n\nhow is everyone?")]);
786        assert_eq!(content.line_chars, [8, 0, 16]);
787    }
788
789    #[test]
790    fn a_link_is_labelled_by_host_and_path_and_keeps_its_address() {
791        assert_eq!(
792            segments("read https://www.example.com/a/page?utm=1, then reply"),
793            [text("read "), link("https://www.example.com/a/page?utm=1", "example.com/a/page"), text(", then reply")]
794        );
795        assert_eq!(segments("https://example.com"), [link("https://example.com/", "example.com")]);
796    }
797
798    /// `text` as the note marks it: bold, slanted, or code.
799    fn styled(text: &str, style: Style) -> Segment {
800        Segment::Styled { text: text.to_string(), style }
801    }
802
803    const BOLD: Style = Style { bold: true, italic: false, strike: false, code: false, quiet: false, heading: 0 };
804    const ITALIC: Style = Style { italic: true, bold: false, ..BOLD };
805    const CODE: Style = Style { code: true, bold: false, ..BOLD };
806
807    #[test]
808    fn what_a_note_marks_is_set_so_and_read_for_links_and_hashtags_like_the_rest() {
809        assert_eq!(
810            segments("**gm** #nostr, *see https://example.com/a now* and **#bitcoin**"),
811            [
812                styled("gm", BOLD),
813                text(" "),
814                Segment::Hashtag("nostr".into()),
815                text(", "),
816                styled("see ", ITALIC),
817                link("https://example.com/a", "example.com/a"),
818                styled(" now", ITALIC),
819                text(" and "),
820                Segment::Hashtag("bitcoin".into()),
821            ]
822        );
823    }
824
825    #[test]
826    fn code_is_shown_as_written_and_read_for_nothing() {
827        let content = parse("run `curl https://example.com/x #now` first", 10_000);
828        assert_eq!(content.segments, [text("run "), styled("curl https://example.com/x #now", CODE), text(" first")]);
829        assert_eq!((content.preview, content.first_link), (None, None), "what is in code is no link");
830        // Code is counted wider than it is long: its letters are.
831        assert_eq!(parse("`abcdefgh`", 10_000).line_chars, [10]);
832    }
833
834    #[test]
835    fn a_link_the_note_labels_says_its_label_and_where_it_goes() {
836        let labelled = |written: &str| match segments(written).as_slice() {
837            [Segment::Link { label, .. }] => label.clone(),
838            other => panic!("not one link: {other:?}"),
839        };
840        // Where it goes is said beside what the note calls it,
841        assert_eq!(labelled("[the docs](https://docs.rs/nostr)"), "the docs (docs.rs)");
842        // whatever the note calls it,
843        assert_eq!(labelled("[paypal.com](https://evil.example/paypal.com)"), "paypal.com (evil.example)");
844        // unless the label says so itself.
845        assert_eq!(labelled("[docs.rs/nostr](https://www.docs.rs/nostr)"), "docs.rs/nostr");
846        // One with no label is as any other link.
847        assert_eq!(labelled("[](https://example.com/a/page)"), "example.com/a/page");
848
849        // It is a link like any other: the page to preview, the first link.
850        let content = parse("see [this](https://example.com/page)", 10_000);
851        assert_eq!(content.preview.as_deref(), Some("https://example.com/page"));
852        assert_eq!(content.first_link.as_deref(), Some("https://example.com/page"));
853        // And a picture written as one is set aside as any other.
854        let content = parse("look ![a cat](https://example.com/cat.png) there", 10_000);
855        assert_eq!(content.segments, [text("look there")]);
856        assert_eq!(content.images.iter().map(|image| image.url.as_str()).collect::<Vec<_>>(), ["https://example.com/cat.png"]);
857    }
858
859    #[test]
860    fn a_note_cut_inside_what_it_marks_is_cut_as_any_other() {
861        let content = parse(&format!("**{}**", "bold ".repeat(40).trim_end()), 12);
862        assert_eq!(content.segments, [styled("bold bold bo", BOLD), text("\u{2026}")]);
863        assert!(content.whole.is_some());
864    }
865
866    #[test]
867    fn a_table_stands_apart_and_its_cells_are_read_as_the_text_is() {
868        let friend = Keys::generate().public_key();
869        let written = format!(
870            "Who:\n\n| Who | Where |\n|---|---|\n| nostr:{} | #nostr at https://example.com/page |\n| a cat | https://example.com/cat.png |\n\nso",
871            friend.to_bech32().unwrap()
872        );
873        let content = parse(&written, 10_000);
874        let [Segment::Text(before), Segment::Block(Block::Table(table)), Segment::Text(after)] = content.segments.as_slice()
875        else {
876            panic!("text, a table, text: {:?}", content.segments);
877        };
878        assert_eq!((before.as_str(), after.as_str()), ("Who:", "so"), "no line break is left on either side");
879        assert_eq!(
880            table.rows,
881            [
882                vec![vec![text("Who")], vec![text("Where")]],
883                vec![
884                    vec![Segment::Mention(friend)],
885                    vec![Segment::Hashtag("nostr".into()), text(" at "), link("https://example.com/page", "example.com/page")]
886                ],
887                // A picture in a cell is set aside, as anywhere.
888                vec![vec![text("a cat")], vec![]],
889            ]
890        );
891        assert_eq!(content.images.iter().map(|image| image.url.as_str()).collect::<Vec<_>>(), ["https://example.com/cat.png"]);
892        assert_eq!(content.preview.as_deref(), Some("https://example.com/page"));
893        assert_eq!(content.mentions().collect::<Vec<_>>(), [friend], "who is named in a cell is named");
894        // The lines of text are the two around it: its own height is its own.
895        assert_eq!(content.line_chars, [4, 2]);
896    }
897
898    #[test]
899    fn a_table_is_shown_whole_or_not_at_all_and_code_as_far_as_there_is_room() {
900        let table = "| a | b |\n|---|---|\n| one | two |\n| three | https://example.com/cat.png |";
901        let content = parse(&format!("see\n{table}"), 12);
902        assert_eq!(content.segments, [text("see\u{2026}")]);
903        assert_eq!(content.images.len(), 1, "what a cell sets aside is found past the cut");
904        let whole = content.whole.expect("it was cut");
905        assert!(matches!(whole.segments.as_slice(), [Segment::Text(_), Segment::Block(Block::Table(_))]), "{:?}", whole.segments);
906
907        let content = parse("```\nlet a = 1;\nlet b = 2;\n```", 12);
908        assert_eq!(content.segments, [Segment::Block(Block::Code("let a = 1;\nl".into())), text("\u{2026}")]);
909        assert!(content.whole.is_some());
910    }
911
912    #[test]
913    fn what_stands_apart_reads_as_words_where_there_is_one_line_for_a_note() {
914        let content = parse("Dams\n|Where|Count|\n|-|-|\n|U.S.|92,000+|\n---\n```\ncode\n```", 10_000);
915        let said: String = content.segments.iter().map(|piece| piece.words(&|_| String::new())).collect();
916        assert_eq!(said.split_whitespace().collect::<Vec<_>>().join(" "), "Dams Where Count U.S. 92,000+ code");
917    }
918
919    #[test]
920    fn a_long_link_gets_a_short_label() {
921        let url = format!("https://example.com/{}", "x".repeat(100));
922        let parsed = segments(&url);
923        let [Segment::Link { url: target, label }] = &parsed[..] else {
924            panic!("one link");
925        };
926        assert_eq!(target, &url, "the address is whole");
927        assert_eq!(label.chars().count(), 50);
928        assert!(label.ends_with('…'));
929    }
930
931    #[test]
932    fn only_web_links_are_links() {
933        // Nothing but http(s) is ever handed to the system to open.
934        for content in ["file:///etc/passwd", "javascript://alert(1)", "ftp://example.com/file"] {
935            assert!(
936                segments(content).iter().all(|segment| matches!(segment, Segment::Text(_))),
937                "{content} must stay text: {:?}",
938                segments(content)
939            );
940        }
941    }
942
943    #[test]
944    fn people_are_mentioned_by_key_whichever_way_the_key_is_written() {
945        let key = Keys::generate().public_key();
946        let npub = key.to_bech32().unwrap();
947        assert_eq!(segments(&format!("hey nostr:{npub}!")), [text("hey "), Segment::Mention(key), text("!")]);
948
949        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
950        let nprofile = Nip19Profile::new(key, [relay]).to_bech32().unwrap();
951        let content = parse(&format!("nostr:{nprofile}"), 10_000);
952        assert_eq!(content.segments, [Segment::Mention(key)]);
953        assert_eq!(content.mentions().collect::<Vec<_>>(), [key]);
954    }
955
956    #[test]
957    fn another_note_is_referred_to_by_the_start_of_its_address() {
958        let id = EventId::from_byte_array([7; 32]);
959        let note = id.to_bech32().unwrap();
960        let label = format!("{}…", &note[..12]);
961        let content = parse(&format!("look at this\n\nnostr:{note}"), 10_000);
962        assert_eq!(content.quotes, [Quote { id, author: None, relay: None, label: label.clone() }]);
963        // Set aside: its address is not in the text, and leaves no gap.
964        assert_eq!((content.segments, content.line_chars), (vec![text("look at this")], vec![12]));
965
966        // The longer address is the same note, with who wrote it and where
967        // it is.
968        let author = Keys::generate().public_key();
969        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
970        let nevent = Nip19Event::new(id).author(author).relays([relay.clone()]).to_bech32().unwrap();
971        let quoted = Quote { id, author: Some(author), relay: Some(relay), label };
972        assert_eq!(parse(&format!("nostr:{nevent}"), 10_000).quotes, [quoted.clone()]);
973
974        // Named twice, it is quoted once, as it was first named; and one
975        // named past where the note is cut is quoted all the same.
976        let other = EventId::from_byte_array([8; 32]);
977        let long = format!("{} nostr:{nevent} nostr:{note} nostr:{}", "word ".repeat(50), other.to_bech32().unwrap());
978        let content = parse(&long, 20);
979        assert_eq!(content.segments, [text("word word word word…")]);
980        assert_eq!(content.quotes.iter().map(|quote| quote.id).collect::<Vec<_>>(), [id, other]);
981        assert_eq!(content.quotes[0], quoted);
982    }
983
984    #[test]
985    fn hashtags_lose_their_hash() {
986        assert_eq!(segments("#nostr is #fun"), [Segment::Hashtag("nostr".into()), text(" is "), Segment::Hashtag("fun".into())]);
987    }
988
989    #[test]
990    fn a_long_note_is_cut_at_the_limit_and_marked() {
991        let content = parse("one two three four five", 9);
992        assert_eq!(content.segments, [text("one two t…")]);
993
994        // Cut on a word boundary, the space before the mark goes too.
995        assert_eq!(parse("one two three", 8).segments, [text("one two…")]);
996
997        // Under the limit, nothing is marked.
998        assert_eq!(parse("one two", 7).segments, [text("one two")]);
999    }
1000
1001    #[test]
1002    fn a_note_that_is_cut_keeps_all_of_its_text_beside_what_is_shown() {
1003        let someone = Keys::generate().public_key();
1004        let said = format!("one two three\nfour https://example.com/page nostr:{} five", someone.to_bech32().unwrap());
1005        let content = parse(&said, 9);
1006        assert_eq!(content.segments, [text("one two t…")]);
1007        let whole = content.whole.clone().expect("it was cut");
1008        let all = parse(&said, 10_000);
1009        assert_eq!((&whole.segments, &whole.line_chars), (&all.segments, &all.line_chars));
1010        assert_eq!(whole.line_chars.len(), 2);
1011
1012        // Either is there to show, and the one who is named past the cut
1013        // is among those mentioned.
1014        assert_eq!(content.text(false), (&content.segments[..], &content.line_chars[..]));
1015        assert_eq!(content.text(true), (&whole.segments[..], &whole.line_chars[..]));
1016        assert_eq!(content.mentions().collect::<Vec<_>>(), [someone]);
1017
1018        // A note that is all there has nothing beside it, and shows the
1019        // same either way.
1020        assert_eq!(all.whole, None);
1021        assert_eq!(all.text(true), all.text(false));
1022        // To the last character, and no further.
1023        assert_eq!(parse("one two", 7).whole, None);
1024        assert!(parse("one two", 6).whole.is_some());
1025
1026        // What is set aside is the same, cut or not.
1027        let with_picture = format!("{} https://example.com/end.png", "word ".repeat(50));
1028        let cut = parse(&with_picture, 20);
1029        assert_eq!(image_urls(&cut), ["https://example.com/end.png"]);
1030        assert_eq!(cut.whole.map(|whole| whole.segments), Some(parse(&with_picture, 10_000).segments));
1031    }
1032
1033    #[test]
1034    fn a_link_is_shown_whole_or_not_at_all() {
1035        // "see " is 4 characters; the label "example.com/page" is 16.
1036        let content = parse("see https://example.com/page now", 10);
1037        assert_eq!(content.segments, [text("see…")]);
1038
1039        // With room for it, the link is there, and the cut comes after it.
1040        let content = parse("see https://example.com/page now", 20);
1041        assert_eq!(content.segments, [text("see "), link("https://example.com/page", "example.com/page"), text("…")]);
1042        assert_eq!(parse("see https://example.com/page now", 22).segments.last(), Some(&text(" n…")));
1043    }
1044
1045    #[test]
1046    fn an_empty_note_has_one_empty_line() {
1047        assert_eq!(parse("   ", 100), Content { line_chars: vec![0], ..Content::default() });
1048    }
1049
1050    fn image_urls(content: &Content) -> Vec<&str> {
1051        content.images.iter().map(|image| image.url.as_str()).collect()
1052    }
1053
1054    #[test]
1055    fn a_picture_is_set_aside_and_leaves_no_gap_in_the_text() {
1056        let content = parse("look at this\n\nhttps://example.com/cat.JPG?size=large\n", 10_000);
1057        assert_eq!(content.segments, [text("look at this")]);
1058        assert_eq!(content.line_chars, [12]);
1059        assert_eq!(
1060            content.images,
1061            [NoteImage { url: "https://example.com/cat.JPG?size=large".into(), label: "example.com/cat.JPG".into(), size: None }]
1062        );
1063
1064        // In the middle of the text, it leaves the space or the line
1065        // breaks around it once.
1066        let between = |content: &str| (parse(content, 10_000).segments, parse(content, 10_000).line_chars);
1067        assert_eq!(between("before https://example.com/cat.png after"), (vec![text("before after")], vec![12]));
1068        assert_eq!(between("before\nhttps://example.com/cat.png\nafter"), (vec![text("before\nafter")], vec![6, 5]));
1069        assert_eq!(between("before\n\nhttps://example.com/cat.png\n\nafter"), (vec![text("before\n\nafter")], vec![6, 0, 5]));
1070        // A line break is not blank space, and stays.
1071        assert_eq!(between("before https://example.com/cat.png\nafter"), (vec![text("before \nafter")], vec![7, 5]));
1072        let note = EventId::from_byte_array([7; 32]).to_bech32().unwrap();
1073        assert_eq!(between(&format!("see nostr:{note} and https://example.com/a.png then")).0, [text("see and then")]);
1074
1075        // A picture first leaves no blank line above the text either.
1076        let content = parse("https://example.com/cat.png\ncaption", 10_000);
1077        assert_eq!((content.segments, content.line_chars), (vec![text("caption")], vec![7]));
1078
1079        // A note that is only a picture has no text at all.
1080        let content = parse("https://example.com/cat.png", 10_000);
1081        assert!(content.segments.is_empty());
1082        assert_eq!(image_urls(&content), ["https://example.com/cat.png"]);
1083    }
1084
1085    #[test]
1086    fn only_what_can_be_fetched_and_decoded_is_a_picture() {
1087        // Not https: never fetched, so it stays a link.
1088        assert!(matches!(&segments("http://example.com/cat.png")[..], [Segment::Link { .. }]));
1089        // Not a format that is decoded.
1090        for url in ["https://example.com/song.mp3", "https://example.com/drawing.svg", "https://example.com/page"] {
1091            let content = parse(url, 10_000);
1092            assert!(content.images.is_empty(), "{url}");
1093            assert!(matches!(&content.segments[..], [Segment::Link { .. }]), "{url}");
1094        }
1095    }
1096
1097    #[test]
1098    fn a_picture_after_the_cut_is_still_shown_and_only_so_many_are() {
1099        let note = format!("{} https://example.com/end.png", "word ".repeat(50));
1100        let content = parse(&note, 20);
1101        assert_eq!(content.segments, [text("word word word word…")]);
1102        assert_eq!(image_urls(&content), ["https://example.com/end.png"]);
1103
1104        let many: String = (0..6).map(|n| format!("https://example.com/{n}.png ")).collect();
1105        assert_eq!(parse(&many, 10_000).images.len(), 4);
1106    }
1107
1108    #[test]
1109    fn the_last_page_a_note_links_to_is_the_one_previewed() {
1110        let preview = |content: &str| parse(content, 10_000).preview;
1111        assert_eq!(preview("no links here"), None);
1112        assert_eq!(
1113            preview("first https://example.com/one then https://example.org/two?x=1 and a word").as_deref(),
1114            Some("https://example.org/two?x=1")
1115        );
1116        // Its link stays in the text.
1117        assert!(matches!(&segments("see https://example.com/one")[..], [Segment::Text(_), Segment::Link { .. }]));
1118
1119        // What is not fetched, and what is plainly a file, is not a page.
1120        assert_eq!(preview("http://example.com/plain"), None);
1121        assert_eq!(preview("https://example.com/cat.png https://example.com/clip.MP4 https://example.com/paper.pdf"), None);
1122        assert_eq!(preview("https://example.com/page https://example.com/cat.png").as_deref(), Some("https://example.com/page"));
1123
1124        // A page linked to past where the note is cut is still previewed.
1125        let long = format!("{} https://example.com/at-the-end", "word ".repeat(50));
1126        let content = parse(&long, 20);
1127        assert_eq!(content.segments, [text("word word word word…")]);
1128        assert_eq!(content.preview.as_deref(), Some("https://example.com/at-the-end"));
1129    }
1130
1131    fn tag(fields: &[&str]) -> Vec<String> {
1132        fields.iter().map(|field| (*field).to_string()).collect()
1133    }
1134
1135    #[test]
1136    fn the_first_link_of_a_note_is_its_first_that_is_no_picture() {
1137        let first = |said: &str| parse(said, FEED_NOTE_MAX_CHARS).first_link;
1138        let (picture, video, page) = ("https://example.com/a.jpg", "https://example.com/b.mp4", "https://example.com/read");
1139        assert_eq!(first(&format!("{picture} {video} {page}")).as_deref(), Some(video));
1140        assert_eq!(first(&format!("{picture} {page} {video}")).as_deref(), Some(page));
1141        assert_eq!(first(&format!("only {picture}")), None);
1142        assert_eq!(first("only words, and ftp://example.com/not-followed"), None);
1143        // What is not a page to preview is a link all the same.
1144        assert_eq!(first("https://example.com/paper.pdf").as_deref(), Some("https://example.com/paper.pdf"));
1145        // Past where the text is cut, it is still the note's first.
1146        let long = format!("{} {page}", "word ".repeat(FEED_NOTE_MAX_CHARS));
1147        assert_eq!(first(&long).as_deref(), Some(page));
1148    }
1149
1150    #[test]
1151    fn imeta_tags_say_what_a_link_is() {
1152        let said = imeta(&tag(&[
1153            "imeta",
1154            "url https://example.com/clip",
1155            "m video/mp4",
1156            "dim 1920x1080",
1157            "thumb https://example.com/small.jpg",
1158            "image https://example.com/poster.jpg",
1159            "blurhash eVF$^OI:${M{o#*0-nNFxakD",
1160        ]))
1161        .unwrap();
1162        assert_eq!(
1163            said,
1164            Attachment {
1165                url: "https://example.com/clip".into(),
1166                kind: Some("video/mp4".into()),
1167                size: Some((1920, 1080)),
1168                picture: Some("https://example.com/poster.jpg".into()),
1169            }
1170        );
1171
1172        let of = |fields: &[&str]| imeta(&tag(fields));
1173        let bare = Attachment { url: "https://example.com/cat.png".into(), ..Attachment::default() };
1174        assert_eq!(of(&["imeta", "url https://example.com/cat.png"]), Some(bare.clone()), "only what it says");
1175        assert_eq!(of(&["imeta", "url https://example.com/cat.png", "dim 0x800"]), Some(bare.clone()));
1176        assert_eq!(of(&["imeta", "url https://example.com/cat.png", "dim wide"]), Some(bare.clone()));
1177        // The smaller picture stands in where there is no other, and one
1178        // that would not be fetched is not kept.
1179        let pictured = |fields: &[&str]| of(fields).unwrap().picture;
1180        assert_eq!(
1181            pictured(&["imeta", "url https://example.com/a", "thumb https://example.com/small.jpg"]).as_deref(),
1182            Some("https://example.com/small.jpg")
1183        );
1184        assert_eq!(pictured(&["imeta", "url https://example.com/a", "image http://example.com/poster.jpg"]), None);
1185        assert_eq!(of(&["imeta", "m video/mp4", "dim 1x1"]), None, "of no address");
1186        assert_eq!(of(&["e", "url https://example.com/cat.png", "dim 1x1"]), None, "not an imeta tag");
1187    }
1188
1189    #[test]
1190    fn imeta_tags_give_pictures_their_size() {
1191        let known = imeta(&tag(&["imeta", "url https://example.com/cat.png", "m image/png", "dim 1200x800"])).unwrap();
1192        let content = parse_attached("https://example.com/cat.png https://example.com/dog.png", 100, &[known]);
1193        assert_eq!(content.images[0].size, Some((1200, 800)));
1194        assert_eq!(content.images[1].size, None);
1195    }
1196
1197    #[test]
1198    fn a_video_is_set_aside_as_a_picture_is() {
1199        let content = parse("watch this\n\nhttps://example.com/clip.MP4?download=1\n\nand say what you think", 10_000);
1200        assert_eq!(content.segments, [text("watch this\n\nand say what you think")]);
1201        assert_eq!(
1202            content.videos,
1203            [NoteVideo {
1204                url: "https://example.com/clip.MP4?download=1".into(),
1205                label: "example.com/clip.MP4".into(),
1206                size: None,
1207                posters: Vec::new(),
1208                page: false
1209            }]
1210        );
1211        // It is nothing else as well: no picture, and no page to preview.
1212        assert!(content.images.is_empty());
1213        assert_eq!(content.preview, None);
1214
1215        for played in ["mp4", "webm", "mov", "mkv", "m4v", "ogv", "avi"] {
1216            assert_eq!(parse(&format!("https://example.com/clip.{played}"), 100).videos.len(), 1, "{played}");
1217        }
1218        // Not https: never fetched, so it stays a link. Sound alone, and a
1219        // list of parts, are not played either.
1220        for link in ["http://example.com/clip.mp4", "https://example.com/song.mp3", "https://example.com/live.m3u8"] {
1221            let content = parse(link, 100);
1222            assert!(content.videos.is_empty(), "{link}");
1223            assert!(matches!(&content.segments[..], [Segment::Link { .. }]), "{link}");
1224        }
1225
1226        // One past the cut is still given its room, and only so many are.
1227        let long = format!("{} https://example.com/end.webm", "word ".repeat(50));
1228        let content = parse(&long, 20);
1229        assert_eq!(content.segments, [text("word word word word…")]);
1230        assert_eq!(content.videos.len(), 1);
1231        let many: String = (0..6).map(|n| format!("https://example.com/{n}.mp4 ")).collect();
1232        assert_eq!(parse(&many, 10_000).videos.len(), 4);
1233    }
1234
1235    #[test]
1236    fn a_youtube_link_is_a_video_and_no_page_to_preview() {
1237        let content = parse("worth an evening\nhttps://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt\nall of it", 10_000);
1238        assert_eq!(content.segments, [text("worth an evening\nall of it")]);
1239        assert_eq!(
1240            content.videos,
1241            [NoteVideo {
1242                // As it was written: that is what opens in the browser.
1243                url: "https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt".into(),
1244                label: "youtu.be/aqz-KE-bpKQ".into(),
1245                size: None,
1246                posters: vec![
1247                    "https://i.ytimg.com/vi/aqz-KE-bpKQ/maxresdefault.jpg".into(),
1248                    "https://i.ytimg.com/vi/aqz-KE-bpKQ/mqdefault.jpg".into()
1249                ],
1250                page: true,
1251            }]
1252        );
1253        assert_eq!(content.preview, None);
1254
1255        // A short is given the room of something upright.
1256        let short = parse("https://www.youtube.com/shorts/aqz-KE-bpKQ", 100);
1257        assert_eq!(short.videos[0].size, Some((1080, 1920)));
1258        // What on YouTube is not a video stays a link, and a page.
1259        let channel = parse("https://www.youtube.com/@BlenderOfficial", 100);
1260        assert!(channel.videos.is_empty());
1261        assert_eq!(channel.preview.as_deref(), Some("https://www.youtube.com/@BlenderOfficial"));
1262    }
1263
1264    #[test]
1265    fn a_link_the_note_calls_a_video_is_one_whatever_its_address() {
1266        let said = |fields: &[&str]| imeta(&tag(fields)).unwrap();
1267        let address = "https://blossom.example.com/b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553";
1268        let note = format!("look {address} at this https://example.com/page");
1269
1270        // Left to its address, it is a link like any other, and the page
1271        // after it is the one previewed.
1272        let plain = parse(&note, 10_000);
1273        assert!(plain.videos.is_empty());
1274        assert!(matches!(&plain.segments[..], [Segment::Text(_), Segment::Link { .. }, Segment::Text(_), Segment::Link { .. }]));
1275
1276        let attached = [said(&[
1277            "imeta",
1278            &format!("url {address}"),
1279            "m Video/Quicktime",
1280            "dim 1080x1920",
1281            "image https://blossom.example.com/poster.jpg",
1282        ])];
1283        let content = parse_attached(&note, 10_000, &attached);
1284        assert_eq!(
1285            content.videos,
1286            [NoteVideo {
1287                url: address.into(),
1288                label: "blossom.example.com/b1674191a88ec5cdd733e4240a818…".into(),
1289                size: Some((1080, 1920)),
1290                posters: vec!["https://blossom.example.com/poster.jpg".into()],
1291                page: false,
1292            }]
1293        );
1294        assert_eq!(content.segments, [text("look at this "), link("https://example.com/page", "example.com/page")]);
1295        assert_eq!(content.preview.as_deref(), Some("https://example.com/page"));
1296        // As the last link of a note, it is not taken for a page.
1297        assert_eq!(parse_attached(address, 100, &attached).preview, None);
1298
1299        // A video by its address has what the note says of it too.
1300        let sized = [said(&["imeta", "url https://example.com/clip.mp4", "dim 640x360"])];
1301        assert_eq!(parse_attached("https://example.com/clip.mp4", 100, &sized).videos[0].size, Some((640, 360)));
1302        // What the note calls something else stays what its address makes
1303        // it; and http is not fetched, whatever it is called.
1304        let other = [said(&["imeta", &format!("url {address}"), "m application/pdf"])];
1305        assert!(parse_attached(address, 100, &other).videos.is_empty());
1306        let insecure = [said(&["imeta", "url http://example.com/clip", "m video/mp4"])];
1307        assert!(parse_attached("http://example.com/clip", 100, &insecure).videos.is_empty());
1308    }
1309}