fix: child webview is not reposition after scroll

This commit is contained in:
reya
2024-07-19 13:10:29 +07:00
parent f3db010c74
commit 07ce253f5b
17 changed files with 2163 additions and 2161 deletions
File diff suppressed because it is too large Load Diff
+60 -60
View File
@@ -2,74 +2,74 @@ use crate::Settings;
use nostr_sdk::prelude::*;
pub async fn init_nip65(client: &Client) {
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
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)
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);
}
}
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);
}
}
};
}
};
}
pub async fn get_user_settings(client: &Client) -> Result<Settings, String> {
let ident = "lume:settings";
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
let ident = "lume:settings";
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
let filter = Filter::new()
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(ident)
.limit(1);
let filter = Filter::new()
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(ident)
.limit(1);
if let Ok(events) = client.get_events_of(vec![filter], None).await {
if let Some(event) = events.first() {
let content = event.content();
if let Ok(decrypted) = signer.nip44_decrypt(public_key, content).await {
match serde_json::from_str(&decrypted) {
Ok(parsed) => parsed,
Err(_) => Err("Could not parse settings payload".into()),
if let Ok(events) = client.get_events_of(vec![filter], None).await {
if let Some(event) = events.first() {
let content = event.content();
if let Ok(decrypted) = signer.nip44_decrypt(public_key, content).await {
match serde_json::from_str(&decrypted) {
Ok(parsed) => parsed,
Err(_) => Err("Could not parse settings payload".into()),
}
} else {
Err("Decrypt settings failed.".into())
}
} else {
Err("Settings not found.".into())
}
} else {
Err("Decrypt settings failed.".into())
}
} else {
Err("Settings not found.".into())
Err("Settings not found.".into())
}
} else {
Err("Settings not found.".into())
}
}
+339 -326
View File
@@ -1,3 +1,7 @@
use crate::nostr::event::RichEvent;
use crate::nostr::internal::{get_user_settings, init_nip65};
use crate::nostr::utils::parse_event;
use crate::{Nostr, NEWSFEED_NEG_LIMIT, NOTIFICATION_NEG_LIMIT};
use keyring::Entry;
use keyring_search::{Limit, List, Search};
use nostr_sdk::prelude::*;
@@ -8,402 +12,411 @@ use std::time::Duration;
use tauri::{Emitter, EventTarget, Manager, State};
use tauri_plugin_notification::NotificationExt;
use crate::commands::tray::create_tray_panel;
use crate::nostr::event::RichEvent;
use crate::nostr::internal::{get_user_settings, init_nip65};
use crate::nostr::utils::parse_event;
use crate::{Nostr, NEWSFEED_NEG_LIMIT, NOTIFICATION_NEG_LIMIT};
#[derive(Serialize, Type)]
pub struct Account {
npub: String,
nsec: String,
npub: String,
nsec: String,
}
#[tauri::command]
#[specta::specta]
pub fn get_accounts() -> Result<Vec<String>, String> {
let search = Search::new().map_err(|e| e.to_string())?;
let results = search.by("Account", "nostr_secret");
let search = Search::new().map_err(|e| e.to_string())?;
let results = search.by("Account", "nostr_secret");
match List::list_credentials(results, Limit::All) {
Ok(list) => {
let accounts: HashSet<String> = list
.split_whitespace()
.filter(|v| v.starts_with("npub1"))
.map(String::from)
.collect();
match List::list_credentials(results, Limit::All) {
Ok(list) => {
let accounts: HashSet<String> = list
.split_whitespace()
.filter(|v| v.starts_with("npub1"))
.map(String::from)
.collect();
Ok(accounts.into_iter().collect())
Ok(accounts.into_iter().collect())
}
Err(_) => Err("Empty.".into()),
}
Err(_) => Err("Empty.".into()),
}
}
#[tauri::command]
#[specta::specta]
pub fn create_account() -> Result<Account, String> {
let keys = Keys::generate();
let public_key = keys.public_key();
let secret_key = keys.secret_key().unwrap();
let keys = Keys::generate();
let public_key = keys.public_key();
let secret_key = keys.secret_key().unwrap();
let result = Account {
npub: public_key.to_bech32().unwrap(),
nsec: secret_key.to_bech32().unwrap(),
};
let result = Account {
npub: public_key.to_bech32().unwrap(),
nsec: secret_key.to_bech32().unwrap(),
};
Ok(result)
Ok(result)
}
#[tauri::command]
#[specta::specta]
pub fn get_private_key(npub: &str) -> Result<String, String> {
let keyring = Entry::new(npub, "nostr_secret").unwrap();
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())
}
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(
nsec: &str,
password: &str,
state: State<'_, Nostr>,
nsec: &str,
password: &str,
state: State<'_, Nostr>,
) -> Result<String, String> {
let secret_key = if nsec.starts_with("ncryptsec") {
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap();
encrypted_key
.to_secret_key(password)
.map_err(|err| err.to_string())
} else {
SecretKey::from_bech32(nsec).map_err(|err| err.to_string())
};
let secret_key = if nsec.starts_with("ncryptsec") {
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap();
encrypted_key
.to_secret_key(password)
.map_err(|err| err.to_string())
} else {
SecretKey::from_bech32(nsec).map_err(|err| err.to_string())
};
match secret_key {
Ok(val) => {
let nostr_keys = Keys::new(val);
let npub = nostr_keys.public_key().to_bech32().unwrap();
let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap();
match secret_key {
Ok(val) => {
let nostr_keys = Keys::new(val);
let npub = nostr_keys.public_key().to_bech32().unwrap();
let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap();
let keyring = Entry::new(&npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&nsec);
let keyring = Entry::new(&npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&nsec);
let signer = NostrSigner::Keys(nostr_keys);
let client = &state.client;
let signer = NostrSigner::Keys(nostr_keys);
let client = &state.client;
// Update client's signer
client.set_signer(Some(signer)).await;
// Update client's signer
client.set_signer(Some(signer)).await;
Ok(npub)
Ok(npub)
}
Err(msg) => Err(msg),
}
Err(msg) => Err(msg),
}
}
#[tauri::command]
#[specta::specta]
pub async fn connect_remote_account(uri: &str, state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
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();
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();
// 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);
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;
// Update signer
let _ = client.set_signer(Some(signer.into())).await;
Ok(remote_npub)
Ok(remote_npub)
}
Err(err) => Err(err.to_string()),
}
}
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();
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(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())
if let Ok(key) = new_key {
Ok(key.to_bech32().unwrap())
} else {
Err("Encrypt key failed".into())
}
} else {
Err("Encrypt key failed".into())
Err("Key not found".into())
}
} else {
Err("Key not found".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn load_account(
npub: &str,
bunker: Option<&str>,
state: State<'_, Nostr>,
app: tauri::AppHandle,
npub: &str,
bunker: Option<&str>,
state: State<'_, Nostr>,
app: tauri::AppHandle,
) -> Result<bool, String> {
let handle = app.clone();
let client = &state.client;
let keyring = Entry::new(npub, "nostr_secret").unwrap();
let password = match keyring.get_password() {
Ok(pw) => pw,
Err(_) => return Err("Cancelled".into()),
};
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;
}
}
// Connect to user's relay (NIP-65)
init_nip65(client).await;
// Create tray (macOS)
#[cfg(target_os = "macos")]
create_tray_panel(npub, &handle);
// Get user's contact list
if let Ok(contacts) = client.get_contact_list(None).await {
*state.contact_list.lock().unwrap() = contacts
};
// Get user's settings
if let Ok(settings) = get_user_settings(client).await {
*state.settings.lock().unwrap() = settings
};
tauri::async_runtime::spawn(async move {
let window = handle.get_window("main").unwrap();
let state = window.state::<Nostr>();
let handle = app.clone();
let client = &state.client;
let contact_list = state.contact_list.lock().unwrap().clone();
let keyring = Entry::new(npub, "nostr_secret").unwrap();
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
if !contact_list.is_empty() {
let authors: Vec<PublicKey> = contact_list.into_iter().map(|f| f.public_key).collect();
match client
.reconcile(
Filter::new()
.authors(authors)
.kinds(vec![Kind::TextNote, Kind::Repost])
.limit(NEWSFEED_NEG_LIMIT),
NegentropyOptions::default(),
)
.await
{
Ok(_) => {
if handle.emit_to(EventTarget::Any, "synced", true).is_err() {
println!("Emit event failed.")
}
}
Err(_) => println!("Sync newsfeed failed."),
}
let password = match keyring.get_password() {
Ok(pw) => pw,
Err(_) => return Err("Cancelled".into()),
};
match client
.reconcile(
Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(NOTIFICATION_NEG_LIMIT),
NegentropyOptions::default(),
)
.await
{
Ok(_) => {
if handle.emit_to(EventTarget::Any, "synced", true).is_err() {
println!("Emit event failed.")
}
}
Err(_) => println!("Sync notification failed."),
};
match bunker {
Some(uri) => {
let app_keys =
Keys::parse(password).expect("Secret Key is modified, please check again.");
let subscription_id = SubscriptionId::new("notification");
let subscription = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.since(Timestamp::now());
// Subscribing for new notification...
client
.subscribe_with_id(subscription_id, vec![subscription], None)
.await;
// Handle notifications
client
.handle_notifications(|notification| async {
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event {
subscription_id,
event,
} = message
{
let id = subscription_id.to_string();
if id.starts_with("notification") {
if app
.emit_to(
EventTarget::window("panel"),
"notification",
event.as_json(),
)
.is_err()
{
println!("Emit new notification failed.")
}
let handle = app.app_handle();
let author = client.metadata(event.pubkey).await.unwrap();
match event.kind() {
Kind::TextNote => {
if let Err(e) = handle
.notification()
.builder()
.body("Mentioned you in a thread.")
.title(author.display_name.unwrap_or_else(|| "Lume".to_string()))
.show()
{
println!("Failed to show notification: {:?}", e);
}
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()),
}
}
Kind::Repost => {
if let Err(e) = handle
.notification()
.builder()
.body("Reposted your note.")
.title(author.display_name.unwrap_or_else(|| "Lume".to_string()))
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
Kind::Reaction => {
let content = event.content();
if let Err(e) = handle
.notification()
.builder()
.body(content)
.title(author.display_name.unwrap_or_else(|| "Lume".to_string()))
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
Kind::ZapReceipt => {
if let Err(e) = handle
.notification()
.builder()
.body("Zapped you.")
.title(author.display_name.unwrap_or_else(|| "Lume".to_string()))
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
_ => {}
}
} 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 if id.starts_with("column-") {
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_event",
RichEvent { raw, parsed },
)
.is_err()
{
println!("Emit new notification failed.")
}
} else {
println!("new event: {}", event.as_json())
Err(err) => return Err(err.to_string()),
}
} else {
println!("new message: {}", message.as_json())
}
}
Ok(false)
})
.await
});
None => {
let keys = Keys::parse(password).expect("Secret Key is modified, please check again.");
let signer = NostrSigner::Keys(keys);
Ok(true)
// Update signer
client.set_signer(Some(signer)).await;
}
}
// Connect to user's relay (NIP-65)
init_nip65(client).await;
// Get user's contact list
if let Ok(contacts) = client.get_contact_list(None).await {
*state.contact_list.lock().unwrap() = contacts
};
// Get user's settings
if let Ok(settings) = get_user_settings(client).await {
*state.settings.lock().unwrap() = settings
};
tauri::async_runtime::spawn(async move {
let window = handle.get_window("main").unwrap();
let state = window.state::<Nostr>();
let client = &state.client;
let contact_list = state.contact_list.lock().unwrap().clone();
let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap();
if !contact_list.is_empty() {
let authors: Vec<PublicKey> = contact_list.into_iter().map(|f| f.public_key).collect();
match client
.reconcile(
Filter::new()
.authors(authors)
.kinds(vec![Kind::TextNote, Kind::Repost])
.limit(NEWSFEED_NEG_LIMIT),
NegentropyOptions::default(),
)
.await
{
Ok(_) => {
if handle.emit_to(EventTarget::Any, "synced", true).is_err() {
println!("Emit event failed.")
}
}
Err(_) => println!("Sync newsfeed failed."),
}
};
match client
.reconcile(
Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(NOTIFICATION_NEG_LIMIT),
NegentropyOptions::default(),
)
.await
{
Ok(_) => {
if handle.emit_to(EventTarget::Any, "synced", true).is_err() {
println!("Emit event failed.")
}
}
Err(_) => println!("Sync notification failed."),
};
let subscription_id = SubscriptionId::new("notification");
let subscription = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.since(Timestamp::now());
// Subscribing for new notification...
let _ = client
.subscribe_with_id(subscription_id, vec![subscription], None)
.await;
// Handle notifications
client
.handle_notifications(|notification| async {
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event {
subscription_id,
event,
} = message
{
let id = subscription_id.to_string();
if id.starts_with("notification") {
if app
.emit_to(
EventTarget::window("panel"),
"notification",
event.as_json(),
)
.is_err()
{
println!("Emit new notification failed.")
}
let handle = app.app_handle();
let author = client.metadata(event.pubkey).await.unwrap();
match event.kind() {
Kind::TextNote => {
if let Err(e) = handle
.notification()
.builder()
.body("Mentioned you in a thread.")
.title(
author
.display_name
.unwrap_or_else(|| "Lume".to_string()),
)
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
Kind::Repost => {
if let Err(e) = handle
.notification()
.builder()
.body("Reposted your note.")
.title(
author
.display_name
.unwrap_or_else(|| "Lume".to_string()),
)
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
Kind::Reaction => {
let content = event.content();
if let Err(e) = handle
.notification()
.builder()
.body(content)
.title(
author
.display_name
.unwrap_or_else(|| "Lume".to_string()),
)
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
Kind::ZapReceipt => {
if let Err(e) = handle
.notification()
.builder()
.body("Zapped you.")
.title(
author
.display_name
.unwrap_or_else(|| "Lume".to_string()),
)
.show()
{
println!("Failed to show notification: {:?}", e);
}
}
_ => {}
}
} 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 if id.starts_with("column-") {
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_event",
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)
}
+409 -406
View File
@@ -11,584 +11,587 @@ use super::get_latest_event;
#[tauri::command]
#[specta::specta]
pub async fn get_current_profile(state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
let client = &state.client;
let signer = match client.signer().await {
Ok(signer) => signer,
Err(err) => return Err(format!("Failed to get signer: {}", err)),
};
let signer = match client.signer().await {
Ok(signer) => signer,
Err(err) => return Err(format!("Failed to get signer: {}", err)),
};
let public_key = match signer.public_key().await {
Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)),
};
let public_key = match signer.public_key().await {
Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)),
};
let filter = Filter::new()
.author(public_key)
.kind(Kind::Metadata)
.limit(1);
let filter = Filter::new()
.author(public_key)
.kind(Kind::Metadata)
.limit(1);
let events_result = client
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
.await;
let events_result = client
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
.await;
match events_result {
Ok(events) => {
if let Some(event) = get_latest_event(&events) {
match Metadata::from_json(&event.content) {
Ok(metadata) => Ok(metadata.as_json()),
Err(_) => Err("Failed to parse metadata.".into()),
match events_result {
Ok(events) => {
if let Some(event) = get_latest_event(&events) {
match Metadata::from_json(&event.content) {
Ok(metadata) => Ok(metadata.as_json()),
Err(_) => Err("Failed to parse metadata.".into()),
}
} else {
Err("No matching events found.".into())
}
}
} else {
Err("No matching events found.".into())
}
Err(err) => Err(format!("Failed to get events: {}", err)),
}
Err(err) => Err(format!("Failed to get events: {}", err)),
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_profile(id: &str, state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
let public_key: Option<PublicKey> = match Nip19::from_bech32(id) {
Ok(val) => match val {
Nip19::Pubkey(key) => Some(key),
Nip19::Profile(profile) => {
let relays = profile.relays;
for relay in relays.into_iter() {
let _ = client.add_relay(&relay).await.unwrap_or_default();
client.connect_relay(&relay).await.unwrap_or_default();
}
Some(profile.public_key)
}
_ => None,
},
Err(_) => match PublicKey::from_str(id) {
Ok(val) => Some(val),
Err(_) => None,
},
};
let client = &state.client;
let public_key: Option<PublicKey> = match Nip19::from_bech32(id) {
Ok(val) => match val {
Nip19::Pubkey(key) => Some(key),
Nip19::Profile(profile) => {
let relays = profile.relays;
for relay in relays.into_iter() {
let _ = client.add_relay(&relay).await.unwrap_or_default();
client.connect_relay(&relay).await.unwrap_or_default();
}
Some(profile.public_key)
}
_ => None,
},
Err(_) => match PublicKey::from_str(id) {
Ok(val) => Some(val),
Err(_) => None,
},
};
if let Some(author) = public_key {
let filter = Filter::new().author(author).kind(Kind::Metadata).limit(1);
let query = client
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
.await;
if let Some(author) = public_key {
let filter = Filter::new().author(author).kind(Kind::Metadata).limit(1);
let query = client
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
.await;
if let Ok(events) = query {
if let Some(event) = events.first() {
if let Ok(metadata) = Metadata::from_json(&event.content) {
Ok(metadata.as_json())
if let Ok(events) = query {
if let Some(event) = events.first() {
if let Ok(metadata) = Metadata::from_json(&event.content) {
Ok(metadata.as_json())
} else {
Err("Parse metadata failed".into())
}
} else {
let rand_metadata = Metadata::new();
Ok(rand_metadata.as_json())
}
} else {
Err("Parse metadata failed".into())
Err("Get metadata failed".into())
}
} else {
let rand_metadata = Metadata::new();
Ok(rand_metadata.as_json())
}
} else {
Err("Get metadata failed".into())
Err("Public Key is not valid".into())
}
} else {
Err("Public Key is not valid".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn set_contact_list(
public_keys: Vec<&str>,
state: State<'_, Nostr>,
public_keys: Vec<&str>,
state: State<'_, Nostr>,
) -> Result<bool, String> {
let client = &state.client;
let contact_list: Vec<Contact> = public_keys
.into_iter()
.filter_map(|p| match PublicKey::from_hex(p) {
Ok(pk) => Some(Contact::new(pk, None, Some(""))),
Err(_) => None,
})
.collect();
let client = &state.client;
let contact_list: Vec<Contact> = public_keys
.into_iter()
.filter_map(|p| match PublicKey::from_hex(p) {
Ok(pk) => Some(Contact::new(pk, None, Some(""))),
Err(_) => None,
})
.collect();
match client.set_contact_list(contact_list).await {
Ok(_) => Ok(true),
Err(err) => Err(err.to_string()),
}
match client.set_contact_list(contact_list).await {
Ok(_) => Ok(true),
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_contact_list(state: State<'_, Nostr>) -> Result<Vec<String>, String> {
let client = &state.client;
let client = &state.client;
match client.get_contact_list(Some(Duration::from_secs(10))).await {
Ok(contact_list) => {
if !contact_list.is_empty() {
let list = contact_list
.into_iter()
.map(|f| f.public_key.to_hex())
.collect();
match client.get_contact_list(Some(Duration::from_secs(10))).await {
Ok(contact_list) => {
if !contact_list.is_empty() {
let list = contact_list
.into_iter()
.map(|f| f.public_key.to_hex())
.collect();
Ok(list)
} else {
Err("Empty.".into())
}
Ok(list)
} else {
Err("Empty.".into())
}
}
Err(err) => Err(err.to_string()),
}
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn create_profile(
name: &str,
display_name: &str,
about: &str,
picture: &str,
banner: &str,
nip05: &str,
lud16: &str,
website: &str,
state: State<'_, Nostr>,
name: &str,
display_name: &str,
about: &str,
picture: &str,
banner: &str,
nip05: &str,
lud16: &str,
website: &str,
state: State<'_, Nostr>,
) -> Result<String, String> {
let client = &state.client;
let mut metadata = Metadata::new()
.name(name)
.display_name(display_name)
.about(about)
.nip05(nip05)
.lud16(lud16);
let client = &state.client;
let mut metadata = Metadata::new()
.name(name)
.display_name(display_name)
.about(about)
.nip05(nip05)
.lud16(lud16);
if let Ok(url) = Url::parse(picture) {
metadata = metadata.picture(url)
}
if let Ok(url) = Url::parse(picture) {
metadata = metadata.picture(url)
}
if let Ok(url) = Url::parse(banner) {
metadata = metadata.banner(url)
}
if let Ok(url) = Url::parse(banner) {
metadata = metadata.banner(url)
}
if let Ok(url) = Url::parse(website) {
metadata = metadata.website(url)
}
if let Ok(url) = Url::parse(website) {
metadata = metadata.website(url)
}
if let Ok(event_id) = client.set_metadata(&metadata).await {
Ok(event_id.to_string())
} else {
Err("Create profile failed".into())
}
if let Ok(event_id) = client.set_metadata(&metadata).await {
Ok(event_id.to_string())
} else {
Err("Create profile failed".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn is_contact_list_empty(state: State<'_, Nostr>) -> Result<bool, ()> {
let contact_list = state.contact_list.lock().unwrap();
Ok(contact_list.is_empty())
let contact_list = state.contact_list.lock().unwrap();
Ok(contact_list.is_empty())
}
#[tauri::command]
#[specta::specta]
pub async fn check_contact(hex: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let contact_list = state.contact_list.lock().unwrap();
let contact_list = state.contact_list.lock().unwrap();
match PublicKey::from_str(hex) {
Ok(public_key) => match contact_list.iter().position(|x| x.public_key == public_key) {
Some(_) => Ok(true),
None => Ok(false),
},
Err(err) => Err(err.to_string()),
}
match PublicKey::from_str(hex) {
Ok(public_key) => match contact_list.iter().position(|x| x.public_key == public_key) {
Some(_) => Ok(true),
None => Ok(false),
},
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn toggle_contact(
hex: &str,
alias: Option<&str>,
state: State<'_, Nostr>,
hex: &str,
alias: Option<&str>,
state: State<'_, Nostr>,
) -> Result<String, String> {
let client = &state.client;
let client = &state.client;
match client.get_contact_list(None).await {
Ok(mut contact_list) => {
let public_key = PublicKey::from_str(hex).unwrap();
match client.get_contact_list(None).await {
Ok(mut contact_list) => {
let public_key = PublicKey::from_str(hex).unwrap();
match contact_list.iter().position(|x| x.public_key == public_key) {
Some(index) => {
// Remove contact
contact_list.remove(index);
match contact_list.iter().position(|x| x.public_key == public_key) {
Some(index) => {
// Remove contact
contact_list.remove(index);
}
None => {
// TODO: Add relay_url
let new_contact = Contact::new(public_key, None, alias);
// Add new contact
contact_list.push(new_contact);
}
}
// Update local state
state.contact_list.lock().unwrap().clone_from(&contact_list);
// Publish
match client.set_contact_list(contact_list).await {
Ok(event_id) => Ok(event_id.to_string()),
Err(err) => Err(err.to_string()),
}
}
None => {
// TODO: Add relay_url
let new_contact = Contact::new(public_key, None, alias);
// Add new contact
contact_list.push(new_contact);
}
}
// Update local state
state.contact_list.lock().unwrap().clone_from(&contact_list);
// Publish
match client.set_contact_list(contact_list).await {
Ok(event_id) => Ok(event_id.to_string()),
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn set_nstore(
key: &str,
content: &str,
state: State<'_, Nostr>,
key: &str,
content: &str,
state: State<'_, Nostr>,
) -> Result<String, String> {
let client = &state.client;
let client = &state.client;
match client.signer().await {
Ok(signer) => {
let public_key = match signer.public_key().await {
Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)),
};
match client.signer().await {
Ok(signer) => {
let public_key = match signer.public_key().await {
Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)),
};
let encrypted = match signer.nip44_encrypt(public_key, content).await {
Ok(enc) => enc,
Err(err) => return Err(format!("Encryption failed: {}", err)),
};
let encrypted = match signer.nip44_encrypt(public_key, content).await {
Ok(enc) => enc,
Err(err) => return Err(format!("Encryption failed: {}", err)),
};
let tag = Tag::identifier(key);
let builder = EventBuilder::new(Kind::ApplicationSpecificData, encrypted, vec![tag]);
let tag = Tag::identifier(key);
let builder = EventBuilder::new(Kind::ApplicationSpecificData, encrypted, vec![tag]);
match client.send_event_builder(builder).await {
Ok(event_id) => Ok(event_id.to_string()),
match client.send_event_builder(builder).await {
Ok(event_id) => Ok(event_id.to_string()),
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_nstore(key: &str, state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
let client = &state.client;
if let Ok(signer) = client.signer().await {
let public_key = match signer.public_key().await {
Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)),
};
if let Ok(signer) = client.signer().await {
let public_key = match signer.public_key().await {
Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)),
};
let filter = Filter::new()
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(key)
.limit(1);
let filter = Filter::new()
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(key)
.limit(1);
match client
.get_events_of(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => {
if let Some(event) = events.first() {
let content = event.content();
match signer.nip44_decrypt(public_key, content).await {
Ok(decrypted) => Ok(decrypted),
Err(_) => Err(event.content.to_string()),
}
} else {
Err("Value not found".into())
match client
.get_events_of(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => {
if let Some(event) = events.first() {
let content = event.content();
match signer.nip44_decrypt(public_key, content).await {
Ok(decrypted) => Ok(decrypted),
Err(_) => Err(event.content.to_string()),
}
} else {
Err("Value not found".into())
}
}
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
} else {
Err("Signer is required".into())
}
} else {
Err("Signer is required".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn set_wallet(uri: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let client = &state.client;
let client = &state.client;
if let Ok(nwc_uri) = NostrWalletConnectURI::from_str(uri) {
let nwc = NWC::new(nwc_uri);
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").map_err(|e| e.to_string())?;
keyring.set_password(uri).map_err(|e| e.to_string())?;
client.set_zapper(nwc).await;
if let Ok(nwc_uri) = NostrWalletConnectURI::from_str(uri) {
let nwc = NWC::new(nwc_uri);
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").map_err(|e| e.to_string())?;
keyring.set_password(uri).map_err(|e| e.to_string())?;
client.set_zapper(nwc).await;
Ok(true)
} else {
Err("Set NWC failed".into())
}
Ok(true)
} else {
Err("Set NWC failed".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn load_wallet(state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client;
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap();
let client = &state.client;
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap();
match keyring.get_password() {
Ok(val) => {
let uri = NostrWalletConnectURI::from_str(&val).unwrap();
let nwc = NWC::new(uri);
match keyring.get_password() {
Ok(val) => {
let uri = NostrWalletConnectURI::from_str(&val).unwrap();
let nwc = NWC::new(uri);
// Get current balance
let balance = nwc.get_balance().await;
// Get current balance
let balance = nwc.get_balance().await;
// Update zapper
client.set_zapper(nwc).await;
// Update zapper
client.set_zapper(nwc).await;
match balance {
Ok(val) => Ok(val.to_string()),
Err(_) => Err("Get balance failed.".into()),
}
match balance {
Ok(val) => Ok(val.to_string()),
Err(_) => Err("Get balance failed.".into()),
}
}
Err(_) => Err("NWC not found.".into()),
}
Err(_) => Err("NWC not found.".into()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn remove_wallet(state: State<'_, Nostr>) -> Result<(), ()> {
let client = &state.client;
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap();
let client = &state.client;
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap();
match keyring.delete_password() {
Ok(_) => {
client.unset_zapper().await;
Ok(())
match keyring.delete_password() {
Ok(_) => {
client.unset_zapper().await;
Ok(())
}
Err(_) => Err(()),
}
Err(_) => Err(()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn zap_profile(
id: &str,
amount: &str,
message: &str,
state: State<'_, Nostr>,
id: &str,
amount: &str,
message: &str,
state: State<'_, Nostr>,
) -> Result<bool, String> {
let client = &state.client;
let public_key = match Nip19::from_bech32(id) {
Ok(val) => match val {
Nip19::Pubkey(key) => key,
Nip19::Profile(profile) => profile.public_key,
_ => return Err("Public Key is not valid.".into()),
},
Err(_) => match PublicKey::from_str(id) {
Ok(val) => val,
Err(_) => return Err("Public Key is not valid.".into()),
},
};
let client = &state.client;
let public_key = match Nip19::from_bech32(id) {
Ok(val) => match val {
Nip19::Pubkey(key) => key,
Nip19::Profile(profile) => profile.public_key,
_ => return Err("Public Key is not valid.".into()),
},
Err(_) => match PublicKey::from_str(id) {
Ok(val) => val,
Err(_) => return Err("Public Key is not valid.".into()),
},
};
let details = ZapDetails::new(ZapType::Private).message(message);
let num = match amount.parse::<u64>() {
Ok(val) => val,
Err(_) => return Err("Invalid amount.".into()),
};
let details = ZapDetails::new(ZapType::Private).message(message);
let num = match amount.parse::<u64>() {
Ok(val) => val,
Err(_) => return Err("Invalid amount.".into()),
};
if client.zap(public_key, num, Some(details)).await.is_ok() {
Ok(true)
} else {
Err("Zap profile failed".into())
}
if client.zap(public_key, num, Some(details)).await.is_ok() {
Ok(true)
} else {
Err("Zap profile failed".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn zap_event(
id: &str,
amount: &str,
message: &str,
state: State<'_, Nostr>,
id: &str,
amount: &str,
message: &str,
state: State<'_, Nostr>,
) -> Result<bool, String> {
let client = &state.client;
let event_id = match Nip19::from_bech32(id) {
Ok(val) => match val {
Nip19::EventId(id) => id,
Nip19::Event(event) => event.event_id,
_ => return Err("Event ID is invalid.".into()),
},
Err(_) => match EventId::from_hex(id) {
Ok(val) => val,
Err(_) => return Err("Event ID is invalid.".into()),
},
};
let client = &state.client;
let event_id = match Nip19::from_bech32(id) {
Ok(val) => match val {
Nip19::EventId(id) => id,
Nip19::Event(event) => event.event_id,
_ => return Err("Event ID is invalid.".into()),
},
Err(_) => match EventId::from_hex(id) {
Ok(val) => val,
Err(_) => return Err("Event ID is invalid.".into()),
},
};
let details = ZapDetails::new(ZapType::Private).message(message);
let num = match amount.parse::<u64>() {
Ok(val) => val,
Err(_) => return Err("Invalid amount.".into()),
};
let details = ZapDetails::new(ZapType::Private).message(message);
let num = match amount.parse::<u64>() {
Ok(val) => val,
Err(_) => return Err("Invalid amount.".into()),
};
if client.zap(event_id, num, Some(details)).await.is_ok() {
Ok(true)
} else {
Err("Zap event failed".into())
}
if client.zap(event_id, num, Some(details)).await.is_ok() {
Ok(true)
} else {
Err("Zap event failed".into())
}
}
#[tauri::command]
#[specta::specta]
pub async fn friend_to_friend(npub: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let client = &state.client;
let client = &state.client;
match PublicKey::from_bech32(npub) {
Ok(author) => {
let mut contact_list: Vec<Contact> = Vec::new();
let contact_list_filter = Filter::new()
.author(author)
.kind(Kind::ContactList)
.limit(1);
match PublicKey::from_bech32(npub) {
Ok(author) => {
let mut contact_list: Vec<Contact> = Vec::new();
let contact_list_filter = Filter::new()
.author(author)
.kind(Kind::ContactList)
.limit(1);
if let Ok(contact_list_events) = client.get_events_of(vec![contact_list_filter], None).await {
for event in contact_list_events.into_iter() {
for tag in event.into_iter_tags() {
if let Some(TagStandard::PublicKey {
public_key,
relay_url,
alias,
uppercase: false,
}) = tag.to_standardized()
if let Ok(contact_list_events) =
client.get_events_of(vec![contact_list_filter], None).await
{
contact_list.push(Contact::new(public_key, relay_url, alias))
for event in contact_list_events.into_iter() {
for tag in event.into_iter_tags() {
if let Some(TagStandard::PublicKey {
public_key,
relay_url,
alias,
uppercase: false,
}) = tag.to_standardized()
{
contact_list.push(Contact::new(public_key, relay_url, alias))
}
}
}
}
}
}
}
match client.set_contact_list(contact_list).await {
Ok(_) => Ok(true),
match client.set_contact_list(contact_list).await {
Ok(_) => Ok(true),
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
pub async fn get_following(
state: State<'_, Nostr>,
public_key: &str,
timeout: Option<u64>,
state: State<'_, Nostr>,
public_key: &str,
timeout: Option<u64>,
) -> Result<Vec<String>, String> {
let client = &state.client;
let public_key = match PublicKey::from_str(public_key) {
Ok(val) => val,
Err(err) => return Err(err.to_string()),
};
let duration = timeout.map(Duration::from_secs);
let filter = Filter::new().kind(Kind::ContactList).author(public_key);
let events = match client.get_events_of(vec![filter], duration).await {
Ok(events) => events,
Err(err) => return Err(err.to_string()),
};
let mut ret: Vec<String> = vec![];
if let Some(latest_event) = events.iter().max_by_key(|event| event.created_at()) {
ret.extend(latest_event.tags().iter().filter_map(|tag| {
if let Some(TagStandard::PublicKey {
uppercase: false, ..
}) = <nostr_sdk::Tag as Clone>::clone(tag).to_standardized()
{
tag.content().map(String::from)
} else {
None
}
}));
}
Ok(ret)
let client = &state.client;
let public_key = match PublicKey::from_str(public_key) {
Ok(val) => val,
Err(err) => return Err(err.to_string()),
};
let duration = timeout.map(Duration::from_secs);
let filter = Filter::new().kind(Kind::ContactList).author(public_key);
let events = match client.get_events_of(vec![filter], duration).await {
Ok(events) => events,
Err(err) => return Err(err.to_string()),
};
let mut ret: Vec<String> = vec![];
if let Some(latest_event) = events.iter().max_by_key(|event| event.created_at()) {
ret.extend(latest_event.tags().iter().filter_map(|tag| {
if let Some(TagStandard::PublicKey {
uppercase: false, ..
}) = <nostr_sdk::Tag as Clone>::clone(tag).to_standardized()
{
tag.content().map(String::from)
} else {
None
}
}));
}
Ok(ret)
}
pub async fn get_followers(
state: State<'_, Nostr>,
public_key: &str,
timeout: Option<u64>,
state: State<'_, Nostr>,
public_key: &str,
timeout: Option<u64>,
) -> Result<Vec<String>, String> {
let client = &state.client;
let public_key = match PublicKey::from_str(public_key) {
Ok(val) => val,
Err(err) => return Err(err.to_string()),
};
let duration = timeout.map(Duration::from_secs);
let client = &state.client;
let public_key = match PublicKey::from_str(public_key) {
Ok(val) => val,
Err(err) => return Err(err.to_string()),
};
let duration = timeout.map(Duration::from_secs);
let filter = Filter::new().kind(Kind::ContactList).custom_tag(
SingleLetterTag::lowercase(Alphabet::P),
vec![public_key.to_hex()],
);
let events = match client.get_events_of(vec![filter], duration).await {
Ok(events) => events,
Err(err) => return Err(err.to_string()),
};
let ret: Vec<String> = events
.into_iter()
.map(|event| event.author().to_hex())
.collect();
Ok(ret)
// TODO: get more than 500 events
let filter = Filter::new().kind(Kind::ContactList).custom_tag(
SingleLetterTag::lowercase(Alphabet::P),
vec![public_key.to_hex()],
);
let events = match client.get_events_of(vec![filter], duration).await {
Ok(events) => events,
Err(err) => return Err(err.to_string()),
};
let ret: Vec<String> = events
.into_iter()
.map(|event| event.author().to_hex())
.collect();
Ok(ret)
// TODO: get more than 500 events
}
#[tauri::command]
#[specta::specta]
pub async fn get_notifications(state: State<'_, Nostr>) -> Result<Vec<String>, String> {
let client = &state.client;
let client = &state.client;
match client.signer().await {
Ok(signer) => {
let public_key = signer.public_key().await.unwrap();
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(200);
match client.signer().await {
Ok(signer) => {
let public_key = signer.public_key().await.unwrap();
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(200);
match client
.database()
.query(vec![filter], Order::default())
.await
{
Ok(events) => Ok(events.into_iter().map(|ev| ev.as_json()).collect()),
match client
.database()
.query(vec![filter], Order::default())
.await
{
Ok(events) => Ok(events.into_iter().map(|ev| ev.as_json()).collect()),
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_settings(state: State<'_, Nostr>) -> Result<Settings, ()> {
let settings = state.settings.lock().unwrap().clone();
Ok(settings)
let settings = state.settings.lock().unwrap().clone();
Ok(settings)
}
#[tauri::command]
#[specta::specta]
pub async fn set_new_settings(settings: &str, state: State<'_, Nostr>) -> Result<(), ()> {
let parsed: Settings = serde_json::from_str(settings).expect("Could not parse settings payload");
*state.settings.lock().unwrap() = parsed;
let parsed: Settings =
serde_json::from_str(settings).expect("Could not parse settings payload");
*state.settings.lock().unwrap() = parsed;
Ok(())
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn verify_nip05(key: &str, nip05: &str) -> Result<bool, String> {
match PublicKey::from_str(key) {
Ok(public_key) => {
let status = nip05::verify(&public_key, nip05, None).await;
Ok(status.is_ok())
match PublicKey::from_str(key) {
Ok(public_key) => {
let status = nip05::verify(&public_key, nip05, None).await;
Ok(status.is_ok())
}
Err(err) => Err(err.to_string()),
}
Err(err) => Err(err.to_string()),
}
}
+109 -109
View File
@@ -3,155 +3,155 @@ use nostr_sdk::prelude::*;
use serde::Serialize;
use specta::Type;
use std::{
fs::OpenOptions,
io::{self, BufRead, Write},
fs::OpenOptions,
io::{self, BufRead, Write},
};
use tauri::{path::BaseDirectory, Manager, State};
#[derive(Serialize, Type)]
pub struct Relays {
connected: Vec<String>,
read: Option<Vec<String>>,
write: Option<Vec<String>>,
both: Option<Vec<String>>,
connected: Vec<String>,
read: Option<Vec<String>>,
write: Option<Vec<String>>,
both: Option<Vec<String>>,
}
#[tauri::command]
#[specta::specta]
pub async fn get_relays(state: State<'_, Nostr>) -> Result<Relays, String> {
let client = &state.client;
let client = &state.client;
let connected_relays = client
.relays()
.await
.into_keys()
.map(|url| url.to_string())
.collect::<Vec<_>>();
let connected_relays = client
.relays()
.await
.into_keys()
.map(|url| url.to_string())
.collect::<Vec<_>>();
let signer = client.signer().await.map_err(|e| e.to_string())?;
let public_key = signer.public_key().await.map_err(|e| e.to_string())?;
let signer = client.signer().await.map_err(|e| e.to_string())?;
let public_key = signer.public_key().await.map_err(|e| e.to_string())?;
let filter = Filter::new()
.author(public_key)
.kind(Kind::RelayList)
.limit(1);
let filter = Filter::new()
.author(public_key)
.kind(Kind::RelayList)
.limit(1);
match client.get_events_of(vec![filter], None).await {
Ok(events) => {
if let Some(event) = events.first() {
let nip65_list = nip65::extract_relay_list(event).collect::<Vec<_>>();
match client.get_events_of(vec![filter], None).await {
Ok(events) => {
if let Some(event) = events.first() {
let nip65_list = nip65::extract_relay_list(event).collect::<Vec<_>>();
let read = nip65_list
.iter()
.filter_map(|(url, meta)| {
if let Some(RelayMetadata::Read) = meta {
Some(url.to_string())
let read = nip65_list
.iter()
.filter_map(|(url, meta)| {
if let Some(RelayMetadata::Read) = meta {
Some(url.to_string())
} else {
None
}
})
.collect();
let write = nip65_list
.iter()
.filter_map(|(url, meta)| {
if let Some(RelayMetadata::Write) = meta {
Some(url.to_string())
} else {
None
}
})
.collect();
let both = nip65_list
.iter()
.filter_map(|(url, meta)| {
if meta.is_none() {
Some(url.to_string())
} else {
None
}
})
.collect();
Ok(Relays {
connected: connected_relays,
read: Some(read),
write: Some(write),
both: Some(both),
})
} else {
None
Ok(Relays {
connected: connected_relays,
read: None,
write: None,
both: None,
})
}
})
.collect();
let write = nip65_list
.iter()
.filter_map(|(url, meta)| {
if let Some(RelayMetadata::Write) = meta {
Some(url.to_string())
} else {
None
}
})
.collect();
let both = nip65_list
.iter()
.filter_map(|(url, meta)| {
if meta.is_none() {
Some(url.to_string())
} else {
None
}
})
.collect();
Ok(Relays {
connected: connected_relays,
read: Some(read),
write: Some(write),
both: Some(both),
})
} else {
Ok(Relays {
connected: connected_relays,
read: None,
write: None,
both: None,
})
}
}
Err(e) => Err(e.to_string()),
}
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn connect_relay(relay: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let client = &state.client;
let status = client.add_relay(relay).await.map_err(|e| e.to_string())?;
if status {
println!("Connecting to relay: {}", relay);
client
.connect_relay(relay)
.await
.map_err(|e| e.to_string())?;
}
Ok(status)
let client = &state.client;
let status = client.add_relay(relay).await.map_err(|e| e.to_string())?;
if status {
println!("Connecting to relay: {}", relay);
client
.connect_relay(relay)
.await
.map_err(|e| e.to_string())?;
}
Ok(status)
}
#[tauri::command]
#[specta::specta]
pub async fn remove_relay(relay: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let client = &state.client;
client
.remove_relay(relay)
.await
.map_err(|e| e.to_string())?;
client
.disconnect_relay(relay)
.await
.map_err(|e| e.to_string())?;
Ok(true)
let client = &state.client;
client
.remove_relay(relay)
.await
.map_err(|e| e.to_string())?;
client
.disconnect_relay(relay)
.await
.map_err(|e| e.to_string())?;
Ok(true)
}
#[tauri::command]
#[specta::specta]
pub fn get_bootstrap_relays(app: tauri::AppHandle) -> Result<Vec<String>, String> {
let relays_path = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
.map_err(|e| e.to_string())?;
let relays_path = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
.map_err(|e| e.to_string())?;
let file = std::fs::File::open(relays_path).map_err(|e| e.to_string())?;
let reader = io::BufReader::new(file);
let file = std::fs::File::open(relays_path).map_err(|e| e.to_string())?;
let reader = io::BufReader::new(file);
reader
.lines()
.collect::<Result<Vec<String>, io::Error>>()
.map_err(|e| e.to_string())
reader
.lines()
.collect::<Result<Vec<String>, io::Error>>()
.map_err(|e| e.to_string())
}
#[tauri::command]
#[specta::specta]
pub fn save_bootstrap_relays(relays: &str, app: tauri::AppHandle) -> Result<(), String> {
let relays_path = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
.map_err(|e| e.to_string())?;
let relays_path = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
.map_err(|e| e.to_string())?;
let mut file = OpenOptions::new()
.write(true)
.open(relays_path)
.map_err(|e| e.to_string())?;
let mut file = OpenOptions::new()
.write(true)
.open(relays_path)
.map_err(|e| e.to_string())?;
file.write_all(relays.as_bytes()).map_err(|e| e.to_string())
file.write_all(relays.as_bytes()).map_err(|e| e.to_string())
}
+197 -197
View File
@@ -11,255 +11,255 @@ use url::Url;
#[derive(Debug, Clone, Serialize, Type)]
pub struct Meta {
pub content: String,
pub images: Vec<String>,
pub videos: Vec<String>,
pub events: Vec<String>,
pub mentions: Vec<String>,
pub hashtags: Vec<String>,
pub content: String,
pub images: Vec<String>,
pub videos: Vec<String>,
pub events: Vec<String>,
pub mentions: Vec<String>,
pub hashtags: Vec<String>,
}
const NOSTR_EVENTS: [&str; 10] = [
"@nevent1",
"@note1",
"@nostr:note1",
"@nostr:nevent1",
"nostr:note1",
"note1",
"nostr:nevent1",
"nevent1",
"Nostr:note1",
"Nostr:nevent1",
"@nevent1",
"@note1",
"@nostr:note1",
"@nostr:nevent1",
"nostr:note1",
"note1",
"nostr:nevent1",
"nevent1",
"Nostr:note1",
"Nostr:nevent1",
];
const NOSTR_MENTIONS: [&str; 10] = [
"@npub1",
"nostr:npub1",
"nostr:nprofile1",
"nostr:naddr1",
"npub1",
"nprofile1",
"naddr1",
"Nostr:npub1",
"Nostr:nprofile1",
"Nostr:naddr1",
"@npub1",
"nostr:npub1",
"nostr:nprofile1",
"nostr:naddr1",
"npub1",
"nprofile1",
"naddr1",
"Nostr:npub1",
"Nostr:nprofile1",
"Nostr:naddr1",
];
const IMAGES: [&str; 7] = ["jpg", "jpeg", "gif", "png", "webp", "avif", "tiff"];
const VIDEOS: [&str; 5] = ["mp4", "mov", "avi", "webm", "mkv"];
pub fn get_latest_event(events: &[Event]) -> Option<&Event> {
events.iter().next()
events.iter().next()
}
pub fn dedup_event(events: &[Event]) -> Vec<Event> {
let mut seen_ids = HashSet::new();
events
.iter()
.filter(|&event| {
let e = TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::E));
let e_tags: Vec<&Tag> = event.tags.iter().filter(|el| el.kind() == e).collect();
let ids: Vec<&str> = e_tags.iter().filter_map(|tag| tag.content()).collect();
let is_dup = ids.iter().any(|id| seen_ids.contains(*id));
let mut seen_ids = HashSet::new();
events
.iter()
.filter(|&event| {
let e = TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::E));
let e_tags: Vec<&Tag> = event.tags.iter().filter(|el| el.kind() == e).collect();
let ids: Vec<&str> = e_tags.iter().filter_map(|tag| tag.content()).collect();
let is_dup = ids.iter().any(|id| seen_ids.contains(*id));
for id in &ids {
seen_ids.insert(*id);
}
for id in &ids {
seen_ids.insert(*id);
}
!is_dup
})
.cloned()
.collect()
!is_dup
})
.cloned()
.collect()
}
pub async fn parse_event(content: &str) -> Meta {
let mut finder = LinkFinder::new();
finder.url_must_have_scheme(false);
let mut finder = LinkFinder::new();
finder.url_must_have_scheme(false);
// Get urls
let urls: Vec<_> = finder.links(content).collect();
// Get words
let words: Vec<_> = content.split_whitespace().collect();
// Get urls
let urls: Vec<_> = finder.links(content).collect();
// Get words
let words: Vec<_> = content.split_whitespace().collect();
let hashtags = words
.iter()
.filter(|&&word| word.starts_with('#'))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
let hashtags = words
.iter()
.filter(|&&word| word.starts_with('#'))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
let events = words
.iter()
.filter(|&&word| NOSTR_EVENTS.iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
let events = words
.iter()
.filter(|&&word| NOSTR_EVENTS.iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
let mentions = words
.iter()
.filter(|&&word| NOSTR_MENTIONS.iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
let mentions = words
.iter()
.filter(|&&word| NOSTR_MENTIONS.iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
let mut images = Vec::new();
let mut videos = Vec::new();
let mut text = content.to_string();
let mut images = Vec::new();
let mut videos = Vec::new();
let mut text = content.to_string();
if !urls.is_empty() {
let client = Client::new();
if !urls.is_empty() {
let client = Client::new();
for url in urls {
let url_str = url.as_str();
for url in urls {
let url_str = url.as_str();
if let Ok(parsed_url) = Url::from_str(url_str) {
if let Some(ext) = parsed_url
.path_segments()
.and_then(|segments| segments.last().and_then(|s| s.split('.').last()))
{
if IMAGES.contains(&ext) {
text = text.replace(url_str, "");
images.push(url_str.to_string());
// Process the next item.
continue;
}
if VIDEOS.contains(&ext) {
text = text.replace(url_str, "");
videos.push(url_str.to_string());
// Process the next item.
continue;
}
}
if let Ok(parsed_url) = Url::from_str(url_str) {
if let Some(ext) = parsed_url
.path_segments()
.and_then(|segments| segments.last().and_then(|s| s.split('.').last()))
{
if IMAGES.contains(&ext) {
text = text.replace(url_str, "");
images.push(url_str.to_string());
// Process the next item.
continue;
}
if VIDEOS.contains(&ext) {
text = text.replace(url_str, "");
videos.push(url_str.to_string());
// Process the next item.
continue;
}
}
// Check the content type of URL via HEAD request
if let Ok(res) = client.head(url_str).send().await {
if let Some(content_type) = res.headers().get("Content-Type") {
if content_type.to_str().unwrap_or("").starts_with("image") {
text = text.replace(url_str, "");
images.push(url_str.to_string());
// Process the next item.
continue;
// Check the content type of URL via HEAD request
if let Ok(res) = client.head(url_str).send().await {
if let Some(content_type) = res.headers().get("Content-Type") {
if content_type.to_str().unwrap_or("").starts_with("image") {
text = text.replace(url_str, "");
images.push(url_str.to_string());
// Process the next item.
continue;
}
}
}
}
}
}
}
}
}
// Clean up the resulting content string to remove extra spaces
let cleaned_text = text.trim().to_string();
// Clean up the resulting content string to remove extra spaces
let cleaned_text = text.trim().to_string();
Meta {
content: cleaned_text,
events,
mentions,
hashtags,
images,
videos,
}
Meta {
content: cleaned_text,
events,
mentions,
hashtags,
images,
videos,
}
}
pub fn create_event_tags(content: &str) -> Vec<Tag> {
let mut tags: Vec<Tag> = vec![];
let mut tag_set: HashSet<String> = HashSet::new();
let mut tags: Vec<Tag> = vec![];
let mut tag_set: HashSet<String> = HashSet::new();
// Get words
let words: Vec<_> = content.split_whitespace().collect();
// Get words
let words: Vec<_> = content.split_whitespace().collect();
// Get mentions
let mentions = words
.iter()
.filter(|&&word| ["nostr:", "@"].iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
// Get mentions
let mentions = words
.iter()
.filter(|&&word| ["nostr:", "@"].iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
// Get hashtags
let hashtags = words
.iter()
.filter(|&&word| word.starts_with('#'))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
// Get hashtags
let hashtags = words
.iter()
.filter(|&&word| word.starts_with('#'))
.map(|&s| s.to_string())
.collect::<Vec<_>>();
for mention in mentions {
let entity = mention.replace("nostr:", "").replace('@', "");
for mention in mentions {
let entity = mention.replace("nostr:", "").replace('@', "");
if !tag_set.contains(&entity) {
if entity.starts_with("npub") {
if let Ok(public_key) = PublicKey::from_bech32(&entity) {
let tag = Tag::public_key(public_key);
tags.push(tag);
} else {
continue;
if !tag_set.contains(&entity) {
if entity.starts_with("npub") {
if let Ok(public_key) = PublicKey::from_bech32(&entity) {
let tag = Tag::public_key(public_key);
tags.push(tag);
} else {
continue;
}
}
if entity.starts_with("nprofile") {
if let Ok(public_key) = PublicKey::from_bech32(&entity) {
let tag = Tag::public_key(public_key);
tags.push(tag);
} else {
continue;
}
}
if entity.starts_with("note") {
if let Ok(event_id) = EventId::from_bech32(&entity) {
let hex = event_id.to_hex();
let tag = Tag::parse(&["e", &hex, "", "mention"]).unwrap();
tags.push(tag);
} else {
continue;
}
}
if entity.starts_with("nevent") {
if let Ok(event) = Nip19Event::from_bech32(&entity) {
let hex = event.event_id.to_hex();
let relay = event.clone().relays.into_iter().next().unwrap_or("".into());
let tag = Tag::parse(&["e", &hex, &relay, "mention"]).unwrap();
if let Some(author) = event.author {
let tag = Tag::public_key(author);
tags.push(tag);
}
tags.push(tag);
} else {
continue;
}
}
tag_set.insert(entity);
}
}
if entity.starts_with("nprofile") {
if let Ok(public_key) = PublicKey::from_bech32(&entity) {
let tag = Tag::public_key(public_key);
tags.push(tag);
} else {
continue;
}
}
if entity.starts_with("note") {
if let Ok(event_id) = EventId::from_bech32(&entity) {
let hex = event_id.to_hex();
let tag = Tag::parse(&["e", &hex, "", "mention"]).unwrap();
tags.push(tag);
} else {
continue;
}
}
if entity.starts_with("nevent") {
if let Ok(event) = Nip19Event::from_bech32(&entity) {
let hex = event.event_id.to_hex();
let relay = event.clone().relays.into_iter().next().unwrap_or("".into());
let tag = Tag::parse(&["e", &hex, &relay, "mention"]).unwrap();
}
if let Some(author) = event.author {
let tag = Tag::public_key(author);
for hashtag in hashtags {
if !tag_set.contains(&hashtag) {
let tag = Tag::hashtag(hashtag.clone());
tags.push(tag);
}
tags.push(tag);
} else {
continue;
tag_set.insert(hashtag);
}
}
tag_set.insert(entity);
}
}
for hashtag in hashtags {
if !tag_set.contains(&hashtag) {
let tag = Tag::hashtag(hashtag.clone());
tags.push(tag);
tag_set.insert(hashtag);
}
}
tags
tags
}
#[cfg(test)]
mod tests {
use super::*;
use super::*;
#[tokio::test]
async fn test_parse_event() {
let content = "Check this image: https://example.com/image.jpg #cool @npub1";
let meta = parse_event(content).await;
#[tokio::test]
async fn test_parse_event() {
let content = "Check this image: https://example.com/image.jpg #cool @npub1";
let meta = parse_event(content).await;
assert_eq!(meta.content, "Check this image: #cool @npub1");
assert_eq!(meta.images, vec!["https://example.com/image.jpg"]);
assert_eq!(meta.videos, Vec::<String>::new());
assert_eq!(meta.hashtags, vec!["#cool"]);
assert_eq!(meta.mentions, vec!["@npub1"]);
}
assert_eq!(meta.content, "Check this image: #cool @npub1");
assert_eq!(meta.images, vec!["https://example.com/image.jpg"]);
assert_eq!(meta.videos, Vec::<String>::new());
assert_eq!(meta.hashtags, vec!["#cool"]);
assert_eq!(meta.mentions, vec!["@npub1"]);
}
#[tokio::test]
async fn test_parse_video() {
let content = "Check this video: https://example.com/video.mp4 #cool @npub1";
let meta = parse_event(content).await;
#[tokio::test]
async fn test_parse_video() {
let content = "Check this video: https://example.com/video.mp4 #cool @npub1";
let meta = parse_event(content).await;
assert_eq!(meta.content, "Check this video: #cool @npub1");
assert_eq!(meta.images, Vec::<String>::new());
assert_eq!(meta.videos, vec!["https://example.com/video.mp4"]);
assert_eq!(meta.hashtags, vec!["#cool"]);
assert_eq!(meta.mentions, vec!["@npub1"]);
}
assert_eq!(meta.content, "Check this video: #cool @npub1");
assert_eq!(meta.images, Vec::<String>::new());
assert_eq!(meta.videos, vec!["https://example.com/video.mp4"]);
assert_eq!(meta.hashtags, vec!["#cool"]);
assert_eq!(meta.mentions, vec!["@npub1"]);
}
}