Skip to main content

cosmic_applet_avestruz/handlers/
profile.rs

1// SPDX-License-Identifier: MIT
2
3//! Profile message handlers for Avestruz.
4//!
5//! A profile is a page: who someone is and what they say of themselves,
6//! and under that their notes, newest first. It opens with whatever is
7//! known of them already. The event store is asked for the rest and answers
8//! within the frame; the relays are asked at the same time, for their notes
9//! and for whether they have said something newer of themselves.
10//!
11//! The notes are a list like the feed's, kept and filled as the feed is
12//! (see [`crate::handlers::feed`]).
13//!
14//! The name at a domain someone gives as theirs (NIP-05) is checked with
15//! that domain when their profile is open, and only then: a feed of notes
16//! would have a hundred domains asked, and told who reads what.
17//!
18//! Following and unfollowing change the account's contact list, which is
19//! one list everywhere and replaced whole. It is asked of the relays again
20//! just before it is changed, one change at a time, and the feed starts
21//! over with whoever it then follows.
22
23use cosmic::iced::clipboard;
24use cosmic::prelude::*;
25use nostr_sdk::prelude::{PublicKey, ToBech32};
26
27use crate::fl;
28use crate::handlers::compose::publish_error_text;
29use crate::handlers::feed::fetch_profiles;
30use crate::messages::Message;
31use crate::nostr::client::{FetchError, FollowError};
32use crate::nostr::nip05;
33use crate::state::{AppModel, FollowProblem, Nip05Check, Nip05State, Page, ProfileState, ViewState};
34
35impl AppModel {
36    /// Whether the profile of `public_key` is the page on show.
37    fn profile_on_show(&self, public_key: PublicKey) -> bool {
38        self.view_state == ViewState::Page && self.profile_on_top().is_some_and(|state| state.public_key == public_key)
39    }
40
41    /// Whether a profile of `public_key` is open, on show or under other
42    /// pages.
43    fn profile_is_open(&self, public_key: PublicKey) -> bool {
44        self.pages.iter().any(|page| matches!(page, Page::Profile(state) if state.public_key == public_key))
45    }
46
47    /// Show the profile of `public_key`, over whatever is on show now.
48    pub fn handle_open_profile(&mut self, public_key: PublicKey) -> Task<cosmic::Action<Message>> {
49        let Some(service) = self.nostr.clone() else {
50            return Task::none();
51        };
52        if self.profile_on_show(public_key) {
53            return Task::none();
54        }
55        let notes = self.new_feed();
56        let list = notes.id;
57        let opened = self.open_page(Page::Profile(Box::new(ProfileState::new(public_key, notes))));
58
59        // Asked about here and now, whatever was asked before: the store
60        // for what it has, and the relays for anything newer.
61        self.profiles_requested.insert(public_key);
62        let stored = {
63            let service = service.clone();
64            Task::perform(async move { service.cached_profiles(vec![public_key]).await }, |found| {
65                cosmic::Action::App(Message::ProfilesFetched(found))
66            })
67        };
68        let fetched = fetch_profiles(service, vec![public_key]);
69        // A domain that didn't answer the last time may answer now.
70        if self.nip05.get(&public_key).is_some_and(|check| check.state == Nip05State::Unverified) {
71            self.nip05.remove(&public_key);
72        }
73        Task::batch([opened, stored, fetched, self.load_feed(list), self.check_nip05(public_key)])
74    }
75
76    /// Copy the `npub` of `public_key`, whose profile is on show.
77    pub fn handle_copy_npub(&mut self, public_key: PublicKey) -> Task<cosmic::Action<Message>> {
78        for state in self.profiles_mut().filter(|state| state.public_key == public_key) {
79            state.npub_copied = true;
80        }
81        let Ok(npub) = public_key.to_bech32();
82        clipboard::write(npub)
83    }
84
85    // =========================================================================
86    // Names at a domain (NIP-05)
87    // =========================================================================
88
89    /// Ask the domain in the name `person` gives as theirs whether it is,
90    /// if their profile is open and that name was not asked about yet.
91    pub(crate) fn check_nip05(&mut self, person: PublicKey) -> Task<cosmic::Action<Message>> {
92        if !self.profile_is_open(person) {
93            return Task::none();
94        }
95        let Some(name) = self.profiles.get(&person).and_then(|profile| profile.nip05.clone()) else {
96            return Task::none();
97        };
98        if self.nip05.get(&person).is_some_and(|check| check.name == name) {
99            return Task::none();
100        }
101        self.nip05.insert(person, Nip05Check { name: name.clone(), state: Nip05State::Checking });
102        let http = self.http.clone();
103        Task::perform(
104            async move {
105                let verified = nip05::verify(&http, person, &name).await;
106                (name, verified)
107            },
108            move |(name, verified)| cosmic::Action::App(Message::Nip05Checked { person, name, verified }),
109        )
110    }
111
112    /// The domain in `name` said whether it is the name of `person`. If
113    /// they gave another name since, this answer is not about it.
114    pub fn handle_nip05_checked(&mut self, person: PublicKey, name: &str, verified: bool) {
115        if let Some(check) = self.nip05.get_mut(&person).filter(|check| check.name == name) {
116            check.state = if verified { Nip05State::Verified } else { Nip05State::Unverified };
117        }
118    }
119
120    // =========================================================================
121    // Following
122    // =========================================================================
123
124    /// Follow `person` (`follow`), or stop following them. `first_list`
125    /// when the account agreed to a first contact list being written.
126    pub fn handle_follow(&mut self, person: PublicKey, follow: bool, first_list: bool) -> Task<cosmic::Action<Message>> {
127        let (Some(service), Some(account)) = (self.nostr.clone(), self.account.as_ref().map(|account| account.public_key)) else {
128            return Task::none();
129        };
130        if !self.can_publish() || self.follow_pending.is_some() || person == account {
131            return Task::none();
132        }
133        self.follow_pending = Some(person);
134        for state in self.profiles_mut().filter(|state| state.public_key == person) {
135            state.follow_problem = None;
136        }
137        let signer = self.signer.clone();
138        Task::perform(async move { service.set_following(&signer, account, person, follow, first_list).await }, move |result| {
139            cosmic::Action::App(Message::FollowChanged { account, person, result })
140        })
141    }
142
143    /// The contact list of `account` was changed for `person`, or wasn't.
144    /// Changed, the feed starts over with whoever is followed now.
145    pub fn handle_follow_changed(
146        &mut self,
147        account: PublicKey,
148        person: PublicKey,
149        result: Result<Vec<PublicKey>, FollowError>,
150    ) -> Task<cosmic::Action<Message>> {
151        if self.follow_pending == Some(person) {
152            self.follow_pending = None;
153        }
154        // Whoever signed out meanwhile took their follows with them.
155        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
156            return Task::none();
157        }
158        let problem = match result {
159            Ok(follows) => {
160                tracing::info!("the contact list changed: following {} account(s)", follows.len());
161                return self.set_follows(follows);
162            }
163            Err(FollowError::NoList) => FollowProblem::NoList,
164            Err(FollowError::Fetch(e)) => {
165                tracing::error!("the contact list could not be asked for: {e:?}");
166                let why = match e {
167                    FetchError::NoRelayReachable => fl!("profile-follow-unreachable"),
168                    FetchError::Incomplete => fl!("error-relays-incomplete"),
169                    FetchError::Failed(error) => error,
170                };
171                FollowProblem::Failed(fl!("profile-follow-error", error = why))
172            }
173            Err(FollowError::Publish(e)) => {
174                tracing::error!("the contact list did not go out: {e:?}");
175                FollowProblem::Failed(fl!("profile-follow-error", error = publish_error_text(e)))
176            }
177        };
178        let mut told = false;
179        for state in self.profiles_mut().filter(|state| state.public_key == person) {
180            state.follow_problem = Some(problem.clone());
181            told = true;
182        }
183        // Asked for somewhere else than on their profile: among the
184        // people a search found.
185        if !told {
186            self.error_message = Some(match problem {
187                FollowProblem::NoList => fl!("follow-no-list-elsewhere"),
188                FollowProblem::Failed(why) => why,
189            });
190        }
191        Task::none()
192    }
193}