This commit is contained in:
2024-10-26 17:24:39 +07:00
parent 470dc1c759
commit 83d24351cd
13 changed files with 191 additions and 496 deletions

View File

@@ -84,28 +84,6 @@ pub async fn get_replies(id: String, state: State<'_, Nostr>) -> Result<Vec<Rich
}
}
#[tauri::command]
#[specta::specta]
pub async fn subscribe_to(id: String, state: State<'_, Nostr>) -> Result<(), String> {
let client = &state.client;
let subscription_id = SubscriptionId::new(&id);
let event_id = EventId::parse(&id).map_err(|err| err.to_string())?;
let filter = Filter::new()
.kinds(vec![Kind::TextNote])
.event(event_id)
.since(Timestamp::now());
match client
.subscribe_with_id(subscription_id, vec![filter], None)
.await
{
Ok(_) => Ok(()),
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_all_events_by_author(
@@ -178,10 +156,7 @@ pub async fn get_all_events_by_hashtags(
.until(as_of)
.hashtags(hashtags);
match client
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
match client.database().query(vec![filter]).await {
Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()),
}

View File

@@ -1,126 +1,9 @@
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::{
collections::HashSet,
fs::{self, File},
str::FromStr,
};
use tauri::{ipc::Channel, AppHandle, Manager, State};
use tauri_specta::Event as TauriEvent;
use std::fs::{self, File};
use tauri::{ipc::Channel, Manager, State};
use crate::Nostr;
#[derive(Clone, Serialize, Type, TauriEvent)]
pub struct NegentropyEvent {
kind: NegentropyKind,
total_event: i32,
}
#[derive(Clone, Serialize, Deserialize, Type)]
pub enum NegentropyKind {
Profile,
Metadata,
Events,
EventIds,
Global,
Notification,
Others,
}
pub fn sync_all(accounts: Vec<String>, app_handle: AppHandle) {
if accounts.is_empty() {
return;
};
let public_keys: Vec<PublicKey> = accounts
.iter()
.filter_map(|acc| {
if let Ok(pk) = PublicKey::from_str(acc) {
Some(pk)
} else {
None
}
})
.collect();
tauri::async_runtime::spawn(async move {
let state = app_handle.state::<Nostr>();
let client = &state.client;
let bootstrap_relays = state.bootstrap_relays.lock().unwrap().clone();
// NEG: Sync events for all pubkeys in local database
//
if let Ok(events) = client
.database()
.query(vec![Filter::new()
.authors(public_keys)
.kinds(vec![Kind::ContactList, Kind::FollowSet])])
.await
{
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;
}
let authors = chunk.to_owned();
// NEG: Sync event
//
let events = Filter::new()
.authors(authors.clone())
.kinds(vec![Kind::TextNote, Kind::Repost])
.limit(500);
if let Ok(output) = client
.sync_with(&bootstrap_relays, events, &SyncOptions::default())
.await
{
NegentropyEvent {
kind: NegentropyKind::Events,
total_event: output.received.len() as i32,
}
.emit(&app_handle)
.unwrap();
}
// NEG: Sync metadata
//
let events = Filter::new()
.authors(authors.clone())
.kinds(vec![
Kind::Metadata,
Kind::InterestSet,
Kind::Interests,
Kind::FollowSet,
Kind::EventDeletion,
Kind::Custom(30315),
])
.limit(500);
if let Ok(output) = client
.sync_with(&bootstrap_relays, events, &SyncOptions::default())
.await
{
NegentropyEvent {
kind: NegentropyKind::Metadata,
total_event: output.received.len() as i32,
}
.emit(&app_handle)
.unwrap();
}
}
}
});
}
#[tauri::command]
#[specta::specta]
pub fn is_account_sync(id: String, app_handle: tauri::AppHandle) -> Result<bool, String> {

View File

@@ -1,7 +1,9 @@
use std::path::PathBuf;
use std::str::FromStr;
#[cfg(target_os = "macos")]
use border::WebviewWindowExt as BorderWebviewWindowExt;
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::utils::config::WindowEffectsConfig;
@@ -14,6 +16,9 @@ use tauri::{WebviewBuilder, WebviewWindowBuilder};
#[cfg(target_os = "windows")]
use tauri_plugin_decorum::WebviewWindowExt;
use crate::common::get_last_segment;
use crate::Nostr;
#[derive(Serialize, Deserialize, Type)]
pub struct NewWindow {
label: String,
@@ -55,8 +60,101 @@ pub async fn create_column(
.transparent(true)
.on_page_load(|webview, payload| match payload.event() {
PageLoadEvent::Started => {
let url = payload.url();
println!("#TODO, preload: {}", url)
if let Ok(id) = get_last_segment(payload.url()) {
if let Ok(public_key) = PublicKey::from_str(&id) {
let is_newsfeed = payload.url().to_string().contains("newsfeed");
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,
Kind::Repost,
Kind::EventDeletion,
]);
if let Err(e) = client
.subscribe_with_id(
subscription_id,
vec![filter.clone().since(Timestamp::now())],
None,
)
.await
{
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());
}
}
});
} else if let Ok(event_id) = EventId::from_str(&id) {
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)]);
if let Err(e) = client
.subscribe_with_id(
subscription_id,
vec![filter.clone().since(Timestamp::now())],
None,
)
.await
{
println!("Subscription error: {}", e);
}
if let Ok(output) =
client.sync_with(relays, filter, &opts).await
{
println!("Success: {:?}", output.success.len());
}
});
}
}
}
PageLoadEvent::Finished => {
println!("{} finished loading", payload.url());
@@ -80,7 +178,7 @@ pub async fn create_column(
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()),
None => Err(format!("Cannot close, column not found: {}", label)),
}
}