This commit is contained in:
2024-10-27 09:57:56 +07:00
parent 1e95a2fd95
commit eb6e3e52df
8 changed files with 113 additions and 209 deletions

View File

@@ -1,3 +1,4 @@
wss://relay.damus.io,
wss://relay.primal.net,
wss://relay.nostr.band,
wss://nostr.fmt.wiz.biz,

View File

@@ -31,11 +31,10 @@ pub async fn get_event(id: String, state: State<'_, Nostr>) -> Result<RichEvent,
Ok(RichEvent { raw, parsed })
} else {
let filter = Filter::new().id(event_id);
match client
.fetch_events(
vec![Filter::new().id(event_id)],
Some(Duration::from_secs(5)),
)
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => {
@@ -48,7 +47,7 @@ pub async fn get_event(id: String, state: State<'_, Nostr>) -> Result<RichEvent,
};
Ok(RichEvent { raw, parsed })
} else {
Err("Event not found.".into())
Err(format!("Cannot found the event with ID {}", id))
}
}
Err(err) => Err(err.to_string()),
@@ -99,7 +98,10 @@ pub async fn get_all_events_by_author(
.author(author)
.limit(limit as usize);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
@@ -130,7 +132,10 @@ pub async fn get_all_events_by_authors(
.until(as_of)
.authors(authors);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}
@@ -156,7 +161,10 @@ pub async fn get_all_events_by_hashtags(
.until(as_of)
.hashtags(hashtags);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}

View File

@@ -6,7 +6,7 @@ use std::{str::FromStr, time::Duration};
use tauri::{Emitter, Manager, State};
use crate::{
common::{get_all_accounts, get_latest_event, process_event},
common::{get_latest_event, process_event},
Nostr, RichEvent, Settings,
};
@@ -36,36 +36,12 @@ 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())?;
let filter = Filter::new()
.author(public_key)
.kind(Kind::Metadata)
.limit(1);
let metadata = client
.fetch_metadata(public_key, Some(Duration::from_secs(3)))
.await
.map_err(|e| e.to_string())?;
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()),
}
Ok(metadata.as_json())
}
#[tauri::command]
@@ -102,7 +78,10 @@ pub async fn get_contact_list(id: String, state: State<'_, Nostr>) -> Result<Vec
let mut contact_list: Vec<String> = Vec::new();
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => {
if let Some(event) = events.into_iter().next() {
for tag in event.tags.into_iter() {
@@ -288,7 +267,10 @@ pub async fn get_group(id: String, state: State<'_, Nostr>) -> Result<String, St
let event_id = EventId::from_str(&id).map_err(|e| e.to_string())?;
let filter = Filter::new().kind(Kind::FollowSet).id(event_id);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => match get_latest_event(&events) {
Some(ev) => Ok(ev.as_json()),
None => Err("Not found.".to_string()),
@@ -299,22 +281,15 @@ pub async fn get_group(id: String, state: State<'_, Nostr>) -> Result<String, St
#[tauri::command]
#[specta::specta]
pub async fn get_all_groups(state: State<'_, Nostr>) -> Result<Vec<RichEvent>, String> {
pub async fn get_all_groups(id: String, state: State<'_, Nostr>) -> Result<Vec<RichEvent>, String> {
let client = &state.client;
let accounts = get_all_accounts();
let authors: Vec<PublicKey> = accounts
.iter()
.filter_map(|acc| {
if let Ok(pk) = PublicKey::from_str(acc) {
Some(pk)
} else {
None
}
})
.collect();
let filter = Filter::new().kind(Kind::FollowSet).authors(authors);
let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?;
let filter = Filter::new().kind(Kind::FollowSet).author(public_key);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()),
}
@@ -384,7 +359,10 @@ pub async fn get_interest(id: String, state: State<'_, Nostr>) -> Result<String,
.kinds(vec![Kind::Interests, Kind::InterestSet])
.id(event_id);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => match get_latest_event(&events) {
Some(ev) => Ok(ev.as_json()),
None => Err("Not found.".to_string()),
@@ -395,24 +373,20 @@ pub async fn get_interest(id: String, state: State<'_, Nostr>) -> Result<String,
#[tauri::command]
#[specta::specta]
pub async fn get_all_interests(state: State<'_, Nostr>) -> Result<Vec<RichEvent>, String> {
pub async fn get_all_interests(
id: String,
state: State<'_, Nostr>,
) -> Result<Vec<RichEvent>, String> {
let client = &state.client;
let accounts = get_all_accounts();
let authors: Vec<PublicKey> = accounts
.iter()
.filter_map(|acc| {
if let Ok(pk) = PublicKey::from_str(acc) {
Some(pk)
} else {
None
}
})
.collect();
let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?;
let filter = Filter::new()
.kinds(vec![Kind::InterestSet, Kind::Interests])
.authors(authors);
.author(public_key);
match client.database().query(vec![filter]).await {
match client
.fetch_events(vec![filter], Some(Duration::from_secs(3)))
.await
{
Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()),
}
@@ -600,7 +574,7 @@ pub async fn get_notifications(id: String, state: State<'_, Nostr>) -> Result<Ve
Kind::Reaction,
Kind::ZapReceipt,
])
.limit(200);
.limit(500);
match client
.fetch_events(vec![filter], Some(Duration::from_secs(5)))

View File

@@ -64,15 +64,14 @@ pub async fn create_column(
tauri::async_runtime::spawn(async move {
let state = webview.state::<Nostr>();
let client = &state.client;
let relays = &state.bootstrap_relays.lock().unwrap().clone();
if is_newsfeed {
if let Ok(contact_list) =
client.database().contacts_public_keys(public_key).await
{
let opts = SyncOptions::default();
let subscription_id =
SubscriptionId::new(webview.label());
let filter =
Filter::new().authors(contact_list).kinds(vec![
Kind::TextNote,
@@ -90,34 +89,6 @@ pub async fn create_column(
{
println!("Subscription error: {}", e);
}
if let Ok(output) = client
.sync_with(relays, filter.limit(1000), &opts)
.await
{
println!("Success: {:?}", output.success.len());
}
}
} else {
let opts = SyncOptions::default();
let filter = Filter::new()
.author(public_key)
.kinds(vec![
Kind::Interests,
Kind::InterestSet,
Kind::FollowSet,
Kind::Bookmarks,
Kind::BookmarkSet,
Kind::TextNote,
Kind::Repost,
Kind::Custom(30315),
])
.limit(500);
if let Ok(output) =
client.sync_with(relays, filter, &opts).await
{
println!("Success: {:?}", output.success.len());
}
}
});
@@ -125,10 +96,9 @@ pub async fn create_column(
tauri::async_runtime::spawn(async move {
let state = webview.state::<Nostr>();
let client = &state.client;
let relays = &state.bootstrap_relays.lock().unwrap().clone();
let opts = SyncOptions::default();
let subscription_id = SubscriptionId::new(webview.label());
let filter = Filter::new()
.event(event_id)
.kinds(vec![Kind::TextNote, Kind::Custom(1111)]);
@@ -143,12 +113,6 @@ pub async fn create_column(
{
println!("Subscription error: {}", e);
}
if let Ok(output) =
client.sync_with(relays, filter, &opts).await
{
println!("Success: {:?}", output.success.len());
}
});
}
}

View File

@@ -21,7 +21,7 @@ use std::{
use tauri::{path::BaseDirectory, Emitter, EventTarget, Manager};
use tauri_plugin_decorum::WebviewWindowExt;
use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_specta::{collect_commands, Builder, Event as TauriEvent};
use tauri_specta::{collect_commands, Builder};
pub mod commands;
pub mod common;
@@ -64,11 +64,6 @@ impl Default for Settings {
}
}
#[derive(Serialize, Deserialize, Type, TauriEvent)]
struct Sync {
id: String,
}
pub const DEFAULT_DIFFICULTY: u8 = 0;
pub const FETCH_LIMIT: usize = 50;
pub const NOTIFICATION_SUB_ID: &str = "lume_notification";
@@ -181,13 +176,13 @@ fn main() {
// Config
let opts = Options::new()
.gossip(true)
.max_avg_latency(Duration::from_millis(500))
.automatic_authentication(false)
.connection_timeout(Some(Duration::from_secs(20)))
.gossip(false)
.max_avg_latency(Duration::from_millis(300))
.automatic_authentication(true)
.connection_timeout(Some(Duration::from_secs(5)))
.send_timeout(Some(Duration::from_secs(10)))
.wait_for_send(false)
.timeout(Duration::from_secs(12));
.timeout(Duration::from_secs(5));
// Setup nostr client
let client = ClientBuilder::default()
@@ -266,7 +261,7 @@ fn main() {
.collect();
// Subscribe for new notification
if let Ok(e) = client
if let Err(e) = client
.subscribe_with_id(
SubscriptionId::new(NOTIFICATION_SUB_ID),
vec![Filter::new().pubkeys(public_keys).since(Timestamp::now())],
@@ -274,7 +269,7 @@ fn main() {
)
.await
{
println!("Subscribed for notification on {} relays", e.success.len())
println!("Error: {}", e)
}
}
@@ -290,54 +285,14 @@ fn main() {
};
let notification_id = SubscriptionId::new(NOTIFICATION_SUB_ID);
let mut notifications = client.pool().notifications();
while let Ok(notification) = notifications.recv().await {
match notification {
RelayPoolNotification::Message { relay_url, message } => {
if let RelayMessage::Auth { challenge } = message {
match client.auth(challenge, relay_url.clone()).await {
Ok(..) => {
if let Ok(relay) = client.relay(&relay_url).await {
let msg =
format!("Authenticated to {} relay.", relay_url);
let opts = RelaySendOptions::new()
.skip_send_confirmation(true);
if let Err(e) = relay.resubscribe(opts).await {
println!("Error: {}", e);
}
if allow_notification {
if let Err(e) = &handle_clone
.notification()
.builder()
.body(&msg)
.title("Lume")
.show()
{
println!("Error: {}", e);
}
}
}
}
Err(e) => {
if allow_notification {
if let Err(e) = &handle_clone
.notification()
.builder()
.body(e.to_string())
.title("Lume")
.show()
{
println!("Error: {}", e);
}
}
}
}
} else if let RelayMessage::Event {
subscription_id,
let _ = client
.handle_notifications(|notification| async {
#[allow(clippy::collapsible_match)]
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event {
event,
subscription_id,
} = message
{
// Handle events from notification subscription
@@ -358,7 +313,7 @@ fn main() {
&handle_clone,
);
}
} else {
} else if event.kind != Kind::RelayList {
let payload = RichEvent {
raw: event.as_json(),
parsed: if event.kind == Kind::TextNote {
@@ -376,12 +331,11 @@ fn main() {
println!("Emitter error: {}", e)
}
}
};
}
}
RelayPoolNotification::Shutdown => break,
_ => (),
}
}
Ok(false)
})
.await;
});
Ok(())