Skip to main content

cosmic_applet_avestruz/nostr/
notifications.rs

1// SPDX-License-Identifier: MIT
2
3//! What others did that concerns the account: answered it, named it,
4//! quoted it, reacted to a note of its own, passed one on, zapped it.
5//!
6//! All of these are events that name the account in a `p` tag, which is
7//! what the relays are asked for: notes and comments (kinds 1 and 1111),
8//! reactions (kind 7, NIP-25), reposts (kinds 6 and 16, NIP-18) and zap
9//! receipts (kind 9735, NIP-57). What each one is, is read off the event
10//! and off the note it is about, where that is at hand (see [`read`]):
11//!
12//! ```mermaid
13//! flowchart TD
14//!     event["An event that names the account"] --> own{"Did the account do it itself?"}
15//!     own -->|"yes"| nothing["Nothing to tell"]
16//!     own -->|"no"| kind{"Its kind"}
17//!     kind -->|"a note, a comment"| said{"What it says"}
18//!     said -->|"names the account in its text"| mention["Mentioned you"]
19//!     said -->|"answers a note of the account's"| reply["Replied to you"]
20//!     said -->|"answers someone else"| thread["Replied in a thread you are in"]
21//!     said -->|"quotes a note of the account's"| quote["Quoted you"]
22//!     said -->|"none of these"| mention
23//!     kind -->|"a reaction, to the account last of all"| reaction["Reacted to your note"]
24//!     kind -->|"a repost"| repost["Reposted your note"]
25//!     kind -->|"a zap receipt"| zap["Zapped you: shown once the account's wallet service is known to have signed it"]
26//! ```
27//!
28//! A zap receipt says who paid and how much, and anyone can write one. It
29//! counts when it is signed by the key the account's own Lightning
30//! address answers with (NIP-57): until that key is known, and for an
31//! account with no such address, no zap is told of. See
32//! [`Notifications::set_zapper`].
33//!
34//! Which of them are new is one moment, kept for the account on this
35//! machine: what was written after the notifications were last looked at
36//! (see [`Notifications::unread`]).
37
38use std::collections::{HashMap, HashSet};
39
40use nostr_sdk::prelude::{Event, EventId, Filter, Kind, PublicKey, Timestamp};
41
42use crate::helpers::truncate_chars;
43use crate::nostr::engagement::{Reaction, zap_request};
44use crate::nostr::models::Note;
45use crate::nostr::zap::invoice_millisats;
46
47/// The kinds of event that tell the account of something.
48const NOTIFICATION_KINDS: [Kind; 6] =
49    [Kind::TextNote, Kind::Comment, Kind::Reaction, Kind::Repost, Kind::GenericRepost, Kind::ZapReceipt];
50
51/// How many events are asked for at a time.
52pub const NOTIFICATIONS_PAGE: usize = 100;
53
54/// How much of the note something is about is shown under it, and how
55/// much of what was said with a zap, in characters.
56const PREVIEW_MAX_CHARS: usize = 140;
57const COMMENT_MAX_CHARS: usize = 140;
58
59/// What someone did.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum What {
62    /// Answered a note of the account's.
63    Reply,
64    /// Answered someone else, in a conversation the account is named in.
65    ThreadReply,
66    /// Named the account in what they wrote.
67    Mention,
68    /// Quoted a note of the account's.
69    Quote,
70    /// Reacted to a note of the account's: with a like, or an emoji.
71    Reaction(Reaction),
72    /// Passed a note of the account's on.
73    Repost,
74    /// Zapped the account, or a note of its own: so many sats, with what
75    /// was said along with them, as the receipt signed by `issuer` has it.
76    Zap { sats: u64, comment: String, issuer: PublicKey },
77}
78
79/// Which of the notifications a list shows.
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
81pub enum Tab {
82    /// Every one.
83    #[default]
84    All,
85    /// What was written to the account, or about it: replies, mentions
86    /// and quotes.
87    Mentions,
88    /// What was made of its notes: reactions and reposts.
89    Reactions,
90    /// What it was paid.
91    Zaps,
92}
93
94impl Tab {
95    /// Every tab, in the order they are offered.
96    pub const ALL: [Self; 4] = [Self::All, Self::Mentions, Self::Reactions, Self::Zaps];
97}
98
99/// Where in the list of all notifications the ones each tab shows are.
100#[derive(Debug, Default)]
101struct Listed {
102    all: Vec<usize>,
103    mentions: Vec<usize>,
104    reactions: Vec<usize>,
105    zaps: Vec<usize>,
106}
107
108impl Listed {
109    /// The ones `tab` shows.
110    fn of(&self, tab: Tab) -> &[usize] {
111        match tab {
112            Tab::All => &self.all,
113            Tab::Mentions => &self.mentions,
114            Tab::Reactions => &self.reactions,
115            Tab::Zaps => &self.zaps,
116        }
117    }
118
119    /// The ones `tab` shows, to add to.
120    fn of_mut(&mut self, tab: Tab) -> &mut Vec<usize> {
121        match tab {
122            Tab::All => &mut self.all,
123            Tab::Mentions => &mut self.mentions,
124            Tab::Reactions => &mut self.reactions,
125            Tab::Zaps => &mut self.zaps,
126        }
127    }
128}
129
130impl What {
131    /// The tab this is under, beside the one everything is under.
132    pub fn tab(&self) -> Tab {
133        match self {
134            Self::Reply | Self::ThreadReply | Self::Mention | Self::Quote => Tab::Mentions,
135            Self::Reaction(_) | Self::Repost => Tab::Reactions,
136            Self::Zap { .. } => Tab::Zaps,
137        }
138    }
139}
140
141/// One thing the account is told of.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Notification {
144    /// The event that says so.
145    pub id: EventId,
146    /// When it says it was written, in seconds since the Unix epoch.
147    pub at: u64,
148    /// Who did it.
149    pub who: PublicKey,
150    pub what: What,
151    /// The note it is, when it is one: a reply, a mention, a quote.
152    pub note: Option<Note>,
153    /// The note it is about: the one answered, quoted, reacted to, passed
154    /// on or zapped.
155    pub about: Option<EventId>,
156    /// The start of what that note says, if it was at hand.
157    pub preview: Option<String>,
158}
159
160/// The question that finds what names `account`: so many events at most,
161/// written after `since` and at or before `until`, where those are given.
162pub fn filter(account: PublicKey, since: Option<u64>, until: Option<u64>, limit: usize) -> Filter {
163    let mut filter = Filter::new().kinds(NOTIFICATION_KINDS).pubkey(account).limit(limit);
164    if let Some(since) = since {
165        filter = filter.since(Timestamp::from_secs(since.saturating_add(1)));
166    }
167    if let Some(until) = until {
168        filter = filter.until(Timestamp::from_secs(until));
169    }
170    filter
171}
172
173/// The note `event` is about, which says what it tells of: the note a
174/// note answers, or else the first it quotes; the note a reaction is to,
175/// which is the last it names (NIP-25); the one a repost passes on or a
176/// zap receipt is for, which is the first.
177pub fn about(event: &Event) -> Option<EventId> {
178    match event.kind {
179        Kind::TextNote | Kind::Comment => {
180            let note = Note::from(event.clone());
181            note.reply_to.map(|reply| reply.parent).or_else(|| note.content.quotes.first().map(|quote| quote.id))
182        }
183        Kind::Reaction => event.tags.event_ids().last(),
184        Kind::Repost | Kind::GenericRepost | Kind::ZapReceipt => event.tags.event_ids().next(),
185        _ => None,
186    }
187}
188
189/// The start of what `note` says, on one line: what stands for it where
190/// there is no room for it.
191fn preview(note: &Note) -> String {
192    let said: String = note.content.segments.iter().map(|segment| segment.words(&|_| "@\u{2026}".to_string())).collect();
193    let said = said.split_whitespace().collect::<Vec<_>>().join(" ");
194    truncate_chars(&said, PREVIEW_MAX_CHARS).into_owned()
195}
196
197/// What `event` tells `account` of, if anything, with `at_hand` the notes
198/// such events are [`about`], as far as they were found.
199///
200/// Nothing, of what the account did itself, of an event that doesn't name
201/// it, and of what is about a note that is at hand and is somebody
202/// else's: a reaction to another's note in a conversation the account is
203/// named in is no news for it.
204pub fn read(event: &Event, account: PublicKey, at_hand: &HashMap<EventId, Note>) -> Option<Notification> {
205    if !event.tags.public_keys().any(|named| named == account) {
206        return None;
207    }
208    let about = about(event);
209    let target = about.and_then(|id| at_hand.get(&id));
210    let of_account = |note: &Note| note.author == account;
211    let (who, what, note) = match event.kind {
212        Kind::TextNote | Kind::Comment => {
213            let note = Note::from(event.clone());
214            let what = if note.content.mentions().any(|named| named == account) {
215                What::Mention
216            } else if note.reply_to.is_some() {
217                if target.is_some_and(of_account) { What::Reply } else { What::ThreadReply }
218            } else if !note.content.quotes.is_empty() && target.is_some_and(of_account) {
219                What::Quote
220            } else {
221                What::Mention
222            };
223            (event.pubkey, what, Some(note))
224        }
225        Kind::Reaction => {
226            // To the account, and not only in a conversation it is in:
227            // the one reacted to is named last. A downvote is not told.
228            let to_account = event.tags.public_keys().last() == Some(account);
229            if !to_account || event.content == "-" || target.is_some_and(|note| !of_account(note)) {
230                return None;
231            }
232            (event.pubkey, What::Reaction(Reaction::said(&event.content)), None)
233        }
234        Kind::Repost | Kind::GenericRepost => {
235            if target.is_some_and(|note| !of_account(note)) {
236                return None;
237            }
238            (event.pubkey, What::Repost, None)
239        }
240        Kind::ZapReceipt => {
241            let request = zap_request(event)?;
242            let invoice = event.tags.iter().find(|tag| tag.kind() == "bolt11")?.content()?;
243            let sats = invoice_millisats(invoice)? / 1000;
244            if sats == 0 {
245                return None;
246            }
247            let comment = truncate_chars(request.content.trim(), COMMENT_MAX_CHARS).into_owned();
248            (request.pubkey, What::Zap { sats, comment, issuer: event.pubkey }, None)
249        }
250        _ => return None,
251    };
252    if who == account {
253        return None;
254    }
255    Some(Notification { id: event.id, at: event.created_at.as_secs(), who, what, note, about, preview: target.map(preview) })
256}
257
258/// What the account is told of, newest first, and which of it each tab
259/// shows.
260#[derive(Debug, Default)]
261pub struct Notifications {
262    all: Vec<Notification>,
263    ids: HashSet<EventId>,
264    /// Where in `all` the ones each tab shows are.
265    listed: Listed,
266    /// The key the account's wallet service signs zap receipts with, once
267    /// it is known.
268    zapper: Option<PublicKey>,
269}
270
271impl Notifications {
272    /// Whether `notification` is shown: all are, but a zap whose receipt
273    /// was not signed by the account's wallet service, as far as that is
274    /// known.
275    fn shown(&self, notification: &Notification) -> bool {
276        match &notification.what {
277            What::Zap { issuer, .. } => self.zapper == Some(*issuer),
278            _ => true,
279        }
280    }
281
282    /// Work out again which notifications each tab shows.
283    fn arrange(&mut self) {
284        let mut listed = Listed::default();
285        for (at, notification) in self.all.iter().enumerate() {
286            if self.shown(notification) {
287                listed.of_mut(Tab::All).push(at);
288                listed.of_mut(notification.what.tab()).push(at);
289            }
290        }
291        self.listed = listed;
292    }
293
294    /// Add `found` to what is known, each once. Returns those that are
295    /// news: not known before.
296    pub fn merge(&mut self, found: Vec<Notification>) -> Vec<EventId> {
297        let new: Vec<Notification> = found.into_iter().filter(|notification| self.ids.insert(notification.id)).collect();
298        let ids = new.iter().map(|notification| notification.id).collect();
299        self.all.extend(new);
300        self.all.sort_by(|a, b| b.at.cmp(&a.at).then(a.id.cmp(&b.id)));
301        self.arrange();
302        ids
303    }
304
305    /// Let go of what was written before `oldest`.
306    pub fn forget_before(&mut self, oldest: u64) {
307        self.all.retain(|notification| notification.at >= oldest);
308        self.ids = self.all.iter().map(|notification| notification.id).collect();
309        self.arrange();
310    }
311
312    /// The key the account's wallet service signs zap receipts with is
313    /// `zapper`: the zaps it signed show from now on, and no others.
314    pub fn set_zapper(&mut self, zapper: Option<PublicKey>) {
315        self.zapper = zapper;
316        self.arrange();
317    }
318
319    /// Where the notifications `tab` shows are, newest first: what
320    /// [`Self::get`] is asked with.
321    pub fn listed(&self, tab: Tab) -> &[usize] {
322        self.listed.of(tab)
323    }
324
325    /// The notification at `place`.
326    pub fn get(&self, place: usize) -> Option<&Notification> {
327        self.all.get(place)
328    }
329
330    /// The notes among them: the replies, mentions and quotes.
331    pub fn notes(&self) -> impl Iterator<Item = &Note> + '_ {
332        self.all.iter().filter_map(|notification| notification.note.as_ref())
333    }
334
335    /// When the newest of them was written, shown or not.
336    pub fn newest(&self) -> Option<u64> {
337        self.all.first().map(|notification| notification.at)
338    }
339
340    /// Whether `notification`, one of those shown, is new to someone who
341    /// last looked at `seen_at`.
342    pub fn is_new(notification: &Notification, seen_at: u64) -> bool {
343        notification.at > seen_at
344    }
345
346    /// How many of those shown were written after `seen_at`.
347    pub fn unread(&self, seen_at: u64) -> usize {
348        // Newest first: the new ones are the first so many.
349        self.listed(Tab::All).iter().take_while(|place| self.get(**place).is_some_and(|n| Self::is_new(n, seen_at))).count()
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::{Notification, Notifications, Tab, What, about, filter, read};
356    use crate::nostr::engagement::Reaction;
357    use crate::nostr::models::Note;
358    use nostr_sdk::prelude::{Event, EventBuilder, EventId, FinalizeEvent, Keys, Kind, PublicKey, Tag, Timestamp, ToBech32};
359    use std::collections::HashMap;
360
361    /// An event of `kind` saying `content`, with `tags`, signed by `keys`
362    /// at the moment `at`.
363    fn event(kind: Kind, content: &str, tags: Vec<Tag>, keys: &Keys, at: u64) -> Event {
364        EventBuilder::new(kind, content).tags(tags).custom_created_at(Timestamp::from_secs(at)).finalize(keys).unwrap()
365    }
366
367    /// A tag `name` with `values`.
368    fn tag(name: &str, values: &[&str]) -> Tag {
369        Tag::parse(std::iter::once(name).chain(values.iter().copied())).unwrap()
370    }
371
372    /// The notes of `events`, by id: what is at hand.
373    fn at_hand(events: &[&Event]) -> HashMap<EventId, Note> {
374        events.iter().map(|event| (event.id, Note::from((*event).clone()))).collect()
375    }
376
377    /// A receipt, signed by `wallet`, of `payer` zapping `recipient` what
378    /// `invoice` asks for, for the note `note`, saying `comment`.
379    fn receipt(wallet: &Keys, payer: &Keys, recipient: PublicKey, note: Option<EventId>, invoice: &str, comment: &str) -> Event {
380        let request = event(Kind::ZapRequest, comment, vec![Tag::public_key(recipient)], payer, 90);
381        let mut tags = vec![Tag::public_key(recipient), tag("bolt11", &[invoice]), tag("description", &[&request.as_json()])];
382        tags.extend(note.map(Tag::event));
383        event(Kind::ZapReceipt, "", tags, wallet, 100)
384    }
385
386    #[test]
387    fn what_a_note_tells_is_read_off_what_it_says_and_what_it_answers() {
388        let (me, them, other) = (Keys::generate(), Keys::generate(), Keys::generate());
389        let mine = event(Kind::TextNote, "what I said", vec![], &me, 10);
390        let theirs = event(Kind::TextNote, "what someone else said", vec![Tag::public_key(me.public_key())], &other, 20);
391        let known = at_hand(&[&mine, &theirs]);
392        let naming = |tags: Vec<Tag>| [vec![Tag::public_key(me.public_key())], tags].concat();
393        let told = |event: &Event| read(event, me.public_key(), &known).map(|told| told.what);
394
395        // An answer to the account's note; to someone else's; to a note
396        // that is not at hand, which is not known to be the account's.
397        let reply = event(Kind::TextNote, "I agree", naming(vec![Tag::event(mine.id)]), &them, 30);
398        assert_eq!(told(&reply), Some(What::Reply));
399        let in_thread = event(Kind::TextNote, "so do I", naming(vec![Tag::event(theirs.id)]), &them, 31);
400        assert_eq!(told(&in_thread), Some(What::ThreadReply));
401        let unknown = event(Kind::TextNote, "and I", naming(vec![Tag::event(EventId::from_byte_array([9; 32]))]), &them, 32);
402        assert_eq!(told(&unknown), Some(What::ThreadReply));
403
404        // Named in the text, answering or not.
405        let npub = me.public_key().to_bech32().unwrap();
406        let mention = event(Kind::TextNote, &format!("ask nostr:{npub}"), naming(vec![]), &them, 33);
407        assert_eq!(told(&mention), Some(What::Mention));
408        let both = event(Kind::TextNote, &format!("nostr:{npub} look"), naming(vec![Tag::event(theirs.id)]), &them, 34);
409        assert_eq!(told(&both), Some(What::Mention));
410
411        // A quote of the account's note; of another's, which only names it.
412        let quoting = |id: EventId| format!("this: nostr:{}", id.to_bech32().unwrap());
413        let quote = event(Kind::TextNote, &quoting(mine.id), naming(vec![]), &them, 35);
414        assert_eq!(told(&quote), Some(What::Quote));
415        assert_eq!(about(&quote), Some(mine.id));
416        let cited = event(Kind::TextNote, &quoting(theirs.id), naming(vec![]), &them, 36);
417        assert_eq!(told(&cited), Some(What::Mention));
418
419        // The note is there to show, with the start of what it answers.
420        let read = read(&reply, me.public_key(), &known).unwrap();
421        assert_eq!((read.id, read.at, read.who), (reply.id, 30, them.public_key()));
422        assert_eq!(read.note.map(|note| note.id), Some(reply.id));
423        assert_eq!((read.about, read.preview.as_deref()), (Some(mine.id), Some("what I said")));
424
425        // Nothing of what the account wrote itself, or of what doesn't
426        // name it.
427        let own = event(Kind::TextNote, "to myself", naming(vec![Tag::event(mine.id)]), &me, 37);
428        assert_eq!(told(&own), None);
429        let elsewhere = event(Kind::TextNote, "I agree", vec![Tag::event(mine.id)], &them, 38);
430        assert_eq!(told(&elsewhere), None);
431    }
432
433    #[test]
434    fn a_reaction_or_a_repost_is_told_when_it_is_to_a_note_of_the_accounts() {
435        let (me, them, other) = (Keys::generate(), Keys::generate(), Keys::generate());
436        let mine = event(Kind::TextNote, "what I said\n\nat some length", vec![], &me, 10);
437        let theirs = event(Kind::TextNote, "what someone else said", vec![], &other, 20);
438        let known = at_hand(&[&mine, &theirs]);
439        let told = |event: &Event| read(event, me.public_key(), &known);
440        let (to_me, to_other) = (Tag::public_key(me.public_key()), Tag::public_key(other.public_key()));
441
442        let liked = event(Kind::Reaction, "+", vec![Tag::event(mine.id), to_me.clone()], &them, 30);
443        let read = told(&liked).unwrap();
444        assert_eq!(read.what, What::Reaction(Reaction::Like));
445        assert_eq!((read.about, read.preview.as_deref()), (Some(mine.id), Some("what I said at some length")));
446        assert!(read.note.is_none());
447        let clown = event(Kind::Reaction, "🤡", vec![Tag::event(mine.id), to_me.clone()], &them, 31);
448        assert_eq!(told(&clown).map(|told| told.what), Some(What::Reaction(Reaction::Emoji("🤡".into()))));
449
450        // To a note that is not at hand: told, with nothing to show of it.
451        let unknown = event(Kind::Reaction, "+", vec![Tag::event(EventId::from_byte_array([9; 32])), to_me.clone()], &them, 32);
452        assert_eq!(told(&unknown).map(|told| told.preview), Some(None));
453
454        // Not a downvote; not a reaction to another in a conversation
455        // the account is named in; not one to another's note.
456        let down = event(Kind::Reaction, "-", vec![Tag::event(mine.id), to_me.clone()], &them, 33);
457        assert!(told(&down).is_none());
458        let beside = event(Kind::Reaction, "+", vec![Tag::event(mine.id), to_me.clone(), to_other], &them, 34);
459        assert!(told(&beside).is_none());
460        let to_theirs = event(Kind::Reaction, "+", vec![Tag::event(theirs.id), to_me.clone()], &them, 35);
461        assert!(told(&to_theirs).is_none());
462
463        let repost = event(Kind::Repost, "", vec![Tag::event(mine.id), to_me.clone()], &them, 36);
464        assert_eq!(told(&repost).map(|told| (told.what, told.about)), Some((What::Repost, Some(mine.id))));
465        let of_theirs = event(Kind::Repost, "", vec![Tag::event(theirs.id), to_me], &them, 37);
466        assert!(told(&of_theirs).is_none());
467    }
468
469    #[test]
470    fn a_zap_is_told_as_its_receipt_has_it_and_shown_when_the_accounts_wallet_signed_it() {
471        let (me, payer, wallet, forger) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate());
472        let note = EventId::from_byte_array([4; 32]);
473        let told = |event: &Event| read(event, me.public_key(), &HashMap::new());
474
475        let zapped = receipt(&wallet, &payer, me.public_key(), Some(note), "lnbc210n1pjq9xyz", " thanks ");
476        let read = told(&zapped).unwrap();
477        assert_eq!((read.who, read.about), (payer.public_key(), Some(note)));
478        assert_eq!(read.what, What::Zap { sats: 21, comment: "thanks".into(), issuer: wallet.public_key() });
479
480        // Not one with no amount, with no request, or with a request
481        // somebody else signed; not what the account paid itself.
482        assert!(told(&receipt(&wallet, &payer, me.public_key(), None, "lnbc1pjq9xyz", "")).is_none());
483        let bare =
484            event(Kind::ZapReceipt, "", vec![Tag::public_key(me.public_key()), tag("bolt11", &["lnbc210n1pjq9xyz"])], &wallet, 1);
485        assert!(told(&bare).is_none());
486        let request = event(Kind::ZapRequest, "", vec![Tag::public_key(me.public_key())], &payer, 90);
487        let mut altered = serde_json::from_str::<serde_json::Value>(&request.as_json()).unwrap();
488        altered["pubkey"] = forger.public_key().to_hex().into();
489        let tags = vec![
490            Tag::public_key(me.public_key()),
491            tag("bolt11", &["lnbc210n1pjq9xyz"]),
492            tag("description", &[&altered.to_string()]),
493        ];
494        assert!(told(&event(Kind::ZapReceipt, "", tags, &wallet, 1)).is_none());
495        assert!(told(&receipt(&wallet, &me, me.public_key(), None, "lnbc210n1pjq9xyz", "")).is_none());
496
497        // Shown once the wallet's key is known, and only what it signed.
498        let forged = receipt(&forger, &payer, me.public_key(), None, "lnbc2500u1pvjluez", "a fortune");
499        let mut notifications = Notifications::default();
500        notifications.merge([&zapped, &forged].into_iter().filter_map(told).collect());
501        assert!(notifications.listed(Tab::All).is_empty() && notifications.listed(Tab::Zaps).is_empty());
502        assert_eq!(notifications.unread(0), 0);
503        notifications.set_zapper(Some(wallet.public_key()));
504        let shown: Vec<EventId> =
505            notifications.listed(Tab::Zaps).iter().filter_map(|at| notifications.get(*at)).map(|n| n.id).collect();
506        assert_eq!(shown, [zapped.id]);
507        assert_eq!(notifications.unread(0), 1);
508    }
509
510    /// A notification of `what` by nobody in particular, written at `at`.
511    fn told(byte: u8, at: u64, what: What) -> Notification {
512        Notification {
513            id: EventId::from_byte_array([byte; 32]),
514            at,
515            who: Keys::generate().public_key(),
516            what,
517            note: None,
518            about: None,
519            preview: None,
520        }
521    }
522
523    #[test]
524    fn they_are_kept_newest_first_each_once_under_its_tab_and_the_new_ones_are_counted() {
525        let mut notifications = Notifications::default();
526        let like = What::Reaction(Reaction::Like);
527        let new = notifications.merge(vec![told(1, 10, What::Reply), told(2, 30, like.clone()), told(3, 20, What::Repost)]);
528        assert_eq!(new.len(), 3);
529        // Again, with one more: only that one is news.
530        let new = notifications.merge(vec![told(2, 30, like), told(4, 40, What::Mention)]);
531        assert_eq!(new, [EventId::from_byte_array([4; 32])]);
532
533        let ids = |notifications: &Notifications, tab: Tab| -> Vec<u8> {
534            notifications.listed(tab).iter().filter_map(|at| notifications.get(*at)).map(|n| n.id.as_bytes()[0]).collect()
535        };
536        assert_eq!(ids(&notifications, Tab::All), [4, 2, 3, 1]);
537        assert_eq!(ids(&notifications, Tab::Mentions), [4, 1]);
538        assert_eq!(ids(&notifications, Tab::Reactions), [2, 3]);
539        assert!(ids(&notifications, Tab::Zaps).is_empty());
540        assert_eq!(notifications.newest(), Some(40));
541
542        // New is what was written after the last look.
543        assert_eq!(notifications.unread(0), 4);
544        assert_eq!(notifications.unread(20), 2);
545        assert_eq!(notifications.unread(40), 0);
546
547        // What is older than a moment can be let go of, and is then news
548        // again when it comes back.
549        notifications.forget_before(20);
550        assert_eq!(ids(&notifications, Tab::All), [4, 2, 3]);
551        assert_eq!(ids(&notifications, Tab::Mentions), [4]);
552        assert_eq!(notifications.merge(vec![told(1, 10, What::Reply)]).len(), 1);
553    }
554
555    #[test]
556    fn the_question_names_the_account_and_the_time_it_is_about() {
557        let account = Keys::generate().public_key();
558        let asked = filter(account, Some(100), Some(200), 50);
559        assert_eq!(asked.limit, Some(50));
560        // After `since`, not at it: what was written then is known.
561        assert_eq!((asked.since, asked.until), (Some(Timestamp::from_secs(101)), Some(Timestamp::from_secs(200))));
562        assert_eq!(asked.kinds.map(|kinds| kinds.len()), Some(6));
563        let open = filter(account, None, None, 50);
564        assert_eq!((open.since, open.until), (None, None));
565    }
566}