Skip to main content

cosmic_applet_avestruz/handlers/
bookmarks.rs

1// SPDX-License-Identifier: MIT
2
3//! Bookmark message handlers for Avestruz: what the account has bookmarked,
4//! and bookmarking a note or taking its bookmark off.
5//!
6//! The bookmarks are the account's bookmark list (see
7//! [`crate::nostr::bookmarks`]), and part of it is encrypted: reading it
8//! takes the account's key. They are asked for when the popup opens, not
9//! when the applet starts, so that a remote signer is not reached for, nor
10//! whoever keeps it asked anything, before the account is looked at; and
11//! again each time it opens after a while, for what was bookmarked
12//! elsewhere since. The store answers first and the relays after. A list
13//! that was read once is not decrypted again.
14//!
15//! A bookmark shows at once and goes out behind it: the newest list, asked
16//! of the relays just then, written again with that one change. One at a
17//! time, since each change is made to the list the last one left. If it
18//! does not go out, the note shows as it was, with the reason.
19//!
20//! An account whose relays have no list of its own is told so the first
21//! time, and nothing is written: a first list replaces any list kept on
22//! relays that are not asked here. Bookmarking again writes it.
23//!
24//! The bookmarks page shows the notes bookmarked, and looks them up by id
25//! a page at a time, in the store and then on the relays, as its list is
26//! scrolled. Which notes it shows is taken from the bookmarks when it
27//! opens, and again when they turn out to be others than they were, if
28//! its list is at its top: further down it is being read, and stays as it
29//! is. A bookmark put on or taken off here changes nothing on a page that
30//! is open, for the same reason.
31
32use std::time::{Duration, Instant};
33
34use cosmic::prelude::*;
35use nostr_sdk::prelude::{EventId, PublicKey};
36
37use crate::fl;
38use crate::handlers::auth::sign_error_text;
39use crate::handlers::compose::publish_error_text;
40use crate::messages::Message;
41use crate::nostr::bookmarks::Bookmarks;
42use crate::nostr::client::{FetchError, ListError, Source};
43use crate::nostr::models::Note;
44use crate::nostr::outbox::Whereabouts;
45use crate::state::{AppModel, BookmarkState, BookmarkedNotes, BookmarksPage, Page};
46
47/// How long the bookmarks are taken as known, before the popup opening
48/// has them asked for again.
49const BOOKMARKS_FRESH: Duration = Duration::from_secs(60);
50
51/// How many bookmarked notes the bookmarks page looks up at a time.
52const BOOKMARKS_PAGE: usize = 20;
53
54impl AppModel {
55    /// Forget the bookmarks: the account changed, and they were its own.
56    pub(crate) fn reset_bookmarks(&mut self) {
57        self.bookmarks = BookmarkState::Unknown;
58        self.bookmarks_asked_at = None;
59        self.bookmark_pending = None;
60        self.bookmark_first_list = false;
61    }
62
63    /// The account that keeps bookmarks: the one signed in, if it has its
64    /// key.
65    fn bookmarking_account(&self) -> Option<PublicKey> {
66        self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key)
67    }
68
69    /// Find out what the account has bookmarked, while the popup is open
70    /// and unless that was asked a moment ago. Called whenever the popup
71    /// opens, and when the account or the store arrive.
72    pub(crate) fn load_bookmarks(&mut self) -> Task<cosmic::Action<Message>> {
73        if self.popup.is_none() || self.bookmark_pending.is_some() {
74            return Task::none();
75        }
76        let now = Instant::now();
77        if self.bookmarks_asked_at.is_some_and(|at| now.duration_since(at) < BOOKMARKS_FRESH) {
78            return Task::none();
79        }
80        let asked = self.ask_bookmarks(Source::Store);
81        if asked.is_some() {
82            self.bookmarks_asked_at = Some(now);
83        }
84        asked.unwrap_or_else(Task::none)
85    }
86
87    /// Ask `source` what the account has bookmarked, if there is an
88    /// account that keeps bookmarks, and a store.
89    fn ask_bookmarks(&self, source: Source) -> Option<Task<cosmic::Action<Message>>> {
90        let (service, account) = (self.nostr.clone()?, self.bookmarking_account()?);
91        let signer = self.signer.clone();
92        let known = self.known_bookmarks().cloned();
93        Some(Task::perform(async move { service.bookmarks(source, &signer, account, known).await }, move |result| {
94            cosmic::Action::App(Message::BookmarksLoaded { account, source, result })
95        }))
96    }
97
98    /// The bookmarks, if they are known.
99    fn known_bookmarks(&self) -> Option<&Bookmarks> {
100        match &self.bookmarks {
101            BookmarkState::Known(bookmarks) => Some(bookmarks),
102            BookmarkState::Unknown | BookmarkState::Unreadable(_) => None,
103        }
104    }
105
106    /// The account's bookmarks are `bookmarks`, unless what is known is
107    /// from a newer list: answers come from the store and from the relays,
108    /// in no order that can be counted on. An open bookmarks page takes
109    /// its notes from them.
110    fn take_bookmarks(&mut self, bookmarks: Bookmarks) -> Task<cosmic::Action<Message>> {
111        let written = |bookmarks: &Bookmarks| bookmarks.list().map(|list| list.created_at);
112        if self.known_bookmarks().is_some_and(|known| written(known) > written(&bookmarks)) {
113            return Task::none();
114        }
115        if bookmarks.list().is_some() {
116            self.bookmark_first_list = false;
117        }
118        self.bookmarks = BookmarkState::Known(Box::new(bookmarks));
119        // What stays in the event store is known now.
120        Task::batch([self.fill_bookmarks_pages(), self.sweep_store()])
121    }
122
123    /// What the account has bookmarked came from the store or from the
124    /// relays, or didn't. After the store, the relays are asked.
125    pub fn handle_bookmarks_loaded(
126        &mut self,
127        account: PublicKey,
128        source: Source,
129        result: Result<Bookmarks, ListError>,
130    ) -> Task<cosmic::Action<Message>> {
131        // Whoever signed out meanwhile took their bookmarks with them.
132        if self.bookmarking_account() != Some(account) {
133            return Task::none();
134        }
135        let taken = match result {
136            // A change on its way is made to the newest list, and says
137            // what the bookmarks are when it is done.
138            Ok(_) if self.bookmark_pending.is_some() => Task::none(),
139            Ok(bookmarks) => {
140                tracing::debug!("{} note(s) bookmarked, by {source:?}", bookmarks.count());
141                self.take_bookmarks(bookmarks)
142            }
143            Err(ListError::Unreadable(e)) => {
144                tracing::error!("the bookmarks could not be read: {e:?}");
145                self.bookmarks = BookmarkState::Unreadable(sign_error_text(e));
146                Task::none()
147            }
148            Err(e) => {
149                tracing::warn!("the bookmarks could not be asked of {source:?}: {e:?}");
150                Task::none()
151            }
152        };
153        let asked = match source {
154            Source::Store => self.ask_bookmarks(Source::Relays).unwrap_or_else(Task::none),
155            Source::Relays => Task::none(),
156        };
157        Task::batch([taken, asked])
158    }
159
160    // =========================================================================
161    // The bookmarks page
162    // =========================================================================
163
164    /// The notes of the bookmarks page `id`, if that page is still open.
165    fn bookmarked_notes_mut(&mut self, id: u64) -> Option<&mut BookmarkedNotes> {
166        self.pages.iter_mut().find_map(|page| match page {
167            Page::Bookmarks(page) if page.id == id => Some(&mut page.notes),
168            _ => None,
169        })
170    }
171
172    /// Have every open bookmarks page take its notes from the bookmarks,
173    /// which are known now or are others than they were, if it was never
174    /// filled or is at its top. Then look up the first of them.
175    fn fill_bookmarks_pages(&mut self) -> Task<cosmic::Action<Message>> {
176        let Self { bookmarks: BookmarkState::Known(bookmarks), pages, .. } = self else {
177            return Task::none();
178        };
179        let mut to_load = Vec::new();
180        for page in pages.iter_mut() {
181            let Page::Bookmarks(page) = page else { continue };
182            if page.notes.taken == 0 || page.notes.position.get() == 0.0 {
183                page.notes.take(bookmarks);
184            }
185            if page.notes.asked == 0 {
186                to_load.push(page.id);
187            }
188        }
189        Task::batch(to_load.into_iter().map(|page| self.handle_load_bookmarked_notes(page)))
190    }
191
192    /// Show the notes the account has bookmarked, over whatever is on show
193    /// now. The bookmarks are asked for again if that was a while ago.
194    pub fn handle_open_bookmarks(&mut self) -> Task<cosmic::Action<Message>> {
195        self.menu_open = false;
196        if self.bookmarking_account().is_none() {
197            return Task::none();
198        }
199        self.feeds_made += 1;
200        let page = BookmarksPage::new(self.feeds_made);
201        let opened = self.open_page(Page::Bookmarks(Box::new(page)));
202        Task::batch([opened, self.fill_bookmarks_pages(), self.load_bookmarks()])
203    }
204
205    /// Look up the next notes of the bookmarks page `page`, unless they
206    /// are being looked up or there are no more.
207    pub fn handle_load_bookmarked_notes(&mut self, page: u64) -> Task<cosmic::Action<Message>> {
208        let Some(service) = self.nostr.clone() else {
209            return Task::none();
210        };
211        let Some(listed) = self.bookmarked_notes_mut(page) else {
212            return Task::none();
213        };
214        if listed.loading || listed.all_asked() {
215            return Task::none();
216        }
217        let from = listed.asked;
218        let ids: Vec<EventId> = listed.ids.iter().skip(from).take(BOOKMARKS_PAGE).copied().collect();
219        let (taken, to) = (listed.taken, from + ids.len());
220        listed.loading = true;
221        // With where the list says each is, for those the account's own
222        // relays don't have.
223        let said = |id: &EventId| match &self.bookmarks {
224            BookmarkState::Known(bookmarks) => bookmarks.whereabouts(id),
225            _ => Whereabouts::default(),
226        };
227        let listed: Vec<(EventId, Whereabouts)> = ids.into_iter().map(|id| (id, said(&id))).collect();
228        Task::perform(async move { service.notes_listed(listed).await }, move |notes| {
229            cosmic::Action::App(Message::BookmarkedNotesLoaded { page, taken, from, to, notes })
230        })
231    }
232
233    /// The notes bookmarked `from`th to `to`th were looked up for the page
234    /// `page`, as it had them the `taken`th time: `notes` are those that
235    /// were found, which go under the ones already there. A page that
236    /// brought none is followed by the next at once: nothing was added to
237    /// the list that scrolling could reach the end of.
238    pub fn handle_bookmarked_notes_loaded(
239        &mut self,
240        page: u64,
241        taken: u64,
242        from: usize,
243        to: usize,
244        notes: Vec<Note>,
245    ) -> Task<cosmic::Action<Message>> {
246        let Some(listed) = self.bookmarked_notes_mut(page) else {
247            return Task::none();
248        };
249        // Asked of a list that was taken anew since.
250        if listed.taken != taken || listed.asked != from {
251            return Task::none();
252        }
253        listed.loading = false;
254        listed.asked = to;
255        listed.missing += to.saturating_sub(from).saturating_sub(notes.len());
256        tracing::debug!("bookmarks: {} of {} note(s) found", notes.len(), to.saturating_sub(from));
257        let people: Vec<PublicKey> = notes.iter().flat_map(Note::people).collect();
258        let ids: Vec<EventId> = notes.iter().map(|note| note.id).collect();
259        listed.notes.extend(notes);
260        let next = if ids.is_empty() { self.handle_load_bookmarked_notes(page) } else { Task::none() };
261        Task::batch([self.look_up_people(people), self.look_up_engagement(ids), next])
262    }
263
264    /// Bookmark the note `id`, or take its bookmark off if it has one.
265    /// Not while another change is on its way, nor before the bookmarks
266    /// are known; and if they could not be read, that is said again.
267    pub fn handle_bookmark(&mut self, id: EventId) -> Task<cosmic::Action<Message>> {
268        self.repost_menu = None;
269        let (Some(service), Some(account)) = (self.nostr.clone(), self.bookmarking_account()) else {
270            return Task::none();
271        };
272        let known = match &self.bookmarks {
273            BookmarkState::Known(bookmarks) => bookmarks.as_ref().clone(),
274            BookmarkState::Unreadable(why) => {
275                self.error_message = Some(fl!("bookmark-unreadable", error = why.as_str()));
276                return Task::none();
277            }
278            BookmarkState::Unknown => return Task::none(),
279        };
280        if self.bookmark_pending.is_some() {
281            return Task::none();
282        }
283        let bookmark = !known.has(&id);
284        self.bookmark_pending = Some((id, bookmark));
285        let (signer, first_list) = (self.signer.clone(), self.bookmark_first_list);
286        Task::perform(
287            async move { service.set_bookmarked(&signer, account, id, bookmark, first_list, Some(known)).await },
288            move |result| cosmic::Action::App(Message::Bookmarked { account, note: id, result }),
289        )
290    }
291
292    /// The bookmark list of `account` was changed for the note `id`, or
293    /// wasn't.
294    pub fn handle_bookmarked(&mut self, account: PublicKey, id: EventId, result: Result<Bookmarks, ListError>) {
295        if self.bookmark_pending.is_some_and(|(pending, _)| pending == id) {
296            self.bookmark_pending = None;
297        }
298        // Whoever signed out meanwhile took their bookmarks with them.
299        if self.bookmarking_account() != Some(account) {
300            return;
301        }
302        self.error_message = match result {
303            Ok(bookmarks) => {
304                tracing::info!("the bookmark list changed: {} note(s) bookmarked", bookmarks.count());
305                // What said there was no list has been answered.
306                let answered = std::mem::take(&mut self.bookmark_first_list);
307                self.bookmarks = BookmarkState::Known(Box::new(bookmarks));
308                if answered { None } else { self.error_message.take() }
309            }
310            Err(ListError::NoList) => {
311                self.bookmark_first_list = true;
312                Some(fl!("bookmark-no-list"))
313            }
314            Err(ListError::Fetch(e)) => {
315                tracing::error!("the bookmark list could not be asked for: {e:?}");
316                let why = match e {
317                    FetchError::NoRelayReachable => fl!("bookmark-unreachable"),
318                    FetchError::Incomplete => fl!("error-relays-incomplete"),
319                    FetchError::Failed(error) => error,
320                };
321                Some(fl!("bookmark-error", error = why))
322            }
323            Err(ListError::Unreadable(e)) => {
324                tracing::error!("the bookmarks could not be read: {e:?}");
325                let why = sign_error_text(e);
326                self.bookmarks = BookmarkState::Unreadable(why.clone());
327                Some(fl!("bookmark-unreadable", error = why))
328            }
329            Err(ListError::Publish(e)) => {
330                tracing::error!("the bookmark list did not go out: {e:?}");
331                Some(fl!("bookmark-error", error = publish_error_text(e)))
332            }
333        };
334    }
335}