Skip to main content

cosmic_applet_avestruz/nostr/
models.rs

1// SPDX-License-Identifier: MIT
2
3//! Notes and profiles, reduced to what the views show.
4
5use 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
13/// How much of what someone says about themselves is kept. It is theirs to
14/// write, at any length.
15const ABOUT_MAX_CHARS: usize = 1_000;
16
17/// Where a note stands in a conversation, when it is a reply (NIP-10).
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct ReplyTo {
20    /// The note the conversation started with.
21    pub root: EventId,
22    /// The note this one answers: the root itself, for a reply straight to it.
23    pub parent: EventId,
24}
25
26/// What `event` says it replies to, if to anything that can be named as a
27/// note is: a text note by its `e` tags (NIP-10), a comment by the tags of
28/// the comment it answers and of what the comments are about (NIP-22). An
29/// event of another kind replies to nothing, whatever it cites.
30pub(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
38/// What a comment (kind 1111) answers: the event it names as its parent,
39/// under the event the comments are about. Comments on something that is
40/// no event (an article by its address, a web page) have no such root; the
41/// first comment then stands for it, and answers nothing.
42fn 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
52/// What the `e` tags of a text note say it replies to, if to anything.
53///
54/// Tags marked `reply` and `root` say so themselves. Without markers it is
55/// the older convention, by position: the first tag is the root and the last
56/// the parent. A tag marked `mention` only cites a note, and is no part of
57/// this.
58fn 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        // A root marker and no reply marker: a reply straight to the root,
77        // unless tags without the root marker follow the older convention.
78        .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/// Something someone wrote, as a row shows it: a short text note (kind 1),
84/// a comment (kind 1111), or, at the top of a thread of comments, whatever
85/// they are about, as far as it is text. With the notes it quotes, as far
86/// as they were at hand.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Note {
89    pub id: EventId,
90    /// What kind of event it is.
91    pub kind: Kind,
92    pub author: PublicKey,
93    /// When the author says it was written, in seconds since the Unix epoch.
94    pub created_at: u64,
95    /// What it says, parsed, and cut to what its row shows.
96    pub content: Content,
97    /// What it replies to. `None` for a note that starts a conversation.
98    pub reply_to: Option<ReplyTo>,
99    /// The notes it quotes, of those its row shows, that were at hand when
100    /// it was put together: each as a row shows it, with the notes it
101    /// quotes in turn, down to [`QUOTE_DEPTH`](content::QUOTE_DEPTH) notes
102    /// from the note of a row. The rest of what it
103    /// [quotes](Content::quotes) shows as links.
104    pub quoted: Vec<Note>,
105}
106
107/// A note as a feed row shows it: a long one is cut.
108impl From<Event> for Note {
109    fn from(event: Event) -> Self {
110        Self::new(&event, FEED_NOTE_MAX_CHARS)
111    }
112}
113
114impl Note {
115    /// `event` as a note, showing at most `max_chars` characters of what it
116    /// says.
117    fn new(event: &Event, max_chars: usize) -> Self {
118        // What the note says of what it links to: how large its pictures
119        // are, and which of its links are videos.
120        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    /// The notes it quotes that its row shows, by id: the first few.
133    pub fn quotes_shown(&self) -> impl Iterator<Item = &Quote> + '_ {
134        self.content.quotes.iter().take(MAX_NOTE_QUOTES)
135    }
136
137    /// This, with those of the notes its row shows it quoting that are
138    /// among `found`.
139    #[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(&quote.id)).cloned().collect();
142        self
143    }
144
145    /// The note `id`, if it is one this quotes and it was at hand.
146    pub fn quoted(&self, id: EventId) -> Option<&Note> {
147        self.quoted.iter().find(|quoted| quoted.id == id)
148    }
149
150    /// How many quoted notes it is shown with, the ones in those counted:
151    /// more of them is more of the same note at hand.
152    pub fn quoted_count(&self) -> usize {
153        self.quoted.iter().map(|quoted| 1 + quoted.quoted_count()).sum()
154    }
155
156    /// A note with all it says: how the note a thread was opened for shows.
157    pub fn in_full(event: &Event) -> Self {
158        Self::new(event, usize::MAX)
159    }
160
161    /// What `author` is writing, as a row would show it in full if it went
162    /// out now as it is, with `said` for what it says of the files it
163    /// links to. It is no note yet, and has no id of its own; the notes it
164    /// quotes are for whoever has them to add.
165    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    /// Whether it answers something, rather than starting a conversation.
179    /// A comment always does, whatever it is about.
180    pub fn is_reply(&self) -> bool {
181        self.reply_to.is_some() || self.kind == Kind::Comment
182    }
183
184    /// Everyone whose profile showing this note needs: its author and the
185    /// people it mentions, and those of the notes it is shown quoting, as
186    /// deep as they go.
187    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/// What an author published about themselves (kind 0), as far as it is shown.
197#[derive(Debug, Clone, Default, PartialEq, Eq)]
198pub struct Profile {
199    /// The name to show: `display_name`, or else `name`. `None` when both are
200    /// missing or blank.
201    pub name: Option<String>,
202    /// Where their picture is, if it is somewhere it can be fetched from: an
203    /// `https` address.
204    pub picture: Option<String>,
205    /// Where the picture across the top of their profile is, likewise.
206    pub banner: Option<String>,
207    /// The name at a domain they say is theirs (NIP-05). Theirs to say:
208    /// whether the domain agrees is another matter (see
209    /// [`crate::nostr::nip05`]).
210    pub nip05: Option<String>,
211    /// Their Lightning address (`lud16`): where they can be zapped.
212    pub lightning: Option<String>,
213    /// What they say about themselves, cut if it runs long.
214    pub about: Option<String>,
215    /// Their website, if what they gave is a web address.
216    pub website: Option<Website>,
217}
218
219/// A web address someone gives as theirs.
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct Website {
222    /// Where it is.
223    pub url: String,
224    /// How it shows: as links in notes do.
225    pub label: String,
226}
227
228impl Website {
229    /// The web address in `given`, which people write with a scheme or
230    /// without one. `None` for anything that is not a web address.
231    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    /// The profile in a kind-0 event's content. Content that isn't profile
241    /// JSON gives an empty profile: the author exists, and said nothing usable.
242    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
269/// A public key short enough to stand in for a name: `npub1abcd…wxyz`.
270pub 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
278/// The name someone goes by: the one in their profile, or a short form of
279/// their public key until (and unless) they have one.
280pub 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    /// The reply the `e` tags `(id, marker)` make a note, an empty marker
299    /// being none.
300    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        // The second is not to be found, and the last two are more than a
381        // row shows.
382        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(&quoted[2]));
387        assert_eq!(note.quoted(quoted[1].id), None);
388
389        // Showing it takes knowing who wrote what it quotes, and whom
390        // those mention.
391        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        // And so on down: a quoted note that is shown with one it quotes.
396        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        // An answer to a comment, on an event.
429        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        // On an article, named by its address: the comment answered stands
434        // for the conversation.
435        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        // On a web page: nothing to name as a note, and a reply all the same.
439        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(&note), 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        // Written without a scheme, as people do.
521        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}