1use 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
47const NOTIFICATION_KINDS: [Kind; 6] =
49 [Kind::TextNote, Kind::Comment, Kind::Reaction, Kind::Repost, Kind::GenericRepost, Kind::ZapReceipt];
50
51pub const NOTIFICATIONS_PAGE: usize = 100;
53
54const PREVIEW_MAX_CHARS: usize = 140;
57const COMMENT_MAX_CHARS: usize = 140;
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum What {
62 Reply,
64 ThreadReply,
66 Mention,
68 Quote,
70 Reaction(Reaction),
72 Repost,
74 Zap { sats: u64, comment: String, issuer: PublicKey },
77}
78
79#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
81pub enum Tab {
82 #[default]
84 All,
85 Mentions,
88 Reactions,
90 Zaps,
92}
93
94impl Tab {
95 pub const ALL: [Self; 4] = [Self::All, Self::Mentions, Self::Reactions, Self::Zaps];
97}
98
99#[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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Notification {
144 pub id: EventId,
146 pub at: u64,
148 pub who: PublicKey,
150 pub what: What,
151 pub note: Option<Note>,
153 pub about: Option<EventId>,
156 pub preview: Option<String>,
158}
159
160pub 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
173pub 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
189fn 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
197pub 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 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#[derive(Debug, Default)]
261pub struct Notifications {
262 all: Vec<Notification>,
263 ids: HashSet<EventId>,
264 listed: Listed,
266 zapper: Option<PublicKey>,
269}
270
271impl Notifications {
272 fn shown(&self, notification: &Notification) -> bool {
276 match ¬ification.what {
277 What::Zap { issuer, .. } => self.zapper == Some(*issuer),
278 _ => true,
279 }
280 }
281
282 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 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 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 pub fn set_zapper(&mut self, zapper: Option<PublicKey>) {
315 self.zapper = zapper;
316 self.arrange();
317 }
318
319 pub fn listed(&self, tab: Tab) -> &[usize] {
322 self.listed.of(tab)
323 }
324
325 pub fn get(&self, place: usize) -> Option<&Notification> {
327 self.all.get(place)
328 }
329
330 pub fn notes(&self) -> impl Iterator<Item = &Note> + '_ {
332 self.all.iter().filter_map(|notification| notification.note.as_ref())
333 }
334
335 pub fn newest(&self) -> Option<u64> {
337 self.all.first().map(|notification| notification.at)
338 }
339
340 pub fn is_new(notification: &Notification, seen_at: u64) -> bool {
343 notification.at > seen_at
344 }
345
346 pub fn unread(&self, seen_at: u64) -> usize {
348 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 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 fn tag(name: &str, values: &[&str]) -> Tag {
369 Tag::parse(std::iter::once(name).chain(values.iter().copied())).unwrap()
370 }
371
372 fn at_hand(events: &[&Event]) -> HashMap<EventId, Note> {
374 events.iter().map(|event| (event.id, Note::from((*event).clone()))).collect()
375 }
376
377 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 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 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 let quoting = |id: EventId| format!("this: nostr:{}", id.to_bech32().unwrap());
413 let quote = event(Kind::TextNote, "ing(mine.id), naming(vec![]), &them, 35);
414 assert_eq!(told("e), Some(What::Quote));
415 assert_eq!(about("e), Some(mine.id));
416 let cited = event(Kind::TextNote, "ing(theirs.id), naming(vec![]), &them, 36);
417 assert_eq!(told(&cited), Some(What::Mention));
418
419 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 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 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 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 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 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 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 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(¬ifications, Tab::All), [4, 2, 3, 1]);
537 assert_eq!(ids(¬ifications, Tab::Mentions), [4, 1]);
538 assert_eq!(ids(¬ifications, Tab::Reactions), [2, 3]);
539 assert!(ids(¬ifications, Tab::Zaps).is_empty());
540 assert_eq!(notifications.newest(), Some(40));
541
542 assert_eq!(notifications.unread(0), 4);
544 assert_eq!(notifications.unread(20), 2);
545 assert_eq!(notifications.unread(40), 0);
546
547 notifications.forget_before(20);
550 assert_eq!(ids(¬ifications, Tab::All), [4, 2, 3]);
551 assert_eq!(ids(¬ifications, 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 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}