cosmic_applet_avestruz/nostr/
article.rs1use nostr_sdk::prelude::{Event, Kind, Nip19Coordinate, PublicKey, RelayUrl};
21use reqwest::Url;
22
23use crate::helpers::truncate_chars;
24
25pub(crate) const ARTICLE_KIND: Kind = Kind::LongFormTextNote;
27
28const TITLE_MAX_CHARS: usize = 200;
31const SUMMARY_MAX_CHARS: usize = 600;
32
33const MAX_TOPICS: usize = 6;
36const TOPIC_MAX_CHARS: usize = 32;
37
38const WORDS_PER_MINUTE: f32 = 220.0;
41const UNSPACED_PER_MINUTE: f32 = 300.0;
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Article {
46 pub title: String,
49 pub summary: Option<String>,
51 pub image: Option<String>,
53 pub topics: Vec<String>,
55 pub identifier: String,
58 pub minutes: u32,
60 pub whole: bool,
63}
64
65impl Article {
66 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ArticleLink {
112 pub author: PublicKey,
114 pub identifier: String,
115 pub relay: Option<RelayUrl>,
117 pub label: String,
120}
121
122impl ArticleLink {
123 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 pub fn names(&self, author: &PublicKey, article: &Article) -> bool {
137 self.author == *author && self.identifier == article.identifier
138 }
139}
140
141fn 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
147pub 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(¬e), 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 assert_eq!(reading_minutes(&"\u{9ce5}".repeat(900)), 3);
239 }
240}