This commit is contained in:
2024-10-26 09:08:50 +07:00
parent 5ab2b1ae31
commit 42b780ce6a
26 changed files with 458 additions and 493 deletions

View File

@@ -31,7 +31,28 @@ pub async fn get_event(id: String, state: State<'_, Nostr>) -> Result<RichEvent,
Ok(RichEvent { raw, parsed })
} else {
Err("Event not found".to_string())
match client
.fetch_events(
vec![Filter::new().id(event_id)],
Some(Duration::from_secs(5)),
)
.await
{
Ok(events) => {
if let Some(event) = events.iter().next() {
let raw = event.as_json();
let parsed = if event.kind == Kind::TextNote {
Some(parse_event(&event.content).await)
} else {
None
};
Ok(RichEvent { raw, parsed })
} else {
Err("Event not found.".into())
}
}
Err(err) => Err(err.to_string()),
}
}
}
Err(err) => Err(err.to_string()),
@@ -49,13 +70,16 @@ pub async fn get_meta_from_event(content: String) -> Result<Meta, ()> {
pub async fn get_replies(id: String, state: State<'_, Nostr>) -> Result<Vec<RichEvent>, String> {
let client = &state.client;
let event_id = EventId::parse(&id).map_err(|err| err.to_string())?;
let filter = Filter::new().kinds(vec![Kind::TextNote]).event(event_id);
let filter = Filter::new()
.kinds(vec![Kind::TextNote, Kind::Custom(1111)])
.event(event_id);
match client
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, true).await),
Err(err) => Err(err.to_string()),
}
}
@@ -98,7 +122,7 @@ pub async fn get_all_events_by_author(
.limit(limit as usize);
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
}
@@ -129,7 +153,7 @@ pub async fn get_all_events_by_authors(
.authors(authors);
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
}
@@ -158,7 +182,7 @@ pub async fn get_all_events_by_hashtags(
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
}
@@ -182,7 +206,7 @@ pub async fn get_local_events(
.until(as_of);
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
}
@@ -205,11 +229,8 @@ pub async fn get_global_events(
.limit(FETCH_LIMIT)
.until(as_of);
match client
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => Ok(process_event(client, events).await),
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
}
@@ -334,7 +355,13 @@ pub async fn is_reposted(id: String, state: State<'_, Nostr>) -> Result<bool, St
let authors: Vec<PublicKey> = accounts
.iter()
.map(|acc| PublicKey::from_str(acc).unwrap())
.filter_map(|acc| {
if let Ok(pk) = PublicKey::from_str(acc) {
Some(pk)
} else {
None
}
})
.collect();
let filter = Filter::new()
@@ -452,7 +479,7 @@ pub async fn search(query: String, state: State<'_, Nostr>) -> Result<Vec<RichEv
let filter = Filter::new().search(query);
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()),
}
}

View File

@@ -36,8 +36,34 @@ pub async fn get_profile(id: String, state: State<'_, Nostr>) -> Result<String,
let client = &state.client;
let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?;
match client.database().profile(public_key).await {
Ok(profile) => Ok(profile.metadata().as_json()),
let filter = Filter::new()
.author(public_key)
.kind(Kind::Metadata)
.limit(1);
match client.database().query(vec![filter.clone()]).await {
Ok(events) => {
if let Some(event) = events.iter().next() {
let metadata = Metadata::from_json(&event.content).map_err(|e| e.to_string())?;
Ok(metadata.as_json())
} else {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => {
if let Some(event) = events.iter().next() {
let metadata =
Metadata::from_json(&event.content).map_err(|e| e.to_string())?;
Ok(metadata.as_json())
} else {
Err("Profile not found.".into())
}
}
Err(err) => Err(err.to_string()),
}
}
}
Err(e) => Err(e.to_string()),
}
}
@@ -203,7 +229,13 @@ pub async fn set_group(
let client = &state.client;
let public_keys: Vec<PublicKey> = users
.iter()
.map(|u| PublicKey::from_str(u).unwrap())
.filter_map(|u| {
if let Ok(pk) = PublicKey::from_str(u) {
Some(pk)
} else {
None
}
})
.collect();
let label = title.to_lowercase().replace(" ", "-");
let mut tags: Vec<Tag> = vec![Tag::title(title)];
@@ -237,7 +269,7 @@ pub async fn set_group(
.authors(public_keys)
.limit(500);
if let Ok(report) = client.sync(filter, SyncOptions::default()).await {
if let Ok(report) = client.sync(filter, &SyncOptions::default()).await {
println!("Received: {}", report.received.len());
handle.emit("synchronized", ()).unwrap();
};
@@ -283,7 +315,7 @@ pub async fn get_all_groups(state: State<'_, Nostr>) -> Result<Vec<RichEvent>, S
let filter = Filter::new().kind(Kind::FollowSet).authors(authors);
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()),
}
}
@@ -331,7 +363,7 @@ pub async fn set_interest(
.hashtags(hashtags)
.limit(500);
if let Ok(report) = client.sync(filter, SyncOptions::default()).await {
if let Ok(report) = client.sync(filter, &SyncOptions::default()).await {
println!("Received: {}", report.received.len());
handle.emit("synchronized", ()).unwrap();
};
@@ -381,7 +413,7 @@ pub async fn get_all_interests(state: State<'_, Nostr>) -> Result<Vec<RichEvent>
.authors(authors);
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events).await),
Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()),
}
}
@@ -560,14 +592,20 @@ pub async fn get_notifications(id: String, state: State<'_, Nostr>) -> Result<Ve
let client = &state.client;
let public_key = PublicKey::from_str(&id).map_err(|e| e.to_string())?;
let filter = Filter::new().pubkey(public_key).kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
]);
let filter = Filter::new()
.pubkey(public_key)
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(200);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => Ok(events.into_iter().map(|ev| ev.as_json()).collect()),
Err(err) => Err(err.to_string()),
}

View File

@@ -2,6 +2,7 @@ use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::{
collections::HashSet,
fs::{self, File},
str::FromStr,
};
@@ -52,20 +53,18 @@ pub fn sync_all(accounts: Vec<String>, app_handle: AppHandle) {
//
if let Ok(events) = client
.database()
.query(vec![Filter::new().kinds(vec![
Kind::ContactList,
Kind::FollowSet,
Kind::MuteList,
Kind::Repost,
Kind::TextNote,
])])
.query(vec![Filter::new()
.authors(public_keys)
.kinds(vec![Kind::ContactList, Kind::FollowSet])])
.await
{
let pubkeys: Vec<PublicKey> = events
let set: HashSet<PublicKey> = events
.iter()
.flat_map(|ev| ev.tags.public_keys().copied())
.collect();
let pubkeys: Vec<PublicKey> = set.into_iter().collect();
for chunk in pubkeys.chunks(500) {
if chunk.is_empty() {
break;
@@ -78,10 +77,10 @@ pub fn sync_all(accounts: Vec<String>, app_handle: AppHandle) {
let events = Filter::new()
.authors(authors.clone())
.kinds(vec![Kind::TextNote, Kind::Repost])
.limit(1000);
.limit(500);
if let Ok(output) = client
.sync_with(&bootstrap_relays, events, SyncOptions::default())
.sync_with(&bootstrap_relays, events, &SyncOptions::default())
.await
{
NegentropyEvent {
@@ -94,21 +93,20 @@ pub fn sync_all(accounts: Vec<String>, app_handle: AppHandle) {
// NEG: Sync metadata
//
let metadata = Filter::new()
.authors(authors)
let events = Filter::new()
.authors(authors.clone())
.kinds(vec![
Kind::Metadata,
Kind::ContactList,
Kind::Interests,
Kind::InterestSet,
Kind::Interests,
Kind::FollowSet,
Kind::MuteList,
Kind::RelaySet,
Kind::EventDeletion,
Kind::Custom(30315),
])
.limit(1000);
.limit(500);
if let Ok(output) = client
.sync_with(&bootstrap_relays, metadata, SyncOptions::default())
.sync_with(&bootstrap_relays, events, &SyncOptions::default())
.await
{
NegentropyEvent {
@@ -120,62 +118,6 @@ pub fn sync_all(accounts: Vec<String>, app_handle: AppHandle) {
}
}
}
// NEG: Sync notification
//
let notification = Filter::new()
.pubkeys(public_keys.clone())
.kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(500);
if let Ok(output) = client
.sync_with(&bootstrap_relays, notification, SyncOptions::default())
.await
{
NegentropyEvent {
kind: NegentropyKind::Notification,
total_event: output.received.len() as i32,
}
.emit(&app_handle)
.unwrap();
}
// NEG: Sync metadata
//
let metadata = Filter::new().authors(public_keys.clone()).kinds(vec![
Kind::Metadata,
Kind::ContactList,
Kind::Interests,
Kind::InterestSet,
Kind::FollowSet,
Kind::RelayList,
Kind::MuteList,
Kind::EventDeletion,
Kind::Bookmarks,
Kind::BookmarkSet,
Kind::Emojis,
Kind::EmojiSet,
Kind::TextNote,
Kind::Repost,
Kind::Custom(30315),
]);
if let Ok(output) = client
.sync_with(&bootstrap_relays, metadata, SyncOptions::default())
.await
{
NegentropyEvent {
kind: NegentropyKind::Others,
total_event: output.received.len() as i32,
}
.emit(&app_handle)
.unwrap();
}
});
}
@@ -235,10 +177,7 @@ pub async fn sync_account(
}
});
if let Ok(output) = client
.sync_with(&bootstrap_relays, filter, opts.clone())
.await
{
if let Ok(output) = client.sync_with(&bootstrap_relays, filter, &opts).await {
println!("Success: {:?}", output.success);
println!("Failed: {:?}", output.failed);
@@ -279,37 +218,13 @@ pub async fn sync_account(
])
.limit(10000);
if let Ok(output) = client
.sync_with(&bootstrap_relays, filter, opts.clone())
.await
{
if let Ok(output) = client.sync_with(&bootstrap_relays, filter, &opts).await {
println!("Success: {:?}", output.success);
println!("Failed: {:?}", output.failed);
}
};
}
let event_ids = client
.database()
.query(vec![Filter::new().kinds(vec![
Kind::TextNote,
Kind::Repost,
Kind::Bookmarks,
Kind::BookmarkSet,
])])
.await
.map_err(|e| e.to_string())?;
if !event_ids.is_empty() {
let ids: Vec<EventId> = event_ids.iter().map(|ev| ev.id).collect();
let filter = Filter::new().events(ids);
if let Ok(output) = client.sync_with(&bootstrap_relays, filter, opts).await {
println!("Success: {:?}", output.success);
println!("Failed: {:?}", output.failed);
}
}
let config_dir = app_handle
.path()
.app_config_dir()

View File

@@ -10,6 +10,7 @@ use tauri::window::Effect;
use tauri::TitleBarStyle;
use tauri::{LogicalPosition, LogicalSize, Manager, WebviewUrl};
use tauri::{WebviewBuilder, WebviewWindowBuilder};
#[cfg(target_os = "windows")]
use tauri_plugin_decorum::WebviewWindowExt;
#[derive(Serialize, Deserialize, Type)]
@@ -35,9 +36,9 @@ pub struct Column {
height: f32,
}
#[tauri::command(async)]
#[tauri::command]
#[specta::specta]
pub fn create_column(column: Column, app_handle: tauri::AppHandle) -> Result<String, String> {
pub async fn create_column(column: Column, app_handle: tauri::AppHandle) -> Result<String, String> {
match app_handle.get_window("main") {
Some(main_window) => match app_handle.get_webview(&column.label) {
Some(_) => Ok(column.label),
@@ -63,18 +64,18 @@ pub fn create_column(column: Column, app_handle: tauri::AppHandle) -> Result<Str
}
}
#[tauri::command(async)]
#[tauri::command]
#[specta::specta]
pub fn close_column(label: String, app_handle: tauri::AppHandle) -> Result<bool, String> {
pub async fn close_column(label: String, app_handle: tauri::AppHandle) -> Result<bool, String> {
match app_handle.get_webview(&label) {
Some(webview) => Ok(webview.close().is_ok()),
None => Err("Cannot close, column not found.".into()),
}
}
#[tauri::command(async)]
#[tauri::command]
#[specta::specta]
pub fn update_column(
pub async fn update_column(
label: String,
width: f32,
height: f32,
@@ -98,9 +99,9 @@ pub fn update_column(
}
}
#[tauri::command(async)]
#[tauri::command]
#[specta::specta]
pub fn reload_column(label: String, app_handle: tauri::AppHandle) -> Result<(), String> {
pub async fn reload_column(label: String, app_handle: tauri::AppHandle) -> Result<(), String> {
match app_handle.get_webview(&label) {
Some(webview) => {
webview.eval("location.reload(true)").unwrap();
@@ -124,6 +125,7 @@ pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<Strin
Ok(current_window.label().to_string())
} else {
#[cfg(target_os = "macos")]
let new_window = WebviewWindowBuilder::new(
&app_handle,
&window.label,
@@ -147,27 +149,7 @@ pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<Strin
.build()
.unwrap();
// Restore native border
new_window.add_border(None);
Ok(new_window.label().to_string())
}
}
#[tauri::command(async)]
#[specta::specta]
#[cfg(target_os = "windows")]
pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<String, String> {
if let Some(current_window) = app_handle.get_window(&window.label) {
if current_window.is_visible().unwrap_or_default() {
let _ = current_window.set_focus();
} else {
let _ = current_window.show();
let _ = current_window.set_focus();
};
Ok(current_window.label().to_string())
} else {
#[cfg(target_os = "windows")]
let new_window = WebviewWindowBuilder::new(
&app_handle,
&window.label,
@@ -190,58 +172,14 @@ pub fn open_window(window: Window, app_handle: tauri::AppHandle) -> Result<Strin
.build()
.unwrap();
// Set decoration
new_window.create_overlay_titlebar().unwrap();
Ok(new_window.label().to_string())
}
Ok(())
}
#[tauri::command]
#[specta::specta]
pub fn reopen_lume(app: tauri::AppHandle) {
if let Some(window) = app.get_window("main") {
if window.is_visible().unwrap_or_default() {
let _ = window.set_focus();
} else {
let _ = window.show();
let _ = window.set_focus();
};
} else {
let window =
WebviewWindowBuilder::from_config(&app, app.config().app.windows.first().unwrap())
.unwrap()
.build()
.unwrap();
// Set decoration
#[cfg(target_os = "windows")]
window.create_overlay_titlebar().unwrap();
new_window.create_overlay_titlebar().unwrap();
// Restore native border
#[cfg(target_os = "macos")]
window.add_border(None);
new_window.add_border(None);
// Set a custom inset to the traffic lights
#[cfg(target_os = "macos")]
window.set_traffic_lights_inset(7.0, 10.0).unwrap();
#[cfg(target_os = "macos")]
let win = window.clone();
#[cfg(target_os = "macos")]
window.on_window_event(move |event| {
if let tauri::WindowEvent::ThemeChanged(_) = event {
win.set_traffic_lights_inset(7.0, 10.0).unwrap();
}
});
Ok(new_window.label().to_string())
}
}
#[tauri::command]
#[specta::specta]
pub fn quit() {
std::process::exit(0)
}

View File

@@ -143,29 +143,33 @@ pub fn get_all_accounts() -> Vec<String> {
accounts.into_iter().collect()
}
pub async fn process_event(client: &Client, events: Events) -> Vec<RichEvent> {
pub async fn process_event(client: &Client, events: Events, is_reply: bool) -> Vec<RichEvent> {
// Remove event thread if event is TextNote
let events: Vec<Event> = events
.into_iter()
.filter_map(|ev| {
if ev.kind == Kind::TextNote {
let tags = ev
.tags
.iter()
.filter(|t| t.is_reply() || t.is_root())
.filter_map(|t| t.content())
.collect::<Vec<_>>();
let events: Vec<Event> = if !is_reply {
events
.into_iter()
.filter_map(|ev| {
if ev.kind == Kind::TextNote {
let tags = ev
.tags
.iter()
.filter(|t| t.is_reply() || t.is_root())
.filter_map(|t| t.content())
.collect::<Vec<_>>();
if tags.is_empty() {
Some(ev)
if tags.is_empty() {
Some(ev)
} else {
None
}
} else {
None
Some(ev)
}
} else {
Some(ev)
}
})
.collect();
})
.collect()
} else {
events.into_iter().collect()
};
// Get deletion request by event's authors
let ids: Vec<EventId> = events.iter().map(|ev| ev.id).collect();

View File

@@ -156,8 +156,6 @@ fn main() {
reload_column,
close_column,
open_window,
reopen_lume,
quit
])
.events(collect_events![Subscription, NegentropyEvent]);
@@ -207,12 +205,12 @@ fn main() {
// Config
let opts = Options::new()
.gossip(true)
.max_avg_latency(Duration::from_millis(800))
.max_avg_latency(Duration::from_millis(500))
.automatic_authentication(false)
.connection_timeout(Some(Duration::from_secs(20)))
.send_timeout(Some(Duration::from_secs(10)))
.wait_for_send(false)
.timeout(Duration::from_secs(20));
.timeout(Duration::from_secs(12));
// Setup nostr client
let client = ClientBuilder::default()
@@ -370,29 +368,31 @@ fn main() {
tauri::async_runtime::spawn(async move {
let state = handle_clone.state::<Nostr>();
let client = &state.client;
let accounts = state.accounts.lock().unwrap().clone();
let accounts = get_all_accounts();
let public_keys: Vec<PublicKey> = accounts
.iter()
.filter_map(|acc| {
if let Ok(pk) = PublicKey::from_str(acc) {
Some(pk)
} else {
None
}
})
.collect();
if !accounts.is_empty() {
let public_keys: Vec<PublicKey> = accounts
.iter()
.filter_map(|acc| {
if let Ok(pk) = PublicKey::from_str(acc) {
Some(pk)
} else {
None
}
})
.collect();
// Subscribe for new notification
if let Ok(e) = client
.subscribe_with_id(
SubscriptionId::new(NOTIFICATION_SUB_ID),
vec![Filter::new().pubkeys(public_keys).since(Timestamp::now())],
None,
)
.await
{
println!("Subscribed for notification on {} relays", e.success.len())
// Subscribe for new notification
if let Ok(e) = client
.subscribe_with_id(
SubscriptionId::new(NOTIFICATION_SUB_ID),
vec![Filter::new().pubkeys(public_keys).since(Timestamp::now())],
None,
)
.await
{
println!("Subscribed for notification on {} relays", e.success.len())
}
}
let allow_notification = match handle_clone.notification().request_permission() {
@@ -408,7 +408,6 @@ fn main() {
let notification_id = SubscriptionId::new(NOTIFICATION_SUB_ID);
let mut notifications = client.pool().notifications();
let mut new_events: Vec<EventId> = Vec::new();
while let Ok(notification) = notifications.recv().await {
match notification {
@@ -426,17 +425,6 @@ fn main() {
println!("Error: {}", e);
}
// Workaround for https://github.com/rust-nostr/nostr/issues/509
// TODO: remove
let _ = client
.fetch_events(
vec![Filter::new()
.kind(Kind::TextNote)
.limit(0)],
Some(Duration::from_secs(5)),
)
.await;
if allow_notification {
if let Err(e) = &handle_clone
.notification()
@@ -469,22 +457,8 @@ fn main() {
event,
} = message
{
let tags: Vec<String> = event
.tags
.public_keys()
.filter_map(|pk| {
if let Ok(bech32) = pk.to_bech32() {
Some(bech32)
} else {
None
}
})
.collect();
// Handle events from notification subscription
if subscription_id == notification_id
&& tags.iter().any(|item| accounts.iter().any(|i| i == item))
{
if subscription_id == notification_id {
// Send native notification
if allow_notification {
let author = client
@@ -501,37 +475,22 @@ fn main() {
&handle_clone,
);
}
}
} else {
let payload = RichEvent {
raw: event.as_json(),
parsed: if event.kind == Kind::TextNote {
Some(parse_event(&event.content).await)
} else {
None
},
};
let payload = RichEvent {
raw: event.as_json(),
parsed: if event.kind == Kind::TextNote {
Some(parse_event(&event.content).await)
} else {
None
},
};
handle_clone
.emit_to(
if let Err(e) = handle_clone.emit_to(
EventTarget::labeled(subscription_id.to_string()),
"event",
payload,
)
.unwrap();
if state
.subscriptions
.lock()
.unwrap()
.iter()
.any(|i| i == &subscription_id)
{
new_events.push(event.id);
if new_events.len() > 5 {
handle_clone.emit("synchronized", ()).unwrap();
new_events.clear();
) {
println!("Emitter error: {}", e)
}
}
};