Event Subscriptions (#218)

* feat: improve create column command

* refactor: thread

* feat: add window virtualized to event screen

* chore: update deps

* fix: window decoration

* feat: improve mention ntoe

* feat: add subscription to event screen
This commit is contained in:
雨宮蓮
2024-06-26 14:51:50 +07:00
committed by GitHub
parent a4540a0802
commit 717c3e17df
45 changed files with 2504 additions and 2150 deletions

View File

@@ -5,12 +5,12 @@ use std::str::FromStr;
use cocoa::{appkit::NSApp, base::nil, foundation::NSString};
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::{LogicalPosition, LogicalSize, Manager, State, WebviewUrl};
use tauri::utils::config::WindowEffectsConfig;
use tauri::window::Effect;
#[cfg(target_os = "macos")]
use tauri::TitleBarStyle;
use tauri::utils::config::WindowEffectsConfig;
use tauri::WebviewWindowBuilder;
use tauri::window::Effect;
use tauri::{LogicalPosition, LogicalSize, Manager, State, WebviewUrl};
use tauri_plugin_decorum::WebviewWindowExt;
use url::Url;
@@ -25,39 +25,45 @@ pub struct Window {
height: f64,
maximizable: bool,
minimizable: bool,
hidden_title: bool,
}
#[derive(Serialize, Deserialize, Type)]
pub struct Column {
label: String,
url: String,
x: f32,
y: f32,
width: f32,
height: f32,
}
#[tauri::command]
#[specta::specta]
pub fn create_column(
label: &str,
x: f32,
y: f32,
width: f32,
height: f32,
url: &str,
column: Column,
app_handle: tauri::AppHandle,
state: State<'_, Nostr>,
) -> Result<String, String> {
let settings = state.settings.lock().unwrap().clone();
match app_handle.get_window("main") {
Some(main_window) => match app_handle.get_webview(label) {
Some(_) => Ok(label.into()),
Some(main_window) => match app_handle.get_webview(&column.label) {
Some(_) => Ok(column.label),
None => {
let path = PathBuf::from(url);
let path = PathBuf::from(column.url);
let webview_url = WebviewUrl::App(path);
let builder = match settings.proxy {
Some(url) => {
let proxy = Url::from_str(&url).unwrap();
tauri::webview::WebviewBuilder::new(label, webview_url)
tauri::webview::WebviewBuilder::new(column.label, webview_url)
.user_agent("Lume/4.0")
.zoom_hotkeys_enabled(true)
.enable_clipboard_access()
.transparent(true)
.proxy_url(proxy)
}
None => tauri::webview::WebviewBuilder::new(label, webview_url)
None => tauri::webview::WebviewBuilder::new(column.label, webview_url)
.user_agent("Lume/4.0")
.zoom_hotkeys_enabled(true)
.enable_clipboard_access()
@@ -65,8 +71,8 @@ pub fn create_column(
};
match main_window.add_child(
builder,
LogicalPosition::new(x, y),
LogicalSize::new(width, height),
LogicalPosition::new(column.x, column.y),
LogicalSize::new(column.width, column.height),
) {
Ok(webview) => Ok(webview.label().into()),
Err(_) => Err("Create webview failed".into()),
@@ -79,7 +85,7 @@ pub fn create_column(
#[tauri::command]
#[specta::specta]
pub fn close_column(label: &str, app_handle: tauri::AppHandle) -> Result<bool, ()> {
pub fn close_column(label: &str, app_handle: tauri::AppHandle) -> Result<bool, String> {
match app_handle.get_webview(label) {
Some(webview) => {
if webview.close().is_ok() {
@@ -88,7 +94,7 @@ pub fn close_column(label: &str, app_handle: tauri::AppHandle) -> Result<bool, (
Ok(false)
}
}
None => Ok(true),
None => Err("Column not found.".into()),
}
}
@@ -152,14 +158,13 @@ pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<(), S
.title(&window.title)
.min_inner_size(window.width, window.height)
.inner_size(window.width, window.height)
.hidden_title(true)
.hidden_title(window.hidden_title)
.title_bar_style(TitleBarStyle::Overlay)
.transparent(true)
.minimizable(window.minimizable)
.maximizable(window.maximizable)
.effects(WindowEffectsConfig {
state: None,
effects: vec![Effect::WindowBackground],
effects: vec![Effect::UnderWindowBackground],
radius: None,
color: None,
})
@@ -171,7 +176,6 @@ pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<(), S
.title(title)
.min_inner_size(width, height)
.inner_size(width, height)
.transparent(true)
.effects(WindowEffectsConfig {
state: None,
effects: vec![Effect::Mica],
@@ -189,9 +193,12 @@ pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<(), S
.build()
.unwrap();
#[cfg(target_os = "windows")]
// Create a custom titlebar for Windows
// Set decoration
window.create_overlay_titlebar().unwrap();
// Make main window transparent
#[cfg(target_os = "macos")]
window.make_transparent().unwrap();
}
Ok(())
@@ -223,9 +230,13 @@ pub fn open_main_window(app: tauri::AppHandle) {
let _ = window.set_focus();
};
} else {
let _ = WebviewWindowBuilder::from_config(&app, app.config().app.windows.first().unwrap())
let window = WebviewWindowBuilder::from_config(&app, app.config().app.windows.first().unwrap())
.unwrap()
.build()
.unwrap();
// Make main window transparent
#[cfg(target_os = "macos")]
window.make_transparent().unwrap();
}
}

View File

@@ -12,6 +12,7 @@ use tauri_nspanel::{
objc::{class, msg_send, runtime::NO, sel, sel_impl},
panel_delegate, ManagerExt, WebviewWindowExt,
};
use tauri_plugin_decorum::WebviewWindowExt as WebviewWindowExt2;
#[allow(non_upper_case_globals)]
const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;
@@ -22,9 +23,9 @@ pub fn swizzle_to_menubar_panel(app_handle: &tauri::AppHandle) {
});
let window = app_handle.get_webview_window("panel").unwrap();
window.make_transparent().unwrap();
let panel = window.to_panel().unwrap();
let handle = app_handle.clone();
panel_delegate.set_listener(Box::new(move |delegate_name: String| {

View File

@@ -9,20 +9,20 @@ extern crate cocoa;
#[macro_use]
extern crate objc;
use std::sync::Mutex;
use std::time::Duration;
use std::{
fs,
io::{self, BufRead},
str::FromStr,
};
use std::sync::Mutex;
use std::time::Duration;
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::{Manager, path::BaseDirectory};
#[cfg(target_os = "macos")]
use tauri::tray::{MouseButtonState, TrayIconEvent};
use tauri::{path::BaseDirectory, Manager};
use tauri_nspanel::ManagerExt;
use tauri_plugin_decorum::WebviewWindowExt;
@@ -112,6 +112,8 @@ fn main() {
nostr::event::get_event,
nostr::event::get_event_from,
nostr::event::get_replies,
nostr::event::listen_event_reply,
nostr::event::unlisten_event_reply,
nostr::event::get_events_by,
nostr::event::get_local_events,
nostr::event::get_group_events,
@@ -142,10 +144,14 @@ fn main() {
.setup(|app| {
let main_window = app.get_webview_window("main").unwrap();
// Create a custom titlebar for Windows
// Set custom decoration for Windows
#[cfg(target_os = "windows")]
main_window.create_overlay_titlebar().unwrap();
// Make main window transparent
#[cfg(target_os = "macos")]
main_window.make_transparent().unwrap();
// Set a custom inset to the traffic lights
#[cfg(target_os = "macos")]
main_window.set_traffic_lights_inset(8.0, 16.0).unwrap();
@@ -192,7 +198,8 @@ fn main() {
// Config
let opts = Options::new()
.automatic_authentication(true)
.connection_timeout(Some(Duration::from_secs(5)));
.connection_timeout(Some(Duration::from_secs(5)))
.timeout(Duration::from_secs(30));
// Setup nostr client
let client = match database {
@@ -201,29 +208,30 @@ fn main() {
};
// Get bootstrap relays
let relays_path = app
if let Ok(path) = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
.expect("Bootstrap relays not found.");
let file = std::fs::File::open(&relays_path).unwrap();
let lines = io::BufReader::new(file).lines();
{
let file = std::fs::File::open(&path).unwrap();
let lines = io::BufReader::new(file).lines();
// Add bootstrap relays to relay pool
for line in lines.map_while(Result::ok) {
if let Some((relay, option)) = line.split_once(',') {
match RelayMetadata::from_str(option) {
Ok(meta) => {
println!("connecting to bootstrap relay...: {} - {}", relay, meta);
let opts = if meta == RelayMetadata::Read {
RelayOptions::new().read(true).write(false)
} else {
RelayOptions::new().write(true).read(false)
};
let _ = client.add_relay_with_opts(relay, opts).await;
}
Err(_) => {
println!("connecting to bootstrap relay...: {}", relay);
let _ = client.add_relay(relay).await;
// Add bootstrap relays to relay pool
for line in lines.map_while(Result::ok) {
if let Some((relay, option)) = line.split_once(',') {
match RelayMetadata::from_str(option) {
Ok(meta) => {
println!("connecting to bootstrap relay...: {} - {}", relay, meta);
let opts = if meta == RelayMetadata::Read {
RelayOptions::new().read(true).write(false)
} else {
RelayOptions::new().write(true).read(false)
};
let _ = client.add_relay_with_opts(relay, opts).await;
}
Err(_) => {
println!("connecting to bootstrap relay...: {}", relay);
let _ = client.add_relay(relay).await;
}
}
}
}

View File

@@ -9,7 +9,7 @@ use tauri::State;
use crate::nostr::utils::{create_event_tags, dedup_event, parse_event, Meta};
use crate::Nostr;
#[derive(Debug, Serialize, Type)]
#[derive(Debug, Clone, Serialize, Type)]
pub struct RichEvent {
pub raw: String,
pub parsed: Option<Meta>,
@@ -146,33 +146,69 @@ pub async fn get_event_from(
pub async fn get_replies(id: &str, state: State<'_, Nostr>) -> Result<Vec<RichEvent>, String> {
let client = &state.client;
match EventId::from_hex(id) {
Ok(event_id) => {
let filter = Filter::new().kinds(vec![Kind::TextNote]).event(event_id);
let event_id = match EventId::from_hex(id) {
Ok(id) => id,
Err(err) => return Err(err.to_string()),
};
match client.get_events_of(vec![filter], None).await {
Ok(events) => {
let futures = events.into_iter().map(|ev| async move {
let raw = ev.as_json();
let parsed = if ev.kind == Kind::TextNote {
Some(parse_event(&ev.content).await)
} else {
None
};
let filter = Filter::new().kinds(vec![Kind::TextNote]).event(event_id);
RichEvent { raw, parsed }
});
let rich_events = join_all(futures).await;
match client.get_events_of(vec![filter], None).await {
Ok(events) => {
let futures = events.into_iter().map(|ev| async move {
let raw = ev.as_json();
let parsed = if ev.kind == Kind::TextNote {
Some(parse_event(&ev.content).await)
} else {
None
};
Ok(rich_events)
}
Err(err) => Err(err.to_string()),
}
RichEvent { raw, parsed }
});
let rich_events = join_all(futures).await;
Ok(rich_events)
}
Err(_) => Err("Event ID is not valid".into()),
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn listen_event_reply(id: &str, state: State<'_, Nostr>) -> Result<(), String> {
let client = &state.client;
let mut label = "event-".to_owned();
label.push_str(id);
let sub_id = SubscriptionId::new(label);
let event_id = match EventId::from_hex(id) {
Ok(id) => id,
Err(err) => return Err(err.to_string()),
};
let filter = Filter::new()
.kinds(vec![Kind::TextNote])
.event(event_id)
.since(Timestamp::now());
// Subscribe
client.subscribe_with_id(sub_id, vec![filter], None).await;
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn unlisten_event_reply(id: &str, state: State<'_, Nostr>) -> Result<(), ()> {
let client = &state.client;
let sub_id = SubscriptionId::new(id);
// Remove subscription
client.unsubscribe(sub_id).await;
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn get_events_by(

View File

@@ -8,6 +8,8 @@ use specta::Type;
use tauri::{EventTarget, Manager, State};
use tauri_plugin_notification::NotificationExt;
use crate::nostr::event::RichEvent;
use crate::nostr::utils::parse_event;
use crate::{Nostr, Settings};
#[derive(Serialize, Type)]
@@ -44,7 +46,7 @@ pub fn get_accounts() -> Result<Vec<String>, String> {
#[tauri::command]
#[specta::specta]
pub fn create_account() -> Result<Account, ()> {
pub fn create_account() -> Result<Account, String> {
let keys = Keys::generate();
let public_key = keys.public_key();
let secret_key = keys.secret_key().unwrap();
@@ -57,6 +59,19 @@ pub fn create_account() -> Result<Account, ()> {
Ok(result)
}
#[tauri::command]
#[specta::specta]
pub fn get_private_key(npub: &str) -> Result<String, String> {
let keyring = Entry::new(npub, "nostr_secret").unwrap();
if let Ok(nsec) = keyring.get_password() {
let secret_key = SecretKey::from_bech32(nsec).unwrap();
Ok(secret_key.to_bech32().unwrap())
} else {
Err("Key not found".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn save_account(
@@ -94,6 +109,56 @@ pub async fn save_account(
}
}
#[tauri::command]
#[specta::specta]
pub async fn connect_remote_account(uri: &str, state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
match NostrConnectURI::parse(uri) {
Ok(bunker_uri) => {
let app_keys = Keys::generate();
let app_secret = app_keys.secret_key().unwrap().to_string();
// Get remote user
let remote_user = bunker_uri.signer_public_key().unwrap();
let remote_npub = remote_user.to_bech32().unwrap();
match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await {
Ok(signer) => {
let keyring = Entry::new(&remote_npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&app_secret);
// Update signer
let _ = client.set_signer(Some(signer.into())).await;
Ok(remote_npub)
}
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_encrypted_key(npub: &str, password: &str) -> Result<String, String> {
let keyring = Entry::new(npub, "nostr_secret").unwrap();
if let Ok(nsec) = keyring.get_password() {
let secret_key = SecretKey::from_bech32(nsec).unwrap();
let new_key = EncryptedSecretKey::new(&secret_key, password, 16, KeySecurity::Medium);
if let Ok(key) = new_key {
Ok(key.to_bech32().unwrap())
} else {
Err("Encrypt key failed".into())
}
} else {
Err("Key not found".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn load_account(
@@ -105,175 +170,171 @@ pub async fn load_account(
let client = &state.client;
let keyring = Entry::new(npub, "nostr_secret").unwrap();
if let Ok(password) = keyring.get_password() {
match bunker {
Some(uri) => {
let app_keys = Keys::parse(password).expect("Secret Key is modified, please check again.");
let password = match keyring.get_password() {
Ok(pw) => pw,
Err(_) => return Err("Cancelled".into()),
};
match NostrConnectURI::parse(uri) {
Ok(bunker_uri) => {
match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(30), None).await {
Ok(signer) => client.set_signer(Some(signer.into())).await,
Err(err) => return Err(err.to_string()),
}
match bunker {
Some(uri) => {
let app_keys = Keys::parse(password).expect("Secret Key is modified, please check again.");
match NostrConnectURI::parse(uri) {
Ok(bunker_uri) => {
match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(30), None).await {
Ok(signer) => client.set_signer(Some(signer.into())).await,
Err(err) => return Err(err.to_string()),
}
Err(err) => return Err(err.to_string()),
}
}
None => {
let keys = Keys::parse(password).expect("Secret Key is modified, please check again.");
let signer = NostrSigner::Keys(keys);
// Update signer
client.set_signer(Some(signer)).await;
Err(err) => return Err(err.to_string()),
}
}
None => {
let keys = Keys::parse(password).expect("Secret Key is modified, please check again.");
let signer = NostrSigner::Keys(keys);
// Verify signer
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
// Update signer
client.set_signer(Some(signer)).await;
}
}
// Verify signer
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
// Connect to user's relay (NIP-65)
if let Ok(events) = client
.get_events_of(
vec![Filter::new()
.author(public_key)
.kind(Kind::RelayList)
.limit(1)],
None,
)
.await
{
if let Some(event) = events.first() {
let relay_list = nip65::extract_relay_list(event);
for item in relay_list.into_iter() {
let relay_url = item.0.to_string();
let opts = match item.1 {
Some(val) => {
if val == &RelayMetadata::Read {
RelayOptions::new().read(true).write(false)
} else {
RelayOptions::new().write(true).read(false)
}
}
None => RelayOptions::default(),
};
// Add relay to relay pool
let _ = client
.add_relay_with_opts(&relay_url, opts)
.await
.unwrap_or_default();
// Connect relay
client.connect_relay(relay_url).await.unwrap_or_default();
println!("connecting to relay: {} - {:?}", item.0, item.1);
}
}
};
// Get user's contact list
let contacts = client.get_contact_list(None).await.unwrap();
*state.contact_list.lock().unwrap() = contacts;
// Create a subscription for notification
let sub_id = SubscriptionId::new("notification");
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.since(Timestamp::now());
// Subscribe
print!("Subscribing for new notification...");
client.subscribe_with_id(sub_id, vec![filter], None).await;
// Get user's settings
let handle = app.clone();
// Spawn a thread to handle it
tauri::async_runtime::spawn(async move {
let window = handle.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
let ident = "lume:settings";
let filter = Filter::new()
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(ident)
.limit(1);
// Connect to user's relay (NIP-65)
if let Ok(events) = client
.get_events_of(
vec![Filter::new()
.author(public_key)
.kind(Kind::RelayList)
.limit(1)],
Some(Duration::from_secs(10)),
)
.get_events_of(vec![filter], Some(Duration::from_secs(5)))
.await
{
if let Some(event) = events.first() {
let relay_list = nip65::extract_relay_list(event);
for item in relay_list.into_iter() {
let relay_url = item.0.to_string();
let opts = match item.1 {
Some(val) => {
if val == &RelayMetadata::Read {
RelayOptions::new().read(true).write(false)
} else {
RelayOptions::new().write(true).read(false)
}
}
None => RelayOptions::default(),
};
let content = event.content();
if let Ok(decrypted) = signer.nip44_decrypt(public_key, content).await {
let parsed: Settings =
serde_json::from_str(&decrypted).expect("Could not parse settings payload");
// Add relay to relay pool
let _ = client
.add_relay_with_opts(&relay_url, opts)
.await
.unwrap_or_default();
// Connect relay
client.connect_relay(relay_url).await.unwrap_or_default();
println!("connecting to relay: {} - {:?}", item.0, item.1);
*state.settings.lock().unwrap() = parsed;
}
}
};
}
});
// Get user's contact list
let contacts = client
.get_contact_list(Some(Duration::from_secs(10)))
.await
.unwrap();
// Run sync service
let handle = app.clone();
// Spawn a thread to handle it
tauri::async_runtime::spawn(async move {
let window = handle.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
// Update state
*state.contact_list.lock().unwrap() = contacts;
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(500);
// Get user's settings
let handle = app.clone();
// Spawn a thread to handle it
tauri::async_runtime::spawn(async move {
let window = handle.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
match client.reconcile(filter, NegentropyOptions::default()).await {
Ok(_) => println!("Sync notification done."),
Err(_) => println!("Sync notification failed."),
}
});
let ident = "lume:settings";
let filter = Filter::new()
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(ident)
.limit(1);
// Run notification service
// Spawn a thread to handle it
tauri::async_runtime::spawn(async move {
let window = app.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
if let Ok(events) = client
.get_events_of(vec![filter], Some(Duration::from_secs(5)))
.await
{
if let Some(event) = events.first() {
let content = event.content();
if let Ok(decrypted) = signer.nip44_decrypt(public_key, content).await {
let parsed: Settings =
serde_json::from_str(&decrypted).expect("Could not parse settings payload");
*state.settings.lock().unwrap() = parsed;
}
}
}
});
// Run sync service
let handle = app.clone();
// Spawn a thread to handle it
tauri::async_runtime::spawn(async move {
let window = handle.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(500);
match client.reconcile(filter, NegentropyOptions::default()).await {
Ok(_) => println!("Sync notification done."),
Err(_) => println!("Sync notification failed."),
}
});
// Run notification service
// Spawn a thread to handle it
tauri::async_runtime::spawn(async move {
println!("Starting notification service...");
let window = app.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
// Create a subscription for notification
let notification_id = SubscriptionId::new("notification");
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.since(Timestamp::now());
// Subscribe
client
.subscribe_with_id(notification_id.clone(), vec![filter], None)
.await;
// Handle notifications
let _ = client
.handle_notifications(|notification| async {
if let RelayPoolNotification::Event {
// Handle notifications
if client
.handle_notifications(|notification| async {
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event {
subscription_id,
event,
..
} = notification
} = message
{
if subscription_id == notification_id {
println!("new notification: {}", event.as_json());
let id = subscription_id.to_string();
if id.starts_with("notification") {
if app
.emit_to(
EventTarget::window("panel"),
@@ -336,78 +397,39 @@ pub async fn load_account(
}
_ => {}
}
} else if id.starts_with("event-") {
let raw = event.as_json();
let parsed = if event.kind == Kind::TextNote {
Some(parse_event(&event.content).await)
} else {
None
};
if app
.emit_to(
EventTarget::window(id),
"new_reply",
RichEvent { raw, parsed },
)
.is_err()
{
println!("Emit new notification failed.")
}
} else {
println!("new event: {}", event.as_json())
}
} else {
println!("new message: {}", message.as_json())
}
Ok(false)
})
.await;
});
Ok(true)
} else {
Err("Cancelled".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn connect_remote_account(uri: &str, state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
match NostrConnectURI::parse(uri) {
Ok(bunker_uri) => {
let app_keys = Keys::generate();
let app_secret = app_keys.secret_key().unwrap().to_string();
// Get remote user
let remote_user = bunker_uri.signer_public_key().unwrap();
let remote_npub = remote_user.to_bech32().unwrap();
match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await {
Ok(signer) => {
let keyring = Entry::new(&remote_npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&app_secret);
// Update signer
let _ = client.set_signer(Some(signer.into())).await;
Ok(remote_npub)
}
Err(err) => Err(err.to_string()),
}
Ok(false)
})
.await
.is_ok()
{
print!("Listing for new event...");
}
Err(err) => Err(err.to_string()),
}
}
#[tauri::command(async)]
#[specta::specta]
pub fn get_encrypted_key(npub: &str, password: &str) -> Result<String, String> {
let keyring = Entry::new(npub, "nostr_secret").unwrap();
if let Ok(nsec) = keyring.get_password() {
let secret_key = SecretKey::from_bech32(nsec).unwrap();
let new_key = EncryptedSecretKey::new(&secret_key, password, 16, KeySecurity::Medium);
if let Ok(key) = new_key {
Ok(key.to_bech32().unwrap())
} else {
Err("Encrypt key failed".into())
}
} else {
Err("Key not found".into())
}
}
#[tauri::command(async)]
#[specta::specta]
pub fn get_private_key(npub: &str) -> Result<String, String> {
let keyring = Entry::new(npub, "nostr_secret").unwrap();
if let Ok(nsec) = keyring.get_password() {
let secret_key = SecretKey::from_bech32(nsec).unwrap();
Ok(secret_key.to_bech32().unwrap())
} else {
Err("Key not found".into())
}
});
Ok(true)
}

View File

@@ -2,14 +2,14 @@ use std::collections::HashSet;
use std::str::FromStr;
use linkify::LinkFinder;
use nostr_sdk::prelude::Nip19Event;
use nostr_sdk::{Alphabet, Event, EventId, FromBech32, PublicKey, SingleLetterTag, Tag, TagKind};
use nostr_sdk::prelude::Nip19Event;
use reqwest::Client;
use serde::Serialize;
use specta::Type;
use url::Url;
#[derive(Debug, Serialize, Type)]
#[derive(Debug, Clone, Serialize, Type)]
pub struct Meta {
pub content: String,
pub images: Vec<String>,