Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e95cc5967f | |||
| 5edc8d311e | |||
| e812ae05a9 | |||
| 0230fcff23 | |||
| 04983be23f | |||
| 57a129fa93 | |||
| c791309659 | |||
| d53e9d538c | |||
| a0d76e2cf4 | |||
| 2d3d90774c | |||
| ef227032bb | |||
| ce8f431aaa |
594
Cargo.lock
generated
594
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
12
Cargo.toml
12
Cargo.toml
@@ -19,12 +19,12 @@ gpui_tokio = { git = "https://github.com/zed-industries/zed" }
|
||||
reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
||||
|
||||
# Nostr
|
||||
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
||||
nostr-connect = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
||||
nostr-blossom = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
||||
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ], rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
||||
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr", }
|
||||
nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44" ] }
|
||||
|
||||
# Others
|
||||
anyhow = "1.0.44"
|
||||
|
||||
@@ -7,7 +7,6 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||
use common::EventExt;
|
||||
use device::{DeviceEvent, DeviceRegistry};
|
||||
use fuzzy_matcher::FuzzyMatcher;
|
||||
use fuzzy_matcher::skim::SkimMatcherV2;
|
||||
use gpui::{
|
||||
@@ -17,7 +16,7 @@ use gpui::{
|
||||
use nostr_sdk::prelude::*;
|
||||
use smallvec::{SmallVec, smallvec};
|
||||
use smol::lock::RwLock;
|
||||
use state::{CoopSigner, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP};
|
||||
use state::{DEVICE_GIFTWRAP, NostrRegistry, USER_GIFTWRAP};
|
||||
|
||||
mod message;
|
||||
mod room;
|
||||
@@ -42,6 +41,8 @@ pub enum ChatEvent {
|
||||
CloseRoom(u64),
|
||||
/// An event to notify UI about a new chat request
|
||||
Ping,
|
||||
/// No Inbox Relays found, the app is not ready to subscribe messages
|
||||
InboxRelayNotFound,
|
||||
/// An error occurred
|
||||
Error(SharedString),
|
||||
}
|
||||
@@ -49,6 +50,10 @@ pub enum ChatEvent {
|
||||
/// Channel signal.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Signal {
|
||||
/// Inbox Relays found, the app is ready to subscribe messages
|
||||
InboxReady(Box<Event>),
|
||||
/// No Inbox Relays found, the app is not ready to subscribe messages
|
||||
InboxRelayNotFound,
|
||||
/// Message received from relay pool
|
||||
Message(NewMessage),
|
||||
/// Eose received from relay pool
|
||||
@@ -62,6 +67,14 @@ impl Signal {
|
||||
Self::Message(NewMessage::new(gift_wrap, rumor))
|
||||
}
|
||||
|
||||
pub fn inbox_ready(event: &Event) -> Self {
|
||||
Self::InboxReady(Box::new(event.to_owned()))
|
||||
}
|
||||
|
||||
pub fn inbox_relay_not_found() -> Self {
|
||||
Self::InboxRelayNotFound
|
||||
}
|
||||
|
||||
pub fn eose() -> Self {
|
||||
Self::Eose
|
||||
}
|
||||
@@ -74,15 +87,9 @@ impl Signal {
|
||||
}
|
||||
}
|
||||
|
||||
type Dekey = bool;
|
||||
type GiftWrapId = EventId;
|
||||
|
||||
/// Chat Registry
|
||||
#[derive(Debug)]
|
||||
pub struct ChatRegistry {
|
||||
/// Whether the chat registry is currently initializing.
|
||||
pub initializing: bool,
|
||||
|
||||
/// Chat rooms
|
||||
rooms: Vec<Entity<Room>>,
|
||||
|
||||
@@ -93,10 +100,13 @@ pub struct ChatRegistry {
|
||||
seens: Arc<RwLock<HashMap<EventId, HashSet<RelayUrl>>>>,
|
||||
|
||||
/// Mapping of unwrapped event ids to their gift wrap event ids
|
||||
event_map: Arc<RwLock<HashMap<EventId, (GiftWrapId, Dekey)>>>,
|
||||
event_map: Arc<RwLock<HashMap<EventId, EventId>>>,
|
||||
|
||||
/// Tracking the status of unwrapping gift wrap events.
|
||||
tracking_flag: Arc<AtomicBool>,
|
||||
tracking: Arc<AtomicBool>,
|
||||
|
||||
/// Whether the messaging relays have been found.
|
||||
msg_relays_existed: Arc<AtomicBool>,
|
||||
|
||||
/// Channel for sending signals to the UI.
|
||||
signal_tx: flume::Sender<Signal>,
|
||||
@@ -127,66 +137,36 @@ impl ChatRegistry {
|
||||
/// Create a new chat registry instance
|
||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let device = DeviceRegistry::global(cx);
|
||||
let user_signer = nostr.read(cx).signer.clone();
|
||||
|
||||
let (tx, rx) = flume::unbounded::<Signal>();
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to the signer event
|
||||
cx.subscribe_in(&nostr, window, |this, state, event, window, cx| {
|
||||
if event == &StateEvent::SignerSet {
|
||||
cx.observe(&user_signer, |this, signer, cx| {
|
||||
if let Some(keys) = signer.read(cx).clone() {
|
||||
this.reset(cx);
|
||||
this.get_contact_list(cx);
|
||||
this.handle_notifications(keys, cx);
|
||||
this.get_metadata(cx);
|
||||
this.get_rooms(cx);
|
||||
|
||||
let signer = state.read(cx).signer();
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let user_signer = signer.get().await;
|
||||
this.update(cx, |this, cx| {
|
||||
this.get_messages(user_signer, cx);
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to the device event
|
||||
cx.subscribe_in(&device, window, |_this, _s, event, window, cx| {
|
||||
if event == &DeviceEvent::Set {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
if let Some(device_signer) = signer.get_encryption_signer().await {
|
||||
this.update(cx, |this, cx| {
|
||||
this.get_messages(device_signer, cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
// Run at the end of the current cycle
|
||||
cx.defer_in(window, |this, _window, cx| {
|
||||
this.get_rooms(cx);
|
||||
this.handle_notifications(cx);
|
||||
this.tracking(cx);
|
||||
this.get_rooms(cx);
|
||||
});
|
||||
|
||||
Self {
|
||||
initializing: true,
|
||||
rooms: vec![],
|
||||
trashes: cx.new(|_| BTreeSet::default()),
|
||||
seens: Arc::new(RwLock::new(HashMap::default())),
|
||||
event_map: Arc::new(RwLock::new(HashMap::default())),
|
||||
tracking_flag: Arc::new(AtomicBool::new(false)),
|
||||
tracking: Arc::new(AtomicBool::new(false)),
|
||||
msg_relays_existed: Arc::new(AtomicBool::new(false)),
|
||||
signal_rx: rx,
|
||||
signal_tx: tx,
|
||||
tasks: smallvec![],
|
||||
@@ -195,11 +175,13 @@ impl ChatRegistry {
|
||||
}
|
||||
|
||||
/// Handle nostr notifications
|
||||
fn handle_notifications(&mut self, cx: &mut Context<Self>) {
|
||||
fn handle_notifications(&mut self, signer: Keys, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
let status = self.tracking_flag.clone();
|
||||
|
||||
let tracking = self.tracking.clone();
|
||||
let msg_relays_existed = self.msg_relays_existed.clone();
|
||||
|
||||
let seens = self.seens.clone();
|
||||
let event_map = self.event_map.clone();
|
||||
let trashes = self.trashes.downgrade();
|
||||
@@ -223,10 +205,7 @@ impl ChatRegistry {
|
||||
};
|
||||
|
||||
match *message {
|
||||
RelayMessage::Event {
|
||||
event,
|
||||
subscription_id,
|
||||
} => {
|
||||
RelayMessage::Event { event, .. } => {
|
||||
// Keep track of which relays have seen this event
|
||||
{
|
||||
let mut seens = seens.write().await;
|
||||
@@ -238,6 +217,18 @@ impl ChatRegistry {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle msg relays event to determine when the app is ready to subscribe
|
||||
if event.kind == Kind::InboxRelays {
|
||||
let current_user = signer.get_public_key_async().await?;
|
||||
|
||||
if event.pubkey == current_user {
|
||||
// Mark that the msg relays have been found
|
||||
msg_relays_existed.store(true, Ordering::Release);
|
||||
// Emit the inbox ready signal
|
||||
tx.send_async(Signal::inbox_ready(&event)).await?;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip non-gift wrap events
|
||||
if event.kind != Kind::GiftWrap {
|
||||
continue;
|
||||
@@ -249,21 +240,12 @@ impl ChatRegistry {
|
||||
// Map the rumor id to the gift wrap event id for later lookup
|
||||
{
|
||||
let mut event_map = event_map.write().await;
|
||||
let dekey = subscription_id.as_ref() == &sub_id1;
|
||||
event_map.insert(rumor.id.unwrap(), (event.id, dekey));
|
||||
}
|
||||
|
||||
if rumor.kind != Kind::PrivateDirectMessage
|
||||
|| rumor.kind != Kind::Custom(15)
|
||||
{
|
||||
log::info!("Rumor is not releated to NIP17");
|
||||
continue;
|
||||
event_map.insert(rumor.id.unwrap(), event.id);
|
||||
}
|
||||
|
||||
// Check if the rumor has a recipient
|
||||
if rumor.tags.is_empty() {
|
||||
let signal =
|
||||
Signal::error(event.as_ref(), "Recipient is missing");
|
||||
let signal = Signal::error(&event, "Recipient is missing");
|
||||
tx.send_async(signal).await?;
|
||||
}
|
||||
|
||||
@@ -273,7 +255,7 @@ impl ChatRegistry {
|
||||
tx.send_async(signal).await?;
|
||||
} else {
|
||||
// Mark the chat still processing new messages
|
||||
status.store(true, Ordering::Release);
|
||||
tracking.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -283,11 +265,11 @@ impl ChatRegistry {
|
||||
}
|
||||
}
|
||||
}
|
||||
RelayMessage::EndOfStoredEvents(id) => {
|
||||
if id.as_ref() == &sub_id1 || id.as_ref() == &sub_id2 {
|
||||
RelayMessage::EndOfStoredEvents(id)
|
||||
if (id.as_ref() == &sub_id1 || id.as_ref() == &sub_id2) =>
|
||||
{
|
||||
tx.send_async(Signal::eose()).await?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -303,6 +285,16 @@ impl ChatRegistry {
|
||||
this.new_message(message, cx);
|
||||
})?;
|
||||
}
|
||||
Signal::InboxReady(event) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.get_messages(&event, cx);
|
||||
})?;
|
||||
}
|
||||
Signal::InboxRelayNotFound => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(ChatEvent::InboxRelayNotFound);
|
||||
})?;
|
||||
}
|
||||
Signal::Eose => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.get_rooms(cx);
|
||||
@@ -323,7 +315,7 @@ impl ChatRegistry {
|
||||
|
||||
/// Tracking the status of unwrapping gift wrap events.
|
||||
fn tracking(&mut self, cx: &mut Context<Self>) {
|
||||
let status = self.tracking_flag.clone();
|
||||
let status = self.tracking.clone();
|
||||
let tx = self.signal_tx.clone();
|
||||
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
@@ -341,107 +333,71 @@ impl ChatRegistry {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Get contact list from relays
|
||||
fn get_contact_list(&mut self, cx: &mut Context<Self>) {
|
||||
/// Get all necessary metadata from relays for current user
|
||||
pub fn get_metadata(&mut self, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
let Some(public_key) = signer.public_key() else {
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let id = SubscriptionId::new("contact-list");
|
||||
let opts = SubscribeAutoCloseOptions::default()
|
||||
.exit_policy(ReqExitPolicy::ExitOnEOSE)
|
||||
.timeout(Some(Duration::from_secs(TIMEOUT)));
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
// Construct filter for inbox relays
|
||||
let filter = Filter::new()
|
||||
// Construct filter for msg relays
|
||||
let msg_relays = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
// Construct filter for contact list
|
||||
let contact_list = Filter::new()
|
||||
.kind(Kind::ContactList)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
// Subscribe
|
||||
client.subscribe(filter).close_on(opts).with_id(id).await?;
|
||||
client
|
||||
.subscribe(vec![msg_relays, contact_list])
|
||||
.close_on(opts)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
}));
|
||||
|
||||
self.tasks.push(task);
|
||||
let tx = self.signal_tx.clone();
|
||||
let msg_relays_existed = self.msg_relays_existed.clone();
|
||||
|
||||
// Reset the status flag
|
||||
msg_relays_existed.store(false, Ordering::Release);
|
||||
|
||||
// Wait for the msg relays to be found or timeout
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
// Wait for 5 seconds
|
||||
smol::Timer::after(Duration::from_secs(5)).await;
|
||||
|
||||
// Then check if the msg relays have been found
|
||||
if !msg_relays_existed.load(Ordering::Acquire) {
|
||||
tx.send_async(Signal::inbox_relay_not_found()).await?;
|
||||
}
|
||||
|
||||
/// Get all messages for the provided signer
|
||||
fn get_messages<T>(&mut self, signer: T, cx: &mut Context<Self>)
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
let task = self.subscribe_gift_wrap_events(signer, cx);
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(_) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_initializing(false, cx);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(ChatEvent::Error(SharedString::from(e.to_string())));
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
// Get messaging relay list for current user
|
||||
fn get_messaging_relays(&self, cx: &App) -> Task<Result<Vec<RelayUrl>, Error>> {
|
||||
/// Get all messages for the provided signer
|
||||
fn get_messages(&mut self, msg_relays: &Event, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
let urls: Vec<RelayUrl> = nip17::extract_relay_list(msg_relays).collect();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let id = SubscriptionId::new("inbox-relay");
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Construct filter for inbox relays
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
// Stream events from user's write relays
|
||||
let mut stream = client
|
||||
.stream_events(filter)
|
||||
.with_id(id)
|
||||
.timeout(Duration::from_secs(TIMEOUT))
|
||||
.await?;
|
||||
|
||||
while let Some((_url, res)) = stream.next().await {
|
||||
if let Ok(event) = res {
|
||||
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
|
||||
return Ok(urls);
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow!("Messaging Relays not found"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Continuously get gift wrap events for the signer
|
||||
fn subscribe_gift_wrap_events<T>(&self, signer: T, cx: &App) -> Task<Result<(), Error>>
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let urls = self.get_messaging_relays(cx);
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let urls = urls.await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
||||
let id = SubscriptionId::new(format!("{}-msg", public_key.to_hex()));
|
||||
|
||||
@@ -464,43 +420,28 @@ impl ChatRegistry {
|
||||
);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
if let Err(e) = task.await {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(ChatEvent::Error(SharedString::from(e.to_string())));
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Refresh the chat registry, fetching messages and contact list from relays.
|
||||
pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||
self.reset(cx);
|
||||
self.get_contact_list(cx);
|
||||
self.get_metadata(cx);
|
||||
self.get_rooms(cx);
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let user_signer = signer.get().await;
|
||||
let device_signer = signer.get_encryption_signer().await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.get_messages(user_signer, cx);
|
||||
|
||||
if let Some(device_signer) = device_signer {
|
||||
this.get_messages(device_signer, cx);
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Set the initializing status of the chat registry
|
||||
fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
|
||||
self.initializing = initializing;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Get the loading status of the chat registry
|
||||
pub fn loading(&self) -> bool {
|
||||
self.tracking_flag.load(Ordering::Acquire)
|
||||
self.tracking.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Get a weak reference to a room by its ID.
|
||||
@@ -552,7 +493,7 @@ impl ChatRegistry {
|
||||
self.event_map
|
||||
.read_blocking()
|
||||
.get(id)
|
||||
.map(|(id, _dekey)| self.seen_on(id))
|
||||
.map(|id| self.seen_on(id))
|
||||
}
|
||||
|
||||
/// Get the relays that have seen a given gift wrap id.
|
||||
@@ -564,26 +505,18 @@ impl ChatRegistry {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Check if a given rumor was encrypted by the dekey.
|
||||
pub fn encrypted_by_dekey(&self, id: &EventId) -> bool {
|
||||
self.event_map
|
||||
.read_blocking()
|
||||
.get(id)
|
||||
.map(|(_, dekey)| *dekey)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Add a new room to the start of list.
|
||||
pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>)
|
||||
where
|
||||
I: Into<Room> + 'static,
|
||||
{
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let signer = client.signer()?;
|
||||
let public_key = signer.get_public_key().await.ok()?;
|
||||
let room: Room = room.into().organize(&public_key);
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -650,7 +583,6 @@ impl ChatRegistry {
|
||||
|
||||
/// Reset the registry.
|
||||
pub fn reset(&mut self, cx: &mut Context<Self>) {
|
||||
self.initializing = true;
|
||||
self.rooms.clear();
|
||||
self.trashes.update(cx, |this, cx| {
|
||||
this.clear();
|
||||
@@ -689,7 +621,13 @@ impl ChatRegistry {
|
||||
|
||||
/// Load all rooms from the database.
|
||||
pub fn get_rooms(&mut self, cx: &mut Context<Self>) {
|
||||
let task = self.get_rooms_from_database(cx);
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task = self.get_rooms_from_database(public_key, cx);
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
@@ -709,14 +647,15 @@ impl ChatRegistry {
|
||||
}
|
||||
|
||||
/// Create a task to load rooms from the database
|
||||
fn get_rooms_from_database(&self, cx: &App) -> Task<Result<HashSet<Room>, Error>> {
|
||||
fn get_rooms_from_database(
|
||||
&self,
|
||||
public_key: PublicKey,
|
||||
cx: &App,
|
||||
) -> Task<Result<HashSet<Room>, Error>> {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
// Get contacts
|
||||
let contacts = client
|
||||
.database()
|
||||
@@ -793,15 +732,15 @@ impl ChatRegistry {
|
||||
/// Updates room ordering based on the most recent messages.
|
||||
pub fn new_message(&mut self, message: NewMessage, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
match self.rooms.iter().find(|e| e.read(cx).id == message.room) {
|
||||
Some(room) => {
|
||||
room.update(cx, |this, cx| {
|
||||
if this.kind == RoomKind::Request
|
||||
&& let Some(public_key) = signer.public_key()
|
||||
&& message.rumor.pubkey == public_key
|
||||
{
|
||||
if this.kind == RoomKind::Request && message.rumor.pubkey == public_key {
|
||||
this.set_ongoing(cx);
|
||||
}
|
||||
this.push_message(message, cx);
|
||||
@@ -830,7 +769,7 @@ impl ChatRegistry {
|
||||
/// Unwraps a gift-wrapped event and processes its contents.
|
||||
async fn extract_rumor(
|
||||
client: &Client,
|
||||
signer: &Arc<CoopSigner>,
|
||||
signer: &Keys,
|
||||
gift_wrap: &Event,
|
||||
) -> Result<UnsignedEvent, Error> {
|
||||
// Try to get cached rumor first
|
||||
@@ -854,8 +793,9 @@ async fn extract_rumor(
|
||||
}
|
||||
|
||||
/// Helper method to try unwrapping with different signers
|
||||
async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
|
||||
// Try with the device signer first
|
||||
async fn try_unwrap(signer: &Keys, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
|
||||
/*
|
||||
* // Try with the device signer first
|
||||
if let Some(signer) = signer.get_encryption_signer().await {
|
||||
log::info!("trying with encryption key");
|
||||
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, &signer).await {
|
||||
@@ -865,19 +805,17 @@ async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<Unwra
|
||||
|
||||
// Fallback to the user's signer
|
||||
let user_signer = signer.get().await;
|
||||
let unwrapped = try_unwrap_with(gift_wrap, &user_signer).await?;
|
||||
*/
|
||||
let unwrapped = try_unwrap_with(gift_wrap, signer).await?;
|
||||
|
||||
Ok(unwrapped)
|
||||
}
|
||||
|
||||
/// Attempts to unwrap a gift wrap event with a given signer.
|
||||
async fn try_unwrap_with<T>(gift_wrap: &Event, signer: &T) -> Result<UnwrappedGift, Error>
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
async fn try_unwrap_with(gift_wrap: &Event, signer: &Keys) -> Result<UnwrappedGift, Error> {
|
||||
// Get the sealed event
|
||||
let seal = signer
|
||||
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)
|
||||
.nip44_decrypt_async(&gift_wrap.pubkey, &gift_wrap.content)
|
||||
.await?;
|
||||
|
||||
// Verify the sealed event
|
||||
@@ -885,7 +823,10 @@ where
|
||||
seal.verify_with_ctx(&SECP256K1)?;
|
||||
|
||||
// Get the rumor event
|
||||
let rumor = signer.nip44_decrypt(&seal.pubkey, &seal.content).await?;
|
||||
let rumor = signer
|
||||
.nip44_decrypt_async(&seal.pubkey, &seal.content)
|
||||
.await?;
|
||||
|
||||
let rumor = UnsignedEvent::from_json(rumor)?;
|
||||
|
||||
Ok(UnwrappedGift {
|
||||
@@ -906,26 +847,17 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
|
||||
tags.push(Tag::identifier(id));
|
||||
|
||||
// Add a reference to the rumor's author
|
||||
tags.push(Tag::custom(
|
||||
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::A)),
|
||||
[author],
|
||||
));
|
||||
tags.push(Tag::custom("a", [author]));
|
||||
|
||||
// Add a conversation id
|
||||
tags.push(Tag::custom(
|
||||
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::C)),
|
||||
[conversation.to_string()],
|
||||
));
|
||||
tags.push(Tag::custom("c", [conversation.to_string()]));
|
||||
|
||||
// Add a reference to the rumor's id
|
||||
tags.push(Tag::event(rumor_id));
|
||||
|
||||
// Add references to the rumor's participants
|
||||
for receiver in rumor.tags.public_keys().copied() {
|
||||
tags.push(Tag::custom(
|
||||
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::P)),
|
||||
[receiver],
|
||||
));
|
||||
for receiver in rumor.tags.public_keys() {
|
||||
tags.push(Tag::custom("P", [receiver]));
|
||||
}
|
||||
|
||||
// Convert rumor to json
|
||||
@@ -934,7 +866,7 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
|
||||
// Construct the event
|
||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
||||
.tags(tags)
|
||||
.sign(&Keys::generate())
|
||||
.finalize_async(&Keys::generate())
|
||||
.await?;
|
||||
|
||||
// Save the event to the database
|
||||
@@ -960,7 +892,7 @@ async fn get_rumor(client: &Client, gift_wrap: EventId) -> Result<UnsignedEvent,
|
||||
/// Get the conversation ID for a given rumor (message).
|
||||
fn conversation_id(rumor: &UnsignedEvent) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
let mut pubkeys: Vec<PublicKey> = rumor.tags.public_keys().copied().collect();
|
||||
let mut pubkeys: Vec<PublicKey> = rumor.tags.public_keys().collect();
|
||||
pubkeys.push(rumor.pubkey);
|
||||
pubkeys.sort();
|
||||
pubkeys.dedup();
|
||||
|
||||
@@ -5,6 +5,106 @@ use common::{EventExt, NostrParser, extract_and_remove_media_urls};
|
||||
use gpui::{SharedString, SharedUri};
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
/// Rendered message.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Message {
|
||||
pub id: EventId,
|
||||
/// Author's public key
|
||||
pub author: PublicKey,
|
||||
/// The content/text of the message
|
||||
pub content: String,
|
||||
/// List of media URLs in the message
|
||||
pub media: Vec<SharedUri>,
|
||||
/// Message created time as unix timestamp
|
||||
pub created_at: Timestamp,
|
||||
/// List of mentioned public keys in the message
|
||||
pub mentions: Vec<Mention>,
|
||||
/// List of event of the message this message is a reply to
|
||||
pub replies_to: Vec<EventId>,
|
||||
}
|
||||
|
||||
impl From<&Event> for Message {
|
||||
fn from(val: &Event) -> Self {
|
||||
let mentions = extract_mentions(&val.content);
|
||||
let replies_to = extract_reply_ids(&val.tags);
|
||||
let (media, string) = extract_and_remove_media_urls(&val.content);
|
||||
|
||||
Self {
|
||||
id: val.id,
|
||||
author: val.pubkey,
|
||||
content: string,
|
||||
media,
|
||||
created_at: val.created_at,
|
||||
mentions,
|
||||
replies_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&UnsignedEvent> for Message {
|
||||
fn from(val: &UnsignedEvent) -> Self {
|
||||
let mentions = extract_mentions(&val.content);
|
||||
let replies_to = extract_reply_ids(&val.tags);
|
||||
let (media, string) = extract_and_remove_media_urls(&val.content);
|
||||
|
||||
Self {
|
||||
// Event ID must be known
|
||||
id: val.id.unwrap(),
|
||||
author: val.pubkey,
|
||||
content: string,
|
||||
media,
|
||||
created_at: val.created_at,
|
||||
mentions,
|
||||
replies_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&NewMessage> for Message {
|
||||
fn from(val: &NewMessage) -> Self {
|
||||
let mentions = extract_mentions(&val.rumor.content);
|
||||
let replies_to = extract_reply_ids(&val.rumor.tags);
|
||||
let (media, string) = extract_and_remove_media_urls(&val.rumor.content);
|
||||
|
||||
Self {
|
||||
// Event ID must be known
|
||||
id: val.rumor.id.unwrap(),
|
||||
author: val.rumor.pubkey,
|
||||
content: string,
|
||||
media,
|
||||
created_at: val.rumor.created_at,
|
||||
mentions,
|
||||
replies_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Message {}
|
||||
|
||||
impl PartialEq for Message {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Message {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.created_at.cmp(&other.created_at)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Message {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for Message {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.id.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// New message.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct NewMessage {
|
||||
@@ -44,74 +144,6 @@ impl FailedMessage {
|
||||
}
|
||||
}
|
||||
|
||||
/// Message.
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||
pub enum Message {
|
||||
User(RenderedMessage),
|
||||
Warning(String, Timestamp),
|
||||
System(Timestamp),
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn user<I>(user: I) -> Self
|
||||
where
|
||||
I: Into<RenderedMessage>,
|
||||
{
|
||||
Self::User(user.into())
|
||||
}
|
||||
|
||||
pub fn warning<I>(content: I) -> Self
|
||||
where
|
||||
I: Into<String>,
|
||||
{
|
||||
Self::Warning(content.into(), Timestamp::now())
|
||||
}
|
||||
|
||||
pub fn system() -> Self {
|
||||
Self::System(Timestamp::default())
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> &Timestamp {
|
||||
match self {
|
||||
Message::User(msg) => &msg.created_at,
|
||||
Message::Warning(_, ts) => ts,
|
||||
Message::System(ts) => ts,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&NewMessage> for Message {
|
||||
fn from(val: &NewMessage) -> Self {
|
||||
Self::User(val.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&UnsignedEvent> for Message {
|
||||
fn from(val: &UnsignedEvent) -> Self {
|
||||
Self::User(val.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Message {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
match (self, other) {
|
||||
// System always comes first
|
||||
(Message::System(_), Message::System(_)) => self.timestamp().cmp(other.timestamp()),
|
||||
(Message::System(_), _) => std::cmp::Ordering::Less,
|
||||
(_, Message::System(_)) => std::cmp::Ordering::Greater,
|
||||
|
||||
// For non-system messages, compare by timestamp
|
||||
_ => self.timestamp().cmp(other.timestamp()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Message {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Mention {
|
||||
pub public_key: PublicKey,
|
||||
@@ -124,106 +156,6 @@ impl Mention {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rendered message.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RenderedMessage {
|
||||
pub id: EventId,
|
||||
/// Author's public key
|
||||
pub author: PublicKey,
|
||||
/// The content/text of the message
|
||||
pub content: String,
|
||||
/// List of media URLs in the message
|
||||
pub media: Vec<SharedUri>,
|
||||
/// Message created time as unix timestamp
|
||||
pub created_at: Timestamp,
|
||||
/// List of mentioned public keys in the message
|
||||
pub mentions: Vec<Mention>,
|
||||
/// List of event of the message this message is a reply to
|
||||
pub replies_to: Vec<EventId>,
|
||||
}
|
||||
|
||||
impl From<&Event> for RenderedMessage {
|
||||
fn from(val: &Event) -> Self {
|
||||
let mentions = extract_mentions(&val.content);
|
||||
let replies_to = extract_reply_ids(&val.tags);
|
||||
let (media, string) = extract_and_remove_media_urls(&val.content);
|
||||
|
||||
Self {
|
||||
id: val.id,
|
||||
author: val.pubkey,
|
||||
content: string,
|
||||
media,
|
||||
created_at: val.created_at,
|
||||
mentions,
|
||||
replies_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&UnsignedEvent> for RenderedMessage {
|
||||
fn from(val: &UnsignedEvent) -> Self {
|
||||
let mentions = extract_mentions(&val.content);
|
||||
let replies_to = extract_reply_ids(&val.tags);
|
||||
let (media, string) = extract_and_remove_media_urls(&val.content);
|
||||
|
||||
Self {
|
||||
// Event ID must be known
|
||||
id: val.id.unwrap(),
|
||||
author: val.pubkey,
|
||||
content: string,
|
||||
media,
|
||||
created_at: val.created_at,
|
||||
mentions,
|
||||
replies_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&NewMessage> for RenderedMessage {
|
||||
fn from(val: &NewMessage) -> Self {
|
||||
let mentions = extract_mentions(&val.rumor.content);
|
||||
let replies_to = extract_reply_ids(&val.rumor.tags);
|
||||
let (media, string) = extract_and_remove_media_urls(&val.rumor.content);
|
||||
|
||||
Self {
|
||||
// Event ID must be known
|
||||
id: val.rumor.id.unwrap(),
|
||||
author: val.rumor.pubkey,
|
||||
content: string,
|
||||
media,
|
||||
created_at: val.rumor.created_at,
|
||||
mentions,
|
||||
replies_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for RenderedMessage {}
|
||||
|
||||
impl PartialEq for RenderedMessage {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for RenderedMessage {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.created_at.cmp(&other.created_at)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for RenderedMessage {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for RenderedMessage {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.id.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts all mentions (public keys) from a content string.
|
||||
fn extract_mentions(content: &str) -> Vec<Mention> {
|
||||
let parser = NostrParser::new();
|
||||
@@ -242,13 +174,13 @@ fn extract_mentions(content: &str) -> Vec<Mention> {
|
||||
fn extract_reply_ids(inner: &Tags) -> Vec<EventId> {
|
||||
let mut replies_to = vec![];
|
||||
|
||||
for tag in inner.filter(TagKind::e()) {
|
||||
for tag in inner.iter().filter(|tag| tag.kind() == "e") {
|
||||
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
||||
replies_to.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
for tag in inner.filter(TagKind::q()) {
|
||||
for tag in inner.iter().filter(|tag| tag.kind() == "q") {
|
||||
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
||||
replies_to.push(id);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::{Error, anyhow};
|
||||
use common::EventExt;
|
||||
use device::DeviceRegistry;
|
||||
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
@@ -21,7 +22,7 @@ pub struct SendReport {
|
||||
pub receiver: PublicKey,
|
||||
pub gift_wrap_id: Option<EventId>,
|
||||
pub error: Option<SharedString>,
|
||||
pub output: Option<Output<EventId>>,
|
||||
pub output: Option<Output<EventId, EventSendStatus>>,
|
||||
}
|
||||
|
||||
impl SendReport {
|
||||
@@ -41,7 +42,7 @@ impl SendReport {
|
||||
}
|
||||
|
||||
/// Set the output.
|
||||
pub fn output(mut self, output: Output<EventId>) -> Self {
|
||||
pub fn output(mut self, output: Output<EventId, EventSendStatus>) -> Self {
|
||||
self.output = Some(output);
|
||||
self
|
||||
}
|
||||
@@ -171,7 +172,8 @@ impl From<&UnsignedEvent> for Room {
|
||||
let members = val.extract_public_keys();
|
||||
let subject = val
|
||||
.tags
|
||||
.find(TagKind::Subject)
|
||||
.iter()
|
||||
.find(|tag| tag.kind() == "subject")
|
||||
.and_then(|tag| tag.content().map(|s| s.to_owned().into()));
|
||||
|
||||
Room {
|
||||
@@ -205,7 +207,7 @@ impl Room {
|
||||
// WARNING: never sign this event
|
||||
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, "")
|
||||
.tags(tags)
|
||||
.build(author);
|
||||
.finalize_unsigned(author);
|
||||
|
||||
// Ensure that the ID is set
|
||||
event.ensure_id();
|
||||
@@ -425,7 +427,7 @@ impl Room {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
|
||||
// Get current user's public key
|
||||
let sender = nostr.read(cx).signer().public_key()?;
|
||||
let sender = nostr.read(cx).signer_pubkey(cx)?;
|
||||
|
||||
// Get all members, excluding the sender
|
||||
let members: Vec<Person> = self
|
||||
@@ -440,9 +442,7 @@ impl Room {
|
||||
|
||||
// Add subject tag if present
|
||||
if let Some(value) = self.subject.as_ref() {
|
||||
tags.push(Tag::from_standardized_without_cell(TagStandard::Subject(
|
||||
value.to_string(),
|
||||
)));
|
||||
tags.push(Tag::custom("subject", vec![value.to_string()]));
|
||||
}
|
||||
|
||||
// Add all reply tags
|
||||
@@ -452,19 +452,20 @@ impl Room {
|
||||
|
||||
// Add all receiver tags
|
||||
for member in members.into_iter() {
|
||||
tags.push(Tag::from_standardized_without_cell(
|
||||
TagStandard::PublicKey {
|
||||
tags.push(
|
||||
Nip01Tag::PublicKey {
|
||||
public_key: member.public_key(),
|
||||
relay_url: member.messaging_relay_hint(),
|
||||
alias: None,
|
||||
uppercase: false,
|
||||
},
|
||||
));
|
||||
relay_hint: member.messaging_relay_hint(),
|
||||
}
|
||||
.to_tag(),
|
||||
);
|
||||
}
|
||||
|
||||
// Construct a direct message rumor event
|
||||
// WARNING: never sign and send this event to relays
|
||||
let mut event = EventBuilder::new(kind, content).tags(tags).build(sender);
|
||||
let mut event = EventBuilder::new(kind, content)
|
||||
.tags(tags)
|
||||
.finalize_unsigned(sender);
|
||||
|
||||
// Ensure that the ID is set
|
||||
event.ensure_id();
|
||||
@@ -475,13 +476,18 @@ impl Room {
|
||||
/// Send rumor event to all members's messaging relays
|
||||
pub fn send(&self, rumor: UnsignedEvent, cx: &App) -> Option<Task<Vec<SendReport>>> {
|
||||
let config = self.config.clone();
|
||||
let persons = PersonRegistry::global(cx);
|
||||
|
||||
let device = DeviceRegistry::global(cx);
|
||||
let encryption_signer = device.read(cx).signer(cx);
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
// Get current user's public key
|
||||
let public_key = nostr.read(cx).signer().public_key()?;
|
||||
let user_signer = nostr.read(cx).signer(cx)?;
|
||||
let public_key = nostr.read(cx).signer_pubkey(cx)?;
|
||||
|
||||
let persons = PersonRegistry::global(cx);
|
||||
let sender = persons.read(cx).get(&public_key, cx);
|
||||
|
||||
// Get all members (excluding sender)
|
||||
@@ -496,9 +502,6 @@ impl Room {
|
||||
let signer_kind = config.signer_kind();
|
||||
let backup = config.backup();
|
||||
|
||||
let user_signer = signer.get().await;
|
||||
let encryption_signer = signer.get_encryption_signer().await;
|
||||
|
||||
let mut sents = 0;
|
||||
let mut reports = Vec::new();
|
||||
|
||||
@@ -592,17 +595,14 @@ impl Room {
|
||||
}
|
||||
|
||||
// Helper function to send a gift-wrapped event
|
||||
async fn send_gift_wrap<T>(
|
||||
async fn send_gift_wrap(
|
||||
client: &Client,
|
||||
signer: &T,
|
||||
signer: &Keys,
|
||||
receiver: &Person,
|
||||
rumor: &UnsignedEvent,
|
||||
config: &SignerKind,
|
||||
) -> Result<SendReport, Error>
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
let k_tag = Tag::custom(TagKind::k(), vec!["14"]);
|
||||
) -> Result<SendReport, Error> {
|
||||
let k_tag = Tag::custom("k", vec!["14"]);
|
||||
let mut extra_tags = vec![k_tag];
|
||||
|
||||
// Determine the receiver public key based on the config
|
||||
@@ -627,7 +627,10 @@ where
|
||||
};
|
||||
|
||||
// Construct the gift wrap event
|
||||
let event = EventBuilder::gift_wrap(signer, &receiver, rumor.clone(), extra_tags).await?;
|
||||
let event = nip59::GiftWrapBuilder::new(receiver, rumor.clone())
|
||||
.extra_tags(extra_tags)
|
||||
.finalize_async(signer)
|
||||
.await?;
|
||||
|
||||
// Send the gift wrap event and collect the report
|
||||
let report = client
|
||||
|
||||
@@ -3,15 +3,15 @@ use std::sync::Arc;
|
||||
|
||||
pub use actions::*;
|
||||
use anyhow::{Context as AnyhowContext, Error};
|
||||
use chat::{ChatRegistry, Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus};
|
||||
use chat::{ChatRegistry, Message, Room, RoomEvent, SendReport, SendStatus};
|
||||
use common::{TimestampExt, coop_cache};
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||
Focusable, InteractiveElement, IntoElement, ListAlignment, ListOffset, ListState, MouseButton,
|
||||
ObjectFit, ParentElement, PathPromptOptions, Render, SharedString, SharedUri,
|
||||
StatefulInteractiveElement, Styled, StyledImage, Subscription, Task, WeakEntity, Window,
|
||||
deferred, div, img, list, px, red, relative, svg, white,
|
||||
StatefulInteractiveElement, Styled, StyledImage, Subscription, Task, WeakEntity, Window, div,
|
||||
img, list, px, red, relative, svg, white,
|
||||
};
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
@@ -38,9 +38,6 @@ use crate::text::RenderedText;
|
||||
mod actions;
|
||||
mod text;
|
||||
|
||||
const ANNOUNCEMENT: &str =
|
||||
"This conversation is private. Only members can see each other's messages.";
|
||||
|
||||
pub fn init(room: WeakEntity<Room>, window: &mut Window, cx: &mut App) -> Entity<ChatPanel> {
|
||||
cx.new(|cx| ChatPanel::new(room, window, cx))
|
||||
}
|
||||
@@ -101,7 +98,7 @@ impl ChatPanel {
|
||||
let reports_by_id = cx.new(|_| BTreeMap::new());
|
||||
|
||||
// Define list of messages
|
||||
let messages = BTreeSet::from([Message::system()]);
|
||||
let messages = BTreeSet::default();
|
||||
let list_state = ListState::new(messages.len(), ListAlignment::Bottom, px(1024.));
|
||||
|
||||
// Get room id and name
|
||||
@@ -234,7 +231,7 @@ impl ChatPanel {
|
||||
match &*status {
|
||||
SendStatus::Ok { id, relay } => {
|
||||
if output.id() == id {
|
||||
output.success.insert(relay.clone());
|
||||
output.success.insert(relay.clone(), EventSendStatus::Sent);
|
||||
}
|
||||
}
|
||||
SendStatus::Failed { id, relay, message } => {
|
||||
@@ -470,37 +467,19 @@ impl ChatPanel {
|
||||
self.reports_by_id.read(cx).get(id).is_some()
|
||||
}
|
||||
|
||||
/// Check if a message was encrypted by the dekey
|
||||
fn encrypted_by_dekey(&self, id: &EventId, cx: &App) -> bool {
|
||||
let chat = ChatRegistry::global(cx);
|
||||
chat.read(cx).encrypted_by_dekey(id)
|
||||
}
|
||||
|
||||
/// Get all sent reports for a message by its ID
|
||||
fn sent_reports(&self, id: &EventId, cx: &App) -> Option<Vec<SendReport>> {
|
||||
self.reports_by_id.read(cx).get(id).cloned()
|
||||
}
|
||||
|
||||
/// Get a message by its ID
|
||||
fn message(&self, id: &EventId) -> Option<&RenderedMessage> {
|
||||
self.messages.iter().find_map(|msg| {
|
||||
if let Message::User(rendered) = msg
|
||||
&& &rendered.id == id
|
||||
{
|
||||
return Some(rendered);
|
||||
}
|
||||
None
|
||||
})
|
||||
fn message(&self, id: &EventId) -> Option<&Message> {
|
||||
self.messages.iter().find(|msg| &msg.id == id)
|
||||
}
|
||||
|
||||
fn scroll_to(&self, id: EventId) {
|
||||
if let Some(ix) = self.messages.iter().position(|m| {
|
||||
if let Message::User(msg) = m {
|
||||
msg.id == id
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}) {
|
||||
/// Scroll to a message by its ID
|
||||
fn scroll_to(&self, id: &EventId) {
|
||||
if let Some(ix) = self.messages.iter().position(|msg| &msg.id == id) {
|
||||
self.list_state.scroll_to_reveal_item(ix);
|
||||
}
|
||||
}
|
||||
@@ -620,13 +599,19 @@ impl ChatPanel {
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
window.push_notification(
|
||||
Notification::error("Failed to change subject").autohide(false),
|
||||
cx,
|
||||
);
|
||||
window.push_notification(Notification::error("Failed to change subject"), cx);
|
||||
}
|
||||
}
|
||||
Command::ChangeSigner(kind) => {
|
||||
let settings = AppSettings::global(cx);
|
||||
let is_nip4e_enabled = settings.read(cx).is_nip4e_enabled(cx);
|
||||
let is_force_nip4e = *kind == SignerKind::Encryption || *kind == SignerKind::Auto;
|
||||
|
||||
if !is_nip4e_enabled && is_force_nip4e {
|
||||
window.push_notification("Decoupling Encryption Key is not enabled", cx);
|
||||
return;
|
||||
}
|
||||
|
||||
if self
|
||||
.room
|
||||
.update(cx, |this, cx| {
|
||||
@@ -634,10 +619,7 @@ impl ChatPanel {
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
window.push_notification(
|
||||
Notification::error("Failed to change signer").autohide(false),
|
||||
cx,
|
||||
);
|
||||
window.push_notification(Notification::error("Failed to change signer"), cx);
|
||||
}
|
||||
}
|
||||
Command::ToggleBackup => {
|
||||
@@ -648,10 +630,7 @@ impl ChatPanel {
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
window.push_notification(
|
||||
Notification::error("Failed to toggle backup").autohide(false),
|
||||
cx,
|
||||
);
|
||||
window.push_notification(Notification::error("Failed to toggle backup"), cx);
|
||||
}
|
||||
}
|
||||
Command::Copy(public_key) => {
|
||||
@@ -748,9 +727,11 @@ impl ChatPanel {
|
||||
cx.open_url(&content);
|
||||
}
|
||||
|
||||
fn render_announcement(&self, ix: usize, cx: &Context<Self>) -> AnyElement {
|
||||
fn render_announcement(&self, cx: &Context<Self>) -> AnyElement {
|
||||
const MSG: &str =
|
||||
"This conversation is private. Only members can see each other's messages.";
|
||||
|
||||
v_flex()
|
||||
.id(ix)
|
||||
.h_40()
|
||||
.w_full()
|
||||
.gap_3()
|
||||
@@ -767,7 +748,7 @@ impl ChatPanel {
|
||||
.size_12()
|
||||
.text_color(cx.theme().ghost_element_active),
|
||||
)
|
||||
.child(SharedString::from(ANNOUNCEMENT))
|
||||
.child(MSG)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
@@ -804,6 +785,34 @@ impl ChatPanel {
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn is_group_start(&self, ix: usize) -> bool {
|
||||
// 5 minutes
|
||||
const GROUP_WINDOW: u64 = 300;
|
||||
|
||||
if ix == 0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
let mut iter = self.messages.iter();
|
||||
|
||||
if let Some(previous) = iter.nth(ix - 1)
|
||||
&& let Some(current) = iter.next()
|
||||
{
|
||||
if current.author != previous.author {
|
||||
return true;
|
||||
}
|
||||
|
||||
let gap = current
|
||||
.created_at
|
||||
.as_secs()
|
||||
.saturating_sub(previous.created_at.as_secs());
|
||||
|
||||
return gap > GROUP_WINDOW;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn render_message(
|
||||
&mut self,
|
||||
ix: usize,
|
||||
@@ -811,24 +820,17 @@ impl ChatPanel {
|
||||
cx: &mut Context<Self>,
|
||||
) -> AnyElement {
|
||||
if let Some(message) = self.messages.iter().nth(ix) {
|
||||
match message {
|
||||
Message::User(rendered) => {
|
||||
let persons = PersonRegistry::global(cx);
|
||||
let show_author = self.is_group_start(ix);
|
||||
let text = self
|
||||
.rendered_texts_by_id
|
||||
.entry(rendered.id)
|
||||
.entry(message.id)
|
||||
.or_insert_with(|| {
|
||||
RenderedText::new(&rendered.content, &rendered.mentions, &persons, cx)
|
||||
RenderedText::new(&message.content, &message.mentions, &persons, cx)
|
||||
})
|
||||
.element(ix.into(), window, cx);
|
||||
|
||||
self.render_text_message(ix, rendered, text, cx)
|
||||
}
|
||||
Message::Warning(content, _timestamp) => {
|
||||
self.render_warning(ix, SharedString::from(content), cx)
|
||||
}
|
||||
Message::System(_timestamp) => self.render_announcement(ix, cx),
|
||||
}
|
||||
self.render_text_message(ix, message, text, show_author, cx)
|
||||
} else {
|
||||
self.render_warning(ix, SharedString::from("Message not found"), cx)
|
||||
}
|
||||
@@ -837,8 +839,9 @@ impl ChatPanel {
|
||||
fn render_text_message(
|
||||
&self,
|
||||
ix: usize,
|
||||
message: &RenderedMessage,
|
||||
message: &Message,
|
||||
rendered_text: AnyElement,
|
||||
show_author: bool,
|
||||
cx: &Context<Self>,
|
||||
) -> AnyElement {
|
||||
let id = message.id;
|
||||
@@ -848,7 +851,6 @@ impl ChatPanel {
|
||||
let replies = message.replies_to.as_slice();
|
||||
let has_replies = !replies.is_empty();
|
||||
let has_reports = self.has_reports(&id, cx);
|
||||
let encrypted_by_dekey = self.encrypted_by_dekey(&id, cx);
|
||||
|
||||
// Hide avatar setting
|
||||
let hide_avatar = AppSettings::get_hide_avatar(cx);
|
||||
@@ -865,6 +867,7 @@ impl ChatPanel {
|
||||
.flex()
|
||||
.gap_3()
|
||||
.when(!hide_avatar, |this| {
|
||||
if show_author {
|
||||
this.child(
|
||||
Avatar::new(author.avatar())
|
||||
.flex_shrink_0()
|
||||
@@ -876,6 +879,9 @@ impl ChatPanel {
|
||||
.menu("View on njump.me", Box::new(Command::Njump(pk)))
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
this.child(div().flex_shrink_0().w(px(32.)))
|
||||
}
|
||||
})
|
||||
.child(
|
||||
v_flex()
|
||||
@@ -883,7 +889,8 @@ impl ChatPanel {
|
||||
.w_full()
|
||||
.flex_initial()
|
||||
.overflow_hidden()
|
||||
.child(
|
||||
.when(show_author, |this| {
|
||||
this.child(
|
||||
h_flex()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
@@ -894,22 +901,12 @@ impl ChatPanel {
|
||||
.text_color(cx.theme().text)
|
||||
.child(author.name()),
|
||||
)
|
||||
.when(encrypted_by_dekey, |this| {
|
||||
this.child(
|
||||
Button::new(format!("dekey-{ix}"))
|
||||
.icon(IconName::Shield)
|
||||
.ghost()
|
||||
.xsmall()
|
||||
.px_4()
|
||||
.tooltip("Encrypted by Dekey")
|
||||
.disabled(true),
|
||||
)
|
||||
})
|
||||
.child(message.created_at.to_human_time())
|
||||
.when(has_reports, |this| {
|
||||
this.child(deferred(self.render_sent_reports(&id, cx)))
|
||||
this.child(self.render_sent_reports(&id, cx))
|
||||
}),
|
||||
)
|
||||
})
|
||||
.when(has_replies, |this| {
|
||||
this.children(self.render_message_replies(replies, cx))
|
||||
})
|
||||
@@ -1027,7 +1024,7 @@ impl ChatPanel {
|
||||
.on_click({
|
||||
let id = *id;
|
||||
cx.listener(move |this, _event, _window, _cx| {
|
||||
this.scroll_to(id);
|
||||
this.scroll_to(&id);
|
||||
})
|
||||
}),
|
||||
);
|
||||
@@ -1176,7 +1173,7 @@ impl ChatPanel {
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.line_height(relative(1.25))
|
||||
.child(SharedString::from(url.to_string())),
|
||||
.child(SharedString::from(url.0.to_string())),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
@@ -1518,7 +1515,18 @@ impl Render for ChatPanel {
|
||||
v_flex()
|
||||
.flex_1()
|
||||
.relative()
|
||||
.child(
|
||||
.map(|this| {
|
||||
if self.messages.is_empty() {
|
||||
this.child(
|
||||
div()
|
||||
.size_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_end()
|
||||
.child(self.render_announcement(cx)),
|
||||
)
|
||||
} else {
|
||||
this.child(
|
||||
list(
|
||||
self.list_state.clone(),
|
||||
cx.processor(move |this, ix, window, cx| {
|
||||
@@ -1527,6 +1535,8 @@ impl Render for ChatPanel {
|
||||
)
|
||||
.size_full(),
|
||||
)
|
||||
}
|
||||
})
|
||||
.child(Scrollbar::vertical(&self.list_state)),
|
||||
)
|
||||
.child(
|
||||
@@ -1552,7 +1562,7 @@ impl Render for ChatPanel {
|
||||
this.upload(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(Input::new(&self.input).appearance(false).text_sm().flex_1())
|
||||
.child(Input::new(&self.input).appearance(false).flex_1())
|
||||
.child(
|
||||
h_flex()
|
||||
.pl_1()
|
||||
|
||||
@@ -18,7 +18,7 @@ impl EventExt for Event {
|
||||
}
|
||||
|
||||
fn extract_public_keys(&self) -> Vec<PublicKey> {
|
||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
|
||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().collect();
|
||||
public_keys.push(self.pubkey);
|
||||
|
||||
public_keys.into_iter().unique().collect()
|
||||
@@ -46,7 +46,7 @@ impl EventExt for UnsignedEvent {
|
||||
}
|
||||
|
||||
fn extract_public_keys(&self) -> Vec<PublicKey> {
|
||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
|
||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().collect();
|
||||
public_keys.push(self.pubkey);
|
||||
public_keys.into_iter().unique().sorted().collect()
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ state = { path = "../state" }
|
||||
person = { path = "../person" }
|
||||
ui = { path = "../ui" }
|
||||
theme = { path = "../theme" }
|
||||
settings = { path = "../settings" }
|
||||
|
||||
gpui.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
|
||||
@@ -2,6 +2,8 @@ use std::cell::Cell;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||
@@ -11,7 +13,9 @@ use gpui::{
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use person::PersonRegistry;
|
||||
use state::{Announcement, CLIENT_NAME, NostrRegistry, StateEvent, TIMEOUT};
|
||||
use settings::AppSettings;
|
||||
use smallvec::{SmallVec, smallvec};
|
||||
use state::{Announcement, CLIENT_NAME, NostrRegistry};
|
||||
use theme::ActiveTheme;
|
||||
use ui::avatar::Avatar;
|
||||
use ui::button::Button;
|
||||
@@ -19,8 +23,6 @@ use ui::notification::{Notification, NotificationKind};
|
||||
use ui::{Disableable, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
|
||||
|
||||
const IDENTIFIER: &str = "coop:device";
|
||||
const MSG: &str = "You've requested an encryption key from another device. \
|
||||
Approve to allow Coop to share with it.";
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) {
|
||||
DeviceRegistry::set_global(cx.new(|cx| DeviceRegistry::new(window, cx)), cx);
|
||||
@@ -35,10 +37,10 @@ impl Global for GlobalDeviceRegistry {}
|
||||
pub enum DeviceEvent {
|
||||
/// A new encryption signer has been set
|
||||
Set,
|
||||
/// User have not setup encryption key
|
||||
NotSet,
|
||||
/// The device is requesting an encryption key
|
||||
Requesting,
|
||||
/// The device is creating a new encryption key
|
||||
Creating,
|
||||
/// An error occurred
|
||||
Error(SharedString),
|
||||
}
|
||||
@@ -57,17 +59,20 @@ impl DeviceEvent {
|
||||
/// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
|
||||
#[derive(Debug)]
|
||||
pub struct DeviceRegistry {
|
||||
/// Whether the registry is currently initializing
|
||||
pub initializing: bool,
|
||||
|
||||
/// Whether there is a pending request for encryption key approval
|
||||
pub pending_request: bool,
|
||||
|
||||
/// Whether an announcement has been made for this device
|
||||
pub announcement_existed: Arc<AtomicBool>,
|
||||
|
||||
/// Signer
|
||||
signer: Entity<Option<Keys>>,
|
||||
|
||||
/// Async tasks
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
|
||||
/// Event subscription
|
||||
_subscription: Option<Subscription>,
|
||||
_subscriptions: SmallVec<[Subscription; 2]>,
|
||||
}
|
||||
|
||||
impl EventEmitter<DeviceEvent> for DeviceRegistry {}
|
||||
@@ -85,31 +90,53 @@ impl DeviceRegistry {
|
||||
|
||||
/// Create a new device registry instance
|
||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = cx.new(|_| None);
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let user_signer = nostr.read(cx).signer.clone();
|
||||
|
||||
let settings = AppSettings::global(cx);
|
||||
let is_nip4e_enabled = settings.read(cx).is_nip4e_enabled(cx);
|
||||
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to nostr state events
|
||||
let subscription = cx.subscribe_in(&nostr, window, |this, _e, event, _window, cx| {
|
||||
if event == &StateEvent::SignerSet {
|
||||
this.set_initializing(true, cx);
|
||||
cx.observe(&settings, move |this, settings, cx| {
|
||||
if settings.read(cx).is_nip4e_enabled(cx) {
|
||||
this.get_announcement(cx);
|
||||
};
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
subscriptions.push(
|
||||
// Observe the user signer
|
||||
cx.observe(&user_signer, move |this, signer, cx| {
|
||||
if signer.read(cx).is_some() && is_nip4e_enabled {
|
||||
this.get_announcement(cx);
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
cx.defer_in(window, |this, window, cx| {
|
||||
this.handle_notifications(window, cx);
|
||||
});
|
||||
|
||||
Self {
|
||||
initializing: true,
|
||||
signer,
|
||||
pending_request: false,
|
||||
announcement_existed: Arc::new(AtomicBool::new(false)),
|
||||
tasks: vec![],
|
||||
_subscription: Some(subscription),
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_notifications(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let current_user = nostr.read(cx).signer_pubkey(cx);
|
||||
|
||||
let announcement_existed = self.announcement_existed.clone();
|
||||
let (tx, rx) = flume::bounded::<Event>(100);
|
||||
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
@@ -126,15 +153,15 @@ impl DeviceRegistry {
|
||||
}
|
||||
|
||||
match event.kind {
|
||||
Kind::Custom(4454) => {
|
||||
if verify_author(&client, event.as_ref()).await {
|
||||
Kind::Custom(10044) if current_user == Some(event.pubkey) => {
|
||||
announcement_existed.store(true, Ordering::Relaxed);
|
||||
tx.send_async(event.into_owned()).await?;
|
||||
}
|
||||
}
|
||||
Kind::Custom(4455) => {
|
||||
if verify_author(&client, event.as_ref()).await {
|
||||
Kind::Custom(4454) if current_user == Some(event.pubkey) => {
|
||||
tx.send_async(event.into_owned()).await?;
|
||||
}
|
||||
Kind::Custom(4455) if current_user == Some(event.pubkey) => {
|
||||
tx.send_async(event.into_owned()).await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -147,6 +174,11 @@ impl DeviceRegistry {
|
||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||
while let Ok(event) = rx.recv_async().await {
|
||||
match event.kind {
|
||||
Kind::Custom(10044) => {
|
||||
this.update_in(cx, |this, _window, cx| {
|
||||
this.set_encryption(&event, cx);
|
||||
})?;
|
||||
}
|
||||
// New request event from other device
|
||||
Kind::Custom(4454) => {
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
@@ -166,37 +198,24 @@ impl DeviceRegistry {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Set whether the registry is currently initializing
|
||||
fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
|
||||
self.initializing = initializing;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Set whether there is a pending request for encryption key approval
|
||||
fn set_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
|
||||
self.pending_request = pending;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Get the signer
|
||||
pub fn signer(&self, cx: &App) -> Option<Keys> {
|
||||
self.signer.read(cx).clone()
|
||||
}
|
||||
|
||||
/// Set the decoupled encryption key for the current user
|
||||
fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
|
||||
where
|
||||
S: NostrSigner + 'static,
|
||||
{
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
signer.set_encryption_signer(new).await;
|
||||
|
||||
// Update state
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_initializing(false, cx);
|
||||
fn set_signer(&mut self, new: Keys, cx: &mut Context<Self>) {
|
||||
self.signer.update(cx, |this, cx| {
|
||||
*this = Some(new);
|
||||
cx.notify();
|
||||
});
|
||||
cx.emit(DeviceEvent::Set);
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Backup the encryption's secret key to a file
|
||||
@@ -204,8 +223,12 @@ impl DeviceRegistry {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return Task::ready(Err(anyhow!("Signer is required")));
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let keys = get_keys(&client).await?;
|
||||
let keys = get_keys(&client, &signer).await?;
|
||||
let content = keys.secret_key().to_bech32()?;
|
||||
|
||||
smol::fs::write(path, &content).await?;
|
||||
@@ -219,46 +242,49 @@ impl DeviceRegistry {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let task: Task<Result<Event, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
// Construct the filter for the device announcement event
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Custom(10044))
|
||||
.author(public_key)
|
||||
.author(current_user)
|
||||
.limit(1);
|
||||
|
||||
// Stream events from user's write relays
|
||||
let mut stream = client
|
||||
.stream_events(filter)
|
||||
.timeout(Duration::from_secs(TIMEOUT))
|
||||
client
|
||||
.subscribe(filter)
|
||||
.close_on(opts)
|
||||
.with_id(SubscriptionId::new("nip4e"))
|
||||
.await?;
|
||||
|
||||
while let Some((_url, res)) = stream.next().await {
|
||||
if let Ok(event) = res {
|
||||
return Ok(event);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
|
||||
Err(anyhow!("Announcement not found"))
|
||||
});
|
||||
let announcement_existed = self.announcement_existed.clone();
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(event) => {
|
||||
// Set encryption key from the announcement event
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_encryption(&event, cx);
|
||||
})?;
|
||||
if !cx
|
||||
.background_spawn(async move {
|
||||
// Wait for 5 seconds
|
||||
smol::Timer::after(Duration::from_secs(5)).await;
|
||||
|
||||
// Then check if the msg relays have been found
|
||||
if !announcement_existed.load(Ordering::Acquire) {
|
||||
return true;
|
||||
}
|
||||
Err(_) => {
|
||||
// User has no announcement, create a new one
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_announcement(Keys::generate(), cx);
|
||||
|
||||
false
|
||||
})
|
||||
.await
|
||||
{
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(DeviceEvent::NotSet);
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
@@ -268,9 +294,6 @@ impl DeviceRegistry {
|
||||
pub fn set_announcement(&mut self, keys: Keys, cx: &mut Context<Self>) {
|
||||
let task = self.create_encryption(keys, cx);
|
||||
|
||||
// Notify that we're creating a new encryption key
|
||||
cx.emit(DeviceEvent::Creating);
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(keys) => {
|
||||
@@ -297,15 +320,19 @@ impl DeviceRegistry {
|
||||
let secret = keys.secret_key().to_secret_hex();
|
||||
let n = keys.public_key();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return Task::ready(Err(anyhow!("Signer is required")));
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
// Construct an announcement event
|
||||
let builder = EventBuilder::new(Kind::Custom(10044), "").tags(vec![
|
||||
Tag::custom(TagKind::custom("n"), vec![n]),
|
||||
Tag::client(CLIENT_NAME),
|
||||
]);
|
||||
|
||||
// Sign the event with user's signer
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::new(Kind::Custom(10044), "")
|
||||
.tags(vec![
|
||||
Tag::custom("n", vec![n]),
|
||||
Tag::custom("client", vec![CLIENT_NAME]),
|
||||
])
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Publish announcement
|
||||
client
|
||||
@@ -315,7 +342,7 @@ impl DeviceRegistry {
|
||||
.await?;
|
||||
|
||||
// Save device keys to the database
|
||||
set_keys(&client, &secret).await?;
|
||||
set_keys(&client, &signer, &secret).await?;
|
||||
|
||||
Ok(keys)
|
||||
})
|
||||
@@ -326,12 +353,16 @@ impl DeviceRegistry {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let announcement = Announcement::from(event);
|
||||
let device_pubkey = announcement.public_key();
|
||||
|
||||
// Get encryption key from the database and compare with the announcement
|
||||
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
||||
let keys = get_keys(&client).await?;
|
||||
let keys = get_keys(&client, &signer).await?;
|
||||
|
||||
// Compare the public key from the announcement with the one from the database
|
||||
if keys.public_key() != device_pubkey {
|
||||
@@ -360,10 +391,13 @@ impl DeviceRegistry {
|
||||
fn wait_for_request(&mut self, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
let id = SubscriptionId::new("dekey-requests");
|
||||
|
||||
// Construct a filter for encryption key requests
|
||||
@@ -383,13 +417,18 @@ impl DeviceRegistry {
|
||||
pub fn request(&mut self, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
let app_keys = nostr.read(cx).keys();
|
||||
let app_pubkey = app_keys.public_key();
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(app_keys) = get_or_init_app_keys(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<Option<Event>, Error>> = cx.background_spawn(async move {
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let app_pubkey = app_keys.public_key();
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
|
||||
// Construct a filter to get the latest approval event
|
||||
let filter = Filter::new()
|
||||
@@ -404,13 +443,13 @@ impl DeviceRegistry {
|
||||
// No approval event found, construct a request event
|
||||
None => {
|
||||
// Construct an event for device key request
|
||||
let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
|
||||
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
|
||||
Tag::client(CLIENT_NAME),
|
||||
]);
|
||||
|
||||
// Sign the event with user's signer
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::new(Kind::Custom(4454), "")
|
||||
.tags(vec![
|
||||
Tag::custom("P", vec![app_pubkey]),
|
||||
Tag::custom("client", vec![CLIENT_NAME]),
|
||||
])
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Send the event to write relays
|
||||
client.send_event(&event).to_nip65().await?;
|
||||
@@ -429,10 +468,7 @@ impl DeviceRegistry {
|
||||
}
|
||||
Ok(None) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_initializing(false, cx);
|
||||
this.wait_for_approval(cx);
|
||||
|
||||
cx.emit(DeviceEvent::Requesting);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -449,10 +485,15 @@ impl DeviceRegistry {
|
||||
fn wait_for_approval(&mut self, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
cx.emit(DeviceEvent::Requesting);
|
||||
|
||||
self.tasks.push(cx.background_spawn(async move {
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
|
||||
// Construct a filter for device key requests
|
||||
let filter = Filter::new()
|
||||
@@ -469,19 +510,21 @@ impl DeviceRegistry {
|
||||
|
||||
/// Parse the approval event to get encryption key then set it
|
||||
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let app_keys = nostr.read(cx).keys();
|
||||
let Ok(app_keys) = get_or_init_app_keys(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
||||
let master = event
|
||||
.tags
|
||||
.find(TagKind::custom("P"))
|
||||
.iter()
|
||||
.find(|tag| tag.kind() == "P")
|
||||
.and_then(|tag| tag.content())
|
||||
.and_then(|content| PublicKey::parse(content).ok())
|
||||
.context("Invalid event's tags")?;
|
||||
|
||||
let payload = event.content.as_str();
|
||||
let decrypted = app_keys.nip44_decrypt(&master, payload).await?;
|
||||
let decrypted = app_keys.nip44_decrypt_async(&master, payload).await?;
|
||||
|
||||
let secret = SecretKey::from_hex(&decrypted)?;
|
||||
let keys = Keys::new(secret);
|
||||
@@ -511,37 +554,42 @@ impl DeviceRegistry {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Get user's write relays
|
||||
let event = event.clone();
|
||||
let id: SharedString = event.id.to_hex().into();
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
// Get device keys
|
||||
let keys = get_keys(&client).await?;
|
||||
let keys = get_keys(&client, &signer).await?;
|
||||
let secret = keys.secret_key().to_secret_hex();
|
||||
|
||||
// Extract the target public key from the event tags
|
||||
let target = event
|
||||
.tags
|
||||
.find(TagKind::custom("P"))
|
||||
.iter()
|
||||
.find(|tag| tag.kind() == "P")
|
||||
.and_then(|tag| tag.content())
|
||||
.and_then(|content| PublicKey::parse(content).ok())
|
||||
.context("Target is not a valid public key")?;
|
||||
|
||||
// Encrypt the device keys with the user's signer
|
||||
let payload = keys.nip44_encrypt(&target, &secret).await?;
|
||||
let payload = keys.nip44_encrypt_async(&target, &secret).await?;
|
||||
|
||||
// Construct the response event
|
||||
//
|
||||
// P tag: the current device's public key
|
||||
// p tag: the requester's public key
|
||||
let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![
|
||||
Tag::custom(TagKind::custom("P"), vec![keys.public_key().to_hex()]),
|
||||
let event = EventBuilder::new(Kind::Custom(4455), payload)
|
||||
.tags(vec![
|
||||
Tag::custom("P", vec![keys.public_key().to_hex()]),
|
||||
Tag::public_key(target),
|
||||
]);
|
||||
|
||||
// Sign the builder
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
])
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Send the response event to the user's relay list
|
||||
client.send_event(&event).to_nip65().await?;
|
||||
@@ -586,6 +634,9 @@ impl DeviceRegistry {
|
||||
|
||||
/// Build a notification for the encryption request.
|
||||
fn notification(&self, event: Event, cx: &Context<Self>) -> Notification {
|
||||
const MSG: &str = "You've requested an encryption key from another device. \
|
||||
Approve to allow Coop to share with it.";
|
||||
|
||||
let request = Announcement::from(&event);
|
||||
let persons = PersonRegistry::global(cx);
|
||||
let profile = persons.read(cx).get(&request.public_key(), cx);
|
||||
@@ -688,29 +739,44 @@ impl DeviceRegistry {
|
||||
|
||||
struct DeviceNotification;
|
||||
|
||||
/// Verify the author of an event
|
||||
async fn verify_author(client: &Client, event: &Event) -> bool {
|
||||
if let Some(signer) = client.signer()
|
||||
&& let Ok(public_key) = signer.get_public_key().await
|
||||
{
|
||||
return public_key == event.pubkey;
|
||||
/// Get or create new app keys
|
||||
fn get_or_init_app_keys(cx: &App) -> Result<Keys, Error> {
|
||||
let read = cx.read_credentials(CLIENT_NAME);
|
||||
let stored_keys: Option<Keys> = cx.foreground_executor().block_on(async move {
|
||||
if let Ok(Some((_, secret))) = read.await {
|
||||
SecretKey::from_slice(&secret).map(Keys::new).ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(keys) = stored_keys {
|
||||
Ok(keys)
|
||||
} else {
|
||||
let keys = Keys::generate();
|
||||
let user = keys.public_key().to_hex();
|
||||
let secret = keys.secret_key().to_secret_bytes();
|
||||
let write = cx.write_credentials(CLIENT_NAME, &user, &secret);
|
||||
|
||||
cx.foreground_executor().block_on(async move {
|
||||
if let Err(e) = write.await {
|
||||
log::error!("Keyring not available or panic: {e}")
|
||||
}
|
||||
});
|
||||
|
||||
Ok(keys)
|
||||
}
|
||||
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?;
|
||||
async fn set_keys(client: &Client, signer: &Keys, secret: &str) -> Result<(), Error> {
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
let content = signer.nip44_encrypt_async(&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())
|
||||
.finalize_async(signer)
|
||||
.await?;
|
||||
|
||||
// Save the event to the database
|
||||
@@ -720,9 +786,8 @@ async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
|
||||
}
|
||||
|
||||
/// 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?;
|
||||
async fn get_keys(client: &Client, signer: &Keys) -> Result<Keys, Error> {
|
||||
let public_key = signer.get_public_key_async().await?;
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::ApplicationSpecificData)
|
||||
@@ -730,7 +795,10 @@ async fn get_keys(client: &Client) -> Result<Keys, Error> {
|
||||
.author(public_key);
|
||||
|
||||
if let Some(event) = client.database().query(filter).await?.first() {
|
||||
let content = signer.nip44_decrypt(&public_key, &event.content).await?;
|
||||
let content = signer
|
||||
.nip44_decrypt_async(&public_key, &event.content)
|
||||
.await?;
|
||||
|
||||
let secret = SecretKey::parse(&content)?;
|
||||
let keys = Keys::new(secret);
|
||||
|
||||
|
||||
@@ -242,7 +242,7 @@ impl PersonRegistry {
|
||||
|
||||
/// Set messaging relays for a person
|
||||
fn set_messaging_relays(&mut self, event: &Event, cx: &mut App) {
|
||||
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).cloned().collect();
|
||||
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).collect();
|
||||
|
||||
if let Some(person) = self.persons.get(&event.pubkey) {
|
||||
person.update(cx, |person, cx| {
|
||||
|
||||
@@ -193,15 +193,20 @@ impl RelayAuth {
|
||||
fn auth(&self, req: &Arc<AuthRequest>, cx: &App) -> Task<Result<(), Error>> {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
let req = req.clone();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return Task::ready(Err(anyhow!("Signer is required")));
|
||||
};
|
||||
|
||||
// Get all pending events for the relay
|
||||
let req = req.clone();
|
||||
let pending_events = self.get_pending_events(req.url(), cx);
|
||||
|
||||
cx.background_spawn(async move {
|
||||
// Construct event
|
||||
let builder = EventBuilder::auth(req.challenge(), req.url().clone());
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::auth(req.challenge(), req.url().clone())
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Get the event ID
|
||||
let id = event.id;
|
||||
@@ -217,8 +222,6 @@ impl RelayAuth {
|
||||
.send_msg(ClientMessage::Auth(Cow::Borrowed(&event)))
|
||||
.await?;
|
||||
|
||||
log::info!("Sending AUTH event");
|
||||
|
||||
while let Some(notification) = notifications.next().await {
|
||||
match notification {
|
||||
RelayNotification::Message { message } => {
|
||||
@@ -272,30 +275,22 @@ impl RelayAuth {
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
window.clear_notification_by_id::<AuthNotification>(challenge, cx);
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
if let Err(e) = result {
|
||||
window
|
||||
.push_notification(Notification::error(e.to_string()).autohide(false), cx);
|
||||
} else {
|
||||
// Clear pending events for the authenticated relay
|
||||
this.clear_pending_events(url, cx);
|
||||
|
||||
let domain = url.domain().unwrap_or_default();
|
||||
let msg = format!("Relay {} has been authenticated", domain);
|
||||
|
||||
window.push_notification(Notification::success(msg), cx);
|
||||
|
||||
// Save the authenticated relay to automatically authenticate future requests
|
||||
settings.update(cx, |this, cx| {
|
||||
this.add_trusted_relay(url, cx);
|
||||
});
|
||||
|
||||
window.push_notification(
|
||||
Notification::success(format!(
|
||||
"Relay {} has been authenticated",
|
||||
url.domain().unwrap_or_default()
|
||||
)),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
window.push_notification(
|
||||
Notification::error(e.to_string()).autohide(false),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Display;
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -20,14 +19,16 @@ macro_rules! setting_accessors {
|
||||
$(
|
||||
paste::paste! {
|
||||
pub fn [<get_ $field>](cx: &App) -> $type {
|
||||
Self::global(cx).read(cx).values.$field.clone()
|
||||
Self::global(cx).read(cx).inner.read(cx).$field.clone()
|
||||
}
|
||||
|
||||
pub fn [<update_ $field>](value: $type, cx: &mut App) {
|
||||
Self::global(cx).update(cx, |this, cx| {
|
||||
this.values.$field = value;
|
||||
this.inner.update(cx, |inner, cx| {
|
||||
inner.$field = value;
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
)*
|
||||
@@ -40,9 +41,9 @@ setting_accessors! {
|
||||
pub theme_mode: ThemeMode,
|
||||
pub hide_avatar: bool,
|
||||
pub screening: bool,
|
||||
pub nip4e: bool,
|
||||
pub auth_mode: AuthMode,
|
||||
pub trusted_relays: HashSet<RelayUrl>,
|
||||
pub room_configs: HashMap<u64, RoomConfig>,
|
||||
pub trusted_relays: Vec<String>,
|
||||
pub file_server: Url,
|
||||
}
|
||||
|
||||
@@ -66,10 +67,10 @@ impl Display for AuthMode {
|
||||
/// Signer kind
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum SignerKind {
|
||||
#[default]
|
||||
Auto,
|
||||
User,
|
||||
Encryption,
|
||||
#[default]
|
||||
User,
|
||||
}
|
||||
|
||||
impl SignerKind {
|
||||
@@ -97,7 +98,7 @@ impl RoomConfig {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
backup: true,
|
||||
signer_kind: SignerKind::Auto,
|
||||
signer_kind: SignerKind::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,14 +138,14 @@ pub struct Settings {
|
||||
/// Enable screening for unknown chat requests
|
||||
pub screening: bool,
|
||||
|
||||
/// Enable decoupling encryption key
|
||||
pub nip4e: bool,
|
||||
|
||||
/// Authentication mode
|
||||
pub auth_mode: AuthMode,
|
||||
|
||||
/// Trusted relays; Coop will automatically authenticate with these relays
|
||||
pub trusted_relays: HashSet<RelayUrl>,
|
||||
|
||||
/// Configuration for each chat room
|
||||
pub room_configs: HashMap<u64, RoomConfig>,
|
||||
pub trusted_relays: Vec<String>,
|
||||
|
||||
/// Server for blossom media attachments
|
||||
pub file_server: Url,
|
||||
@@ -157,9 +158,9 @@ impl Default for Settings {
|
||||
theme_mode: ThemeMode::default(),
|
||||
hide_avatar: false,
|
||||
screening: true,
|
||||
nip4e: false,
|
||||
auth_mode: AuthMode::default(),
|
||||
trusted_relays: HashSet::default(),
|
||||
room_configs: HashMap::default(),
|
||||
trusted_relays: vec![],
|
||||
file_server: Url::parse("https://blossom.band/").unwrap(),
|
||||
}
|
||||
}
|
||||
@@ -178,7 +179,7 @@ impl Global for GlobalAppSettings {}
|
||||
/// Application settings
|
||||
pub struct AppSettings {
|
||||
/// Settings
|
||||
values: Settings,
|
||||
inner: Entity<Settings>,
|
||||
|
||||
/// Event subscriptions
|
||||
_subscriptions: SmallVec<[Subscription; 2]>,
|
||||
@@ -196,11 +197,12 @@ impl AppSettings {
|
||||
}
|
||||
|
||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let inner = cx.new(|_| Settings::default());
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(
|
||||
// Observe and automatically save settings on changes
|
||||
cx.observe_self(|this, cx| {
|
||||
cx.observe(&inner, |this, _inner, cx| {
|
||||
this.save(cx);
|
||||
}),
|
||||
);
|
||||
@@ -211,15 +213,17 @@ impl AppSettings {
|
||||
});
|
||||
|
||||
Self {
|
||||
values: Settings::default(),
|
||||
inner,
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
/// Update settings
|
||||
fn set_settings(&mut self, settings: Settings, cx: &mut Context<Self>) {
|
||||
self.values = settings;
|
||||
self.inner.update(cx, |this, cx| {
|
||||
*this = settings;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
/// Load settings
|
||||
@@ -249,19 +253,16 @@ impl AppSettings {
|
||||
|
||||
/// Save settings
|
||||
pub fn save(&mut self, cx: &mut Context<Self>) {
|
||||
let settings = self.values.clone();
|
||||
let settings = self.inner.read(cx);
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
if let Ok(content) = serde_json::to_string(&settings) {
|
||||
cx.background_spawn(async move {
|
||||
let path = config_dir().join(".settings");
|
||||
let content = serde_json::to_string(&settings)?;
|
||||
|
||||
// Write settings to file
|
||||
smol::fs::write(&path, content).await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
smol::fs::write(&path, content).await.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
/// Set theme
|
||||
@@ -270,8 +271,10 @@ impl AppSettings {
|
||||
T: Into<String>,
|
||||
{
|
||||
// Update settings
|
||||
self.values.theme = Some(theme.into());
|
||||
self.inner.update(cx, |this, cx| {
|
||||
this.theme = Some(theme.into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Apply the new theme
|
||||
self.apply_theme(window, cx);
|
||||
@@ -279,16 +282,17 @@ impl AppSettings {
|
||||
|
||||
/// Reset theme
|
||||
pub fn reset_theme(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.values.theme = None;
|
||||
self.inner.update(cx, |this, cx| {
|
||||
this.theme = None;
|
||||
cx.notify();
|
||||
|
||||
});
|
||||
self.apply_theme(window, cx);
|
||||
}
|
||||
|
||||
/// Apply theme
|
||||
pub fn apply_theme(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(name) = self.values.theme.as_ref() {
|
||||
let mode = self.values.theme_mode;
|
||||
if let Some(name) = self.inner.read(cx).theme.as_ref() {
|
||||
let mode = self.inner.read(cx).theme_mode;
|
||||
|
||||
if let Ok(new_theme) = ThemeFamily::from_assets(name) {
|
||||
Theme::apply_theme(Rc::new(new_theme), Some(window), cx);
|
||||
@@ -301,26 +305,32 @@ impl AppSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if decoupling encryption key is enabled
|
||||
pub fn is_nip4e_enabled(&self, cx: &App) -> bool {
|
||||
self.inner.read(cx).nip4e
|
||||
}
|
||||
|
||||
/// Check if the given relay is already authenticated
|
||||
pub fn trusted_relay(&self, url: &RelayUrl, _cx: &App) -> bool {
|
||||
self.values.trusted_relays.iter().any(|relay| {
|
||||
relay.as_str_without_trailing_slash() == url.as_str_without_trailing_slash()
|
||||
})
|
||||
pub fn trusted_relay(&self, url: &RelayUrl, cx: &App) -> bool {
|
||||
self.inner
|
||||
.read(cx)
|
||||
.trusted_relays
|
||||
.iter()
|
||||
.any(|relay| relay == url.as_str_without_trailing_slash())
|
||||
}
|
||||
|
||||
/// Add a relay to the trusted list
|
||||
pub fn add_trusted_relay(&mut self, url: &RelayUrl, cx: &mut Context<Self>) {
|
||||
self.values.trusted_relays.insert(url.clone());
|
||||
self.inner.update(cx, |this, cx| {
|
||||
if !this
|
||||
.trusted_relays
|
||||
.iter()
|
||||
.any(|relay| relay == url.as_str_without_trailing_slash())
|
||||
{
|
||||
this.trusted_relays
|
||||
.push(url.as_str_without_trailing_slash().to_string());
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Add a room configuration
|
||||
pub fn add_room_config(&mut self, id: u64, config: RoomConfig, cx: &mut Context<Self>) {
|
||||
self.values
|
||||
.room_configs
|
||||
.entry(id)
|
||||
.and_modify(|this| *this = config)
|
||||
.or_default();
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||
use anyhow::{Error, anyhow};
|
||||
use common::config_dir;
|
||||
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
|
||||
use nostr_connect::prelude::*;
|
||||
@@ -13,15 +11,13 @@ use nostr_sdk::prelude::*;
|
||||
|
||||
mod blossom;
|
||||
mod constants;
|
||||
mod device;
|
||||
mod nip05;
|
||||
mod signer;
|
||||
mod nip4e;
|
||||
|
||||
pub use blossom::*;
|
||||
pub use constants::*;
|
||||
pub use device::*;
|
||||
pub use nip4e::*;
|
||||
pub use nip05::*;
|
||||
pub use signer::*;
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) {
|
||||
// rustls uses the `aws_lc_rs` provider by default
|
||||
@@ -48,12 +44,6 @@ pub enum StateEvent {
|
||||
Connecting,
|
||||
/// Connected to the bootstrapping relay
|
||||
Connected,
|
||||
/// Creating the signer
|
||||
Creating,
|
||||
/// Show the identity dialog
|
||||
Show,
|
||||
/// A new signer has been set
|
||||
SignerSet,
|
||||
/// An error occurred
|
||||
Error(SharedString),
|
||||
}
|
||||
@@ -73,19 +63,8 @@ pub struct NostrRegistry {
|
||||
/// Nostr client
|
||||
client: Client,
|
||||
|
||||
/// Nostr signer
|
||||
signer: Arc<CoopSigner>,
|
||||
|
||||
/// All local stored identities
|
||||
npubs: Entity<Vec<PublicKey>>,
|
||||
|
||||
/// Keys directory
|
||||
key_dir: PathBuf,
|
||||
|
||||
/// Master app keys used for various operations.
|
||||
///
|
||||
/// Example: Nostr Connect and NIP-4e operations
|
||||
app_keys: Keys,
|
||||
/// Currently active signer
|
||||
pub signer: Entity<Option<Keys>>,
|
||||
|
||||
/// Tasks for asynchronous operations
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
@@ -106,20 +85,7 @@ impl NostrRegistry {
|
||||
|
||||
/// Create a new nostr instance
|
||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let key_dir = config_dir().join("keys");
|
||||
let app_keys = get_or_init_app_keys(cx).unwrap_or(Keys::generate());
|
||||
|
||||
// Construct the nostr signer
|
||||
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
|
||||
|
||||
// Get all local stored npubs
|
||||
let npubs = cx.new(|_| match Self::discover(&key_dir) {
|
||||
Ok(npubs) => npubs,
|
||||
Err(e) => {
|
||||
log::error!("Failed to discover npubs: {e}");
|
||||
vec![]
|
||||
}
|
||||
});
|
||||
let signer = cx.new(|_| None);
|
||||
|
||||
// Construct the nostr lmdb instance
|
||||
let lmdb = cx.foreground_executor().block_on(async move {
|
||||
@@ -130,16 +96,9 @@ impl NostrRegistry {
|
||||
|
||||
// Construct the nostr client
|
||||
let client = ClientBuilder::default()
|
||||
.signer(signer.clone())
|
||||
.database(lmdb)
|
||||
.gossip(NostrGossipMemory::unbounded())
|
||||
.gossip_config(
|
||||
GossipConfig::default()
|
||||
.sync_initial_timeout(Duration::from_millis(100))
|
||||
.sync_idle_timeout(Duration::from_millis(100))
|
||||
.no_background_refresh(),
|
||||
)
|
||||
.automatic_authentication(false)
|
||||
.gossip_config(GossipConfig::default().no_background_refresh())
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.sleep_when_idle(SleepWhenIdle::Enabled {
|
||||
timeout: Duration::from_secs(600),
|
||||
@@ -149,21 +108,11 @@ impl NostrRegistry {
|
||||
// Run at the end of current cycle
|
||||
cx.defer_in(window, |this, _window, cx| {
|
||||
this.connect(cx);
|
||||
// Create an identity if none exists
|
||||
if this.npubs.read(cx).is_empty() {
|
||||
this.create_identity(cx);
|
||||
} else {
|
||||
// Show the identity dialog
|
||||
cx.emit(StateEvent::Show);
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
client,
|
||||
signer,
|
||||
npubs,
|
||||
key_dir,
|
||||
app_keys,
|
||||
tasks: vec![],
|
||||
}
|
||||
}
|
||||
@@ -173,46 +122,22 @@ impl NostrRegistry {
|
||||
self.client.clone()
|
||||
}
|
||||
|
||||
/// Get the nostr signer
|
||||
pub fn signer(&self) -> Arc<CoopSigner> {
|
||||
self.signer.clone()
|
||||
/// Get the signer
|
||||
pub fn signer(&self, cx: &App) -> Option<Keys> {
|
||||
self.signer.read(cx).clone()
|
||||
}
|
||||
|
||||
/// Get the npubs entity
|
||||
pub fn npubs(&self) -> Entity<Vec<PublicKey>> {
|
||||
self.npubs.clone()
|
||||
/// Get the public key of the signer
|
||||
pub fn signer_pubkey(&self, cx: &App) -> Option<PublicKey> {
|
||||
self.signer.read(cx).as_ref().map(|s| s.public_key())
|
||||
}
|
||||
|
||||
/// Get the app keys
|
||||
pub fn keys(&self) -> Keys {
|
||||
self.app_keys.clone()
|
||||
}
|
||||
|
||||
/// Discover all npubs in the keys directory
|
||||
fn discover(dir: &PathBuf) -> Result<Vec<PublicKey>, Error> {
|
||||
// Ensure keys directory exists
|
||||
std::fs::create_dir_all(dir)?;
|
||||
|
||||
let files = std::fs::read_dir(dir)?;
|
||||
let mut entries = Vec::new();
|
||||
let mut npubs: Vec<PublicKey> = Vec::new();
|
||||
|
||||
for file in files.flatten() {
|
||||
let metadata = file.metadata()?;
|
||||
let modified_time = metadata.modified()?;
|
||||
let name = file.file_name().into_string().unwrap().replace(".npub", "");
|
||||
entries.push((modified_time, name));
|
||||
}
|
||||
|
||||
// Sort by modification time (most recent first)
|
||||
entries.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
|
||||
for (_, name) in entries {
|
||||
let public_key = PublicKey::parse(&name)?;
|
||||
npubs.push(public_key);
|
||||
}
|
||||
|
||||
Ok(npubs)
|
||||
/// Set the signer to the given keys
|
||||
pub fn set_signer(&mut self, new_keys: Keys, cx: &mut Context<Self>) {
|
||||
self.signer.update(cx, |this, cx| {
|
||||
*this = Some(new_keys);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
/// Connect to the bootstrapping relays
|
||||
@@ -234,10 +159,7 @@ impl NostrRegistry {
|
||||
}
|
||||
|
||||
// Connect to all added relays
|
||||
client
|
||||
.connect()
|
||||
.and_wait(Duration::from_secs(TIMEOUT))
|
||||
.await;
|
||||
client.connect().await;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
@@ -260,319 +182,8 @@ impl NostrRegistry {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Get the secret for a given npub.
|
||||
pub fn get_secret(
|
||||
&self,
|
||||
public_key: PublicKey,
|
||||
cx: &App,
|
||||
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
||||
let npub = public_key.to_bech32().unwrap();
|
||||
let key_path = self.key_dir.join(format!("{}.npub", npub));
|
||||
let app_keys = self.app_keys.clone();
|
||||
|
||||
if let Ok(payload) = std::fs::read_to_string(key_path) {
|
||||
if !payload.is_empty() {
|
||||
cx.background_spawn(async move {
|
||||
let decrypted = app_keys.nip44_decrypt(&public_key, &payload).await?;
|
||||
let secret = SecretKey::parse(&decrypted)?;
|
||||
let keys = Keys::new(secret);
|
||||
|
||||
Ok(keys.into_nostr_signer())
|
||||
})
|
||||
} else {
|
||||
self.get_secret_keyring(&npub, cx)
|
||||
}
|
||||
} else {
|
||||
self.get_secret_keyring(&npub, cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the secret for a given npub in the OS credentials store.
|
||||
#[deprecated = "Use get_secret instead"]
|
||||
fn get_secret_keyring(
|
||||
&self,
|
||||
user: &str,
|
||||
cx: &App,
|
||||
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
||||
let read = cx.read_credentials(user);
|
||||
let app_keys = self.app_keys.clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let (_, secret) = read
|
||||
.await
|
||||
.map_err(|_| anyhow!("Failed to get signer. Please re-import the secret key"))?
|
||||
.ok_or_else(|| anyhow!("Failed to get signer. Please re-import the secret key"))?;
|
||||
|
||||
// Try to parse as a direct secret key first
|
||||
if let Ok(secret_key) = SecretKey::from_slice(&secret) {
|
||||
return Ok(Keys::new(secret_key).into_nostr_signer());
|
||||
}
|
||||
|
||||
// Convert the secret into string
|
||||
let sec = String::from_utf8(secret)
|
||||
.map_err(|_| anyhow!("Failed to parse secret as UTF-8"))?;
|
||||
|
||||
// Try to parse as a NIP-46 URI
|
||||
let uri =
|
||||
NostrConnectUri::parse(&sec).map_err(|_| anyhow!("Failed to parse NIP-46 URI"))?;
|
||||
|
||||
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
|
||||
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
|
||||
|
||||
// Set the auth URL handler
|
||||
nip46.auth_url_handler(CoopAuthUrlHandler);
|
||||
|
||||
Ok(nip46.into_nostr_signer())
|
||||
})
|
||||
}
|
||||
|
||||
/// Add a new npub to the keys directory
|
||||
fn write_secret(
|
||||
&self,
|
||||
public_key: PublicKey,
|
||||
secret: String,
|
||||
cx: &App,
|
||||
) -> Task<Result<(), Error>> {
|
||||
let npub = public_key.to_bech32().unwrap();
|
||||
let key_path = self.key_dir.join(format!("{}.npub", npub));
|
||||
let app_keys = self.app_keys.clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
// If the secret starts with "bunker://" (nostr connect), use it directly; otherwise, encrypt it
|
||||
let content = if secret.starts_with("bunker://") {
|
||||
secret
|
||||
} else {
|
||||
app_keys.nip44_encrypt(&public_key, &secret).await?
|
||||
};
|
||||
|
||||
// Write the encrypted secret to the keys directory
|
||||
smol::fs::write(key_path, &content).await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove a secret
|
||||
pub fn remove_secret(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
|
||||
let public_key = public_key.to_owned();
|
||||
let npub = public_key.to_bech32().unwrap();
|
||||
|
||||
let keys_dir = config_dir().join("keys");
|
||||
let key_path = keys_dir.join(format!("{}.npub", npub));
|
||||
|
||||
// Remove the secret file from the keys directory
|
||||
std::fs::remove_file(key_path).ok();
|
||||
|
||||
self.npubs.update(cx, |this, cx| {
|
||||
this.retain(|k| k != &public_key);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a new identity
|
||||
pub fn create_identity(&mut self, cx: &mut Context<Self>) {
|
||||
let client = self.client();
|
||||
let keys = Keys::generate();
|
||||
let async_keys = keys.clone();
|
||||
|
||||
// Emit creating event
|
||||
cx.emit(StateEvent::Creating);
|
||||
|
||||
// Create the write secret task
|
||||
let write_secret =
|
||||
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
||||
|
||||
// Run async tasks in background
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let signer = async_keys.into_nostr_signer();
|
||||
|
||||
// Construct relay list event
|
||||
let relay_list = default_relay_list();
|
||||
let event = EventBuilder::relay_list(relay_list).sign(&signer).await?;
|
||||
|
||||
// Publish relay list
|
||||
client
|
||||
.send_event(&event)
|
||||
.to(BOOTSTRAP_RELAYS)
|
||||
.ack_policy(AckPolicy::none())
|
||||
.await?;
|
||||
|
||||
// Construct the default metadata
|
||||
let name = petname::petname(2, "-").unwrap_or("Cooper".to_string());
|
||||
let avatar = Url::parse(&format!("https://avatar.vercel.sh/{name}")).unwrap();
|
||||
let metadata = Metadata::new().display_name(&name).picture(avatar);
|
||||
let event = EventBuilder::metadata(&metadata).sign(&signer).await?;
|
||||
|
||||
// Publish metadata event
|
||||
client
|
||||
.send_event(&event)
|
||||
.to_nip65()
|
||||
.ack_policy(AckPolicy::none())
|
||||
.await?;
|
||||
|
||||
// Construct the default contact list
|
||||
let contacts = vec![Contact::new(PublicKey::parse(COOP_PUBKEY).unwrap())];
|
||||
let event = EventBuilder::contact_list(contacts).sign(&signer).await?;
|
||||
|
||||
// Publish contact list event
|
||||
client
|
||||
.send_event(&event)
|
||||
.to_nip65()
|
||||
.ack_policy(AckPolicy::none())
|
||||
.await?;
|
||||
|
||||
// Construct the default messaging relay list
|
||||
let relays = default_messaging_relays();
|
||||
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
|
||||
|
||||
// Publish messaging relay list event
|
||||
client.send_event(&event).to_nip65().await?;
|
||||
|
||||
// Write user's credentials to the system keyring
|
||||
write_secret.await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(_) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, cx);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(StateEvent::error(e.to_string()));
|
||||
})?;
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Set the signer for the nostr client and verify the public key
|
||||
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
let client = self.client();
|
||||
let signer = self.signer();
|
||||
|
||||
// Create a task to update the signer and verify the public key
|
||||
let task: Task<Result<PublicKey, Error>> = cx.background_spawn(async move {
|
||||
// Update signer and unsubscribe
|
||||
signer.switch(new).await;
|
||||
client.unsubscribe_all().await?;
|
||||
|
||||
// Verify and get public key
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
log::info!("Signer's public key: {}", public_key);
|
||||
Ok(public_key)
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(public_key) => {
|
||||
this.update(cx, |this, cx| {
|
||||
// Add public key to npubs if not already present
|
||||
this.npubs.update(cx, |this, cx| {
|
||||
if !this.contains(&public_key) {
|
||||
this.push(public_key);
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
|
||||
// Emit signer changed event
|
||||
cx.emit(StateEvent::SignerSet);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(StateEvent::error(e.to_string()));
|
||||
})?;
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Add a key signer to keyring
|
||||
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
|
||||
let keys = keys.clone();
|
||||
let write_secret =
|
||||
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match write_secret.await {
|
||||
Ok(_) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, cx);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(StateEvent::error(e.to_string()));
|
||||
})?;
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Add a nostr connect signer to keyring
|
||||
pub fn add_nip46_signer(&mut self, nip46: &NostrConnect, cx: &mut Context<Self>) {
|
||||
let nip46 = nip46.clone();
|
||||
let async_nip46 = nip46.clone();
|
||||
|
||||
// Connect and verify the remote signer
|
||||
let task: Task<Result<(PublicKey, NostrConnectUri), Error>> =
|
||||
cx.background_spawn(async move {
|
||||
let uri = async_nip46.bunker_uri().await?;
|
||||
let public_key = async_nip46.get_public_key().await?;
|
||||
|
||||
Ok((public_key, uri))
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok((public_key, uri)) => {
|
||||
// Create the write secret task
|
||||
let write_secret = this.read_with(cx, |this, cx| {
|
||||
this.write_secret(public_key, uri.to_string(), cx)
|
||||
})?;
|
||||
|
||||
match write_secret.await {
|
||||
Ok(_) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(nip46, cx);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(StateEvent::error(e.to_string()));
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(StateEvent::error(e.to_string()));
|
||||
})?;
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Get the public key of a NIP-05 address
|
||||
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
||||
pub fn query_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
||||
let client = self.client();
|
||||
let http_client = cx.http_client();
|
||||
|
||||
@@ -609,7 +220,7 @@ impl NostrRegistry {
|
||||
|
||||
// Get the address task if the query is a valid NIP-05 address
|
||||
let address_task = if let Ok(addr) = Nip05Address::parse(&query) {
|
||||
Some(self.get_address(addr, cx))
|
||||
Some(self.query_address(addr, cx))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -681,13 +292,19 @@ impl NostrRegistry {
|
||||
let client = self.client();
|
||||
let query = query.to_string();
|
||||
|
||||
let Some(signer) = self.signer.read(cx).clone() else {
|
||||
return Task::ready(Err(anyhow!("Signer is required")));
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
// Construct a vertex request event
|
||||
let builder = EventBuilder::new(Kind::Custom(5315), "").tags(vec![
|
||||
Tag::custom(TagKind::custom("param"), vec!["search", &query]),
|
||||
Tag::custom(TagKind::custom("param"), vec!["limit", "10"]),
|
||||
]);
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::new(Kind::Custom(5315), "")
|
||||
.tags(vec![
|
||||
Tag::custom("param", vec!["search", &query]),
|
||||
Tag::custom("param", vec!["limit", "10"]),
|
||||
])
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Send the event to vertex relays
|
||||
let output = client.send_event(&event).to(WOT_RELAYS).await?;
|
||||
@@ -737,78 +354,3 @@ impl NostrRegistry {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get or create new app keys
|
||||
fn get_or_init_app_keys(cx: &App) -> Result<Keys, Error> {
|
||||
let read = cx.read_credentials(CLIENT_NAME);
|
||||
let stored_keys: Option<Keys> = cx.foreground_executor().block_on(async move {
|
||||
if let Ok(Some((_, secret))) = read.await {
|
||||
SecretKey::from_slice(&secret).map(Keys::new).ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(keys) = stored_keys {
|
||||
Ok(keys)
|
||||
} else {
|
||||
let keys = Keys::generate();
|
||||
let user = keys.public_key().to_hex();
|
||||
let secret = keys.secret_key().to_secret_bytes();
|
||||
let write = cx.write_credentials(CLIENT_NAME, &user, &secret);
|
||||
|
||||
cx.foreground_executor().block_on(async move {
|
||||
if let Err(e) = write.await {
|
||||
log::error!("Keyring not available or panic: {e}")
|
||||
}
|
||||
});
|
||||
|
||||
Ok(keys)
|
||||
}
|
||||
}
|
||||
|
||||
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
|
||||
vec![
|
||||
(
|
||||
RelayUrl::parse("wss://relay.nostr.net").unwrap(),
|
||||
Some(RelayMetadata::Write),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://relay.primal.net").unwrap(),
|
||||
Some(RelayMetadata::Write),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://relay.damus.io").unwrap(),
|
||||
Some(RelayMetadata::Read),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
||||
Some(RelayMetadata::Read),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://nostr.superfriends.online").unwrap(),
|
||||
None,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn default_messaging_relays() -> Vec<RelayUrl> {
|
||||
vec![
|
||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
||||
RelayUrl::parse("wss://nip17.com").unwrap(),
|
||||
RelayUrl::parse("wss://auth.nostr1.com").unwrap(),
|
||||
]
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoopAuthUrlHandler;
|
||||
|
||||
impl AuthUrlHandler for CoopAuthUrlHandler {
|
||||
#[allow(mismatched_lifetime_syntaxes)]
|
||||
fn on_auth_url(&self, auth_url: Url) -> BoxedFuture<Result<()>> {
|
||||
Box::pin(async move {
|
||||
webbrowser::open(auth_url.as_str())?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,15 @@ impl From<&Event> for Announcement {
|
||||
let public_key = val
|
||||
.tags
|
||||
.iter()
|
||||
.find(|tag| tag.kind().as_str() == "n")
|
||||
.find(|tag| tag.kind() == "n")
|
||||
.and_then(|tag| tag.content())
|
||||
.and_then(|c| PublicKey::parse(c).ok())
|
||||
.unwrap_or(val.pubkey);
|
||||
|
||||
let client_name = val
|
||||
.tags
|
||||
.find(TagKind::Client)
|
||||
.iter()
|
||||
.find(|tag| tag.kind() == "client")
|
||||
.and_then(|tag| tag.content())
|
||||
.map(|c| c.to_string());
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
use std::borrow::Cow;
|
||||
use std::result::Result;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nostr_sdk::prelude::*;
|
||||
use smol::lock::RwLock;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CoopSigner {
|
||||
/// User's signer
|
||||
signer: RwLock<Arc<dyn NostrSigner>>,
|
||||
|
||||
/// User's signer public key
|
||||
signer_pkey: RwLock<Option<PublicKey>>,
|
||||
|
||||
/// Specific signer for encryption purposes
|
||||
encryption_signer: RwLock<Option<Arc<dyn NostrSigner>>>,
|
||||
}
|
||||
|
||||
impl CoopSigner {
|
||||
pub fn new<T>(signer: T) -> Self
|
||||
where
|
||||
T: IntoNostrSigner,
|
||||
{
|
||||
Self {
|
||||
signer: RwLock::new(signer.into_nostr_signer()),
|
||||
signer_pkey: RwLock::new(None),
|
||||
encryption_signer: RwLock::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current signer.
|
||||
pub async fn get(&self) -> Arc<dyn NostrSigner> {
|
||||
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
|
||||
///
|
||||
/// Ensure to call this method after the signer has been initialized.
|
||||
/// Otherwise, it will panic.
|
||||
pub fn public_key(&self) -> Option<PublicKey> {
|
||||
*self.signer_pkey.read_blocking()
|
||||
}
|
||||
|
||||
/// Switch the current signer to a new signer.
|
||||
pub async fn switch<T>(&self, new: T)
|
||||
where
|
||||
T: IntoNostrSigner,
|
||||
{
|
||||
let new_signer = new.into_nostr_signer();
|
||||
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;
|
||||
|
||||
// Update the public key
|
||||
*signer_pkey = public_key;
|
||||
|
||||
// Reset the encryption signer
|
||||
*encryption_signer = None;
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
#[allow(mismatched_lifetime_syntaxes)]
|
||||
fn backend(&self) -> SignerBackend {
|
||||
SignerBackend::Custom(Cow::Borrowed("custom"))
|
||||
}
|
||||
|
||||
fn get_public_key<'a>(&'a self) -> BoxedFuture<'a, Result<PublicKey, SignerError>> {
|
||||
Box::pin(async move { self.get().await.get_public_key().await })
|
||||
}
|
||||
|
||||
fn sign_event<'a>(
|
||||
&'a self,
|
||||
unsigned: UnsignedEvent,
|
||||
) -> BoxedFuture<'a, Result<Event, SignerError>> {
|
||||
Box::pin(async move { self.get().await.sign_event(unsigned).await })
|
||||
}
|
||||
|
||||
fn nip04_encrypt<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
content: &'a str,
|
||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
||||
Box::pin(async move { self.get().await.nip04_encrypt(public_key, content).await })
|
||||
}
|
||||
|
||||
fn nip04_decrypt<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
encrypted_content: &'a str,
|
||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
||||
Box::pin(async move {
|
||||
self.get()
|
||||
.await
|
||||
.nip04_decrypt(public_key, encrypted_content)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
fn nip44_encrypt<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
content: &'a str,
|
||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
||||
Box::pin(async move { self.get().await.nip44_encrypt(public_key, content).await })
|
||||
}
|
||||
|
||||
fn nip44_decrypt<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
payload: &'a str,
|
||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
||||
Box::pin(async move { self.get().await.nip44_decrypt(public_key, payload).await })
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,4 @@
|
||||
/// Display mapping system for Editor/Input.
|
||||
///
|
||||
/// This module implements a layered display mapping architecture:
|
||||
/// - **WrapMap**: Handles soft-wrapping (buffer → wrap rows)
|
||||
/// - **FoldMap**: Handles folding (wrap rows → display rows)
|
||||
/// - **DisplayMap**: Public facade for Editor/Input
|
||||
///
|
||||
/// The goal is to provide a clean, unified API where Editor only needs to know
|
||||
/// about `BufferPoint ↔ DisplayPoint` mapping, without worrying about internal wrap/fold complexity.
|
||||
#[allow(clippy::module_inception)]
|
||||
mod display_map;
|
||||
mod fold_map;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use std::ops::Range;
|
||||
use gpui::Half;
|
||||
|
||||
use gpui::{
|
||||
App, Font, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign, Window, point, px,
|
||||
App, Font, Half, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign, Window, point, px,
|
||||
size,
|
||||
};
|
||||
use ropey::Rope;
|
||||
@@ -97,7 +96,7 @@ impl TextWrapper {
|
||||
/// Get the line item by row index.
|
||||
#[inline]
|
||||
pub(crate) fn line(&self, row: usize) -> Option<&LineItem> {
|
||||
self.lines.iter().skip(row).next()
|
||||
self.lines.get(row)
|
||||
}
|
||||
|
||||
pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
|
||||
@@ -228,7 +227,7 @@ impl TextWrapper {
|
||||
});
|
||||
}
|
||||
|
||||
if self.lines.len() == 0 {
|
||||
if self.lines.is_empty() {
|
||||
self.lines = new_lines;
|
||||
} else {
|
||||
self.lines.splice(rows_range, new_lines);
|
||||
@@ -246,7 +245,7 @@ impl TextWrapper {
|
||||
///
|
||||
/// If the `text` is the same as the current text, do nothing.
|
||||
fn update_all(&mut self, text: &Rope, cx: &mut App) {
|
||||
self.update(text, &(0..text.len()), &text, cx);
|
||||
self.update(text, &(0..text.len()), text, cx);
|
||||
}
|
||||
|
||||
/// Return display point (with soft wrap) from the given byte offset in the text.
|
||||
@@ -278,7 +277,8 @@ impl TextWrapper {
|
||||
// Otherwise return the eof of the line.
|
||||
let last_range = line.wrapped_lines.last().unwrap_or(&(0..0));
|
||||
let ix = line.lines_len().saturating_sub(1);
|
||||
return WrapDisplayPoint::new(wrapped_row + ix, ix, last_range.len());
|
||||
|
||||
WrapDisplayPoint::new(wrapped_row + ix, ix, last_range.len())
|
||||
}
|
||||
|
||||
/// Return byte offset in the text from the given display point (with soft wrap).
|
||||
@@ -301,7 +301,7 @@ impl TextWrapper {
|
||||
wrapped_row += line.lines_len();
|
||||
}
|
||||
|
||||
return self.text.len();
|
||||
self.text.len()
|
||||
}
|
||||
|
||||
pub(crate) fn display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
|
||||
@@ -580,351 +580,3 @@ impl LineLayout {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{Boundary, FontFeatures, FontStyle, FontWeight, px};
|
||||
|
||||
#[test]
|
||||
fn test_update() {
|
||||
let font = gpui::Font {
|
||||
family: "Arial".into(),
|
||||
weight: FontWeight::default(),
|
||||
style: FontStyle::Normal,
|
||||
features: FontFeatures::default(),
|
||||
fallbacks: None,
|
||||
};
|
||||
|
||||
let mut wrapper = TextWrapper::new(font, px(14.), None);
|
||||
let mut text = Rope::from(
|
||||
"Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
|
||||
);
|
||||
|
||||
fn fake_wrap_line(_line: &str, _wrap_width: Pixels) -> Vec<Boundary> {
|
||||
vec![]
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn assert_wrapper_lines(text: &Rope, wrapper: &TextWrapper, expected_lines: &[&[&str]]) {
|
||||
let mut actual_lines = vec![];
|
||||
let mut offset = 0;
|
||||
for line in wrapper.lines.iter() {
|
||||
actual_lines.push(
|
||||
line.wrapped_lines
|
||||
.iter()
|
||||
.map(|range| text.slice(offset + range.start..offset + range.end))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
// +1 \n
|
||||
offset += line.len() + 1;
|
||||
}
|
||||
assert_eq!(actual_lines, expected_lines);
|
||||
}
|
||||
|
||||
wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
|
||||
assert_eq!(wrapper.lines.len(), 4);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["Hello, 世界!\r"],
|
||||
&["This is second line."],
|
||||
&["This is third line."],
|
||||
&["这里是第 4 行。"],
|
||||
],
|
||||
);
|
||||
|
||||
// Add a new text to end
|
||||
let range = text.len()..text.len();
|
||||
let new_text = "New text";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 4);
|
||||
assert_eq!(wrapper.lines.len(), 4);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["Hello, 世界!\r"],
|
||||
&["This is second line."],
|
||||
&["This is third line."],
|
||||
&["这里是第 4 行。New text"],
|
||||
],
|
||||
);
|
||||
|
||||
// Replace first line `Hello` to `AAA`
|
||||
let range = 0..5;
|
||||
let new_text = "AAA";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 4);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["AAA, 世界!\r"],
|
||||
&["This is second line."],
|
||||
&["This is third line."],
|
||||
&["这里是第 4 行。New text"],
|
||||
],
|
||||
);
|
||||
|
||||
// Remove the second line
|
||||
let start_offset = text.line_start_offset(1);
|
||||
let end_offset = text.line_end_offset(1);
|
||||
let range = start_offset..end_offset + 1;
|
||||
text.replace(range.clone(), "");
|
||||
wrapper._update(&text, &range, &Rope::from(""), &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 3);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["AAA, 世界!\r"],
|
||||
&["This is third line."],
|
||||
&["这里是第 4 行。New text"],
|
||||
],
|
||||
);
|
||||
|
||||
// Replace the first 2 lines to "This is a new line."
|
||||
let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
|
||||
let new_text = "This is a new line.\nThis is new line 2.\n";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 3);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["This is a new line."],
|
||||
&["This is new line 2."],
|
||||
&["这里是第 4 行。New text"],
|
||||
],
|
||||
);
|
||||
|
||||
// Add a new line at the end
|
||||
let range = text.len()..text.len();
|
||||
let new_text = "\nThis is a new line at the end.";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 4);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["This is a new line."],
|
||||
&["This is new line 2."],
|
||||
&["这里是第 4 行。New text"],
|
||||
&["This is a new line at the end."],
|
||||
],
|
||||
);
|
||||
|
||||
// Add a new line at the beginning
|
||||
let range = 0..0;
|
||||
let new_text = "This is a new line at the beginning.\n";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"This is a new line at the beginning.\nThis is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 5);
|
||||
assert_wrapper_lines(
|
||||
&text,
|
||||
&wrapper,
|
||||
&[
|
||||
&["This is a new line at the beginning."],
|
||||
&["This is a new line."],
|
||||
&["This is new line 2."],
|
||||
&["这里是第 4 行。New text"],
|
||||
&["This is a new line at the end."],
|
||||
],
|
||||
);
|
||||
|
||||
// Remove all to at least one line in `lines`.
|
||||
let range = 0..text.len();
|
||||
let new_text = "";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
|
||||
assert_eq!(text.to_string(), "");
|
||||
assert_eq!(wrapper.lines.len(), 1);
|
||||
assert_eq!(wrapper.lines[0].wrapped_lines, vec![0..0]);
|
||||
|
||||
// Test update_all
|
||||
let range = 0..text.len();
|
||||
let new_text = "This is a full text.\nThis is a second line.";
|
||||
text.replace(range.clone(), new_text);
|
||||
wrapper._update(&text, &range, &text, &mut fake_wrap_line);
|
||||
assert_eq!(
|
||||
text.to_string(),
|
||||
"This is a full text.\nThis is a second line."
|
||||
);
|
||||
assert_eq!(wrapper.lines.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_line_layout() {
|
||||
let mut line_layout = LineLayout::new();
|
||||
|
||||
let line1 = ShapedLine::default().with_len(100);
|
||||
let line2 = ShapedLine::default().with_len(50);
|
||||
let wrapped_lines = smallvec::smallvec![line1, line2];
|
||||
line_layout.set_wrapped_lines(wrapped_lines);
|
||||
assert_eq!(line_layout.len(), 150);
|
||||
assert_eq!(line_layout.wrapped_lines.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_position_for_index_prefers_first_leading_empty_visual_line() {
|
||||
let mut line_layout = LineLayout::new();
|
||||
line_layout.set_wrapped_lines(smallvec::smallvec![
|
||||
ShapedLine::default(),
|
||||
ShapedLine::default(),
|
||||
ShapedLine::default().with_len(3),
|
||||
]);
|
||||
|
||||
let last_layout = LastLayout {
|
||||
visible_range: 0..1,
|
||||
visible_buffer_lines: vec![0],
|
||||
visible_line_byte_offsets: vec![0],
|
||||
visible_top: px(0.),
|
||||
visible_range_offset: 0..0,
|
||||
lines: Rc::new(vec![]),
|
||||
line_height: px(20.),
|
||||
wrap_width: None,
|
||||
line_number_width: px(0.),
|
||||
cursor_bounds: None,
|
||||
text_align: TextAlign::Left,
|
||||
content_width: px(0.),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
line_layout.position_for_index(0, &last_layout, false),
|
||||
Some(point(px(0.), px(0.)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offset_to_display_point() {
|
||||
let font = gpui::Font {
|
||||
family: "Arial".into(),
|
||||
weight: FontWeight::default(),
|
||||
style: FontStyle::Normal,
|
||||
features: FontFeatures::default(),
|
||||
fallbacks: None,
|
||||
};
|
||||
|
||||
let mut wrapper = TextWrapper::new(font, px(14.), None);
|
||||
wrapper.text = Rope::from(
|
||||
"Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
|
||||
);
|
||||
wrapper.lines = vec![
|
||||
// range: 0..15
|
||||
LineItem {
|
||||
line: Rope::from("Hello, 世界!\r"),
|
||||
wrapped_lines: vec![0..15],
|
||||
},
|
||||
// range: 16..36
|
||||
LineItem {
|
||||
line: Rope::from("This is second line."),
|
||||
wrapped_lines: vec![0..10, 10..20],
|
||||
},
|
||||
// range: 37..56
|
||||
LineItem {
|
||||
line: Rope::from("This is third line."),
|
||||
wrapped_lines: vec![0..9, 9..15, 15..20],
|
||||
},
|
||||
// range: 57..79
|
||||
LineItem {
|
||||
line: Rope::from("这里是第 4 行。"),
|
||||
wrapped_lines: vec![0..22],
|
||||
},
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(12),
|
||||
WrapDisplayPoint::new(0, 0, 12)
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(15),
|
||||
WrapDisplayPoint::new(0, 0, 15)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(16),
|
||||
WrapDisplayPoint::new(1, 0, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(21),
|
||||
WrapDisplayPoint::new(1, 0, 5)
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(27),
|
||||
WrapDisplayPoint::new(2, 1, 1)
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(37),
|
||||
WrapDisplayPoint::new(3, 0, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(54),
|
||||
WrapDisplayPoint::new(5, 2, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.offset_to_display_point(59),
|
||||
WrapDisplayPoint::new(6, 0, 2)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(6, 0, 2)),
|
||||
59
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(5, 2, 2)),
|
||||
54
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(3, 0, 0)),
|
||||
37
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(2, 1, 1)),
|
||||
27
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 5)),
|
||||
21
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 0)),
|
||||
16
|
||||
);
|
||||
assert_eq!(
|
||||
wrapper.display_point_to_offset(WrapDisplayPoint::new(0, 0, 15)),
|
||||
15
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,11 +131,14 @@ impl Element for EditorScrollbar {
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let mut style = Style::default();
|
||||
style.position = Position::Absolute;
|
||||
style.size.width = relative(1.).into();
|
||||
style.size.height = relative(1.).into();
|
||||
|
||||
let style = Style {
|
||||
position: Position::Absolute,
|
||||
size: Size {
|
||||
width: relative(1.).into(),
|
||||
height: relative(1.).into(),
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
(window.request_layout(style, [], cx), ())
|
||||
}
|
||||
|
||||
@@ -309,9 +312,8 @@ impl TextElement {
|
||||
let mut cursor_bounds = None;
|
||||
|
||||
// If the input has a fixed height (Otherwise is auto-grow), we need to add a bottom margin to the input.
|
||||
let top_bottom_margin = if state.mode.is_auto_grow() {
|
||||
line_height
|
||||
} else if visible_range.len() < BOTTOM_MARGIN_ROWS * 8 {
|
||||
let top_bottom_margin =
|
||||
if state.mode.is_auto_grow() || visible_range.len() < BOTTOM_MARGIN_ROWS * 8 {
|
||||
line_height
|
||||
} else {
|
||||
BOTTOM_MARGIN_ROWS * line_height
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(crate) fn input_style(disabled: bool, cx: &App) -> (Hsla, Hsla) {
|
||||
if disabled {
|
||||
(cx.theme().surface_background, cx.theme().text_muted)
|
||||
} else {
|
||||
(cx.theme().surface_background, cx.theme().text)
|
||||
(cx.theme().elevated_surface_background, cx.theme().text)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -298,10 +298,10 @@ impl Render for Notification {
|
||||
|
||||
let action = self.action_builder.clone().map(|builder| {
|
||||
builder(self, window, cx)
|
||||
.xsmall()
|
||||
.small()
|
||||
.primary()
|
||||
.px_3()
|
||||
.font_semibold()
|
||||
.px_4()
|
||||
.font_medium()
|
||||
});
|
||||
|
||||
let icon = match self.kind {
|
||||
@@ -364,8 +364,14 @@ impl Render for Notification {
|
||||
})
|
||||
.when_some(content, |this, content| this.child(content))
|
||||
.when_some(action, |this, action| {
|
||||
this.gap_2()
|
||||
.child(h_flex().w_full().flex_1().justify_end().child(action))
|
||||
this.gap_2().child(
|
||||
h_flex()
|
||||
.mt_2()
|
||||
.w_full()
|
||||
.flex_1()
|
||||
.justify_end()
|
||||
.child(action),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
use anyhow::Error;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
App, AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,
|
||||
SharedString, StatefulInteractiveElement, Styled, Subscription, Task, Window, div, px,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use person::PersonRegistry;
|
||||
use state::{NostrRegistry, StateEvent};
|
||||
use theme::ActiveTheme;
|
||||
use ui::avatar::Avatar;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
use ui::indicator::Indicator;
|
||||
use ui::{Disableable, Icon, IconName, Sizable, WindowExtension, h_flex, v_flex};
|
||||
|
||||
use crate::dialogs::connect::ConnectSigner;
|
||||
use crate::dialogs::import::ImportKey;
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<AccountSelector> {
|
||||
cx.new(|cx| AccountSelector::new(window, cx))
|
||||
}
|
||||
|
||||
/// Account selector
|
||||
pub struct AccountSelector {
|
||||
/// Public key currently being chosen for login
|
||||
logging_in: Entity<Option<PublicKey>>,
|
||||
|
||||
/// The error message displayed when an error occurs.
|
||||
error: Entity<Option<SharedString>>,
|
||||
|
||||
/// Async tasks
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
|
||||
/// Subscription to the signer events
|
||||
_subscription: Option<Subscription>,
|
||||
}
|
||||
|
||||
impl AccountSelector {
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let logging_in = cx.new(|_| None);
|
||||
let error = cx.new(|_| None);
|
||||
|
||||
// Subscribe to the signer events
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let subscription = cx.subscribe_in(&nostr, window, |this, _state, event, window, cx| {
|
||||
match event {
|
||||
StateEvent::SignerSet => {
|
||||
window.close_all_modals(cx);
|
||||
window.refresh();
|
||||
}
|
||||
StateEvent::Error(e) => {
|
||||
this.set_error(e.to_string(), cx);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
});
|
||||
|
||||
Self {
|
||||
logging_in,
|
||||
error,
|
||||
tasks: vec![],
|
||||
_subscription: Some(subscription),
|
||||
}
|
||||
}
|
||||
|
||||
fn logging_in(&self, public_key: &PublicKey, cx: &App) -> bool {
|
||||
self.logging_in.read(cx) == &Some(*public_key)
|
||||
}
|
||||
|
||||
fn set_logging_in(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||
self.logging_in.update(cx, |this, cx| {
|
||||
*this = Some(public_key);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
fn set_error<T>(&mut self, error: T, cx: &mut Context<Self>)
|
||||
where
|
||||
T: Into<SharedString>,
|
||||
{
|
||||
self.error.update(cx, |this, cx| {
|
||||
*this = Some(error.into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
self.logging_in.update(cx, |this, cx| {
|
||||
*this = None;
|
||||
cx.notify();
|
||||
})
|
||||
}
|
||||
|
||||
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let task = nostr.read(cx).get_secret(public_key, cx);
|
||||
|
||||
// Mark the public key as being logged in
|
||||
self.set_logging_in(public_key, cx);
|
||||
|
||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(signer) => {
|
||||
nostr.update(cx, |this, cx| {
|
||||
this.set_signer(signer, cx);
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_error(e.to_string(), cx);
|
||||
})?;
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
fn remove(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
|
||||
nostr.update(cx, |this, cx| {
|
||||
this.remove_secret(&public_key, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn open_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let import = cx.new(|cx| ImportKey::new(window, cx));
|
||||
|
||||
window.open_modal(cx, move |this, _window, _cx| {
|
||||
this.width(px(460.))
|
||||
.title("Import a Secret Key or Bunker Connection")
|
||||
.show_close(true)
|
||||
.pb_2()
|
||||
.child(import.clone())
|
||||
});
|
||||
}
|
||||
|
||||
fn open_connect(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let connect = cx.new(|cx| ConnectSigner::new(window, cx));
|
||||
|
||||
window.open_modal(cx, move |this, _window, _cx| {
|
||||
this.width(px(460.))
|
||||
.title("Scan QR Code to Connect")
|
||||
.show_close(true)
|
||||
.pb_2()
|
||||
.child(connect.clone())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for AccountSelector {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let persons = PersonRegistry::global(cx);
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let npubs = nostr.read(cx).npubs();
|
||||
let loading = self.logging_in.read(cx).is_some();
|
||||
|
||||
v_flex()
|
||||
.size_full()
|
||||
.gap_2()
|
||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
||||
this.child(
|
||||
div()
|
||||
.italic()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.text_color(cx.theme().text_danger)
|
||||
.child(error.clone()),
|
||||
)
|
||||
})
|
||||
.children({
|
||||
let mut items = vec![];
|
||||
|
||||
for (ix, public_key) in npubs.read(cx).iter().enumerate() {
|
||||
let profile = persons.read(cx).get(public_key, cx);
|
||||
let logging_in = self.logging_in(public_key, cx);
|
||||
|
||||
items.push(
|
||||
h_flex()
|
||||
.id(ix)
|
||||
.group("")
|
||||
.px_2()
|
||||
.h_10()
|
||||
.justify_between()
|
||||
.w_full()
|
||||
.rounded(cx.theme().radius)
|
||||
.bg(cx.theme().ghost_element_background)
|
||||
.hover(|this| this.bg(cx.theme().ghost_element_hover))
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_2()
|
||||
.child(Avatar::new(profile.avatar()).small())
|
||||
.child(div().text_sm().child(profile.name())),
|
||||
)
|
||||
.when(logging_in, |this| this.child(Indicator::new().small()))
|
||||
.when(!logging_in, |this| {
|
||||
this.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.invisible()
|
||||
.group_hover("", |this| this.visible())
|
||||
.child(
|
||||
Button::new(format!("del-{ix}"))
|
||||
.icon(IconName::Close)
|
||||
.ghost()
|
||||
.small()
|
||||
.disabled(logging_in)
|
||||
.on_click(cx.listener({
|
||||
let public_key = *public_key;
|
||||
move |this, _ev, _window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.remove(public_key, cx);
|
||||
}
|
||||
})),
|
||||
),
|
||||
)
|
||||
})
|
||||
.when(!logging_in, |this| {
|
||||
let public_key = *public_key;
|
||||
this.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.login(public_key, window, cx);
|
||||
}))
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
items
|
||||
})
|
||||
.child(div().w_full().h_px().bg(cx.theme().border_variant))
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.justify_end()
|
||||
.w_full()
|
||||
.child(
|
||||
Button::new("input")
|
||||
.icon(Icon::new(IconName::Usb))
|
||||
.label("Import")
|
||||
.ghost()
|
||||
.small()
|
||||
.disabled(loading)
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.open_import(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
Button::new("qr")
|
||||
.icon(Icon::new(IconName::Scan))
|
||||
.label("Scan QR to connect")
|
||||
.ghost()
|
||||
.small()
|
||||
.disabled(loading)
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.open_connect(window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use common::StringExt;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||
Subscription, Window, div, img, px,
|
||||
};
|
||||
use nostr_connect::prelude::*;
|
||||
use state::{
|
||||
CLIENT_NAME, CoopAuthUrlHandler, NOSTR_CONNECT_RELAY, NOSTR_CONNECT_TIMEOUT, NostrRegistry,
|
||||
StateEvent,
|
||||
};
|
||||
use theme::ActiveTheme;
|
||||
use ui::v_flex;
|
||||
|
||||
pub struct ConnectSigner {
|
||||
/// QR Code
|
||||
qr_code: Option<Arc<Image>>,
|
||||
|
||||
/// Error message
|
||||
error: Entity<Option<SharedString>>,
|
||||
|
||||
/// Subscription to the signer event
|
||||
_subscription: Option<Subscription>,
|
||||
}
|
||||
|
||||
impl ConnectSigner {
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let error = cx.new(|_| None);
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let app_keys = nostr.read(cx).keys();
|
||||
|
||||
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
|
||||
let relay = RelayUrl::parse(NOSTR_CONNECT_RELAY).unwrap();
|
||||
|
||||
// Generate the nostr connect uri
|
||||
let uri = NostrConnectUri::client(app_keys.public_key(), vec![relay], CLIENT_NAME);
|
||||
|
||||
// Generate the nostr connect
|
||||
let mut signer = NostrConnect::new(uri.clone(), app_keys.clone(), timeout, None).unwrap();
|
||||
|
||||
// Handle the auth request
|
||||
signer.auth_url_handler(CoopAuthUrlHandler);
|
||||
|
||||
// Generate a QR code for quick connection
|
||||
let qr_code = uri.to_string().to_qr();
|
||||
|
||||
// Set signer in the background
|
||||
nostr.update(cx, |this, cx| {
|
||||
this.add_nip46_signer(&signer, cx);
|
||||
});
|
||||
|
||||
// Subscribe to the signer event
|
||||
let subscription = cx.subscribe_in(&nostr, window, |this, _state, event, _window, cx| {
|
||||
if let StateEvent::Error(e) = event {
|
||||
this.set_error(e, cx);
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
qr_code,
|
||||
error,
|
||||
_subscription: Some(subscription),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_error<S>(&mut self, message: S, cx: &mut Context<Self>)
|
||||
where
|
||||
S: Into<SharedString>,
|
||||
{
|
||||
self.error.update(cx, |this, cx| {
|
||||
*this = Some(message.into());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for ConnectSigner {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
const MSG: &str = "Scan with any Nostr Connect-compatible app to connect";
|
||||
|
||||
v_flex()
|
||||
.size_full()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.p_4()
|
||||
.when_some(self.qr_code.as_ref(), |this, qr| {
|
||||
this.child(
|
||||
img(qr.clone())
|
||||
.size(px(256.))
|
||||
.rounded(cx.theme().radius_lg)
|
||||
.border_1()
|
||||
.border_color(cx.theme().border),
|
||||
)
|
||||
})
|
||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
||||
this.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.text_color(cx.theme().text_danger)
|
||||
.child(error.clone()),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.child(SharedString::from(MSG)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,14 @@ use gpui::{
|
||||
Subscription, Task, Window, div,
|
||||
};
|
||||
use nostr_connect::prelude::*;
|
||||
use smallvec::{SmallVec, smallvec};
|
||||
use state::{CoopAuthUrlHandler, NostrRegistry, StateEvent};
|
||||
use state::NostrRegistry;
|
||||
use theme::ActiveTheme;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
use ui::input::{Input, InputEvent, InputState};
|
||||
use ui::{Disableable, v_flex};
|
||||
use ui::{Disableable, WindowExtension, v_flex};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ImportKey {
|
||||
pub struct ImportIdentity {
|
||||
/// Secret key input
|
||||
key_input: Entity<InputState>,
|
||||
|
||||
@@ -25,73 +24,43 @@ pub struct ImportKey {
|
||||
/// Error message
|
||||
error: Entity<Option<SharedString>>,
|
||||
|
||||
/// Countdown timer for nostr connect
|
||||
countdown: Entity<Option<u64>>,
|
||||
|
||||
/// Whether the user is currently loading
|
||||
loading: bool,
|
||||
|
||||
/// Async tasks
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
|
||||
/// Event subscriptions
|
||||
_subscriptions: SmallVec<[Subscription; 2]>,
|
||||
/// Input subscription
|
||||
_subscription: Option<Subscription>,
|
||||
}
|
||||
|
||||
impl ImportKey {
|
||||
impl ImportIdentity {
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let key_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||
let pass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||
let error = cx.new(|_| None);
|
||||
let countdown = cx.new(|_| None);
|
||||
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to key input events and process login when the user presses enter
|
||||
let input_subscription =
|
||||
cx.subscribe_in(&key_input, window, |this, _input, event, window, cx| {
|
||||
if let InputEvent::PressEnter { .. } = event {
|
||||
this.login(window, cx);
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to the nostr signer event
|
||||
cx.subscribe_in(&nostr, window, |this, _state, event, _window, cx| {
|
||||
if let StateEvent::Error(e) = event {
|
||||
this.set_error(e, cx);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
Self {
|
||||
key_input,
|
||||
pass_input,
|
||||
error,
|
||||
countdown,
|
||||
loading: false,
|
||||
tasks: vec![],
|
||||
_subscriptions: subscriptions,
|
||||
_subscription: Some(input_subscription),
|
||||
}
|
||||
}
|
||||
|
||||
fn login(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.loading {
|
||||
return;
|
||||
};
|
||||
// Prevent duplicate login requests
|
||||
self.set_loading(true, cx);
|
||||
|
||||
let value = self.key_input.read(cx).value();
|
||||
let password = self.pass_input.read(cx).value();
|
||||
|
||||
if value.starts_with("bunker://") {
|
||||
self.bunker(&value, window, cx);
|
||||
return;
|
||||
}
|
||||
|
||||
if value.starts_with("ncryptsec1") {
|
||||
self.ncryptsec(value, password, window, cx);
|
||||
return;
|
||||
@@ -103,52 +72,14 @@ impl ImportKey {
|
||||
|
||||
// Update the signer
|
||||
nostr.update(cx, |this, cx| {
|
||||
this.add_key_signer(&keys, cx);
|
||||
this.set_signer(keys, cx);
|
||||
});
|
||||
window.close_modal(cx);
|
||||
} else {
|
||||
self.set_error("Invalid key", cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn bunker(&mut self, content: &str, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Ok(uri) = NostrConnectUri::parse(content) else {
|
||||
self.set_error("Bunker is not valid", cx);
|
||||
return;
|
||||
};
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let app_keys = nostr.read(cx).keys();
|
||||
let timeout = Duration::from_secs(30);
|
||||
|
||||
// Construct the nostr connect signer
|
||||
let mut signer = NostrConnect::new(uri, app_keys.clone(), timeout, None).unwrap();
|
||||
|
||||
// Handle auth url with the default browser
|
||||
signer.auth_url_handler(CoopAuthUrlHandler);
|
||||
|
||||
// Set signer in the background
|
||||
nostr.update(cx, |this, cx| {
|
||||
this.add_nip46_signer(&signer, cx);
|
||||
});
|
||||
|
||||
// Start countdown
|
||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||
for i in (0..=30).rev() {
|
||||
if i == 0 {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_countdown(None, cx);
|
||||
})?;
|
||||
} else {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_countdown(Some(i), cx);
|
||||
})?;
|
||||
}
|
||||
cx.background_executor().timer(Duration::from_secs(1)).await;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
fn ncryptsec<S>(&mut self, content: S, pwd: S, window: &mut Window, cx: &mut Context<Self>)
|
||||
where
|
||||
S: Into<String>,
|
||||
@@ -179,9 +110,10 @@ impl ImportKey {
|
||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(keys) => {
|
||||
nostr.update(cx, |this, cx| {
|
||||
this.add_key_signer(&keys, cx);
|
||||
});
|
||||
nostr.update_in(cx, |this, window, cx| {
|
||||
this.set_signer(keys, cx);
|
||||
window.close_modal(cx);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -198,12 +130,6 @@ impl ImportKey {
|
||||
where
|
||||
S: Into<SharedString>,
|
||||
{
|
||||
// Reset the log in state
|
||||
self.set_loading(false, cx);
|
||||
|
||||
// Reset the countdown
|
||||
self.set_countdown(None, cx);
|
||||
|
||||
// Update error message
|
||||
self.error.update(cx, |this, cx| {
|
||||
*this = Some(message.into());
|
||||
@@ -224,22 +150,12 @@ impl ImportKey {
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
fn set_loading(&mut self, status: bool, cx: &mut Context<Self>) {
|
||||
self.loading = status;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn set_countdown(&mut self, i: Option<u64>, cx: &mut Context<Self>) {
|
||||
self.countdown.update(cx, |this, cx| {
|
||||
*this = i;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for ImportKey {
|
||||
impl Render for ImportIdentity {
|
||||
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
const MSG: &str = "Coop isn't stored your identity secret in local device. Everything will be reset on the next login.";
|
||||
|
||||
v_flex()
|
||||
.size_full()
|
||||
.gap_2()
|
||||
@@ -249,7 +165,7 @@ impl Render for ImportKey {
|
||||
.gap_1()
|
||||
.text_sm()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.child("nsec or bunker://")
|
||||
.child("nsec or ncryptsec://")
|
||||
.child(Input::new(&self.key_input)),
|
||||
)
|
||||
.when(
|
||||
@@ -265,6 +181,7 @@ impl Render for ImportKey {
|
||||
)
|
||||
},
|
||||
)
|
||||
.child(div().text_xs().text_color(cx.theme().text_muted).child(MSG))
|
||||
.child(
|
||||
Button::new("login")
|
||||
.label("Continue")
|
||||
@@ -275,18 +192,6 @@ impl Render for ImportKey {
|
||||
this.login(window, cx);
|
||||
})),
|
||||
)
|
||||
.when_some(self.countdown.read(cx).as_ref(), |this, i| {
|
||||
this.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.child(SharedString::from(format!(
|
||||
"Approve connection request from your signer in {} seconds",
|
||||
i
|
||||
))),
|
||||
)
|
||||
})
|
||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
||||
this.child(
|
||||
div()
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
pub mod accounts;
|
||||
pub mod connect;
|
||||
pub mod import;
|
||||
pub mod restore;
|
||||
pub mod screening;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error};
|
||||
use anyhow::Error;
|
||||
use common::TimestampExt;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
@@ -78,12 +78,13 @@ impl Screening {
|
||||
let client = nostr.read(cx).client();
|
||||
let public_key = self.public_key;
|
||||
|
||||
let task: Task<Result<bool, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let signer_pubkey = signer.get_public_key().await?;
|
||||
let Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<bool, Error>> = cx.background_spawn(async move {
|
||||
// Check if user is in contact list
|
||||
let contacts = client.database().contacts_public_keys(signer_pubkey).await;
|
||||
let contacts = client.database().contacts_public_keys(current_user).await;
|
||||
let followed = contacts.unwrap_or_default().contains(&public_key);
|
||||
|
||||
Ok(followed)
|
||||
@@ -105,16 +106,17 @@ impl Screening {
|
||||
let client = nostr.read(cx).client();
|
||||
let public_key = self.public_key;
|
||||
|
||||
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let signer_pubkey = signer.get_public_key().await?;
|
||||
let Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||
// Check mutual contacts
|
||||
let filter = Filter::new().kind(Kind::ContactList).pubkey(public_key);
|
||||
let mut mutual_contacts = vec![];
|
||||
|
||||
if let Ok(events) = client.database().query(filter).await {
|
||||
for event in events.into_iter().filter(|ev| ev.pubkey != signer_pubkey) {
|
||||
for event in events.into_iter().filter(|ev| ev.pubkey != current_user) {
|
||||
mutual_contacts.push(event.pubkey);
|
||||
}
|
||||
}
|
||||
@@ -224,10 +226,20 @@ impl Screening {
|
||||
let client = nostr.read(cx).client();
|
||||
let public_key = self.public_key;
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let tag = Tag::public_key_report(public_key, Report::Impersonation);
|
||||
let builder = EventBuilder::report(vec![tag], "");
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let tag = Nip56Tag::PublicKey {
|
||||
public_key,
|
||||
report: Report::Impersonation,
|
||||
}
|
||||
.to_tag();
|
||||
|
||||
let event = EventBuilder::report(vec![tag], "")
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Send the report to the public relays
|
||||
client.send_event(&event).to(BOOTSTRAP_RELAYS).await?;
|
||||
|
||||
@@ -56,17 +56,16 @@ impl Preferences {
|
||||
|
||||
impl Render for Preferences {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
const SCREENING: &str =
|
||||
"When opening a request, a popup will appear to help you identify the sender.";
|
||||
const AVATAR: &str =
|
||||
"Hide all avatar pictures to improve performance and protect your privacy.";
|
||||
const MODE: &str =
|
||||
"Choose whether to use the selected light or dark theme, or to follow the OS.";
|
||||
const SCREENING: &str = "Show an screening dialog to verify the unknown sender.";
|
||||
const AVATAR: &str = "Hide all avatar pictures to improve performance.";
|
||||
const MODE: &str = "Use the selected light or dark theme, or to follow the OS.";
|
||||
const NIP4E: &str = "Use a dedicated key to encrypt and decrypt messages.";
|
||||
const AUTH: &str = "Choose the authentication behavior for relays.";
|
||||
const RESET: &str = "Reset the theme to the default one.";
|
||||
|
||||
let screening = AppSettings::get_screening(cx);
|
||||
let hide_avatar = AppSettings::get_hide_avatar(cx);
|
||||
let nip4e = AppSettings::get_nip4e(cx);
|
||||
let auth_mode = AppSettings::get_auth_mode(cx);
|
||||
let theme_mode = AppSettings::get_theme_mode(cx);
|
||||
|
||||
@@ -207,6 +206,21 @@ impl Render for Preferences {
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
GroupBox::new()
|
||||
.id("experiments")
|
||||
.title("Experiments")
|
||||
.fill()
|
||||
.child(
|
||||
Switch::new("nip4e")
|
||||
.label("Decoupling Encryption Key")
|
||||
.description(NIP4E)
|
||||
.checked(nip4e)
|
||||
.on_click(move |_, _window, cx| {
|
||||
AppSettings::update_nip4e(!nip4e, cx);
|
||||
}),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
GroupBox::new()
|
||||
.id("media")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error};
|
||||
use anyhow::Error;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
||||
@@ -82,11 +82,12 @@ impl ContactListPanel {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let contact_list = client.database().contacts_public_keys(public_key).await?;
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||
let contact_list = client.database().contacts_public_keys(public_key).await?;
|
||||
Ok(contact_list)
|
||||
});
|
||||
|
||||
@@ -157,6 +158,10 @@ impl ContactListPanel {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Get contacts
|
||||
let contacts: Vec<Contact> = self
|
||||
.contacts
|
||||
@@ -169,8 +174,9 @@ impl ContactListPanel {
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
// Construct contact list event builder
|
||||
let builder = EventBuilder::contact_list(contacts);
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = ContactListBuilder::new(contacts)
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Set contact list
|
||||
client.send_event(&event).to_nip65().await?;
|
||||
|
||||
@@ -30,9 +30,8 @@ impl GreeterPanel {
|
||||
|
||||
fn add_profile_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
if let Some(public_key) = signer.public_key() {
|
||||
if let Some(public_key) = nostr.read(cx).signer_pubkey(cx) {
|
||||
cx.spawn_in(window, async move |_this, cx| {
|
||||
cx.update(|window, cx| {
|
||||
Workspace::add_panel(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||
use anyhow::{Error, anyhow};
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
||||
@@ -83,17 +83,18 @@ impl MessagingRelayPanel {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let task: Task<Result<Vec<RelayUrl>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<Vec<RelayUrl>, Error>> = cx.background_spawn(async move {
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||
Ok(nip17::extract_owned_relay_list(event).collect())
|
||||
Ok(nip17::extract_relay_list(&event).collect())
|
||||
} else {
|
||||
Err(anyhow!("Not found."))
|
||||
}
|
||||
@@ -171,11 +172,15 @@ impl MessagingRelayPanel {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Construct event tags
|
||||
let tags: Vec<Tag> = self
|
||||
.relays
|
||||
.iter()
|
||||
.map(|relay| Tag::relay(relay.clone()))
|
||||
.map(|relay| Nip17Tag::Relay(relay.to_owned()).to_tag())
|
||||
.collect();
|
||||
|
||||
// Set updating state
|
||||
@@ -183,8 +188,10 @@ impl MessagingRelayPanel {
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
// Construct nip17 event builder
|
||||
let builder = EventBuilder::new(Kind::InboxRelays, "").tags(tags);
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::new(Kind::InboxRelays, "")
|
||||
.tags(tags)
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Set messaging relays
|
||||
client.send_event(&event).to_nip65().await?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error};
|
||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||
use gpui::{
|
||||
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||
Focusable, IntoElement, ParentElement, PathPromptOptions, Render, SharedString, Styled, Task,
|
||||
@@ -209,10 +209,15 @@ impl ProfilePanel {
|
||||
let client = nostr.read(cx).client();
|
||||
let metadata = metadata.clone();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return Task::ready(Err(anyhow!("Signer is required")));
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
// Build and sign the metadata event
|
||||
let builder = EventBuilder::metadata(&metadata);
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::metadata(&metadata)
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Send event to user's relays
|
||||
client.send_event(&event).await?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||
use anyhow::{Error, anyhow};
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
Action, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
||||
@@ -100,18 +100,19 @@ impl RelayListPanel {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<Vec<(RelayUrl, Option<RelayMetadata>)>, Error>> = cx
|
||||
.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::RelayList)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||
Ok(nip65::extract_owned_relay_list(event).collect())
|
||||
Ok(nip65::extract_relay_list(&event).collect())
|
||||
} else {
|
||||
Err(anyhow!("Not found."))
|
||||
}
|
||||
@@ -207,6 +208,10 @@ impl RelayListPanel {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Get all relays
|
||||
let relays = self.relays.clone();
|
||||
|
||||
@@ -214,8 +219,9 @@ impl RelayListPanel {
|
||||
self.set_updating(true, cx);
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let builder = EventBuilder::relay_list(relays);
|
||||
let event = client.sign_event_builder(builder).await?;
|
||||
let event = EventBuilder::relay_list(relays)
|
||||
.finalize_async(&signer)
|
||||
.await?;
|
||||
|
||||
// Set relay list for current user
|
||||
client.send_event(&event).await?;
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::ops::Range;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as AnyhowContext, Error};
|
||||
use anyhow::Error;
|
||||
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
||||
use common::{DebouncedDelay, TimestampExt, coop_cache};
|
||||
use entry::RoomEntry;
|
||||
@@ -159,11 +159,12 @@ impl Sidebar {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let client = nostr.read(cx).client();
|
||||
|
||||
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().context("Signer not found")?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let contacts = client.database().contacts_public_keys(public_key).await?;
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||
let contacts = client.database().contacts_public_keys(public_key).await?;
|
||||
Ok(contacts)
|
||||
});
|
||||
|
||||
@@ -319,14 +320,14 @@ impl Sidebar {
|
||||
let async_chat = chat.downgrade();
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Get all selected public keys
|
||||
let receivers = self.get_selected(cx);
|
||||
|
||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
// Create a new room and emit it
|
||||
async_chat.update_in(cx, |this, _window, cx| {
|
||||
let room = cx.new(|_| {
|
||||
|
||||
@@ -24,30 +24,24 @@ use ui::menu::{DropdownMenu, PopupMenuItem};
|
||||
use ui::notification::{Notification, NotificationKind};
|
||||
use ui::{Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
||||
|
||||
use crate::dialogs::import::ImportIdentity;
|
||||
use crate::dialogs::restore::RestoreEncryption;
|
||||
use crate::dialogs::{accounts, settings};
|
||||
use crate::dialogs::settings;
|
||||
use crate::panels::{backup, contact_list, greeter, messaging_relays, profile, relay_list, trash};
|
||||
use crate::sidebar;
|
||||
|
||||
const PREPARE_MSG: &str = "Coop is preparing a new identity for you. This may take a moment...";
|
||||
const ENC_MSG: &str = "Encryption Key is a special key that used to encrypt and decrypt your messages. \
|
||||
Your identity is completely decoupled from all encryption processes to protect your privacy.";
|
||||
const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \
|
||||
all your encrypted messages before. This action cannot be undone.";
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Workspace> {
|
||||
cx.new(|cx| Workspace::new(window, cx))
|
||||
}
|
||||
|
||||
struct DeviceNotifcation;
|
||||
struct SignerNotifcation;
|
||||
struct RelayNotifcation;
|
||||
struct MsgRelayNotification;
|
||||
|
||||
#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[action(namespace = workspace, no_json)]
|
||||
enum Command {
|
||||
ToggleTheme,
|
||||
ToggleAccount,
|
||||
|
||||
RefreshMessagingRelays,
|
||||
BackupEncryption,
|
||||
@@ -74,7 +68,7 @@ pub struct Workspace {
|
||||
image_cache: Entity<CoopImageCache>,
|
||||
|
||||
/// Event subscriptions
|
||||
_subscriptions: SmallVec<[Subscription; 5]>,
|
||||
_subscriptions: SmallVec<[Subscription; 6]>,
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
@@ -82,6 +76,7 @@ impl Workspace {
|
||||
let chat = ChatRegistry::global(cx);
|
||||
let device = DeviceRegistry::global(cx);
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer.clone();
|
||||
|
||||
let titlebar = cx.new(|_| TitleBar::new());
|
||||
let dock = cx.new(|cx| DockArea::new(window, cx));
|
||||
@@ -97,19 +92,20 @@ impl Workspace {
|
||||
);
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to the signer events
|
||||
cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| {
|
||||
match event {
|
||||
StateEvent::Creating => {
|
||||
let note = Notification::new()
|
||||
.id::<SignerNotifcation>()
|
||||
.title("Preparing a new identity")
|
||||
.message(PREPARE_MSG)
|
||||
.autohide(false)
|
||||
.with_kind(NotificationKind::Info);
|
||||
|
||||
window.push_notification(note, cx);
|
||||
// Observe the signer
|
||||
cx.observe_in(&signer, window, |this, signer, window, cx| {
|
||||
if signer.read(cx).is_some() {
|
||||
this.set_center_layout(window, cx);
|
||||
} else {
|
||||
this.import_identity(window, cx);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe to the nostr events
|
||||
cx.subscribe_in(&nostr, window, move |this, state, event, window, cx| {
|
||||
match event {
|
||||
StateEvent::Connecting => {
|
||||
let note = Notification::new()
|
||||
.id::<RelayNotifcation>()
|
||||
@@ -125,14 +121,10 @@ impl Workspace {
|
||||
.with_kind(NotificationKind::Success);
|
||||
|
||||
window.push_notification(note, cx);
|
||||
|
||||
if state.read(cx).signer.read(cx).is_none() {
|
||||
this.import_identity(window, cx);
|
||||
}
|
||||
StateEvent::SignerSet => {
|
||||
this.set_center_layout(window, cx);
|
||||
// Clear the signer notification
|
||||
window.clear_notification::<SignerNotifcation>(cx);
|
||||
}
|
||||
StateEvent::Show => {
|
||||
this.account_selector(window, cx);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
@@ -145,7 +137,7 @@ impl Workspace {
|
||||
match event {
|
||||
DeviceEvent::Requesting => {
|
||||
const MSG: &str =
|
||||
"Coop has sent a request for an encryption key. Please open the other client then approve the request.";
|
||||
"Please open other client and approve the request for encryption key.";
|
||||
|
||||
let note = Notification::new()
|
||||
.id::<DeviceNotifcation>()
|
||||
@@ -156,12 +148,25 @@ impl Workspace {
|
||||
|
||||
window.push_notification(note, cx);
|
||||
}
|
||||
DeviceEvent::Creating => {
|
||||
DeviceEvent::NotSet => {
|
||||
const MSG: &str =
|
||||
"User're not setup encryption key yet. Do you want to create one?";
|
||||
|
||||
let note = Notification::new()
|
||||
.id::<DeviceNotifcation>()
|
||||
.autohide(false)
|
||||
.message("Creating encryption key")
|
||||
.with_kind(NotificationKind::Info);
|
||||
.message(MSG)
|
||||
.with_kind(NotificationKind::Info)
|
||||
.action(|_this, _window, _cx| {
|
||||
Button::new("retry").label("Retry").on_click(
|
||||
move |_this, window, cx| {
|
||||
let device = DeviceRegistry::global(cx);
|
||||
device.update(cx, |this, cx| {
|
||||
this.set_announcement(Keys::generate(), cx);
|
||||
});
|
||||
window.clear_notification::<DeviceNotifcation>(cx);
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
window.push_notification(note, cx);
|
||||
}
|
||||
@@ -184,6 +189,27 @@ impl Workspace {
|
||||
// Observe all events emitted by the chat registry
|
||||
cx.subscribe_in(&chat, window, move |this, chat, ev, window, cx| {
|
||||
match ev {
|
||||
ChatEvent::InboxRelayNotFound => {
|
||||
const MSG: &str = "Messaging Relays not found. Cannot receive messages.";
|
||||
|
||||
window.push_notification(
|
||||
Notification::warning(MSG)
|
||||
.id::<MsgRelayNotification>()
|
||||
.autohide(false)
|
||||
.action(|_this, _window, _cx| {
|
||||
Button::new("retry").label("Retry").on_click(
|
||||
move |_this, window, cx| {
|
||||
let chat = ChatRegistry::global(cx);
|
||||
chat.update(cx, |this, cx| {
|
||||
this.get_metadata(cx);
|
||||
});
|
||||
window.clear_notification::<MsgRelayNotification>(cx);
|
||||
},
|
||||
)
|
||||
}),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
ChatEvent::OpenRoom(id) => {
|
||||
if let Some(room) = chat.read(cx).room(id, cx) {
|
||||
this.dock.update(cx, |this, cx| {
|
||||
@@ -306,9 +332,8 @@ impl Workspace {
|
||||
}
|
||||
Command::ShowProfile => {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
if let Some(public_key) = signer.public_key() {
|
||||
if let Some(public_key) = nostr.read(cx).signer_pubkey(cx) {
|
||||
self.dock.update(cx, |this, cx| {
|
||||
this.add_panel(
|
||||
Arc::new(profile::init(public_key, window, cx)),
|
||||
@@ -353,7 +378,7 @@ impl Workspace {
|
||||
let chat = ChatRegistry::global(cx);
|
||||
// Trigger a refresh of the chat registry
|
||||
chat.update(cx, |this, cx| {
|
||||
this.refresh(window, cx);
|
||||
this.refresh(cx);
|
||||
});
|
||||
}
|
||||
Command::ShowRelayList => {
|
||||
@@ -378,9 +403,6 @@ impl Workspace {
|
||||
Command::ToggleTheme => {
|
||||
self.theme_selector(window, cx);
|
||||
}
|
||||
Command::ToggleAccount => {
|
||||
self.account_selector(window, cx);
|
||||
}
|
||||
Command::BackupEncryption => {
|
||||
let device = DeviceRegistry::global(cx).downgrade();
|
||||
let save_dialog = cx.prompt_for_new_path(download_dir(), Some("encryption.txt"));
|
||||
@@ -423,6 +445,12 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn confirm_reset_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
const ENC_MSG: &str = "Encryption Key is a special key that used to encrypt and decrypt your messages. \
|
||||
Your identity is completely decoupled from all encryption processes to protect your privacy.";
|
||||
|
||||
const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \
|
||||
all your encrypted messages before. This action cannot be undone.";
|
||||
|
||||
let device = DeviceRegistry::global(cx);
|
||||
let ent = device.downgrade();
|
||||
|
||||
@@ -457,24 +485,21 @@ impl Workspace {
|
||||
|
||||
fn import_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let restore = cx.new(|cx| RestoreEncryption::new(window, cx));
|
||||
|
||||
window.open_modal(cx, move |this, _window, _cx| {
|
||||
this.width(px(520.))
|
||||
this.width(px(420.))
|
||||
.title("Restore Encryption")
|
||||
.child(restore.clone())
|
||||
});
|
||||
}
|
||||
|
||||
fn account_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let accounts = accounts::init(window, cx);
|
||||
fn import_identity(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let import = cx.new(|cx| ImportIdentity::new(window, cx));
|
||||
|
||||
window.open_modal(cx, move |this, _window, _cx| {
|
||||
this.width(px(520.))
|
||||
.title("Continue with")
|
||||
this.width(px(420.))
|
||||
.show_close(false)
|
||||
.keyboard(false)
|
||||
.overlay_closable(false)
|
||||
.child(accounts.clone())
|
||||
.title("Import Identity")
|
||||
.child(import.clone())
|
||||
});
|
||||
}
|
||||
|
||||
@@ -560,8 +585,7 @@ impl Workspace {
|
||||
|
||||
fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
let current_user = signer.public_key();
|
||||
let current_user = nostr.read(cx).signer_pubkey(cx);
|
||||
|
||||
h_flex()
|
||||
.flex_shrink_0()
|
||||
@@ -571,7 +595,7 @@ impl Workspace {
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.child(SharedString::from("Choose an account to continue...")),
|
||||
.child(SharedString::from("Import your identity to continue")),
|
||||
)
|
||||
})
|
||||
.when_some(current_user.as_ref(), |this, public_key| {
|
||||
@@ -622,11 +646,6 @@ impl Workspace {
|
||||
Box::new(Command::ToggleTheme),
|
||||
)
|
||||
.separator()
|
||||
.menu_with_icon(
|
||||
"Accounts",
|
||||
IconName::Group,
|
||||
Box::new(Command::ToggleAccount),
|
||||
)
|
||||
.menu_with_icon(
|
||||
"Settings",
|
||||
IconName::Settings,
|
||||
@@ -639,16 +658,12 @@ impl Workspace {
|
||||
|
||||
fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let chat = ChatRegistry::global(cx);
|
||||
let initializing = chat.read(cx).initializing;
|
||||
let trash_messages = chat.read(cx).count_trash_messages(cx);
|
||||
|
||||
let device = DeviceRegistry::global(cx);
|
||||
let device_initializing = device.read(cx).initializing;
|
||||
|
||||
let is_nip4e_enabled = AppSettings::get_nip4e(cx);
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let signer = nostr.read(cx).signer();
|
||||
|
||||
let Some(public_key) = signer.public_key() else {
|
||||
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||
return div();
|
||||
};
|
||||
|
||||
@@ -691,18 +706,13 @@ impl Workspace {
|
||||
}),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
.when(is_nip4e_enabled, |this| {
|
||||
this.child(
|
||||
Button::new("key")
|
||||
.icon(IconName::UserKey)
|
||||
.tooltip("Decoupled encryption key")
|
||||
.small()
|
||||
.ghost()
|
||||
.loading(device_initializing)
|
||||
.when(device_initializing, |this| {
|
||||
this.label("Dekey")
|
||||
.xsmall()
|
||||
.tooltip("Loading decoupled encryption key...")
|
||||
})
|
||||
.dropdown_menu(move |this, _window, _cx| {
|
||||
this.min_w(px(260.))
|
||||
.label("Encryption Key")
|
||||
@@ -721,7 +731,8 @@ impl Workspace {
|
||||
)
|
||||
.child(name.clone())
|
||||
}))
|
||||
.item(PopupMenuItem::element(move |_window, cx| {
|
||||
.item(
|
||||
PopupMenuItem::element(move |_window, cx| {
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.text_sm()
|
||||
@@ -731,7 +742,8 @@ impl Workspace {
|
||||
.text_color(cx.theme().icon_muted),
|
||||
)
|
||||
.child(SharedString::from(pkey.clone()))
|
||||
}))
|
||||
}),
|
||||
)
|
||||
})
|
||||
.separator()
|
||||
.menu_with_icon(
|
||||
@@ -757,17 +769,12 @@ impl Workspace {
|
||||
)
|
||||
}),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
Button::new("inbox")
|
||||
.icon(IconName::Inbox)
|
||||
.small()
|
||||
.ghost()
|
||||
.loading(initializing)
|
||||
.when(initializing, |this| {
|
||||
this.label("Inbox")
|
||||
.xsmall()
|
||||
.tooltip("Getting inbox messages...")
|
||||
})
|
||||
.dropdown_menu(move |this, _window, cx| {
|
||||
let urls: Vec<(SharedString, SharedString)> = profile
|
||||
.messaging_relays()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[toolchain]
|
||||
channel = "1.92"
|
||||
channel = "1.96"
|
||||
profile = "minimal"
|
||||
components = ["rustfmt", "clippy"]
|
||||
targets = [
|
||||
|
||||
Reference in New Issue
Block a user