From 452253bece19f2c4d1a2aed252cf159c3ecb0b2d Mon Sep 17 00:00:00 2001 From: reya Date: Sun, 15 Feb 2026 16:52:35 +0700 Subject: [PATCH] wip --- Cargo.lock | 52 +++--- crates/chat/src/lib.rs | 13 +- crates/chat/src/message.rs | 4 +- crates/chat/src/room.rs | 210 +++++++++++++++++------ crates/chat_ui/src/lib.rs | 245 +++++++++----------------- crates/coop/src/main.rs | 2 +- crates/device/src/lib.rs | 330 +++++++++++++++--------------------- crates/person/src/lib.rs | 34 +++- crates/person/src/person.rs | 23 +++ crates/settings/src/lib.rs | 26 ++- crates/state/src/device.rs | 18 +- crates/state/src/lib.rs | 197 ++++++++++----------- crates/state/src/signer.rs | 25 ++- 13 files changed, 610 insertions(+), 569 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b14c862..ea3a59a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/crates/chat/src/lib.rs b/crates/chat/src/lib.rs index 43b6448..42348b3 100644 --- a/crates/chat/src/lib.rs +++ b/crates/chat/src/lib.rs @@ -97,12 +97,10 @@ impl ChatRegistry { /// Create a new chat registry instance fn new(cx: &mut Context) -> 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) { 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(); diff --git a/crates/chat/src/message.rs b/crates/chat/src/message.rs index 5ec33a7..6118331 100644 --- a/crates/chat/src/message.rs +++ b/crates/chat/src/message.rs @@ -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, } } diff --git a/crates/chat/src/room.rs b/crates/chat/src/room.rs index a09cfea..f5fedc6 100644 --- a/crates/chat/src/room.rs +++ b/crates/chat/src/room.rs @@ -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>, pub error: Option, - pub on_hold: Option, - pub encryption: bool, - pub relays_not_found: bool, - pub device_not_found: bool, + pub output: Option>, } 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) -> Self { - self.status = Some(output); + pub fn output(mut self, output: Output) -> Self { + self.output = Some(output); self } - pub fn error(mut self, error: impl Into) -> Self { + pub fn error(mut self, error: T) -> Self + where + T: Into, + { 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> { + pub fn early_connect(&self, cx: &App) -> Task> { 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 { + 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(&self, content: S, replies: I, cx: &App) -> Option>> + where + S: Into, + I: IntoIterator, + { + 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 = 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 = 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 = 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) }) } + */ } diff --git a/crates/chat_ui/src/lib.rs b/crates/chat_ui/src/lib.rs index 4cb3ecc..1c79adc 100644 --- a/crates/chat_ui/src/lib.rs +++ b/crates/chat_ui/src/lib.rs @@ -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, window: &mut Window, cx: &mut App) -> Entity pub struct ChatPanel { id: SharedString, focus_handle: FocusHandle, - image_cache: Entity, /// Chat Room room: WeakEntity, @@ -77,14 +76,22 @@ pub struct ChatPanel { uploading: bool, /// Async operations - tasks: SmallVec<[Task<()>; 2]>, + tasks: SmallVec<[Task>; 2]>, /// Event subscriptions - _subscriptions: SmallVec<[Subscription; 2]>, + subscriptions: SmallVec<[Subscription; 2]>, } impl ChatPanel { pub fn new(room: WeakEntity, window: &mut Window, cx: &mut Context) -> 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); - } + // Define subscriptions + let subscriptions = + smallvec![ + cx.subscribe_in(&input, window, move |this, _input, event, window, cx| { + if let InputEvent::PressEnter { .. } = event { + this.send_text_message(window, cx); }; - }), - ); - } + }) + ]; - subscriptions.push( - // Subscribe to input events - cx.subscribe_in(&input, window, move |this, _input, event, window, cx| { - if let InputEvent::PressEnter { .. } = event { - this.send_input_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,32 +139,47 @@ 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![], } } - /// Load all messages belonging to this room - fn load_messages(&mut self, window: &mut Window, cx: &mut Context) { - 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; + fn subscribe_room_events(&mut self, window: &mut Window, cx: &mut Context) { + let Some(room) = self.room.upgrade() else { + return; + }; - 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); - } - }; - }) - .ok(); - })); - } + 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 get_messages(&mut self, _window: &mut Window, cx: &mut Context) { + let Ok(get_messages) = self.room.read_with(cx, |this, cx| this.get_messages(cx)) else { + return; + }; + + 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 @@ -235,7 +207,7 @@ impl ChatPanel { content } - fn send_input_message(&mut self, window: &mut Window, cx: &mut Context) { + fn send_text_message(&mut self, window: &mut Window, cx: &mut Context) { // Get the message which includes all attachments let content = self.get_input_value(cx); @@ -250,80 +222,12 @@ impl ChatPanel { /// Send a message to all members of the chat fn send_message(&mut self, value: &str, window: &mut Window, cx: &mut Context) { - // Get replies_to if it's present - let replies: Vec = 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> = 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; - 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(); + fn insert_reports(&mut self, id: EventId, reports: Vec, cx: &mut Context) { + self.reports_by_id.insert(id, reports); + cx.notify(); } /// Insert a message into the chat panel @@ -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) -> impl IntoElement { div() @@ -1174,7 +1082,6 @@ impl Render for ChatPanel { fn render(&mut self, window: &mut Window, cx: &mut Context) -> 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); })), ), ), diff --git a/crates/coop/src/main.rs b/crates/coop/src/main.rs index 0336fbd..afeac78 100644 --- a/crates/coop/src/main.rs +++ b/crates/coop/src/main.rs @@ -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); diff --git a/crates/device/src/lib.rs b/crates/device/src/lib.rs index 199ff94..6c3ae72 100644 --- a/crates/device/src/lib.rs +++ b/crates/device/src/lib.rs @@ -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); @@ -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>>, - /// Device state - pub state: DeviceState, + state: DeviceState, /// Device requests requests: Entity>, @@ -40,7 +36,7 @@ pub struct DeviceRegistry { tasks: Vec>>, /// 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 { + fn new(window: &mut Window, cx: &mut Context) -> 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::(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) { + let nostr = NostrRegistry::global(cx); + let client = nostr.read(cx).client(); + let (tx, rx) = flume::bounded::(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) -> 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 { - 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.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> { - self.device_signer.read(cx).clone() - } - /// Set the decoupled encryption key for the current user - fn set_device_signer(&mut self, signer: S, cx: &mut Context) + fn set_signer(&mut self, new: S, cx: &mut Context) 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) { - 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> = 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::>(); - - 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::>(); - - 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) { 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> = 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 { + 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")) + } +} diff --git a/crates/person/src/lib.rs b/crates/person/src/lib.rs index 624efe8..63ea2ea 100644 --- a/crates/person/src/lib.rs +++ b/crates/person/src/lib.rs @@ -26,6 +26,7 @@ impl Global for GlobalPersonRegistry {} enum Dispatch { Person(Box), Announcement(Box), + Relays(Box), } /// 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 = 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, cx: &mut Context) { for person in persons.into_iter() { diff --git a/crates/person/src/person.rs b/crates/person/src/person.rs index f37fffd..3c515fd 100644 --- a/crates/person/src/person.rs +++ b/crates/person/src/person.rs @@ -18,6 +18,9 @@ pub struct Person { /// Dekey (NIP-4e) announcement announcement: Option, + + /// Messaging relays + messaging_relays: Vec, } 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 { + &self.messaging_relays + } + + /// Get relay hint for messaging relay list + pub fn messaging_relay_hint(&self) -> Option { + self.messaging_relays.first().cloned() + } + + /// Set profile messaging relays + pub fn set_messaging_relays(&mut self, public_key: PublicKey, relays: I) + where + I: IntoIterator, + { + 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() diff --git a/crates/settings/src/lib.rs b/crates/settings/src/lib.rs index b1538e2..4a43bec 100644 --- a/crates/settings/src/lib.rs +++ b/crates/settings/src/lib.rs @@ -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 { diff --git a/crates/state/src/device.rs b/crates/state/src/device.rs index f809c38..682e8b2 100644 --- a/crates/state/src/device.rs +++ b/crates/state/src/device.rs @@ -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); diff --git a/crates/state/src/lib.rs b/crates/state/src/lib.rs index 49d73ad..0209498 100644 --- a/crates/state/src/lib.rs +++ b/crates/state/src/lib.rs @@ -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> { - 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 = 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> { 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::>(); - - client.subscribe(target).close_on(opts).await?; - - Ok(()) - } - */ - - /// Get or create a new app keys - fn create_or_init_app_keys() -> Result { - 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) { 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) { + let client = self.client(); + let signer = self.signer(); + let messaging_relays = self.messaging_relays(cx); + + let task: Task> = 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::>(); + + 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::>(); + + 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) { 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 { + 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)> { vec![ ( diff --git a/crates/state/src/signer.rs b/crates/state/src/signer.rs index 6067fb6..fca70c7 100644 --- a/crates/state/src/signer.rs +++ b/crates/state/src/signer.rs @@ -8,11 +8,15 @@ use smol::lock::RwLock; #[derive(Debug)] pub struct CoopSigner { + /// User's signer signer: RwLock>, - /// Signer's public key + /// User's signer public key signer_pkey: RwLock>, + /// Specific signer for encryption purposes + encryption_signer: RwLock>>, + /// 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> { + self.encryption_signer.read().await.clone() + } + /// Get public key pub fn public_key(&self) -> Option { 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(&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 {