1use std::borrow::Cow;
6use std::collections::HashMap;
7
8use nostr_sdk::prelude::{CommentTarget, Event, EventId, Kind, Metadata, PublicKey, Tag, Tags, ToBech32, Url, nip22};
9
10use crate::helpers::truncate_chars;
11use crate::nostr::content::{self, Content, FEED_NOTE_MAX_CHARS, MAX_NOTE_QUOTES, Quote, imeta, link_label};
12
13const ABOUT_MAX_CHARS: usize = 1_000;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct ReplyTo {
20 pub root: EventId,
22 pub parent: EventId,
24}
25
26pub(crate) fn reply_to(event: &Event) -> Option<ReplyTo> {
31 match event.kind {
32 Kind::TextNote => note_reply_to(&event.tags),
33 Kind::Comment => comment_reply_to(event),
34 _ => None,
35 }
36}
37
38fn comment_reply_to(comment: &Event) -> Option<ReplyTo> {
43 let event = |target: Option<CommentTarget<'_>>| match target {
44 Some(CommentTarget::Event { id, .. }) => Some(id),
45 _ => None,
46 };
47 let (root, parent) = (event(nip22::extract_root(comment)), event(nip22::extract_parent(comment)));
48 let parent = parent.or(root)?;
49 Some(ReplyTo { root: root.unwrap_or(parent), parent })
50}
51
52fn note_reply_to(tags: &Tags) -> Option<ReplyTo> {
59 let tagged: Vec<(EventId, Option<&str>)> = tags
60 .iter()
61 .filter_map(|tag| {
62 let fields = tag.as_slice();
63 if fields.first().map(String::as_str) != Some("e") {
64 return None;
65 }
66 let id = EventId::from_hex(fields.get(1)?).ok()?;
67 Some((id, fields.get(3).map(String::as_str).filter(|marker| !marker.is_empty())))
68 })
69 .filter(|(_, marker)| *marker != Some("mention"))
70 .collect();
71 let (first, last) = (tagged.first()?.0, tagged.last()?.0);
72 let marked = |marker: &str| tagged.iter().find(|(_, found)| *found == Some(marker)).map(|(id, _)| *id);
73
74 let root = marked("root");
75 let parent = marked("reply")
76 .or_else(|| root.map(|root| tagged.iter().rev().find(|(_, marker)| *marker != Some("root")).map_or(root, |(id, _)| *id)))
79 .unwrap_or(last);
80 Some(ReplyTo { root: root.unwrap_or(first), parent })
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Note {
89 pub id: EventId,
90 pub kind: Kind,
92 pub author: PublicKey,
93 pub created_at: u64,
95 pub content: Content,
97 pub reply_to: Option<ReplyTo>,
99 pub quoted: Vec<Note>,
105}
106
107impl From<Event> for Note {
109 fn from(event: Event) -> Self {
110 Self::new(&event, FEED_NOTE_MAX_CHARS)
111 }
112}
113
114impl Note {
115 fn new(event: &Event, max_chars: usize) -> Self {
118 let attached: Vec<_> = event.tags.iter().filter_map(|tag| imeta(tag.as_slice())).collect();
121 Self {
122 id: event.id,
123 kind: event.kind,
124 author: event.pubkey,
125 created_at: event.created_at.as_secs(),
126 content: content::parse_attached(&event.content, max_chars, &attached),
127 reply_to: reply_to(event),
128 quoted: Vec::new(),
129 }
130 }
131
132 pub fn quotes_shown(&self) -> impl Iterator<Item = &Quote> + '_ {
134 self.content.quotes.iter().take(MAX_NOTE_QUOTES)
135 }
136
137 #[must_use]
140 pub fn with_quoted(mut self, found: &HashMap<EventId, Note>) -> Self {
141 self.quoted = self.quotes_shown().filter_map(|quote| found.get("e.id)).cloned().collect();
142 self
143 }
144
145 pub fn quoted(&self, id: EventId) -> Option<&Note> {
147 self.quoted.iter().find(|quoted| quoted.id == id)
148 }
149
150 pub fn quoted_count(&self) -> usize {
153 self.quoted.iter().map(|quoted| 1 + quoted.quoted_count()).sum()
154 }
155
156 pub fn in_full(event: &Event) -> Self {
158 Self::new(event, usize::MAX)
159 }
160
161 pub fn being_written(text: &str, said: &[Tag], author: PublicKey, now: u64) -> Self {
166 let attached: Vec<_> = said.iter().filter_map(|tag| imeta(tag.as_slice())).collect();
167 Self {
168 id: EventId::from_byte_array([0; 32]),
169 kind: Kind::TextNote,
170 author,
171 created_at: now,
172 content: content::parse_attached(text, usize::MAX, &attached),
173 reply_to: None,
174 quoted: Vec::new(),
175 }
176 }
177
178 pub fn is_reply(&self) -> bool {
181 self.reply_to.is_some() || self.kind == Kind::Comment
182 }
183
184 pub fn people(&self) -> impl Iterator<Item = PublicKey> + '_ {
188 let mut people: Vec<PublicKey> = std::iter::once(self.author).chain(self.content.mentions()).collect();
189 for quoted in &self.quoted {
190 people.extend(quoted.people());
191 }
192 people.into_iter()
193 }
194}
195
196#[derive(Debug, Clone, Default, PartialEq, Eq)]
198pub struct Profile {
199 pub name: Option<String>,
202 pub picture: Option<String>,
205 pub banner: Option<String>,
207 pub nip05: Option<String>,
211 pub lightning: Option<String>,
213 pub about: Option<String>,
215 pub website: Option<Website>,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct Website {
222 pub url: String,
224 pub label: String,
226}
227
228impl Website {
229 fn parse(given: &str) -> Option<Self> {
232 let given = given.trim();
233 let url = if given.contains("://") { Url::parse(given) } else { Url::parse(&format!("https://{given}")) }.ok()?;
234 let on_the_web = matches!(url.scheme(), "http" | "https") && url.host_str().is_some_and(|host| host.contains('.'));
235 on_the_web.then(|| Self { label: link_label(&url), url: url.to_string() })
236 }
237}
238
239impl Profile {
240 pub fn from_content(content: &str) -> Self {
243 let Ok(metadata) = Metadata::from_json(content) else {
244 return Self::default();
245 };
246 let name = [metadata.display_name, metadata.name]
247 .into_iter()
248 .flatten()
249 .map(|name| name.trim().to_string())
250 .find(|name| !name.is_empty());
251 let fetchable = |address: Option<String>| {
252 address
253 .and_then(|address| Url::parse(address.trim()).ok())
254 .filter(|url| url.scheme() == "https")
255 .map(|url| url.to_string())
256 };
257 let (picture, banner) = (fetchable(metadata.picture), fetchable(metadata.banner));
258 let nip05 = metadata.nip05.map(|name| name.trim().to_string()).filter(|name| !name.is_empty());
259 let lightning = metadata.lud16.map(|address| address.trim().to_string()).filter(|address| !address.is_empty());
260 let about = metadata
261 .about
262 .map(|about| truncate_chars(about.trim(), ABOUT_MAX_CHARS).into_owned())
263 .filter(|about| !about.is_empty());
264 let website = metadata.website.as_deref().and_then(Website::parse);
265 Self { name, picture, banner, nip05, lightning, about, website }
266 }
267}
268
269pub fn short_npub(public_key: &PublicKey) -> String {
271 let Ok(npub) = public_key.to_bech32();
272 match (npub.get(..9), npub.get(npub.len().saturating_sub(4)..)) {
273 (Some(head), Some(tail)) => format!("{head}\u{2026}{tail}"),
274 _ => npub,
275 }
276}
277
278pub fn display_name<'a>(profiles: &'a HashMap<PublicKey, Profile>, public_key: &PublicKey) -> Cow<'a, str> {
281 match profiles.get(public_key).and_then(|profile| profile.name.as_deref()) {
282 Some(name) => Cow::Borrowed(name),
283 None => Cow::Owned(short_npub(public_key)),
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::{ABOUT_MAX_CHARS, Note, Profile, ReplyTo, display_name, note_reply_to, reply_to, short_npub};
290 use crate::nostr::content::FEED_NOTE_MAX_CHARS;
291 use nostr_sdk::prelude::{EventBuilder, EventId, FinalizeEvent, Keys, Kind, PublicKey, Tag, Tags, ToBech32};
292 use std::collections::HashMap;
293
294 fn id(byte: u8) -> EventId {
295 EventId::from_byte_array([byte; 32])
296 }
297
298 fn reply(tags: &[(u8, &str)]) -> Option<(EventId, EventId)> {
301 let tags = Tags::from_list(
302 tags.iter()
303 .map(|(byte, marker)| {
304 let mut fields = vec!["e".to_string(), id(*byte).to_hex()];
305 if !marker.is_empty() {
306 fields.extend([String::new(), (*marker).to_string()]);
307 }
308 Tag::parse(fields).unwrap()
309 })
310 .collect(),
311 );
312 note_reply_to(&tags).map(|ReplyTo { root, parent }| (root, parent))
313 }
314
315 #[test]
316 fn what_is_being_written_reads_as_the_note_it_would_be() {
317 let keys = Keys::generate();
318 let text = "# gm\nlook at **this**\nhttps://cdn.example.com/a.jpg\n".to_string() + &"and more ".repeat(200);
319 let said = Tag::parse(["imeta", "url https://cdn.example.com/a.jpg", "dim 800x600"]).unwrap();
320
321 let written = Note::being_written(&text, std::slice::from_ref(&said), keys.public_key(), 7);
322 let event = EventBuilder::new(Kind::TextNote, &text).tags([said]).finalize(&keys).unwrap();
323 let published = Note::in_full(&event);
324
325 assert_eq!(written.content, published.content, "as the note in full would read, once out");
326 assert!(written.content.whole.is_none(), "nothing of it is cut, long as it is");
327 assert_eq!(written.content.images[0].size, Some((800, 600)), "what it says of a file attached counts");
328 assert_eq!((written.author, written.created_at, written.reply_to), (keys.public_key(), 7, None));
329 }
330
331 #[test]
332 fn marked_tags_say_what_a_note_replies_to() {
333 assert_eq!(reply(&[]), None, "no e tags: not a reply");
334 assert_eq!(reply(&[(1, "root")]), Some((id(1), id(1))), "straight to the root");
335 assert_eq!(reply(&[(1, "root"), (2, "reply")]), Some((id(1), id(2))));
336 assert_eq!(reply(&[(2, "reply"), (1, "root")]), Some((id(1), id(2))), "whatever the order");
337 assert_eq!(reply(&[(1, "root"), (3, "mention")]), Some((id(1), id(1))), "a cited note is not answered");
338 assert_eq!(reply(&[(3, "mention")]), None, "citing alone is not replying");
339 }
340
341 #[test]
342 fn unmarked_tags_say_it_by_position() {
343 assert_eq!(reply(&[(1, "")]), Some((id(1), id(1))));
344 assert_eq!(reply(&[(1, ""), (2, "")]), Some((id(1), id(2))));
345 assert_eq!(reply(&[(1, ""), (2, ""), (3, "")]), Some((id(1), id(3))), "first the root, last the parent");
346 assert_eq!(reply(&[(1, "root"), (2, "")]), Some((id(1), id(2))), "a marked root and a parent by position");
347 }
348
349 #[test]
350 fn tags_that_name_no_event_are_passed_over() {
351 let tags = Tags::from_list(vec![
352 Tag::parse(["e", "not an id"]).unwrap(),
353 Tag::parse(["p", &id(7).to_hex()]).unwrap(),
354 Tag::parse(["e", &id(1).to_hex()]).unwrap(),
355 ]);
356 assert_eq!(note_reply_to(&tags), Some(ReplyTo { root: id(1), parent: id(1) }));
357 }
358
359 #[test]
360 fn a_feed_row_cuts_a_long_note_and_its_own_view_does_not() {
361 let long = "word ".repeat(FEED_NOTE_MAX_CHARS);
362 let event = EventBuilder::new(Kind::TextNote, long.clone()).finalize(&Keys::generate()).unwrap();
363 let shown = |note: &Note| note.content.line_chars.iter().sum::<usize>();
364
365 assert_eq!(shown(&Note::in_full(&event)), long.trim().chars().count());
366 assert_eq!(shown(&Note::from(event)), FEED_NOTE_MAX_CHARS);
367 }
368
369 #[test]
370 fn a_note_is_shown_with_the_first_few_notes_it_quotes_that_are_at_hand() {
371 let (me, them, friend) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
372 let said = |text: String, keys: &Keys| Note::from(EventBuilder::new(Kind::TextNote, text).finalize(keys).unwrap());
373 let quoted: Vec<Note> =
374 (0..5).map(|number| said(format!("quoted {number} nostr:{}", friend.to_bech32().unwrap()), &them)).collect();
375 let addresses: Vec<String> = quoted.iter().map(|note| format!("nostr:{}", note.id.to_bech32().unwrap())).collect();
376 let note = said(format!("look {}", addresses.join(" ")), &me);
377 assert_eq!(note.content.quotes.len(), 5);
378 assert!(note.quoted.is_empty(), "nothing is at hand until it is looked for");
379
380 let found: HashMap<EventId, Note> =
383 [0, 2, 3, 4].into_iter().map(|number: usize| (quoted[number].id, quoted[number].clone())).collect();
384 let note = note.with_quoted(&found);
385 assert_eq!(note.quoted, [quoted[0].clone(), quoted[2].clone()]);
386 assert_eq!(note.quoted(quoted[2].id), Some("ed[2]));
387 assert_eq!(note.quoted(quoted[1].id), None);
388
389 let people: Vec<PublicKey> = note.people().collect();
392 assert_eq!(people, [me.public_key(), them.public_key(), friend, them.public_key(), friend]);
393 assert_eq!(note.quoted_count(), 2);
394
395 let third = Keys::generate();
397 let inner = said("the first of them".to_string(), &third);
398 let mut outer = note.clone();
399 outer.quoted[0].quoted = vec![inner];
400 assert_eq!(outer.quoted_count(), 3);
401 assert_eq!(outer.people().nth(3), Some(third.public_key()), "after the note that quotes it, before the next");
402 }
403
404 #[test]
405 fn someone_goes_by_their_profile_name_or_else_their_short_key() {
406 let key = PublicKey::parse("npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6").unwrap();
407 let mut profiles = HashMap::new();
408 assert_eq!(display_name(&profiles, &key), "npub180cv…h6w6");
409
410 profiles.insert(key, Profile::default());
411 assert_eq!(display_name(&profiles, &key), "npub180cv…h6w6", "a profile without a name");
412
413 profiles.insert(key, Profile { name: Some("fiatjaf".into()), ..Profile::default() });
414 assert_eq!(display_name(&profiles, &key), "fiatjaf");
415 }
416
417 #[test]
418 fn a_comment_answers_what_it_names_in_small_letters_under_what_it_names_in_capitals() {
419 let keys = Keys::generate();
420 let comment = |tags: &[&[&str]]| {
421 EventBuilder::new(Kind::Comment, "said")
422 .tags(tags.iter().map(|tag| Tag::parse(tag.iter().copied()).unwrap()))
423 .finalize(&keys)
424 .unwrap()
425 };
426 let (about, answered) = (id(1).to_hex(), id(2).to_hex());
427
428 let deep = comment(&[&["E", &about], &["K", "20"], &["e", &answered], &["k", "1111"]]);
430 assert_eq!(reply_to(&deep), Some(ReplyTo { root: id(1), parent: id(2) }));
431 assert!(Note::from(deep).is_reply());
432
433 let on_article = comment(&[&["A", "30023:aa:herons"], &["K", "30023"], &["e", &answered], &["k", "1111"]]);
436 assert_eq!(reply_to(&on_article), Some(ReplyTo { root: id(2), parent: id(2) }));
437
438 let on_page = comment(&[&["I", "https://example.com/"], &["K", "web"], &["i", "https://example.com/"], &["k", "web"]]);
440 assert_eq!(reply_to(&on_page), None);
441 let shown = Note::from(on_page);
442 assert!(shown.is_reply());
443 assert_eq!(shown.kind, Kind::Comment);
444 }
445
446 #[test]
447 fn only_notes_and_comments_reply_to_anything() {
448 let keys = Keys::generate();
449 let citing = Tag::parse(["e", &id(1).to_hex()]).unwrap();
450 let article = EventBuilder::new(Kind::LongFormTextNote, "# Cites a note").tag(citing.clone()).finalize(&keys).unwrap();
451 let note = EventBuilder::new(Kind::TextNote, "answers one").tag(citing).finalize(&keys).unwrap();
452
453 assert_eq!(reply_to(&article), None);
454 assert!(!Note::from(article).is_reply());
455 assert_eq!(reply_to(¬e), Some(ReplyTo { root: id(1), parent: id(1) }));
456 }
457
458 #[test]
459 fn a_profile_prefers_the_display_name_and_skips_blank_ones() {
460 let name = |content: &str| Profile::from_content(content).name;
461 assert_eq!(name(r#"{"name":"fiatjaf","display_name":"Fiat Jaf"}"#).as_deref(), Some("Fiat Jaf"));
462 assert_eq!(name(r#"{"name":"fiatjaf","display_name":" "}"#).as_deref(), Some("fiatjaf"));
463 assert_eq!(name(r#"{"name":" padded "}"#).as_deref(), Some("padded"));
464 assert_eq!(name(r#"{"about":"no name here"}"#), None);
465 }
466
467 #[test]
468 fn a_profile_picture_is_kept_only_if_it_can_be_fetched() {
469 let picture = |content: &str| Profile::from_content(content).picture;
470 assert_eq!(picture(r#"{"picture":" https://example.com/me.png "}"#).as_deref(), Some("https://example.com/me.png"));
471 assert_eq!(picture(r#"{"picture":"http://example.com/me.png"}"#), None, "not https");
472 assert_eq!(picture(r#"{"picture":"data:image/png;base64,AAAA"}"#), None);
473 assert_eq!(picture(r#"{"picture":"not an address"}"#), None);
474 assert_eq!(picture(r#"{"name":"nobody"}"#), None);
475 }
476
477 #[test]
478 fn a_profile_banner_is_kept_as_its_picture_is() {
479 let banner = |content: &str| Profile::from_content(content).banner;
480 assert_eq!(banner(r#"{"banner":"https://example.com/wide.jpg"}"#).as_deref(), Some("https://example.com/wide.jpg"));
481 assert_eq!(banner(r#"{"banner":"http://example.com/wide.jpg"}"#), None, "not https");
482 assert_eq!(banner(r#"{"picture":"https://example.com/me.png"}"#), None);
483 }
484
485 #[test]
486 fn a_profile_says_which_name_its_author_claims() {
487 let nip05 = |content: &str| Profile::from_content(content).nip05;
488 assert_eq!(nip05(r#"{"nip05":" ana@example.com "}"#).as_deref(), Some("ana@example.com"));
489 assert_eq!(nip05(r#"{"nip05":""}"#), None);
490 assert_eq!(nip05(r#"{"name":"ana"}"#), None);
491 }
492
493 #[test]
494 fn a_profile_says_where_its_author_can_be_zapped() {
495 let lightning = |content: &str| Profile::from_content(content).lightning;
496 assert_eq!(lightning(r#"{"lud16":" ana@example.com "}"#).as_deref(), Some("ana@example.com"));
497 assert_eq!(lightning(r#"{"lud16":""}"#), None);
498 assert_eq!(lightning(r#"{"name":"ana"}"#), None);
499 }
500
501 #[test]
502 fn a_profile_says_what_its_author_says_of_themselves_up_to_a_length() {
503 let about = |content: &str| Profile::from_content(content).about;
504 assert_eq!(
505 about(r#"{"about":" bird watcher\nand relay operator "}"#).as_deref(),
506 Some("bird watcher\nand relay operator")
507 );
508 assert_eq!(about(r#"{"about":" "}"#), None);
509 assert_eq!(about(r#"{"name":"ana"}"#), None);
510
511 let long = about(&format!(r#"{{"about":"{}"}}"#, "a".repeat(ABOUT_MAX_CHARS + 50))).unwrap();
512 assert_eq!(long.chars().count(), ABOUT_MAX_CHARS + 1, "cut, and marked as cut");
513 }
514
515 #[test]
516 fn a_profile_website_is_kept_only_if_it_is_a_web_address() {
517 let website = |content: &str| Profile::from_content(content).website.map(|website| (website.url, website.label));
518 let (url, label) = website(r#"{"website":" https://www.example.com/me "}"#).unwrap();
519 assert_eq!((url.as_str(), label.as_str()), ("https://www.example.com/me", "example.com/me"));
520 let (url, label) = website(r#"{"website":"example.com"}"#).unwrap();
522 assert_eq!((url.as_str(), label.as_str()), ("https://example.com/", "example.com"));
523
524 assert_eq!(website(r#"{"website":"javascript://example.com/%0Aalert(1)"}"#), None);
525 assert_eq!(website(r#"{"website":"file:///etc/passwd"}"#), None);
526 assert_eq!(website(r#"{"website":"not a website"}"#), None);
527 assert_eq!(website(r#"{"website":""}"#), None);
528 }
529
530 #[test]
531 fn content_that_is_not_a_profile_gives_an_empty_one() {
532 assert_eq!(Profile::from_content("not json"), Profile::default());
533 assert_eq!(Profile::from_content(""), Profile::default());
534 }
535
536 #[test]
537 fn a_short_npub_keeps_both_ends() {
538 let key = PublicKey::parse("npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6").unwrap();
539 assert_eq!(short_npub(&key), "npub180cv…h6w6");
540 }
541}