chore: refactor chat registry

This commit is contained in:
2025-02-11 15:01:03 +07:00
parent 76d2c14870
commit 140a16e617
13 changed files with 297 additions and 319 deletions

2
crates/chats/src/lib.rs Normal file
View File

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

View File

@@ -0,0 +1,175 @@
use async_utility::tokio::sync::oneshot;
use common::utils::{compare, room_hash, signer_public_key};
use gpui::{App, AppContext, Context, Entity, Global};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use state::get_client;
use std::cmp::Reverse;
use crate::room::Room;
pub fn init(cx: &mut App) {
ChatRegistry::register(cx);
}
struct GlobalChatRegistry(Entity<ChatRegistry>);
impl Global for GlobalChatRegistry {}
pub struct ChatRegistry {
rooms: Vec<Entity<Room>>,
is_loading: bool,
}
impl ChatRegistry {
pub fn global(cx: &mut App) -> Option<Entity<Self>> {
cx.try_global::<GlobalChatRegistry>()
.map(|global| global.0.clone())
}
pub fn register(cx: &mut App) -> Entity<Self> {
Self::global(cx).unwrap_or_else(|| {
let entity = cx.new(Self::new);
// Set global state
cx.set_global(GlobalChatRegistry(entity.clone()));
// Observe and load metadata for any new rooms
cx.observe_new::<Room>(|this, _window, cx| {
let client = get_client();
let pubkeys = this.pubkeys();
let (tx, rx) = oneshot::channel::<Vec<(PublicKey, Metadata)>>();
cx.background_spawn(async move {
let mut profiles = Vec::new();
for public_key in pubkeys.into_iter() {
if let Ok(metadata) = client.database().metadata(public_key).await {
profiles.push((public_key, metadata.unwrap_or_default()));
}
}
_ = tx.send(profiles);
})
.detach();
cx.spawn(|this, mut cx| async move {
if let Ok(profiles) = rx.await {
if let Some(room) = this.upgrade() {
_ = cx.update_entity(&room, |this, cx| {
for profile in profiles.into_iter() {
this.set_metadata(profile.0, profile.1);
}
cx.notify();
});
}
}
})
.detach();
})
.detach();
entity
})
}
fn new(_cx: &mut Context<Self>) -> Self {
Self {
rooms: Vec::with_capacity(5),
is_loading: true,
}
}
pub fn current_rooms_ids(&self, cx: &mut Context<Self>) -> Vec<u64> {
self.rooms.iter().map(|room| room.read(cx).id).collect()
}
pub fn load_chat_rooms(&mut self, cx: &mut Context<Self>) {
let client = get_client();
let (tx, rx) = oneshot::channel::<Vec<Event>>();
cx.background_spawn(async move {
if let Ok(public_key) = signer_public_key(client).await {
let filter = Filter::new()
.kind(Kind::PrivateDirectMessage)
.author(public_key);
// Get all DM events from database
if let Ok(events) = client.database().query(filter).await {
let result: Vec<Event> = events
.into_iter()
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
.unique_by(room_hash)
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect();
_ = tx.send(result);
}
}
})
.detach();
cx.spawn(|this, cx| async move {
if let Ok(events) = rx.await {
_ = cx.update(|cx| {
_ = this.update(cx, |this, cx| {
let current_rooms = this.current_rooms_ids(cx);
let items: Vec<Entity<Room>> = events
.into_iter()
.filter_map(|ev| {
let new = room_hash(&ev);
// Filter all seen events
if !current_rooms.iter().any(|this| this == &new) {
Some(cx.new(|_| Room::parse(&ev)))
} else {
None
}
})
.collect();
this.rooms.extend(items);
this.is_loading = false;
cx.notify();
});
});
}
})
.detach();
}
pub fn rooms(&self) -> &Vec<Entity<Room>> {
&self.rooms
}
pub fn is_loading(&self) -> bool {
self.is_loading
}
pub fn get(&self, id: &u64, cx: &App) -> Option<Entity<Room>> {
self.rooms
.iter()
.find(|model| &model.read(cx).id == id)
.cloned()
}
pub fn push_message(&mut self, event: Event, cx: &mut Context<Self>) {
// Get all pubkeys from event's tags for comparision
let mut pubkeys: Vec<_> = event.tags.public_keys().copied().collect();
pubkeys.push(event.pubkey);
if let Some(room) = self
.rooms
.iter()
.find(|room| compare(&room.read(cx).pubkeys(), &pubkeys))
{
room.update(cx, |this, cx| {
this.last_seen.set(event.created_at);
this.new_messages.push(event);
cx.notify();
});
} else {
let room = cx.new(|_| Room::parse(&event));
self.rooms.insert(0, room);
cx.notify();
}
}
}

192
crates/chats/src/room.rs Normal file
View File

@@ -0,0 +1,192 @@
use chrono::{Datelike, Local, TimeZone};
use common::{
profile::NostrProfile,
utils::{compare, random_name, room_hash},
};
use gpui::SharedString;
use nostr_sdk::prelude::*;
use std::collections::HashSet;
pub struct LastSeen(pub Timestamp);
impl LastSeen {
pub fn ago(&self) -> SharedString {
let now = Local::now();
let input_time = Local.timestamp_opt(self.0.as_u64() as i64, 0).unwrap();
let diff = (now - input_time).num_hours();
if diff < 24 {
let duration = now.signed_duration_since(input_time);
if duration.num_seconds() < 60 {
"now".to_string().into()
} else if duration.num_minutes() == 1 {
"1m".to_string().into()
} else if duration.num_minutes() < 60 {
format!("{}m", duration.num_minutes()).into()
} else if duration.num_hours() == 1 {
"1h".to_string().into()
} else if duration.num_hours() < 24 {
format!("{}h", duration.num_hours()).into()
} else if duration.num_days() == 1 {
"1d".to_string().into()
} else {
format!("{}d", duration.num_days()).into()
}
} else {
input_time.format("%b %d").to_string().into()
}
}
pub fn human_readable(&self) -> SharedString {
let now = Local::now();
let input_time = Local.timestamp_opt(self.0.as_u64() as i64, 0).unwrap();
if input_time.day() == now.day() {
format!("Today at {}", input_time.format("%H:%M %p")).into()
} else if input_time.day() == now.day() - 1 {
format!("Yesterday at {}", input_time.format("%H:%M %p")).into()
} else {
format!(
"{}, {}",
input_time.format("%d/%m/%y"),
input_time.format("%H:%M %p")
)
.into()
}
}
pub fn set(&mut self, created_at: Timestamp) {
self.0 = created_at
}
}
pub struct Room {
pub id: u64,
pub title: Option<SharedString>,
pub owner: NostrProfile, // Owner always match current user
pub members: Vec<NostrProfile>, // Extract from event's tags
pub last_seen: LastSeen,
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: NostrProfile,
members: Vec<NostrProfile>,
title: Option<SharedString>,
last_seen: LastSeen,
) -> 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);
let last_seen = LastSeen(event.created_at);
// Always equal to current user
let owner = NostrProfile::new(event.pubkey, Metadata::default());
// Get all pubkeys that invole in this group
let members: Vec<NostrProfile> = event
.tags
.public_keys()
.collect::<HashSet<_>>()
.into_iter()
.map(|public_key| NostrProfile::new(*public_key, Metadata::default()))
.collect();
// Get title from event's tags
let title = if let Some(tag) = event.tags.find(TagKind::Subject) {
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.set_metadata(&metadata);
}
for member in self.members.iter_mut() {
if member.public_key() == public_key {
member.set_metadata(&metadata);
}
}
}
/// Get room's member by public key
pub fn member(&self, public_key: &PublicKey) -> Option<NostrProfile> {
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<_>>()
.join(", ")
} else {
let name = self
.members
.iter()
.take(2)
.map(|profile| profile.name())
.collect::<Vec<_>>()
.join(", ");
format!("{}, +{}", name, self.members.len() - 2)
}
}
/// Get all public keys from current room
pub fn pubkeys(&self) -> Vec<PublicKey> {
let mut pubkeys: Vec<_> = self.members.iter().map(|m| m.public_key()).collect();
pubkeys.push(self.owner.public_key());
pubkeys
}
}