Skip to main content

cosmic_applet_avestruz/nostr/
article.rs

1// SPDX-License-Identifier: MIT
2
3//! Long-form writing (NIP-23, kind 30023): what an article says of itself
4//! in its tags, and how long it takes to read.
5//!
6//! An article is no note. It has a title, a line that sums it up, a
7//! picture and topics, all in its tags, and what it says is Markdown
8//! proper: a line break in a paragraph is a space, as it is not in a note.
9//! It is known by an address (who wrote it and what they called it), under
10//! which it is written again when it is changed, so that each version has
11//! an id of its own and the address stays. When it was written is so
12//! when it was last changed.
13//!
14//! Where it is listed among notes, an article shows as a card: its
15//! picture, its title, and what sums it up. All of it is shown where it
16//! is opened, as the note a thread is for (see [`Note::in_full`]).
17//!
18//! [`Note::in_full`]: crate::nostr::models::Note::in_full
19
20use nostr_sdk::prelude::{Event, Kind, Nip19Coordinate, PublicKey, RelayUrl};
21use reqwest::Url;
22
23use crate::helpers::truncate_chars;
24
25/// The kind of event an article is.
26pub(crate) const ARTICLE_KIND: Kind = Kind::LongFormTextNote;
27
28/// How much of an article's title and of what sums it up is kept: both
29/// are the author's to write, at any length.
30const TITLE_MAX_CHARS: usize = 200;
31const SUMMARY_MAX_CHARS: usize = 600;
32
33/// How many topics of an article are shown, and how much of each: as
34/// many as Jumble shows.
35const MAX_TOPICS: usize = 6;
36const TOPIC_MAX_CHARS: usize = 32;
37
38/// How many words are read in a minute, and how many characters of what
39/// is written without spaces between words: what Jumble takes them to be.
40const WORDS_PER_MINUTE: f32 = 220.0;
41const UNSPACED_PER_MINUTE: f32 = 300.0;
42
43/// What an article says of itself, beside what it says.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Article {
46    /// What it is called. Empty where it doesn't say: it is then called
47    /// what the view calls an article without a title.
48    pub title: String,
49    /// What sums it up, if it says.
50    pub summary: Option<String>,
51    /// The picture it is shown with, if it names one that can be fetched.
52    pub image: Option<String>,
53    /// What it is about: its hashtags, in lowercase, each once.
54    pub topics: Vec<String>,
55    /// What its author called it, which with who they are is its
56    /// address.
57    pub identifier: String,
58    /// How many minutes it takes to read, one at the least.
59    pub minutes: u32,
60    /// Whether the note this is of has all the article says: the note a
61    /// thread is for. Elsewhere it has none of it, and shows as a card.
62    pub whole: bool,
63}
64
65impl Article {
66    /// What `event` says of itself, if it is an article.
67    pub fn of(event: &Event) -> Option<Self> {
68        if event.kind != ARTICLE_KIND {
69            return None;
70        }
71        let said = |name: &str| {
72            event.tags.iter().map(|tag| tag.as_slice()).find(|tag| tag.first().is_some_and(|first| first == name)).and_then(
73                |tag| {
74                    let said: String = tag.get(1)?.chars().filter(|c| !c.is_control() || *c == '\n').collect();
75                    Some(said.trim().to_string()).filter(|said| !said.is_empty())
76                },
77            )
78        };
79        let identifier = event.tags.identifier().unwrap_or_default().to_string();
80        // An article without a title is called what its address calls it,
81        // as in Jumble, unless that says nothing either.
82        let title = said("title").map(|title| title.replace('\n', " ")).unwrap_or_else(|| identifier.clone());
83        let mut topics: Vec<String> = Vec::new();
84        for topic in event.tags.hashtags() {
85            let topic = truncate_chars(&topic.trim().to_lowercase(), TOPIC_MAX_CHARS).into_owned();
86            if !topic.is_empty() && !topic.chars().any(char::is_control) && !topics.contains(&topic) && topics.len() < MAX_TOPICS
87            {
88                topics.push(topic);
89            }
90        }
91        Some(Self {
92            title: truncate_chars(title.trim(), TITLE_MAX_CHARS).into_owned(),
93            summary: said("summary").map(|summary| truncate_chars(&summary, SUMMARY_MAX_CHARS).into_owned()),
94            // Nothing but `https` is fetched.
95            image: said("image")
96                .and_then(|image| Url::parse(&image).ok())
97                .filter(|url| url.scheme() == "https")
98                .map(String::from),
99            topics,
100            identifier,
101            minutes: reading_minutes(&event.content),
102            whole: false,
103        })
104    }
105}
106
107/// An article a note names by its address (`nostr:naddr1…`). Shown under
108/// the note's text, as the card of the article when that is at hand, and
109/// as a link to it when it isn't.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ArticleLink {
112    /// Who wrote it and what they called it: its address.
113    pub author: PublicKey,
114    pub identifier: String,
115    /// A relay that has it, when the address says.
116    pub relay: Option<RelayUrl>,
117    /// The short form of its address, which stands for it where the
118    /// article itself can't.
119    pub label: String,
120}
121
122impl ArticleLink {
123    /// The article `address` is the address of, with `label` to stand for
124    /// it. `None` for the address of what is no article.
125    pub fn at(address: Nip19Coordinate, label: String) -> Option<Self> {
126        (address.kind == ARTICLE_KIND).then(|| Self {
127            author: address.public_key,
128            identifier: address.identifier.clone(),
129            relay: address.relays.into_iter().next(),
130            label,
131        })
132    }
133
134    /// Whether this is the address of the article `article`, which
135    /// `author` wrote.
136    pub fn names(&self, author: &PublicKey, article: &Article) -> bool {
137        self.author == *author && self.identifier == article.identifier
138    }
139}
140
141/// Whether `c` is of a script written without spaces between words:
142/// Japanese, Chinese, Korean.
143fn unspaced(c: char) -> bool {
144    matches!(c, '\u{3040}'..='\u{30ff}' | '\u{3400}'..='\u{4dbf}' | '\u{4e00}'..='\u{9fff}' | '\u{ac00}'..='\u{d7af}')
145}
146
147/// How many minutes `text` takes to read, near enough: its words, and
148/// the characters of what is written without spaces, each at the pace
149/// such are read. One minute at the least. The addresses in it are
150/// counted as the word or two they come to, which is little either way.
151pub fn reading_minutes(text: &str) -> u32 {
152    let characters = text.chars().filter(|c| unspaced(*c)).count();
153    let words = text.split(|c: char| !c.is_alphanumeric() || unspaced(c)).filter(|word| !word.is_empty()).count();
154    let minutes = characters as f32 / UNSPACED_PER_MINUTE + words as f32 / WORDS_PER_MINUTE;
155    (minutes.round() as u32).max(1)
156}
157
158#[cfg(test)]
159mod tests {
160    use super::{ARTICLE_KIND, Article, MAX_TOPICS, reading_minutes};
161    use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, Tag, Timestamp};
162
163    fn article(tags: Vec<Tag>, body: &str) -> Event {
164        EventBuilder::new(ARTICLE_KIND, body)
165            .tags(tags)
166            .custom_created_at(Timestamp::from_secs(2_000))
167            .finalize(&Keys::generate())
168            .unwrap()
169    }
170
171    fn tag(name: &str, said: &str) -> Tag {
172        Tag::custom(name, [said])
173    }
174
175    #[test]
176    fn an_article_says_what_it_is_in_its_tags() {
177        let event = article(
178            vec![
179                Tag::identifier("on-birds"),
180                tag("title", "  On birds\nthat run "),
181                tag("summary", "Why some gave up flying."),
182                tag("image", "https://example.com/bird.jpg"),
183                Tag::hashtag("Birds"),
184                Tag::hashtag("birds"),
185                Tag::hashtag("running"),
186            ],
187            "They run.",
188        );
189        let said = Article::of(&event).unwrap();
190        assert_eq!(said.title, "On birds that run");
191        assert_eq!(said.summary.as_deref(), Some("Why some gave up flying."));
192        assert_eq!(said.image.as_deref(), Some("https://example.com/bird.jpg"));
193        assert_eq!(said.topics, ["birds", "running"]);
194        assert_eq!(said.identifier, "on-birds");
195        assert_eq!(said.minutes, 1);
196        assert!(!said.whole);
197    }
198
199    #[test]
200    fn what_an_article_leaves_out_is_left_out() {
201        let said = Article::of(&article(vec![Tag::identifier("untitled-7")], "")).unwrap();
202        assert_eq!(said.title, "untitled-7", "called what its address calls it");
203        assert_eq!((said.summary, said.image), (None, None));
204        assert!(said.topics.is_empty());
205
206        let nameless = Article::of(&article(vec![], "")).unwrap();
207        assert_eq!(nameless.title, "");
208        assert_eq!(nameless.identifier, "");
209    }
210
211    #[test]
212    fn what_is_no_article_is_none() {
213        let note = EventBuilder::new(Kind::TextNote, "a note").tags([tag("title", "No")]).finalize(&Keys::generate()).unwrap();
214        assert_eq!(Article::of(&note), None);
215    }
216
217    #[test]
218    fn what_cannot_be_what_it_says_is_left_out() {
219        let event = article(vec![tag("image", "http://example.com/plain.jpg"), tag("summary", " \u{7} ")], "");
220        let said = Article::of(&event).unwrap();
221        assert_eq!((said.image, said.summary), (None, None));
222        assert_eq!(Article::of(&article(vec![tag("image", "not an address")], "")).unwrap().image, None);
223    }
224
225    #[test]
226    fn only_so_many_topics_are_kept() {
227        let tags = (0..20).map(|n| Tag::hashtag(format!("topic{n}"))).collect();
228        assert_eq!(Article::of(&article(tags, "")).unwrap().topics.len(), MAX_TOPICS);
229    }
230
231    #[test]
232    fn reading_takes_a_minute_for_so_many_words() {
233        assert_eq!(reading_minutes(""), 1);
234        assert_eq!(reading_minutes("a few words"), 1);
235        assert_eq!(reading_minutes(&"word ".repeat(220)), 1);
236        assert_eq!(reading_minutes(&"word ".repeat(1_100)), 5);
237        // Written without spaces: counted by the character.
238        assert_eq!(reading_minutes(&"\u{9ce5}".repeat(900)), 3);
239    }
240}