use AcquireKeyState for AddColumn

Signed-off-by: kernelkind <kernelkind@gmail.com>
This commit is contained in:
kernelkind
2024-11-02 22:16:04 -04:00
parent 529b76094c
commit 412ba9b565
6 changed files with 143 additions and 109 deletions

View File

@@ -6,7 +6,7 @@ use nostrdb::Ndb;
use crate::{
column::Columns,
imgcache::ImageCache,
login_manager::LoginState,
login_manager::AcquireKeyState,
route::{Route, Router},
storage::{KeyStorageResponse, KeyStorageType},
ui::{
@@ -47,7 +47,7 @@ pub fn render_accounts_route(
columns: &mut Columns,
img_cache: &mut ImageCache,
accounts: &mut AccountManager,
login_state: &mut LoginState,
login_state: &mut AcquireKeyState,
route: AccountsRoute,
) {
let router = columns.column_mut(col).router_mut();

View File

@@ -8,21 +8,23 @@ use reqwest::{Request, Response};
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq)]
pub enum LoginError {
pub enum AcquireKeyError {
InvalidKey,
Nip05Failed(String),
}
impl std::fmt::Display for LoginError {
impl std::fmt::Display for AcquireKeyError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
LoginError::InvalidKey => write!(f, "The inputted key is invalid."),
LoginError::Nip05Failed(e) => write!(f, "Failed to get pubkey from Nip05 address: {e}"),
AcquireKeyError::InvalidKey => write!(f, "The inputted key is invalid."),
AcquireKeyError::Nip05Failed(e) => {
write!(f, "Failed to get pubkey from Nip05 address: {e}")
}
}
}
}
impl std::error::Error for LoginError {}
impl std::error::Error for AcquireKeyError {}
#[derive(Deserialize, Serialize)]
pub struct Nip05Result {
@@ -95,9 +97,9 @@ fn retrieving_nip05_pubkey(key: &str) -> bool {
key.contains('@')
}
pub fn perform_key_retrieval(key: &str) -> Promise<Result<Keypair, LoginError>> {
pub fn perform_key_retrieval(key: &str) -> Promise<Result<Keypair, AcquireKeyError>> {
let key_string = String::from(key);
Promise::spawn_async(async move { get_login_key(&key_string).await })
Promise::spawn_async(async move { get_key(&key_string).await })
}
/// Attempts to turn a string slice key from the user into a Nostr-Sdk Keypair object.
@@ -108,7 +110,7 @@ pub fn perform_key_retrieval(key: &str) -> Promise<Result<Keypair, LoginError>>
/// - Private hex key: "5dab..."
/// - NIP-05 address: "example@nostr.com"
///
pub async fn get_login_key(key: &str) -> Result<Keypair, LoginError> {
pub async fn get_key(key: &str) -> Result<Keypair, AcquireKeyError> {
let tmp_key: &str = if let Some(stripped) = key.strip_prefix('@') {
stripped
} else {
@@ -118,7 +120,7 @@ pub async fn get_login_key(key: &str) -> Result<Keypair, LoginError> {
if retrieving_nip05_pubkey(tmp_key) {
match get_nip05_pubkey(tmp_key).await {
Ok(pubkey) => Ok(Keypair::only_pubkey(pubkey)),
Err(e) => Err(LoginError::Nip05Failed(e.to_string())),
Err(e) => Err(AcquireKeyError::Nip05Failed(e.to_string())),
}
} else if let Ok(pubkey) = Pubkey::try_from_bech32_string(tmp_key, true) {
Ok(Keypair::only_pubkey(pubkey))
@@ -127,7 +129,7 @@ pub async fn get_login_key(key: &str) -> Result<Keypair, LoginError> {
} else if let Ok(secret_key) = SecretKey::from_str(tmp_key) {
Ok(Keypair::from_secret(secret_key))
} else {
Err(LoginError::InvalidKey)
Err(AcquireKeyError::InvalidKey)
}
}
@@ -141,7 +143,7 @@ mod tests {
let pubkey_str = "npub1xtscya34g58tk0z605fvr788k263gsu6cy9x0mhnm87echrgufzsevkk5s";
let expected_pubkey =
Pubkey::try_from_bech32_string(pubkey_str, false).expect("Should not have errored.");
let login_key_result = get_login_key(pubkey_str).await;
let login_key_result = get_key(pubkey_str).await;
assert_eq!(Ok(Keypair::only_pubkey(expected_pubkey)), login_key_result);
}

View File

@@ -1,47 +1,47 @@
use crate::key_parsing::perform_key_retrieval;
use crate::key_parsing::LoginError;
use crate::key_parsing::AcquireKeyError;
use egui::{TextBuffer, TextEdit};
use enostr::Keypair;
use poll_promise::Promise;
/// The UI view interface to log in to a nostr account.
/// The state data for acquiring a nostr key
#[derive(Default)]
pub struct LoginState {
login_key: String,
promise_query: Option<(String, Promise<Result<Keypair, LoginError>>)>,
error: Option<LoginError>,
pub struct AcquireKeyState {
desired_key: String,
promise_query: Option<(String, Promise<Result<Keypair, AcquireKeyError>>)>,
error: Option<AcquireKeyError>,
key_on_error: Option<String>,
should_create_new: bool,
}
impl<'a> LoginState {
impl<'a> AcquireKeyState {
pub fn new() -> Self {
LoginState::default()
AcquireKeyState::default()
}
/// Get the textedit for the login UI without exposing the key variable
pub fn get_login_textedit(
/// Get the textedit for the UI without exposing the key variable
pub fn get_acquire_textedit(
&'a mut self,
textedit_closure: fn(&'a mut dyn TextBuffer) -> TextEdit<'a>,
) -> TextEdit<'a> {
textedit_closure(&mut self.login_key)
textedit_closure(&mut self.desired_key)
}
/// User pressed the 'login' button
pub fn apply_login(&'a mut self) {
/// User pressed the 'acquire' button
pub fn apply_acquire(&'a mut self) {
let new_promise = match &self.promise_query {
Some((query, _)) => {
if query != &self.login_key {
Some(perform_key_retrieval(&self.login_key))
if query != &self.desired_key {
Some(perform_key_retrieval(&self.desired_key))
} else {
None
}
}
None => Some(perform_key_retrieval(&self.login_key)),
None => Some(perform_key_retrieval(&self.desired_key)),
};
if let Some(new_promise) = new_promise {
self.promise_query = Some((self.login_key.clone(), new_promise));
self.promise_query = Some((self.desired_key.clone(), new_promise));
}
}
@@ -51,9 +51,9 @@ impl<'a> LoginState {
}
/// Whether to indicate to the user that a login error occured
pub fn check_for_error(&'a mut self) -> Option<&'a LoginError> {
pub fn check_for_error(&'a mut self) -> Option<&'a AcquireKeyError> {
if let Some(error_key) = &self.key_on_error {
if self.login_key != *error_key {
if self.desired_key != *error_key {
self.error = None;
self.key_on_error = None;
}
@@ -73,7 +73,7 @@ impl<'a> LoginState {
}
Err(e) => {
self.error = Some(e);
self.key_on_error = Some(self.login_key.clone());
self.key_on_error = Some(self.desired_key.clone());
}
};
}
@@ -100,7 +100,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_retrieve_key() {
let mut manager = LoginState::new();
let mut manager = AcquireKeyState::new();
let expected_str = "3efdaebb1d8923ebd99c9e7ace3b4194ab45512e2be79c1b7d68d9243e0d2681";
let expected_key = Keypair::only_pubkey(Pubkey::from_hex(expected_str).unwrap());
@@ -110,21 +110,21 @@ mod tests {
let cur_time = start_time.elapsed();
if cur_time < Duration::from_millis(10u64) {
let _ = manager.get_login_textedit(|text| {
let _ = manager.get_acquire_textedit(|text| {
text.clear();
text.insert_text("test", 0);
egui::TextEdit::singleline(text)
});
manager.apply_login();
manager.apply_acquire();
} else if cur_time < Duration::from_millis(30u64) {
let _ = manager.get_login_textedit(|text| {
let _ = manager.get_acquire_textedit(|text| {
text.clear();
text.insert_text("test2", 0);
egui::TextEdit::singleline(text)
});
manager.apply_login();
manager.apply_acquire();
} else {
let _ = manager.get_login_textedit(|text| {
let _ = manager.get_acquire_textedit(|text| {
text.clear();
text.insert_text(
"3efdaebb1d8923ebd99c9e7ace3b4194ab45512e2be79c1b7d68d9243e0d2681",
@@ -132,7 +132,7 @@ mod tests {
);
egui::TextEdit::singleline(text)
});
manager.apply_login();
manager.apply_acquire();
}
if let Some(key) = manager.check_for_successful_login() {

View File

@@ -1,13 +1,13 @@
use crate::app_style::NotedeckTextStyle;
use crate::key_parsing::LoginError;
use crate::login_manager::LoginState;
use crate::key_parsing::AcquireKeyError;
use crate::login_manager::AcquireKeyState;
use crate::ui::{Preview, PreviewConfig, View};
use egui::TextEdit;
use egui::{Align, Button, Color32, Frame, InnerResponse, Margin, RichText, Vec2};
use enostr::Keypair;
pub struct AccountLoginView<'a> {
manager: &'a mut LoginState,
manager: &'a mut AcquireKeyState,
}
pub enum AccountLoginResponse {
@@ -16,7 +16,7 @@ pub enum AccountLoginResponse {
}
impl<'a> AccountLoginView<'a> {
pub fn new(state: &'a mut LoginState) -> Self {
pub fn new(state: &'a mut AcquireKeyState) -> Self {
AccountLoginView { manager: state }
}
@@ -43,7 +43,7 @@ impl<'a> AccountLoginView<'a> {
self.loading_and_error(ui);
if ui.add(login_button()).clicked() {
self.manager.apply_login();
self.manager.apply_acquire();
}
});
@@ -90,13 +90,13 @@ impl<'a> AccountLoginView<'a> {
}
}
fn show_error(ui: &mut egui::Ui, err: &LoginError) {
fn show_error(ui: &mut egui::Ui, err: &AcquireKeyError) {
ui.horizontal(|ui| {
let error_label = match err {
LoginError::InvalidKey => {
AcquireKeyError::InvalidKey => {
egui::Label::new(RichText::new("Invalid key.").color(ui.visuals().error_fg_color))
}
LoginError::Nip05Failed(e) => {
AcquireKeyError::Nip05Failed(e) => {
egui::Label::new(RichText::new(e).color(ui.visuals().error_fg_color))
}
};
@@ -126,8 +126,8 @@ fn login_button() -> Button<'static> {
.min_size(Vec2::new(0.0, 40.0))
}
fn login_textedit(manager: &mut LoginState) -> TextEdit {
manager.get_login_textedit(|text| {
fn login_textedit(manager: &mut AcquireKeyState) -> TextEdit {
manager.get_acquire_textedit(|text| {
egui::TextEdit::singleline(text)
.hint_text(
RichText::new("Enter your public key (npub, nip05), or private key (nsec) here...")
@@ -143,7 +143,7 @@ mod preview {
use super::*;
pub struct AccountLoginPreview {
manager: LoginState,
manager: AcquireKeyState,
}
impl View for AccountLoginPreview {
@@ -157,7 +157,7 @@ mod preview {
fn preview(cfg: PreviewConfig) -> Self::Prev {
let _ = cfg;
let manager = LoginState::new();
let manager = AcquireKeyState::new();
AccountLoginPreview { manager }
}
}

View File

@@ -1,17 +1,23 @@
use egui::{pos2, vec2, Color32, FontId, ImageSource, Pos2, Rect, RichText, Separator, Ui};
use core::f32;
use std::collections::HashMap;
use egui::{
pos2, vec2, Align, Color32, FontId, Id, ImageSource, Margin, Pos2, Rect, RichText, Separator,
Ui, Vec2,
};
use nostrdb::Ndb;
use tracing::{error, info};
use tracing::error;
use crate::{
app_style::{get_font_size, NotedeckTextStyle},
key_parsing::perform_key_retrieval,
login_manager::AcquireKeyState,
timeline::{PubkeySource, Timeline, TimelineKind},
ui::anim::ICON_EXPANSION_MULTIPLE,
user_account::UserAccount,
Damus,
};
use super::anim::AnimationHelper;
use super::{anim::AnimationHelper, padding};
pub enum AddColumnResponse {
Timeline(Timeline),
@@ -67,13 +73,22 @@ impl AddColumnOption {
}
pub struct AddColumnView<'a> {
key_state_map: &'a mut HashMap<Id, AcquireKeyState>,
ndb: &'a Ndb,
cur_account: Option<&'a UserAccount>,
}
impl<'a> AddColumnView<'a> {
pub fn new(ndb: &'a Ndb, cur_account: Option<&'a UserAccount>) -> Self {
Self { ndb, cur_account }
pub fn new(
key_state_map: &'a mut HashMap<Id, AcquireKeyState>,
ndb: &'a Ndb,
cur_account: Option<&'a UserAccount>,
) -> Self {
Self {
key_state_map,
ndb,
cur_account,
}
}
pub fn ui(&mut self, ui: &mut Ui) -> Option<AddColumnResponse> {
@@ -105,48 +120,49 @@ impl<'a> AddColumnView<'a> {
}
fn external_notification_ui(&mut self, ui: &mut Ui) -> Option<AddColumnResponse> {
ui.label(RichText::new("External Notification").heading());
ui.label("Paste the user's npub that you would like to have a notifications column for:");
padding(16.0, ui, |ui| {
let id = ui.id().with("external_notif");
let key_state = self.key_state_map.entry(id).or_default();
let id = ui.id().with("external_notif");
let mut text = ui.ctx().data_mut(|data| {
let text = data.get_temp_mut_or_insert_with(id, String::new);
text.clone()
});
ui.text_edit_singleline(&mut text);
ui.ctx().data_mut(|d| d.insert_temp(id, text.clone()));
let text_edit = key_state.get_acquire_textedit(|text| {
egui::TextEdit::singleline(text)
.hint_text(
RichText::new("Enter the user's key (npub, hex, nip05) here...")
.text_style(NotedeckTextStyle::Body.text_style()),
)
.vertical_align(Align::Center)
.desired_width(f32::INFINITY)
.min_size(Vec2::new(0.0, 40.0))
.margin(Margin::same(12.0))
});
if ui.button("Validate").clicked() {
if let Some(payload) = perform_key_retrieval(&text).ready() {
match payload {
Ok(keypair) => {
info!(
"Successfully retrieved external notification keypair {}",
keypair.pubkey
);
if let Some(resp) =
AddColumnOption::Notification(PubkeySource::Explicit(keypair.pubkey))
.take_as_response(self.ndb, self.cur_account)
{
Some(resp)
} else {
error!("Failed to get timeline column");
None
}
}
Err(_) => {
info!("User did not enter a valid npub or nip05");
ui.colored_label(Color32::RED, "Please enter a valid npub or nip05");
None
}
}
} else {
ui.add(text_edit);
if ui.button("Add").clicked() {
key_state.apply_acquire();
}
if key_state.is_awaiting_network() {
ui.spinner();
}
if let Some(error) = key_state.check_for_error() {
error!("acquire key error: {}", error);
ui.colored_label(
Color32::RED,
"Please enter a valid npub, public hex key or nip05",
);
}
if let Some(keypair) = key_state.check_for_successful_login() {
key_state.should_create_new();
AddColumnOption::Notification(PubkeySource::Explicit(keypair.pubkey))
.take_as_response(self.ndb, self.cur_account)
} else {
None
}
} else {
None
}
})
.inner
}
fn column_option_ui(&mut self, ui: &mut Ui, data: ColumnOptionData) -> egui::Response {
@@ -326,16 +342,24 @@ pub fn render_add_column_routes(
route: &AddColumnRoute,
) {
let resp = match route {
AddColumnRoute::Base => {
AddColumnView::new(&app.ndb, app.accounts.get_selected_account()).ui(ui)
}
AddColumnRoute::UndecidedNotification => {
AddColumnView::new(&app.ndb, app.accounts.get_selected_account()).notifications_ui(ui)
}
AddColumnRoute::ExternalNotification => {
AddColumnView::new(&app.ndb, app.accounts.get_selected_account())
.external_notification_ui(ui)
}
AddColumnRoute::Base => AddColumnView::new(
&mut app.view_state.id_state_map,
&app.ndb,
app.accounts.get_selected_account(),
)
.ui(ui),
AddColumnRoute::UndecidedNotification => AddColumnView::new(
&mut app.view_state.id_state_map,
&app.ndb,
app.accounts.get_selected_account(),
)
.notifications_ui(ui),
AddColumnRoute::ExternalNotification => AddColumnView::new(
&mut app.view_state.id_state_map,
&app.ndb,
app.accounts.get_selected_account(),
)
.external_notification_ui(ui),
};
if let Some(resp) = resp {
@@ -382,7 +406,12 @@ mod preview {
impl View for AddColumnPreview {
fn ui(&mut self, ui: &mut egui::Ui) {
AddColumnView::new(&self.app.ndb, self.app.accounts.get_selected_account()).ui(ui);
AddColumnView::new(
&mut self.app.view_state.id_state_map,
&self.app.ndb,
self.app.accounts.get_selected_account(),
)
.ui(ui);
}
}

View File

@@ -1,13 +1,16 @@
use crate::login_manager::LoginState;
use std::collections::HashMap;
use crate::login_manager::AcquireKeyState;
/// Various state for views
#[derive(Default)]
pub struct ViewState {
pub login: LoginState,
pub login: AcquireKeyState,
pub id_state_map: HashMap<egui::Id, AcquireKeyState>,
}
impl ViewState {
pub fn login_mut(&mut self) -> &mut LoginState {
pub fn login_mut(&mut self) -> &mut AcquireKeyState {
&mut self.login
}
}