wip: refactor

This commit is contained in:
2025-01-25 08:11:34 +07:00
parent 29a8e2c8ac
commit 6a67a79c3f
21 changed files with 410 additions and 452 deletions

View File

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

View File

@@ -0,0 +1,95 @@
use common::constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID};
use gpui::{AppContext, Context, Global, Model, WeakModel, WindowContext};
use nostr_sdk::prelude::*;
use state::get_client;
use std::time::Duration;
use crate::contact::Contact;
pub struct AppRegistry {
user: Model<Option<Contact>>,
pub is_loading: bool,
}
impl Global for AppRegistry {}
impl AppRegistry {
pub fn set_global(cx: &mut AppContext) {
let is_loading = true;
let user: Model<Option<Contact>> = cx.new_model(|_| None);
cx.observe(&user, |this, cx| {
if let Some(contact) = this.read(cx).as_ref() {
let client = get_client();
let public_key = contact.public_key();
cx.background_executor()
.spawn(async move {
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;
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);
// 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;
})
.detach();
}
})
.detach();
cx.set_global(Self { user, is_loading });
}
pub fn user(&self) -> WeakModel<Option<Contact>> {
self.user.downgrade()
}
pub fn set_user(&mut self, contact: Contact, cx: &mut AppContext) {
self.user.update(cx, |this, cx| {
*this = Some(contact);
cx.notify();
});
self.is_loading = false;
}
pub fn current_user(&self, cx: &WindowContext) -> Option<Contact> {
self.user.read(cx).clone()
}
}

197
crates/registry/src/chat.rs Normal file
View File

@@ -0,0 +1,197 @@
use common::utils::{compare, room_hash};
use gpui::{AppContext, Context, Global, Model, WeakModel};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use state::get_client;
use std::cmp::Reverse;
use crate::room::Room;
pub struct Inbox {
pub rooms: Vec<Model<Room>>,
pub is_loading: bool,
}
impl Inbox {
pub fn new() -> Self {
Self {
rooms: vec![],
is_loading: true,
}
}
}
impl Default for Inbox {
fn default() -> Self {
Self::new()
}
}
pub struct ChatRegistry {
inbox: Model<Inbox>,
}
impl Global for ChatRegistry {}
impl ChatRegistry {
pub fn set_global(cx: &mut AppContext) {
let inbox = cx.new_model(|_| Inbox::default());
cx.observe_new_models::<Room>(|this, cx| {
// Get all pubkeys to load metadata
let pubkeys = this.get_all_keys();
cx.spawn(|weak_model, mut async_cx| async move {
let query: Result<Vec<(PublicKey, Metadata)>, Error> = async_cx
.background_executor()
.spawn(async move {
let client = get_client();
let mut profiles = Vec::new();
for public_key in pubkeys.into_iter() {
let query = client.database().metadata(public_key).await?;
let metadata = query.unwrap_or_default();
profiles.push((public_key, metadata));
}
Ok(profiles)
})
.await;
if let Ok(profiles) = query {
if let Some(model) = weak_model.upgrade() {
_ = async_cx.update_model(&model, |model, cx| {
for profile in profiles.into_iter() {
model.set_metadata(profile.0, profile.1);
}
cx.notify();
});
}
}
})
.detach();
})
.detach();
cx.set_global(Self { inbox });
}
pub fn init(&mut self, cx: &mut AppContext) {
let mut async_cx = cx.to_async();
let async_inbox = self.inbox.clone();
// Get all current room's id
let hashes: Vec<u64> = self
.inbox
.read(cx)
.rooms
.iter()
.map(|room| room.read(cx).id)
.collect();
cx.foreground_executor()
.spawn(async move {
let client = get_client();
let query: anyhow::Result<Vec<Event>, anyhow::Error> = async_cx
.background_executor()
.spawn(async move {
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
.kind(Kind::PrivateDirectMessage)
.author(public_key);
// Get all DM events from database
let events = client.database().query(vec![filter]).await?;
// Filter result
// - Only unique rooms
// - Sorted by created_at
let result = events
.into_iter()
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
.unique_by(|ev| room_hash(&ev.tags))
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect::<Vec<_>>();
Ok(result)
})
.await;
if let Ok(events) = query {
_ = async_cx.update_model(&async_inbox, |model, cx| {
let items: Vec<Model<Room>> = events
.into_iter()
.filter_map(|ev| {
let id = room_hash(&ev.tags);
// Filter all seen events
if !hashes.iter().any(|h| h == &id) {
Some(cx.new_model(|_| Room::parse(&ev)))
} else {
None
}
})
.collect();
model.rooms.extend(items);
model.is_loading = false;
cx.notify();
});
}
})
.detach();
}
pub fn inbox(&self) -> WeakModel<Inbox> {
self.inbox.downgrade()
}
pub fn room(&self, id: &u64, cx: &AppContext) -> Option<WeakModel<Room>> {
self.inbox
.read(cx)
.rooms
.iter()
.find(|model| &model.read(cx).id == id)
.map(|model| model.downgrade())
}
pub fn new_room(&mut self, room: Room, cx: &mut AppContext) {
let room = cx.new_model(|_| room);
self.inbox.update(cx, |this, cx| {
if !this.rooms.iter().any(|r| r.read(cx) == room.read(cx)) {
this.rooms.insert(0, room);
cx.notify();
}
})
}
pub fn receive(&mut self, event: Event, cx: &mut AppContext) {
let mut pubkeys: Vec<_> = event.tags.public_keys().copied().collect();
pubkeys.push(event.pubkey);
self.inbox.update(cx, |this, cx| {
if let Some(room) = this.rooms.iter().find(|room| {
let all_keys = room.read(cx).get_all_keys();
compare(&all_keys, &pubkeys)
}) {
room.update(cx, |this, cx| {
this.new_messages.push(event);
cx.notify();
})
} else {
let room = cx.new_model(|_| Room::parse(&event));
self.inbox.update(cx, |this, cx| {
this.rooms.insert(0, room);
cx.notify();
})
}
// cx.notify();
})
}
}

View File

@@ -0,0 +1,63 @@
use common::{constants::IMAGE_SERVICE, utils::shorted_public_key};
use nostr_sdk::prelude::*;
#[derive(Debug, Clone)]
pub struct Contact {
public_key: PublicKey,
metadata: Metadata,
}
impl PartialEq for Contact {
fn eq(&self, other: &Self) -> bool {
self.public_key() == other.public_key()
}
}
impl Contact {
pub fn new(public_key: PublicKey, metadata: Metadata) -> Self {
Self {
public_key,
metadata,
}
}
/// Get contact's public key
pub fn public_key(&self) -> PublicKey {
self.public_key
}
/// Set contact's metadata
pub fn metadata(&mut self, metadata: &Metadata) {
self.metadata = metadata.clone()
}
/// Get contact's avatar
pub fn avatar(&self) -> String {
if let Some(picture) = &self.metadata.picture {
format!(
"{}/?url={}&w=100&h=100&fit=cover&mask=circle&n=-1",
IMAGE_SERVICE, picture
)
} else {
"brand/avatar.png".into()
}
}
/// Get contact's name
/// Fallback to public key as shorted format
pub fn name(&self) -> String {
if let Some(display_name) = &self.metadata.display_name {
if !display_name.is_empty() {
return display_name.clone();
}
}
if let Some(name) = &self.metadata.name {
if !name.is_empty() {
return name.clone();
}
}
shorted_public_key(self.public_key)
}
}

View File

@@ -0,0 +1,4 @@
pub mod app;
pub mod chat;
pub mod contact;
pub mod room;

131
crates/registry/src/room.rs Normal file
View File

@@ -0,0 +1,131 @@
use common::utils::{compare, random_name, room_hash};
use gpui::SharedString;
use nostr_sdk::prelude::*;
use crate::contact::Contact;
#[derive(Debug)]
pub struct Room {
pub id: u64,
pub title: Option<SharedString>,
pub owner: Contact, // Owner always match current user
pub members: Vec<Contact>, // Extract from event's tags
pub last_seen: Timestamp,
pub is_group: bool,
pub new_messages: Vec<Event>, // Hold all new messages
}
impl PartialEq for Room {
fn eq(&self, other: &Self) -> bool {
let mut pubkeys: Vec<PublicKey> = self.members.iter().map(|m| m.public_key()).collect();
pubkeys.push(self.owner.public_key());
let mut pubkeys2: Vec<PublicKey> = other.members.iter().map(|m| m.public_key()).collect();
pubkeys2.push(other.owner.public_key());
compare(&pubkeys, &pubkeys2)
}
}
impl Room {
pub fn new(
id: u64,
owner: Contact,
members: Vec<Contact>,
title: Option<SharedString>,
last_seen: Timestamp,
) -> Self {
let is_group = members.len() > 1;
let title = if title.is_none() {
Some(random_name(2).into())
} else {
title
};
Self {
id,
owner,
members,
title,
last_seen,
is_group,
new_messages: vec![],
}
}
/// Convert nostr event to room
pub fn parse(event: &Event) -> Room {
let id = room_hash(&event.tags);
let last_seen = event.created_at;
let owner = Contact::new(event.pubkey, Metadata::default());
let members: Vec<Contact> = event
.tags
.public_keys()
.copied()
.map(|public_key| Contact::new(public_key, Metadata::default()))
.collect();
let title = if let Some(tag) = event.tags.find(TagKind::Title) {
tag.content().map(|s| s.to_owned().into())
} else {
None
};
Self::new(id, owner, members, title, last_seen)
}
/// Set contact's metadata by public key
pub fn set_metadata(&mut self, public_key: PublicKey, metadata: Metadata) {
if self.owner.public_key() == public_key {
self.owner.metadata(&metadata);
}
for member in self.members.iter_mut() {
if member.public_key() == public_key {
member.metadata(&metadata);
}
}
}
/// Get room's member by public key
pub fn member(&self, public_key: &PublicKey) -> Option<Contact> {
if &self.owner.public_key() == public_key {
Some(self.owner.clone())
} else {
self.members
.iter()
.find(|m| &m.public_key() == public_key)
.cloned()
}
}
/// Get room's display name
pub fn name(&self) -> String {
if self.members.len() <= 2 {
self.members
.iter()
.map(|profile| profile.name())
.collect::<Vec<String>>()
.join(", ")
} else {
let name = self
.members
.iter()
.take(2)
.map(|profile| profile.name())
.collect::<Vec<String>>()
.join(", ");
format!("{}, +{}", name, self.members.len() - 2)
}
}
/// Get all public keys from room's contacts
pub fn get_all_keys(&self) -> Vec<PublicKey> {
let mut pubkeys: Vec<_> = self.members.iter().map(|m| m.public_key()).collect();
pubkeys.push(self.owner.public_key());
pubkeys
}
}