feat: improve chat state
This commit is contained in:
@@ -1,9 +1,4 @@
|
||||
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 gpui::{Context, Entity};
|
||||
|
||||
use crate::room::Room;
|
||||
|
||||
@@ -20,36 +15,9 @@ impl Inbox {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_room_ids(&self, cx: &Context<Self>) -> Vec<u64> {
|
||||
pub fn 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 {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use anyhow::Error;
|
||||
use common::utils::{compare, room_hash};
|
||||
use async_utility::tokio::sync::oneshot;
|
||||
use common::utils::{compare, room_hash, signer_public_key};
|
||||
use gpui::{App, AppContext, Entity, Global, WeakEntity, Window};
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
use state::get_client;
|
||||
use std::cmp::Reverse;
|
||||
|
||||
use crate::{inbox::Inbox, room::Room};
|
||||
|
||||
@@ -18,34 +20,30 @@ impl ChatRegistry {
|
||||
|
||||
cx.observe_new::<Room>(|this, _window, cx| {
|
||||
// Get all pubkeys to load metadata
|
||||
let pubkeys = this.get_pubkeys();
|
||||
let pubkeys = this.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();
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
let (tx, rx) = oneshot::channel::<Vec<(PublicKey, Metadata)>>();
|
||||
|
||||
for public_key in pubkeys.into_iter() {
|
||||
let metadata = client
|
||||
.database()
|
||||
.metadata(public_key)
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
cx.background_spawn(async move {
|
||||
let client = get_client();
|
||||
let mut profiles = Vec::new();
|
||||
|
||||
profiles.push((public_key, metadata));
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(profiles)
|
||||
})
|
||||
.await;
|
||||
_ = tx.send(profiles);
|
||||
})
|
||||
.detach();
|
||||
|
||||
if let Ok(profiles) = query {
|
||||
if let Some(model) = weak_model.upgrade() {
|
||||
_ = async_cx.update_entity(&model, |model, cx| {
|
||||
if let Ok(profiles) = rx.await {
|
||||
if let Some(room) = this.upgrade() {
|
||||
_ = cx.update_entity(&room, |this, cx| {
|
||||
for profile in profiles.into_iter() {
|
||||
model.set_metadata(profile.0, profile.1);
|
||||
this.set_metadata(profile.0, profile.1);
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
@@ -61,38 +59,60 @@ impl ChatRegistry {
|
||||
|
||||
pub fn load(&mut self, window: &mut Window, cx: &mut App) {
|
||||
let window_handle = window.window_handle();
|
||||
let inbox = self.inbox.downgrade();
|
||||
|
||||
self.inbox.update(cx, |this, cx| {
|
||||
let task = this.load(cx.to_async());
|
||||
cx.spawn(|mut cx| async move {
|
||||
let (tx, rx) = oneshot::channel::<Vec<Event>>();
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if let Ok(events) = task.await {
|
||||
_ = cx.update_window(window_handle, |_, _, cx| {
|
||||
_ = this.update(cx, |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();
|
||||
cx.background_spawn(async move {
|
||||
let client = get_client();
|
||||
|
||||
this.rooms.extend(items);
|
||||
this.is_loading = false;
|
||||
if let Ok(public_key) = signer_public_key(client).await {
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.author(public_key);
|
||||
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
// 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();
|
||||
});
|
||||
|
||||
if let Ok(events) = rx.await {
|
||||
_ = cx.update_window(window_handle, |_, _, cx| {
|
||||
_ = inbox.update(cx, |this, cx| {
|
||||
let current_rooms = this.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 inbox(&self) -> WeakEntity<Inbox> {
|
||||
@@ -121,7 +141,6 @@ impl ChatRegistry {
|
||||
|
||||
pub fn new_room_message(&mut self, event: Event, window: &mut Window, cx: &mut App) {
|
||||
let window_handle = window.window_handle();
|
||||
|
||||
// Get all pubkeys from event's tags for comparision
|
||||
let mut pubkeys: Vec<_> = event.tags.public_keys().copied().collect();
|
||||
pubkeys.push(event.pubkey);
|
||||
@@ -131,14 +150,14 @@ impl ChatRegistry {
|
||||
.read(cx)
|
||||
.rooms
|
||||
.iter()
|
||||
.find(|room| compare(&room.read(cx).get_pubkeys(), &pubkeys))
|
||||
.find(|room| compare(&room.read(cx).pubkeys(), &pubkeys))
|
||||
{
|
||||
let weak_room = room.downgrade();
|
||||
let this = room.downgrade();
|
||||
|
||||
cx.spawn(|mut cx| async move {
|
||||
if let Err(e) = cx.update_window(window_handle, |_, _, cx| {
|
||||
_ = weak_room.update(cx, |this, cx| {
|
||||
this.last_seen = event.created_at;
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.last_seen.set(event.created_at);
|
||||
this.new_messages.push(event);
|
||||
|
||||
cx.notify();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use chrono::{Datelike, Local, TimeZone};
|
||||
use common::{
|
||||
profile::NostrProfile,
|
||||
utils::{compare, random_name, room_hash},
|
||||
@@ -6,13 +7,66 @@ use gpui::SharedString;
|
||||
use nostr_sdk::prelude::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Debug)]
|
||||
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: Timestamp,
|
||||
pub last_seen: LastSeen,
|
||||
pub is_group: bool,
|
||||
pub new_messages: Vec<Event>, // Hold all new messages
|
||||
}
|
||||
@@ -35,7 +89,7 @@ impl Room {
|
||||
owner: NostrProfile,
|
||||
members: Vec<NostrProfile>,
|
||||
title: Option<SharedString>,
|
||||
last_seen: Timestamp,
|
||||
last_seen: LastSeen,
|
||||
) -> Self {
|
||||
let is_group = members.len() > 1;
|
||||
let title = if title.is_none() {
|
||||
@@ -57,8 +111,8 @@ impl Room {
|
||||
|
||||
/// Convert nostr event to room
|
||||
pub fn parse(event: &Event) -> Room {
|
||||
let id = room_hash(&event.tags);
|
||||
let last_seen = event.created_at;
|
||||
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());
|
||||
@@ -73,7 +127,7 @@ impl Room {
|
||||
.collect();
|
||||
|
||||
// Get title from event's tags
|
||||
let title = if let Some(tag) = event.tags.find(TagKind::Title) {
|
||||
let title = if let Some(tag) = event.tags.find(TagKind::Subject) {
|
||||
tag.content().map(|s| s.to_owned().into())
|
||||
} else {
|
||||
None
|
||||
@@ -113,7 +167,7 @@ impl Room {
|
||||
self.members
|
||||
.iter()
|
||||
.map(|profile| profile.name())
|
||||
.collect::<Vec<String>>()
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
} else {
|
||||
let name = self
|
||||
@@ -121,15 +175,15 @@ impl Room {
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|profile| profile.name())
|
||||
.collect::<Vec<String>>()
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
format!("{}, +{}", name, self.members.len() - 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all public keys from room's contacts
|
||||
pub fn get_pubkeys(&self) -> Vec<PublicKey> {
|
||||
/// 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());
|
||||
|
||||
|
||||
Reference in New Issue
Block a user