Skip to main content

cosmic_applet_avestruz/handlers/
engagement.rs

1// SPDX-License-Identifier: MIT
2
3//! Engagement message handlers for Avestruz: what was made of the notes on
4//! show, and the account's own reactions and reposts.
5//!
6//! Whenever notes come into a feed or a thread, the event store is asked
7//! how many answered, reposted, liked and zapped them, and the relays are
8//! asked the same, and whether they have the notes themselves: the ones
9//! that do are the relays a note was seen on. What was asked within the
10//! last couple of minutes is not asked again, so a refresh that brings the
11//! same notes costs nothing.
12//!
13//! A reaction is a like or an emoji, chosen from what is offered under a
14//! note's like: the emoji reacted with most, which are kept for that (see
15//! [`crate::emoji`]), or any there is.
16//!
17//! A reaction or a repost shows at once and goes out behind it. Until a relay
18//! has taken it the note is remembered as carrying it, so that a count
19//! arriving in the meantime doesn't take it off the screen; if no relay
20//! takes it, it is taken off, with the reason.
21
22use std::time::{Duration, Instant};
23
24use cosmic::prelude::*;
25use cosmic::widget::text_input;
26use nostr_sdk::prelude::{EventId, PublicKey};
27
28use crate::emoji::{self, Group};
29use crate::fl;
30use crate::handlers::compose::publish_error_text;
31use crate::handlers::feed::fetch_profiles;
32use crate::helpers::unix_now;
33use crate::messages::{Message, PublishFailure};
34use crate::nostr::client::{FetchError, Source};
35use crate::nostr::engagement::{self, Doer, Left, Mark, Reaction, Standing};
36use crate::state::{AppModel, EmojiPicker, REACTIONS_OFFERED, ReactionMenu, RepostMenu, WHO_SHOWN, WhoMenu};
37use crate::views::components::emoji_search_id;
38
39/// How long what was made of a note is taken as known, before it is asked
40/// again.
41const ENGAGEMENT_FRESH: Duration = Duration::from_secs(120);
42
43impl AppModel {
44    /// Find out what was made of `notes`, those of them that were not asked
45    /// about just now: from the event store at once, from the relays after.
46    pub(crate) fn look_up_engagement(&mut self, notes: impl IntoIterator<Item = EventId>) -> Task<cosmic::Action<Message>> {
47        let Some(service) = self.nostr.clone() else {
48            return Task::none();
49        };
50        let now = Instant::now();
51        let asked = &mut self.engagement_asked;
52        let notes: Vec<EventId> = notes
53            .into_iter()
54            .filter(|note| match asked.get(note) {
55                Some(at) if now.duration_since(*at) < ENGAGEMENT_FRESH => false,
56                _ => {
57                    asked.insert(*note, now);
58                    true
59                }
60            })
61            .collect();
62        if notes.is_empty() {
63            return Task::none();
64        }
65        let account = self.account.as_ref().map(|account| account.public_key);
66        let ask = |source: Source| {
67            let (service, notes) = (service.clone(), notes.clone());
68            Task::perform(async move { service.standing(source, notes, account).await }, move |result| {
69                cosmic::Action::App(Message::EngagementLoaded { source, account, result })
70            })
71        };
72        Task::batch([ask(Source::Store), ask(Source::Relays)])
73    }
74
75    /// Forget what was made of the notes seen: the account changed, and
76    /// whose likes and reposts are its own with it.
77    pub(crate) fn reset_engagement(&mut self) {
78        self.engagement.clear();
79        self.engagement_asked.clear();
80        self.pending_marks.clear();
81        self.repost_menu = None;
82        self.reaction_menu = None;
83        self.who_menu = None;
84    }
85
86    /// What was made of some notes came from the store or from the relays
87    /// (or didn't: the counts are not worth a banner).
88    pub fn handle_engagement_loaded(&mut self, source: Source, account: Option<PublicKey>, result: Result<Standing, FetchError>) {
89        // Counted for another account: its likes and reposts are not this
90        // one's.
91        if account != self.account.as_ref().map(|account| account.public_key) {
92            return;
93        }
94        match result {
95            Ok(Standing { engagement: counted, seen_on }) => {
96                // A relay that had a note has it still, whoever was asked
97                // last: what is known only grows.
98                self.seen_on.extend(seen_on);
99                // What is on its way out is in no count yet.
100                let pending = &self.pending_marks;
101                self.engagement.extend(counted.into_iter().map(|(note, engagement)| {
102                    let on_its_way = pending.iter().filter(|(marked, _)| *marked == note);
103                    (note, on_its_way.fold(engagement, |engagement, (_, mark)| engagement.with(mark)))
104                }));
105            }
106            Err(e) => tracing::warn!("engagement could not be fetched from {source:?}: {e:?}"),
107        }
108    }
109
110    /// Show who left `what` on the note `id`, under the count of them, or
111    /// put that away if it is what shows. They are read from the store,
112    /// which is where they were counted from.
113    pub fn handle_show_who(&mut self, id: EventId, what: Left) -> Task<cosmic::Action<Message>> {
114        self.repost_menu = None;
115        self.reaction_menu = None;
116        if self.who_menu.take().is_some_and(|menu| menu.note == id && menu.what == what) {
117            return Task::none();
118        }
119        let Some(service) = self.nostr.clone() else {
120            return Task::none();
121        };
122        self.who_menu = Some(WhoMenu { note: id, what, people: None });
123        Task::perform(async move { service.who_did(id, what).await }, move |result| {
124            cosmic::Action::App(Message::WhoLoaded { note: id, what, result })
125        })
126    }
127
128    /// Who left `what` on `note` was read, or could not be, which shows
129    /// as nobody having. Nothing comes of it if that is no longer what is
130    /// asked for. Those of them who are not known yet are asked after, as
131    /// many as are shown.
132    pub fn handle_who_loaded(
133        &mut self,
134        note: EventId,
135        what: Left,
136        result: Result<Vec<Doer>, FetchError>,
137    ) -> Task<cosmic::Action<Message>> {
138        let Some(menu) = self.who_menu.as_mut().filter(|menu| menu.note == note && menu.what == what) else {
139            return Task::none();
140        };
141        let people = result.unwrap_or_else(|e| {
142            tracing::warn!("who left something on a note could not be read: {e:?}");
143            Vec::new()
144        });
145        let unknown: Vec<PublicKey> =
146            people.iter().take(WHO_SHOWN).filter_map(|doer| doer.who).filter(|who| !self.profiles.contains_key(who)).collect();
147        menu.people = Some(people);
148        match self.nostr.clone() {
149            Some(service) if !unknown.is_empty() => fetch_profiles(service, unknown),
150            _ => Task::none(),
151        }
152    }
153
154    /// Show what can be done to pass the note `id` on, or put it away if
155    /// it is showing.
156    pub fn handle_toggle_repost_menu(&mut self, id: EventId) {
157        self.reaction_menu = None;
158        self.who_menu = None;
159        let showing = self.repost_menu.is_some_and(|menu| menu.note == id);
160        self.repost_menu = (!showing).then_some(RepostMenu::of(id));
161    }
162
163    // =========================================================================
164    // Reactions
165    // =========================================================================
166
167    /// Work out again which emoji are offered first to react with: what
168    /// the settings have of the ones used changed.
169    pub(crate) fn suggest_reactions(&mut self) {
170        self.reaction_suggestions = emoji::suggested(&self.config.reaction_emojis, REACTIONS_OFFERED);
171    }
172
173    /// Offer what to react to the note `id` with, or put the offer away
174    /// if it is showing.
175    pub fn handle_toggle_reaction_menu(&mut self, id: EventId) {
176        self.repost_menu = None;
177        self.who_menu = None;
178        let showing = self.reaction_menu.as_ref().is_some_and(|menu| menu.note == id);
179        self.reaction_menu = (!showing).then_some(ReactionMenu { note: id, picker: None });
180    }
181
182    /// Show every emoji there is, in place of the few offered first, with
183    /// the field to find one by ready to be typed in.
184    pub fn handle_open_emoji_picker(&mut self) -> Task<cosmic::Action<Message>> {
185        let Some(menu) = &mut self.reaction_menu else {
186            return Task::none();
187        };
188        menu.picker = Some(EmojiPicker { typed: String::new(), group: Group::SmileysAndEmotion });
189        text_input::focus(emoji_search_id())
190    }
191
192    /// The emoji picker, if it is open.
193    fn emoji_picker_mut(&mut self) -> Option<&mut EmojiPicker> {
194        self.reaction_menu.as_mut()?.picker.as_mut()
195    }
196
197    /// What to find an emoji by was typed.
198    pub fn handle_emoji_search_typed(&mut self, typed: String) {
199        if let Some(picker) = self.emoji_picker_mut() {
200            picker.typed = typed;
201        }
202    }
203
204    /// Another group of emoji was chosen to pick from: it shows, and what
205    /// was typed to find one by is dropped, which would hide it.
206    pub fn handle_emoji_group(&mut self, group: Group) {
207        if let Some(picker) = self.emoji_picker_mut() {
208            picker.group = group;
209            picker.typed.clear();
210        }
211    }
212
213    /// React to the note `id` with `reaction`. An emoji reacted with is
214    /// one to offer again: it is noted in the settings, whatever comes of
215    /// the reaction.
216    pub fn handle_react(&mut self, id: EventId, reaction: Reaction) -> Task<cosmic::Action<Message>> {
217        self.reaction_menu = None;
218        if let Reaction::Emoji(used) = &reaction {
219            emoji::record(&mut self.config.reaction_emojis, used, unix_now());
220            self.save_config("reaction emoji");
221            self.suggest_reactions();
222        }
223        self.handle_mark(id, Mark::React(reaction))
224    }
225
226    /// Leave `mark` on the note `id`, which is one on show: react to it,
227    /// or repost it. Once is enough: a note that carries a mark of that
228    /// kind stays as it is.
229    pub fn handle_mark(&mut self, id: EventId, mark: Mark) -> Task<cosmic::Action<Message>> {
230        self.repost_menu = None;
231        let (Some(service), Some(account)) =
232            (self.nostr.clone(), self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key))
233        else {
234            return Task::none();
235        };
236        let Some(note) = self.note_at_hand(id) else {
237            return Task::none();
238        };
239        let engagement = self.engagement.entry(id).or_default();
240        if engagement.has(&mark) {
241            return Task::none();
242        }
243        *engagement = std::mem::take(engagement).with(&mark);
244        self.pending_marks.insert((id, mark.clone()));
245
246        let signer = self.signer.clone();
247        let left = mark.clone();
248        let publish = async move {
249            let unsigned = match &left {
250                Mark::React(reaction) => engagement::react(id, note.kind, note.author, reaction),
251                // A repost carries the note as it was signed, and says
252                // where it is.
253                Mark::Repost => {
254                    let event = service.event(id, note.author).await.ok_or(PublishFailure::NoteGone)?;
255                    engagement::repost(&event, service.relay_holding(id).await)
256                }
257            };
258            service.sign_and_publish(&signer, account, unsigned).await.map(|_| ()).map_err(PublishFailure::Failed)
259        };
260        Task::perform(publish, move |result| cosmic::Action::App(Message::Marked { note: id, mark: mark.clone(), result }))
261    }
262
263    /// The reaction to the note `id`, or its repost, went out, or didn't.
264    pub fn handle_marked(&mut self, id: EventId, mark: Mark, result: Result<(), PublishFailure>) {
265        self.pending_marks.remove(&(id, mark.clone()));
266        if let Err(failure) = result {
267            tracing::error!("the {mark:?} could not be published: {failure:?}");
268            if let Some(engagement) = self.engagement.get_mut(&id) {
269                *engagement = std::mem::take(engagement).without(&mark);
270            }
271            self.error_message = Some(match failure {
272                PublishFailure::NoteGone => fl!("note-error-gone"),
273                PublishFailure::Failed(error) => publish_error_text(error),
274            });
275        }
276    }
277}