mirror of
https://github.com/lumehq/lume.git
synced 2025-03-28 02:31:49 +01:00
wip: multi accounts
This commit is contained in:
parent
0f06522c28
commit
bfe35ad885
@ -1,19 +1,72 @@
|
||||
import { createFileRoute, redirect } from "@tanstack/react-router";
|
||||
import { useArk } from "@lume/ark";
|
||||
import { User } from "@lume/ui";
|
||||
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
export const Route = createFileRoute("/")({
|
||||
beforeLoad: async ({ location, context }) => {
|
||||
const ark = context.ark;
|
||||
const signer = await ark.verify_signer();
|
||||
if (!signer) {
|
||||
throw redirect({
|
||||
to: "/landing",
|
||||
search: {
|
||||
redirect: location.href,
|
||||
},
|
||||
const accounts = await ark.get_all_accounts();
|
||||
|
||||
switch (accounts.length) {
|
||||
// Empty account
|
||||
case 0:
|
||||
throw redirect({
|
||||
to: "/landing",
|
||||
search: {
|
||||
redirect: location.href,
|
||||
},
|
||||
});
|
||||
// Only 1 account, skip account selection screen
|
||||
case 1:
|
||||
const loadAccount = await ark.load_selected_account(accounts[0].npub);
|
||||
if (loadAccount) {
|
||||
throw redirect({
|
||||
to: "/app/home",
|
||||
search: {
|
||||
redirect: location.href,
|
||||
},
|
||||
});
|
||||
}
|
||||
// Account selection
|
||||
default:
|
||||
return;
|
||||
}
|
||||
},
|
||||
component: Screen,
|
||||
});
|
||||
|
||||
function Screen() {
|
||||
const ark = useArk();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const select = async (npub: string) => {
|
||||
const loadAccount = await ark.load_selected_account(npub);
|
||||
if (loadAccount) {
|
||||
navigate({
|
||||
to: "/app/home",
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
throw redirect({
|
||||
to: "/app/space",
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<div className="flex items-center gap-6">
|
||||
{ark.accounts.map((account) => (
|
||||
<button
|
||||
type="button"
|
||||
key={account.npub}
|
||||
onClick={() => select(account.npub)}
|
||||
>
|
||||
<User.Provider pubkey={account.npub}>
|
||||
<User.Root className="flex h-36 w-32 flex-col items-center justify-center gap-4 rounded-xl p-2 hover:bg-neutral-100 dark:bg-neutral-900">
|
||||
<User.Avatar className="size-20 rounded-full object-cover" />
|
||||
<User.Name className="max-w-[5rem] truncate text-lg font-medium leading-tight" />
|
||||
</User.Root>
|
||||
</User.Provider>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
5
apps/desktop2/src/routes/select.tsx
Normal file
5
apps/desktop2/src/routes/select.tsx
Normal file
@ -0,0 +1,5 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/select')({
|
||||
component: () => <div>Hello /select!</div>
|
||||
})
|
@ -1,5 +1,5 @@
|
||||
import type {
|
||||
CurrentAccount,
|
||||
Account,
|
||||
Event,
|
||||
EventWithReplies,
|
||||
Keys,
|
||||
@ -9,25 +9,46 @@ import { invoke } from "@tauri-apps/api/core";
|
||||
import { WebviewWindow } from "@tauri-apps/api/webview";
|
||||
|
||||
export class Ark {
|
||||
public account: CurrentAccount;
|
||||
public account: Account;
|
||||
public accounts: Array<Account>;
|
||||
|
||||
constructor() {
|
||||
this.account = { npub: "" };
|
||||
}
|
||||
|
||||
public async verify_signer() {
|
||||
public async get_all_accounts() {
|
||||
try {
|
||||
const signer: boolean = await invoke("verify_signer");
|
||||
if (signer) {
|
||||
const account: string = await invoke("load_account");
|
||||
this.account.npub = account;
|
||||
const accounts: Account[] = [];
|
||||
const cmd: string[] = await invoke("get_all_nsecs");
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
for (const item of cmd) {
|
||||
accounts.push({ npub: item.replace(".nsec", "") });
|
||||
}
|
||||
|
||||
this.accounts = accounts;
|
||||
return accounts;
|
||||
} catch (e) {
|
||||
console.error(String(e));
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async load_selected_account(npub: string) {
|
||||
try {
|
||||
const fullNpub = `${npub}.nsec`;
|
||||
const cmd: boolean = await invoke("load_selected_account", {
|
||||
npub: fullNpub,
|
||||
});
|
||||
|
||||
if (cmd) {
|
||||
const contacts: string[] = await invoke("get_contact_list");
|
||||
this.account.npub = npub;
|
||||
this.account.contacts = contacts;
|
||||
}
|
||||
|
||||
return cmd;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -6,12 +6,12 @@ export function useEvent(id: string) {
|
||||
const { isLoading, isError, data } = useQuery({
|
||||
queryKey: ["event", id],
|
||||
queryFn: async () => {
|
||||
const event = await ark.get_event(id);
|
||||
if (!event)
|
||||
throw new Error(
|
||||
`Cannot get event with ${id}, will be retry after 10 seconds`,
|
||||
);
|
||||
return event;
|
||||
try {
|
||||
const event = await ark.get_event(id);
|
||||
return event;
|
||||
} catch (e) {
|
||||
throw new Error(e);
|
||||
}
|
||||
},
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
|
@ -10,12 +10,12 @@ export function useProfile(pubkey: string) {
|
||||
} = useQuery({
|
||||
queryKey: ["user", pubkey],
|
||||
queryFn: async () => {
|
||||
const profile = await ark.get_profile(pubkey);
|
||||
if (!profile)
|
||||
throw new Error(
|
||||
`Cannot get metadata for ${pubkey}, will be retry after 10 seconds`,
|
||||
);
|
||||
return profile;
|
||||
try {
|
||||
const profile = await ark.get_profile(pubkey);
|
||||
return profile;
|
||||
} catch (e) {
|
||||
throw new Error(e);
|
||||
}
|
||||
},
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
|
2
packages/types/index.d.ts
vendored
2
packages/types/index.d.ts
vendored
@ -54,7 +54,7 @@ export interface Metadata {
|
||||
lud16?: string;
|
||||
}
|
||||
|
||||
export interface CurrentAccount {
|
||||
export interface Account {
|
||||
npub: string;
|
||||
contacts?: string[];
|
||||
interests?: Interests;
|
||||
|
451
src-tauri/Cargo.lock
generated
451
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,5 @@
|
||||
use std::process::Command;
|
||||
use tauri::Manager;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn show_in_folder(path: String) {
|
||||
@ -46,3 +47,26 @@ pub async fn show_in_folder(path: String) {
|
||||
Command::new("open").args(["-R", &path]).spawn().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_all_nsecs(app_handle: tauri::AppHandle) -> Result<Vec<String>, ()> {
|
||||
let dir = app_handle.path().app_config_dir().unwrap();
|
||||
|
||||
if let Ok(paths) = std::fs::read_dir(dir) {
|
||||
let files = paths
|
||||
.filter_map(|res| res.ok())
|
||||
.map(|dir_entry| dir_entry.path())
|
||||
.filter_map(|path| {
|
||||
if path.extension().map_or(false, |ext| ext == "nsec") {
|
||||
Some(path.file_name().unwrap().to_str().unwrap().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(files)
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
@ -9,23 +9,11 @@ pub mod nostr;
|
||||
use age::secrecy::ExposeSecret;
|
||||
use keyring::Entry;
|
||||
use nostr_sdk::prelude::*;
|
||||
use std::error::Error;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read};
|
||||
use std::iter;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tauri::Manager;
|
||||
use tauri_plugin_autostart::MacosLauncher;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub struct Nostr {
|
||||
pub client: Arc<Client>,
|
||||
pub client_user: Option<PublicKey>,
|
||||
pub contact_list: Option<Vec<Contact>>,
|
||||
}
|
||||
pub struct NostrClient(Mutex<Client>);
|
||||
|
||||
fn main() {
|
||||
let mut ctx = tauri::generate_context!();
|
||||
@ -33,35 +21,10 @@ fn main() {
|
||||
.setup(|app| {
|
||||
let handle = app.handle().clone();
|
||||
let config_dir = handle.path().app_config_dir().unwrap();
|
||||
|
||||
let keyring_entry = Entry::new("Lume Secret Storage", "AppKey").unwrap();
|
||||
let mut stored_nsec_key = None;
|
||||
|
||||
if let Ok(key) = keyring_entry.get_password() {
|
||||
let app_key = age::x25519::Identity::from_str(&key.to_string()).unwrap();
|
||||
if let Ok(nsec_paths) = get_nsec_paths(config_dir.as_path()) {
|
||||
let last_nsec_path = nsec_paths.last();
|
||||
if let Some(nsec_path) = last_nsec_path {
|
||||
let file = File::open(nsec_path).expect("Open nsec file failed");
|
||||
let file_buf = BufReader::new(file);
|
||||
let decryptor = match age::Decryptor::new_buffered(file_buf).expect("Decryptor failed")
|
||||
{
|
||||
age::Decryptor::Recipients(d) => d,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let mut decrypted = vec![];
|
||||
let mut reader = decryptor
|
||||
.decrypt(iter::once(&app_key as &dyn age::Identity))
|
||||
.expect("Decrypt nsec file failed");
|
||||
reader
|
||||
.read_to_end(&mut decrypted)
|
||||
.expect("Read secret key failed");
|
||||
|
||||
stored_nsec_key = Some(String::from_utf8(decrypted).expect("Not valid"))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Create new master key if not exist
|
||||
if let Err(_) = keyring_entry.get_password() {
|
||||
let app_key = age::x25519::Identity::generate().to_string();
|
||||
let app_secret = app_key.expose_secret();
|
||||
let _ = keyring_entry.set_password(app_secret);
|
||||
@ -86,42 +49,16 @@ fn main() {
|
||||
.add_relay("wss://bostr.yonle.lecturify.net")
|
||||
.await
|
||||
.expect("Failed to add bootstrap relay.");
|
||||
client
|
||||
.add_relay("wss://purplepag.es")
|
||||
.await
|
||||
.expect("Failed to add bootstrap relay.");
|
||||
|
||||
// Connect
|
||||
client.connect().await;
|
||||
|
||||
// Prepare contact list
|
||||
let mut user = None;
|
||||
let mut contact_list = None;
|
||||
|
||||
// Run somethings if account existed
|
||||
if let Some(key) = stored_nsec_key {
|
||||
let secret_key = SecretKey::from_bech32(key).expect("Get secret key failed");
|
||||
let keys = Keys::new(secret_key);
|
||||
let public_key = keys.public_key();
|
||||
let signer = NostrSigner::Keys(keys);
|
||||
|
||||
// Update client's signer
|
||||
client.set_signer(Some(signer)).await;
|
||||
|
||||
// Update user
|
||||
user = Some(public_key);
|
||||
|
||||
// Get contact list
|
||||
contact_list = Some(
|
||||
client
|
||||
.get_contact_list(Some(Duration::from_secs(10)))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
};
|
||||
|
||||
// Init global state
|
||||
handle.manage(Nostr {
|
||||
client: client.into(),
|
||||
client_user: user.into(),
|
||||
contact_list: contact_list.into(),
|
||||
})
|
||||
// Update global state
|
||||
handle.manage(NostrClient(Mutex::new(client)))
|
||||
});
|
||||
|
||||
Ok(())
|
||||
@ -138,7 +75,6 @@ fn main() {
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_upload::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_window_state::Builder::default().build())
|
||||
.plugin(tauri_plugin_autostart::init(
|
||||
MacosLauncher::LaunchAgent,
|
||||
Some(vec![]),
|
||||
@ -149,11 +85,12 @@ fn main() {
|
||||
nostr::keys::get_public_key,
|
||||
nostr::keys::update_signer,
|
||||
nostr::keys::verify_signer,
|
||||
nostr::keys::load_account,
|
||||
nostr::keys::load_selected_account,
|
||||
nostr::keys::event_to_bech32,
|
||||
nostr::keys::user_to_bech32,
|
||||
nostr::keys::verify_nip05,
|
||||
nostr::metadata::get_profile,
|
||||
nostr::metadata::get_contact_list,
|
||||
nostr::metadata::create_profile,
|
||||
nostr::event::get_event,
|
||||
nostr::event::get_text_events,
|
||||
@ -164,6 +101,7 @@ fn main() {
|
||||
nostr::event::upvote,
|
||||
nostr::event::downvote,
|
||||
commands::folder::show_in_folder,
|
||||
commands::folder::get_all_nsecs,
|
||||
commands::opg::fetch_opg,
|
||||
])
|
||||
.build(ctx)
|
||||
@ -175,19 +113,3 @@ fn main() {
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
fn get_nsec_paths(dir: &Path) -> Result<Vec<PathBuf>, Box<dyn Error>> {
|
||||
let paths = std::fs::read_dir(dir)?
|
||||
.filter_map(|res| res.ok())
|
||||
.map(|dir_entry| dir_entry.path())
|
||||
.filter_map(|path| {
|
||||
if path.extension().map_or(false, |ext| ext == "nsec") {
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(paths)
|
||||
}
|
||||
|
@ -1,68 +1,85 @@
|
||||
use crate::Nostr;
|
||||
use crate::NostrClient;
|
||||
use nostr_sdk::prelude::*;
|
||||
use std::{str::FromStr, time::Duration};
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_event(id: &str, nostr: State<'_, Nostr>) -> Result<String, String> {
|
||||
let client = &nostr.client;
|
||||
let event_id: EventId = match Nip19::from_bech32(id) {
|
||||
pub async fn get_event(id: &str, state: State<'_, NostrClient>) -> Result<String, String> {
|
||||
let client = state.0.lock().await;
|
||||
let event_id: Option<EventId> = match Nip19::from_bech32(id) {
|
||||
Ok(val) => match val {
|
||||
Nip19::EventId(id) => id,
|
||||
Nip19::Event(event) => event.event_id,
|
||||
_ => panic!("not nip19"),
|
||||
Nip19::EventId(id) => Some(id),
|
||||
Nip19::Event(event) => Some(event.event_id),
|
||||
_ => None,
|
||||
},
|
||||
Err(_) => match EventId::from_hex(id) {
|
||||
Ok(val) => Some(val),
|
||||
Err(_) => None,
|
||||
},
|
||||
Err(_) => EventId::from_hex(id).unwrap(),
|
||||
};
|
||||
|
||||
let filter = Filter::new().id(event_id);
|
||||
let events = client
|
||||
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
|
||||
.await
|
||||
.expect("Get event failed");
|
||||
if let Some(id) = event_id {
|
||||
let filter = Filter::new().id(id);
|
||||
|
||||
if let Some(event) = events.first() {
|
||||
Ok(event.as_json())
|
||||
if let Ok(events) = &client
|
||||
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
|
||||
.await
|
||||
{
|
||||
if let Some(event) = events.first() {
|
||||
Ok(event.as_json())
|
||||
} else {
|
||||
Err("Event not found with current relay list".into())
|
||||
}
|
||||
} else {
|
||||
Err("Event not found with current relay list".into())
|
||||
}
|
||||
} else {
|
||||
Err("Event not found".into())
|
||||
Err("EventId is not valid".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_text_events(
|
||||
limit: usize,
|
||||
until: Option<String>,
|
||||
nostr: State<'_, Nostr>,
|
||||
until: Option<&str>,
|
||||
contact_list: Option<Vec<&str>>,
|
||||
state: State<'_, NostrClient>,
|
||||
) -> Result<Vec<Event>, ()> {
|
||||
let client = &nostr.client;
|
||||
let contact_list = &nostr.contact_list.clone().unwrap();
|
||||
let client = state.0.lock().await;
|
||||
|
||||
let authors: Vec<PublicKey> = contact_list.into_iter().map(|x| x.public_key).collect();
|
||||
let mut final_until = Timestamp::now();
|
||||
if let Some(list) = contact_list {
|
||||
let authors: Vec<PublicKey> = list
|
||||
.into_iter()
|
||||
.map(|x| PublicKey::from_str(x).unwrap())
|
||||
.collect();
|
||||
let mut final_until = Timestamp::now();
|
||||
|
||||
if let Some(t) = until {
|
||||
final_until = Timestamp::from_str(&t).unwrap();
|
||||
}
|
||||
if let Some(t) = until {
|
||||
final_until = Timestamp::from_str(&t).unwrap();
|
||||
}
|
||||
|
||||
let filter = Filter::new()
|
||||
.kinds(vec![Kind::TextNote, Kind::Repost])
|
||||
.authors(authors)
|
||||
.limit(limit)
|
||||
.until(final_until);
|
||||
let filter = Filter::new()
|
||||
.kinds(vec![Kind::TextNote, Kind::Repost])
|
||||
.authors(authors)
|
||||
.limit(limit)
|
||||
.until(final_until);
|
||||
|
||||
if let Ok(events) = client
|
||||
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
|
||||
.await
|
||||
{
|
||||
Ok(events)
|
||||
if let Ok(events) = client
|
||||
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
|
||||
.await
|
||||
{
|
||||
Ok(events)
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_event_thread(id: &str, nostr: State<'_, Nostr>) -> Result<Vec<Event>, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn get_event_thread(id: &str, state: State<'_, NostrClient>) -> Result<Vec<Event>, ()> {
|
||||
let client = state.0.lock().await;
|
||||
let event_id = EventId::from_hex(id).unwrap();
|
||||
let filter = Filter::new().kinds(vec![Kind::TextNote]).event(event_id);
|
||||
|
||||
@ -77,9 +94,8 @@ pub async fn get_event_thread(id: &str, nostr: State<'_, Nostr>) -> Result<Vec<E
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn publish(content: &str, nostr: State<'_, Nostr>) -> Result<EventId, ()> {
|
||||
let client = &nostr.client;
|
||||
|
||||
pub async fn publish(content: &str, state: State<'_, NostrClient>) -> Result<EventId, ()> {
|
||||
let client = state.0.lock().await;
|
||||
let event = client
|
||||
.publish_text_note(content, [])
|
||||
.await
|
||||
@ -92,10 +108,9 @@ pub async fn publish(content: &str, nostr: State<'_, Nostr>) -> Result<EventId,
|
||||
pub async fn reply_to(
|
||||
content: &str,
|
||||
tags: Vec<String>,
|
||||
nostr: State<'_, Nostr>,
|
||||
state: State<'_, NostrClient>,
|
||||
) -> Result<EventId, String> {
|
||||
let client = &nostr.client;
|
||||
|
||||
let client = state.0.lock().await;
|
||||
if let Ok(event_tags) = Tag::parse(tags) {
|
||||
let event = client
|
||||
.publish_text_note(content, vec![event_tags])
|
||||
@ -109,8 +124,8 @@ pub async fn reply_to(
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn repost(id: &str, pubkey: &str, nostr: State<'_, Nostr>) -> Result<EventId, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn repost(id: &str, pubkey: &str, state: State<'_, NostrClient>) -> Result<EventId, ()> {
|
||||
let client = state.0.lock().await;
|
||||
let public_key = PublicKey::from_str(pubkey).unwrap();
|
||||
let event_id = EventId::from_hex(id).unwrap();
|
||||
|
||||
@ -123,8 +138,8 @@ pub async fn repost(id: &str, pubkey: &str, nostr: State<'_, Nostr>) -> Result<E
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn upvote(id: &str, pubkey: &str, nostr: State<'_, Nostr>) -> Result<EventId, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn upvote(id: &str, pubkey: &str, state: State<'_, NostrClient>) -> Result<EventId, ()> {
|
||||
let client = state.0.lock().await;
|
||||
let public_key = PublicKey::from_str(pubkey).unwrap();
|
||||
let event_id = EventId::from_hex(id).unwrap();
|
||||
|
||||
@ -137,8 +152,12 @@ pub async fn upvote(id: &str, pubkey: &str, nostr: State<'_, Nostr>) -> Result<E
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn downvote(id: &str, pubkey: &str, nostr: State<'_, Nostr>) -> Result<EventId, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn downvote(
|
||||
id: &str,
|
||||
pubkey: &str,
|
||||
state: State<'_, NostrClient>,
|
||||
) -> Result<EventId, ()> {
|
||||
let client = state.0.lock().await;
|
||||
let public_key = PublicKey::from_str(pubkey).unwrap();
|
||||
let event_id = EventId::from_hex(id).unwrap();
|
||||
|
||||
|
@ -1,6 +1,9 @@
|
||||
use crate::Nostr;
|
||||
use crate::NostrClient;
|
||||
use keyring::Entry;
|
||||
use nostr_sdk::prelude::*;
|
||||
use std::io::{BufReader, Read};
|
||||
use std::iter;
|
||||
use std::time::Duration;
|
||||
use std::{fs::File, io::Write, str::FromStr};
|
||||
use tauri::{Manager, State};
|
||||
|
||||
@ -28,7 +31,7 @@ pub fn create_keys() -> Result<CreateKeysResponse, ()> {
|
||||
pub async fn save_key(
|
||||
nsec: &str,
|
||||
app_handle: tauri::AppHandle,
|
||||
nostr: State<'_, Nostr>,
|
||||
state: State<'_, NostrClient>,
|
||||
) -> Result<bool, ()> {
|
||||
if let Ok(nostr_secret_key) = SecretKey::from_bech32(nsec) {
|
||||
let nostr_keys = Keys::new(nostr_secret_key);
|
||||
@ -36,7 +39,7 @@ pub async fn save_key(
|
||||
let signer = NostrSigner::Keys(nostr_keys);
|
||||
|
||||
// Update client's signer
|
||||
let client = &nostr.client;
|
||||
let client = state.0.lock().await;
|
||||
client.set_signer(Some(signer)).await;
|
||||
|
||||
let keyring_entry = Entry::new("Lume Secret Storage", "AppKey").unwrap();
|
||||
@ -78,8 +81,8 @@ pub fn get_public_key(nsec: &str) -> Result<String, ()> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn update_signer(nsec: &str, nostr: State<'_, Nostr>) -> Result<(), ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn update_signer(nsec: &str, state: State<'_, NostrClient>) -> Result<(), ()> {
|
||||
let client = state.0.lock().await;
|
||||
let secret_key = SecretKey::from_bech32(nsec).unwrap();
|
||||
let keys = Keys::new(secret_key);
|
||||
let signer = NostrSigner::Keys(keys);
|
||||
@ -90,8 +93,8 @@ pub async fn update_signer(nsec: &str, nostr: State<'_, Nostr>) -> Result<(), ()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn verify_signer(nostr: State<'_, Nostr>) -> Result<bool, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn verify_signer(state: State<'_, NostrClient>) -> Result<bool, ()> {
|
||||
let client = state.0.lock().await;
|
||||
|
||||
if let Ok(_) = client.signer().await {
|
||||
Ok(true)
|
||||
@ -101,13 +104,61 @@ pub async fn verify_signer(nostr: State<'_, Nostr>) -> Result<bool, ()> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn load_account(nostr: State<'_, Nostr>) -> Result<String, ()> {
|
||||
let user = &nostr.client_user;
|
||||
pub async fn load_selected_account(
|
||||
npub: &str,
|
||||
app_handle: tauri::AppHandle,
|
||||
state: State<'_, NostrClient>,
|
||||
) -> Result<bool, String> {
|
||||
let client = state.0.lock().await;
|
||||
let config_dir = app_handle.path().app_config_dir().unwrap();
|
||||
let keyring_entry = Entry::new("Lume Secret Storage", "AppKey").unwrap();
|
||||
|
||||
if let Some(key) = user {
|
||||
Ok(key.to_hex())
|
||||
// Get master password
|
||||
if let Ok(key) = keyring_entry.get_password() {
|
||||
// Build master key
|
||||
let app_key = age::x25519::Identity::from_str(&key.to_string()).unwrap();
|
||||
|
||||
// Open nsec file
|
||||
if let Ok(file) = File::open(config_dir.join(npub)) {
|
||||
let file_buf = BufReader::new(file);
|
||||
let decryptor = match age::Decryptor::new_buffered(file_buf).expect("Decryptor failed") {
|
||||
age::Decryptor::Recipients(d) => d,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let mut decrypted = vec![];
|
||||
let mut reader = decryptor
|
||||
.decrypt(iter::once(&app_key as &dyn age::Identity))
|
||||
.expect("Decrypt nsec file failed");
|
||||
reader
|
||||
.read_to_end(&mut decrypted)
|
||||
.expect("Read secret key failed");
|
||||
|
||||
// Get decrypted nsec key
|
||||
let nsec_key = String::from_utf8(decrypted).unwrap();
|
||||
|
||||
// Build nostr signer
|
||||
let secret_key = SecretKey::from_bech32(nsec_key).expect("Get secret key failed");
|
||||
let keys = Keys::new(secret_key);
|
||||
let signer = NostrSigner::Keys(keys);
|
||||
|
||||
// Update signer
|
||||
client.set_signer(Some(signer)).await;
|
||||
|
||||
// Update contact list
|
||||
let _contact_list = Some(
|
||||
client
|
||||
.get_contact_list(Some(Duration::from_secs(10)))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
} else {
|
||||
Err(())
|
||||
Err("App Key not found".into())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,35 +1,52 @@
|
||||
use crate::Nostr;
|
||||
use crate::NostrClient;
|
||||
use nostr_sdk::prelude::*;
|
||||
use std::{str::FromStr, time::Duration};
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_profile(id: &str, nostr: State<'_, Nostr>) -> Result<Metadata, ()> {
|
||||
let client = &nostr.client;
|
||||
let public_key: PublicKey = match Nip19::from_bech32(id) {
|
||||
pub async fn get_profile(id: &str, state: State<'_, NostrClient>) -> Result<Metadata, String> {
|
||||
let client = state.0.lock().await;
|
||||
let public_key: Option<PublicKey> = match Nip19::from_bech32(id) {
|
||||
Ok(val) => match val {
|
||||
Nip19::Pubkey(pubkey) => pubkey,
|
||||
Nip19::Profile(profile) => profile.public_key,
|
||||
_ => panic!("not nip19"),
|
||||
Nip19::Pubkey(pubkey) => Some(pubkey),
|
||||
Nip19::Profile(profile) => Some(profile.public_key),
|
||||
_ => None,
|
||||
},
|
||||
Err(_) => match PublicKey::from_str(id) {
|
||||
Ok(val) => Some(val),
|
||||
Err(_) => None,
|
||||
},
|
||||
Err(_) => PublicKey::from_str(id).unwrap(),
|
||||
};
|
||||
|
||||
let filter = Filter::new()
|
||||
.author(public_key)
|
||||
.kind(Kind::Metadata)
|
||||
.limit(1);
|
||||
if let Some(author) = public_key {
|
||||
let filter = Filter::new().author(author).kind(Kind::Metadata).limit(1);
|
||||
let events = client
|
||||
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
|
||||
.await
|
||||
.expect("Get metadata failed");
|
||||
|
||||
let events = client
|
||||
.get_events_of(vec![filter], Some(Duration::from_secs(10)))
|
||||
.await
|
||||
.expect("Get metadata failed");
|
||||
|
||||
if let Some(event) = events.first() {
|
||||
let metadata: Metadata = Metadata::from_json(&event.content).unwrap();
|
||||
Ok(metadata)
|
||||
if let Some(event) = events.first() {
|
||||
let metadata: Metadata = Metadata::from_json(&event.content).unwrap();
|
||||
Ok(metadata)
|
||||
} else {
|
||||
let rand_metadata = Metadata::new();
|
||||
Ok(rand_metadata)
|
||||
}
|
||||
} else {
|
||||
Err(())
|
||||
Err("Public Key is not valid".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_contact_list(state: State<'_, NostrClient>) -> Result<Vec<String>, String> {
|
||||
let client = state.0.lock().await;
|
||||
let contact_list = client.get_contact_list(Some(Duration::from_secs(10))).await;
|
||||
|
||||
if let Ok(list) = contact_list {
|
||||
let v = list.into_iter().map(|f| f.public_key.to_hex()).collect();
|
||||
Ok(v)
|
||||
} else {
|
||||
Err("Contact list not found".into())
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,10 +60,9 @@ pub async fn create_profile(
|
||||
nip05: &str,
|
||||
lud16: &str,
|
||||
website: &str,
|
||||
nostr: State<'_, Nostr>,
|
||||
state: State<'_, NostrClient>,
|
||||
) -> Result<EventId, ()> {
|
||||
let client = &nostr.client;
|
||||
|
||||
let client = state.0.lock().await;
|
||||
let metadata = Metadata::new()
|
||||
.name(name)
|
||||
.display_name(display_name)
|
||||
|
@ -1,10 +1,10 @@
|
||||
use crate::Nostr;
|
||||
use crate::NostrClient;
|
||||
use nostr_sdk::prelude::*;
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_connected_relays(nostr: State<'_, Nostr>) -> Result<Vec<Url>, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn list_connected_relays(state: State<'_, NostrClient>) -> Result<Vec<Url>, ()> {
|
||||
let client = state.0.lock().await;
|
||||
let relays = client.relays().await;
|
||||
let list: Vec<Url> = relays.into_keys().collect();
|
||||
|
||||
@ -12,8 +12,8 @@ pub async fn list_connected_relays(nostr: State<'_, Nostr>) -> Result<Vec<Url>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn connect_relay(relay: &str, nostr: State<'_, Nostr>) -> Result<bool, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn connect_relay(relay: &str, state: State<'_, NostrClient>) -> Result<bool, ()> {
|
||||
let client = state.0.lock().await;
|
||||
if let Ok(_) = client.add_relay(relay).await {
|
||||
Ok(true)
|
||||
} else {
|
||||
@ -22,8 +22,8 @@ pub async fn connect_relay(relay: &str, nostr: State<'_, Nostr>) -> Result<bool,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn remove_relay(relay: &str, nostr: State<'_, Nostr>) -> Result<bool, ()> {
|
||||
let client = &nostr.client;
|
||||
pub async fn remove_relay(relay: &str, state: State<'_, NostrClient>) -> Result<bool, ()> {
|
||||
let client = state.0.lock().await;
|
||||
if let Ok(_) = client.remove_relay(relay).await {
|
||||
Ok(true)
|
||||
} else {
|
||||
|
Loading…
x
Reference in New Issue
Block a user