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

View File

@ -3,7 +3,7 @@ import type { LumeColumn } from "@lume/types";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu"; import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { memo, useCallback, useEffect, useRef, useState } from "react"; import { memo, useCallback, useEffect, useRef, useState } from "react";
type WindowEvent = { type WindowEvent = {
@ -106,7 +106,7 @@ function Header({
const [isChanged, setIsChanged] = useState(false); const [isChanged, setIsChanged] = useState(false);
const saveNewTitle = async () => { const saveNewTitle = async () => {
const mainWindow = getCurrentWebviewWindow(); const mainWindow = getCurrentWindow();
await mainWindow.emit("columns", { type: "set_title", label, title }); await mainWindow.emit("columns", { type: "set_title", label, title });
// update search params // update search params
@ -135,7 +135,7 @@ function Header({
MenuItem.new({ MenuItem.new({
text: "Move left", text: "Move left",
action: async () => { action: async () => {
await getCurrentWebviewWindow().emit("columns", { await getCurrentWindow().emit("columns", {
type: "move", type: "move",
label, label,
direction: "left", direction: "left",
@ -145,7 +145,7 @@ function Header({
MenuItem.new({ MenuItem.new({
text: "Move right", text: "Move right",
action: async () => { action: async () => {
await getCurrentWebviewWindow().emit("columns", { await getCurrentWindow().emit("columns", {
type: "move", type: "move",
label, label,
direction: "right", direction: "right",
@ -156,7 +156,7 @@ function Header({
MenuItem.new({ MenuItem.new({
text: "Close", text: "Close",
action: async () => { action: async () => {
await getCurrentWebviewWindow().emit("columns", { await getCurrentWindow().emit("columns", {
type: "remove", type: "remove",
label, label,
}); });

View File

@ -30,11 +30,11 @@ function Screen() {
}); });
const scrollPrev = useCallback(() => { const scrollPrev = useCallback(() => {
if (emblaApi) emblaApi.scrollPrev(true); if (emblaApi) emblaApi.scrollPrev();
}, [emblaApi]); }, [emblaApi]);
const scrollNext = useCallback(() => { const scrollNext = useCallback(() => {
if (emblaApi) emblaApi.scrollNext(true); if (emblaApi) emblaApi.scrollNext();
}, [emblaApi]); }, [emblaApi]);
const emitScrollEvent = useCallback(() => { const emitScrollEvent = useCallback(() => {
@ -101,10 +101,10 @@ function Screen() {
switch (event.code) { switch (event.code) {
case "ArrowLeft": case "ArrowLeft":
if (emblaApi) emblaApi.scrollPrev(true); if (emblaApi) emblaApi.scrollPrev();
break; break;
case "ArrowRight": case "ArrowRight":
if (emblaApi) emblaApi.scrollNext(true); if (emblaApi) emblaApi.scrollNext();
break; break;
default: default:
break; break;

View File

@ -11,7 +11,6 @@ interface RouterContext {
export const Route = createRootRouteWithContext<RouterContext>()({ export const Route = createRootRouteWithContext<RouterContext>()({
component: () => <Outlet />, component: () => <Outlet />,
pendingComponent: Pending, pendingComponent: Pending,
wrapInSuspense: true,
}); });
function Pending() { function Pending() {

View File

@ -21,6 +21,9 @@ import { type ReactNode, useCallback, useEffect, useRef } from "react";
import { Virtualizer } from "virtua"; import { Virtualizer } from "virtua";
export const Route = createFileRoute("/panel/$account")({ export const Route = createFileRoute("/panel/$account")({
beforeLoad: async ({ context }) => {
console.log(context);
},
component: Screen, component: Screen,
}); });
@ -30,6 +33,7 @@ function Screen() {
const { isLoading, data } = useQuery({ const { isLoading, data } = useQuery({
queryKey: ["notification", account], queryKey: ["notification", account],
queryFn: async () => { queryFn: async () => {
console.log(queryClient);
const events = await NostrQuery.getNotifications(); const events = await NostrQuery.getNotifications();
return events; return events;
}, },

View File

@ -1 +0,0 @@
tab_spaces=2

View File

@ -2,173 +2,173 @@ use std::ffi::CString;
use tauri::{AppHandle, Emitter, Listener, Manager, WebviewWindow}; use tauri::{AppHandle, Emitter, Listener, Manager, WebviewWindow};
use tauri_nspanel::{ use tauri_nspanel::{
block::ConcreteBlock, block::ConcreteBlock,
cocoa::{ cocoa::{
appkit::{NSMainMenuWindowLevel, NSView, NSWindow, NSWindowCollectionBehavior}, appkit::{NSMainMenuWindowLevel, NSView, NSWindow, NSWindowCollectionBehavior},
base::{id, nil}, base::{id, nil},
foundation::{NSPoint, NSRect}, foundation::{NSPoint, NSRect},
}, },
objc::{class, msg_send, runtime::NO, sel, sel_impl}, objc::{class, msg_send, runtime::NO, sel, sel_impl},
panel_delegate, ManagerExt, WebviewWindowExt, panel_delegate, ManagerExt, WebviewWindowExt,
}; };
#[allow(non_upper_case_globals)] #[allow(non_upper_case_globals)]
const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7; const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;
pub fn swizzle_to_menubar_panel(app_handle: &tauri::AppHandle) { pub fn swizzle_to_menubar_panel(app_handle: &tauri::AppHandle) {
let panel_delegate = panel_delegate!(SpotlightPanelDelegate { let panel_delegate = panel_delegate!(SpotlightPanelDelegate {
window_did_resign_key window_did_resign_key
}); });
let window = app_handle.get_webview_window("panel").unwrap(); let window = app_handle.get_webview_window("panel").unwrap();
let panel = window.to_panel().unwrap(); let panel = window.to_panel().unwrap();
let handle = app_handle.clone(); let handle = app_handle.clone();
panel_delegate.set_listener(Box::new(move |delegate_name: String| { panel_delegate.set_listener(Box::new(move |delegate_name: String| {
if delegate_name.as_str() == "window_did_resign_key" { if delegate_name.as_str() == "window_did_resign_key" {
let _ = handle.emit("menubar_panel_did_resign_key", ()); let _ = handle.emit("menubar_panel_did_resign_key", ());
} }
})); }));
panel.set_level(NSMainMenuWindowLevel + 1); panel.set_level(NSMainMenuWindowLevel + 1);
panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel); panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel);
panel.set_collection_behaviour( panel.set_collection_behaviour(
NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces
| NSWindowCollectionBehavior::NSWindowCollectionBehaviorStationary | NSWindowCollectionBehavior::NSWindowCollectionBehaviorStationary
| NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary, | NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary,
); );
panel.set_delegate(panel_delegate); panel.set_delegate(panel_delegate);
} }
pub fn setup_menubar_panel_listeners(app_handle: &AppHandle) { pub fn setup_menubar_panel_listeners(app_handle: &AppHandle) {
fn hide_menubar_panel(app_handle: &tauri::AppHandle) { fn hide_menubar_panel(app_handle: &tauri::AppHandle) {
if check_menubar_frontmost() { if check_menubar_frontmost() {
return; return;
}
let panel = app_handle.get_webview_panel("panel").unwrap();
panel.order_out(None);
} }
let panel = app_handle.get_webview_panel("panel").unwrap(); let handle = app_handle.clone();
panel.order_out(None); app_handle.listen_any("menubar_panel_did_resign_key", move |_| {
} hide_menubar_panel(&handle);
});
let handle = app_handle.clone(); let handle = app_handle.clone();
app_handle.listen_any("menubar_panel_did_resign_key", move |_| { let callback = Box::new(move || {
hide_menubar_panel(&handle); hide_menubar_panel(&handle);
}); });
let handle = app_handle.clone(); register_workspace_listener(
"NSWorkspaceDidActivateApplicationNotification".into(),
callback.clone(),
);
let callback = Box::new(move || { register_workspace_listener(
hide_menubar_panel(&handle); "NSWorkspaceActiveSpaceDidChangeNotification".into(),
}); callback,
);
register_workspace_listener(
"NSWorkspaceDidActivateApplicationNotification".into(),
callback.clone(),
);
register_workspace_listener(
"NSWorkspaceActiveSpaceDidChangeNotification".into(),
callback,
);
} }
pub fn set_corner_radius(window: &WebviewWindow, radius: f64) { pub fn set_corner_radius(window: &WebviewWindow, radius: f64) {
let win: id = window.ns_window().unwrap() as _; let win: id = window.ns_window().unwrap() as _;
unsafe { unsafe {
let view: id = win.contentView(); let view: id = win.contentView();
view.wantsLayer(); view.wantsLayer();
let layer: id = view.layer(); let layer: id = view.layer();
let _: () = msg_send![layer, setCornerRadius: radius]; let _: () = msg_send![layer, setCornerRadius: radius];
} }
} }
pub fn position_menubar_panel(app_handle: &tauri::AppHandle, padding_top: f64) { pub fn position_menubar_panel(app_handle: &tauri::AppHandle, padding_top: f64) {
let window = app_handle.get_webview_window("panel").unwrap(); let window = app_handle.get_webview_window("panel").unwrap();
let monitor = monitor::get_monitor_with_cursor().unwrap(); let monitor = monitor::get_monitor_with_cursor().unwrap();
let scale_factor = monitor.scale_factor(); let scale_factor = monitor.scale_factor();
let visible_area = monitor.visible_area(); let visible_area = monitor.visible_area();
let monitor_pos = visible_area.position().to_logical::<f64>(scale_factor); let monitor_pos = visible_area.position().to_logical::<f64>(scale_factor);
let monitor_size = visible_area.size().to_logical::<f64>(scale_factor); let monitor_size = visible_area.size().to_logical::<f64>(scale_factor);
let mouse_location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; let mouse_location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] };
let handle: id = window.ns_window().unwrap() as _; let handle: id = window.ns_window().unwrap() as _;
let mut win_frame: NSRect = unsafe { msg_send![handle, frame] }; let mut win_frame: NSRect = unsafe { msg_send![handle, frame] };
win_frame.origin.y = (monitor_pos.y + monitor_size.height) - win_frame.size.height; win_frame.origin.y = (monitor_pos.y + monitor_size.height) - win_frame.size.height;
win_frame.origin.y -= padding_top; win_frame.origin.y -= padding_top;
win_frame.origin.x = { win_frame.origin.x = {
let top_right = mouse_location.x + (win_frame.size.width / 2.0); let top_right = mouse_location.x + (win_frame.size.width / 2.0);
let is_offscreen = top_right > monitor_pos.x + monitor_size.width; let is_offscreen = top_right > monitor_pos.x + monitor_size.width;
if !is_offscreen { if !is_offscreen {
mouse_location.x - (win_frame.size.width / 2.0) mouse_location.x - (win_frame.size.width / 2.0)
} else { } else {
let diff = top_right - (monitor_pos.x + monitor_size.width); let diff = top_right - (monitor_pos.x + monitor_size.width);
mouse_location.x - (win_frame.size.width / 2.0) - diff mouse_location.x - (win_frame.size.width / 2.0) - diff
} }
}; };
let _: () = unsafe { msg_send![handle, setFrame: win_frame display: NO] }; let _: () = unsafe { msg_send![handle, setFrame: win_frame display: NO] };
} }
fn register_workspace_listener(name: String, callback: Box<dyn Fn()>) { fn register_workspace_listener(name: String, callback: Box<dyn Fn()>) {
let workspace: id = unsafe { msg_send![class!(NSWorkspace), sharedWorkspace] }; let workspace: id = unsafe { msg_send![class!(NSWorkspace), sharedWorkspace] };
let notification_center: id = unsafe { msg_send![workspace, notificationCenter] }; let notification_center: id = unsafe { msg_send![workspace, notificationCenter] };
let block = ConcreteBlock::new(move |_notif: id| { let block = ConcreteBlock::new(move |_notif: id| {
callback(); callback();
}); });
let block = block.copy(); let block = block.copy();
let name: id = let name: id =
unsafe { msg_send![class!(NSString), stringWithCString: CString::new(name).unwrap()] }; unsafe { msg_send![class!(NSString), stringWithCString: CString::new(name).unwrap()] };
unsafe { unsafe {
let _: () = msg_send![ let _: () = msg_send![
notification_center, notification_center,
addObserverForName: name object: nil queue: nil usingBlock: block addObserverForName: name object: nil queue: nil usingBlock: block
]; ];
} }
} }
fn app_pid() -> i32 { fn app_pid() -> i32 {
let process_info: id = unsafe { msg_send![class!(NSProcessInfo), processInfo] }; let process_info: id = unsafe { msg_send![class!(NSProcessInfo), processInfo] };
let pid: i32 = unsafe { msg_send![process_info, processIdentifier] }; let pid: i32 = unsafe { msg_send![process_info, processIdentifier] };
pid pid
} }
fn get_frontmost_app_pid() -> i32 { fn get_frontmost_app_pid() -> i32 {
let workspace: id = unsafe { msg_send![class!(NSWorkspace), sharedWorkspace] }; let workspace: id = unsafe { msg_send![class!(NSWorkspace), sharedWorkspace] };
let frontmost_application: id = unsafe { msg_send![workspace, frontmostApplication] }; let frontmost_application: id = unsafe { msg_send![workspace, frontmostApplication] };
let pid: i32 = unsafe { msg_send![frontmost_application, processIdentifier] }; let pid: i32 = unsafe { msg_send![frontmost_application, processIdentifier] };
pid pid
} }
pub fn check_menubar_frontmost() -> bool { pub fn check_menubar_frontmost() -> bool {
get_frontmost_app_pid() == app_pid() get_frontmost_app_pid() == app_pid()
} }

View File

@ -1,65 +1,65 @@
use std::path::PathBuf; use std::path::PathBuf;
use tauri::window::{Effect, EffectsBuilder}; use tauri::window::{Effect, EffectsBuilder};
use tauri::{ use tauri::{
tray::{MouseButtonState, TrayIconEvent}, tray::{MouseButtonState, TrayIconEvent},
WebviewWindowBuilder, WebviewWindowBuilder,
}; };
use tauri::{AppHandle, Manager, WebviewUrl}; use tauri::{AppHandle, Manager, WebviewUrl};
use tauri_nspanel::ManagerExt; use tauri_nspanel::ManagerExt;
use super::fns::{ use super::fns::{
position_menubar_panel, set_corner_radius, setup_menubar_panel_listeners, position_menubar_panel, set_corner_radius, setup_menubar_panel_listeners,
swizzle_to_menubar_panel, swizzle_to_menubar_panel,
}; };
pub fn create_tray_panel(account: &str, app: &AppHandle) { pub fn create_tray_panel(account: &str, app: &AppHandle) {
let tray = app.tray_by_id("main").unwrap(); let tray = app.tray_by_id("main").unwrap();
tray.on_tray_icon_event(|tray, event| { tray.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click { button_state, .. } = event { if let TrayIconEvent::Click { button_state, .. } = event {
if button_state == MouseButtonState::Up { if button_state == MouseButtonState::Up {
let app = tray.app_handle(); let app = tray.app_handle();
let panel = app.get_webview_panel("panel").unwrap(); let panel = app.get_webview_panel("panel").unwrap();
match panel.is_visible() { match panel.is_visible() {
true => panel.order_out(None), true => panel.order_out(None),
false => { false => {
position_menubar_panel(app, 0.0); position_menubar_panel(app, 0.0);
panel.show(); panel.show();
} }
}
}
} }
} });
}
});
if let Some(window) = app.get_webview_window("panel") { if let Some(window) = app.get_webview_window("panel") {
let _ = window.destroy(); let _ = window.destroy();
}; };
let mut url = "/panel/".to_owned(); let mut url = "/panel/".to_owned();
url.push_str(account); url.push_str(account);
let window = WebviewWindowBuilder::new(app, "panel", WebviewUrl::App(PathBuf::from(url))) let window = WebviewWindowBuilder::new(app, "panel", WebviewUrl::App(PathBuf::from(url)))
.title("Panel") .title("Panel")
.inner_size(350.0, 500.0) .inner_size(350.0, 500.0)
.fullscreen(false) .fullscreen(false)
.resizable(false) .resizable(false)
.visible(false) .visible(false)
.decorations(false) .decorations(false)
.transparent(true) .transparent(true)
.build() .build()
.unwrap(); .unwrap();
let _ = window.set_effects( let _ = window.set_effects(
EffectsBuilder::new() EffectsBuilder::new()
.effect(Effect::Popover) .effect(Effect::Popover)
.state(tauri::window::EffectState::FollowsWindowActiveState) .state(tauri::window::EffectState::FollowsWindowActiveState)
.build(), .build(),
); );
set_corner_radius(&window, 13.0); set_corner_radius(&window, 13.0);
// Convert window to panel // Convert window to panel
swizzle_to_menubar_panel(app); swizzle_to_menubar_panel(app);
setup_menubar_panel_listeners(app); setup_menubar_panel_listeners(app);
} }

View File

@ -23,259 +23,260 @@ use crate::Nostr;
#[derive(Serialize, Deserialize, Type)] #[derive(Serialize, Deserialize, Type)]
pub struct Window { pub struct Window {
label: String, label: String,
title: String, title: String,
url: String, url: String,
width: f64, width: f64,
height: f64, height: f64,
maximizable: bool, maximizable: bool,
minimizable: bool, minimizable: bool,
hidden_title: bool, hidden_title: bool,
} }
#[derive(Serialize, Deserialize, Type)] #[derive(Serialize, Deserialize, Type)]
pub struct Column { pub struct Column {
label: String, label: String,
url: String, url: String,
x: f32, x: f32,
y: f32, y: f32,
width: f32, width: f32,
height: f32, height: f32,
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn create_column( pub fn create_column(
column: Column, column: Column,
app_handle: tauri::AppHandle, app_handle: tauri::AppHandle,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let settings = state.settings.lock().unwrap().clone(); let settings = state.settings.lock().unwrap().clone();
match app_handle.get_window("main") { match app_handle.get_window("main") {
Some(main_window) => match app_handle.get_webview(&column.label) { Some(main_window) => match app_handle.get_webview(&column.label) {
Some(_) => Ok(column.label), Some(_) => Ok(column.label),
None => { None => {
let path = PathBuf::from(column.url); let path = PathBuf::from(column.url);
let webview_url = WebviewUrl::App(path); let webview_url = WebviewUrl::App(path);
let builder = match settings.proxy { let builder = match settings.proxy {
Some(url) => { Some(url) => {
let proxy = Url::from_str(&url).unwrap(); let proxy = Url::from_str(&url).unwrap();
tauri::webview::WebviewBuilder::new(column.label, webview_url) tauri::webview::WebviewBuilder::new(column.label, webview_url)
.user_agent("Lume/4.0") .user_agent("Lume/4.0")
.zoom_hotkeys_enabled(true) .zoom_hotkeys_enabled(true)
.enable_clipboard_access() .enable_clipboard_access()
.transparent(true) .transparent(true)
.proxy_url(proxy) .proxy_url(proxy)
} }
None => tauri::webview::WebviewBuilder::new(column.label, webview_url) None => tauri::webview::WebviewBuilder::new(column.label, webview_url)
.user_agent("Lume/4.0") .user_agent("Lume/4.0")
.zoom_hotkeys_enabled(true) .zoom_hotkeys_enabled(true)
.enable_clipboard_access() .enable_clipboard_access()
.transparent(true), .transparent(true),
}; };
match main_window.add_child( match main_window.add_child(
builder, builder,
LogicalPosition::new(column.x, column.y), LogicalPosition::new(column.x, column.y),
LogicalSize::new(column.width, column.height), LogicalSize::new(column.width, column.height),
) { ) {
Ok(webview) => Ok(webview.label().into()), Ok(webview) => Ok(webview.label().into()),
Err(_) => Err("Create webview failed".into()), Err(_) => Err("Create webview failed".into()),
} }
} }
}, },
None => Err("Main window not found".into()), None => Err("Main window not found".into()),
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn close_column(label: &str, app_handle: tauri::AppHandle) -> Result<bool, String> { pub fn close_column(label: &str, app_handle: tauri::AppHandle) -> Result<bool, String> {
match app_handle.get_webview(label) { match app_handle.get_webview(label) {
Some(webview) => { Some(webview) => {
if webview.close().is_ok() { if webview.close().is_ok() {
Ok(true) Ok(true)
} else { } else {
Ok(false) Ok(false)
} }
}
None => Err("Column not found.".into()),
} }
None => Err("Column not found.".into()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn reposition_column( pub fn reposition_column(
label: &str, label: &str,
x: f32, x: f32,
y: f32, y: f32,
app_handle: tauri::AppHandle, app_handle: tauri::AppHandle,
) -> Result<(), String> { ) -> Result<(), String> {
match app_handle.get_webview(label) { match app_handle.get_webview(label) {
Some(webview) => { Some(webview) => {
if webview.set_position(LogicalPosition::new(x, y)).is_ok() { if webview.set_position(LogicalPosition::new(x, y)).is_ok() {
Ok(()) Ok(())
} else { } else {
Err("Reposition column failed".into()) Err("Reposition column failed".into())
} }
}
None => Err("Webview not found".into()),
} }
None => Err("Webview not found".into()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn resize_column( pub fn resize_column(
label: &str, label: &str,
width: f32, width: f32,
height: f32, height: f32,
app_handle: tauri::AppHandle, app_handle: tauri::AppHandle,
) -> Result<(), String> { ) -> Result<(), String> {
match app_handle.get_webview(label) { match app_handle.get_webview(label) {
Some(webview) => { Some(webview) => {
if webview.set_size(LogicalSize::new(width, height)).is_ok() { if webview.set_size(LogicalSize::new(width, height)).is_ok() {
Ok(()) Ok(())
} else { } else {
Err("Resize column failed".into()) Err("Resize column failed".into())
} }
}
None => Err("Webview not found".into()),
} }
None => Err("Webview not found".into()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn reload_column(label: &str, app_handle: tauri::AppHandle) -> Result<(), String> { pub fn reload_column(label: &str, app_handle: tauri::AppHandle) -> Result<(), String> {
match app_handle.get_webview(label) { match app_handle.get_webview(label) {
Some(webview) => { Some(webview) => {
if webview.eval("window.location.reload()").is_ok() { if webview.eval("window.location.reload()").is_ok() {
Ok(()) Ok(())
} else { } else {
Err("Reload column failed".into()) Err("Reload column failed".into())
} }
}
None => Err("Webview not found".into()),
} }
None => Err("Webview not found".into()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<(), String> { pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<(), String> {
if let Some(window) = app_handle.get_window(&window.label) { if let Some(window) = app_handle.get_window(&window.label) {
if window.is_visible().unwrap_or_default() { if window.is_visible().unwrap_or_default() {
let _ = window.set_focus(); let _ = window.set_focus();
} else {
let _ = window.show();
let _ = window.set_focus();
};
} else { } else {
let _ = window.show(); #[cfg(target_os = "macos")]
let _ = window.set_focus(); let window = WebviewWindowBuilder::new(
}; &app_handle,
} else { &window.label,
#[cfg(target_os = "macos")] WebviewUrl::App(PathBuf::from(window.url)),
let window = WebviewWindowBuilder::new( )
&app_handle, .title(&window.title)
&window.label, .min_inner_size(window.width, window.height)
WebviewUrl::App(PathBuf::from(window.url)), .inner_size(window.width, window.height)
) .hidden_title(window.hidden_title)
.title(&window.title) .title_bar_style(TitleBarStyle::Overlay)
.min_inner_size(window.width, window.height) .minimizable(window.minimizable)
.inner_size(window.width, window.height) .maximizable(window.maximizable)
.hidden_title(window.hidden_title) .transparent(true)
.title_bar_style(TitleBarStyle::Overlay) .effects(WindowEffectsConfig {
.minimizable(window.minimizable) state: None,
.maximizable(window.maximizable) effects: vec![Effect::UnderWindowBackground],
.transparent(true) radius: None,
.effects(WindowEffectsConfig { color: None,
state: None, })
effects: vec![Effect::UnderWindowBackground], .build()
radius: None, .unwrap();
color: None,
})
.build()
.unwrap();
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let window = WebviewWindowBuilder::new( let window = WebviewWindowBuilder::new(
&app_handle, &app_handle,
&window.label, &window.label,
WebviewUrl::App(PathBuf::from(window.url)), WebviewUrl::App(PathBuf::from(window.url)),
) )
.title(title) .title(title)
.min_inner_size(window.width, window.height) .min_inner_size(window.width, window.height)
.inner_size(window.width, window.height) .inner_size(window.width, window.height)
.minimizable(window.minimizable) .minimizable(window.minimizable)
.maximizable(window.maximizable) .maximizable(window.maximizable)
.effects(WindowEffectsConfig { .effects(WindowEffectsConfig {
state: None, state: None,
effects: vec![Effect::Mica], effects: vec![Effect::Mica],
radius: None, radius: None,
color: None, color: None,
}) })
.build() .build()
.unwrap(); .unwrap();
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
let window = WebviewWindowBuilder::new( let window = WebviewWindowBuilder::new(
&app_handle, &app_handle,
&window.label, &window.label,
WebviewUrl::App(PathBuf::from(window.url)), WebviewUrl::App(PathBuf::from(window.url)),
) )
.title(title) .title(title)
.min_inner_size(window.width, window.height) .min_inner_size(window.width, window.height)
.inner_size(window.width, window.height) .inner_size(window.width, window.height)
.minimizable(window.minimizable) .minimizable(window.minimizable)
.maximizable(window.maximizable) .maximizable(window.maximizable)
.build() .build()
.unwrap(); .unwrap();
// Set decoration // Set decoration
window.create_overlay_titlebar().unwrap(); window.create_overlay_titlebar().unwrap();
// Restore native border // Restore native border
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
window.add_border(None); window.add_border(None);
} }
Ok(()) Ok(())
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn open_main_window(app: tauri::AppHandle) { pub fn open_main_window(app: tauri::AppHandle) {
if let Some(window) = app.get_window("main") { if let Some(window) = app.get_window("main") {
if window.is_visible().unwrap_or_default() { if window.is_visible().unwrap_or_default() {
let _ = window.set_focus(); let _ = window.set_focus();
} else {
let _ = window.show();
let _ = window.set_focus();
};
} else { } else {
let _ = window.show(); let window =
let _ = window.set_focus(); WebviewWindowBuilder::from_config(&app, app.config().app.windows.first().unwrap())
}; .unwrap()
} else { .build()
let window = WebviewWindowBuilder::from_config(&app, app.config().app.windows.first().unwrap()) .unwrap();
.unwrap()
.build()
.unwrap();
// Restore native border // Restore native border
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
window.add_border(None); window.add_border(None);
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn force_quit() { pub fn force_quit() {
std::process::exit(0) std::process::exit(0)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn set_badge(count: i32) { pub fn set_badge(count: i32) {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
unsafe { unsafe {
let label = if count == 0 { let label = if count == 0 {
nil nil
} else { } else {
NSString::alloc(nil).init_str(&format!("{}", count)) NSString::alloc(nil).init_str(&format!("{}", count))
}; };
let dock_tile: cocoa::base::id = msg_send![NSApp(), dockTile]; let dock_tile: cocoa::base::id = msg_send![NSApp(), dockTile];
let _: cocoa::base::id = msg_send![dock_tile, setBadgeLabel: label]; let _: cocoa::base::id = msg_send![dock_tile, setBadgeLabel: label];
} }
} }

View File

@ -1,6 +1,6 @@
#![cfg_attr( #![cfg_attr(
all(not(debug_assertions), target_os = "windows"), all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows" windows_subsystem = "windows"
)] )]
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -17,9 +17,9 @@ use specta::Type;
use std::sync::Mutex; use std::sync::Mutex;
use std::time::Duration; use std::time::Duration;
use std::{ use std::{
fs, fs,
io::{self, BufRead}, io::{self, BufRead},
str::FromStr, str::FromStr,
}; };
use tauri::{path::BaseDirectory, Manager}; use tauri::{path::BaseDirectory, Manager};
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
@ -30,39 +30,39 @@ pub mod nostr;
#[derive(Serialize)] #[derive(Serialize)]
pub struct Nostr { pub struct Nostr {
#[serde(skip_serializing)] #[serde(skip_serializing)]
client: Client, client: Client,
contact_list: Mutex<Vec<Contact>>, contact_list: Mutex<Vec<Contact>>,
settings: Mutex<Settings>, settings: Mutex<Settings>,
} }
#[derive(Clone, Serialize, Deserialize, Type)] #[derive(Clone, Serialize, Deserialize, Type)]
pub struct Settings { pub struct Settings {
proxy: Option<String>, proxy: Option<String>,
image_resize_service: Option<String>, image_resize_service: Option<String>,
use_relay_hint: bool, use_relay_hint: bool,
content_warning: bool, content_warning: bool,
display_avatar: bool, display_avatar: bool,
display_zap_button: bool, display_zap_button: bool,
display_repost_button: bool, display_repost_button: bool,
display_media: bool, display_media: bool,
vibrancy: bool, vibrancy: bool,
} }
impl Default for Settings { impl Default for Settings {
fn default() -> Self { fn default() -> Self {
Self { Self {
proxy: None, proxy: None,
image_resize_service: Some("https://wsrv.nl/".into()), image_resize_service: Some("https://wsrv.nl/".into()),
use_relay_hint: true, use_relay_hint: true,
content_warning: true, content_warning: true,
display_avatar: true, display_avatar: true,
display_zap_button: true, display_zap_button: true,
display_repost_button: true, display_repost_button: true,
display_media: true, display_media: true,
vibrancy: true, vibrancy: true,
}
} }
}
} }
pub const FETCH_LIMIT: usize = 20; pub const FETCH_LIMIT: usize = 20;
@ -70,201 +70,190 @@ pub const NEWSFEED_NEG_LIMIT: usize = 256;
pub const NOTIFICATION_NEG_LIMIT: usize = 64; pub const NOTIFICATION_NEG_LIMIT: usize = 64;
fn main() { fn main() {
let mut ctx = tauri::generate_context!(); let mut ctx = tauri::generate_context!();
let invoke_handler = { let invoke_handler = {
let builder = tauri_specta::ts::builder().commands(tauri_specta::collect_commands![ let builder = tauri_specta::ts::builder().commands(tauri_specta::collect_commands![
nostr::relay::get_relays, nostr::relay::get_relays,
nostr::relay::connect_relay, nostr::relay::connect_relay,
nostr::relay::remove_relay, nostr::relay::remove_relay,
nostr::relay::get_bootstrap_relays, nostr::relay::get_bootstrap_relays,
nostr::relay::save_bootstrap_relays, nostr::relay::save_bootstrap_relays,
nostr::keys::get_accounts, nostr::keys::get_accounts,
nostr::keys::create_account, nostr::keys::create_account,
nostr::keys::save_account, nostr::keys::save_account,
nostr::keys::get_encrypted_key, nostr::keys::get_encrypted_key,
nostr::keys::get_private_key, nostr::keys::get_private_key,
nostr::keys::connect_remote_account, nostr::keys::connect_remote_account,
nostr::keys::load_account, nostr::keys::load_account,
nostr::metadata::get_current_profile, nostr::metadata::get_current_profile,
nostr::metadata::get_profile, nostr::metadata::get_profile,
nostr::metadata::get_contact_list, nostr::metadata::get_contact_list,
nostr::metadata::set_contact_list, nostr::metadata::set_contact_list,
nostr::metadata::create_profile, nostr::metadata::create_profile,
nostr::metadata::is_contact_list_empty, nostr::metadata::is_contact_list_empty,
nostr::metadata::check_contact, nostr::metadata::check_contact,
nostr::metadata::toggle_contact, nostr::metadata::toggle_contact,
nostr::metadata::get_nstore, nostr::metadata::get_nstore,
nostr::metadata::set_nstore, nostr::metadata::set_nstore,
nostr::metadata::set_wallet, nostr::metadata::set_wallet,
nostr::metadata::load_wallet, nostr::metadata::load_wallet,
nostr::metadata::remove_wallet, nostr::metadata::remove_wallet,
nostr::metadata::zap_profile, nostr::metadata::zap_profile,
nostr::metadata::zap_event, nostr::metadata::zap_event,
nostr::metadata::friend_to_friend, nostr::metadata::friend_to_friend,
nostr::metadata::get_notifications, nostr::metadata::get_notifications,
nostr::metadata::get_settings, nostr::metadata::get_settings,
nostr::metadata::set_new_settings, nostr::metadata::set_new_settings,
nostr::metadata::verify_nip05, nostr::metadata::verify_nip05,
nostr::event::get_event_meta, nostr::event::get_event_meta,
nostr::event::get_event, nostr::event::get_event,
nostr::event::get_event_from, nostr::event::get_event_from,
nostr::event::get_replies, nostr::event::get_replies,
nostr::event::listen_event_reply, nostr::event::listen_event_reply,
nostr::event::get_events_by, nostr::event::get_events_by,
nostr::event::get_local_events, nostr::event::get_local_events,
nostr::event::listen_local_event, nostr::event::listen_local_event,
nostr::event::get_group_events, nostr::event::get_group_events,
nostr::event::get_global_events, nostr::event::get_global_events,
nostr::event::get_hashtag_events, nostr::event::get_hashtag_events,
nostr::event::publish, nostr::event::publish,
nostr::event::reply, nostr::event::reply,
nostr::event::repost, nostr::event::repost,
nostr::event::event_to_bech32, nostr::event::event_to_bech32,
nostr::event::user_to_bech32, nostr::event::user_to_bech32,
nostr::event::unlisten, nostr::event::unlisten,
commands::window::create_column, commands::window::create_column,
commands::window::close_column, commands::window::close_column,
commands::window::reposition_column, commands::window::reposition_column,
commands::window::resize_column, commands::window::resize_column,
commands::window::reload_column, commands::window::reload_column,
commands::window::open_window, commands::window::open_window,
commands::window::open_main_window, commands::window::open_main_window,
commands::window::force_quit, commands::window::force_quit,
commands::window::set_badge commands::window::set_badge
]); ]);
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
let builder = builder.path("../packages/system/src/commands.ts"); let builder = builder.path("../packages/system/src/commands.ts");
builder.build().unwrap() builder.build().unwrap()
}; };
tauri::Builder::default() tauri::Builder::default()
.setup(|app| { .setup(|app| {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
app.handle().plugin(tauri_nspanel::init()).unwrap(); app.handle().plugin(tauri_nspanel::init()).unwrap();
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
let main_window = app.get_webview_window("main").unwrap(); let main_window = app.get_webview_window("main").unwrap();
// Set custom decoration for Windows // Set custom decoration for Windows
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
main_window.create_overlay_titlebar().unwrap(); main_window.create_overlay_titlebar().unwrap();
// Restore native border // Restore native border
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
main_window.add_border(None); main_window.add_border(None);
// Set a custom inset to the traffic lights // Set a custom inset to the traffic lights
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
main_window.set_traffic_lights_inset(8.0, 16.0).unwrap(); main_window.set_traffic_lights_inset(8.0, 16.0).unwrap();
// Create data folder if not exist #[cfg(target_os = "macos")]
let home_dir = app.path().home_dir().unwrap(); let win = main_window.clone();
let _ = fs::create_dir_all(home_dir.join("Lume/"));
tauri::async_runtime::block_on(async move { #[cfg(target_os = "macos")]
// Setup database main_window.on_window_event(move |event| {
let database = SQLiteDatabase::open(home_dir.join("Lume/lume.db")).await; if let tauri::WindowEvent::ThemeChanged(_) = event {
win.set_traffic_lights_inset(8.0, 16.0).unwrap();
// Config
let opts = Options::new()
.automatic_authentication(true)
.connection_timeout(Some(Duration::from_secs(5)))
.timeout(Duration::from_secs(30));
// Setup nostr client
let client = match database {
Ok(db) => ClientBuilder::default().database(db).opts(opts).build(),
Err(_) => ClientBuilder::default().opts(opts).build(),
};
// Get bootstrap relays
if let Ok(path) = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
{
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(_) => { if let tauri::WindowEvent::Resized(_) = event {
println!("connecting to bootstrap relay...: {}", relay); win.set_traffic_lights_inset(8.0, 16.0).unwrap();
let _ = client.add_relay(relay).await;
} }
} });
}
}
}
// Connect // Create data folder if not exist
client.connect().await; let home_dir = app.path().home_dir().unwrap();
let _ = fs::create_dir_all(home_dir.join("Lume/"));
// Update global state tauri::async_runtime::block_on(async move {
app.handle().manage(Nostr { // Setup database
client, let database = SQLiteDatabase::open(home_dir.join("Lume/lume.db")).await;
contact_list: Mutex::new(vec![]),
settings: Mutex::new(Settings::default()), // Config
let opts = Options::new()
.automatic_authentication(true)
.connection_timeout(Some(Duration::from_secs(5)))
.timeout(Duration::from_secs(30));
// Setup nostr client
let client = match database {
Ok(db) => ClientBuilder::default().database(db).opts(opts).build(),
Err(_) => ClientBuilder::default().opts(opts).build(),
};
// Get bootstrap relays
if let Ok(path) = app
.path()
.resolve("resources/relays.txt", BaseDirectory::Resource)
{
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;
}
}
}
}
}
// Connect
client.connect().await;
// Update global state
app.handle().manage(Nostr {
client,
contact_list: Mutex::new(vec![]),
settings: Mutex::new(Settings::default()),
})
});
Ok(())
}) })
}); .enable_macos_default_menu(false)
.plugin(tauri_nspanel::init())
Ok(()) .plugin(tauri_plugin_theme::init(ctx.config_mut()))
}) .plugin(tauri_plugin_decorum::init())
.enable_macos_default_menu(false) .plugin(tauri_plugin_clipboard_manager::init())
.on_window_event(move |window, event| { .plugin(tauri_plugin_dialog::init())
#[cfg(target_os = "macos")] .plugin(tauri_plugin_fs::init())
if let tauri::WindowEvent::ThemeChanged(_) = event { .plugin(tauri_plugin_http::init())
if let Some(webview) = window.get_webview_window(window.label()) { .plugin(tauri_plugin_notification::init())
webview.set_traffic_lights_inset(8.0, 16.0).unwrap(); .plugin(tauri_plugin_os::init())
} .plugin(tauri_plugin_process::init())
} .plugin(tauri_plugin_shell::init())
#[cfg(target_os = "macos")] .plugin(tauri_plugin_upload::init())
if let tauri::WindowEvent::Resized(_) = event { .plugin(tauri_plugin_updater::Builder::new().build())
if let Some(webview) = window.get_webview_window(window.label()) { .invoke_handler(invoke_handler)
webview.set_traffic_lights_inset(8.0, 16.0).unwrap(); .run(ctx)
} .expect("error while running tauri application");
}
})
.plugin(tauri_nspanel::init())
.plugin(tauri_plugin_theme::init(ctx.config_mut()))
.plugin(tauri_plugin_decorum::init())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_upload::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(
tauri_plugin_window_state::Builder::new()
.with_denylist(&["panel"])
.build(),
)
.invoke_handler(invoke_handler)
.build(ctx)
.expect("error while running tauri application")
.run(|_, event| {
if let tauri::RunEvent::ExitRequested { api, .. } = event {
// Hide app icon on macOS
// let _ = app.set_activation_policy(tauri::ActivationPolicy::Accessory);
// Keep API running
api.prevent_exit();
}
});
} }

File diff suppressed because it is too large Load Diff

View File

@ -2,74 +2,74 @@ use crate::Settings;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
pub async fn init_nip65(client: &Client) { pub async fn init_nip65(client: &Client) {
let signer = client.signer().await.unwrap(); let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap(); let public_key = signer.public_key().await.unwrap();
if let Ok(events) = client if let Ok(events) = client
.get_events_of( .get_events_of(
vec![Filter::new() vec![Filter::new()
.author(public_key) .author(public_key)
.kind(Kind::RelayList) .kind(Kind::RelayList)
.limit(1)], .limit(1)],
None, None,
) )
.await .await
{ {
if let Some(event) = events.first() { if let Some(event) = events.first() {
let relay_list = nip65::extract_relay_list(event); let relay_list = nip65::extract_relay_list(event);
for item in relay_list.into_iter() { for item in relay_list.into_iter() {
let relay_url = item.0.to_string(); let relay_url = item.0.to_string();
let opts = match item.1 { let opts = match item.1 {
Some(val) => { Some(val) => {
if val == &RelayMetadata::Read { if val == &RelayMetadata::Read {
RelayOptions::new().read(true).write(false) RelayOptions::new().read(true).write(false)
} else { } else {
RelayOptions::new().write(true).read(false) 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> { pub async fn get_user_settings(client: &Client) -> Result<Settings, String> {
let ident = "lume:settings"; let ident = "lume:settings";
let signer = client.signer().await.unwrap(); let signer = client.signer().await.unwrap();
let public_key = signer.public_key().await.unwrap(); let public_key = signer.public_key().await.unwrap();
let filter = Filter::new() let filter = Filter::new()
.author(public_key) .author(public_key)
.kind(Kind::ApplicationSpecificData) .kind(Kind::ApplicationSpecificData)
.identifier(ident) .identifier(ident)
.limit(1); .limit(1);
if let Ok(events) = client.get_events_of(vec![filter], None).await { if let Ok(events) = client.get_events_of(vec![filter], None).await {
if let Some(event) = events.first() { if let Some(event) = events.first() {
let content = event.content(); let content = event.content();
if let Ok(decrypted) = signer.nip44_decrypt(public_key, content).await { if let Ok(decrypted) = signer.nip44_decrypt(public_key, content).await {
match serde_json::from_str(&decrypted) { match serde_json::from_str(&decrypted) {
Ok(parsed) => parsed, Ok(parsed) => parsed,
Err(_) => Err("Could not parse settings payload".into()), 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 { } else {
Err("Settings not found.".into()) Err("Settings not found.".into())
} }
} else {
Err("Settings not found.".into())
}
} }

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::Entry;
use keyring_search::{Limit, List, Search}; use keyring_search::{Limit, List, Search};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
@ -8,402 +12,411 @@ use std::time::Duration;
use tauri::{Emitter, EventTarget, Manager, State}; use tauri::{Emitter, EventTarget, Manager, State};
use tauri_plugin_notification::NotificationExt; 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)] #[derive(Serialize, Type)]
pub struct Account { pub struct Account {
npub: String, npub: String,
nsec: String, nsec: String,
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn get_accounts() -> Result<Vec<String>, String> { pub fn get_accounts() -> Result<Vec<String>, String> {
let search = Search::new().map_err(|e| e.to_string())?; let search = Search::new().map_err(|e| e.to_string())?;
let results = search.by("Account", "nostr_secret"); let results = search.by("Account", "nostr_secret");
match List::list_credentials(results, Limit::All) { match List::list_credentials(results, Limit::All) {
Ok(list) => { Ok(list) => {
let accounts: HashSet<String> = list let accounts: HashSet<String> = list
.split_whitespace() .split_whitespace()
.filter(|v| v.starts_with("npub1")) .filter(|v| v.starts_with("npub1"))
.map(String::from) .map(String::from)
.collect(); .collect();
Ok(accounts.into_iter().collect()) Ok(accounts.into_iter().collect())
}
Err(_) => Err("Empty.".into()),
} }
Err(_) => Err("Empty.".into()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn create_account() -> Result<Account, String> { pub fn create_account() -> Result<Account, String> {
let keys = Keys::generate(); let keys = Keys::generate();
let public_key = keys.public_key(); let public_key = keys.public_key();
let secret_key = keys.secret_key().unwrap(); let secret_key = keys.secret_key().unwrap();
let result = Account { let result = Account {
npub: public_key.to_bech32().unwrap(), npub: public_key.to_bech32().unwrap(),
nsec: secret_key.to_bech32().unwrap(), nsec: secret_key.to_bech32().unwrap(),
}; };
Ok(result) Ok(result)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn get_private_key(npub: &str) -> Result<String, String> { 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() { if let Ok(nsec) = keyring.get_password() {
let secret_key = SecretKey::from_bech32(nsec).unwrap(); let secret_key = SecretKey::from_bech32(nsec).unwrap();
Ok(secret_key.to_bech32().unwrap()) Ok(secret_key.to_bech32().unwrap())
} else { } else {
Err("Key not found".into()) Err("Key not found".into())
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn save_account( pub async fn save_account(
nsec: &str, nsec: &str,
password: &str, password: &str,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let secret_key = if nsec.starts_with("ncryptsec") { let secret_key = if nsec.starts_with("ncryptsec") {
let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap(); let encrypted_key = EncryptedSecretKey::from_bech32(nsec).unwrap();
encrypted_key encrypted_key
.to_secret_key(password) .to_secret_key(password)
.map_err(|err| err.to_string()) .map_err(|err| err.to_string())
} else { } else {
SecretKey::from_bech32(nsec).map_err(|err| err.to_string()) SecretKey::from_bech32(nsec).map_err(|err| err.to_string())
}; };
match secret_key { match secret_key {
Ok(val) => { Ok(val) => {
let nostr_keys = Keys::new(val); let nostr_keys = Keys::new(val);
let npub = nostr_keys.public_key().to_bech32().unwrap(); let npub = nostr_keys.public_key().to_bech32().unwrap();
let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap(); let nsec = nostr_keys.secret_key().unwrap().to_bech32().unwrap();
let keyring = Entry::new(&npub, "nostr_secret").unwrap(); let keyring = Entry::new(&npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&nsec); let _ = keyring.set_password(&nsec);
let signer = NostrSigner::Keys(nostr_keys); let signer = NostrSigner::Keys(nostr_keys);
let client = &state.client; let client = &state.client;
// Update client's signer // Update client's signer
client.set_signer(Some(signer)).await; client.set_signer(Some(signer)).await;
Ok(npub) Ok(npub)
}
Err(msg) => Err(msg),
} }
Err(msg) => Err(msg),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn connect_remote_account(uri: &str, state: State<'_, Nostr>) -> Result<String, String> { 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) { match NostrConnectURI::parse(uri) {
Ok(bunker_uri) => { Ok(bunker_uri) => {
let app_keys = Keys::generate(); let app_keys = Keys::generate();
let app_secret = app_keys.secret_key().unwrap().to_string(); let app_secret = app_keys.secret_key().unwrap().to_string();
// Get remote user // Get remote user
let remote_user = bunker_uri.signer_public_key().unwrap(); let remote_user = bunker_uri.signer_public_key().unwrap();
let remote_npub = remote_user.to_bech32().unwrap(); let remote_npub = remote_user.to_bech32().unwrap();
match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await { match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(120), None).await {
Ok(signer) => { Ok(signer) => {
let keyring = Entry::new(&remote_npub, "nostr_secret").unwrap(); let keyring = Entry::new(&remote_npub, "nostr_secret").unwrap();
let _ = keyring.set_password(&app_secret); let _ = keyring.set_password(&app_secret);
// Update signer // Update signer
let _ = client.set_signer(Some(signer.into())).await; 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()),
}
} }
Err(err) => Err(err.to_string()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_encrypted_key(npub: &str, password: &str) -> Result<String, String> { 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() { if let Ok(nsec) = keyring.get_password() {
let secret_key = SecretKey::from_bech32(nsec).unwrap(); let secret_key = SecretKey::from_bech32(nsec).unwrap();
let new_key = EncryptedSecretKey::new(&secret_key, password, 16, KeySecurity::Medium); let new_key = EncryptedSecretKey::new(&secret_key, password, 16, KeySecurity::Medium);
if let Ok(key) = new_key { if let Ok(key) = new_key {
Ok(key.to_bech32().unwrap()) Ok(key.to_bech32().unwrap())
} else {
Err("Encrypt key failed".into())
}
} else { } else {
Err("Encrypt key failed".into()) Err("Key not found".into())
} }
} else {
Err("Key not found".into())
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn load_account( pub async fn load_account(
npub: &str, npub: &str,
bunker: Option<&str>, bunker: Option<&str>,
state: State<'_, Nostr>, state: State<'_, Nostr>,
app: tauri::AppHandle, app: tauri::AppHandle,
) -> Result<bool, String> { ) -> Result<bool, String> {
let handle = app.clone(); 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 client = &state.client; 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 password = match keyring.get_password() {
let public_key = signer.public_key().await.unwrap(); Ok(pw) => pw,
Err(_) => return Err("Cancelled".into()),
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 match bunker {
.reconcile( Some(uri) => {
Filter::new() let app_keys =
.pubkey(public_key) Keys::parse(password).expect("Secret Key is modified, please check again.");
.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"); match NostrConnectURI::parse(uri) {
let subscription = Filter::new() Ok(bunker_uri) => {
.pubkey(public_key) match Nip46Signer::new(bunker_uri, app_keys, Duration::from_secs(30), None)
.kinds(vec![ .await
Kind::TextNote, {
Kind::Repost, Ok(signer) => client.set_signer(Some(signer.into())).await,
Kind::Reaction, Err(err) => return Err(err.to_string()),
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);
}
} }
Kind::Repost => { Err(err) => return Err(err.to_string()),
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) None => {
}) let keys = Keys::parse(password).expect("Secret Key is modified, please check again.");
.await 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)
} }

View File

@ -11,584 +11,587 @@ use super::get_latest_event;
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_current_profile(state: State<'_, Nostr>) -> Result<String, String> { 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 { let signer = match client.signer().await {
Ok(signer) => signer, Ok(signer) => signer,
Err(err) => return Err(format!("Failed to get signer: {}", err)), Err(err) => return Err(format!("Failed to get signer: {}", err)),
}; };
let public_key = match signer.public_key().await { let public_key = match signer.public_key().await {
Ok(pk) => pk, Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)), Err(err) => return Err(format!("Failed to get public key: {}", err)),
}; };
let filter = Filter::new() let filter = Filter::new()
.author(public_key) .author(public_key)
.kind(Kind::Metadata) .kind(Kind::Metadata)
.limit(1); .limit(1);
let events_result = client let events_result = client
.get_events_of(vec![filter], Some(Duration::from_secs(10))) .get_events_of(vec![filter], Some(Duration::from_secs(10)))
.await; .await;
match events_result { match events_result {
Ok(events) => { Ok(events) => {
if let Some(event) = get_latest_event(&events) { if let Some(event) = get_latest_event(&events) {
match Metadata::from_json(&event.content) { match Metadata::from_json(&event.content) {
Ok(metadata) => Ok(metadata.as_json()), Ok(metadata) => Ok(metadata.as_json()),
Err(_) => Err("Failed to parse metadata.".into()), Err(_) => Err("Failed to parse metadata.".into()),
}
} else {
Err("No matching events found.".into())
}
} }
} else { Err(err) => Err(format!("Failed to get events: {}", err)),
Err("No matching events found.".into())
}
} }
Err(err) => Err(format!("Failed to get events: {}", err)),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_profile(id: &str, state: State<'_, Nostr>) -> Result<String, String> { pub async fn get_profile(id: &str, state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client; let client = &state.client;
let public_key: Option<PublicKey> = match Nip19::from_bech32(id) { let public_key: Option<PublicKey> = match Nip19::from_bech32(id) {
Ok(val) => match val { Ok(val) => match val {
Nip19::Pubkey(key) => Some(key), Nip19::Pubkey(key) => Some(key),
Nip19::Profile(profile) => { Nip19::Profile(profile) => {
let relays = profile.relays; let relays = profile.relays;
for relay in relays.into_iter() { for relay in relays.into_iter() {
let _ = client.add_relay(&relay).await.unwrap_or_default(); let _ = client.add_relay(&relay).await.unwrap_or_default();
client.connect_relay(&relay).await.unwrap_or_default(); client.connect_relay(&relay).await.unwrap_or_default();
} }
Some(profile.public_key) Some(profile.public_key)
} }
_ => None, _ => None,
}, },
Err(_) => match PublicKey::from_str(id) { Err(_) => match PublicKey::from_str(id) {
Ok(val) => Some(val), Ok(val) => Some(val),
Err(_) => None, Err(_) => None,
}, },
}; };
if let Some(author) = public_key { if let Some(author) = public_key {
let filter = Filter::new().author(author).kind(Kind::Metadata).limit(1); let filter = Filter::new().author(author).kind(Kind::Metadata).limit(1);
let query = client let query = client
.get_events_of(vec![filter], Some(Duration::from_secs(10))) .get_events_of(vec![filter], Some(Duration::from_secs(10)))
.await; .await;
if let Ok(events) = query { if let Ok(events) = query {
if let Some(event) = events.first() { if let Some(event) = events.first() {
if let Ok(metadata) = Metadata::from_json(&event.content) { if let Ok(metadata) = Metadata::from_json(&event.content) {
Ok(metadata.as_json()) Ok(metadata.as_json())
} else {
Err("Parse metadata failed".into())
}
} else {
let rand_metadata = Metadata::new();
Ok(rand_metadata.as_json())
}
} else { } else {
Err("Parse metadata failed".into()) Err("Get metadata failed".into())
} }
} else {
let rand_metadata = Metadata::new();
Ok(rand_metadata.as_json())
}
} else { } else {
Err("Get metadata failed".into()) Err("Public Key is not valid".into())
} }
} else {
Err("Public Key is not valid".into())
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn set_contact_list( pub async fn set_contact_list(
public_keys: Vec<&str>, public_keys: Vec<&str>,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<bool, String> { ) -> Result<bool, String> {
let client = &state.client; let client = &state.client;
let contact_list: Vec<Contact> = public_keys let contact_list: Vec<Contact> = public_keys
.into_iter() .into_iter()
.filter_map(|p| match PublicKey::from_hex(p) { .filter_map(|p| match PublicKey::from_hex(p) {
Ok(pk) => Some(Contact::new(pk, None, Some(""))), Ok(pk) => Some(Contact::new(pk, None, Some(""))),
Err(_) => None, Err(_) => None,
}) })
.collect(); .collect();
match client.set_contact_list(contact_list).await { match client.set_contact_list(contact_list).await {
Ok(_) => Ok(true), Ok(_) => Ok(true),
Err(err) => Err(err.to_string()), Err(err) => Err(err.to_string()),
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_contact_list(state: State<'_, Nostr>) -> Result<Vec<String>, String> { 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 { match client.get_contact_list(Some(Duration::from_secs(10))).await {
Ok(contact_list) => { Ok(contact_list) => {
if !contact_list.is_empty() { if !contact_list.is_empty() {
let list = contact_list let list = contact_list
.into_iter() .into_iter()
.map(|f| f.public_key.to_hex()) .map(|f| f.public_key.to_hex())
.collect(); .collect();
Ok(list) Ok(list)
} else { } else {
Err("Empty.".into()) Err("Empty.".into())
} }
}
Err(err) => Err(err.to_string()),
} }
Err(err) => Err(err.to_string()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn create_profile( pub async fn create_profile(
name: &str, name: &str,
display_name: &str, display_name: &str,
about: &str, about: &str,
picture: &str, picture: &str,
banner: &str, banner: &str,
nip05: &str, nip05: &str,
lud16: &str, lud16: &str,
website: &str, website: &str,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let client = &state.client; let client = &state.client;
let mut metadata = Metadata::new() let mut metadata = Metadata::new()
.name(name) .name(name)
.display_name(display_name) .display_name(display_name)
.about(about) .about(about)
.nip05(nip05) .nip05(nip05)
.lud16(lud16); .lud16(lud16);
if let Ok(url) = Url::parse(picture) { if let Ok(url) = Url::parse(picture) {
metadata = metadata.picture(url) metadata = metadata.picture(url)
} }
if let Ok(url) = Url::parse(banner) { if let Ok(url) = Url::parse(banner) {
metadata = metadata.banner(url) metadata = metadata.banner(url)
} }
if let Ok(url) = Url::parse(website) { if let Ok(url) = Url::parse(website) {
metadata = metadata.website(url) metadata = metadata.website(url)
} }
if let Ok(event_id) = client.set_metadata(&metadata).await { if let Ok(event_id) = client.set_metadata(&metadata).await {
Ok(event_id.to_string()) Ok(event_id.to_string())
} else { } else {
Err("Create profile failed".into()) Err("Create profile failed".into())
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn is_contact_list_empty(state: State<'_, Nostr>) -> Result<bool, ()> { pub async fn is_contact_list_empty(state: State<'_, Nostr>) -> Result<bool, ()> {
let contact_list = state.contact_list.lock().unwrap(); let contact_list = state.contact_list.lock().unwrap();
Ok(contact_list.is_empty()) Ok(contact_list.is_empty())
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn check_contact(hex: &str, state: State<'_, Nostr>) -> Result<bool, String> { 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) { match PublicKey::from_str(hex) {
Ok(public_key) => match contact_list.iter().position(|x| x.public_key == public_key) { Ok(public_key) => match contact_list.iter().position(|x| x.public_key == public_key) {
Some(_) => Ok(true), Some(_) => Ok(true),
None => Ok(false), None => Ok(false),
}, },
Err(err) => Err(err.to_string()), Err(err) => Err(err.to_string()),
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn toggle_contact( pub async fn toggle_contact(
hex: &str, hex: &str,
alias: Option<&str>, alias: Option<&str>,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let client = &state.client; let client = &state.client;
match client.get_contact_list(None).await { match client.get_contact_list(None).await {
Ok(mut contact_list) => { Ok(mut contact_list) => {
let public_key = PublicKey::from_str(hex).unwrap(); let public_key = PublicKey::from_str(hex).unwrap();
match contact_list.iter().position(|x| x.public_key == public_key) { match contact_list.iter().position(|x| x.public_key == public_key) {
Some(index) => { Some(index) => {
// Remove contact // Remove contact
contact_list.remove(index); 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()),
}
} }
Err(err) => Err(err.to_string()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn set_nstore( pub async fn set_nstore(
key: &str, key: &str,
content: &str, content: &str,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<String, String> { ) -> Result<String, String> {
let client = &state.client; let client = &state.client;
match client.signer().await { match client.signer().await {
Ok(signer) => { Ok(signer) => {
let public_key = match signer.public_key().await { let public_key = match signer.public_key().await {
Ok(pk) => pk, Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)), Err(err) => return Err(format!("Failed to get public key: {}", err)),
}; };
let encrypted = match signer.nip44_encrypt(public_key, content).await { let encrypted = match signer.nip44_encrypt(public_key, content).await {
Ok(enc) => enc, Ok(enc) => enc,
Err(err) => return Err(format!("Encryption failed: {}", err)), Err(err) => return Err(format!("Encryption failed: {}", err)),
}; };
let tag = Tag::identifier(key); let tag = Tag::identifier(key);
let builder = EventBuilder::new(Kind::ApplicationSpecificData, encrypted, vec![tag]); let builder = EventBuilder::new(Kind::ApplicationSpecificData, encrypted, vec![tag]);
match client.send_event_builder(builder).await { match client.send_event_builder(builder).await {
Ok(event_id) => Ok(event_id.to_string()), 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()),
}
} }
Err(err) => Err(err.to_string()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_nstore(key: &str, state: State<'_, Nostr>) -> Result<String, String> { 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 { if let Ok(signer) = client.signer().await {
let public_key = match signer.public_key().await { let public_key = match signer.public_key().await {
Ok(pk) => pk, Ok(pk) => pk,
Err(err) => return Err(format!("Failed to get public key: {}", err)), Err(err) => return Err(format!("Failed to get public key: {}", err)),
}; };
let filter = Filter::new() let filter = Filter::new()
.author(public_key) .author(public_key)
.kind(Kind::ApplicationSpecificData) .kind(Kind::ApplicationSpecificData)
.identifier(key) .identifier(key)
.limit(1); .limit(1);
match client match client
.get_events_of(vec![filter], Some(Duration::from_secs(5))) .get_events_of(vec![filter], Some(Duration::from_secs(5)))
.await .await
{ {
Ok(events) => { Ok(events) => {
if let Some(event) = events.first() { if let Some(event) = events.first() {
let content = event.content(); let content = event.content();
match signer.nip44_decrypt(public_key, content).await { match signer.nip44_decrypt(public_key, content).await {
Ok(decrypted) => Ok(decrypted), Ok(decrypted) => Ok(decrypted),
Err(_) => Err(event.content.to_string()), Err(_) => Err(event.content.to_string()),
} }
} else { } else {
Err("Value not found".into()) Err("Value not found".into())
}
}
Err(err) => Err(err.to_string()),
} }
} } else {
Err(err) => Err(err.to_string()), Err("Signer is required".into())
} }
} else {
Err("Signer is required".into())
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn set_wallet(uri: &str, state: State<'_, Nostr>) -> Result<bool, String> { 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) { if let Ok(nwc_uri) = NostrWalletConnectURI::from_str(uri) {
let nwc = NWC::new(nwc_uri); let nwc = NWC::new(nwc_uri);
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").map_err(|e| e.to_string())?; let keyring = Entry::new("Lume Secret", "Bitcoin Connect").map_err(|e| e.to_string())?;
keyring.set_password(uri).map_err(|e| e.to_string())?; keyring.set_password(uri).map_err(|e| e.to_string())?;
client.set_zapper(nwc).await; client.set_zapper(nwc).await;
Ok(true) Ok(true)
} else { } else {
Err("Set NWC failed".into()) Err("Set NWC failed".into())
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn load_wallet(state: State<'_, Nostr>) -> Result<String, String> { pub async fn load_wallet(state: State<'_, Nostr>) -> Result<String, String> {
let client = &state.client; let client = &state.client;
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap(); let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap();
match keyring.get_password() { match keyring.get_password() {
Ok(val) => { Ok(val) => {
let uri = NostrWalletConnectURI::from_str(&val).unwrap(); let uri = NostrWalletConnectURI::from_str(&val).unwrap();
let nwc = NWC::new(uri); let nwc = NWC::new(uri);
// Get current balance // Get current balance
let balance = nwc.get_balance().await; let balance = nwc.get_balance().await;
// Update zapper // Update zapper
client.set_zapper(nwc).await; client.set_zapper(nwc).await;
match balance { match balance {
Ok(val) => Ok(val.to_string()), Ok(val) => Ok(val.to_string()),
Err(_) => Err("Get balance failed.".into()), Err(_) => Err("Get balance failed.".into()),
} }
}
Err(_) => Err("NWC not found.".into()),
} }
Err(_) => Err("NWC not found.".into()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn remove_wallet(state: State<'_, Nostr>) -> Result<(), ()> { pub async fn remove_wallet(state: State<'_, Nostr>) -> Result<(), ()> {
let client = &state.client; let client = &state.client;
let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap(); let keyring = Entry::new("Lume Secret", "Bitcoin Connect").unwrap();
match keyring.delete_password() { match keyring.delete_password() {
Ok(_) => { Ok(_) => {
client.unset_zapper().await; client.unset_zapper().await;
Ok(()) Ok(())
}
Err(_) => Err(()),
} }
Err(_) => Err(()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn zap_profile( pub async fn zap_profile(
id: &str, id: &str,
amount: &str, amount: &str,
message: &str, message: &str,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<bool, String> { ) -> Result<bool, String> {
let client = &state.client; let client = &state.client;
let public_key = match Nip19::from_bech32(id) { let public_key = match Nip19::from_bech32(id) {
Ok(val) => match val { Ok(val) => match val {
Nip19::Pubkey(key) => key, Nip19::Pubkey(key) => key,
Nip19::Profile(profile) => profile.public_key, Nip19::Profile(profile) => profile.public_key,
_ => return Err("Public Key is not valid.".into()), _ => return Err("Public Key is not valid.".into()),
}, },
Err(_) => match PublicKey::from_str(id) { Err(_) => match PublicKey::from_str(id) {
Ok(val) => val, Ok(val) => val,
Err(_) => return Err("Public Key is not valid.".into()), Err(_) => return Err("Public Key is not valid.".into()),
}, },
}; };
let details = ZapDetails::new(ZapType::Private).message(message); let details = ZapDetails::new(ZapType::Private).message(message);
let num = match amount.parse::<u64>() { let num = match amount.parse::<u64>() {
Ok(val) => val, Ok(val) => val,
Err(_) => return Err("Invalid amount.".into()), Err(_) => return Err("Invalid amount.".into()),
}; };
if client.zap(public_key, num, Some(details)).await.is_ok() { if client.zap(public_key, num, Some(details)).await.is_ok() {
Ok(true) Ok(true)
} else { } else {
Err("Zap profile failed".into()) Err("Zap profile failed".into())
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn zap_event( pub async fn zap_event(
id: &str, id: &str,
amount: &str, amount: &str,
message: &str, message: &str,
state: State<'_, Nostr>, state: State<'_, Nostr>,
) -> Result<bool, String> { ) -> Result<bool, String> {
let client = &state.client; let client = &state.client;
let event_id = match Nip19::from_bech32(id) { let event_id = match Nip19::from_bech32(id) {
Ok(val) => match val { Ok(val) => match val {
Nip19::EventId(id) => id, Nip19::EventId(id) => id,
Nip19::Event(event) => event.event_id, Nip19::Event(event) => event.event_id,
_ => return Err("Event ID is invalid.".into()), _ => return Err("Event ID is invalid.".into()),
}, },
Err(_) => match EventId::from_hex(id) { Err(_) => match EventId::from_hex(id) {
Ok(val) => val, Ok(val) => val,
Err(_) => return Err("Event ID is invalid.".into()), Err(_) => return Err("Event ID is invalid.".into()),
}, },
}; };
let details = ZapDetails::new(ZapType::Private).message(message); let details = ZapDetails::new(ZapType::Private).message(message);
let num = match amount.parse::<u64>() { let num = match amount.parse::<u64>() {
Ok(val) => val, Ok(val) => val,
Err(_) => return Err("Invalid amount.".into()), Err(_) => return Err("Invalid amount.".into()),
}; };
if client.zap(event_id, num, Some(details)).await.is_ok() { if client.zap(event_id, num, Some(details)).await.is_ok() {
Ok(true) Ok(true)
} else { } else {
Err("Zap event failed".into()) Err("Zap event failed".into())
} }
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn friend_to_friend(npub: &str, state: State<'_, Nostr>) -> Result<bool, String> { 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) { match PublicKey::from_bech32(npub) {
Ok(author) => { Ok(author) => {
let mut contact_list: Vec<Contact> = Vec::new(); let mut contact_list: Vec<Contact> = Vec::new();
let contact_list_filter = Filter::new() let contact_list_filter = Filter::new()
.author(author) .author(author)
.kind(Kind::ContactList) .kind(Kind::ContactList)
.limit(1); .limit(1);
if let Ok(contact_list_events) = client.get_events_of(vec![contact_list_filter], None).await { if let Ok(contact_list_events) =
for event in contact_list_events.into_iter() { client.get_events_of(vec![contact_list_filter], None).await
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)) 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 { match client.set_contact_list(contact_list).await {
Ok(_) => Ok(true), Ok(_) => Ok(true),
Err(err) => Err(err.to_string()),
}
}
Err(err) => Err(err.to_string()), Err(err) => Err(err.to_string()),
}
} }
Err(err) => Err(err.to_string()),
}
} }
pub async fn get_following( pub async fn get_following(
state: State<'_, Nostr>, state: State<'_, Nostr>,
public_key: &str, public_key: &str,
timeout: Option<u64>, timeout: Option<u64>,
) -> Result<Vec<String>, String> { ) -> Result<Vec<String>, String> {
let client = &state.client; let client = &state.client;
let public_key = match PublicKey::from_str(public_key) { let public_key = match PublicKey::from_str(public_key) {
Ok(val) => val, Ok(val) => val,
Err(err) => return Err(err.to_string()), Err(err) => return Err(err.to_string()),
}; };
let duration = timeout.map(Duration::from_secs); let duration = timeout.map(Duration::from_secs);
let filter = Filter::new().kind(Kind::ContactList).author(public_key); let filter = Filter::new().kind(Kind::ContactList).author(public_key);
let events = match client.get_events_of(vec![filter], duration).await { let events = match client.get_events_of(vec![filter], duration).await {
Ok(events) => events, Ok(events) => events,
Err(err) => return Err(err.to_string()), Err(err) => return Err(err.to_string()),
}; };
let mut ret: Vec<String> = vec![]; let mut ret: Vec<String> = vec![];
if let Some(latest_event) = events.iter().max_by_key(|event| event.created_at()) { if let Some(latest_event) = events.iter().max_by_key(|event| event.created_at()) {
ret.extend(latest_event.tags().iter().filter_map(|tag| { ret.extend(latest_event.tags().iter().filter_map(|tag| {
if let Some(TagStandard::PublicKey { if let Some(TagStandard::PublicKey {
uppercase: false, .. uppercase: false, ..
}) = <nostr_sdk::Tag as Clone>::clone(tag).to_standardized() }) = <nostr_sdk::Tag as Clone>::clone(tag).to_standardized()
{ {
tag.content().map(String::from) tag.content().map(String::from)
} else { } else {
None None
} }
})); }));
} }
Ok(ret) Ok(ret)
} }
pub async fn get_followers( pub async fn get_followers(
state: State<'_, Nostr>, state: State<'_, Nostr>,
public_key: &str, public_key: &str,
timeout: Option<u64>, timeout: Option<u64>,
) -> Result<Vec<String>, String> { ) -> Result<Vec<String>, String> {
let client = &state.client; let client = &state.client;
let public_key = match PublicKey::from_str(public_key) { let public_key = match PublicKey::from_str(public_key) {
Ok(val) => val, Ok(val) => val,
Err(err) => return Err(err.to_string()), Err(err) => return Err(err.to_string()),
}; };
let duration = timeout.map(Duration::from_secs); let duration = timeout.map(Duration::from_secs);
let filter = Filter::new().kind(Kind::ContactList).custom_tag( let filter = Filter::new().kind(Kind::ContactList).custom_tag(
SingleLetterTag::lowercase(Alphabet::P), SingleLetterTag::lowercase(Alphabet::P),
vec![public_key.to_hex()], vec![public_key.to_hex()],
); );
let events = match client.get_events_of(vec![filter], duration).await { let events = match client.get_events_of(vec![filter], duration).await {
Ok(events) => events, Ok(events) => events,
Err(err) => return Err(err.to_string()), Err(err) => return Err(err.to_string()),
}; };
let ret: Vec<String> = events let ret: Vec<String> = events
.into_iter() .into_iter()
.map(|event| event.author().to_hex()) .map(|event| event.author().to_hex())
.collect(); .collect();
Ok(ret) Ok(ret)
// TODO: get more than 500 events // TODO: get more than 500 events
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_notifications(state: State<'_, Nostr>) -> Result<Vec<String>, String> { pub async fn get_notifications(state: State<'_, Nostr>) -> Result<Vec<String>, String> {
let client = &state.client; let client = &state.client;
match client.signer().await { match client.signer().await {
Ok(signer) => { Ok(signer) => {
let public_key = signer.public_key().await.unwrap(); let public_key = signer.public_key().await.unwrap();
let filter = Filter::new() let filter = Filter::new()
.pubkey(public_key) .pubkey(public_key)
.kinds(vec![ .kinds(vec![
Kind::TextNote, Kind::TextNote,
Kind::Repost, Kind::Repost,
Kind::Reaction, Kind::Reaction,
Kind::ZapReceipt, Kind::ZapReceipt,
]) ])
.limit(200); .limit(200);
match client match client
.database() .database()
.query(vec![filter], Order::default()) .query(vec![filter], Order::default())
.await .await
{ {
Ok(events) => Ok(events.into_iter().map(|ev| ev.as_json()).collect()), 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()),
}
} }
Err(err) => Err(err.to_string()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_settings(state: State<'_, Nostr>) -> Result<Settings, ()> { pub async fn get_settings(state: State<'_, Nostr>) -> Result<Settings, ()> {
let settings = state.settings.lock().unwrap().clone(); let settings = state.settings.lock().unwrap().clone();
Ok(settings) Ok(settings)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn set_new_settings(settings: &str, state: State<'_, Nostr>) -> Result<(), ()> { 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"); let parsed: Settings =
*state.settings.lock().unwrap() = parsed; serde_json::from_str(settings).expect("Could not parse settings payload");
*state.settings.lock().unwrap() = parsed;
Ok(()) Ok(())
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn verify_nip05(key: &str, nip05: &str) -> Result<bool, String> { pub async fn verify_nip05(key: &str, nip05: &str) -> Result<bool, String> {
match PublicKey::from_str(key) { match PublicKey::from_str(key) {
Ok(public_key) => { Ok(public_key) => {
let status = nip05::verify(&public_key, nip05, None).await; let status = nip05::verify(&public_key, nip05, None).await;
Ok(status.is_ok()) Ok(status.is_ok())
}
Err(err) => Err(err.to_string()),
} }
Err(err) => Err(err.to_string()),
}
} }

View File

@ -3,155 +3,155 @@ use nostr_sdk::prelude::*;
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
use std::{ use std::{
fs::OpenOptions, fs::OpenOptions,
io::{self, BufRead, Write}, io::{self, BufRead, Write},
}; };
use tauri::{path::BaseDirectory, Manager, State}; use tauri::{path::BaseDirectory, Manager, State};
#[derive(Serialize, Type)] #[derive(Serialize, Type)]
pub struct Relays { pub struct Relays {
connected: Vec<String>, connected: Vec<String>,
read: Option<Vec<String>>, read: Option<Vec<String>>,
write: Option<Vec<String>>, write: Option<Vec<String>>,
both: Option<Vec<String>>, both: Option<Vec<String>>,
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_relays(state: State<'_, Nostr>) -> Result<Relays, String> { pub async fn get_relays(state: State<'_, Nostr>) -> Result<Relays, String> {
let client = &state.client; let client = &state.client;
let connected_relays = client let connected_relays = client
.relays() .relays()
.await .await
.into_keys() .into_keys()
.map(|url| url.to_string()) .map(|url| url.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let signer = client.signer().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 public_key = signer.public_key().await.map_err(|e| e.to_string())?;
let filter = Filter::new() let filter = Filter::new()
.author(public_key) .author(public_key)
.kind(Kind::RelayList) .kind(Kind::RelayList)
.limit(1); .limit(1);
match client.get_events_of(vec![filter], None).await { match client.get_events_of(vec![filter], None).await {
Ok(events) => { Ok(events) => {
if let Some(event) = events.first() { if let Some(event) = events.first() {
let nip65_list = nip65::extract_relay_list(event).collect::<Vec<_>>(); let nip65_list = nip65::extract_relay_list(event).collect::<Vec<_>>();
let read = nip65_list let read = nip65_list
.iter() .iter()
.filter_map(|(url, meta)| { .filter_map(|(url, meta)| {
if let Some(RelayMetadata::Read) = meta { if let Some(RelayMetadata::Read) = meta {
Some(url.to_string()) 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 { } else {
None Ok(Relays {
connected: connected_relays,
read: None,
write: None,
both: None,
})
} }
}) }
.collect(); Err(e) => Err(e.to_string()),
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()),
}
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn connect_relay(relay: &str, state: State<'_, Nostr>) -> Result<bool, String> { pub async fn connect_relay(relay: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let client = &state.client; let client = &state.client;
let status = client.add_relay(relay).await.map_err(|e| e.to_string())?; let status = client.add_relay(relay).await.map_err(|e| e.to_string())?;
if status { if status {
println!("Connecting to relay: {}", relay); println!("Connecting to relay: {}", relay);
client client
.connect_relay(relay) .connect_relay(relay)
.await .await
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
} }
Ok(status) Ok(status)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn remove_relay(relay: &str, state: State<'_, Nostr>) -> Result<bool, String> { pub async fn remove_relay(relay: &str, state: State<'_, Nostr>) -> Result<bool, String> {
let client = &state.client; let client = &state.client;
client client
.remove_relay(relay) .remove_relay(relay)
.await .await
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
client client
.disconnect_relay(relay) .disconnect_relay(relay)
.await .await
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
Ok(true) Ok(true)
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn get_bootstrap_relays(app: tauri::AppHandle) -> Result<Vec<String>, String> { pub fn get_bootstrap_relays(app: tauri::AppHandle) -> Result<Vec<String>, String> {
let relays_path = app let relays_path = app
.path() .path()
.resolve("resources/relays.txt", BaseDirectory::Resource) .resolve("resources/relays.txt", BaseDirectory::Resource)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let file = std::fs::File::open(relays_path).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 reader = io::BufReader::new(file);
reader reader
.lines() .lines()
.collect::<Result<Vec<String>, io::Error>>() .collect::<Result<Vec<String>, io::Error>>()
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn save_bootstrap_relays(relays: &str, app: tauri::AppHandle) -> Result<(), String> { pub fn save_bootstrap_relays(relays: &str, app: tauri::AppHandle) -> Result<(), String> {
let relays_path = app let relays_path = app
.path() .path()
.resolve("resources/relays.txt", BaseDirectory::Resource) .resolve("resources/relays.txt", BaseDirectory::Resource)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let mut file = OpenOptions::new() let mut file = OpenOptions::new()
.write(true) .write(true)
.open(relays_path) .open(relays_path)
.map_err(|e| e.to_string())?; .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())
} }

View File

@ -11,255 +11,255 @@ use url::Url;
#[derive(Debug, Clone, Serialize, Type)] #[derive(Debug, Clone, Serialize, Type)]
pub struct Meta { pub struct Meta {
pub content: String, pub content: String,
pub images: Vec<String>, pub images: Vec<String>,
pub videos: Vec<String>, pub videos: Vec<String>,
pub events: Vec<String>, pub events: Vec<String>,
pub mentions: Vec<String>, pub mentions: Vec<String>,
pub hashtags: Vec<String>, pub hashtags: Vec<String>,
} }
const NOSTR_EVENTS: [&str; 10] = [ const NOSTR_EVENTS: [&str; 10] = [
"@nevent1", "@nevent1",
"@note1", "@note1",
"@nostr:note1", "@nostr:note1",
"@nostr:nevent1", "@nostr:nevent1",
"nostr:note1", "nostr:note1",
"note1", "note1",
"nostr:nevent1", "nostr:nevent1",
"nevent1", "nevent1",
"Nostr:note1", "Nostr:note1",
"Nostr:nevent1", "Nostr:nevent1",
]; ];
const NOSTR_MENTIONS: [&str; 10] = [ const NOSTR_MENTIONS: [&str; 10] = [
"@npub1", "@npub1",
"nostr:npub1", "nostr:npub1",
"nostr:nprofile1", "nostr:nprofile1",
"nostr:naddr1", "nostr:naddr1",
"npub1", "npub1",
"nprofile1", "nprofile1",
"naddr1", "naddr1",
"Nostr:npub1", "Nostr:npub1",
"Nostr:nprofile1", "Nostr:nprofile1",
"Nostr:naddr1", "Nostr:naddr1",
]; ];
const IMAGES: [&str; 7] = ["jpg", "jpeg", "gif", "png", "webp", "avif", "tiff"]; const IMAGES: [&str; 7] = ["jpg", "jpeg", "gif", "png", "webp", "avif", "tiff"];
const VIDEOS: [&str; 5] = ["mp4", "mov", "avi", "webm", "mkv"]; const VIDEOS: [&str; 5] = ["mp4", "mov", "avi", "webm", "mkv"];
pub fn get_latest_event(events: &[Event]) -> Option<&Event> { pub fn get_latest_event(events: &[Event]) -> Option<&Event> {
events.iter().next() events.iter().next()
} }
pub fn dedup_event(events: &[Event]) -> Vec<Event> { pub fn dedup_event(events: &[Event]) -> Vec<Event> {
let mut seen_ids = HashSet::new(); let mut seen_ids = HashSet::new();
events events
.iter() .iter()
.filter(|&event| { .filter(|&event| {
let e = TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::E)); let e = TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::E));
let e_tags: Vec<&Tag> = event.tags.iter().filter(|el| el.kind() == e).collect(); 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 ids: Vec<&str> = e_tags.iter().filter_map(|tag| tag.content()).collect();
let is_dup = ids.iter().any(|id| seen_ids.contains(*id)); let is_dup = ids.iter().any(|id| seen_ids.contains(*id));
for id in &ids { for id in &ids {
seen_ids.insert(*id); seen_ids.insert(*id);
} }
!is_dup !is_dup
}) })
.cloned() .cloned()
.collect() .collect()
} }
pub async fn parse_event(content: &str) -> Meta { pub async fn parse_event(content: &str) -> Meta {
let mut finder = LinkFinder::new(); let mut finder = LinkFinder::new();
finder.url_must_have_scheme(false); finder.url_must_have_scheme(false);
// Get urls // Get urls
let urls: Vec<_> = finder.links(content).collect(); let urls: Vec<_> = finder.links(content).collect();
// Get words // Get words
let words: Vec<_> = content.split_whitespace().collect(); let words: Vec<_> = content.split_whitespace().collect();
let hashtags = words let hashtags = words
.iter() .iter()
.filter(|&&word| word.starts_with('#')) .filter(|&&word| word.starts_with('#'))
.map(|&s| s.to_string()) .map(|&s| s.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let events = words let events = words
.iter() .iter()
.filter(|&&word| NOSTR_EVENTS.iter().any(|&el| word.starts_with(el))) .filter(|&&word| NOSTR_EVENTS.iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string()) .map(|&s| s.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mentions = words let mentions = words
.iter() .iter()
.filter(|&&word| NOSTR_MENTIONS.iter().any(|&el| word.starts_with(el))) .filter(|&&word| NOSTR_MENTIONS.iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string()) .map(|&s| s.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut images = Vec::new(); let mut images = Vec::new();
let mut videos = Vec::new(); let mut videos = Vec::new();
let mut text = content.to_string(); let mut text = content.to_string();
if !urls.is_empty() { if !urls.is_empty() {
let client = Client::new(); let client = Client::new();
for url in urls { for url in urls {
let url_str = url.as_str(); let url_str = url.as_str();
if let Ok(parsed_url) = Url::from_str(url_str) { if let Ok(parsed_url) = Url::from_str(url_str) {
if let Some(ext) = parsed_url if let Some(ext) = parsed_url
.path_segments() .path_segments()
.and_then(|segments| segments.last().and_then(|s| s.split('.').last())) .and_then(|segments| segments.last().and_then(|s| s.split('.').last()))
{ {
if IMAGES.contains(&ext) { if IMAGES.contains(&ext) {
text = text.replace(url_str, ""); text = text.replace(url_str, "");
images.push(url_str.to_string()); images.push(url_str.to_string());
// Process the next item. // Process the next item.
continue; continue;
} }
if VIDEOS.contains(&ext) { if VIDEOS.contains(&ext) {
text = text.replace(url_str, ""); text = text.replace(url_str, "");
videos.push(url_str.to_string()); videos.push(url_str.to_string());
// Process the next item. // Process the next item.
continue; continue;
} }
} }
// Check the content type of URL via HEAD request // Check the content type of URL via HEAD request
if let Ok(res) = client.head(url_str).send().await { if let Ok(res) = client.head(url_str).send().await {
if let Some(content_type) = res.headers().get("Content-Type") { if let Some(content_type) = res.headers().get("Content-Type") {
if content_type.to_str().unwrap_or("").starts_with("image") { if content_type.to_str().unwrap_or("").starts_with("image") {
text = text.replace(url_str, ""); text = text.replace(url_str, "");
images.push(url_str.to_string()); images.push(url_str.to_string());
// Process the next item. // Process the next item.
continue; continue;
}
}
}
} }
}
} }
}
} }
}
// Clean up the resulting content string to remove extra spaces // Clean up the resulting content string to remove extra spaces
let cleaned_text = text.trim().to_string(); let cleaned_text = text.trim().to_string();
Meta { Meta {
content: cleaned_text, content: cleaned_text,
events, events,
mentions, mentions,
hashtags, hashtags,
images, images,
videos, videos,
} }
} }
pub fn create_event_tags(content: &str) -> Vec<Tag> { pub fn create_event_tags(content: &str) -> Vec<Tag> {
let mut tags: Vec<Tag> = vec![]; let mut tags: Vec<Tag> = vec![];
let mut tag_set: HashSet<String> = HashSet::new(); let mut tag_set: HashSet<String> = HashSet::new();
// Get words // Get words
let words: Vec<_> = content.split_whitespace().collect(); let words: Vec<_> = content.split_whitespace().collect();
// Get mentions // Get mentions
let mentions = words let mentions = words
.iter() .iter()
.filter(|&&word| ["nostr:", "@"].iter().any(|&el| word.starts_with(el))) .filter(|&&word| ["nostr:", "@"].iter().any(|&el| word.starts_with(el)))
.map(|&s| s.to_string()) .map(|&s| s.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Get hashtags // Get hashtags
let hashtags = words let hashtags = words
.iter() .iter()
.filter(|&&word| word.starts_with('#')) .filter(|&&word| word.starts_with('#'))
.map(|&s| s.to_string()) .map(|&s| s.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for mention in mentions { for mention in mentions {
let entity = mention.replace("nostr:", "").replace('@', ""); let entity = mention.replace("nostr:", "").replace('@', "");
if !tag_set.contains(&entity) { if !tag_set.contains(&entity) {
if entity.starts_with("npub") { if entity.starts_with("npub") {
if let Ok(public_key) = PublicKey::from_bech32(&entity) { if let Ok(public_key) = PublicKey::from_bech32(&entity) {
let tag = Tag::public_key(public_key); let tag = Tag::public_key(public_key);
tags.push(tag); tags.push(tag);
} else { } else {
continue; 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 { for hashtag in hashtags {
let tag = Tag::public_key(author); if !tag_set.contains(&hashtag) {
let tag = Tag::hashtag(hashtag.clone());
tags.push(tag); tags.push(tag);
} tag_set.insert(hashtag);
tags.push(tag);
} else {
continue;
} }
}
tag_set.insert(entity);
} }
}
for hashtag in hashtags { tags
if !tag_set.contains(&hashtag) {
let tag = Tag::hashtag(hashtag.clone());
tags.push(tag);
tag_set.insert(hashtag);
}
}
tags
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[tokio::test] #[tokio::test]
async fn test_parse_event() { async fn test_parse_event() {
let content = "Check this image: https://example.com/image.jpg #cool @npub1"; let content = "Check this image: https://example.com/image.jpg #cool @npub1";
let meta = parse_event(content).await; let meta = parse_event(content).await;
assert_eq!(meta.content, "Check this image: #cool @npub1"); assert_eq!(meta.content, "Check this image: #cool @npub1");
assert_eq!(meta.images, vec!["https://example.com/image.jpg"]); assert_eq!(meta.images, vec!["https://example.com/image.jpg"]);
assert_eq!(meta.videos, Vec::<String>::new()); assert_eq!(meta.videos, Vec::<String>::new());
assert_eq!(meta.hashtags, vec!["#cool"]); assert_eq!(meta.hashtags, vec!["#cool"]);
assert_eq!(meta.mentions, vec!["@npub1"]); assert_eq!(meta.mentions, vec!["@npub1"]);
} }
#[tokio::test] #[tokio::test]
async fn test_parse_video() { async fn test_parse_video() {
let content = "Check this video: https://example.com/video.mp4 #cool @npub1"; let content = "Check this video: https://example.com/video.mp4 #cool @npub1";
let meta = parse_event(content).await; let meta = parse_event(content).await;
assert_eq!(meta.content, "Check this video: #cool @npub1"); assert_eq!(meta.content, "Check this video: #cool @npub1");
assert_eq!(meta.images, Vec::<String>::new()); assert_eq!(meta.images, Vec::<String>::new());
assert_eq!(meta.videos, vec!["https://example.com/video.mp4"]); assert_eq!(meta.videos, vec!["https://example.com/video.mp4"]);
assert_eq!(meta.hashtags, vec!["#cool"]); assert_eq!(meta.hashtags, vec!["#cool"]);
assert_eq!(meta.mentions, vec!["@npub1"]); assert_eq!(meta.mentions, vec!["@npub1"]);
} }
} }

View File

@ -5,7 +5,6 @@
{ {
"title": "Lume", "title": "Lume",
"label": "main", "label": "main",
"titleBarStyle": "Overlay",
"width": 1045, "width": 1045,
"height": 800, "height": 800,
"minWidth": 480, "minWidth": 480,

View File

@ -1,12 +1,6 @@
{ {
"$schema": "../node_modules/@tauri-apps/cli/schema.json", "$schema": "../node_modules/@tauri-apps/cli/schema.json",
"app": { "app": {
"trayIcon": {
"id": "main",
"iconPath": "./icons/tray.png",
"iconAsTemplate": true,
"menuOnLeftClick": false
},
"windows": [ "windows": [
{ {
"title": "Lume", "title": "Lume",