Skip to main content

cosmic_applet_avestruz/handlers/
relays.rs

1// SPDX-License-Identifier: MIT
2
3//! The account's relays: where it writes, where it reads and where it
4//! searches, shown as its lists have them and changed there.
5//!
6//! The lists are the account's relay list (NIP-65) and its other lists of
7//! relays (see [`crate::nostr::relay_lists`]). They show as the event
8//! store has them at once, and as the relays have them when they have
9//! answered; until then nothing can be changed, since what is saved
10//! replaces what a list names.
11//!
12//! What a list keeps to itself takes the signer to read, which may ask a
13//! person about each request, so it is read when it is needed: the relays
14//! never connected to and the relays things are looked up on when the
15//! popup opens, since they are gone by all the time; the search relays
16//! when a search page opens; and the rest when the relays page does.
17//!
18//! A search relay has to search, a relay direct messages are sent to has
19//! to know who is asking for them, a relay other people write to, to
20//! reach the account, has to take what they write, and a relay they read
21//! the account's notes on has to let them (see
22//! [`Section::hindrances`]). While the page shows, the relays of those
23//! sets are asked what they say of themselves (NIP-11), each once, and
24//! what one says that gets in the way of what its set is for is said
25//! under its name. One that doesn't answer is not said anything of.
26//!
27//! Relays are added and taken out on the page, and nothing is written
28//! until Save: the popup can close meanwhile, and what was changed is
29//! still there when it opens. Save has each list that names other relays
30//! than the page asked for again, changed and sent out, with everything
31//! else in it as it was. A first list is only written after saying so,
32//! as a first contact list is, and a list whose private part can't be read
33//! is never written over.
34
35use std::collections::HashSet;
36
37use cosmic::prelude::*;
38use nostr_sdk::prelude::{Event, PublicKey, RelayUrl};
39
40use crate::fl;
41use crate::handlers::auth::sign_error_text;
42use crate::handlers::compose::publish_error_text;
43use crate::handlers::feed::fetch_error_text;
44use crate::messages::Message;
45use crate::nostr::client::{FetchError, ListError, Source};
46use crate::nostr::relay_info;
47use crate::nostr::relay_lists::{Kept, ListedRelays, RelayLists, Section, typed_relay};
48use crate::state::{AppModel, RelaysState, ViewState};
49use crate::views::relays::section_title;
50
51/// The lists whose private part is read when the popup opens: they are
52/// gone by whatever is on show.
53pub(crate) const ALWAYS_READ: [Section; 2] = [Section::Blocked, Section::Indexer];
54
55impl AppModel {
56    /// Forget the account's relays: the account changed, and they were
57    /// its own, with whatever was changed and not saved.
58    pub(crate) fn reset_relays(&mut self) {
59        self.relays = RelaysState::default();
60    }
61
62    /// Show the account's relays, in place of the list on show, and ask
63    /// for its lists again, every one read in full.
64    pub fn handle_open_relays(&mut self) -> Task<cosmic::Action<Message>> {
65        self.menu_open = false;
66        self.view_state = ViewState::Relays;
67        self.relays.open.extend(Section::LISTS);
68        // One that didn't say last time is asked again.
69        self.relays.said.retain(|_, info| info.is_some());
70        Task::batch([self.ask_relay_lists(Source::Store), self.ask_relay_use(), self.ask_what_relays_support()])
71    }
72
73    /// Ask the relays of the sets that ask something of a relay what
74    /// they say of themselves, while the relays page shows: those on the
75    /// page that were not asked yet.
76    fn ask_what_relays_support(&mut self) -> Task<cosmic::Action<Message>> {
77        if self.view_state != ViewState::Relays {
78            return Task::none();
79        }
80        let unasked: HashSet<RelayUrl> = Section::ALL
81            .into_iter()
82            .filter(|section| section.asks_of_relays())
83            .flat_map(|section| self.relays.edited.of(section))
84            .filter(|relay| !self.relays.said.contains_key(*relay))
85            .cloned()
86            .collect();
87        let asked = unasked.into_iter().map(|relay| {
88            self.relays.said.insert(relay.clone(), None);
89            let http = self.http.clone();
90            Task::perform(
91                async move {
92                    let info = relay_info::fetch(&http, &relay).await;
93                    (relay, info)
94                },
95                |(relay, info)| cosmic::Action::App(Message::RelaySaid { relay, info }),
96            )
97        });
98        Task::batch(asked.collect::<Vec<_>>())
99    }
100
101    /// Ask how the relays this is connected to are doing, for the relays
102    /// page to say.
103    fn ask_relay_use(&self) -> Task<cosmic::Action<Message>> {
104        let Some(service) = self.nostr.clone() else {
105            return Task::none();
106        };
107        Task::perform(async move { service.relay_use().await }, |in_use| cosmic::Action::App(Message::RelayUseLoaded(in_use)))
108    }
109
110    /// Find out what the account's relay lists say, with the private part
111    /// of the lists of `open` read, while the popup is open, and unless
112    /// the relays said already and those were read then.
113    pub(crate) fn load_relay_lists(&mut self, open: &[Section]) -> Task<cosmic::Action<Message>> {
114        // Reading takes the key, as reading the bookmarks does: not
115        // before there is someone to see what for.
116        if self.popup.is_none() {
117            return Task::none();
118        }
119        let unread =
120            |section: &Section| self.relays.lists.as_ref().is_none_or(|lists| *lists.of(*section).kept() == Kept::Unread);
121        if self.relays.from_relays && !open.iter().any(unread) {
122            return Task::none();
123        }
124        self.relays.open.extend(open);
125        self.ask_relay_lists(Source::Store)
126    }
127
128    /// Ask `source` for the account's relay lists, unless they are being
129    /// changed: what the change leaves is what they are.
130    fn ask_relay_lists(&mut self, source: Source) -> Task<cosmic::Action<Message>> {
131        let (Some(service), Some(account)) = (self.nostr.clone(), self.account.as_ref().map(|account| account.public_key)) else {
132            return Task::none();
133        };
134        if self.relays.saving {
135            return Task::none();
136        }
137        if source == Source::Relays {
138            self.relays.loading = true;
139        }
140        let signer = self.signer.clone();
141        let known = self.relays.lists.clone();
142        let open: Vec<Section> = self.relays.open.iter().copied().collect();
143        Task::perform(async move { service.relay_lists(source, &signer, account, known, &open).await }, move |result| {
144            cosmic::Action::App(Message::RelayListsLoaded { account, source, result })
145        })
146    }
147
148    /// The account's relay lists came from the store or from the relays,
149    /// or didn't. After the store, the relays are asked.
150    pub fn handle_relay_lists_loaded(
151        &mut self,
152        account: PublicKey,
153        source: Source,
154        result: Result<RelayLists, FetchError>,
155    ) -> Task<cosmic::Action<Message>> {
156        // Whoever signed out meanwhile took their relays with them.
157        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
158            return Task::none();
159        }
160        let from_relays = source == Source::Relays;
161        if from_relays {
162            self.relays.loading = false;
163        }
164        match result {
165            // A change on its way says what the lists are when it is done;
166            // and the store's word is not taken over the relays'.
167            Ok(_) if self.relays.saving || (!from_relays && self.relays.from_relays) => {}
168            Ok(lists) => {
169                tracing::debug!("the account's relay lists were read, by {source:?}");
170                // Each set of relays that was not changed here shows
171                // what its list says now; one that was stays as it is.
172                let (before, now) = (self.relays.lists.as_ref().map(RelayLists::sets).unwrap_or_default(), lists.sets());
173                for section in Section::ALL {
174                    if self.relays.edited.of(section) == before.of(section) {
175                        self.relays.edited.set(section, now.of(section).to_vec());
176                    }
177                }
178                self.relays.lists = Some(lists);
179                self.relays.from_relays = from_relays;
180                self.go_by_relay_lists();
181            }
182            Err(e) => {
183                tracing::warn!("the account's relay lists could not be asked of {source:?}: {e:?}");
184                if from_relays && self.view_state == ViewState::Relays {
185                    self.error_message = Some(fl!("relays-not-read", error = fetch_error_text(e)));
186                }
187            }
188        }
189        let next = match source {
190            Source::Store => self.ask_relay_lists(Source::Relays),
191            // The relays were just asked: how they did is news.
192            Source::Relays if self.view_state == ViewState::Relays => self.ask_relay_use(),
193            Source::Relays => Task::none(),
194        };
195        Task::batch([next, self.ask_what_relays_support()])
196    }
197
198    /// Have the relay client go by what the lists say now: where things
199    /// are looked up, and which relays are never connected to.
200    fn go_by_relay_lists(&self) {
201        let (Some(service), Some(lists)) = (&self.nostr, &self.relays.lists) else {
202            return;
203        };
204        service.use_listed(lists.of(Section::Indexer).relays(), lists.of(Section::Blocked).relays());
205    }
206
207    /// Whether the relays of `section` can be changed now: by an account
208    /// with its key, once the relays have said what its lists are, while
209    /// no change is on its way. Not those of a list whose private part
210    /// was not read: a list written without it would lose it.
211    pub(crate) fn relays_can_change(&self, section: Section) -> bool {
212        let read = match section {
213            Section::Outbox | Section::Inbox => true,
214            _ => self.relays.lists.as_ref().is_some_and(|lists| matches!(lists.of(section).kept(), Kept::Read(_))),
215        };
216        self.can_publish() && self.relays.from_relays && !self.relays.saving && read
217    }
218
219    /// Add the relay typed for `section` to it, on the page: nothing is
220    /// written until the relays are saved.
221    pub fn handle_add_relay(&mut self, section: Section) -> Task<cosmic::Action<Message>> {
222        if !self.relays_can_change(section) {
223            return Task::none();
224        }
225        let typed = self.relays.typed(section).trim().to_string();
226        if typed.is_empty() {
227            return Task::none();
228        }
229        match typed_relay(&typed) {
230            Some(relay) => {
231                self.relays.edited.add(section, relay);
232                self.relays.typed.remove(&section);
233            }
234            None => self.error_message = Some(fl!("relays-not-a-relay", typed = typed)),
235        }
236        self.ask_what_relays_support()
237    }
238
239    /// Take `relay` out of `section`, on the page.
240    pub fn handle_remove_relay(&mut self, section: Section, relay: &RelayUrl) {
241        if self.relays_can_change(section) {
242            self.relays.edited.remove(section, relay);
243        }
244    }
245
246    /// Move `relay` a place up `section`, or down, on the page.
247    pub fn handle_shift_relay(&mut self, section: Section, relay: &RelayUrl, up: bool) {
248        if self.relays_can_change(section) {
249            self.relays.edited.shift(section, relay, up);
250        }
251    }
252
253    /// Whether there is anything to save, and it can be saved now.
254    pub(crate) fn relays_can_save(&self) -> bool {
255        self.can_publish() && self.relays.from_relays && !self.relays.saving && self.relays.changed()
256    }
257
258    /// Write the relays as the page has them to the account's lists: each
259    /// list that names others, one after the other.
260    pub fn handle_save_relays(&mut self) -> Task<cosmic::Action<Message>> {
261        if !self.relays_can_save() {
262            return Task::none();
263        }
264        let (Some(service), Some(account)) = (self.nostr.clone(), self.account.as_ref().map(|account| account.public_key)) else {
265            return Task::none();
266        };
267        let Some(lists) = &self.relays.lists else {
268            return Task::none();
269        };
270        let (listed, edited) = (lists.sets(), self.relays.edited.clone());
271        let differs = |section: Section| listed.of(section) != edited.of(section);
272        let advertised_changed = differs(Section::Outbox) || differs(Section::Inbox);
273        let to_change: Vec<(Section, ListedRelays)> = Section::LISTS
274            .into_iter()
275            .filter(|section| self.relays_can_change(*section) && differs(*section))
276            .map(|section| (section, lists.of(section)))
277            .collect();
278        let (signer, first_lists) = (self.signer.clone(), self.relays.first_lists);
279        self.relays.saving = true;
280        self.error_message = None;
281
282        let saving = async move {
283            let advertised = if advertised_changed {
284                let (outbox, inbox) = (edited.of(Section::Outbox), edited.of(Section::Inbox));
285                Some(service.set_advertised_relays(&signer, account, outbox, inbox, first_lists).await)
286            } else {
287                None
288            };
289            let mut changed = Vec::new();
290            for (section, known) in to_change {
291                let relays = edited.of(section);
292                let result = service.set_listed_relays(&signer, account, section, relays, first_lists, Some(known)).await;
293                changed.push((section, result));
294            }
295            (advertised, changed)
296        };
297        Task::perform(saving, move |(advertised, listed)| {
298            cosmic::Action::App(Message::RelaysSaved { account, advertised, listed })
299        })
300    }
301
302    /// The account's lists were changed, or weren't: each is as it came
303    /// back, and the page shows what they say now. What was not saved
304    /// stays on the page, changed, to be saved again.
305    pub fn handle_relays_saved(
306        &mut self,
307        account: PublicKey,
308        advertised: Option<Result<Option<Event>, ListError>>,
309        listed: Vec<(Section, Result<ListedRelays, ListError>)>,
310    ) {
311        self.relays.saving = false;
312        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
313            return;
314        }
315        let Some(lists) = self.relays.lists.as_mut() else {
316            return;
317        };
318        // What went wrong first, and with which set of relays.
319        let mut failed: Option<(Section, ListError)> = None;
320        match advertised {
321            Some(Ok(list)) => {
322                lists.advertised = list;
323                let said = lists.sets();
324                for section in [Section::Outbox, Section::Inbox] {
325                    self.relays.edited.set(section, said.of(section).to_vec());
326                }
327            }
328            Some(Err(e)) => failed = Some((Section::Outbox, e)),
329            None => {}
330        }
331        for (section, result) in listed {
332            match result {
333                Ok(changed) => {
334                    self.relays.edited.set(section, changed.relays());
335                    lists.listed.insert(section, changed);
336                }
337                Err(e) => failed = failed.or(Some((section, e))),
338            }
339        }
340        self.go_by_relay_lists();
341        self.error_message = match failed {
342            None => {
343                self.relays.first_lists = false;
344                None
345            }
346            Some((section, ListError::NoList)) => {
347                self.relays.first_lists = true;
348                Some(fl!("relays-no-list", list = section_title(section)))
349            }
350            Some((_, ListError::Fetch(e))) => {
351                tracing::error!("a relay list could not be asked for: {e:?}");
352                Some(fl!("relays-error", error = fetch_error_text(e)))
353            }
354            Some((_, ListError::Unreadable(e))) => {
355                tracing::error!("a relay list could not be read: {e:?}");
356                Some(fl!("relays-unreadable", error = sign_error_text(e)))
357            }
358            Some((_, ListError::Publish(e))) => {
359                tracing::error!("a relay list did not go out: {e:?}");
360                Some(fl!("relays-error", error = publish_error_text(e)))
361            }
362        };
363    }
364}