1use std::collections::{HashMap, HashSet};
18
19use nostr_sdk::prelude::{Event, EventBuilder, EventId, IntoEventBuilder, Kind, PublicKey, RelayUrl, RepostBuilder, Tag};
20
21use crate::emoji;
22use crate::nostr::models::reply_to;
23use crate::nostr::zap::invoice_millisats;
24
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub enum Reaction {
28 Like,
30 Emoji(String),
32}
33
34impl Reaction {
35 pub fn said(content: &str) -> Self {
39 emoji::known(content.trim()).map_or(Self::Like, |emoji| Self::Emoji(emoji.to_string()))
40 }
41
42 pub fn content(&self) -> &str {
44 match self {
45 Self::Like => "+",
46 Self::Emoji(emoji) => emoji,
47 }
48 }
49}
50
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Engagement {
54 pub replies: usize,
56 pub reposts: usize,
58 pub reposted: bool,
60 pub likes: usize,
62 pub reaction: Option<Reaction>,
64 pub zap_sats: u64,
66}
67
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct Standing {
72 pub engagement: HashMap<EventId, Engagement>,
73 pub seen_on: HashMap<EventId, Vec<RelayUrl>>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum Mark {
80 React(Reaction),
82 Repost,
84}
85
86impl Engagement {
87 pub fn has(&self, mark: &Mark) -> bool {
90 match mark {
91 Mark::React(_) => self.reaction.is_some(),
92 Mark::Repost => self.reposted,
93 }
94 }
95
96 #[must_use]
99 pub fn with(mut self, mark: &Mark) -> Self {
100 if !self.has(mark) {
101 match mark {
102 Mark::React(reaction) => {
103 self.reaction = Some(reaction.clone());
104 self.likes += 1;
105 }
106 Mark::Repost => {
107 self.reposted = true;
108 self.reposts += 1;
109 }
110 }
111 }
112 self
113 }
114
115 #[must_use]
118 pub fn without(mut self, mark: &Mark) -> Self {
119 if self.has(mark) {
120 match mark {
121 Mark::React(_) => {
122 self.reaction = None;
123 self.likes = self.likes.saturating_sub(1);
124 }
125 Mark::Repost => {
126 self.reposted = false;
127 self.reposts = self.reposts.saturating_sub(1);
128 }
129 }
130 }
131 self
132 }
133}
134
135fn reaction_target(event: &Event) -> Option<EventId> {
138 if event.content == "-" {
139 return None;
140 }
141 event.tags.event_ids().last()
142}
143
144fn zap(event: &Event) -> Option<(EventId, u64)> {
151 let invoice = event.tags.iter().find(|tag| tag.kind() == "bolt11")?.content()?;
152 Some((event.tags.event_ids().next()?, invoice_millisats(invoice)?))
153}
154
155pub(crate) fn zap_request(receipt: &Event) -> Option<Event> {
158 let description = receipt.tags.iter().find(|tag| tag.kind() == "description")?.content()?;
159 let request = Event::from_json(description).ok()?;
160 (request.kind == Kind::ZapRequest && request.verify().is_ok()).then_some(request)
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum Left {
166 Reposts,
168 Reactions,
170 Zaps,
172}
173
174impl Left {
175 pub fn kinds(self) -> &'static [Kind] {
177 match self {
178 Self::Reposts => &[Kind::Repost, Kind::GenericRepost],
179 Self::Reactions => &[Kind::Reaction],
180 Self::Zaps => &[Kind::ZapReceipt],
181 }
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum Did {
188 Reposted,
190 Reacted(Reaction),
192 Zapped(u64),
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct Doer {
199 pub who: Option<PublicKey>,
202 pub did: Did,
203}
204
205pub fn who_did(events: impl IntoIterator<Item = Event>, note: EventId, what: Left) -> Vec<Doer> {
217 let mut by: HashMap<Option<PublicKey>, (u64, Did)> = HashMap::new();
219 for event in events.into_iter().filter(|event| what.kinds().contains(&event.kind)) {
220 let at = event.created_at.as_secs();
221 match what {
222 Left::Reposts if event.tags.event_ids().next() == Some(note) => {
223 let last = by.entry(Some(event.pubkey)).or_insert((at, Did::Reposted));
224 last.0 = last.0.max(at);
225 }
226 Left::Reactions if reaction_target(&event) == Some(note) => {
227 let last = by.entry(Some(event.pubkey)).or_insert((at, Did::Reacted(Reaction::said(&event.content))));
228 if at >= last.0 {
229 *last = (at, Did::Reacted(Reaction::said(&event.content)));
230 }
231 }
232 Left::Zaps => {
233 let Some((_, millisats)) = zap(&event).filter(|(zapped, _)| *zapped == note) else {
234 continue;
235 };
236 let who = zap_request(&event).map(|request| request.pubkey);
237 let paid = by.entry(who).or_insert((0, Did::Zapped(0)));
238 paid.0 = paid.0.saturating_add(millisats);
239 }
240 _ => {}
241 }
242 }
243 let mut doers: Vec<(Option<PublicKey>, u64, Did)> = by
244 .into_iter()
245 .map(|(who, (weight, did))| match did {
246 Did::Zapped(_) => (who, weight, Did::Zapped(weight / 1000)),
247 did => (who, weight, did),
248 })
249 .filter(|(_, _, did)| *did != Did::Zapped(0))
250 .collect();
251 doers.sort_by(|(one, weight, _), (other, heavier, _)| {
254 heavier.cmp(weight).then_with(|| one.is_none().cmp(&other.is_none())).then_with(|| one.cmp(other))
255 });
256 doers.into_iter().map(|(who, _, did)| Doer { who, did }).collect()
257}
258
259pub fn tally(
265 events: impl IntoIterator<Item = Event>,
266 notes: &HashSet<EventId>,
267 account: Option<PublicKey>,
268) -> HashMap<EventId, Engagement> {
269 let mut tally: HashMap<EventId, Engagement> = notes.iter().map(|id| (*id, Engagement::default())).collect();
270 let mut reacted: HashSet<(EventId, PublicKey)> = HashSet::new();
271 let mut own_reaction_at: HashMap<EventId, u64> = HashMap::new();
272 let mut reposted: HashSet<(EventId, PublicKey)> = HashSet::new();
273 let mut millisats: HashMap<EventId, u64> = HashMap::new();
274 for event in events {
275 match event.kind {
276 Kind::TextNote | Kind::Comment => {
277 if let Some(engagement) = reply_to(&event).and_then(|reply| tally.get_mut(&reply.parent)) {
278 engagement.replies += 1;
279 }
280 }
281 Kind::Reaction => {
282 let Some(note) = reaction_target(&event) else {
283 continue;
284 };
285 let Some(engagement) = tally.get_mut(¬e) else {
286 continue;
287 };
288 if reacted.insert((note, event.pubkey)) {
289 engagement.likes += 1;
290 }
291 let at = event.created_at.as_secs();
292 if Some(event.pubkey) == account && own_reaction_at.get(¬e).is_none_or(|known| at >= *known) {
293 own_reaction_at.insert(note, at);
294 engagement.reaction = Some(Reaction::said(&event.content));
295 }
296 }
297 Kind::Repost | Kind::GenericRepost => {
299 let Some(note) = event.tags.event_ids().next() else {
300 continue;
301 };
302 if let Some(engagement) = tally.get_mut(¬e)
303 && reposted.insert((note, event.pubkey))
304 {
305 engagement.reposts += 1;
306 engagement.reposted |= Some(event.pubkey) == account;
307 }
308 }
309 Kind::ZapReceipt => {
310 if let Some((note, paid)) = zap(&event).filter(|(note, _)| notes.contains(note)) {
311 let total = millisats.entry(note).or_default();
312 *total = total.saturating_add(paid);
313 }
314 }
315 _ => {}
316 }
317 }
318 for (note, paid) in millisats {
319 if let Some(engagement) = tally.get_mut(¬e) {
320 engagement.zap_sats = paid / 1000;
321 }
322 }
323 tally
324}
325
326pub fn react(id: EventId, kind: Kind, author: PublicKey, reaction: &Reaction) -> EventBuilder {
329 EventBuilder::new(Kind::Reaction, reaction.content()).tags([
330 Tag::event(id),
331 Tag::public_key(author),
332 Tag::custom("k", [kind.as_u16().to_string()]),
333 ])
334}
335
336pub fn repost(event: &Event, relay: Option<RelayUrl>) -> EventBuilder {
342 let repost = RepostBuilder::new(event);
343 match relay {
344 Some(relay) => repost.relay_url(relay),
345 None => repost,
346 }
347 .into_event_builder()
348}
349
350#[cfg(test)]
351mod tests {
352 use super::{Did, Doer, Engagement, Left, Mark, Reaction, react, repost, tally, who_did};
353 use nostr_sdk::prelude::{Event, EventBuilder, EventId, FinalizeEvent, Keys, Kind, RelayUrl, Tag, Timestamp};
354 use std::collections::HashSet;
355
356 fn id(byte: u8) -> EventId {
357 EventId::from_byte_array([byte; 32])
358 }
359
360 fn event(kind: Kind, content: &str, tags: Vec<Tag>, keys: &Keys) -> Event {
361 EventBuilder::new(kind, content).tags(tags).finalize(keys).unwrap()
362 }
363
364 fn reaction(content: &str, note: EventId, keys: &Keys) -> Event {
365 event(Kind::Reaction, content, vec![Tag::event(note)], keys)
366 }
367
368 fn reposting(note: EventId, kind: Kind, keys: &Keys) -> Event {
369 event(kind, "", vec![Tag::event(note)], keys)
370 }
371
372 fn receipt(note: EventId, invoice: &str) -> Event {
373 event(Kind::ZapReceipt, "", vec![Tag::event(note), Tag::custom("bolt11", [invoice])], &Keys::generate())
374 }
375
376 fn event_at(at: u64, kind: Kind, content: &str, tags: Vec<Tag>, keys: &Keys) -> Event {
378 EventBuilder::new(kind, content).tags(tags).custom_created_at(Timestamp::from_secs(at)).finalize(keys).unwrap()
379 }
380
381 fn receipt_from(payer: &Keys, note: EventId, invoice: &str) -> Event {
384 let request = event(Kind::ZapRequest, "", vec![Tag::event(note)], payer);
385 let tags = vec![Tag::event(note), Tag::custom("bolt11", [invoice]), Tag::custom("description", [request.as_json()])];
386 event(Kind::ZapReceipt, "", tags, &Keys::generate())
387 }
388
389 #[test]
390 fn who_reposted_a_note_is_each_of_them_once_the_last_first() {
391 let (first, second) = (Keys::generate(), Keys::generate());
392 let (note, another) = (id(1), id(2));
393 let events = vec![
394 event_at(10, Kind::Repost, "", vec![Tag::event(note)], &first),
395 event_at(20, Kind::GenericRepost, "", vec![Tag::event(note)], &second),
396 event_at(30, Kind::Repost, "", vec![Tag::event(note)], &first),
398 event_at(40, Kind::Repost, "", vec![Tag::event(another)], &second),
400 event_at(50, Kind::Reaction, "+", vec![Tag::event(note)], &second),
401 ];
402 let reposted = |who: &Keys| Doer { who: Some(who.public_key()), did: Did::Reposted };
403 assert_eq!(who_did(events.clone(), note, Left::Reposts), [reposted(&first), reposted(&second)]);
404 assert_eq!(who_did(events, id(9), Left::Reposts), []);
405 }
406
407 #[test]
408 fn who_reacted_to_a_note_is_each_of_them_with_what_they_reacted_with_last() {
409 let (first, second, third) = (Keys::generate(), Keys::generate(), Keys::generate());
410 let (note, another) = (id(1), id(2));
411 let events = vec![
412 event_at(10, Kind::Reaction, "+", vec![Tag::event(note)], &first),
413 event_at(20, Kind::Reaction, "\u{1f525}", vec![Tag::event(note)], &first),
414 event_at(30, Kind::Reaction, "+", vec![Tag::event(note)], &second),
415 event_at(40, Kind::Reaction, "-", vec![Tag::event(note)], &third),
418 event_at(50, Kind::Reaction, "+", vec![Tag::event(note), Tag::event(another)], &third),
419 ];
420 let reacted = |who: &Keys, with: Reaction| Doer { who: Some(who.public_key()), did: Did::Reacted(with) };
421 assert_eq!(
422 who_did(events, note, Left::Reactions),
423 [reacted(&second, Reaction::Like), reacted(&first, Reaction::Emoji("\u{1f525}".into()))]
424 );
425 }
426
427 #[test]
428 fn who_zapped_a_note_is_each_of_them_with_all_they_paid_the_most_first() {
429 let (generous, modest) = (Keys::generate(), Keys::generate());
430 let (note, another) = (id(1), id(2));
431 let forged = {
434 let request = event(Kind::ZapRequest, "", vec![Tag::event(note)], &generous);
435 let mut altered: serde_json::Value = serde_json::from_str(&request.as_json()).unwrap();
436 altered["content"] = "said after signing".into();
437 let tags = vec![
438 Tag::event(note),
439 Tag::custom("bolt11", ["lnbc10u1pjq9xyz"]),
440 Tag::custom("description", [altered.to_string()]),
441 ];
442 event(Kind::ZapReceipt, "", tags, &Keys::generate())
443 };
444 let events = vec![
445 receipt_from(&modest, note, "lnbc210n1pjq9xyz"),
446 receipt_from(&generous, note, "lnbc10u1pjq9xyz"),
447 receipt_from(&generous, note, "lnbc210n1pjq9xyz"),
448 receipt(note, "lnbc210n1pjq9xyz"),
450 forged,
451 receipt_from(&modest, note, "lnbc1pjq9xyz"),
453 receipt_from(&modest, another, "lnbc10u1pjq9xyz"),
454 ];
455 let zapped = |who: Option<&Keys>, sats: u64| Doer { who: who.map(Keys::public_key), did: Did::Zapped(sats) };
456 assert_eq!(
457 who_did(events, note, Left::Zaps),
458 [zapped(Some(&generous), 1_021), zapped(None, 1_021), zapped(Some(&modest), 21)]
459 );
460 }
461
462 #[test]
463 fn each_note_is_counted_by_the_events_about_it() {
464 let (me, other, third) = (Keys::generate(), Keys::generate(), Keys::generate());
465 let (note, another, unasked) = (id(1), id(2), id(3));
466 let reply = |to: EventId| {
467 event(Kind::TextNote, "an answer", vec![Tag::custom("e", [to.to_hex(), String::new(), "root".into()])], &other)
468 };
469 let deeper = event(
470 Kind::TextNote,
471 "an answer to an answer",
472 vec![
473 Tag::custom("e", [note.to_hex(), String::new(), "root".into()]),
474 Tag::custom("e", [id(9).to_hex(), String::new(), "reply".into()]),
475 ],
476 &other,
477 );
478 let events = vec![
479 reply(note),
480 reply(note),
481 deeper,
482 reaction("+", note, &me),
483 reaction("๐ฅ", note, &other),
484 reaction("+", note, &other),
485 reaction("-", note, &third),
486 reaction("+", another, &other),
487 reaction("+", unasked, &me),
488 reposting(note, Kind::Repost, &other),
489 reposting(note, Kind::Repost, &other),
490 reposting(note, Kind::GenericRepost, &third),
491 reposting(another, Kind::Repost, &me),
492 reposting(unasked, Kind::Repost, &me),
493 receipt(note, "lnbc210n1pjq9xyz"),
494 receipt(note, "lnbc10u1pjq9xyz"),
495 receipt(note, "lnbc1pjq9xyz"),
496 receipt(unasked, "lnbc10u1pjq9xyz"),
497 ];
498
499 let counted = tally(events, &HashSet::from([note, another, id(4)]), Some(me.public_key()));
500
501 assert_eq!(
502 counted.get(¬e),
503 Some(&Engagement {
504 replies: 2,
505 reposts: 2,
506 reposted: false,
507 likes: 2,
508 reaction: Some(Reaction::Like),
509 zap_sats: 1_021
510 }),
511 "direct replies; each person once; a downvote not at all; invoices with an amount"
512 );
513 assert_eq!(counted.get(&another), Some(&Engagement { reposts: 1, reposted: true, likes: 1, ..Engagement::default() }));
514 assert_eq!(counted.get(&id(4)), Some(&Engagement::default()), "asked about, and nothing known");
515 assert_eq!(counted.get(&unasked), None, "not asked about");
516 }
517
518 #[test]
519 fn a_reaction_is_to_the_last_note_it_names() {
520 let keys = Keys::generate();
521 let reaction = event(Kind::Reaction, "+", vec![Tag::event(id(1)), Tag::event(id(2))], &keys);
522 let counted = tally([reaction], &HashSet::from([id(1), id(2)]), None);
523 assert_eq!(counted.get(&id(1)).map(|engagement| engagement.likes), Some(0));
524 assert_eq!(counted.get(&id(2)).map(|engagement| engagement.likes), Some(1));
525 }
526
527 #[test]
528 fn a_reaction_counts_as_one_for_the_note_and_its_author_hears_of_it() {
529 let (me, them) = (Keys::generate(), Keys::generate());
530 for (reaction, content) in [(Reaction::Like, "+"), (Reaction::Emoji("๐ค".into()), "๐ค")] {
531 let reacted = react(id(1), Kind::Comment, them.public_key(), &reaction).finalize(&me).unwrap();
532
533 assert_eq!(reacted.kind, Kind::Reaction);
534 assert_eq!(reacted.content, content);
535 assert_eq!(reacted.tags.public_keys().collect::<Vec<_>>(), [them.public_key()]);
536 assert_eq!(reacted.tags.event_ids().collect::<Vec<_>>(), [id(1)]);
537 let counted = tally([reacted], &HashSet::from([id(1)]), Some(me.public_key()));
538 assert_eq!(counted.get(&id(1)), Some(&Engagement { likes: 1, reaction: Some(reaction), ..Engagement::default() }));
539 }
540 }
541
542 #[test]
543 fn a_reaction_is_an_emoji_if_it_says_one_and_a_like_if_it_says_anything_else() {
544 assert_eq!(Reaction::said("๐ค"), Reaction::Emoji("๐ค".into()));
545 assert_eq!(Reaction::said(" ๐\n"), Reaction::Emoji("๐".into()));
546 assert_eq!(Reaction::said("โค"), Reaction::said("โค๏ธ"));
548 for like in ["+", "", ":soapbox:", "nice one", "๐๐๐"] {
549 assert_eq!(Reaction::said(like), Reaction::Like, "{like:?}");
550 }
551 assert_eq!((Reaction::Like.content(), Reaction::Emoji("๐ค".into()).content()), ("+", "๐ค"));
552 }
553
554 #[test]
555 fn the_accounts_own_reaction_is_the_one_it_made_last() {
556 let (me, other) = (Keys::generate(), Keys::generate());
557 let at = |content: &str, seconds: u64, keys: &Keys| {
558 EventBuilder::new(Kind::Reaction, content)
559 .tags([Tag::event(id(1))])
560 .custom_created_at(nostr_sdk::prelude::Timestamp::from_secs(seconds))
561 .finalize(keys)
562 .unwrap()
563 };
564 let (first, last, theirs) = (at("+", 100, &me), at("๐งจ", 200, &me), at("๐คก", 300, &other));
565 for events in [[first.clone(), last.clone(), theirs.clone()], [theirs, last, first]] {
567 let counted = tally(events, &HashSet::from([id(1)]), Some(me.public_key()));
568 let expected = Engagement { likes: 2, reaction: Some(Reaction::Emoji("๐งจ".into())), ..Engagement::default() };
569 assert_eq!(counted.get(&id(1)), Some(&expected));
570 }
571 let counted = tally([at("๐งจ", 200, &me)], &HashSet::from([id(1)]), None);
573 assert_eq!(counted.get(&id(1)).and_then(|engagement| engagement.reaction.clone()), None);
574 }
575
576 fn tags(event: &Event) -> Vec<Vec<&str>> {
578 event.tags.iter().map(|tag| tag.as_slice().iter().map(String::as_str).collect()).collect()
579 }
580
581 #[test]
582 fn a_repost_of_a_note_carries_it_whole_and_says_where_it_is() {
583 let (me, them) = (Keys::generate(), Keys::generate());
584 let note = event(Kind::TextNote, "worth passing on", Vec::new(), &them);
585 let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
586 let reposted = repost(¬e, Some(relay)).finalize(&me).unwrap();
587
588 assert_eq!(reposted.kind, Kind::Repost);
589 let (note_id, their_key) = (note.id.to_hex(), them.public_key().to_hex());
590 assert_eq!(tags(&reposted), [vec!["e", note_id.as_str(), "wss://relay.example.com"], vec!["p", their_key.as_str()]]);
591 assert_eq!(Event::from_json(&reposted.content).unwrap(), note, "the note, as it was signed");
592
593 let counted = tally([reposted], &HashSet::from([note.id]), Some(me.public_key()));
594 assert_eq!(counted.get(¬e.id), Some(&Engagement { reposts: 1, reposted: true, ..Engagement::default() }));
595 }
596
597 #[test]
598 fn a_repost_of_anything_else_says_what_kind_it_is() {
599 let (me, them) = (Keys::generate(), Keys::generate());
600 let comment = event(Kind::Comment, "what a bird", Vec::new(), &them);
601 let reposted = repost(&comment, None).finalize(&me).unwrap();
602
603 assert_eq!(reposted.kind, Kind::GenericRepost);
604 let (comment_id, their_key) = (comment.id.to_hex(), them.public_key().to_hex());
605 assert_eq!(tags(&reposted), [vec!["e", comment_id.as_str()], vec!["p", their_key.as_str()], vec!["k", "1111"]]);
606 assert_eq!(Event::from_json(&reposted.content).unwrap(), comment);
607 }
608
609 #[test]
610 fn a_note_that_was_to_stay_where_it_was_sent_is_reposted_by_name_only() {
611 let (me, them) = (Keys::generate(), Keys::generate());
612 let note = event(Kind::TextNote, "for this relay only", vec![Tag::protected()], &them);
613 assert_eq!(repost(¬e, None).finalize(&me).unwrap().content, "");
614 }
615
616 #[test]
617 fn a_mark_is_counted_once_and_taken_back_once() {
618 let others = Engagement { likes: 3, reposts: 1, ..Engagement::default() };
619
620 let (like, clown) = (Mark::React(Reaction::Like), Mark::React(Reaction::Emoji("๐คก".into())));
621 let liked = others.clone().with(&like);
622 assert_eq!(liked, Engagement { likes: 4, reaction: Some(Reaction::Like), ..others.clone() });
623 assert_eq!(liked.clone().with(&like), liked, "once is enough");
624 assert_eq!(liked.clone().with(&clown), liked, "whatever the second would say");
625 assert!(liked.has(&like) && liked.has(&clown) && !liked.has(&Mark::Repost));
626
627 let both = liked.clone().with(&Mark::Repost);
628 assert_eq!(both, Engagement { reposts: 2, reposted: true, ..liked });
629 assert_eq!(both.without(&clown), Engagement { reposts: 2, reposted: true, ..others.clone() });
630 assert_eq!(others.clone().without(&Mark::Repost), others, "what was not there is not taken away");
631
632 let clowned = others.clone().with(&clown);
634 assert_eq!(clowned, Engagement { likes: 4, reaction: Some(Reaction::Emoji("๐คก".into())), ..others });
635 }
636}