feat: add relay tracking for gift wrap events #21

Merged
reya merged 5 commits from chat-patch into master 2026-03-14 08:18:20 +00:00
8 changed files with 277 additions and 121 deletions

View File

@@ -15,6 +15,7 @@ use gpui::{
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use smol::lock::RwLock;
use state::{DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP}; use state::{DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP};
mod message; mod message;
@@ -60,9 +61,12 @@ enum Signal {
/// Chat Registry /// Chat Registry
#[derive(Debug)] #[derive(Debug)]
pub struct ChatRegistry { pub struct ChatRegistry {
/// Collection of all chat rooms /// Chat rooms
rooms: Vec<Entity<Room>>, rooms: Vec<Entity<Room>>,
/// Tracking events seen on which relays in the current session
seens: Arc<RwLock<HashMap<EventId, HashSet<RelayUrl>>>>,
/// Tracking the status of unwrapping gift wrap events. /// Tracking the status of unwrapping gift wrap events.
tracking_flag: Arc<AtomicBool>, tracking_flag: Arc<AtomicBool>,
@@ -101,12 +105,17 @@ impl ChatRegistry {
subscriptions.push( subscriptions.push(
// Subscribe to the signer event // Subscribe to the signer event
cx.subscribe(&nostr, |this, _state, event, cx| { cx.subscribe(&nostr, |this, _state, event, cx| {
if let StateEvent::SignerSet = event { match event {
this.reset(cx); StateEvent::SignerSet => {
this.get_rooms(cx); this.reset(cx);
this.get_contact_list(cx); this.get_rooms(cx);
this.get_messages(cx) }
} StateEvent::RelayConnected => {
this.get_contact_list(cx);
this.get_messages(cx)
}
_ => {}
};
}), }),
); );
@@ -119,6 +128,7 @@ impl ChatRegistry {
Self { Self {
rooms: vec![], rooms: vec![],
seens: Arc::new(RwLock::new(HashMap::default())),
tracking_flag: Arc::new(AtomicBool::new(false)), tracking_flag: Arc::new(AtomicBool::new(false)),
signal_rx: rx, signal_rx: rx,
signal_tx: tx, signal_tx: tx,
@@ -133,6 +143,7 @@ impl ChatRegistry {
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
let status = self.tracking_flag.clone(); let status = self.tracking_flag.clone();
let seens = self.seens.clone();
let initialized_at = Timestamp::now(); let initialized_at = Timestamp::now();
let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP); let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP);
@@ -148,20 +159,26 @@ impl ChatRegistry {
let mut processed_events = HashSet::new(); let mut processed_events = HashSet::new();
while let Some(notification) = notifications.next().await { while let Some(notification) = notifications.next().await {
let ClientNotification::Message { message, .. } = notification else { let ClientNotification::Message { message, relay_url } = notification else {
// Skip non-message notifications // Skip non-message notifications
continue; continue;
}; };
match message { match message {
RelayMessage::Event { event, .. } => { RelayMessage::Event { event, .. } => {
// Keep track of which relays have seen this event
{
let mut seens = seens.write().await;
seens.entry(event.id).or_default().insert(relay_url);
}
// De-duplicate events by their ID
if !processed_events.insert(event.id) { if !processed_events.insert(event.id) {
// Skip if the event has already been processed
continue; continue;
} }
// Skip non-gift wrap events
if event.kind != Kind::GiftWrap { if event.kind != Kind::GiftWrap {
// Skip non-gift wrap events
continue; continue;
} }
@@ -169,26 +186,21 @@ impl ChatRegistry {
match extract_rumor(&client, &device_signer, event.as_ref()).await { match extract_rumor(&client, &device_signer, event.as_ref()).await {
Ok(rumor) => { Ok(rumor) => {
if rumor.tags.is_empty() { if rumor.tags.is_empty() {
let error: SharedString = let error: SharedString = "No room for message".into();
"Message doesn't belong to any rooms".into();
tx.send_async(Signal::Error(error)).await?; tx.send_async(Signal::Error(error)).await?;
} }
match rumor.created_at >= initialized_at { if rumor.created_at >= initialized_at {
true => { let new_message = NewMessage::new(event.id, rumor);
let new_message = NewMessage::new(event.id, rumor); let signal = Signal::Message(new_message);
let signal = Signal::Message(new_message);
tx.send_async(signal).await?; tx.send_async(signal).await?;
} } else {
false => { status.store(true, Ordering::Release);
status.store(true, Ordering::Release);
}
} }
} }
Err(e) => { Err(e) => {
let error: SharedString = let error: SharedString = format!("Failed to unwrap: {e}").into();
format!("Failed to unwrap the gift wrap event: {e}").into();
tx.send_async(Signal::Error(error)).await?; tx.send_async(Signal::Error(error)).await?;
} }
} }
@@ -325,6 +337,7 @@ impl ChatRegistry {
while let Some((_url, res)) = stream.next().await { while let Some((_url, res)) = stream.next().await {
if let Ok(event) = res { if let Ok(event) = res {
log::debug!("Got event: {:?}", event);
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect(); let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
return Ok(urls); return Ok(urls);
} }
@@ -399,6 +412,24 @@ impl ChatRegistry {
.count() .count()
} }
/// Count the number of messages seen by a given relay.
pub fn count_messages(&self, relay_url: &RelayUrl) -> usize {
self.seens
.read_blocking()
.values()
.filter(|seen| seen.contains(relay_url))
.count()
}
/// Get the relays that have seen a given message.
pub fn seen_on(&self, id: &EventId) -> HashSet<RelayUrl> {
self.seens
.read_blocking()
.get(id)
.cloned()
.unwrap_or_default()
}
/// Add a new room to the start of list. /// Add a new room to the start of list.
pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>) pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>)
where where

View File

@@ -10,7 +10,6 @@ pub enum Command {
ChangeSubject(String), ChangeSubject(String),
ChangeSigner(SignerKind), ChangeSigner(SignerKind),
ToggleBackup, ToggleBackup,
Subject,
Copy(PublicKey), Copy(PublicKey),
Relays(PublicKey), Relays(PublicKey),
Njump(PublicKey), Njump(PublicKey),

View File

@@ -154,6 +154,7 @@ impl ChatPanel {
// Define all functions that will run after the current cycle // Define all functions that will run after the current cycle
cx.defer_in(window, |this, window, cx| { cx.defer_in(window, |this, window, cx| {
this.connect(cx);
this.handle_notifications(cx); this.handle_notifications(cx);
this.subscribe_room_events(window, cx); this.subscribe_room_events(window, cx);
this.get_messages(window, cx); this.get_messages(window, cx);
@@ -179,6 +180,14 @@ impl ChatPanel {
} }
} }
/// Get messaging relays and announcement for each member
fn connect(&mut self, cx: &mut Context<Self>) {
if let Some(room) = self.room.upgrade() {
let task = room.read(cx).connect(cx);
self.tasks.push(task);
}
}
/// Handle nostr notifications /// Handle nostr notifications
fn handle_notifications(&mut self, cx: &mut Context<Self>) { fn handle_notifications(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
@@ -247,11 +256,13 @@ impl ChatPanel {
})); }));
} }
/// Subscribe to room events
fn subscribe_room_events(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn subscribe_room_events(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Some(room) = self.room.upgrade() { if let Some(room) = self.room.upgrade() {
self.subscriptions.push( self.subscriptions.push(cx.subscribe_in(
// Subscribe to room events &room,
cx.subscribe_in(&room, window, move |this, _room, event, window, cx| { window,
move |this, _room, event, window, cx| {
match event { match event {
RoomEvent::Incoming(message) => { RoomEvent::Incoming(message) => {
this.insert_message(message, false, cx); this.insert_message(message, false, cx);
@@ -260,8 +271,8 @@ impl ChatPanel {
this.get_messages(window, cx); this.get_messages(window, cx);
} }
}; };
}), },
); ));
} }
} }
@@ -645,9 +656,6 @@ impl ChatPanel {
); );
} }
} }
Command::Subject => {
self.open_subject(window, cx);
}
Command::Copy(public_key) => { Command::Copy(public_key) => {
self.copy_author(public_key, cx); self.copy_author(public_key, cx);
} }
@@ -660,47 +668,6 @@ impl ChatPanel {
} }
} }
fn open_subject(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let subject_input = self.subject_input.clone();
window.open_modal(cx, move |this, _window, cx| {
let subject = subject_input.read(cx).value();
this.title("Change subject")
.show_close(true)
.confirm()
.child(
v_flex()
.gap_2()
.child(
v_flex()
.gap_1p5()
.child(
div()
.text_sm()
.text_color(cx.theme().text_muted)
.child(SharedString::from("Subject:")),
)
.child(TextInput::new(&subject_input).small()),
)
.child(
div()
.italic()
.text_xs()
.text_color(cx.theme().text_placeholder)
.child(SharedString::from(
"Subject will be updated when you send a new message.",
)),
),
)
.on_ok(move |_ev, window, cx| {
window
.dispatch_action(Box::new(Command::ChangeSubject(subject.to_string())), cx);
true
})
});
}
fn open_relays(&mut self, public_key: &PublicKey, window: &mut Window, cx: &mut Context<Self>) { fn open_relays(&mut self, public_key: &PublicKey, window: &mut Window, cx: &mut Context<Self>) {
let profile = self.profile(public_key, cx); let profile = self.profile(public_key, cx);

View File

@@ -27,9 +27,9 @@ use crate::dialogs::{accounts, settings};
use crate::panels::{backup, contact_list, greeter, messaging_relays, profile, relay_list}; use crate::panels::{backup, contact_list, greeter, messaging_relays, profile, relay_list};
use crate::sidebar; 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. \ 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."; 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 \ const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \
all your encrypted messages before. This action cannot be undone."; all your encrypted messages before. This action cannot be undone.";
@@ -37,6 +37,7 @@ pub fn init(window: &mut Window, cx: &mut App) -> Entity<Workspace> {
cx.new(|cx| Workspace::new(window, cx)) cx.new(|cx| Workspace::new(window, cx))
} }
struct SignerNotifcation;
struct RelayNotifcation; struct RelayNotifcation;
#[derive(Action, Clone, PartialEq, Eq, Deserialize)] #[derive(Action, Clone, PartialEq, Eq, Deserialize)]
@@ -107,21 +108,37 @@ impl Workspace {
// Subscribe to the signer events // Subscribe to the signer events
cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| { cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| {
match event { 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);
}
StateEvent::Connecting => { StateEvent::Connecting => {
let note = Notification::new() let note = Notification::new()
.id::<RelayNotifcation>() .id::<RelayNotifcation>()
.message("Connecting to the bootstrap relay...") .message("Connecting to the bootstrap relays...")
.with_kind(NotificationKind::Info) .with_kind(NotificationKind::Info);
.icon(IconName::Relay);
window.push_notification(note, cx); window.push_notification(note, cx);
} }
StateEvent::Connected => { StateEvent::Connected => {
let note = Notification::new() let note = Notification::new()
.id::<RelayNotifcation>() .id::<RelayNotifcation>()
.message("Connected to the bootstrap relay") .message("Connected to the bootstrap relays")
.with_kind(NotificationKind::Success) .with_kind(NotificationKind::Success);
.icon(IconName::Relay);
window.push_notification(note, cx);
}
StateEvent::FetchingRelayList => {
let note = Notification::new()
.id::<RelayNotifcation>()
.message("Getting relay list...")
.with_kind(NotificationKind::Info);
window.push_notification(note, cx); window.push_notification(note, cx);
} }
@@ -136,6 +153,8 @@ impl Workspace {
this.set_center_layout(window, cx); this.set_center_layout(window, cx);
this.set_relay_connected(false, cx); this.set_relay_connected(false, cx);
this.set_inbox_connected(false, cx); this.set_inbox_connected(false, cx);
// Clear the signer notification
window.clear_notification::<SignerNotifcation>(cx);
} }
_ => {} _ => {}
}; };
@@ -728,28 +747,49 @@ impl Workspace {
}) })
.when(inbox_connected, |this| this.indicator()) .when(inbox_connected, |this| this.indicator())
.dropdown_menu(move |this, _window, cx| { .dropdown_menu(move |this, _window, cx| {
let chat = ChatRegistry::global(cx);
let persons = PersonRegistry::global(cx); let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&public_key, cx); let profile = persons.read(cx).get(&public_key, cx);
let urls: Vec<SharedString> = profile let urls: Vec<(SharedString, SharedString)> = profile
.messaging_relays() .messaging_relays()
.iter() .iter()
.map(|url| SharedString::from(url.to_string())) .map(|url| {
(
SharedString::from(url.to_string()),
chat.read(cx).count_messages(url).to_string().into(),
)
})
.collect(); .collect();
// Header // Header
let menu = this.min_w(px(260.)).label("Messaging Relays"); let menu = this.min_w(px(260.)).label("Messaging Relays");
// Content // Content
let menu = urls.into_iter().fold(menu, |this, url| { let menu = urls.into_iter().fold(menu, |this, (url, count)| {
this.item(PopupMenuItem::element(move |_window, _cx| { this.item(PopupMenuItem::element(move |_window, cx| {
h_flex() h_flex()
.px_1() .px_1()
.w_full() .w_full()
.gap_2()
.text_sm() .text_sm()
.child(div().size_1p5().rounded_full().bg(gpui::green())) .justify_between()
.child(url.clone()) .child(
h_flex()
.gap_2()
.child(
div()
.size_1p5()
.rounded_full()
.bg(cx.theme().icon_accent),
)
.child(url.clone()),
)
.child(
div()
.text_xs()
.text_color(cx.theme().text_muted)
.child(count.clone()),
)
})) }))
}); });

View File

@@ -6,11 +6,13 @@ use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow}; use anyhow::{Context as AnyhowContext, Error, anyhow};
use gpui::{ use gpui::{
App, AppContext, Context, Entity, EventEmitter, Global, IntoElement, ParentElement, App, AppContext, Context, Entity, EventEmitter, Global, IntoElement, ParentElement,
SharedString, Styled, Task, Window, div, relative, SharedString, Styled, Subscription, Task, Window, div, relative,
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::PersonRegistry; use person::PersonRegistry;
use state::{Announcement, DEVICE_GIFTWRAP, DeviceState, NostrRegistry, TIMEOUT, app_name}; use state::{
Announcement, DEVICE_GIFTWRAP, DeviceState, NostrRegistry, StateEvent, TIMEOUT, app_name,
};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariants}; use ui::button::{Button, ButtonVariants};
@@ -48,6 +50,9 @@ pub struct DeviceRegistry {
/// Async tasks /// Async tasks
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
/// Event subscription
_subscription: Option<Subscription>,
} }
impl EventEmitter<DeviceEvent> for DeviceRegistry {} impl EventEmitter<DeviceEvent> for DeviceRegistry {}
@@ -65,16 +70,31 @@ impl DeviceRegistry {
/// Create a new device registry instance /// Create a new device registry instance
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let nostr = NostrRegistry::global(cx);
let state = DeviceState::default(); let state = DeviceState::default();
let subscription = Some(cx.subscribe_in(
&nostr,
window,
|this, _state, event, _window, cx| match event {
StateEvent::SignerSet => {
this.reset(cx);
}
StateEvent::RelayConnected => {
this.get_announcement(cx);
}
_ => {}
},
));
cx.defer_in(window, |this, window, cx| { cx.defer_in(window, |this, window, cx| {
this.handle_notifications(window, cx); this.handle_notifications(window, cx);
this.get_announcement(cx);
}); });
Self { Self {
state, state,
tasks: vec![], tasks: vec![],
_subscription: subscription,
} }
} }
@@ -254,9 +274,6 @@ impl DeviceRegistry {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
// Reset state before fetching announcement
self.reset(cx);
let task: Task<Result<Event, Error>> = cx.background_spawn(async move { let task: Task<Result<Event, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?; let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
@@ -358,7 +375,6 @@ impl DeviceRegistry {
if keys.public_key() != device_pubkey { if keys.public_key() != device_pubkey {
return Err(anyhow!("Key mismatch")); return Err(anyhow!("Key mismatch"));
}; };
Ok(keys) Ok(keys)
} else { } else {
Err(anyhow!("Key not found")) Err(anyhow!("Key not found"))

View File

@@ -17,7 +17,7 @@ use state::NostrRegistry;
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::button::{Button, ButtonVariants}; use ui::button::{Button, ButtonVariants};
use ui::notification::Notification; use ui::notification::Notification;
use ui::{Disableable, IconName, Sizable, WindowExtension, v_flex}; use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, v_flex};
const AUTH_MESSAGE: &str = const AUTH_MESSAGE: &str =
"Approve the authentication request to allow Coop to continue sending or receiving events."; "Approve the authentication request to allow Coop to continue sending or receiving events.";
@@ -344,8 +344,9 @@ impl RelayAuth {
.px_1p5() .px_1p5()
.rounded_sm() .rounded_sm()
.text_xs() .text_xs()
.font_semibold()
.bg(cx.theme().elevated_surface_background) .bg(cx.theme().elevated_surface_background)
.text_color(cx.theme().text_accent) .text_color(cx.theme().text)
.child(url.clone()), .child(url.clone()),
) )
.into_any_element() .into_any_element()

View File

@@ -44,10 +44,14 @@ impl Global for GlobalNostrRegistry {}
/// Signer event. /// Signer event.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StateEvent { pub enum StateEvent {
/// Creating the signer
Creating,
/// Connecting to the bootstrapping relay /// Connecting to the bootstrapping relay
Connecting, Connecting,
/// Connected to the bootstrapping relay /// Connected to the bootstrapping relay
Connected, Connected,
/// Fetching the relay list
FetchingRelayList,
/// User has not set up NIP-65 relays /// User has not set up NIP-65 relays
RelayNotConfigured, RelayNotConfigured,
/// Connected to NIP-65 relays /// Connected to NIP-65 relays
@@ -58,6 +62,15 @@ pub enum StateEvent {
Error(SharedString), Error(SharedString),
} }
impl StateEvent {
pub fn error<T>(error: T) -> Self
where
T: Into<SharedString>,
{
Self::Error(error.into())
}
}
/// Nostr Registry /// Nostr Registry
#[derive(Debug)] #[derive(Debug)]
pub struct NostrRegistry { pub struct NostrRegistry {
@@ -114,7 +127,7 @@ impl NostrRegistry {
.gossip(gossip) .gossip(gossip)
.automatic_authentication(false) .automatic_authentication(false)
.verify_subscriptions(false) .verify_subscriptions(false)
.connect_timeout(Duration::from_secs(TIMEOUT)) .connect_timeout(Duration::from_secs(10))
.sleep_when_idle(SleepWhenIdle::Enabled { .sleep_when_idle(SleepWhenIdle::Enabled {
timeout: Duration::from_secs(600), timeout: Duration::from_secs(600),
}); });
@@ -204,7 +217,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -269,7 +282,7 @@ impl NostrRegistry {
}, },
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -289,6 +302,9 @@ impl NostrRegistry {
// Create a write credential task // Create a write credential task
let write_credential = cx.write_credentials(&username, &username, &secret); let write_credential = cx.write_credentials(&username, &username, &secret);
// Emit creating event
cx.emit(StateEvent::Creating);
// Run async tasks in background // Run async tasks in background
let task: Task<Result<(), Error>> = cx.background_spawn(async move { let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = async_keys.into_nostr_signer(); let signer = async_keys.into_nostr_signer();
@@ -301,7 +317,7 @@ impl NostrRegistry {
client client
.send_event(&event) .send_event(&event)
.to(BOOTSTRAP_RELAYS) .to(BOOTSTRAP_RELAYS)
.ok_timeout(Duration::from_secs(TIMEOUT)) .ack_policy(AckPolicy::none())
.await?; .await?;
// Construct the default metadata // Construct the default metadata
@@ -355,7 +371,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -453,7 +469,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -500,7 +516,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -545,7 +561,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -553,7 +569,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -561,9 +577,72 @@ impl NostrRegistry {
})); }));
} }
/// Ensure the relay list is fetched for the given public key
pub fn ensure_relay_list(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) { pub fn ensure_relay_list(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
let task = self.get_event(public_key, Kind::RelayList, cx); let task = self.get_event(public_key, Kind::RelayList, cx);
// Emit a fetching event before starting the task
cx.emit(StateEvent::FetchingRelayList);
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(event) => {
this.update(cx, |this, cx| {
this.ensure_connection(&event, cx);
})
.ok();
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayNotConfigured);
cx.emit(StateEvent::error(e.to_string()));
})
.ok();
}
};
}));
}
/// Ensure that the user is connected to the relay specified in the NIP-65 event.
pub fn ensure_connection(&mut self, event: &Event, cx: &mut Context<Self>) {
let client = self.client();
// Extract the relay list from the event
let relays: Vec<(RelayUrl, Option<RelayMetadata>)> = nip65::extract_relay_list(event)
.map(|(url, metadata)| (url.to_owned(), metadata.to_owned()))
.collect();
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
for (url, metadata) in relays.into_iter() {
match metadata {
Some(RelayMetadata::Read) => {
client
.add_relay(url)
.capabilities(RelayCapabilities::READ)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
Some(RelayMetadata::Write) => {
client
.add_relay(url)
.capabilities(RelayCapabilities::WRITE)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
None => {
client
.add_relay(url)
.capabilities(RelayCapabilities::NONE)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
}
}
Ok(())
});
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok(_) => { Ok(_) => {
@@ -575,7 +654,7 @@ impl NostrRegistry {
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayNotConfigured); cx.emit(StateEvent::RelayNotConfigured);
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }

View File

@@ -14,7 +14,7 @@ use theme::{ActiveTheme, Anchor};
use crate::animation::cubic_bezier; use crate::animation::cubic_bezier;
use crate::button::{Button, ButtonVariants as _}; use crate::button::{Button, ButtonVariants as _};
use crate::{Icon, IconName, Sizable as _, StyledExt, h_flex, v_flex}; use crate::{Icon, IconName, Sizable as _, Size, StyledExt, h_flex, v_flex};
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub enum NotificationKind { pub enum NotificationKind {
@@ -28,12 +28,18 @@ pub enum NotificationKind {
impl NotificationKind { impl NotificationKind {
fn icon(&self, cx: &App) -> Icon { fn icon(&self, cx: &App) -> Icon {
match self { match self {
Self::Info => Icon::new(IconName::Info).text_color(cx.theme().icon), Self::Info => Icon::new(IconName::Info)
Self::Success => Icon::new(IconName::CheckCircle).text_color(cx.theme().icon_accent), .with_size(Size::Medium)
Self::Warning => Icon::new(IconName::Warning).text_color(cx.theme().text_warning), .text_color(cx.theme().icon),
Self::Error => { Self::Success => Icon::new(IconName::CheckCircle)
Icon::new(IconName::CloseCircle).text_color(cx.theme().danger_foreground) .with_size(Size::Medium)
} .text_color(cx.theme().icon_accent),
Self::Warning => Icon::new(IconName::Warning)
.with_size(Size::Medium)
.text_color(cx.theme().text_warning),
Self::Error => Icon::new(IconName::CloseCircle)
.with_size(Size::Medium)
.text_color(cx.theme().danger_foreground),
} }
} }
} }
@@ -284,9 +290,6 @@ impl Styled for Notification {
} }
impl Render for Notification { impl Render for Notification {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let closing = self.closing;
let placement = cx.theme().notification.placement;
let content = self let content = self
.content_builder .content_builder
.clone() .clone()
@@ -312,6 +315,11 @@ impl Render for Notification {
_ => cx.theme().text, _ => cx.theme().text,
}; };
let closing = self.closing;
let has_title = self.title.is_some();
let only_message = !has_title && content.is_none() && action.is_none();
let placement = cx.theme().notification.placement;
h_flex() h_flex()
.id("notification") .id("notification")
.group("") .group("")
@@ -328,23 +336,38 @@ impl Render for Notification {
.gap_2() .gap_2()
.justify_start() .justify_start()
.items_start() .items_start()
.when(only_message, |this| this.items_center())
.refine_style(&self.style) .refine_style(&self.style)
.when_some(icon, |this, icon| { .when_some(icon, |this, icon| {
this.child(div().flex_shrink_0().child(icon)) this.child(div().flex_shrink_0().size_5().child(icon))
}) })
.child( .child(
v_flex() v_flex()
.flex_1() .flex_1()
.gap_1()
.overflow_hidden() .overflow_hidden()
.when_some(self.title.clone(), |this, title| { .when_some(self.title.clone(), |this, title| {
this.child(div().text_sm().font_semibold().child(title)) this.child(h_flex().h_5().text_sm().font_semibold().child(title))
}) })
.when_some(self.message.clone(), |this, message| { .when_some(self.message.clone(), |this, message| {
this.child(div().text_sm().line_height(relative(1.25)).child(message)) this.child(
div()
.text_sm()
.when(has_title, |this| this.text_color(cx.theme().text_muted))
.line_height(relative(1.3))
.child(message),
)
}) })
.when_some(content, |this, content| this.child(content)) .when_some(content, |this, content| this.child(content))
.when_some(action, |this, action| { .when_some(action, |this, action| {
this.child(h_flex().flex_1().gap_1().justify_end().child(action)) this.child(
h_flex()
.w_full()
.flex_1()
.gap_1()
.justify_end()
.child(action),
)
}), }),
) )
.child( .child(