Skip to main content

cosmic_applet_avestruz/handlers/
search.rs

1// SPDX-License-Identifier: MIT
2
3//! Searching for people and notes.
4//!
5//! A search page is a page like a thread or a profile: what was typed and
6//! what was found stay with it while the popup is closed, and while a
7//! thread or a profile opened from it is on show, and are gone when it
8//! is left. Nothing of a search is written anywhere: there are no recent
9//! searches, and the words are not logged.
10//!
11//! The relays asked are the account's search relays, as its lists have
12//! them (see [`crate::handlers::relays`]): there are no others, and with
13//! none set the page says where to set them. People and notes are
14//! searched for at once, and the page shows one or the other.
15//!
16//! What is typed that names a person or a note by its address is opened
17//! rather than searched for, and no relay is told. A secret key typed
18//! here is cleared, and goes nowhere.
19
20use std::collections::HashSet;
21
22use cosmic::prelude::*;
23use nostr_sdk::prelude::{EventId, PublicKey, RelayUrl};
24
25use crate::fl;
26use crate::handlers::feed::fetch_error_text;
27use crate::handlers::navigation::scroll_list_to;
28use crate::messages::Message;
29use crate::nostr::client::FetchError;
30use crate::nostr::models::Note;
31use crate::nostr::nip05;
32use crate::nostr::relay_info::{self, RelayInfo};
33use crate::nostr::relay_lists::{Kept, Section};
34use crate::nostr::search::{self, Found, SearchFor, Typed};
35use crate::state::{AppModel, Page, SearchPage, SearchProgress};
36use crate::views::components::RowHeights;
37use crate::views::search::search_input_id;
38
39impl AppModel {
40    /// The search page `id`, if that page is still open.
41    fn search_page_mut(&mut self, id: u64) -> Option<&mut SearchPage> {
42        self.pages.iter_mut().find_map(|page| match page {
43            Page::Search(page) if page.id == id => Some(page.as_mut()),
44            _ => None,
45        })
46    }
47
48    /// The account's search relays, as its lists were last read. `None`
49    /// until they were.
50    pub(crate) fn search_relays(&self) -> Option<Vec<RelayUrl>> {
51        let lists = self.relays.lists.as_ref()?;
52        let search = lists.of(Section::Search);
53        // Not before the private part was looked at: most keep them there.
54        (*search.kept() != Kept::Unread).then(|| search.relays())
55    }
56
57    /// Show a page to search on, over whatever is on show now, with the
58    /// place to type in ready to be typed in. The account's lists are
59    /// asked for, its search relays read in full, unless they were
60    /// already: they say which relays search.
61    pub fn handle_open_search(&mut self) -> Task<cosmic::Action<Message>> {
62        self.menu_open = false;
63        if self.account.is_none() {
64            return Task::none();
65        }
66        self.feeds_made += 1;
67        let opened = self.open_page(Page::Search(Box::new(SearchPage::new(self.feeds_made))));
68        let lists = self.load_relay_lists(&[Section::Search]);
69        Task::batch([opened, lists, cosmic::widget::text_input::focus(search_input_id())])
70    }
71
72    /// What is typed on the search page `id` changed.
73    pub fn handle_search_typed(&mut self, id: u64, typed: String) {
74        if let Some(page) = self.search_page_mut(id) {
75            page.typed = typed;
76        }
77    }
78
79    /// Search for what is typed on the search page `id`; or, if that is
80    /// the address of a person or a note, open it.
81    pub fn handle_search(&mut self, id: u64) -> Task<cosmic::Action<Message>> {
82        let Some(page) = self.search_page_mut(id) else {
83            return Task::none();
84        };
85        match search::typed(&page.typed) {
86            Typed::Nothing => Task::none(),
87            Typed::Secret => {
88                // Not left on the screen either.
89                page.typed.clear();
90                self.error_message = Some(fl!("search-secret"));
91                Task::none()
92            }
93            Typed::Person(person) => self.handle_open_profile(person),
94            Typed::Note(note, whereabouts) => self.handle_open_thread(note, whereabouts),
95            Typed::Name(name) => {
96                page.naming = Some(name.clone());
97                let http = self.http.clone();
98                Task::perform(
99                    async move {
100                        let person = nip05::resolve(&http, &name).await;
101                        (name, person)
102                    },
103                    move |(name, person)| cosmic::Action::App(Message::SearchNamed { page: id, name, person }),
104                )
105            }
106            Typed::Relay(relay) => self.show_relay(id, relay),
107            Typed::Words(words) => self.search_for(id, words),
108        }
109    }
110
111    /// The domain of `name`, typed on the search page `id`, said whose it
112    /// is: their profile opens. Or it didn't, and that is said.
113    pub fn handle_search_named(&mut self, id: u64, name: &str, person: Option<PublicKey>) -> Task<cosmic::Action<Message>> {
114        let Some(page) = self.search_page_mut(id).filter(|page| page.naming.as_deref() == Some(name)) else {
115            return Task::none();
116        };
117        page.naming = None;
118        match person {
119            Some(person) => self.handle_open_profile(person),
120            None => {
121                self.error_message = Some(fl!("search-no-such-name", name = name));
122                Task::none()
123            }
124        }
125    }
126
127    /// Start the search page `id` over for another search: what the last
128    /// one found goes, and the answers that come are to this one. Returns
129    /// which search this is.
130    fn start_search(page: &mut SearchPage) -> u64 {
131        page.serial += 1;
132        page.words = None;
133        page.relay = None;
134        page.relay_info = None;
135        page.naming = None;
136        page.people.clear();
137        page.notes.clear();
138        page.heights = RowHeights::default();
139        page.people_position.set(0.0);
140        page.notes_position.set(0.0);
141        page.people_progress = SearchProgress::Idle;
142        page.notes_progress = SearchProgress::Idle;
143        page.serial
144    }
145
146    /// Show what `relay`, whose address was typed on the search page `id`,
147    /// has: the notes it got last, and what it says of itself.
148    fn show_relay(&mut self, id: u64, relay: RelayUrl) -> Task<cosmic::Action<Message>> {
149        let (Some(service), http) = (self.nostr.clone(), self.http.clone()) else {
150            return Task::none();
151        };
152        let Some(page) = self.search_page_mut(id) else {
153            return Task::none();
154        };
155        let serial = Self::start_search(page);
156        page.relay = Some(relay.clone());
157        page.what = SearchFor::Notes;
158        page.notes_progress = SearchProgress::Searching;
159
160        let notes = {
161            let relay = relay.clone();
162            Task::perform(async move { service.relay_notes(&relay).await.map(Found::Notes) }, move |result| {
163                cosmic::Action::App(Message::SearchFound { page: id, serial, what: SearchFor::Notes, result })
164            })
165        };
166        let info = Task::perform(async move { relay_info::fetch(&http, &relay).await }, move |info| {
167            cosmic::Action::App(Message::RelayInfoLoaded { page: id, serial, info })
168        });
169        Task::batch([notes, info, scroll_list_to(0.0)])
170    }
171
172    /// The relay the search page `id` shows said what it is, or didn't.
173    pub fn handle_relay_info_loaded(&mut self, id: u64, serial: u64, info: Option<RelayInfo>) {
174        if let Some(page) = self.search_page_mut(id).filter(|page| page.serial == serial) {
175            page.relay_info = info;
176        }
177    }
178
179    /// Ask the account's search relays what `words` find, of people and
180    /// of notes, for the search page `id`. With no search relays there is
181    /// nobody to ask, and the page says so.
182    fn search_for(&mut self, id: u64, words: String) -> Task<cosmic::Action<Message>> {
183        let Some(service) = self.nostr.clone() else {
184            return Task::none();
185        };
186        let Some(relays) = self.search_relays().filter(|relays| !relays.is_empty()) else {
187            return Task::none();
188        };
189        let Some(page) = self.search_page_mut(id) else {
190            return Task::none();
191        };
192        let serial = Self::start_search(page);
193        page.words = Some(words.clone());
194        page.people_progress = SearchProgress::Searching;
195        page.notes_progress = SearchProgress::Searching;
196        tracing::debug!("searching {} relay(s)", relays.len());
197
198        let ask = |what: SearchFor| {
199            let (service, relays, words) = (service.clone(), relays.clone(), words.clone());
200            Task::perform(async move { service.search(&relays, &words, what).await }, move |result| {
201                cosmic::Action::App(Message::SearchFound { page: id, serial, what, result })
202            })
203        };
204        Task::batch([ask(SearchFor::People), ask(SearchFor::Notes), scroll_list_to(0.0)])
205    }
206
207    /// Show the people the search page `id` found, or the notes, where
208    /// that list was left.
209    pub fn handle_search_show(&mut self, id: u64, what: SearchFor) -> Task<cosmic::Action<Message>> {
210        let Some(page) = self.search_page_mut(id) else {
211            return Task::none();
212        };
213        if page.what == what {
214            return Task::none();
215        }
216        page.what = what;
217        let position = page.position().get();
218        if self.search_on_top().is_some_and(|on_top| on_top.id == id) { scroll_list_to(position) } else { Task::none() }
219    }
220
221    /// The search relays answered the search page `id`, for the search it
222    /// numbered `serial`, with the people or the notes they found; or
223    /// didn't. An answer to a search that another has replaced is dropped.
224    pub fn handle_search_found(
225        &mut self,
226        id: u64,
227        serial: u64,
228        what: SearchFor,
229        result: Result<Found, FetchError>,
230    ) -> Task<cosmic::Action<Message>> {
231        let followed: HashSet<PublicKey> = self.follows.iter().flatten().copied().collect();
232        let Some(page) = self.search_page_mut(id).filter(|page| page.serial == serial) else {
233            return Task::none();
234        };
235        match result {
236            Ok(Found::People(people)) => {
237                tracing::debug!("search: {} people found", people.len());
238                // Whoever the account follows first: a name is anyone's to take.
239                page.people = search::followed_first(people.iter().map(|(person, _)| *person).collect(), &followed);
240                page.people_progress = SearchProgress::Found;
241                self.handle_profiles_fetched(people)
242            }
243            Ok(Found::Notes(notes)) => {
244                tracing::debug!("search: {} note(s) found", notes.len());
245                let people: Vec<PublicKey> = notes.iter().flat_map(Note::people).collect();
246                let ids: Vec<EventId> = notes.iter().map(|note| note.id).collect();
247                page.notes = notes;
248                page.notes_progress = SearchProgress::Found;
249                Task::batch([self.look_up_people(people), self.look_up_engagement(ids)])
250            }
251            Err(e) => {
252                tracing::warn!("the search for {what:?} did not go through: {e:?}");
253                let failed = SearchProgress::Failed(fetch_error_text(e));
254                match what {
255                    SearchFor::People => page.people_progress = failed,
256                    SearchFor::Notes => page.notes_progress = failed,
257                }
258                Task::none()
259            }
260        }
261    }
262}