wip: refactor

This commit is contained in:
reya
2025-01-08 12:34:13 +07:00
parent fe24f84b02
commit 122ee4c8bb
13 changed files with 360 additions and 271 deletions
-85
View File
@@ -1,85 +0,0 @@
use gpui::*;
use nostr_sdk::prelude::*;
use std::time::Duration;
use crate::{
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
get_client,
};
pub struct AccountRegistry {
public_key: Option<PublicKey>,
pub(crate) is_loading: bool,
}
impl Global for AccountRegistry {}
impl AccountRegistry {
pub fn set_global(cx: &mut AppContext) {
cx.set_global(Self::new());
cx.observe_global::<Self>(|cx| {
let state = cx.global::<Self>();
if let Some(public_key) = state.public_key {
let client = get_client();
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
// Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.exit_policy(ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(5)));
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
cx.background_executor()
.spawn(async move {
// Subscribe for all messages
if client
.subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await
.is_ok()
{
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await
}
})
.detach();
}
})
.detach();
}
pub fn set_loading(&mut self) {
self.is_loading = false
}
pub fn get(&self) -> Option<PublicKey> {
self.public_key
}
pub fn set_user(&mut self, public_key: Option<PublicKey>) {
self.public_key = public_key
}
pub fn is_user_logged_in(&self) -> bool {
self.public_key.is_some()
}
fn new() -> Self {
Self {
public_key: None,
is_loading: true,
}
}
}
+111
View File
@@ -0,0 +1,111 @@
use crate::{
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
get_client,
};
use gpui::*;
use nostr_sdk::prelude::*;
use std::time::Duration;
pub struct AppRegistry {
user: Model<Option<PublicKey>>,
refreshs: Model<Vec<PublicKey>>,
pub(crate) is_loading: bool,
}
impl Global for AppRegistry {}
impl AppRegistry {
pub fn set_global(cx: &mut AppContext) {
let refreshs = cx.new_model(|_| Vec::new());
let user = cx.new_model(|_| None);
let async_user = user.clone();
cx.set_global(Self {
user,
refreshs,
is_loading: true,
});
cx.observe(&async_user, |model, cx| {
if let Some(public_key) = model.read(cx).clone().as_ref() {
let client = get_client();
let public_key = *public_key;
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
// Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.exit_policy(ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(5)));
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
cx.background_executor()
.spawn(async move {
// Subscribe for all messages
_ = client
.subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await;
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await;
let subscription = Filter::new()
.kind(Kind::Metadata)
.author(public_key)
.limit(1);
// Get metadata
_ = client.sync(subscription, &SyncOptions::default()).await;
let subscription = Filter::new()
.kind(Kind::ContactList)
.author(public_key)
.limit(1);
// Get contact list
_ = client.sync(subscription, &SyncOptions::default()).await;
})
.detach();
}
})
.detach();
}
pub fn set_loading(&mut self) {
self.is_loading = false
}
pub fn set_user(&mut self, public_key: PublicKey, cx: &mut AppContext) {
self.user.update(cx, |model, cx| {
*model = Some(public_key);
cx.notify();
});
self.is_loading = false;
}
pub fn set_refresh(&mut self, public_key: PublicKey, cx: &mut AppContext) {
self.refreshs.update(cx, |this, cx| {
this.push(public_key);
cx.notify();
})
}
pub fn current_user(&self) -> WeakModel<Option<PublicKey>> {
self.user.downgrade()
}
pub fn refreshs(&self) -> WeakModel<Vec<PublicKey>> {
self.refreshs.downgrade()
}
}
+32 -34
View File
@@ -97,11 +97,8 @@ impl ChatRegistry {
}
pub fn init(&mut self, cx: &mut AppContext) {
if self.is_initialized {
return;
}
let async_cx = cx.to_async();
// Get all current room's ids
let ids: Vec<String> = self
.rooms
@@ -113,42 +110,43 @@ impl ChatRegistry {
cx.foreground_executor()
.spawn(async move {
let client = get_client();
let signer = client.signer().await.unwrap();
let public_key = signer.get_public_key().await.unwrap();
let filter = Filter::new()
.kind(Kind::PrivateDirectMessage)
.pubkey(public_key);
let events = async_cx
let query: anyhow::Result<Vec<Event>, anyhow::Error> = async_cx
.background_executor()
.spawn(async move {
if let Ok(events) = client.database().query(vec![filter]).await {
events
.into_iter()
.filter(|ev| ev.pubkey != public_key)
.filter(|ev| {
let new_id = get_room_id(&ev.pubkey, &ev.tags);
// Get new events only
!ids.iter().any(|id| id == &new_id)
}) // Filter all messages from current user
.unique_by(|ev| ev.pubkey)
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect::<Vec<_>>()
} else {
Vec::new()
}
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
.kind(Kind::PrivateDirectMessage)
.pubkey(public_key);
let events = client.database().query(vec![filter]).await?;
let result = events
.into_iter()
.filter(|ev| ev.pubkey != public_key)
.filter(|ev| {
let new_id = get_room_id(&ev.pubkey, &ev.tags);
// Get new events only
!ids.iter().any(|id| id == &new_id)
}) // Filter all messages from current user
.unique_by(|ev| ev.pubkey)
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect::<Vec<_>>();
Ok(result)
})
.await;
_ = async_cx.update_global::<Self, _>(|state, cx| {
state.rooms.update(cx, |model, cx| {
model.extend(events);
cx.notify();
});
if let Ok(events) = query {
_ = async_cx.update_global::<Self, _>(|state, cx| {
state.rooms.update(cx, |model, cx| {
model.extend(events);
cx.notify();
});
state.is_initialized = true;
});
state.is_initialized = true;
});
}
})
.detach();
}
+1 -1
View File
@@ -1,2 +1,2 @@
pub mod account;
pub mod app;
pub mod chat;