feat: revamp the chat panel ui #7

Merged
reya merged 9 commits from revamp-chat-ui into master 2026-02-19 07:25:08 +00:00
13 changed files with 610 additions and 569 deletions
Showing only changes of commit 452253bece - Show all commits

52
Cargo.lock generated
View File

@@ -1193,7 +1193,7 @@ dependencies = [
[[package]]
name = "collections"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"indexmap",
"rustc-hash 2.1.1",
@@ -1638,7 +1638,7 @@ dependencies = [
[[package]]
name = "derive_refineable"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"proc-macro2",
"quote",
@@ -2589,7 +2589,7 @@ dependencies = [
[[package]]
name = "gpui"
version = "0.2.2"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"as-raw-xcb-connection",
@@ -2689,7 +2689,7 @@ dependencies = [
[[package]]
name = "gpui_macros"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -2700,7 +2700,7 @@ dependencies = [
[[package]]
name = "gpui_tokio"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"gpui",
@@ -2929,7 +2929,7 @@ dependencies = [
[[package]]
name = "http_client"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"async-compression",
@@ -2954,7 +2954,7 @@ dependencies = [
[[package]]
name = "http_client_tls"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"rustls",
"rustls-platform-verifier",
@@ -3735,7 +3735,7 @@ dependencies = [
[[package]]
name = "media"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"bindgen",
@@ -3994,7 +3994,7 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]]
name = "nostr"
version = "0.44.1"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"aes",
"base64",
@@ -4019,7 +4019,7 @@ dependencies = [
[[package]]
name = "nostr-connect"
version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"async-utility",
"futures-core",
@@ -4032,7 +4032,7 @@ dependencies = [
[[package]]
name = "nostr-database"
version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"btreecap",
"flatbuffers",
@@ -4044,7 +4044,7 @@ dependencies = [
[[package]]
name = "nostr-gossip"
version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"nostr",
]
@@ -4052,7 +4052,7 @@ dependencies = [
[[package]]
name = "nostr-gossip-memory"
version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"indexmap",
"lru",
@@ -4064,7 +4064,7 @@ dependencies = [
[[package]]
name = "nostr-lmdb"
version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"async-utility",
"flume",
@@ -4078,7 +4078,7 @@ dependencies = [
[[package]]
name = "nostr-sdk"
version = "0.44.1"
source = "git+https://github.com/rust-nostr/nostr#8410867ef02376a5bd7c7ec3f2af46a1c276a2f4"
source = "git+https://github.com/rust-nostr/nostr#07de813024f930803a1dd81942edb50eb8a87ba3"
dependencies = [
"async-utility",
"async-wsocket",
@@ -4552,7 +4552,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "perf"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"collections",
"serde",
@@ -5228,7 +5228,7 @@ dependencies = [
[[package]]
name = "refineable"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"derive_refineable",
]
@@ -5333,7 +5333,7 @@ dependencies = [
[[package]]
name = "reqwest_client"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"bytes",
@@ -5388,7 +5388,7 @@ dependencies = [
[[package]]
name = "rope"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"arrayvec",
"log",
@@ -5650,7 +5650,7 @@ dependencies = [
[[package]]
name = "scheduler"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"async-task",
"backtrace",
@@ -6231,7 +6231,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "sum_tree"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"arrayvec",
"log",
@@ -7187,7 +7187,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "util"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"async-fs",
@@ -7225,7 +7225,7 @@ dependencies = [
[[package]]
name = "util_macros"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"perf",
"quote",
@@ -9033,7 +9033,7 @@ dependencies = [
[[package]]
name = "zlog"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"anyhow",
"chrono",
@@ -9050,7 +9050,7 @@ checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "ztracing"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
dependencies = [
"tracing",
"tracing-subscriber",
@@ -9061,7 +9061,7 @@ dependencies = [
[[package]]
name = "ztracing_macro"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#b90a370c864a76dc53bc19b650a2a07fbb36b043"
source = "git+https://github.com/zed-industries/zed#e4f2492099cf76bc1eb1eda56eaf56ecf6fadbf8"
[[package]]
name = "zune-core"

View File

@@ -97,12 +97,10 @@ impl ChatRegistry {
/// Create a new chat registry instance
fn new(cx: &mut Context<Self>) -> Self {
let device = DeviceRegistry::global(cx);
let nostr = NostrRegistry::global(cx);
let nip17_state = nostr.read(cx).nip17_state();
let device = DeviceRegistry::global(cx);
let device_signer = device.read(cx).device_signer.clone();
// A flag to indicate if the registry is loading
let tracking_flag = Arc::new(AtomicBool::new(false));
@@ -128,8 +126,8 @@ impl ChatRegistry {
subscriptions.push(
// Observe the device signer state
cx.observe(&device_signer, |this, state, cx| {
if state.read(cx).is_some() {
cx.observe(&device, |this, state, cx| {
if state.read(cx).state().set() {
this.handle_notifications(cx);
}
}),
@@ -180,9 +178,7 @@ impl ChatRegistry {
fn handle_notifications(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let device = DeviceRegistry::global(cx);
let device_signer = device.read(cx).signer(cx);
let signer = nostr.read(cx).signer();
let status = self.tracking_flag.clone();
let tx = self.sender.clone();
@@ -191,6 +187,7 @@ impl ChatRegistry {
let initialized_at = Timestamp::now();
let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP);
let sub_id2 = SubscriptionId::new(USER_GIFTWRAP);
let device_signer = signer.get_encryption_signer().await;
let mut notifications = client.notifications();
let mut processed_events = HashSet::new();

View File

@@ -6,8 +6,8 @@ use nostr_sdk::prelude::*;
/// New message.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NewMessage {
pub gift_wrap: EventId,
pub room: u64,
pub gift_wrap: EventId,
pub rumor: UnsignedEvent,
}
@@ -16,8 +16,8 @@ impl NewMessage {
let room = rumor.uniq_id();
Self {
gift_wrap,
room,
gift_wrap,
rumor,
}
}

View File

@@ -1,5 +1,4 @@
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::time::Duration;
@@ -9,72 +8,47 @@ use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use person::{Person, PersonRegistry};
use state::{tracker, NostrRegistry};
use settings::{RoomConfig, SignerKind};
use state::{NostrRegistry, TIMEOUT};
use crate::{ChatRegistry, NewMessage};
const SEND_RETRY: usize = 10;
#[derive(Debug, Clone)]
pub struct SendReport {
pub receiver: PublicKey,
pub status: Option<Output<EventId>>,
pub error: Option<SharedString>,
pub on_hold: Option<Event>,
pub encryption: bool,
pub relays_not_found: bool,
pub device_not_found: bool,
pub output: Option<Output<EventId>>,
}
impl SendReport {
pub fn new(receiver: PublicKey) -> Self {
Self {
receiver,
status: None,
error: None,
on_hold: None,
encryption: false,
relays_not_found: false,
device_not_found: false,
output: None,
}
}
pub fn status(mut self, output: Output<EventId>) -> Self {
self.status = Some(output);
pub fn output(mut self, output: Output<EventId>) -> Self {
self.output = Some(output);
self
}
pub fn error(mut self, error: impl Into<SharedString>) -> Self {
pub fn error<T>(mut self, error: T) -> Self
where
T: Into<SharedString>,
{
self.error = Some(error.into());
self
}
pub fn on_hold(mut self, event: Event) -> Self {
self.on_hold = Some(event);
self
}
pub fn encryption(mut self) -> Self {
self.encryption = true;
self
}
pub fn relays_not_found(mut self) -> Self {
self.relays_not_found = true;
self
}
pub fn device_not_found(mut self) -> Self {
self.device_not_found = true;
self
}
pub fn is_relay_error(&self) -> bool {
self.error.is_some() || self.relays_not_found
self.error.is_some()
}
pub fn is_sent_success(&self) -> bool {
if let Some(output) = self.status.as_ref() {
if let Some(output) = self.output.as_ref() {
!output.success.is_empty()
} else {
false
@@ -115,6 +89,9 @@ pub struct Room {
/// Kind
pub kind: RoomKind,
/// Configuration
config: RoomConfig,
}
impl Ord for Room {
@@ -161,6 +138,7 @@ impl From<&UnsignedEvent> for Room {
subject,
members,
kind: RoomKind::default(),
config: RoomConfig::default(),
}
}
}
@@ -320,21 +298,17 @@ impl Room {
}
/// Get gossip relays for each member
pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> {
pub fn early_connect(&self, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let members = self.members();
let id = SubscriptionId::new(format!("room-{}", self.id));
let subscription_id = SubscriptionId::new(format!("room-{}", self.id));
cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.timeout(Some(Duration::from_secs(2)))
.exit_policy(ReqExitPolicy::ExitOnEOSE);
for member in members.into_iter() {
if member == public_key {
continue;
@@ -346,8 +320,12 @@ impl Room {
// Subscribe to get member's gossip relays
client
.subscribe(filter)
.close_on(opts)
.with_id(id.clone())
.with_id(subscription_id.clone())
.close_on(
SubscribeAutoCloseOptions::default()
.timeout(Some(Duration::from_secs(TIMEOUT)))
.exit_policy(ReqExitPolicy::ExitOnEOSE),
)
.await?;
}
@@ -379,7 +357,138 @@ impl Room {
})
}
/// Create a new unsigned message event
/// Construct extra tags for a message
fn extra_tags(&self, sender: PublicKey, members: &[Person], replies: &[EventId]) -> Vec<Tag> {
let mut extra_tags = vec![];
// Add subject tag if present
if let Some(value) = self.subject.as_ref() {
extra_tags.push(Tag::from_standardized_without_cell(TagStandard::Subject(
value.to_string(),
)));
}
// Add all reply tags
for id in replies {
extra_tags.push(Tag::event(*id))
}
// Add all receiver tags
for member in members.iter() {
// Skip current user
if member.public_key() == sender {
continue;
}
extra_tags.push(Tag::from_standardized_without_cell(
TagStandard::PublicKey {
public_key: member.public_key(),
relay_url: member.messaging_relay_hint(),
alias: None,
uppercase: false,
},
));
}
extra_tags
}
pub fn send<S, I>(&self, content: S, replies: I, cx: &App) -> Option<Task<Vec<SendReport>>>
where
S: Into<String>,
I: IntoIterator<Item = EventId>,
{
let persons = PersonRegistry::global(cx);
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let content: String = content.into();
let replies: Vec<EventId> = replies.into_iter().collect();
// Get current user's public key
let sender = nostr.read(cx).signer().public_key()?;
// get room's config
let config = self.config.clone();
// Get all members
let members: Vec<Person> = self
.members
.iter()
.filter(|public_key| public_key != &&sender)
.map(|member| persons.read(cx).get(member, cx))
.collect();
// Get extra tags
let extra_tags = self.extra_tags(sender, &members, &replies);
Some(cx.background_spawn(async move {
let signer_kind = config.signer_kind();
let backup = config.backup();
// Get all available signers
let user_signer = signer.get().await;
let encryption_signer = signer.get_encryption_signer().await;
let mut reports: Vec<SendReport> = vec![];
for member in members.into_iter() {
// Skip if member has no messaging relays
if member.messaging_relays().is_empty() {
let report = SendReport::new(member.public_key()).error("No messaging relays");
reports.push(report);
continue;
}
// When the room is forced to use an encryption signer,
// skip if the receiver has not set up an encryption signer.
if signer_kind.encryption() && member.announcement().is_none() {
let report = SendReport::new(member.public_key()).error("Encryption not found");
reports.push(report);
continue;
}
let (receiver, signer) = match signer_kind {
SignerKind::Auto => {
if let Some(announcement) = member.announcement() {
if let Some(enc_signer) = encryption_signer.as_ref() {
(announcement.public_key(), enc_signer.clone())
} else {
(member.public_key(), user_signer.clone())
}
} else {
(member.public_key(), user_signer.clone())
}
}
SignerKind::Encryption => {
let Some(encryption_signer) = encryption_signer.as_ref() else {
let report =
SendReport::new(member.public_key()).error("Encryption not found");
reports.push(report);
continue;
};
let Some(announcement) = member.announcement() else {
let report = SendReport::new(member.public_key())
.error("Announcement not found");
reports.push(report);
continue;
};
(announcement.public_key(), encryption_signer.clone())
}
SignerKind::User => (member.public_key(), user_signer.clone()),
};
}
reports
}))
}
/*
* /// Create a new unsigned message event
pub fn create_message(
&self,
content: &str,
@@ -444,7 +553,7 @@ impl Room {
// WARNING: never sign and send this event to relays
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, content)
.tags(tags)
.build(Keys::generate().public_key());
.build(public_key);
// Ensure the event ID has been generated
event.ensure_id();
@@ -594,4 +703,5 @@ impl Room {
Ok(resend_reports)
})
}
*/
}

View File

@@ -10,8 +10,8 @@ use gpui::{
div, img, list, px, red, relative, rems, svg, white, AnyElement, App, AppContext,
ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
IntoElement, ListAlignment, ListOffset, ListState, MouseButton, ObjectFit, ParentElement,
PathPromptOptions, Render, RetainAllImageCache, SharedString, StatefulInteractiveElement,
Styled, StyledImage, Subscription, Task, WeakEntity, Window,
PathPromptOptions, Render, SharedString, StatefulInteractiveElement, Styled, StyledImage,
Subscription, Task, WeakEntity, Window,
};
use gpui_tokio::Tokio;
use indexset::{BTreeMap, BTreeSet};
@@ -47,7 +47,6 @@ pub fn init(room: WeakEntity<Room>, window: &mut Window, cx: &mut App) -> Entity
pub struct ChatPanel {
id: SharedString,
focus_handle: FocusHandle,
image_cache: Entity<RetainAllImageCache>,
/// Chat Room
room: WeakEntity<Room>,
@@ -77,14 +76,22 @@ pub struct ChatPanel {
uploading: bool,
/// Async operations
tasks: SmallVec<[Task<()>; 2]>,
tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
/// Event subscriptions
_subscriptions: SmallVec<[Subscription; 2]>,
subscriptions: SmallVec<[Subscription; 2]>,
}
impl ChatPanel {
pub fn new(room: WeakEntity<Room>, window: &mut Window, cx: &mut Context<Self>) -> Self {
// Define attachments and replies_to entities
let attachments = cx.new(|_| vec![]);
let replies_to = cx.new(|_| HashSet::new());
// Define list of messages
let messages = BTreeSet::from([Message::system()]);
let list_state = ListState::new(messages.len(), ListAlignment::Bottom, px(1024.));
// Get room id and name
let (id, name) = room
.read_with(cx, |this, _cx| {
@@ -104,74 +111,24 @@ impl ChatPanel {
.clean_on_escape()
});
// Define attachments and replies_to entities
let attachments = cx.new(|_| vec![]);
let replies_to = cx.new(|_| HashSet::new());
// Define list of messages
let messages = BTreeSet::from([Message::system()]);
let list_state = ListState::new(messages.len(), ListAlignment::Bottom, px(1024.));
let mut subscriptions = smallvec![];
let mut tasks = smallvec![];
if let Some(room) = room.upgrade() {
let connect = room.read(cx).connect(cx);
let get_messages = room.read(cx).get_messages(cx);
tasks.push(
// Get messaging relays and encryption keys announcement for each member
cx.background_spawn(async move {
if let Err(e) = connect.await {
log::error!("Failed to initialize room: {}", e);
}
}),
);
tasks.push(
// Load all messages belonging to this room
cx.spawn_in(window, async move |this, cx| {
let result = get_messages.await;
this.update_in(cx, |this, window, cx| {
match result {
Ok(events) => {
this.insert_messages(&events, cx);
}
Err(e) => {
window.push_notification(e.to_string(), cx);
}
};
})
.ok();
}),
);
subscriptions.push(
// Subscribe to room events
cx.subscribe_in(&room, window, move |this, _room, event, window, cx| {
match event {
RoomEvent::Incoming(message) => {
this.insert_message(message, false, cx);
}
RoomEvent::Reload => {
this.load_messages(window, cx);
}
};
}),
);
}
subscriptions.push(
// Subscribe to input events
// Define subscriptions
let subscriptions =
smallvec![
cx.subscribe_in(&input, window, move |this, _input, event, window, cx| {
if let InputEvent::PressEnter { .. } = event {
this.send_input_message(window, cx);
this.send_text_message(window, cx);
};
}),
);
})
];
// Define all functions that will run after the current cycle
cx.defer_in(window, |this, window, cx| {
this.subscribe_room_events(window, cx);
this.get_messages(window, cx);
});
Self {
focus_handle: cx.focus_handle(),
id,
messages,
room,
@@ -182,33 +139,48 @@ impl ChatPanel {
rendered_texts_by_id: BTreeMap::new(),
reports_by_id: BTreeMap::new(),
uploading: false,
image_cache: RetainAllImageCache::new(cx),
focus_handle: cx.focus_handle(),
_subscriptions: subscriptions,
tasks,
subscriptions,
tasks: smallvec![],
}
}
fn subscribe_room_events(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(room) = self.room.upgrade() else {
return;
};
self.subscriptions.push(
// Subscribe to room events
cx.subscribe_in(&room, window, move |this, _room, event, window, cx| {
match event {
RoomEvent::Incoming(message) => {
this.insert_message(message, false, cx);
}
RoomEvent::Reload => {
this.get_messages(window, cx);
}
};
}),
);
}
/// Load all messages belonging to this room
fn load_messages(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Ok(get_messages) = self.room.read_with(cx, |this, cx| this.get_messages(cx)) {
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
let result = get_messages.await;
this.update_in(cx, |this, window, cx| {
match result {
Ok(events) => {
this.insert_messages(&events, cx);
}
Err(e) => {
window.push_notification(Notification::error(e.to_string()), cx);
}
fn get_messages(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
let Ok(get_messages) = self.room.read_with(cx, |this, cx| this.get_messages(cx)) else {
return;
};
})
.ok();
self.tasks.push(cx.spawn(async move |this, cx| {
let events = get_messages.await?;
// Update message list
this.update(cx, |this, cx| {
this.insert_messages(&events, cx);
})?;
Ok(())
}));
}
}
/// Get user input content and merged all attachments
fn get_input_value(&self, cx: &Context<Self>) -> String {
@@ -235,7 +207,7 @@ impl ChatPanel {
content
}
fn send_input_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
fn send_text_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// Get the message which includes all attachments
let content = self.get_input_value(cx);
@@ -250,81 +222,13 @@ impl ChatPanel {
/// Send a message to all members of the chat
fn send_message(&mut self, value: &str, window: &mut Window, cx: &mut Context<Self>) {
// Get replies_to if it's present
let replies: Vec<EventId> = self.replies_to.read(cx).iter().copied().collect();
// TODO
}
// Get a task to create temporary message for optimistic update
let Ok(get_rumor) = self
.room
.read_with(cx, |this, cx| this.create_message(value, replies, cx))
else {
return;
};
// Optimistically update message list
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let mut rumor = get_rumor.await?;
let rumor_id = rumor.id();
// Update the message list and reset the states
this.update_in(cx, |this, window, cx| {
this.remove_all_replies(cx);
this.remove_all_attachments(cx);
// Reset the input to its default state
this.input.update(cx, |this, cx| {
this.set_loading(false, cx);
this.set_disabled(false, cx);
this.set_value("", window, cx);
});
// Update the message list
this.insert_message(&rumor, true, cx);
if let Ok(task) = this
.room
.read_with(cx, |this, cx| this.send_message(&rumor, cx))
{
this.tasks.push(cx.spawn_in(window, async move |this, cx| {
let result = task.await;
this.update_in(cx, |this, window, cx| {
match result {
Ok(reports) => {
// Update room's status
this.room
.update(cx, |this, cx| {
if this.kind != RoomKind::Ongoing {
// Update the room kind to ongoing,
// but keep the room kind if send failed
if reports.iter().all(|r| !r.is_sent_success()) {
this.kind = RoomKind::Ongoing;
fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) {
self.reports_by_id.insert(id, reports);
cx.notify();
}
}
})
.ok();
// Insert the sent reports
this.reports_by_id.insert(rumor_id, reports);
cx.notify();
}
Err(e) => {
window.push_notification(e.to_string(), cx);
}
}
})
.ok();
}))
}
})?;
Ok(())
});
task.detach();
}
/// Insert a message into the chat panel
fn insert_message<E>(&mut self, m: E, scroll: bool, cx: &mut Context<Self>)
@@ -749,7 +653,8 @@ impl ChatPanel {
let mut items = Vec::with_capacity(reports.len());
for report in reports.iter() {
items.push(Self::render_report(report, cx))
//items.push(Self::render_report(report, cx))
items.push(div())
}
items
@@ -781,7 +686,8 @@ impl ChatPanel {
let mut items = Vec::with_capacity(reports.len());
for report in reports.iter() {
items.push(Self::render_report(report, cx))
//items.push(Self::render_report(report, cx))
items.push(div())
}
items
@@ -791,6 +697,7 @@ impl ChatPanel {
})
}
/*
fn render_report(report: &SendReport, cx: &App) -> impl IntoElement {
let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&report.receiver, cx);
@@ -940,6 +847,7 @@ impl ChatPanel {
)
})
}
*/
fn render_border(&self, cx: &Context<Self>) -> impl IntoElement {
div()
@@ -1174,7 +1082,6 @@ impl Render for ChatPanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.on_action(cx.listener(Self::on_command))
.image_cache(self.image_cache.clone())
.size_full()
.child(
list(
@@ -1246,7 +1153,7 @@ impl Render for ChatPanel {
.ghost()
.large()
.on_click(cx.listener(move |this, _ev, window, cx| {
this.send_input_message(window, cx);
this.send_text_message(window, cx);
})),
),
),

View File

@@ -84,7 +84,7 @@ fn main() {
// Initialize device signer
//
// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
device::init(cx);
device::init(window, cx);
// Initialize settings
settings::init(cx);

View File

@@ -1,12 +1,11 @@
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::collections::HashSet;
use std::time::Duration;
use anyhow::{anyhow, Context as AnyhowContext, Error};
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task, Window};
use nostr_sdk::prelude::*;
use smallvec::{smallvec, SmallVec};
use state::{app_name, NostrRegistry, RelayState, DEVICE_GIFTWRAP, TIMEOUT, USER_GIFTWRAP};
use state::{app_name, NostrRegistry, RelayState, TIMEOUT};
mod device;
@@ -14,8 +13,8 @@ pub use device::*;
const IDENTIFIER: &str = "coop:device";
pub fn init(cx: &mut App) {
DeviceRegistry::set_global(cx.new(DeviceRegistry::new), cx);
pub fn init(window: &mut Window, cx: &mut App) {
DeviceRegistry::set_global(cx.new(|cx| DeviceRegistry::new(window, cx)), cx);
}
struct GlobalDeviceRegistry(Entity<DeviceRegistry>);
@@ -27,11 +26,8 @@ impl Global for GlobalDeviceRegistry {}
/// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
#[derive(Debug)]
pub struct DeviceRegistry {
/// Device signer
pub device_signer: Entity<Option<Arc<dyn NostrSigner>>>,
/// Device state
pub state: DeviceState,
state: DeviceState,
/// Device requests
requests: Entity<HashSet<Event>>,
@@ -40,7 +36,7 @@ pub struct DeviceRegistry {
tasks: Vec<Task<Result<(), Error>>>,
/// Subscriptions
_subscriptions: SmallVec<[Subscription; 2]>,
_subscriptions: SmallVec<[Subscription; 1]>,
}
impl DeviceRegistry {
@@ -55,20 +51,14 @@ impl DeviceRegistry {
}
/// Create a new device registry instance
fn new(cx: &mut Context<Self>) -> Self {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let nip65_state = nostr.read(cx).nip65_state();
let nip17_state = nostr.read(cx).nip17_state();
let device_signer = cx.new(|_| None);
// Construct an entity for encryption signer requests
let requests = cx.new(|_| HashSet::default());
// Channel for communication between nostr and gpui
let (tx, rx) = flume::bounded::<Event>(100);
let mut subscriptions = smallvec![];
let mut tasks = vec![];
subscriptions.push(
// Observe the NIP-65 state
@@ -85,21 +75,57 @@ impl DeviceRegistry {
}),
);
subscriptions.push(
// Observe the NIP-17 state
cx.observe(&nip17_state, |this, state, cx| {
if state.read(cx) == &RelayState::Configured {
this.get_messages(cx);
};
}),
);
cx.defer_in(window, |this, _window, cx| {
this.handle_notifications(cx);
});
tasks.push(
// Handle nostr notifications
cx.background_spawn(async move { Self::handle_notifications(&client, &tx).await }),
);
Self {
state: DeviceState::default(),
requests,
tasks: vec![],
_subscriptions: subscriptions,
}
}
tasks.push(
fn handle_notifications(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let (tx, rx) = flume::bounded::<Event>(100);
cx.background_spawn(async move {
let mut notifications = client.notifications();
let mut processed_events = HashSet::new();
while let Some(notification) = notifications.next().await {
if let ClientNotification::Message {
message: RelayMessage::Event { event, .. },
..
} = notification
{
if !processed_events.insert(event.id) {
// Skip if the event has already been processed
continue;
}
match event.kind {
Kind::Custom(4454) => {
if verify_author(&client, event.as_ref()).await {
tx.send_async(event.into_owned()).await.ok();
}
}
Kind::Custom(4455) => {
if verify_author(&client, event.as_ref()).await {
tx.send_async(event.into_owned()).await.ok();
}
}
_ => {}
}
}
}
})
.detach();
self.tasks.push(
// Update GPUI states
cx.spawn(async move |this, cx| {
while let Ok(event) = rx.recv_async().await {
@@ -121,137 +147,39 @@ impl DeviceRegistry {
Ok(())
}),
);
Self {
device_signer,
requests,
state: DeviceState::default(),
tasks,
_subscriptions: subscriptions,
}
}
/// Handle nostr notifications
async fn handle_notifications(client: &Client, tx: &flume::Sender<Event>) -> Result<(), Error> {
let mut notifications = client.notifications();
let mut processed_events = HashSet::new();
while let Some(notification) = notifications.next().await {
if let ClientNotification::Message {
message: RelayMessage::Event { event, .. },
..
} = notification
{
if !processed_events.insert(event.id) {
// Skip if the event has already been processed
continue;
}
match event.kind {
Kind::Custom(4454) => {
if Self::verify_author(client, event.as_ref()).await {
tx.send_async(event.into_owned()).await.ok();
}
}
Kind::Custom(4455) => {
if Self::verify_author(client, event.as_ref()).await {
tx.send_async(event.into_owned()).await.ok();
}
}
_ => {}
}
}
}
Ok(())
}
/// Verify the author of an event
async fn verify_author(client: &Client, event: &Event) -> bool {
if let Some(signer) = client.signer() {
if let Ok(public_key) = signer.get_public_key().await {
return public_key == event.pubkey;
}
}
false
}
/// Encrypt and store device keys in the local database.
async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
// Encrypt the value
let content = signer.nip44_encrypt(&public_key, secret).await?;
// Construct the application data event
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
.tag(Tag::identifier(IDENTIFIER))
.build(public_key)
.sign(&Keys::generate())
.await?;
// Save the event to the database
client.database().save_event(&event).await?;
Ok(())
}
/// Get device keys from the local database.
async fn get_keys(client: &Client) -> Result<Keys, Error> {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
.kind(Kind::ApplicationSpecificData)
.identifier(IDENTIFIER)
.author(public_key)
.limit(1);
if let Some(event) = client.database().query(filter).await?.first() {
let content = signer.nip44_decrypt(&public_key, &event.content).await?;
let secret = SecretKey::parse(&content)?;
let keys = Keys::new(secret);
Ok(keys)
} else {
Err(anyhow!("Key not found"))
}
pub fn state(&self) -> &DeviceState {
&self.state
}
/// Reset the device state
pub fn reset(&mut self, cx: &mut Context<Self>) {
self.state = DeviceState::Initial;
self.requests.update(cx, |this, cx| {
this.clear();
cx.notify();
});
self.device_signer.update(cx, |this, cx| {
*this = None;
cx.notify();
});
self.state = DeviceState::Initial;
cx.notify();
}
/// Returns the device signer entity
pub fn signer(&self, cx: &App) -> Option<Arc<dyn NostrSigner>> {
self.device_signer.read(cx).clone()
}
/// Set the decoupled encryption key for the current user
fn set_device_signer<S>(&mut self, signer: S, cx: &mut Context<Self>)
fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
where
S: NostrSigner + 'static,
{
self.set_state(DeviceState::Set, cx);
self.device_signer.update(cx, |this, cx| {
*this = Some(Arc::new(signer));
cx.notify();
});
let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer();
log::info!("Device Signer set");
self.tasks.push(cx.spawn(async move |this, cx| {
signer.set_encryption_signer(new).await;
this.update(cx, |this, cx| {
this.set_state(DeviceState::Set, cx);
})?;
Ok(())
}));
}
/// Set the device state
@@ -268,51 +196,6 @@ impl DeviceRegistry {
});
}
/// Continuously get gift wrap events for the current user in their messaging relays
fn get_messages(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let device_signer = self.device_signer.read(cx).clone();
let messaging_relays = nostr.read(cx).messaging_relays(cx);
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let urls = messaging_relays.await;
let user_signer = client.signer().context("Signer not found")?;
let public_key = user_signer.get_public_key().await?;
// Get messages with dekey
if let Some(signer) = device_signer.as_ref() {
let device_pkey = signer.get_public_key().await?;
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(device_pkey);
let id = SubscriptionId::new(DEVICE_GIFTWRAP);
// Construct target for subscription
let target = urls
.iter()
.map(|relay| (relay, vec![filter.clone()]))
.collect::<HashMap<_, _>>();
client.subscribe(target).with_id(id).await?;
}
// Get messages with user key
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
let id = SubscriptionId::new(USER_GIFTWRAP);
// Construct target for subscription
let target = urls
.iter()
.map(|relay| (relay, vec![filter.clone()]))
.collect::<HashMap<_, _>>();
client.subscribe(target).with_id(id).await?;
Ok(())
});
task.detach_and_log_err(cx);
}
/// Get device announcement for current user
fn get_announcement(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
@@ -388,7 +271,7 @@ impl DeviceRegistry {
client.send_event(&event).to_nip65().await?;
// Save device keys to the database
Self::set_keys(&client, &secret).await?;
set_keys(&client, &secret).await?;
Ok(())
});
@@ -396,7 +279,7 @@ impl DeviceRegistry {
cx.spawn(async move |this, cx| {
if task.await.is_ok() {
this.update(cx, |this, cx| {
this.set_device_signer(keys, cx);
this.set_signer(keys, cx);
this.listen_device_request(cx);
})
.ok();
@@ -414,7 +297,7 @@ impl DeviceRegistry {
let device_pubkey = announcement.public_key();
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
if let Ok(keys) = Self::get_keys(&client).await {
if let Ok(keys) = get_keys(&client).await {
if keys.public_key() != device_pubkey {
return Err(anyhow!("Key mismatch"));
};
@@ -429,7 +312,7 @@ impl DeviceRegistry {
match task.await {
Ok(keys) => {
this.update(cx, |this, cx| {
this.set_device_signer(keys, cx);
this.set_signer(keys, cx);
this.listen_device_request(cx);
})
.ok();
@@ -551,7 +434,7 @@ impl DeviceRegistry {
match task.await {
Ok(Some(keys)) => {
this.update(cx, |this, cx| {
this.set_device_signer(keys, cx);
this.set_signer(keys, cx);
})
.ok();
}
@@ -595,7 +478,7 @@ impl DeviceRegistry {
match task.await {
Ok(keys) => {
this.update(cx, |this, cx| {
this.set_device_signer(keys, cx);
this.set_signer(keys, cx);
})
.ok();
}
@@ -617,7 +500,7 @@ impl DeviceRegistry {
let signer = client.signer().context("Signer not found")?;
// Get device keys
let keys = Self::get_keys(&client).await?;
let keys = get_keys(&client).await?;
let secret = keys.secret_key().to_secret_hex();
// Extract the target public key from the event tags
@@ -650,3 +533,56 @@ impl DeviceRegistry {
task.detach();
}
}
/// Verify the author of an event
async fn verify_author(client: &Client, event: &Event) -> bool {
if let Some(signer) = client.signer() {
if let Ok(public_key) = signer.get_public_key().await {
return public_key == event.pubkey;
}
}
false
}
/// Encrypt and store device keys in the local database.
async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
// Encrypt the value
let content = signer.nip44_encrypt(&public_key, secret).await?;
// Construct the application data event
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
.tag(Tag::identifier(IDENTIFIER))
.build(public_key)
.sign(&Keys::generate())
.await?;
// Save the event to the database
client.database().save_event(&event).await?;
Ok(())
}
/// Get device keys from the local database.
async fn get_keys(client: &Client) -> Result<Keys, Error> {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
.kind(Kind::ApplicationSpecificData)
.identifier(IDENTIFIER)
.author(public_key)
.limit(1);
if let Some(event) = client.database().query(filter).await?.first() {
let content = signer.nip44_decrypt(&public_key, &event.content).await?;
let secret = SecretKey::parse(&content)?;
let keys = Keys::new(secret);
Ok(keys)
} else {
Err(anyhow!("Key not found"))
}
}

View File

@@ -26,6 +26,7 @@ impl Global for GlobalPersonRegistry {}
enum Dispatch {
Person(Box<Person>),
Announcement(Box<Event>),
Relays(Box<Event>),
}
/// Person Registry
@@ -100,6 +101,9 @@ impl PersonRegistry {
Dispatch::Announcement(event) => {
this.set_announcement(&event, cx);
}
Dispatch::Relays(event) => {
this.set_messaging_relays(&event, cx);
}
};
})
.ok();
@@ -157,18 +161,24 @@ impl PersonRegistry {
// Send
tx.send_async(Dispatch::Person(val)).await.ok();
}
Kind::Custom(10044) => {
let val = Box::new(event.into_owned());
// Send
tx.send_async(Dispatch::Announcement(val)).await.ok();
}
Kind::ContactList => {
let public_keys = event.extract_public_keys();
// Get metadata for all public keys
Self::get_metadata(client, public_keys).await.ok();
}
Kind::InboxRelays => {
let val = Box::new(event.into_owned());
// Send
tx.send_async(Dispatch::Relays(val)).await.ok();
}
Kind::Custom(10044) => {
let val = Box::new(event.into_owned());
// Send
tx.send_async(Dispatch::Announcement(val)).await.ok();
}
_ => {}
}
}
@@ -264,6 +274,18 @@ impl PersonRegistry {
}
}
/// Set messaging relays for a person
fn set_messaging_relays(&mut self, event: &Event, cx: &mut App) {
if let Some(person) = self.persons.get(&event.pubkey) {
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).cloned().collect();
person.update(cx, |person, cx| {
person.set_messaging_relays(event.pubkey, urls);
cx.notify();
});
}
}
/// Insert batch of persons
fn bulk_inserts(&mut self, persons: Vec<Person>, cx: &mut Context<Self>) {
for person in persons.into_iter() {

View File

@@ -18,6 +18,9 @@ pub struct Person {
/// Dekey (NIP-4e) announcement
announcement: Option<Announcement>,
/// Messaging relays
messaging_relays: Vec<RelayUrl>,
}
impl PartialEq for Person {
@@ -58,6 +61,7 @@ impl Person {
public_key,
metadata,
announcement: None,
messaging_relays: vec![],
}
}
@@ -82,6 +86,25 @@ impl Person {
log::info!("Updated announcement for: {}", self.public_key());
}
/// Get profile messaging relays
pub fn messaging_relays(&self) -> &Vec<RelayUrl> {
&self.messaging_relays
}
/// Get relay hint for messaging relay list
pub fn messaging_relay_hint(&self) -> Option<RelayUrl> {
self.messaging_relays.first().cloned()
}
/// Set profile messaging relays
pub fn set_messaging_relays<I>(&mut self, public_key: PublicKey, relays: I)
where
I: IntoIterator<Item = RelayUrl>,
{
self.messaging_relays = relays.into_iter().collect();
log::info!("Updated messaging relays for: {}", public_key);
}
/// Get profile avatar
pub fn avatar(&self) -> SharedString {
self.metadata()

View File

@@ -55,7 +55,21 @@ pub enum SignerKind {
#[default]
Auto,
User,
Device,
Encryption,
}
impl SignerKind {
pub fn auto(&self) -> bool {
matches!(self, SignerKind::Auto)
}
pub fn user(&self) -> bool {
matches!(self, SignerKind::User)
}
pub fn encryption(&self) -> bool {
matches!(self, SignerKind::Encryption)
}
}
/// Room configuration
@@ -65,6 +79,16 @@ pub struct RoomConfig {
signer_kind: SignerKind,
}
impl RoomConfig {
pub fn backup(&self) -> bool {
self.backup
}
pub fn signer_kind(&self) -> &SignerKind {
&self.signer_kind
}
}
/// Settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {

View File

@@ -4,11 +4,25 @@ use nostr_sdk::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum DeviceState {
#[default]
Initial,
Idle,
Requesting,
Set,
}
impl DeviceState {
pub fn idle(&self) -> bool {
matches!(self, DeviceState::Idle)
}
pub fn requesting(&self) -> bool {
matches!(self, DeviceState::Requesting)
}
pub fn set(&self) -> bool {
matches!(self, DeviceState::Set)
}
}
/// Announcement
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Announcement {
@@ -24,7 +38,7 @@ impl From<&Event> for Announcement {
let public_key = val
.tags
.iter()
.find(|tag| tag.kind().as_str() == "n" || tag.kind().as_str() == "P")
.find(|tag| tag.kind().as_str() == "n")
.and_then(|tag| tag.content())
.and_then(|c| PublicKey::parse(c).ok())
.unwrap_or(val.pubkey);

View File

@@ -96,13 +96,9 @@ impl NostrRegistry {
});
// Construct the nostr signer
let app_keys = Self::create_or_init_app_keys().unwrap_or(Keys::generate());
let app_keys = get_or_init_app_keys().unwrap_or(Keys::generate());
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
// Construct the relay states entity
let nip65 = cx.new(|_| RelayState::default());
let nip17 = cx.new(|_| RelayState::default());
// Construct the nostr client
let client = ClientBuilder::default()
.signer(signer.clone())
@@ -122,6 +118,10 @@ impl NostrRegistry {
})
.build();
// Construct the relay states entity
let nip65 = cx.new(|_| RelayState::default());
let nip17 = cx.new(|_| RelayState::default());
let mut subscriptions = vec![];
subscriptions.push(
@@ -134,6 +134,15 @@ impl NostrRegistry {
}),
);
subscriptions.push(
// Observe the NIP-17 state
cx.observe(&nip17, |this, state, cx| {
if state.read(cx) == &RelayState::Configured {
this.get_messages(cx);
};
}),
);
cx.defer(|cx| {
let nostr = NostrRegistry::global(cx);
@@ -244,30 +253,6 @@ impl NostrRegistry {
cx.notify();
}
/// Get a relay hint (messaging relay) for a given public key
///
/// Used for building chat messages
pub fn relay_hint(&self, public_key: &PublicKey, cx: &App) -> Task<Option<RelayUrl>> {
let client = self.client();
let public_key = public_key.to_owned();
cx.background_spawn(async move {
let filter = Filter::new()
.author(public_key)
.kind(Kind::InboxRelays)
.limit(1);
if let Ok(events) = client.database().query(filter).await {
if let Some(event) = events.first_owned() {
let relays: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
return relays.first().cloned();
}
}
None
})
}
/// Get a list of messaging relays with current signer's public key
pub fn messaging_relays(&self, cx: &App) -> Task<Vec<RelayUrl>> {
let client = self.client();
@@ -292,7 +277,7 @@ impl NostrRegistry {
.await
.ok()
.and_then(|events| events.first_owned())
.map(|event| nip17::extract_owned_relay_list(event).collect())
.map(|event| nip17::extract_owned_relay_list(event).take(3).collect())
.unwrap_or_default();
for relay in relays.iter() {
@@ -350,82 +335,6 @@ impl NostrRegistry {
}));
}
/*
async fn get_adv_events_by(client: &Client, event: &Event) -> Result<(), Error> {
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.timeout(Some(Duration::from_secs(TIMEOUT)))
.exit_policy(ReqExitPolicy::ExitOnEOSE);
// Extract write relays from event
let write_relays: Vec<&RelayUrl> = nip65::extract_relay_list(event)
.filter_map(|(url, metadata)| {
if metadata.is_none() || metadata == &Some(RelayMetadata::Write) {
Some(url)
} else {
None
}
})
.collect();
// Ensure relay connections
for relay in write_relays.iter() {
client.add_relay(*relay).await?;
client.connect_relay(*relay).await?;
}
// Construct filter for inbox relays
let inbox = Filter::new()
.kind(Kind::InboxRelays)
.author(event.pubkey)
.limit(1);
// Construct filter for encryption announcement
let announcement = Filter::new()
.kind(Kind::Custom(10044))
.author(event.pubkey)
.limit(1);
// Construct target for subscription
let target = write_relays
.into_iter()
.map(|relay| (relay, vec![inbox.clone(), announcement.clone()]))
.collect::<HashMap<_, _>>();
client.subscribe(target).close_on(opts).await?;
Ok(())
}
*/
/// Get or create a new app keys
fn create_or_init_app_keys() -> Result<Keys, Error> {
let dir = config_dir().join(".app_keys");
let content = match std::fs::read(&dir) {
Ok(content) => content,
Err(_) => {
// Generate new keys if file doesn't exist
let keys = Keys::generate();
let secret_key = keys.secret_key();
// Create directory and write secret key
std::fs::create_dir_all(dir.parent().unwrap())?;
std::fs::write(&dir, secret_key.to_secret_bytes())?;
// Set permissions to readonly
let mut perms = std::fs::metadata(&dir)?.permissions();
perms.set_mode(0o400);
std::fs::set_permissions(&dir, perms)?;
return Ok(keys);
}
};
let secret_key = SecretKey::from_slice(&content)?;
let keys = Keys::new(secret_key);
Ok(keys)
}
// Get relay list for current user
fn get_relay_list(&mut self, cx: &mut Context<Self>) {
let client = self.client();
@@ -578,6 +487,49 @@ impl NostrRegistry {
}));
}
/// Continuously get gift wrap events for the current user in their messaging relays
fn get_messages(&mut self, cx: &mut Context<Self>) {
let client = self.client();
let signer = self.signer();
let messaging_relays = self.messaging_relays(cx);
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let urls = messaging_relays.await;
let public_key = signer.get_public_key().await?;
// Get messages with dekey
if let Some(signer) = signer.get_encryption_signer().await.as_ref() {
let device_pkey = signer.get_public_key().await?;
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(device_pkey);
let id = SubscriptionId::new(DEVICE_GIFTWRAP);
// Construct target for subscription
let target = urls
.iter()
.map(|relay| (relay, vec![filter.clone()]))
.collect::<HashMap<_, _>>();
client.subscribe(target).with_id(id).await?;
}
// Get messages with user key
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
let id = SubscriptionId::new(USER_GIFTWRAP);
// Construct target for subscription
let target = urls
.iter()
.map(|relay| (relay, vec![filter.clone()]))
.collect::<HashMap<_, _>>();
client.subscribe(target).with_id(id).await?;
Ok(())
});
task.detach_and_log_err(cx);
}
/// Get profile and contact list for current user
fn get_profile(&mut self, cx: &mut Context<Self>) {
let client = self.client();
@@ -688,6 +640,7 @@ impl NostrRegistry {
.send_event(&event)
.broadcast()
.ok_timeout(Duration::from_secs(TIMEOUT))
.ack_policy(AckPolicy::none())
.await?;
// Construct the default contact list
@@ -699,6 +652,7 @@ impl NostrRegistry {
.send_event(&event)
.broadcast()
.ok_timeout(Duration::from_secs(TIMEOUT))
.ack_policy(AckPolicy::none())
.await?;
// Construct the default messaging relay list
@@ -710,6 +664,7 @@ impl NostrRegistry {
.send_event(&event)
.to_nip65()
.ok_timeout(Duration::from_secs(TIMEOUT))
.ack_policy(AckPolicy::none())
.await?;
// Write user's credentials to the system keyring
@@ -980,6 +935,36 @@ impl NostrRegistry {
}
}
/// Get or create a new app keys
fn get_or_init_app_keys() -> Result<Keys, Error> {
let dir = config_dir().join(".app_keys");
let content = match std::fs::read(&dir) {
Ok(content) => content,
Err(_) => {
// Generate new keys if file doesn't exist
let keys = Keys::generate();
let secret_key = keys.secret_key();
// Create directory and write secret key
std::fs::create_dir_all(dir.parent().unwrap())?;
std::fs::write(&dir, secret_key.to_secret_bytes())?;
// Set permissions to readonly
let mut perms = std::fs::metadata(&dir)?.permissions();
perms.set_mode(0o400);
std::fs::set_permissions(&dir, perms)?;
return Ok(keys);
}
};
let secret_key = SecretKey::from_slice(&content)?;
let keys = Keys::new(secret_key);
Ok(keys)
}
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
vec![
(

View File

@@ -8,11 +8,15 @@ use smol::lock::RwLock;
#[derive(Debug)]
pub struct CoopSigner {
/// User's signer
signer: RwLock<Arc<dyn NostrSigner>>,
/// Signer's public key
/// User's signer public key
signer_pkey: RwLock<Option<PublicKey>>,
/// Specific signer for encryption purposes
encryption_signer: RwLock<Option<Arc<dyn NostrSigner>>>,
/// Whether coop is creating a new identity
creating: AtomicBool,
@@ -30,6 +34,7 @@ impl CoopSigner {
Self {
signer: RwLock::new(signer.into_nostr_signer()),
signer_pkey: RwLock::new(None),
encryption_signer: RwLock::new(None),
creating: AtomicBool::new(false),
owned: AtomicBool::new(false),
}
@@ -40,6 +45,11 @@ impl CoopSigner {
self.signer.read().await.clone()
}
/// Get the encryption signer.
pub async fn get_encryption_signer(&self) -> Option<Arc<dyn NostrSigner>> {
self.encryption_signer.read().await.clone()
}
/// Get public key
pub fn public_key(&self) -> Option<PublicKey> {
self.signer_pkey.read_blocking().to_owned()
@@ -64,6 +74,7 @@ impl CoopSigner {
let public_key = new_signer.get_public_key().await.ok();
let mut signer = self.signer.write().await;
let mut signer_pkey = self.signer_pkey.write().await;
let mut encryption_signer = self.encryption_signer.write().await;
// Switch to the new signer
*signer = new_signer;
@@ -71,9 +82,21 @@ impl CoopSigner {
// Update the public key
*signer_pkey = public_key;
// Reset the encryption signer
*encryption_signer = None;
// Update the owned flag
self.owned.store(owned, Ordering::SeqCst);
}
/// Set the encryption signer.
pub async fn set_encryption_signer<T>(&self, new: T)
where
T: IntoNostrSigner,
{
let mut encryption_signer = self.encryption_signer.write().await;
*encryption_signer = Some(new.into_nostr_signer());
}
}
impl NostrSigner for CoopSigner {