feat: make global state simpler

This commit is contained in:
2025-02-10 20:05:03 +07:00
parent bfc9588738
commit 1bb9729e75
10 changed files with 211 additions and 147 deletions

View File

@@ -1,12 +0,0 @@
[package]
name = "app_state"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
common = { path = "../common" }
state = { path = "../state" }
gpui.workspace = true
nostr-sdk.workspace = true

View File

@@ -1 +0,0 @@
pub mod registry;

View File

@@ -1,75 +0,0 @@
use common::{
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
profile::NostrProfile,
};
use gpui::{App, AppContext, Global};
use nostr_sdk::prelude::*;
use state::get_client;
use std::time::Duration;
pub struct AppRegistry {
user: Option<NostrProfile>,
}
impl Global for AppRegistry {}
impl AppRegistry {
pub fn set_global(cx: &mut App) {
cx.observe_global::<Self>(|cx| {
if let Some(profile) = cx.global::<Self>().user() {
let client = get_client();
let public_key = profile.public_key();
cx.background_spawn(async move {
let subscription = Filter::new()
.kind(Kind::ContactList)
.author(public_key)
.limit(1);
// Get contact list
_ = client.sync(subscription, &SyncOptions::default()).await;
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);
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
// Subscribe for all messages
_ = client
.subscribe_with_id(
all_messages_sub_id,
all_messages,
Some(SubscribeAutoCloseOptions::default().exit_policy(
ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(3)),
)),
)
.await;
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, new_message, None)
.await
})
.detach();
}
})
.detach();
cx.set_global(Self { user: None });
}
pub fn set_user(&mut self, profile: Option<NostrProfile>) {
self.user = profile;
}
pub fn user(&self) -> Option<NostrProfile> {
self.user.clone()
}
}