Skip to main content

cosmic_applet_avestruz/nostr/
engagement.rs

1// SPDX-License-Identifier: MIT
2
3//! What others made of a note: how many answered it, how many passed it on,
4//! how many reacted to it, and how much it was zapped; and what the
5//! account itself left on it: a repost, a reaction.
6//!
7//! It is counted from the events that name the note: replies (kind 1),
8//! reposts (kinds 6 and 16, NIP-18), reactions (kind 7, NIP-25) and zap
9//! receipts (kind 9735, NIP-57). The count is of what the event store
10//! holds, which is what the relays were willing to send: for a note that
11//! went everywhere, less than everything.
12//!
13//! Who they were is read from the same events ([`who_did`]): who
14//! reposted, who reacted and what with, who zapped and how much. So what
15//! a count names and who is listed under it agree.
16
17use 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/// What a reaction says (NIP-25): that the note is liked, or an emoji.
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub enum Reaction {
28    /// A like: `+`, or nothing at all.
29    Like,
30    /// An emoji, as it is written.
31    Emoji(String),
32}
33
34impl Reaction {
35    /// What a reaction that says `content` is, as it is shown. Anything
36    /// that is not an emoji is a like: a `+`, nothing, and what this
37    /// client has no picture for, as a custom emoji's short code.
38    pub fn said(content: &str) -> Self {
39        emoji::known(content.trim()).map_or(Self::Like, |emoji| Self::Emoji(emoji.to_string()))
40    }
41
42    /// What a reaction says to be this one.
43    pub fn content(&self) -> &str {
44        match self {
45            Self::Like => "+",
46            Self::Emoji(emoji) => emoji,
47        }
48    }
49}
50
51/// What others made of one note.
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Engagement {
54    /// How many notes answer it directly.
55    pub replies: usize,
56    /// How many people reposted it.
57    pub reposts: usize,
58    /// Whether the account is one of them.
59    pub reposted: bool,
60    /// How many people reacted to it, with a like or with an emoji.
61    pub likes: usize,
62    /// What the account reacted to it with, if it did.
63    pub reaction: Option<Reaction>,
64    /// How much it was zapped, in sats.
65    pub zap_sats: u64,
66}
67
68/// How some notes stand, as far as one source knows: what was made of each,
69/// and which relays each was seen on, for those seen on any.
70#[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/// What the account leaves on a note, and once only: it shows at once,
77/// and is published behind what shows.
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum Mark {
80    /// A reaction (NIP-25): a like, or an emoji.
81    React(Reaction),
82    /// A repost (NIP-18).
83    Repost,
84}
85
86impl Engagement {
87    /// Whether the account left a mark of the kind of `mark` on the note:
88    /// a repost, or a reaction, whatever it says.
89    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    /// This, with the account's `mark` on the note: counted, unless one
97    /// of its kind was there already, which then stays as it is.
98    #[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    /// This, without the account's mark of the kind of `mark` on the
116    /// note: no longer counted, if it was.
117    #[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
135/// The note a reaction is to: the last one it names (NIP-25). `None` for a
136/// downvote, which is not counted for or against.
137fn reaction_target(event: &Event) -> Option<EventId> {
138    if event.content == "-" {
139        return None;
140    }
141    event.tags.event_ids().last()
142}
143
144/// The note a zap receipt is for, and what was paid, in millisats: the
145/// amount of the invoice the receipt carries.
146///
147/// A receipt is taken at its word. Whether it comes from the wallet
148/// service of the person zapped is not checked: that takes asking their
149/// Lightning address, once for every author.
150fn 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
155/// The zap request a zap receipt carries, if it carries one that is what
156/// it says: signed by whoever it says paid.
157pub(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/// Which of what others left on a note: what one of its counts is of.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum Left {
166    /// The reposts.
167    Reposts,
168    /// The reactions: likes, and emoji.
169    Reactions,
170    /// The zaps.
171    Zaps,
172}
173
174impl Left {
175    /// The kinds of the events that are it.
176    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/// What one of them left on a note.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum Did {
188    /// Reposted it.
189    Reposted,
190    /// Reacted to it, with this.
191    Reacted(Reaction),
192    /// Zapped it, so many sats in all.
193    Zapped(u64),
194}
195
196/// Someone who left something on a note, and what.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct Doer {
199    /// Who. `None` for the zaps whose receipts don't say who paid, or say
200    /// it in a way that does not hold: all of those are one.
201    pub who: Option<PublicKey>,
202    pub did: Did,
203}
204
205/// Who left `what` on `note`, going by `events`, each of them once: the
206/// last first, for reposts and reactions, and whoever zapped most first.
207/// Someone who reposted twice reposted once; of someone who reacted more
208/// than once, it is the reaction made last; and what someone zapped in
209/// several goes is added up. A downvote is no reaction, here as in the
210/// count, and a zap of less than a sat is none.
211///
212/// A zap is whose its receipt says it is, by the request the receipt
213/// carries, if that request is signed by them (NIP-57). Whether the
214/// receipt itself comes from the wallet of the one zapped is not looked
215/// into, as it is not for the count (see [`tally`]).
216pub fn who_did(events: impl IntoIterator<Item = Event>, note: EventId, what: Left) -> Vec<Doer> {
217    // Each of them, with when they last did it, or how much in all.
218    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    // The most first; among equals, whoever is known before whoever is
252    // not, and always in the same order.
253    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
259/// What `events` make of each of `notes`, with `account` the one whose own
260/// reactions and reposts are told apart. Events about other notes, or of
261/// other kinds, count for nothing; someone who reacted twice reacted once,
262/// and someone who reposted twice reposted once. Of an account that
263/// reacted more than once, elsewhere, the reaction made last is its own.
264pub 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(&note) 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(&note).is_none_or(|known| at >= *known) {
293                    own_reaction_at.insert(note, at);
294                    engagement.reaction = Some(Reaction::said(&event.content));
295                }
296            }
297            // A repost names the one note it passes on (NIP-18).
298            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(&note)
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(&note) {
320            engagement.zap_sats = paid / 1000;
321        }
322    }
323    tally
324}
325
326/// The reaction `reaction` to the event `id`, of kind `kind`, written by
327/// `author`, yet to be signed (NIP-25).
328pub 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
336/// A repost of `event`, yet to be signed (NIP-18): of kind 6 for a text
337/// note and of kind 16, naming the kind, for anything else. It carries the
338/// event whole, so that it can be shown without being looked for, unless
339/// its author asked that it go nowhere they didn't send it (NIP-70).
340/// `relay` is one that has the event, for those who look anyway.
341pub 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    /// As [`event`], made at `at`.
377    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    /// A receipt for `note` of what `invoice` asks for, which says that
382    /// `payer` paid it, in a request signed by them.
383    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            // Again, later: once is what counts, and where it puts them.
397            event_at(30, Kind::Repost, "", vec![Tag::event(note)], &first),
398            // Of another note, and of another kind: not this.
399            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            // A downvote is no reaction, and one to a note it names last is
416            // to that note, not to this one.
417            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        // A request that says who paid, altered after it was signed: it
432        // does not hold, and the zap is nobody's in particular.
433        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            // Receipts that say nobody paid, or say it falsely: one line.
449            receipt(note, "lnbc210n1pjq9xyz"),
450            forged,
451            // No amount, and another note's: not counted here.
452            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(&note),
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        // However the emoji was written, it is the same reaction.
547        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        // In whatever order they come, and counted once.
566        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        // With nobody signed in, nobody's reaction is one's own.
572        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    /// The tags of `event`, each as its fields.
577    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(&note, 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(&note.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(&note, 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        // An emoji is counted as a like is, and shows as itself.
633        let clowned = others.clone().with(&clown);
634        assert_eq!(clowned, Engagement { likes: 4, reaction: Some(Reaction::Emoji("๐Ÿคก".into())), ..others });
635    }
636}