chore: Refactor code for better performance and reliability (#212)

This commit is contained in:
XIAO YU
2024-06-19 16:36:59 +09:00
committed by GitHub
parent e1424b851c
commit 6c26f8967b
5 changed files with 29 additions and 32 deletions

View File

@@ -9,20 +9,20 @@ extern crate cocoa;
#[macro_use] #[macro_use]
extern crate objc; extern crate objc;
use std::sync::Mutex;
use std::time::Duration;
use std::{ use std::{
fs, fs,
io::{self, BufRead}, io::{self, BufRead},
str::FromStr, str::FromStr,
}; };
use std::sync::Mutex;
use std::time::Duration;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use tauri::{Manager, path::BaseDirectory};
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use tauri::tray::{MouseButtonState, TrayIconEvent}; use tauri::tray::{MouseButtonState, TrayIconEvent};
use tauri::{path::BaseDirectory, Manager};
use tauri_nspanel::ManagerExt; use tauri_nspanel::ManagerExt;
use tauri_plugin_decorum::WebviewWindowExt; use tauri_plugin_decorum::WebviewWindowExt;
@@ -152,11 +152,11 @@ fn main() {
// Create panel // Create panel
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
swizzle_to_menubar_panel(&app.handle()); swizzle_to_menubar_panel(app.handle());
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
update_menubar_appearance(&app.handle()); update_menubar_appearance(app.handle());
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
setup_menubar_panel_listeners(&app.handle()); setup_menubar_panel_listeners(app.handle());
// Setup tray icon // Setup tray icon
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@@ -173,7 +173,7 @@ fn main() {
match panel.is_visible() { match panel.is_visible() {
true => panel.order_out(None), true => panel.order_out(None),
false => { false => {
position_menubar_panel(&app, 0.0); position_menubar_panel(app, 0.0);
panel.show(); panel.show();
} }
} }

View File

@@ -6,8 +6,8 @@ use serde::Serialize;
use specta::Type; use specta::Type;
use tauri::State; use tauri::State;
use crate::nostr::utils::{create_event_tags, dedup_event, parse_event, Meta};
use crate::Nostr; use crate::Nostr;
use crate::nostr::utils::{create_event_tags, dedup_event, Meta, parse_event};
#[derive(Debug, Serialize, Type)] #[derive(Debug, Serialize, Type)]
pub struct RichEvent { pub struct RichEvent {
@@ -99,10 +99,10 @@ pub async fn get_event_from(
Ok(RichEvent { raw, parsed }) Ok(RichEvent { raw, parsed })
} else { } else {
return Err("Cannot found this event with current relay list".into()); Err("Cannot found this event with current relay list".into())
} }
} }
Err(err) => return Err(err.to_string()), Err(err) => Err(err.to_string()),
} }
} else { } else {
// Add relay hint to relay pool // Add relay hint to relay pool

View File

@@ -64,20 +64,14 @@ pub async fn save_account(
password: &str, password: &str,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let secret_key: Result<SecretKey, String>; let secret_key = if nsec.starts_with("ncryptsec") {
if nsec.starts_with("ncryptsec") {
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap(); let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap();
secret_key = match encrypted_key.to_secret_key(password) { encrypted_key
Ok(val) => Ok(val), .to_secret_key(password)
Err(err) => Err(err.to_string()), .map_err(|err| err.to_string())
};
} else { } else {
secret_key = match SecretKey::from_bech32(nsec) { SecretKey::from_bech32(nsec).map_err(|err| err.to_string())
Ok(val) => Ok(val), };
Err(err) => Err(err.to_string()),
}
}
match secret_key { match secret_key {
Ok(val) => { Ok(val) => {
@@ -280,11 +274,14 @@ pub async fn load_account(
if subscription_id == notification_id { if subscription_id == notification_id {
println!("new notification: {}", event.as_json()); println!("new notification: {}", event.as_json());
if let Err(_) = app.emit_to( if app
.emit_to(
EventTarget::window("panel"), EventTarget::window("panel"),
"notification", "notification",
event.as_json(), event.as_json(),
) { )
.is_err()
{
println!("Emit new notification failed.") println!("Emit new notification failed.")
} }

View File

@@ -117,12 +117,12 @@ pub fn get_bootstrap_relays(app: tauri::AppHandle) -> Result<Vec<String>, ()> {
.resolve("resources/relays.txt", BaseDirectory::Resource) .resolve("resources/relays.txt", BaseDirectory::Resource)
.expect("Bootstrap relays not found."); .expect("Bootstrap relays not found.");
let file = std::fs::File::open(&relays_path).unwrap(); let file = std::fs::File::open(relays_path).unwrap();
let lines = io::BufReader::new(file).lines(); let lines = io::BufReader::new(file).lines();
let mut relays = Vec::new(); let mut relays = Vec::new();
for line in lines.flatten() { for line in lines.map_while(Result::ok) {
relays.push(line.to_string()) relays.push(line.to_string())
} }
@@ -139,7 +139,7 @@ pub fn save_bootstrap_relays(relays: &str, app: tauri::AppHandle) -> Result<(),
let mut file = fs::OpenOptions::new() let mut file = fs::OpenOptions::new()
.write(true) .write(true)
.open(&relays_path) .open(relays_path)
.unwrap(); .unwrap();
match file.write_all(relays.as_bytes()) { match file.write_all(relays.as_bytes()) {

View File

@@ -2,8 +2,8 @@ use std::collections::HashSet;
use std::str::FromStr; use std::str::FromStr;
use linkify::LinkFinder; use linkify::LinkFinder;
use nostr_sdk::{Alphabet, Event, EventId, FromBech32, PublicKey, SingleLetterTag, Tag, TagKind};
use nostr_sdk::prelude::Nip19Event; use nostr_sdk::prelude::Nip19Event;
use nostr_sdk::{Alphabet, Event, EventId, FromBech32, PublicKey, SingleLetterTag, Tag, TagKind};
use reqwest::Client; use reqwest::Client;
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
@@ -176,7 +176,7 @@ pub fn create_event_tags(content: &str) -> Vec<Tag> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for mention in mentions { for mention in mentions {
let entity = mention.replace("nostr:", "").replace("@", ""); let entity = mention.replace("nostr:", "").replace('@', "");
if !tag_set.contains(&entity) { if !tag_set.contains(&entity) {
if entity.starts_with("npub") { if entity.starts_with("npub") {