cosmic_applet_avestruz/handlers/
bookmarks.rs1use 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
47const BOOKMARKS_FRESH: Duration = Duration::from_secs(60);
50
51const BOOKMARKS_PAGE: usize = 20;
53
54impl AppModel {
55 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 fn bookmarking_account(&self) -> Option<PublicKey> {
66 self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key)
67 }
68
69 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 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 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 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 Task::batch([self.fill_bookmarks_pages(), self.sweep_store()])
121 }
122
123 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 if self.bookmarking_account() != Some(account) {
133 return Task::none();
134 }
135 let taken = match result {
136 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 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 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 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 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 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 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 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 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 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 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 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}