Skip to main content

cosmic_applet_avestruz/handlers/
notifications.rs

1// SPDX-License-Identifier: MIT
2
3//! Notification message handlers for Avestruz: finding out what others
4//! did that concerns the account, showing it, and keeping track of how
5//! much of it was looked at.
6//!
7//! What names the account is read from the store when the account is
8//! known, and asked of the relays after: its own, and the ones it reads
9//! (see [`NostrService::notifications`](crate::nostr::client::NostrService::notifications)).
10//! From then on the relays are
11//! asked again each time the feed is looked at for new notes, for what
12//! was written since. Scrolling the list towards its end asks for the
13//! page before the oldest.
14//!
15//! What is new is what was written after the notifications were last
16//! looked at: one moment, kept in the settings for each account
17//! ([`Config::notifications_seen`](crate::config::Config::notifications_seen)).
18//! Looking is having their page on show in an open popup. The moment is
19//! moved to now when that begins and again when it ends, so that what
20//! arrived meanwhile is not new the next time; what was new when it
21//! began stays picked out for as long as the page is looked at
22//! ([`NotificationsState::seen_before`](crate::state::NotificationsState::seen_before)).
23//!
24//! Zaps show once it is known which key the account's wallet service
25//! signs receipts with, which its Lightning address is asked once (see
26//! [`crate::nostr::notifications`]).
27
28use std::time::Duration;
29
30use cosmic::prelude::*;
31use cosmic::widget::segmented_button;
32use nostr_sdk::prelude::{PublicKey, ToBech32};
33
34use crate::handlers::navigation::scroll_list_to;
35use crate::helpers::unix_now;
36use crate::messages::Message;
37use crate::nostr::client::{FetchError, Notified, Source};
38use crate::nostr::notifications::Tab;
39use crate::nostr::zap;
40use crate::state::{AppModel, NotificationsPage, NotificationsState, Page, ViewState};
41
42/// How far back from the newest notification the relays are asked again
43/// when they are asked for what is new: events reach a relay some time
44/// after they say they were written.
45const CHECK_OVERLAP: Duration = Duration::from_secs(10 * 60);
46
47impl AppModel {
48    /// The public key of the account, if somebody is signed in.
49    fn account_key(&self) -> Option<PublicKey> {
50        self.account.as_ref().map(|account| account.public_key)
51    }
52
53    /// What the settings keep the account's last look at its
54    /// notifications under: its `npub`.
55    fn seen_key(&self) -> Option<String> {
56        self.account_key().and_then(|account| account.to_bech32().ok())
57    }
58
59    /// When the account last looked at its notifications.
60    pub(crate) fn notifications_seen_at(&self) -> u64 {
61        self.seen_key().and_then(|key| self.config.notifications_seen.get(&key).copied()).unwrap_or(0)
62    }
63
64    /// The account has looked at its notifications, as of now.
65    fn mark_notifications_seen(&mut self) {
66        if let Some(key) = self.seen_key() {
67            self.config.notifications_seen.insert(key, unix_now());
68            self.save_config("notifications seen");
69        }
70    }
71
72    /// Which notifications the page shows: as the control above it says.
73    pub(crate) fn notifications_tab(&self) -> Tab {
74        self.notification_tabs.active_data::<Tab>().copied().unwrap_or_default()
75    }
76
77    /// Whether the notifications are being looked at: their page is on
78    /// show, in an open popup.
79    fn notifications_in_view(&self) -> bool {
80        self.popup.is_some() && self.view_state == ViewState::Page && matches!(self.pages.last(), Some(Page::Notifications(_)))
81    }
82
83    /// See whether the notifications came into view or went out of it,
84    /// whatever did that: what was seen before is kept for the visit that
85    /// begins, and either way everything there is has now been seen. To
86    /// be called after every message.
87    pub(crate) fn watch_notifications(&mut self) {
88        let in_view = self.notifications_in_view();
89        if in_view == self.notifications.in_view {
90            return;
91        }
92        self.notifications.in_view = in_view;
93        if in_view {
94            self.notifications.seen_before = self.notifications_seen_at();
95        }
96        self.mark_notifications_seen();
97    }
98
99    /// How many notifications are new: none while they are looked at.
100    pub(crate) fn unread_notifications(&self) -> usize {
101        if self.notifications.in_view { 0 } else { self.notifications.list.unread(self.notifications_seen_at()) }
102    }
103
104    /// Forget what the account was told of: the account changed.
105    pub(crate) fn reset_notifications(&mut self) {
106        self.notifications = NotificationsState::default();
107    }
108
109    /// Find out what the account is told of: from the store now, and from
110    /// the relays after. Does nothing until both the account and the
111    /// store are there.
112    pub(crate) fn load_notifications(&mut self) -> Task<cosmic::Action<Message>> {
113        let (Some(service), Some(account)) = (self.nostr.clone(), self.account_key()) else {
114            return Task::none();
115        };
116        // An account that never looked has seen everything there is: what
117        // is new is what comes from now on, not all it was ever told.
118        if let Some(key) = self.seen_key()
119            && !self.config.notifications_seen.contains_key(&key)
120        {
121            self.mark_notifications_seen();
122        }
123        self.notifications.loading = true;
124        Task::perform(async move { service.notifications(Source::Store, account, None, None).await }, move |result| {
125            cosmic::Action::App(Message::NotificationsLoaded { account, source: Source::Store, older: false, result })
126        })
127    }
128
129    /// Ask the relays what names the account: what was written after
130    /// `since` and at or before `until`, where those are given.
131    fn ask_for_notifications(&mut self, since: Option<u64>, until: Option<u64>) -> Task<cosmic::Action<Message>> {
132        let (Some(service), Some(account)) = (self.nostr.clone(), self.account_key()) else {
133            return Task::none();
134        };
135        let older = until.is_some();
136        if older {
137            self.notifications.loading_older = true;
138        } else {
139            self.notifications.loading = true;
140        }
141        Task::perform(async move { service.notifications(Source::Relays, account, since, until).await }, move |result| {
142            cosmic::Action::App(Message::NotificationsLoaded { account, source: Source::Relays, older, result })
143        })
144    }
145
146    /// It is time to ask the relays what is new for the account: what
147    /// was written since the newest notification known, and a while
148    /// before it; or the newest there is, if they have not answered yet.
149    /// Not while they are being asked.
150    pub(crate) fn check_notifications(&mut self) -> Task<cosmic::Action<Message>> {
151        if self.notifications.loading {
152            return Task::none();
153        }
154        if !self.notifications.settled {
155            return self.ask_for_notifications(None, None);
156        }
157        let since = self.notifications.list.newest().map(|newest| newest.saturating_sub(CHECK_OVERLAP.as_secs()));
158        self.ask_for_notifications(since, None)
159    }
160
161    /// A page of what the account is told of came from the store or from
162    /// the relays (or didn't).
163    pub fn handle_notifications_loaded(
164        &mut self,
165        account: PublicKey,
166        source: Source,
167        older: bool,
168        result: Result<Notified, FetchError>,
169    ) -> Task<cosmic::Action<Message>> {
170        if self.account_key() != Some(account) {
171            return Task::none();
172        }
173        let first = !self.notifications.settled;
174        let state = &mut self.notifications;
175        if older {
176            state.loading_older = false;
177        } else if source == Source::Relays {
178            state.loading = false;
179        }
180        let page = match result {
181            Ok(page) => page,
182            Err(e) => {
183                tracing::warn!("what names the account could not be asked of {source:?}: {e:?}");
184                // A page that didn't come is not the end of them: it is
185                // asked for again when the list is next scrolled there.
186                if source == Source::Relays && !older {
187                    state.failed = first;
188                }
189                return if source == Source::Store { self.ask_for_notifications(None, None) } else { Task::none() };
190            }
191        };
192        tracing::info!(
193            "notifications: {} from {source:?}{}",
194            page.notifications.len(),
195            if older { ", further back" } else { "" }
196        );
197        match (source, older) {
198            (Source::Store, _) => {}
199            // The newest there are. The first answer says where the page
200            // before it ends, and whether there is one. So does one that
201            // is as long as was asked for and ends after everything known
202            // (what the store had from last week, say): there may be more
203            // in between, so what is older is let go of, and comes back
204            // as the list is scrolled to its end. A list with a hole in
205            // it would be filled in above whoever had read past the hole.
206            (Source::Relays, false) => {
207                (state.settled, state.failed) = (true, false);
208                let apart = page.full && page.oldest.zip(state.list.newest()).is_some_and(|(oldest, known)| oldest > known);
209                if first || apart {
210                    (state.oldest, state.end_reached) = (page.oldest, !page.full);
211                }
212                if let Some(oldest) = page.oldest.filter(|_| apart) {
213                    state.list.forget_before(oldest);
214                }
215            }
216            (Source::Relays, true) => {
217                state.end_reached = !page.full || page.oldest.is_none();
218                state.oldest = page.oldest.or(state.oldest);
219            }
220        }
221        let people: Vec<PublicKey> = page
222            .notifications
223            .iter()
224            .flat_map(|told| std::iter::once(told.who).chain(told.note.iter().flat_map(|note| note.people())))
225            .collect();
226        let notes: Vec<_> = page.notifications.iter().filter_map(|told| told.note.as_ref().map(|note| note.id)).collect();
227        let news = state.list.merge(page.notifications);
228        if !news.is_empty() && source == Source::Relays {
229            tracing::info!("notifications: {} not known before", news.len());
230        }
231
232        let asked = if source == Source::Store { self.ask_for_notifications(None, None) } else { Task::none() };
233        Task::batch([asked, self.look_up_people(people), self.look_up_engagement(notes), self.look_up_zapper()])
234    }
235
236    /// Ask the account's Lightning address which key its wallet service
237    /// signs zap receipts with, once, when the account is known to have
238    /// such an address.
239    pub(crate) fn look_up_zapper(&mut self) -> Task<cosmic::Action<Message>> {
240        if self.notifications.zapper_asked {
241            return Task::none();
242        }
243        let Some(account) = self.account_key() else {
244            return Task::none();
245        };
246        let Some(address) = self.profiles.get(&account).and_then(|profile| profile.lightning.clone()) else {
247            return Task::none();
248        };
249        self.notifications.zapper_asked = true;
250        let http = self.http.clone();
251        Task::perform(async move { zap::zapper_key(http, &address).await }, move |result| {
252            cosmic::Action::App(Message::ZapperKnown(account, result.map_err(|e| format!("{e:?}"))))
253        })
254    }
255
256    /// The account's Lightning address said which key signs its zap
257    /// receipts (or could not be asked: it is asked again the next time
258    /// there is reason to).
259    pub fn handle_zapper_known(&mut self, account: PublicKey, result: Result<Option<PublicKey>, String>) {
260        if self.account_key() != Some(account) {
261            return;
262        }
263        match result {
264            Ok(zapper) => self.notifications.list.set_zapper(zapper),
265            Err(e) => {
266                tracing::warn!("the account's Lightning address could not be asked who signs its zap receipts: {e}");
267                self.notifications.zapper_asked = false;
268            }
269        }
270    }
271
272    /// Show what the account is told of, over whatever is on show now,
273    /// and ask the relays whether there is more.
274    pub fn handle_open_notifications(&mut self) -> Task<cosmic::Action<Message>> {
275        self.menu_open = false;
276        if self.account.is_none() {
277            return Task::none();
278        }
279        let opened = self.open_page(Page::Notifications(Box::default()));
280        let _: &NotificationsPage = match self.pages.last() {
281            Some(Page::Notifications(page)) => page,
282            _ => return opened,
283        };
284        Task::batch([opened, self.check_notifications(), self.look_up_zapper()])
285    }
286
287    /// The list of notifications was scrolled near its end: ask for the
288    /// page before the oldest, unless that is under way, or there is none.
289    pub fn handle_load_older_notifications(&mut self) -> Task<cosmic::Action<Message>> {
290        let state = &self.notifications;
291        if !state.settled || state.loading_older || state.end_reached {
292            return Task::none();
293        }
294        match state.oldest {
295            Some(oldest) => self.ask_for_notifications(None, Some(oldest.saturating_sub(1))),
296            None => Task::none(),
297        }
298    }
299
300    /// Another kind of notification was chosen to show: from its top.
301    pub fn handle_select_notifications_tab(&mut self, chosen: segmented_button::Entity) -> Task<cosmic::Action<Message>> {
302        if self.notification_tabs.data::<Tab>(chosen).is_none() || self.notification_tabs.active() == chosen {
303            return Task::none();
304        }
305        self.notification_tabs.activate(chosen);
306        scroll_list_to(0.0)
307    }
308}