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

View File

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

View File

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

View File

@@ -1,5 +1,4 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::time::Duration; use std::time::Duration;
@@ -9,72 +8,47 @@ use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
use itertools::Itertools; use itertools::Itertools;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::{Person, PersonRegistry}; use person::{Person, PersonRegistry};
use state::{tracker, NostrRegistry}; use settings::{RoomConfig, SignerKind};
use state::{NostrRegistry, TIMEOUT};
use crate::{ChatRegistry, NewMessage}; use crate::{ChatRegistry, NewMessage};
const SEND_RETRY: usize = 10;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SendReport { pub struct SendReport {
pub receiver: PublicKey, pub receiver: PublicKey,
pub status: Option<Output<EventId>>,
pub error: Option<SharedString>, pub error: Option<SharedString>,
pub on_hold: Option<Event>, pub output: Option<Output<EventId>>,
pub encryption: bool,
pub relays_not_found: bool,
pub device_not_found: bool,
} }
impl SendReport { impl SendReport {
pub fn new(receiver: PublicKey) -> Self { pub fn new(receiver: PublicKey) -> Self {
Self { Self {
receiver, receiver,
status: None,
error: None, error: None,
on_hold: None, output: None,
encryption: false,
relays_not_found: false,
device_not_found: false,
} }
} }
pub fn status(mut self, output: Output<EventId>) -> Self { pub fn output(mut self, output: Output<EventId>) -> Self {
self.status = Some(output); self.output = Some(output);
self 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.error = Some(error.into());
self 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 { 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 { 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() !output.success.is_empty()
} else { } else {
false false
@@ -115,6 +89,9 @@ pub struct Room {
/// Kind /// Kind
pub kind: RoomKind, pub kind: RoomKind,
/// Configuration
config: RoomConfig,
} }
impl Ord for Room { impl Ord for Room {
@@ -161,6 +138,7 @@ impl From<&UnsignedEvent> for Room {
subject, subject,
members, members,
kind: RoomKind::default(), kind: RoomKind::default(),
config: RoomConfig::default(),
} }
} }
} }
@@ -320,21 +298,17 @@ impl Room {
} }
/// Get gossip relays for each member /// 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 nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let members = self.members(); 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 { cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?; let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?; 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() { for member in members.into_iter() {
if member == public_key { if member == public_key {
continue; continue;
@@ -346,8 +320,12 @@ impl Room {
// Subscribe to get member's gossip relays // Subscribe to get member's gossip relays
client client
.subscribe(filter) .subscribe(filter)
.close_on(opts) .with_id(subscription_id.clone())
.with_id(id.clone()) .close_on(
SubscribeAutoCloseOptions::default()
.timeout(Some(Duration::from_secs(TIMEOUT)))
.exit_policy(ReqExitPolicy::ExitOnEOSE),
)
.await?; .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( pub fn create_message(
&self, &self,
content: &str, content: &str,
@@ -444,7 +553,7 @@ impl Room {
// WARNING: never sign and send this event to relays // WARNING: never sign and send this event to relays
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, content) let mut event = EventBuilder::new(Kind::PrivateDirectMessage, content)
.tags(tags) .tags(tags)
.build(Keys::generate().public_key()); .build(public_key);
// Ensure the event ID has been generated // Ensure the event ID has been generated
event.ensure_id(); event.ensure_id();
@@ -594,4 +703,5 @@ impl Room {
Ok(resend_reports) Ok(resend_reports)
}) })
} }
*/
} }

View File

@@ -10,8 +10,8 @@ use gpui::{
div, img, list, px, red, relative, rems, svg, white, AnyElement, App, AppContext, div, img, list, px, red, relative, rems, svg, white, AnyElement, App, AppContext,
ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
IntoElement, ListAlignment, ListOffset, ListState, MouseButton, ObjectFit, ParentElement, IntoElement, ListAlignment, ListOffset, ListState, MouseButton, ObjectFit, ParentElement,
PathPromptOptions, Render, RetainAllImageCache, SharedString, StatefulInteractiveElement, PathPromptOptions, Render, SharedString, StatefulInteractiveElement, Styled, StyledImage,
Styled, StyledImage, Subscription, Task, WeakEntity, Window, Subscription, Task, WeakEntity, Window,
}; };
use gpui_tokio::Tokio; use gpui_tokio::Tokio;
use indexset::{BTreeMap, BTreeSet}; use indexset::{BTreeMap, BTreeSet};
@@ -47,7 +47,6 @@ pub fn init(room: WeakEntity<Room>, window: &mut Window, cx: &mut App) -> Entity
pub struct ChatPanel { pub struct ChatPanel {
id: SharedString, id: SharedString,
focus_handle: FocusHandle, focus_handle: FocusHandle,
image_cache: Entity<RetainAllImageCache>,
/// Chat Room /// Chat Room
room: WeakEntity<Room>, room: WeakEntity<Room>,
@@ -77,14 +76,22 @@ pub struct ChatPanel {
uploading: bool, uploading: bool,
/// Async operations /// Async operations
tasks: SmallVec<[Task<()>; 2]>, tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
/// Event subscriptions /// Event subscriptions
_subscriptions: SmallVec<[Subscription; 2]>, subscriptions: SmallVec<[Subscription; 2]>,
} }
impl ChatPanel { impl ChatPanel {
pub fn new(room: WeakEntity<Room>, window: &mut Window, cx: &mut Context<Self>) -> Self { 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 // Get room id and name
let (id, name) = room let (id, name) = room
.read_with(cx, |this, _cx| { .read_with(cx, |this, _cx| {
@@ -104,74 +111,24 @@ impl ChatPanel {
.clean_on_escape() .clean_on_escape()
}); });
// Define attachments and replies_to entities // Define subscriptions
let attachments = cx.new(|_| vec![]); let subscriptions =
let replies_to = cx.new(|_| HashSet::new()); smallvec![
// 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
cx.subscribe_in(&input, window, move |this, _input, event, window, cx| { cx.subscribe_in(&input, window, move |this, _input, event, window, cx| {
if let InputEvent::PressEnter { .. } = event { 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 { Self {
focus_handle: cx.focus_handle(),
id, id,
messages, messages,
room, room,
@@ -182,33 +139,48 @@ impl ChatPanel {
rendered_texts_by_id: BTreeMap::new(), rendered_texts_by_id: BTreeMap::new(),
reports_by_id: BTreeMap::new(), reports_by_id: BTreeMap::new(),
uploading: false, uploading: false,
image_cache: RetainAllImageCache::new(cx), subscriptions,
focus_handle: cx.focus_handle(), tasks: smallvec![],
_subscriptions: subscriptions,
tasks,
} }
} }
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 /// Load all messages belonging to this room
fn load_messages(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn get_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)) { let Ok(get_messages) = self.room.read_with(cx, |this, cx| this.get_messages(cx)) else {
self.tasks.push(cx.spawn_in(window, async move |this, cx| { return;
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);
}
}; };
})
.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 /// Get user input content and merged all attachments
fn get_input_value(&self, cx: &Context<Self>) -> String { fn get_input_value(&self, cx: &Context<Self>) -> String {
@@ -235,7 +207,7 @@ impl ChatPanel {
content 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 // Get the message which includes all attachments
let content = self.get_input_value(cx); let content = self.get_input_value(cx);
@@ -250,81 +222,13 @@ impl ChatPanel {
/// Send a message to all members of the chat /// Send a message to all members of the chat
fn send_message(&mut self, value: &str, window: &mut Window, cx: &mut Context<Self>) { fn send_message(&mut self, value: &str, window: &mut Window, cx: &mut Context<Self>) {
// Get replies_to if it's present // TODO
let replies: Vec<EventId> = self.replies_to.read(cx).iter().copied().collect(); }
// Get a task to create temporary message for optimistic update fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) {
let Ok(get_rumor) = self self.reports_by_id.insert(id, reports);
.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;
cx.notify(); 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 /// Insert a message into the chat panel
fn insert_message<E>(&mut self, m: E, scroll: bool, cx: &mut Context<Self>) 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()); let mut items = Vec::with_capacity(reports.len());
for report in reports.iter() { for report in reports.iter() {
items.push(Self::render_report(report, cx)) //items.push(Self::render_report(report, cx))
items.push(div())
} }
items items
@@ -781,7 +686,8 @@ impl ChatPanel {
let mut items = Vec::with_capacity(reports.len()); let mut items = Vec::with_capacity(reports.len());
for report in reports.iter() { for report in reports.iter() {
items.push(Self::render_report(report, cx)) //items.push(Self::render_report(report, cx))
items.push(div())
} }
items items
@@ -791,6 +697,7 @@ impl ChatPanel {
}) })
} }
/*
fn render_report(report: &SendReport, cx: &App) -> impl IntoElement { fn render_report(report: &SendReport, cx: &App) -> impl IntoElement {
let persons = PersonRegistry::global(cx); let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&report.receiver, 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 { fn render_border(&self, cx: &Context<Self>) -> impl IntoElement {
div() div()
@@ -1174,7 +1082,6 @@ impl Render for ChatPanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.on_action(cx.listener(Self::on_command)) .on_action(cx.listener(Self::on_command))
.image_cache(self.image_cache.clone())
.size_full() .size_full()
.child( .child(
list( list(
@@ -1246,7 +1153,7 @@ impl Render for ChatPanel {
.ghost() .ghost()
.large() .large()
.on_click(cx.listener(move |this, _ev, window, cx| { .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 // Initialize device signer
// //
// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md // NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
device::init(cx); device::init(window, cx);
// Initialize settings // Initialize settings
settings::init(cx); settings::init(cx);

View File

@@ -1,12 +1,11 @@
use std::collections::{HashMap, HashSet}; use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use anyhow::{anyhow, Context as AnyhowContext, Error}; 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 nostr_sdk::prelude::*;
use smallvec::{smallvec, SmallVec}; use smallvec::{smallvec, SmallVec};
use state::{app_name, NostrRegistry, RelayState, DEVICE_GIFTWRAP, TIMEOUT, USER_GIFTWRAP}; use state::{app_name, NostrRegistry, RelayState, TIMEOUT};
mod device; mod device;
@@ -14,8 +13,8 @@ pub use device::*;
const IDENTIFIER: &str = "coop:device"; const IDENTIFIER: &str = "coop:device";
pub fn init(cx: &mut App) { pub fn init(window: &mut Window, cx: &mut App) {
DeviceRegistry::set_global(cx.new(DeviceRegistry::new), cx); DeviceRegistry::set_global(cx.new(|cx| DeviceRegistry::new(window, cx)), cx);
} }
struct GlobalDeviceRegistry(Entity<DeviceRegistry>); 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 /// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
#[derive(Debug)] #[derive(Debug)]
pub struct DeviceRegistry { pub struct DeviceRegistry {
/// Device signer
pub device_signer: Entity<Option<Arc<dyn NostrSigner>>>,
/// Device state /// Device state
pub state: DeviceState, state: DeviceState,
/// Device requests /// Device requests
requests: Entity<HashSet<Event>>, requests: Entity<HashSet<Event>>,
@@ -40,7 +36,7 @@ pub struct DeviceRegistry {
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
/// Subscriptions /// Subscriptions
_subscriptions: SmallVec<[Subscription; 2]>, _subscriptions: SmallVec<[Subscription; 1]>,
} }
impl DeviceRegistry { impl DeviceRegistry {
@@ -55,20 +51,14 @@ impl DeviceRegistry {
} }
/// Create a new device registry instance /// 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 nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let nip65_state = nostr.read(cx).nip65_state(); 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()); 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 subscriptions = smallvec![];
let mut tasks = vec![];
subscriptions.push( subscriptions.push(
// Observe the NIP-65 state // Observe the NIP-65 state
@@ -85,21 +75,57 @@ impl DeviceRegistry {
}), }),
); );
subscriptions.push( cx.defer_in(window, |this, _window, cx| {
// Observe the NIP-17 state this.handle_notifications(cx);
cx.observe(&nip17_state, |this, state, cx| { });
if state.read(cx) == &RelayState::Configured {
this.get_messages(cx);
};
}),
);
tasks.push( Self {
// Handle nostr notifications state: DeviceState::default(),
cx.background_spawn(async move { Self::handle_notifications(&client, &tx).await }), 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 // Update GPUI states
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
while let Ok(event) = rx.recv_async().await { while let Ok(event) = rx.recv_async().await {
@@ -121,137 +147,39 @@ impl DeviceRegistry {
Ok(()) Ok(())
}), }),
); );
Self {
device_signer,
requests,
state: DeviceState::default(),
tasks,
_subscriptions: subscriptions,
}
} }
/// Handle nostr notifications pub fn state(&self) -> &DeviceState {
async fn handle_notifications(client: &Client, tx: &flume::Sender<Event>) -> Result<(), Error> { &self.state
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"))
}
} }
/// Reset the device state /// Reset the device state
pub fn reset(&mut self, cx: &mut Context<Self>) { pub fn reset(&mut self, cx: &mut Context<Self>) {
self.state = DeviceState::Initial;
self.requests.update(cx, |this, cx| { self.requests.update(cx, |this, cx| {
this.clear(); this.clear();
cx.notify(); cx.notify();
}); });
self.device_signer.update(cx, |this, cx| {
*this = None;
cx.notify(); 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 /// 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 where
S: NostrSigner + 'static, S: NostrSigner + 'static,
{ {
self.set_state(DeviceState::Set, cx); let nostr = NostrRegistry::global(cx);
self.device_signer.update(cx, |this, cx| { let signer = nostr.read(cx).signer();
*this = Some(Arc::new(signer));
cx.notify();
});
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 /// 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 /// Get device announcement for current user
fn get_announcement(&mut self, cx: &mut Context<Self>) { fn get_announcement(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
@@ -388,7 +271,7 @@ impl DeviceRegistry {
client.send_event(&event).to_nip65().await?; client.send_event(&event).to_nip65().await?;
// Save device keys to the database // Save device keys to the database
Self::set_keys(&client, &secret).await?; set_keys(&client, &secret).await?;
Ok(()) Ok(())
}); });
@@ -396,7 +279,7 @@ impl DeviceRegistry {
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
if task.await.is_ok() { if task.await.is_ok() {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_device_signer(keys, cx); this.set_signer(keys, cx);
this.listen_device_request(cx); this.listen_device_request(cx);
}) })
.ok(); .ok();
@@ -414,7 +297,7 @@ impl DeviceRegistry {
let device_pubkey = announcement.public_key(); let device_pubkey = announcement.public_key();
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move { 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 { if keys.public_key() != device_pubkey {
return Err(anyhow!("Key mismatch")); return Err(anyhow!("Key mismatch"));
}; };
@@ -429,7 +312,7 @@ impl DeviceRegistry {
match task.await { match task.await {
Ok(keys) => { Ok(keys) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_device_signer(keys, cx); this.set_signer(keys, cx);
this.listen_device_request(cx); this.listen_device_request(cx);
}) })
.ok(); .ok();
@@ -551,7 +434,7 @@ impl DeviceRegistry {
match task.await { match task.await {
Ok(Some(keys)) => { Ok(Some(keys)) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_device_signer(keys, cx); this.set_signer(keys, cx);
}) })
.ok(); .ok();
} }
@@ -595,7 +478,7 @@ impl DeviceRegistry {
match task.await { match task.await {
Ok(keys) => { Ok(keys) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_device_signer(keys, cx); this.set_signer(keys, cx);
}) })
.ok(); .ok();
} }
@@ -617,7 +500,7 @@ impl DeviceRegistry {
let signer = client.signer().context("Signer not found")?; let signer = client.signer().context("Signer not found")?;
// Get device keys // Get device keys
let keys = Self::get_keys(&client).await?; let keys = get_keys(&client).await?;
let secret = keys.secret_key().to_secret_hex(); let secret = keys.secret_key().to_secret_hex();
// Extract the target public key from the event tags // Extract the target public key from the event tags
@@ -650,3 +533,56 @@ impl DeviceRegistry {
task.detach(); 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 { enum Dispatch {
Person(Box<Person>), Person(Box<Person>),
Announcement(Box<Event>), Announcement(Box<Event>),
Relays(Box<Event>),
} }
/// Person Registry /// Person Registry
@@ -100,6 +101,9 @@ impl PersonRegistry {
Dispatch::Announcement(event) => { Dispatch::Announcement(event) => {
this.set_announcement(&event, cx); this.set_announcement(&event, cx);
} }
Dispatch::Relays(event) => {
this.set_messaging_relays(&event, cx);
}
}; };
}) })
.ok(); .ok();
@@ -157,18 +161,24 @@ impl PersonRegistry {
// Send // Send
tx.send_async(Dispatch::Person(val)).await.ok(); 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 => { Kind::ContactList => {
let public_keys = event.extract_public_keys(); let public_keys = event.extract_public_keys();
// Get metadata for all public keys // Get metadata for all public keys
Self::get_metadata(client, public_keys).await.ok(); 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 /// Insert batch of persons
fn bulk_inserts(&mut self, persons: Vec<Person>, cx: &mut Context<Self>) { fn bulk_inserts(&mut self, persons: Vec<Person>, cx: &mut Context<Self>) {
for person in persons.into_iter() { for person in persons.into_iter() {

View File

@@ -18,6 +18,9 @@ pub struct Person {
/// Dekey (NIP-4e) announcement /// Dekey (NIP-4e) announcement
announcement: Option<Announcement>, announcement: Option<Announcement>,
/// Messaging relays
messaging_relays: Vec<RelayUrl>,
} }
impl PartialEq for Person { impl PartialEq for Person {
@@ -58,6 +61,7 @@ impl Person {
public_key, public_key,
metadata, metadata,
announcement: None, announcement: None,
messaging_relays: vec![],
} }
} }
@@ -82,6 +86,25 @@ impl Person {
log::info!("Updated announcement for: {}", self.public_key()); 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 /// Get profile avatar
pub fn avatar(&self) -> SharedString { pub fn avatar(&self) -> SharedString {
self.metadata() self.metadata()

View File

@@ -55,7 +55,21 @@ pub enum SignerKind {
#[default] #[default]
Auto, Auto,
User, 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 /// Room configuration
@@ -65,6 +79,16 @@ pub struct RoomConfig {
signer_kind: SignerKind, signer_kind: SignerKind,
} }
impl RoomConfig {
pub fn backup(&self) -> bool {
self.backup
}
pub fn signer_kind(&self) -> &SignerKind {
&self.signer_kind
}
}
/// Settings /// Settings
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings { pub struct Settings {

View File

@@ -4,11 +4,25 @@ use nostr_sdk::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum DeviceState { pub enum DeviceState {
#[default] #[default]
Initial, Idle,
Requesting, Requesting,
Set, 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 /// Announcement
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Announcement { pub struct Announcement {
@@ -24,7 +38,7 @@ impl From<&Event> for Announcement {
let public_key = val let public_key = val
.tags .tags
.iter() .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(|tag| tag.content())
.and_then(|c| PublicKey::parse(c).ok()) .and_then(|c| PublicKey::parse(c).ok())
.unwrap_or(val.pubkey); .unwrap_or(val.pubkey);

View File

@@ -96,13 +96,9 @@ impl NostrRegistry {
}); });
// Construct the nostr signer // 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())); 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 // Construct the nostr client
let client = ClientBuilder::default() let client = ClientBuilder::default()
.signer(signer.clone()) .signer(signer.clone())
@@ -122,6 +118,10 @@ impl NostrRegistry {
}) })
.build(); .build();
// Construct the relay states entity
let nip65 = cx.new(|_| RelayState::default());
let nip17 = cx.new(|_| RelayState::default());
let mut subscriptions = vec![]; let mut subscriptions = vec![];
subscriptions.push( 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| { cx.defer(|cx| {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
@@ -244,30 +253,6 @@ impl NostrRegistry {
cx.notify(); 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 /// Get a list of messaging relays with current signer's public key
pub fn messaging_relays(&self, cx: &App) -> Task<Vec<RelayUrl>> { pub fn messaging_relays(&self, cx: &App) -> Task<Vec<RelayUrl>> {
let client = self.client(); let client = self.client();
@@ -292,7 +277,7 @@ impl NostrRegistry {
.await .await
.ok() .ok()
.and_then(|events| events.first_owned()) .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(); .unwrap_or_default();
for relay in relays.iter() { 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 // Get relay list for current user
fn get_relay_list(&mut self, cx: &mut Context<Self>) { fn get_relay_list(&mut self, cx: &mut Context<Self>) {
let client = self.client(); 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 /// Get profile and contact list for current user
fn get_profile(&mut self, cx: &mut Context<Self>) { fn get_profile(&mut self, cx: &mut Context<Self>) {
let client = self.client(); let client = self.client();
@@ -688,6 +640,7 @@ impl NostrRegistry {
.send_event(&event) .send_event(&event)
.broadcast() .broadcast()
.ok_timeout(Duration::from_secs(TIMEOUT)) .ok_timeout(Duration::from_secs(TIMEOUT))
.ack_policy(AckPolicy::none())
.await?; .await?;
// Construct the default contact list // Construct the default contact list
@@ -699,6 +652,7 @@ impl NostrRegistry {
.send_event(&event) .send_event(&event)
.broadcast() .broadcast()
.ok_timeout(Duration::from_secs(TIMEOUT)) .ok_timeout(Duration::from_secs(TIMEOUT))
.ack_policy(AckPolicy::none())
.await?; .await?;
// Construct the default messaging relay list // Construct the default messaging relay list
@@ -710,6 +664,7 @@ impl NostrRegistry {
.send_event(&event) .send_event(&event)
.to_nip65() .to_nip65()
.ok_timeout(Duration::from_secs(TIMEOUT)) .ok_timeout(Duration::from_secs(TIMEOUT))
.ack_policy(AckPolicy::none())
.await?; .await?;
// Write user's credentials to the system keyring // 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>)> { fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
vec![ vec![
( (

View File

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