Skip to main content

cosmic_applet_avestruz/nostr/
bookmarks.rs

1// SPDX-License-Identifier: MIT
2
3//! The account's bookmarks (NIP-51, kind 10003): the notes it wants to find
4//! again.
5//!
6//! There is one list for an account, and every new one replaces the last
7//! everywhere, as with a contact list. It names notes in two places: in its
8//! tags, for anyone to read, and in its content, which is a list of tags of
9//! the same form, as JSON, that the account encrypted to itself (NIP-44).
10//!
11//! Avestruz keeps bookmarks in the second and nowhere else, and reads them
12//! from the second and nowhere else: what is bookmarked here is nobody
13//! else's to know, and what a list says to anyone is not a bookmark here.
14//! The list's tags are carried from each list to the next as they are,
15//! unread: they are for the clients that keep bookmarks there.
16//!
17//! This is the list Amethyst shows as "Bookmarks" (its "Old Bookmarks" is
18//! kind 30001), and its private half is read and written here as it is
19//! there, so that each finds what the other left: the content is the tags
20//! as compact JSON, an `e` tag names a note by its id and may say after it
21//! where the note is, a new bookmark goes after the others, and a list
22//! that keeps nothing to itself has no content at all.
23//!
24//! A bookmark is one change to the newest list, with everything else in it
25//! as it was: the other notes, and the articles, hashtags and links other
26//! clients keep there.
27//!
28//! ```mermaid
29//! flowchart LR
30//!     subgraph event["A bookmark list, kind 10003"]
31//!         direction TB
32//!         tags["tags: what is bookmarked for anyone to see"]
33//!         content["content: a list of tags of the same form, as JSON, encrypted to the account (NIP-44)"]
34//!     end
35//!     tags -. "carried from each list to the next, unread" .-> next["The next list"]
36//!     content -- "decrypted: takes the key" --> private["e tags: notes. a, t, r tags: what other clients keep"]
37//!     private -- "the e tags" --> shown["The bookmarks shown here"]
38//!     private -- "one tag more or less, re-encrypted" --> next
39//! ```
40//!
41//! How a bookmark is made without losing what another client wrote
42//! meanwhile is in [`crate::guide::flows`].
43
44use std::collections::HashSet;
45use std::fmt;
46
47use nostr_sdk::prelude::{Event, EventBuilder, EventId, Kind, PublicKey, RelayUrl, Tag, Timestamp};
48
49use crate::nostr::outbox::Whereabouts;
50
51/// What a list keeps to itself, once it has been decrypted: tags, as the
52/// list's own are.
53pub type PrivateTags = Vec<Vec<String>>;
54
55/// The tags `json` lists, which is what a bookmark list's content says once
56/// it is decrypted.
57///
58/// The error says nothing of what was read: it is what the account keeps
59/// to itself, and errors end up in logs.
60pub fn decode(json: &str) -> Result<PrivateTags, String> {
61    serde_json::from_str(json).map_err(|_| "what was decrypted is not a list of tags".to_string())
62}
63
64/// `tags` as the JSON a bookmark list's content is, before it is encrypted.
65pub fn encode(tags: &PrivateTags) -> String {
66    serde_json::to_string(tags).unwrap_or_else(|_| "[]".to_string())
67}
68
69/// The note the tag `fields` bookmarks, if it bookmarks one: `["e", <id>, …]`.
70fn note_named(fields: &[String]) -> Option<EventId> {
71    match fields {
72        [name, id, ..] if name == "e" => EventId::from_hex(id).ok(),
73        _ => None,
74    }
75}
76
77/// Where the tag `fields`, which bookmarks a note, says the note is: a
78/// relay that has it and who wrote it, each if a field after the id says
79/// (`["e", <id>, <relay>, <author>]`, either of the two left out, as
80/// Amethyst writes it).
81fn whereabouts_named(fields: &[String]) -> Whereabouts {
82    let said = || fields.iter().skip(2);
83    let relay = said().find_map(|field| RelayUrl::parse(field).ok());
84    let author = said().find_map(|field| PublicKey::from_hex(field).ok());
85    Whereabouts { author, relay }
86}
87
88/// Whether the tag `fields` bookmarks something that is not a note: an
89/// article (`a`), a hashtag (`t`) or a link (`r`), which other clients
90/// keep in the same list.
91fn names_something_else(fields: &[String]) -> bool {
92    fields.len() > 1 && fields.first().is_some_and(|name| ["a", "t", "r"].contains(&name.as_str()))
93}
94
95/// The tag that bookmarks `note`, which is at `hint` as far as is known.
96fn naming(note: EventId, hint: Option<&RelayUrl>) -> Vec<String> {
97    let mut fields = vec!["e".to_string(), note.to_hex()];
98    fields.extend(hint.map(ToString::to_string));
99    fields
100}
101
102/// An account's bookmarks, as its newest list has them: what the list
103/// keeps to itself.
104#[derive(Clone, Default, PartialEq, Eq)]
105pub struct Bookmarks {
106    /// The list they were read from. `None` when the account has none.
107    list: Option<Event>,
108    /// What the list keeps to itself.
109    private: PrivateTags,
110    /// The notes bookmarked.
111    notes: HashSet<EventId>,
112}
113
114/// What is kept private is not printed: whatever is `Debug` ends up in a
115/// log sooner or later.
116impl fmt::Debug for Bookmarks {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("Bookmarks")
119            .field("list", &self.list.as_ref().map(|list| list.id))
120            .field("notes", &self.notes.len())
121            .finish_non_exhaustive()
122    }
123}
124
125impl Bookmarks {
126    /// The bookmarks of `list`, which keeps `private` to itself.
127    pub fn new(list: Option<Event>, private: PrivateTags) -> Self {
128        let notes = private.iter().filter_map(|fields| note_named(fields)).collect();
129        Self { list, private, notes }
130    }
131
132    /// The list they were read from, if the account has one.
133    pub fn list(&self) -> Option<&Event> {
134        self.list.as_ref()
135    }
136
137    /// Whether `note` is bookmarked.
138    pub fn has(&self, note: &EventId) -> bool {
139        self.notes.contains(note)
140    }
141
142    /// How many notes are bookmarked.
143    pub fn count(&self) -> usize {
144        self.notes.len()
145    }
146
147    /// The notes bookmarked, the one bookmarked last first, which is the
148    /// list's order backwards: a new bookmark goes after the others. Each
149    /// note once.
150    pub fn notes(&self) -> Vec<EventId> {
151        let mut seen = HashSet::new();
152        let mut notes: Vec<EventId> =
153            self.private.iter().filter_map(|fields| note_named(fields)).filter(|note| seen.insert(*note)).collect();
154        notes.reverse();
155        notes
156    }
157
158    /// Where the list says the bookmarked `note` is, for looking where the
159    /// account's own relays don't have it: what the first bookmark of it
160    /// that says anything says. The account's own word, as it wrote the
161    /// list, or a client of its did.
162    pub fn whereabouts(&self, note: &EventId) -> Whereabouts {
163        let naming = self.private.iter().filter(|fields| note_named(fields).as_ref() == Some(note));
164        naming.map(|fields| whereabouts_named(fields)).find(|said| *said != Whereabouts::default()).unwrap_or_default()
165    }
166
167    /// How many things that are not notes are bookmarked.
168    pub fn others(&self) -> usize {
169        self.private.iter().filter(|fields| names_something_else(fields)).count()
170    }
171
172    /// What the list keeps to itself with `note` bookmarked (`bookmark`),
173    /// or with no bookmark of it left, and otherwise as it is. `hint` is a
174    /// relay that has the note, for whoever reads the list to look on.
175    ///
176    /// `None` when there is nothing to change: `note` is bookmarked
177    /// already, or already isn't.
178    pub fn changed(&self, note: EventId, hint: Option<&RelayUrl>, bookmark: bool) -> Option<PrivateTags> {
179        if self.has(&note) == bookmark {
180            return None;
181        }
182        let mut private = self.private.clone();
183        if bookmark {
184            private.push(naming(note, hint));
185        } else {
186            private.retain(|fields| note_named(fields) != Some(note));
187        }
188        Some(private)
189    }
190}
191
192/// The bookmark list that replaces `earlier`, if there is one to replace:
193/// with its tags, as they are, and `content` for what it keeps to itself,
194/// written at `now` or, if `earlier` claims to be from later, after it: it
195/// has to be the newer of the two.
196pub fn list(earlier: Option<&Event>, content: String, now: Timestamp) -> EventBuilder {
197    let tags: Vec<Tag> = earlier.map(|earlier| earlier.tags.iter().cloned().collect()).unwrap_or_default();
198    let after = earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)));
199    EventBuilder::new(Kind::Bookmarks, content).tags(tags).custom_created_at(after)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::{Bookmarks, PrivateTags, decode, encode, list};
205    use crate::nostr::outbox::Whereabouts;
206    use nostr_sdk::prelude::{Event, EventBuilder, EventId, FinalizeEvent, Keys, Kind, RelayUrl, Tag, Timestamp};
207
208    fn id(byte: u8) -> EventId {
209        EventId::from_byte_array([byte; 32])
210    }
211
212    fn e(note: EventId) -> Vec<String> {
213        vec!["e".to_string(), note.to_hex()]
214    }
215
216    fn tag(fields: &[&str]) -> Tag {
217        Tag::parse(fields.iter().copied()).unwrap()
218    }
219
220    /// A bookmark list with `tags`, written at `at`. Its content stands for
221    /// what is encrypted in a real one.
222    fn a_list(tags: Vec<Tag>, at: u64) -> Event {
223        EventBuilder::new(Kind::Bookmarks, "encrypted")
224            .tags(tags)
225            .custom_created_at(Timestamp::from_secs(at))
226            .finalize(&Keys::generate())
227            .unwrap()
228    }
229
230    fn fields(tags: &[Tag]) -> Vec<Vec<String>> {
231        tags.iter().map(|tag| tag.as_slice().to_vec()).collect()
232    }
233
234    #[test]
235    fn what_a_list_keeps_to_itself_is_tags_as_compact_json() {
236        // As Amethyst writes it: no spaces, a relay after the id or not.
237        let json = format!(r#"[["e","{}"],["e","{}","wss://relay.example.com/"],["a","30023:abc:post"]]"#, id(1), id(2));
238        let tags = decode(&json).unwrap();
239        assert_eq!(tags.len(), 3);
240        assert_eq!(tags[1], ["e", &id(2).to_hex(), "wss://relay.example.com/"]);
241        assert_eq!(encode(&tags), json, "and it is written as it was read");
242
243        assert_eq!(decode("[]"), Ok(PrivateTags::new()));
244        // What isn't tags is refused, without a word of it in the reason.
245        for not_tags in ["", "{}", "[1]", r#"[["e",1]]"#, r#"["secret words"]"#] {
246            let error = decode(not_tags).unwrap_err();
247            assert!(!error.contains("secret"), "{error}");
248        }
249    }
250
251    #[test]
252    fn only_a_note_the_list_keeps_to_itself_is_bookmarked() {
253        // The first is in the list for anyone to read, where other clients
254        // keep bookmarks; the second is kept private.
255        let public = a_list(vec![Tag::event(id(1)), tag(&["t", "nostr"])], 100);
256        let private =
257            vec![e(id(2)), vec!["a".into(), "30023:abc:post".into()], vec!["e".into()], vec!["e".into(), "no id".into()]];
258        let bookmarks = Bookmarks::new(Some(public), private);
259        assert!(!bookmarks.has(&id(1)));
260        assert!(bookmarks.has(&id(2)));
261        assert_eq!(bookmarks.count(), 1);
262        assert_eq!(bookmarks.notes(), [id(2)]);
263
264        let none = Bookmarks::default();
265        assert!(!none.has(&id(1)));
266        assert_eq!(none.list(), None);
267    }
268
269    #[test]
270    fn the_notes_are_listed_from_the_last_bookmarked_each_once() {
271        let article = vec!["a".to_string(), "30023:abc:post".to_string()];
272        let link = vec!["r".to_string(), "https://example.com".to_string()];
273        let public = a_list(vec![Tag::event(id(1)), tag(&["t", "nostr"]), tag(&["a", "30023:abc:other"])], 100);
274        let bookmarks = Bookmarks::new(Some(public), vec![e(id(3)), article, e(id(4)), link, e(id(2)), e(id(3))]);
275
276        assert_eq!(bookmarks.notes(), [id(2), id(4), id(3)], "a note named twice is where it was named first");
277        // An article and a link: what the list says to anyone is not counted.
278        assert_eq!(bookmarks.others(), 2);
279
280        let none = Bookmarks::default();
281        assert!(none.notes().is_empty());
282        assert_eq!(none.others(), 0);
283    }
284
285    #[test]
286    fn a_bookmark_is_added_to_what_is_kept_private_after_the_others() {
287        let tags = vec![Tag::event(id(1)), tag(&["title", "Mine"])];
288        let private = vec![e(id(2)), vec!["t".to_string(), "nostr".to_string()]];
289        let bookmarks = Bookmarks::new(Some(a_list(tags, 100)), private.clone());
290
291        let changed = bookmarks.changed(id(3), None, true).unwrap();
292        assert_eq!(changed, [private[0].clone(), private[1].clone(), e(id(3))]);
293
294        // With where the note is, for whoever reads the list.
295        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
296        let hinted = bookmarks.changed(id(3), Some(&relay), true).unwrap();
297        assert_eq!(hinted.last().unwrap(), &["e".to_string(), id(3).to_hex(), relay.to_string()]);
298
299        // Bookmarked already: nothing to change.
300        assert!(bookmarks.changed(id(2), None, true).is_none());
301        // In the list for anyone to read is not bookmarked here: it is
302        // kept private as any other note is.
303        assert_eq!(bookmarks.changed(id(1), None, true).unwrap().last(), Some(&e(id(1))));
304    }
305
306    #[test]
307    fn a_bookmark_says_where_its_note_is_when_it_does() {
308        let author = Keys::generate().public_key();
309        let relay = "wss://relay.example.com";
310        let private = vec![
311            e(id(1)),
312            vec!["e".into(), id(2).to_hex(), relay.into()],
313            // The author alone, with no relay before it.
314            vec!["e".into(), id(3).to_hex(), author.to_hex()],
315            vec!["e".into(), id(4).to_hex(), "not a relay".into(), "not a key".into()],
316            // Named twice: the one that says where is the one that counts.
317            e(id(5)),
318            vec!["e".into(), id(5).to_hex(), relay.into(), author.to_hex()],
319        ];
320        let bookmarks = Bookmarks::new(None, private);
321        let relay = RelayUrl::parse(relay).unwrap();
322
323        assert_eq!(bookmarks.whereabouts(&id(1)), Whereabouts::default());
324        assert_eq!(bookmarks.whereabouts(&id(2)), Whereabouts { author: None, relay: Some(relay.clone()) });
325        assert_eq!(bookmarks.whereabouts(&id(3)), Whereabouts { author: Some(author), relay: None });
326        assert_eq!(bookmarks.whereabouts(&id(4)), Whereabouts::default());
327        assert_eq!(bookmarks.whereabouts(&id(5)), Whereabouts { author: Some(author), relay: Some(relay) });
328        assert_eq!(bookmarks.whereabouts(&id(6)), Whereabouts::default(), "not bookmarked");
329    }
330
331    #[test]
332    fn the_first_bookmark_of_an_account_with_no_list_is_a_list_of_one() {
333        assert_eq!(Bookmarks::default().changed(id(1), None, true), Some(vec![e(id(1))]));
334        assert!(Bookmarks::default().changed(id(1), None, false).is_none(), "and there is nothing to take off");
335    }
336
337    #[test]
338    fn taking_a_bookmark_off_takes_the_note_out_of_what_is_kept_private_and_nothing_else() {
339        let hinted = vec!["e".to_string(), id(2).to_hex(), "wss://relay.example.com".to_string()];
340        let link = vec!["r".to_string(), "https://example.com".to_string()];
341        let private = vec![e(id(1)), hinted, e(id(3)), link, e(id(2))];
342        let bookmarks = Bookmarks::new(Some(a_list(vec![Tag::event(id(4))], 100)), private.clone());
343
344        // Named twice, once with a relay: both go.
345        assert_eq!(bookmarks.changed(id(2), None, false).unwrap(), [private[0].clone(), private[2].clone(), private[3].clone()]);
346        assert_eq!(bookmarks.changed(id(3), None, false).unwrap().len(), 4);
347
348        // Not bookmarked, or only in the list for anyone to read: nothing
349        // to change.
350        assert!(bookmarks.changed(id(5), None, false).is_none());
351        assert!(bookmarks.changed(id(4), None, false).is_none());
352    }
353
354    #[test]
355    fn a_changed_list_is_a_newer_bookmark_list_with_the_tags_of_the_one_it_replaces() {
356        let tags = vec![Tag::event(id(1)), tag(&["title", "Mine"]), tag(&["client", "Amethyst"])];
357        let earlier = a_list(tags.clone(), 1_000);
358        let build = |earlier: Option<&Event>, now: u64| {
359            list(earlier, "kept private".to_string(), Timestamp::from_secs(now)).finalize(&Keys::generate()).unwrap()
360        };
361        let changed = build(Some(&earlier), 2_000);
362        assert_eq!(changed.kind, Kind::Bookmarks);
363        assert_eq!(changed.kind.as_u16(), 10_003);
364        assert_eq!(changed.content, "kept private");
365        assert_eq!(fields(&changed.tags.to_vec()), fields(&tags), "what it says to anyone is as it was");
366        assert_eq!(changed.created_at.as_secs(), 2_000);
367
368        // A list that claims to be from later is still replaced.
369        assert_eq!(build(Some(&earlier), 500).created_at.as_secs(), 1_001);
370        // The first list says nothing to anyone.
371        let first = build(None, 500);
372        assert!(first.tags.is_empty());
373        assert_eq!(first.created_at.as_secs(), 500);
374    }
375}