cosmic_applet_avestruz/handlers/
notifications.rs1use 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
42const CHECK_OVERLAP: Duration = Duration::from_secs(10 * 60);
46
47impl AppModel {
48 fn account_key(&self) -> Option<PublicKey> {
50 self.account.as_ref().map(|account| account.public_key)
51 }
52
53 fn seen_key(&self) -> Option<String> {
56 self.account_key().and_then(|account| account.to_bech32().ok())
57 }
58
59 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 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 pub(crate) fn notifications_tab(&self) -> Tab {
74 self.notification_tabs.active_data::<Tab>().copied().unwrap_or_default()
75 }
76
77 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 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 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 pub(crate) fn reset_notifications(&mut self) {
106 self.notifications = NotificationsState::default();
107 }
108
109 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 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 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 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 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 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 (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 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 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 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 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 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}