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

View File

@@ -6,7 +6,7 @@ use std::{str::FromStr, time::Duration};
use tauri::{Emitter, Manager, State}; use tauri::{Emitter, Manager, State};
use crate::{ use crate::{
common::{get_all_accounts, get_latest_event, process_event}, common::{get_latest_event, process_event},
Nostr, RichEvent, Settings, Nostr, RichEvent, Settings,
}; };
@@ -36,36 +36,12 @@ pub async fn get_profile(id: String, state: State<'_, Nostr>) -> Result<String,
let client = &state.client; let client = &state.client;
let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?; let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?;
let filter = Filter::new() let metadata = client
.author(public_key) .fetch_metadata(public_key, Some(Duration::from_secs(3)))
.kind(Kind::Metadata) .await
.limit(1); .map_err(|e| e.to_string())?;
match client.database().query(vec![filter.clone()]).await { Ok(metadata.as_json())
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()),
}
} }
#[tauri::command] #[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(); 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) => { Ok(events) => {
if let Some(event) = events.into_iter().next() { if let Some(event) = events.into_iter().next() {
for tag in event.tags.into_iter() { 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 event_id = EventId::from_str(&id).map_err(|e| e.to_string())?;
let filter = Filter::new().kind(Kind::FollowSet).id(event_id); 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) { Ok(events) => match get_latest_event(&events) {
Some(ev) => Ok(ev.as_json()), Some(ev) => Ok(ev.as_json()),
None => Err("Not found.".to_string()), 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] #[tauri::command]
#[specta::specta] #[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 client = &state.client;
let accounts = get_all_accounts(); let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?;
let authors: Vec<PublicKey> = accounts let filter = Filter::new().kind(Kind::FollowSet).author(public_key);
.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);
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), Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()), 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]) .kinds(vec![Kind::Interests, Kind::InterestSet])
.id(event_id); .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) { Ok(events) => match get_latest_event(&events) {
Some(ev) => Ok(ev.as_json()), Some(ev) => Ok(ev.as_json()),
None => Err("Not found.".to_string()), None => Err("Not found.".to_string()),
@@ -395,24 +373,20 @@ pub async fn get_interest(id: String, state: State<'_, Nostr>) -> Result<String,
#[tauri::command] #[tauri::command]
#[specta::specta] #[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 client = &state.client;
let accounts = get_all_accounts(); let public_key = PublicKey::parse(&id).map_err(|e| e.to_string())?;
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() let filter = Filter::new()
.kinds(vec![Kind::InterestSet, Kind::Interests]) .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), Ok(events) => Ok(process_event(client, events, false).await),
Err(e) => Err(e.to_string()), 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::Reaction,
Kind::ZapReceipt, Kind::ZapReceipt,
]) ])
.limit(200); .limit(500);
match client match client
.fetch_events(vec![filter], Some(Duration::from_secs(5))) .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 { tauri::async_runtime::spawn(async move {
let state = webview.state::<Nostr>(); let state = webview.state::<Nostr>();
let client = &state.client; let client = &state.client;
let relays = &state.bootstrap_relays.lock().unwrap().clone();
if is_newsfeed { if is_newsfeed {
if let Ok(contact_list) = if let Ok(contact_list) =
client.database().contacts_public_keys(public_key).await client.database().contacts_public_keys(public_key).await
{ {
let opts = SyncOptions::default();
let subscription_id = let subscription_id =
SubscriptionId::new(webview.label()); SubscriptionId::new(webview.label());
let filter = let filter =
Filter::new().authors(contact_list).kinds(vec![ Filter::new().authors(contact_list).kinds(vec![
Kind::TextNote, Kind::TextNote,
@@ -90,34 +89,6 @@ pub async fn create_column(
{ {
println!("Subscription error: {}", e); 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 { tauri::async_runtime::spawn(async move {
let state = webview.state::<Nostr>(); let state = webview.state::<Nostr>();
let client = &state.client; let client = &state.client;
let relays = &state.bootstrap_relays.lock().unwrap().clone();
let opts = SyncOptions::default();
let subscription_id = SubscriptionId::new(webview.label()); let subscription_id = SubscriptionId::new(webview.label());
let filter = Filter::new() let filter = Filter::new()
.event(event_id) .event(event_id)
.kinds(vec![Kind::TextNote, Kind::Custom(1111)]); .kinds(vec![Kind::TextNote, Kind::Custom(1111)]);
@@ -143,12 +113,6 @@ pub async fn create_column(
{ {
println!("Subscription error: {}", e); 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::{path::BaseDirectory, Emitter, EventTarget, Manager};
use tauri_plugin_decorum::WebviewWindowExt; use tauri_plugin_decorum::WebviewWindowExt;
use tauri_plugin_notification::{NotificationExt, PermissionState}; 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 commands;
pub mod common; 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 DEFAULT_DIFFICULTY: u8 = 0;
pub const FETCH_LIMIT: usize = 50; pub const FETCH_LIMIT: usize = 50;
pub const NOTIFICATION_SUB_ID: &str = "lume_notification"; pub const NOTIFICATION_SUB_ID: &str = "lume_notification";
@@ -181,13 +176,13 @@ fn main() {
// Config // Config
let opts = Options::new() let opts = Options::new()
.gossip(true) .gossip(false)
.max_avg_latency(Duration::from_millis(500)) .max_avg_latency(Duration::from_millis(300))
.automatic_authentication(false) .automatic_authentication(true)
.connection_timeout(Some(Duration::from_secs(20))) .connection_timeout(Some(Duration::from_secs(5)))
.send_timeout(Some(Duration::from_secs(10))) .send_timeout(Some(Duration::from_secs(10)))
.wait_for_send(false) .wait_for_send(false)
.timeout(Duration::from_secs(12)); .timeout(Duration::from_secs(5));
// Setup nostr client // Setup nostr client
let client = ClientBuilder::default() let client = ClientBuilder::default()
@@ -266,7 +261,7 @@ fn main() {
.collect(); .collect();
// Subscribe for new notification // Subscribe for new notification
if let Ok(e) = client if let Err(e) = client
.subscribe_with_id( .subscribe_with_id(
SubscriptionId::new(NOTIFICATION_SUB_ID), SubscriptionId::new(NOTIFICATION_SUB_ID),
vec![Filter::new().pubkeys(public_keys).since(Timestamp::now())], vec![Filter::new().pubkeys(public_keys).since(Timestamp::now())],
@@ -274,7 +269,7 @@ fn main() {
) )
.await .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 notification_id = SubscriptionId::new(NOTIFICATION_SUB_ID);
let mut notifications = client.pool().notifications();
while let Ok(notification) = notifications.recv().await { let _ = client
match notification { .handle_notifications(|notification| async {
RelayPoolNotification::Message { relay_url, message } => { #[allow(clippy::collapsible_match)]
if let RelayMessage::Auth { challenge } = message { if let RelayPoolNotification::Message { message, .. } = notification {
match client.auth(challenge, relay_url.clone()).await { if let RelayMessage::Event {
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,
event, event,
subscription_id,
} = message } = message
{ {
// Handle events from notification subscription // Handle events from notification subscription
@@ -358,7 +313,7 @@ fn main() {
&handle_clone, &handle_clone,
); );
} }
} else { } else if event.kind != Kind::RelayList {
let payload = RichEvent { let payload = RichEvent {
raw: event.as_json(), raw: event.as_json(),
parsed: if event.kind == Kind::TextNote { parsed: if event.kind == Kind::TextNote {
@@ -376,12 +331,11 @@ fn main() {
println!("Emitter error: {}", e) println!("Emitter error: {}", e)
} }
} }
}; }
} }
RelayPoolNotification::Shutdown => break, Ok(false)
_ => (), })
} .await;
}
}); });
Ok(()) Ok(())

View File

@@ -200,9 +200,9 @@ async getGroup(id: string) : Promise<Result<string, string>> {
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };
} }
}, },
async getAllGroups() : Promise<Result<RichEvent[], string>> { async getAllGroups(id: string) : Promise<Result<RichEvent[], string>> {
try { try {
return { status: "ok", data: await TAURI_INVOKE("get_all_groups") }; return { status: "ok", data: await TAURI_INVOKE("get_all_groups", { id }) };
} catch (e) { } catch (e) {
if(e instanceof Error) throw e; if(e instanceof Error) throw e;
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };
@@ -224,9 +224,9 @@ async getInterest(id: string) : Promise<Result<string, string>> {
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };
} }
}, },
async getAllInterests() : Promise<Result<RichEvent[], string>> { async getAllInterests(id: string) : Promise<Result<RichEvent[], string>> {
try { try {
return { status: "ok", data: await TAURI_INVOKE("get_all_interests") }; return { status: "ok", data: await TAURI_INVOKE("get_all_interests", { id }) };
} catch (e) { } catch (e) {
if(e instanceof Error) throw e; if(e instanceof Error) throw e;
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };

View File

@@ -1,7 +1,11 @@
import type { RichEvent } from "@/commands.gen";
import { Spinner } from "@/components"; import { Spinner } from "@/components";
import type { QueryClient } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query";
import { Outlet, createRootRouteWithContext } from "@tanstack/react-router"; import { Outlet, createRootRouteWithContext } from "@tanstack/react-router";
import { listen } from "@tauri-apps/api/event";
import type { OsType } from "@tauri-apps/plugin-os"; import type { OsType } from "@tauri-apps/plugin-os";
import { nip19 } from "nostr-tools";
import { useEffect } from "react";
interface RouterContext { interface RouterContext {
queryClient: QueryClient; queryClient: QueryClient;
@@ -15,6 +19,25 @@ export const Route = createRootRouteWithContext<RouterContext>()({
}); });
function Screen() { function Screen() {
const { queryClient } = Route.useRouteContext();
useEffect(() => {
const unlisten = listen<RichEvent>("event", async (data) => {
const event = JSON.parse(data.payload.raw);
if (event.kind === 0) {
const npub = nip19.npubEncode(event.pubkey);
await queryClient.invalidateQueries({
queryKey: ["profile", npub, event.pubkey],
});
}
});
return () => {
unlisten.then((f) => f());
};
}, []);
return <Outlet />; return <Outlet />;
} }

View File

@@ -4,35 +4,19 @@ import { Spinner, User } from "@/components";
import { LumeWindow } from "@/system"; import { LumeWindow } from "@/system";
import type { LumeColumn, NostrEvent } from "@/types"; import type { LumeColumn, NostrEvent } from "@/types";
import { ArrowClockwise, Plus } from "@phosphor-icons/react"; import { ArrowClockwise, Plus } from "@phosphor-icons/react";
import * as Progress from "@radix-ui/react-progress";
import * as ScrollArea from "@radix-ui/react-scroll-area"; import * as ScrollArea from "@radix-ui/react-scroll-area";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { createLazyFileRoute } from "@tanstack/react-router"; import { createLazyFileRoute } from "@tanstack/react-router";
import { Channel } from "@tauri-apps/api/core";
import { resolveResource } from "@tauri-apps/api/path"; import { resolveResource } from "@tauri-apps/api/path";
import { readTextFile } from "@tauri-apps/plugin-fs"; import { readTextFile } from "@tauri-apps/plugin-fs";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { useCallback, useEffect, useState } from "react"; import { useCallback } from "react";
export const Route = createLazyFileRoute("/columns/_layout/launchpad/$id")({ export const Route = createLazyFileRoute("/columns/_layout/launchpad/$id")({
component: Screen, component: Screen,
}); });
function Screen() { function Screen() {
const { id } = Route.useParams();
const { isLoading, data: isSync } = useQuery({
queryKey: ["is-sync", id],
queryFn: async () => {
const res = await commands.isAccountSync(id);
if (res.status === "ok") {
return res.data;
} else {
return false;
}
},
});
return ( return (
<ScrollArea.Root <ScrollArea.Root
type={"scroll"} type={"scroll"}
@@ -40,17 +24,9 @@ function Screen() {
className="overflow-hidden size-full" className="overflow-hidden size-full"
> >
<ScrollArea.Viewport className="relative h-full px-3 pb-3"> <ScrollArea.Viewport className="relative h-full px-3 pb-3">
{isLoading ? ( <Groups />
<Spinner className="size-4" /> <Interests />
) : !isSync ? ( <Core />
<SyncProgress />
) : (
<>
<Groups />
<Interests />
<Core />
</>
)}
</ScrollArea.Viewport> </ScrollArea.Viewport>
<ScrollArea.Scrollbar <ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2" className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
@@ -63,6 +39,7 @@ function Screen() {
); );
} }
/*
function SyncProgress() { function SyncProgress() {
const { id } = Route.useParams(); const { id } = Route.useParams();
const { queryClient } = Route.useRouteContext(); const { queryClient } = Route.useRouteContext();
@@ -128,12 +105,14 @@ function SyncProgress() {
</div> </div>
); );
} }
*/
function Groups() { function Groups() {
const { id } = Route.useParams();
const { isLoading, isError, error, data, refetch, isRefetching } = useQuery({ const { isLoading, isError, error, data, refetch, isRefetching } = useQuery({
queryKey: ["others", "groups"], queryKey: ["others", "groups", id],
queryFn: async () => { queryFn: async () => {
const res = await commands.getAllGroups(); const res = await commands.getAllGroups(id);
if (res.status === "ok") { if (res.status === "ok") {
const data = toLumeEvents(res.data); const data = toLumeEvents(res.data);
@@ -254,10 +233,11 @@ function Groups() {
} }
function Interests() { function Interests() {
const { id } = Route.useParams();
const { isLoading, isError, error, data, refetch, isRefetching } = useQuery({ const { isLoading, isError, error, data, refetch, isRefetching } = useQuery({
queryKey: ["others", "interests"], queryKey: ["others", "interests", id],
queryFn: async () => { queryFn: async () => {
const res = await commands.getAllInterests(); const res = await commands.getAllInterests(id);
if (res.status === "ok") { if (res.status === "ok") {
const data = toLumeEvents(res.data); const data = toLumeEvents(res.data);