Skip to main content

cosmic_applet_avestruz/nostr/
thread.rs

1// SPDX-License-Identifier: MIT
2
3//! A conversation: a note, what it answers, and what answers it.
4//!
5//! A thread is opened for one note, the *focused* one, and gathers the other
6//! notes of its conversation as they are found: in the event store first,
7//! on the relays after. However many of them are known, they are shown as
8//! one list, in reading order: every note under the one it answers, and the
9//! answers to one note oldest first.
10//!
11//! Notes written in the order of their numbers, each answering the one
12//! its arrow comes from:
13//!
14//! ```mermaid
15//! flowchart TD
16//!     n1["1: the note that started it"] --> n2["2"]
17//!     n1 --> n4["4"]
18//!     n2 --> n3["3"]
19//!     n2 --> n5["5"]
20//!     n4 --> n6["6"]
21//! ```
22//!
23//! are read as this list, each set in by how many answers deep it is:
24//!
25//! | Row | Note | Depth |
26//! |---|---|---|
27//! | 1 | 1 | 0 |
28//! | 2 | 2 | 1 |
29//! | 3 | 3 | 2 |
30//! | 4 | 5 | 2 |
31//! | 5 | 4 | 1 |
32//! | 6 | 6 | 2 |
33//!
34//! A note whose parent is not among the notes known goes under the root
35//! of its conversation, if that is known, and to the top if not. The
36//! order is the same however the notes arrived: the list is put in order
37//! anew each time notes are added ([`Thread::merge`]).
38//!
39//! Where a thread's notes come from, and which relays are asked, is in
40//! [`crate::guide::flows`].
41
42use std::collections::{HashMap, HashSet};
43
44use nostr_sdk::prelude::{EventId, PublicKey};
45
46use crate::nostr::models::Note;
47
48/// One note of a thread, and how many notes up the conversation starts.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct ThreadRow {
51    pub note: Note,
52    /// How many answers deep the note is: 0 for one that answers nothing
53    /// the thread knows.
54    pub depth: usize,
55}
56
57/// The notes of one conversation, in reading order.
58#[derive(Debug)]
59pub struct Thread {
60    focused: EventId,
61    rows: Vec<ThreadRow>,
62}
63
64/// The order of the answers to one note: oldest first, and by id among
65/// notes of the same second, so the order is the same however they arrived.
66fn reading_order(note: &Note) -> (u64, EventId) {
67    (note.created_at, note.id)
68}
69
70/// `notes` in reading order: each under the note it answers.
71///
72/// A note whose parent isn't among them goes under the conversation's root
73/// if that is, since it is still part of what the root started. Failing
74/// both it stands at the top, among the notes that answer nothing.
75fn arrange(mut notes: HashMap<EventId, Note>) -> Vec<ThreadRow> {
76    let mut tops: Vec<EventId> = Vec::new();
77    let mut answers: HashMap<EventId, Vec<EventId>> = HashMap::new();
78    for note in notes.values() {
79        let under = note
80            .reply_to
81            .and_then(|reply| [reply.parent, reply.root].into_iter().find(|id| *id != note.id && notes.contains_key(id)));
82        match under {
83            Some(parent) => answers.entry(parent).or_default().push(note.id),
84            None => tops.push(note.id),
85        }
86    }
87    // Newest first, because they are taken from the end of a stack.
88    let newest_first = |ids: &mut Vec<EventId>| {
89        ids.sort_by_key(|id| std::cmp::Reverse(notes.get(id).map(reading_order)));
90    };
91    newest_first(&mut tops);
92    answers.values_mut().for_each(newest_first);
93
94    let mut rows = Vec::with_capacity(notes.len());
95    let mut next: Vec<(EventId, usize)> = tops.into_iter().map(|id| (id, 0)).collect();
96    while let Some((id, depth)) = next.pop() {
97        if let Some(below) = answers.remove(&id) {
98            next.extend(below.into_iter().map(|id| (id, depth + 1)));
99        }
100        if let Some(note) = notes.remove(&id) {
101            rows.push(ThreadRow { note, depth });
102        }
103    }
104    rows
105}
106
107impl Thread {
108    /// The thread of the note `focused`, which is all it holds if the note
109    /// is at hand, and nothing if not.
110    pub fn new(focused: EventId, note: Option<Note>) -> Self {
111        let rows = note.filter(|note| note.id == focused).map(|note| ThreadRow { note, depth: 0 }).into_iter().collect();
112        Self { focused, rows }
113    }
114
115    /// The note the thread was opened for.
116    pub fn focused(&self) -> EventId {
117        self.focused
118    }
119
120    /// The notes, in reading order.
121    pub fn rows(&self) -> &[ThreadRow] {
122        &self.rows
123    }
124
125    /// Whether the note `id` is one of the thread's.
126    pub fn contains(&self, id: EventId) -> bool {
127        self.rows.iter().any(|row| row.note.id == id)
128    }
129
130    /// Which row the focused note is, once it is known.
131    pub fn focused_row(&self) -> Option<usize> {
132        self.rows.iter().position(|row| row.note.id == self.focused)
133    }
134
135    /// Whether a note is known that answers the focused one.
136    pub fn has_replies(&self) -> bool {
137        self.rows.iter().any(|row| row.note.reply_to.is_some_and(|reply| reply.parent == self.focused))
138    }
139
140    /// Add `notes`, each where it belongs. One that is already here is
141    /// replaced: the same note, perhaps showing more of itself, or more of
142    /// the notes it quotes. Returns the people that the notes that were
143    /// new, or came with more of what they quote, are shown with: their
144    /// authors and those they mention, each once.
145    pub fn merge(&mut self, notes: impl IntoIterator<Item = Note>) -> Vec<PublicKey> {
146        let mut known: HashMap<EventId, Note> =
147            std::mem::take(&mut self.rows).into_iter().map(|row| (row.note.id, row.note)).collect();
148        let mut people = Vec::new();
149        let mut seen = HashSet::new();
150        for note in notes {
151            if known.get(&note.id).is_none_or(|known| known.quoted_count() < note.quoted_count()) {
152                people.extend(note.people().filter(|person| seen.insert(*person)));
153            }
154            known.insert(note.id, note);
155        }
156        self.rows = arrange(known);
157        people
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::Thread;
164    use crate::nostr::content;
165    use crate::nostr::models::{Note, ReplyTo};
166    use nostr_sdk::prelude::{EventId, Keys, Kind, PublicKey};
167
168    fn id(byte: u8) -> EventId {
169        EventId::from_byte_array([byte; 32])
170    }
171
172    /// The note `byte`, written at `created_at`, answering `parent` in the
173    /// conversation `root` started (0 for neither).
174    fn note(byte: u8, created_at: u64, root: u8, parent: u8, author: PublicKey) -> Note {
175        Note {
176            id: id(byte),
177            kind: Kind::TextNote,
178            author,
179            created_at,
180            content: content::parse(&format!("note {byte}"), 100),
181            reply_to: (root != 0).then(|| ReplyTo { root: id(root), parent: id(parent) }),
182            quoted: Vec::new(),
183        }
184    }
185
186    /// Each row as (note, depth).
187    fn shape(thread: &Thread) -> Vec<(u8, usize)> {
188        thread.rows().iter().map(|row| (row.note.id.as_bytes()[0], row.depth)).collect()
189    }
190
191    #[test]
192    fn every_note_sits_under_the_one_it_answers_oldest_answer_first() {
193        let a = Keys::generate().public_key();
194        let mut thread = Thread::new(id(3), None);
195        // 1 started it. 2 and 4 answer 1; 3 answers 2; 5 answers 3. They
196        // arrive in no order.
197        thread.merge([
198            note(5, 500, 1, 3, a),
199            note(4, 400, 1, 1, a),
200            note(1, 100, 0, 0, a),
201            note(3, 300, 1, 2, a),
202            note(2, 200, 1, 1, a),
203        ]);
204
205        assert_eq!(shape(&thread), [(1, 0), (2, 1), (3, 2), (5, 3), (4, 1)]);
206        assert_eq!(thread.focused_row(), Some(2));
207        assert!(thread.contains(id(5)) && !thread.contains(id(9)));
208        assert!(thread.has_replies());
209    }
210
211    #[test]
212    fn a_note_whose_parent_is_unknown_goes_under_the_root_or_else_to_the_top() {
213        let a = Keys::generate().public_key();
214        // 3 answers 2, which nobody has.
215        let mut thread = Thread::new(id(3), None);
216        thread.merge([note(3, 300, 1, 2, a), note(4, 400, 1, 3, a)]);
217        assert_eq!(shape(&thread), [(3, 0), (4, 1)], "neither parent nor root: at the top");
218
219        thread.merge([note(1, 100, 0, 0, a)]);
220        assert_eq!(shape(&thread), [(1, 0), (3, 1), (4, 2)], "the root is known: under it");
221
222        thread.merge([note(2, 200, 1, 1, a)]);
223        assert_eq!(shape(&thread), [(1, 0), (2, 1), (3, 2), (4, 3)], "the parent turned up");
224    }
225
226    #[test]
227    fn a_thread_starts_with_its_note_if_that_is_at_hand() {
228        let a = Keys::generate().public_key();
229        let thread = Thread::new(id(2), Some(note(2, 200, 1, 1, a)));
230        assert_eq!(shape(&thread), [(2, 0)]);
231        assert_eq!(thread.focused(), id(2));
232        assert!(!thread.has_replies());
233
234        let thread = Thread::new(id(2), None);
235        assert!(thread.rows().is_empty());
236        assert_eq!(thread.focused_row(), None);
237
238        assert!(Thread::new(id(2), Some(note(9, 900, 0, 0, a))).rows().is_empty(), "another note is not its start");
239    }
240
241    #[test]
242    fn merging_replaces_a_known_note_and_reports_only_the_people_of_new_ones() {
243        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
244        let mut thread = Thread::new(id(1), Some(note(1, 100, 0, 0, a)));
245
246        let mut fuller = note(1, 100, 0, 0, a);
247        fuller.content = content::parse("all of note 1", 100);
248        let people = thread.merge([fuller.clone(), note(2, 200, 1, 1, b), note(3, 300, 1, 1, b)]);
249
250        assert_eq!(people, [b], "the author of the new notes, once");
251        assert_eq!(thread.rows()[0].note, fuller);
252        assert_eq!(shape(&thread), [(1, 0), (2, 1), (3, 1)]);
253
254        // A known note that comes again with a note it quotes: whoever
255        // wrote that one is new to the thread.
256        let c = Keys::generate().public_key();
257        let mut quoting = fuller.clone();
258        quoting.quoted = vec![note(9, 50, 0, 0, c)];
259        assert_eq!(thread.merge([quoting.clone(), note(2, 200, 1, 1, b)]), [a, c]);
260        assert_eq!(thread.rows()[0].note, quoting);
261    }
262
263    #[test]
264    fn answers_of_the_same_second_keep_one_order() {
265        let a = Keys::generate().public_key();
266        let mut one_way = Thread::new(id(1), None);
267        one_way.merge([note(1, 100, 0, 0, a), note(2, 200, 1, 1, a), note(3, 200, 1, 1, a)]);
268        let mut another = Thread::new(id(1), None);
269        another.merge([note(3, 200, 1, 1, a), note(2, 200, 1, 1, a), note(1, 100, 0, 0, a)]);
270        assert_eq!(shape(&one_way), shape(&another));
271        assert_eq!(shape(&one_way), [(1, 0), (2, 1), (3, 1)]);
272    }
273}