Skip to main content

cosmic_applet_avestruz/handlers/
store.rs

1// SPDX-License-Identifier: MIT
2
3//! Store message handlers for Avestruz: having the event store let go of
4//! what it has kept for longer than the settings say (see
5//! [`crate::nostr::sweep`]).
6//!
7//! Once a day, in the background, and when the settings say another number
8//! of days. A day begins when the account's bookmarks are known, which is
9//! when the popup first opens: what is bookmarked stays, and what is
10//! bookmarked takes the account's key to read. Bookmarks that can't be
11//! read keep everything where it is until they can. An account without
12//! its key keeps no bookmarks here, and its day begins within the hour.
13//!
14//! Nothing on show changes: the lists are in the model, not in the store.
15
16use std::collections::HashSet;
17use std::time::{Duration, Instant};
18
19use cosmic::prelude::*;
20use nostr_sdk::prelude::{EventId, Timestamp};
21
22use crate::messages::Message;
23use crate::state::{AppModel, BookmarkState};
24
25/// How long after the store let go of what is old it does so again.
26const SWEEP_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
27
28/// How long a day is, for counting the days notes are kept.
29const DAY_SECS: u64 = 24 * 60 * 60;
30
31impl AppModel {
32    /// Have the event store let go of what is older than the settings say
33    /// it keeps, unless it did within the day, or keeps everything, or it
34    /// isn't known yet what stays: whose store it is, and what they
35    /// bookmarked. Called every so often, and when either becomes known.
36    pub(crate) fn sweep_store(&mut self) -> Task<cosmic::Action<Message>> {
37        let days = self.config.keep_days;
38        if days == 0 || self.swept_at.is_some_and(|at| at.elapsed() < SWEEP_EVERY) {
39            return Task::none();
40        }
41        let (Some(service), Some(account)) = (self.nostr.clone(), self.account.as_ref()) else {
42            return Task::none();
43        };
44        let bookmarked: HashSet<EventId> = match &self.bookmarks {
45            BookmarkState::Known(bookmarks) => bookmarks.notes().into_iter().collect(),
46            BookmarkState::Unknown if !account.can_sign => HashSet::new(),
47            BookmarkState::Unknown | BookmarkState::Unreadable(_) => return Task::none(),
48        };
49        let account = account.public_key;
50        let before = Timestamp::from_secs(Timestamp::now().as_secs().saturating_sub(u64::from(days) * DAY_SECS));
51        self.swept_at = Some(Instant::now());
52        Task::future(async move {
53            match service.sweep(account, &bookmarked, before).await {
54                Ok(swept) => tracing::info!("the event store let go of {swept} event(s) older than {days} day(s)"),
55                Err(e) => tracing::warn!("the event store could not let go of what is old: {e}"),
56            }
57        })
58        .discard()
59    }
60}