wip: refactor
This commit is contained in:
15
crates/chat/Cargo.toml
Normal file
15
crates/chat/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "chat"
|
||||
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
|
||||
smol.workspace = true
|
||||
59
crates/chat/src/inbox.rs
Normal file
59
crates/chat/src/inbox.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use common::utils::room_hash;
|
||||
use gpui::{AsyncApp, Context, Entity, Task};
|
||||
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<Entity<Room>>,
|
||||
pub is_loading: bool,
|
||||
}
|
||||
|
||||
impl Inbox {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
rooms: vec![],
|
||||
is_loading: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_room_ids(&self, cx: &Context<Self>) -> Vec<u64> {
|
||||
self.rooms.iter().map(|room| room.read(cx).id).collect()
|
||||
}
|
||||
|
||||
pub fn load(&mut self, cx: AsyncApp) -> Task<Result<Vec<Event>, Error>> {
|
||||
cx.background_executor().spawn(async move {
|
||||
let client = get_client();
|
||||
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(filter).await?;
|
||||
|
||||
// Filter result
|
||||
// - Get unique rooms only
|
||||
// - 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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Inbox {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
3
crates/chat/src/lib.rs
Normal file
3
crates/chat/src/lib.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod inbox;
|
||||
pub mod registry;
|
||||
pub mod room;
|
||||
142
crates/chat/src/registry.rs
Normal file
142
crates/chat/src/registry.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
use anyhow::Error;
|
||||
use common::utils::{compare, room_hash};
|
||||
use gpui::{App, AppContext, Entity, Global, WeakEntity};
|
||||
use nostr_sdk::prelude::*;
|
||||
use state::get_client;
|
||||
|
||||
use crate::{inbox::Inbox, room::Room};
|
||||
|
||||
pub struct ChatRegistry {
|
||||
inbox: Entity<Inbox>,
|
||||
}
|
||||
|
||||
impl Global for ChatRegistry {}
|
||||
|
||||
impl ChatRegistry {
|
||||
pub fn set_global(cx: &mut App) {
|
||||
let inbox = cx.new(|_| Inbox::default());
|
||||
|
||||
cx.observe_new::<Room>(|this, _window, cx| {
|
||||
// Get all pubkeys to load metadata
|
||||
let pubkeys = this.get_pubkeys();
|
||||
|
||||
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_entity(&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 load(&mut self, cx: &mut App) {
|
||||
self.inbox.update(cx, |this, cx| {
|
||||
let task = this.load(cx.to_async());
|
||||
|
||||
cx.spawn(|this, mut async_cx| async move {
|
||||
if let Some(inbox) = this.upgrade() {
|
||||
if let Ok(events) = task.await {
|
||||
_ = async_cx.update_entity(&inbox, |this, cx| {
|
||||
let current_rooms = this.get_room_ids(cx);
|
||||
let items: Vec<Entity<Room>> = events
|
||||
.into_iter()
|
||||
.filter_map(|ev| {
|
||||
let id = room_hash(&ev.tags);
|
||||
// Filter all seen events
|
||||
if !current_rooms.iter().any(|h| h == &id) {
|
||||
Some(cx.new(|_| Room::parse(&ev)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
this.rooms.extend(items);
|
||||
this.is_loading = false;
|
||||
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
}
|
||||
|
||||
pub fn inbox(&self) -> WeakEntity<Inbox> {
|
||||
self.inbox.downgrade()
|
||||
}
|
||||
|
||||
pub fn get_room(&self, id: &u64, cx: &App) -> Option<WeakEntity<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 App) {
|
||||
let room = cx.new(|_| 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 new_room_message(&mut self, event: Event, cx: &mut App) {
|
||||
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_pubkeys();
|
||||
compare(&all_keys, &pubkeys)
|
||||
}) {
|
||||
room.update(cx, |this, cx| {
|
||||
this.new_messages.push(event);
|
||||
cx.notify();
|
||||
})
|
||||
} else {
|
||||
let room = cx.new(|_| Room::parse(&event));
|
||||
|
||||
self.inbox.update(cx, |this, cx| {
|
||||
this.rooms.insert(0, room);
|
||||
cx.notify();
|
||||
})
|
||||
}
|
||||
|
||||
cx.notify();
|
||||
})
|
||||
}
|
||||
}
|
||||
132
crates/chat/src/room.rs
Normal file
132
crates/chat/src/room.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
use common::{
|
||||
profile::NostrProfile,
|
||||
utils::{compare, random_name, room_hash},
|
||||
};
|
||||
use gpui::SharedString;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
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: 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: NostrProfile,
|
||||
members: Vec<NostrProfile>,
|
||||
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 = NostrProfile::new(event.pubkey, Metadata::default());
|
||||
let members: Vec<NostrProfile> = event
|
||||
.tags
|
||||
.public_keys()
|
||||
.copied()
|
||||
.map(|public_key| NostrProfile::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<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<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_pubkeys(&self) -> Vec<PublicKey> {
|
||||
let mut pubkeys: Vec<_> = self.members.iter().map(|m| m.public_key()).collect();
|
||||
pubkeys.push(self.owner.public_key());
|
||||
|
||||
pubkeys
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user