Compare commits
16 Commits
v1.0.0-bet
...
v1.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fef2ae1c6 | ||
|
|
c2a723faa8 | ||
|
|
6b872527ad | ||
|
|
d9b16aea9a | ||
|
|
8345def015 | ||
|
|
b0ba2549d7 | ||
|
|
c8034642c5 | ||
|
|
8205c69e19 | ||
|
|
d36364d60d | ||
|
|
99363475e0 | ||
|
|
a52e1877fe | ||
|
|
b41de00c95 | ||
|
|
94cbb4aa0e | ||
|
|
40e7ca368b | ||
|
|
b91697defc | ||
|
|
1d57a2deab |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -21,3 +21,6 @@ dist/
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
# Added by goreleaser init:
|
# Added by goreleaser init:
|
||||||
.intentionally-empty-file.o
|
.intentionally-empty-file.o
|
||||||
|
|
||||||
|
.cargo/
|
||||||
|
vendor/
|
||||||
|
|||||||
1565
Cargo.lock
generated
1565
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -4,8 +4,8 @@ members = ["crates/*"]
|
|||||||
default-members = ["crates/coop"]
|
default-members = ["crates/coop"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "1.0.0-beta1"
|
version = "1.0.0-beta3"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
@@ -20,10 +20,9 @@ reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
|||||||
|
|
||||||
# Nostr
|
# Nostr
|
||||||
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
|
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr-memory = { git = "https://github.com/rust-nostr/nostr" }
|
|
||||||
nostr-connect = { 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-blossom = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr-gossip-sqlite = { 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-sdk = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ] }
|
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ] }
|
||||||
|
|
||||||
@@ -43,6 +42,7 @@ smallvec = "1.14.0"
|
|||||||
smol = "2"
|
smol = "2"
|
||||||
tracing = "0.1.40"
|
tracing = "0.1.40"
|
||||||
webbrowser = "1.0.4"
|
webbrowser = "1.0.4"
|
||||||
|
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
strip = true
|
strip = true
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
use std::cmp::Reverse;
|
use std::cmp::Reverse;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||||
use common::EventUtils;
|
use common::EventExt;
|
||||||
|
use device::{DeviceEvent, DeviceRegistry};
|
||||||
use fuzzy_matcher::FuzzyMatcher;
|
use fuzzy_matcher::FuzzyMatcher;
|
||||||
use fuzzy_matcher::skim::SkimMatcherV2;
|
use fuzzy_matcher::skim::SkimMatcherV2;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
@@ -15,7 +16,8 @@ use gpui::{
|
|||||||
};
|
};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP};
|
use smol::lock::RwLock;
|
||||||
|
use state::{CoopSigner, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP};
|
||||||
|
|
||||||
mod message;
|
mod message;
|
||||||
mod room;
|
mod room;
|
||||||
@@ -40,8 +42,6 @@ pub enum ChatEvent {
|
|||||||
CloseRoom(u64),
|
CloseRoom(u64),
|
||||||
/// An event to notify UI about a new chat request
|
/// An event to notify UI about a new chat request
|
||||||
Ping,
|
Ping,
|
||||||
/// An event to notify UI that the chat registry has subscribed to messaging relays
|
|
||||||
Subscribed,
|
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
Error(SharedString),
|
Error(SharedString),
|
||||||
}
|
}
|
||||||
@@ -54,15 +54,47 @@ enum Signal {
|
|||||||
/// Eose received from relay pool
|
/// Eose received from relay pool
|
||||||
Eose,
|
Eose,
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
Error(SharedString),
|
Error(FailedMessage),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Signal {
|
||||||
|
pub fn message(gift_wrap: EventId, rumor: UnsignedEvent) -> Self {
|
||||||
|
Self::Message(NewMessage::new(gift_wrap, rumor))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eose() -> Self {
|
||||||
|
Self::Eose
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn error<T>(event: &Event, reason: T) -> Self
|
||||||
|
where
|
||||||
|
T: Into<SharedString>,
|
||||||
|
{
|
||||||
|
Self::Error(FailedMessage::new(event, reason))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Dekey = bool;
|
||||||
|
type GiftWrapId = EventId;
|
||||||
|
|
||||||
/// Chat Registry
|
/// Chat Registry
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ChatRegistry {
|
pub struct ChatRegistry {
|
||||||
/// Collection of all chat rooms
|
/// Whether the chat registry is currently initializing.
|
||||||
|
pub initializing: bool,
|
||||||
|
|
||||||
|
/// Chat rooms
|
||||||
rooms: Vec<Entity<Room>>,
|
rooms: Vec<Entity<Room>>,
|
||||||
|
|
||||||
|
/// Events that failed to unwrap for any reason
|
||||||
|
trashes: Entity<BTreeSet<FailedMessage>>,
|
||||||
|
|
||||||
|
/// Tracking events seen on which relays in the current session
|
||||||
|
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)>>>,
|
||||||
|
|
||||||
/// Tracking the status of unwrapping gift wrap events.
|
/// Tracking the status of unwrapping gift wrap events.
|
||||||
tracking_flag: Arc<AtomicBool>,
|
tracking_flag: Arc<AtomicBool>,
|
||||||
|
|
||||||
@@ -76,7 +108,7 @@ pub struct ChatRegistry {
|
|||||||
tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
|
tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
|
||||||
|
|
||||||
/// Subscriptions
|
/// Subscriptions
|
||||||
_subscriptions: SmallVec<[Subscription; 1]>,
|
_subscriptions: SmallVec<[Subscription; 2]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventEmitter<ChatEvent> for ChatRegistry {}
|
impl EventEmitter<ChatEvent> for ChatRegistry {}
|
||||||
@@ -95,18 +127,49 @@ impl ChatRegistry {
|
|||||||
/// Create a new chat registry instance
|
/// Create a new chat 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 nostr = NostrRegistry::global(cx);
|
||||||
|
let device = DeviceRegistry::global(cx);
|
||||||
|
|
||||||
let (tx, rx) = flume::unbounded::<Signal>();
|
let (tx, rx) = flume::unbounded::<Signal>();
|
||||||
let mut subscriptions = smallvec![];
|
let mut subscriptions = smallvec![];
|
||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// Subscribe to the signer event
|
// Subscribe to the signer event
|
||||||
cx.subscribe(&nostr, |this, _state, event, cx| {
|
cx.subscribe_in(&nostr, window, |this, state, event, window, cx| {
|
||||||
if let StateEvent::SignerSet = event {
|
if event == &StateEvent::SignerSet {
|
||||||
this.reset(cx);
|
this.reset(cx);
|
||||||
this.get_rooms(cx);
|
|
||||||
this.get_contact_list(cx);
|
this.get_contact_list(cx);
|
||||||
this.get_messages(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();
|
||||||
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -118,7 +181,11 @@ impl ChatRegistry {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
|
initializing: true,
|
||||||
rooms: vec![],
|
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_flag: Arc::new(AtomicBool::new(false)),
|
||||||
signal_rx: rx,
|
signal_rx: rx,
|
||||||
signal_tx: tx,
|
signal_tx: tx,
|
||||||
@@ -133,6 +200,9 @@ 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 event_map = self.event_map.clone();
|
||||||
|
let trashes = self.trashes.downgrade();
|
||||||
|
|
||||||
let initialized_at = Timestamp::now();
|
let initialized_at = Timestamp::now();
|
||||||
let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP);
|
let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP);
|
||||||
@@ -143,59 +213,72 @@ impl ChatRegistry {
|
|||||||
let rx = self.signal_rx.clone();
|
let rx = self.signal_rx.clone();
|
||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
let device_signer = signer.get_encryption_signer().await;
|
|
||||||
let mut notifications = client.notifications();
|
let mut notifications = client.notifications();
|
||||||
let mut processed_events = HashSet::new();
|
let mut processed_events = HashSet::new();
|
||||||
|
|
||||||
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,
|
||||||
|
subscription_id,
|
||||||
|
} => {
|
||||||
|
// 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract the rumor from the gift wrap event
|
// Extract the rumor from the gift wrap event
|
||||||
match extract_rumor(&client, &device_signer, event.as_ref()).await {
|
match extract_rumor(&client, &signer, event.as_ref()).await {
|
||||||
Ok(rumor) => {
|
Ok(rumor) => {
|
||||||
if rumor.tags.is_empty() {
|
// Map the rumor id to the gift wrap event id for later lookup
|
||||||
let error: SharedString =
|
{
|
||||||
"Message doesn't belong to any rooms".into();
|
let mut event_map = event_map.write().await;
|
||||||
tx.send_async(Signal::Error(error)).await?;
|
let dekey = subscription_id.as_ref() == &sub_id1;
|
||||||
|
event_map.insert(rumor.id.unwrap(), (event.id, dekey));
|
||||||
}
|
}
|
||||||
|
|
||||||
match rumor.created_at >= initialized_at {
|
// Check if the rumor has a recipient
|
||||||
true => {
|
if rumor.tags.is_empty() {
|
||||||
let new_message = NewMessage::new(event.id, rumor);
|
let signal =
|
||||||
let signal = Signal::Message(new_message);
|
Signal::error(event.as_ref(), "Recipient is missing");
|
||||||
|
tx.send_async(signal).await?;
|
||||||
|
}
|
||||||
|
|
||||||
tx.send_async(signal).await?;
|
// Check if the rumor was created after the chat was initialized (for detecting new messages)
|
||||||
}
|
if rumor.created_at >= initialized_at {
|
||||||
false => {
|
let signal = Signal::message(event.id, rumor);
|
||||||
status.store(true, Ordering::Release);
|
tx.send_async(signal).await?;
|
||||||
}
|
} else {
|
||||||
|
// Mark the chat still processing new messages
|
||||||
|
status.store(true, Ordering::Release);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let error: SharedString =
|
let reason = format!("Failed to extract rumor: {e}");
|
||||||
format!("Failed to unwrap the gift wrap event: {e}").into();
|
let signal = Signal::error(event.as_ref(), reason);
|
||||||
tx.send_async(Signal::Error(error)).await?;
|
tx.send_async(signal).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RelayMessage::EndOfStoredEvents(id) => {
|
RelayMessage::EndOfStoredEvents(id) => {
|
||||||
if id.as_ref() == &sub_id1 || id.as_ref() == &sub_id2 {
|
if id.as_ref() == &sub_id1 || id.as_ref() == &sub_id2 {
|
||||||
tx.send_async(Signal::Eose).await?;
|
tx.send_async(Signal::eose()).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -218,9 +301,10 @@ impl ChatRegistry {
|
|||||||
this.get_rooms(cx);
|
this.get_rooms(cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Signal::Error(error) => {
|
Signal::Error(trash) => {
|
||||||
this.update(cx, |_this, cx| {
|
trashes.update(cx, |this, cx| {
|
||||||
cx.emit(ChatEvent::Error(error));
|
this.insert(trash);
|
||||||
|
cx.notify();
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -251,7 +335,7 @@ impl ChatRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get contact list from relays
|
/// Get contact list from relays
|
||||||
pub fn get_contact_list(&mut self, cx: &mut Context<Self>) {
|
fn get_contact_list(&mut self, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
@@ -281,15 +365,18 @@ impl ChatRegistry {
|
|||||||
self.tasks.push(task);
|
self.tasks.push(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get all messages for current user
|
/// Get all messages for the provided signer
|
||||||
pub fn get_messages(&mut self, cx: &mut Context<Self>) {
|
fn get_messages<T>(&mut self, signer: T, cx: &mut Context<Self>)
|
||||||
let task = self.subscribe(cx);
|
where
|
||||||
|
T: NostrSigner + 'static,
|
||||||
|
{
|
||||||
|
let task = self.subscribe_gift_wrap_events(signer, cx);
|
||||||
|
|
||||||
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(_) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
cx.emit(ChatEvent::Subscribed);
|
this.set_initializing(false, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -310,6 +397,7 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key().await?;
|
||||||
|
let id = SubscriptionId::new("inbox-relay");
|
||||||
|
|
||||||
// Construct filter for inbox relays
|
// Construct filter for inbox relays
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
@@ -320,6 +408,7 @@ impl ChatRegistry {
|
|||||||
// Stream events from user's write relays
|
// Stream events from user's write relays
|
||||||
let mut stream = client
|
let mut stream = client
|
||||||
.stream_events(filter)
|
.stream_events(filter)
|
||||||
|
.with_id(id)
|
||||||
.timeout(Duration::from_secs(TIMEOUT))
|
.timeout(Duration::from_secs(TIMEOUT))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -334,18 +423,20 @@ impl ChatRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Continuously get gift wrap events for the current user in their messaging relays
|
/// Continuously get gift wrap events for the signer
|
||||||
fn subscribe(&self, cx: &App) -> Task<Result<(), Error>> {
|
fn subscribe_gift_wrap_events<T>(&self, signer: T, cx: &App) -> Task<Result<(), Error>>
|
||||||
|
where
|
||||||
|
T: NostrSigner + 'static,
|
||||||
|
{
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
let urls = self.get_messaging_relays(cx);
|
let urls = self.get_messaging_relays(cx);
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let urls = urls.await?;
|
let urls = urls.await?;
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key().await?;
|
||||||
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
||||||
let id = SubscriptionId::new(USER_GIFTWRAP);
|
let id = SubscriptionId::new(format!("{}-msg", public_key.to_hex()));
|
||||||
|
|
||||||
// Ensure relay connections
|
// Ensure relay connections
|
||||||
for url in urls.iter() {
|
for url in urls.iter() {
|
||||||
@@ -369,6 +460,37 @@ impl ChatRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Refresh the chat registry, fetching messages and contact list from relays.
|
||||||
|
pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
|
self.reset(cx);
|
||||||
|
self.get_contact_list(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
|
/// Get the loading status of the chat registry
|
||||||
pub fn loading(&self) -> bool {
|
pub fn loading(&self) -> bool {
|
||||||
self.tracking_flag.load(Ordering::Acquire)
|
self.tracking_flag.load(Ordering::Acquire)
|
||||||
@@ -399,6 +521,51 @@ 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count the number of trash messages.
|
||||||
|
pub fn count_trash_messages(&self, cx: &App) -> usize {
|
||||||
|
self.trashes.read(cx).len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the trash messages entity.
|
||||||
|
pub fn trashes(&self) -> Entity<BTreeSet<FailedMessage>> {
|
||||||
|
self.trashes.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the relays that have seen a given rumor id.
|
||||||
|
pub fn rumor_seen_on(&self, id: &EventId) -> Option<HashSet<RelayUrl>> {
|
||||||
|
self.event_map
|
||||||
|
.read_blocking()
|
||||||
|
.get(id)
|
||||||
|
.map(|(id, _dekey)| self.seen_on(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the relays that have seen a given gift wrap id.
|
||||||
|
pub fn seen_on(&self, id: &EventId) -> HashSet<RelayUrl> {
|
||||||
|
self.seens
|
||||||
|
.read_blocking()
|
||||||
|
.get(id)
|
||||||
|
.cloned()
|
||||||
|
.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.
|
/// 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
|
||||||
@@ -476,7 +643,12 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
/// Reset the registry.
|
/// Reset the registry.
|
||||||
pub fn reset(&mut self, cx: &mut Context<Self>) {
|
pub fn reset(&mut self, cx: &mut Context<Self>) {
|
||||||
|
self.initializing = true;
|
||||||
self.rooms.clear();
|
self.rooms.clear();
|
||||||
|
self.trashes.update(cx, |this, cx| {
|
||||||
|
this.clear();
|
||||||
|
cx.notify();
|
||||||
|
});
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -570,10 +742,10 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
// Process each event and group by room hash
|
// Process each event and group by room hash
|
||||||
for raw in events.into_iter() {
|
for raw in events.into_iter() {
|
||||||
if let Ok(rumor) = UnsignedEvent::from_json(&raw.content) {
|
if let Ok(rumor) = UnsignedEvent::from_json(&raw.content)
|
||||||
if rumor.tags.public_keys().peekable().peek().is_some() {
|
&& rumor.tags.public_keys().peekable().peek().is_some()
|
||||||
grouped.entry(rumor.uniq_id()).or_default().push(rumor);
|
{
|
||||||
}
|
grouped.entry(rumor.uniq_id()).or_default().push(rumor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -619,12 +791,11 @@ impl ChatRegistry {
|
|||||||
match self.rooms.iter().find(|e| e.read(cx).id == message.room) {
|
match self.rooms.iter().find(|e| e.read(cx).id == message.room) {
|
||||||
Some(room) => {
|
Some(room) => {
|
||||||
room.update(cx, |this, cx| {
|
room.update(cx, |this, cx| {
|
||||||
if this.kind == RoomKind::Request {
|
if this.kind == RoomKind::Request
|
||||||
if let Some(public_key) = signer.public_key() {
|
&& let Some(public_key) = signer.public_key()
|
||||||
if message.rumor.pubkey == public_key {
|
&& message.rumor.pubkey == public_key
|
||||||
this.set_ongoing(cx);
|
{
|
||||||
}
|
this.set_ongoing(cx);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
this.push_message(message, cx);
|
this.push_message(message, cx);
|
||||||
});
|
});
|
||||||
@@ -652,16 +823,16 @@ impl ChatRegistry {
|
|||||||
/// Unwraps a gift-wrapped event and processes its contents.
|
/// Unwraps a gift-wrapped event and processes its contents.
|
||||||
async fn extract_rumor(
|
async fn extract_rumor(
|
||||||
client: &Client,
|
client: &Client,
|
||||||
device_signer: &Option<Arc<dyn NostrSigner>>,
|
signer: &Arc<CoopSigner>,
|
||||||
gift_wrap: &Event,
|
gift_wrap: &Event,
|
||||||
) -> Result<UnsignedEvent, Error> {
|
) -> Result<UnsignedEvent, Error> {
|
||||||
// Try to get cached rumor first
|
// Try to get cached rumor first
|
||||||
if let Ok(event) = get_rumor(client, gift_wrap.id).await {
|
if let Ok(rumor) = get_rumor(client, gift_wrap.id).await {
|
||||||
return Ok(event);
|
return Ok(rumor);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to unwrap with the available signer
|
// Try to unwrap with the available signer
|
||||||
let unwrapped = try_unwrap(client, device_signer, gift_wrap).await?;
|
let unwrapped = try_unwrap(signer, gift_wrap).await?;
|
||||||
let mut rumor = unwrapped.rumor;
|
let mut rumor = unwrapped.rumor;
|
||||||
|
|
||||||
// Generate event id for the rumor if it doesn't have one
|
// Generate event id for the rumor if it doesn't have one
|
||||||
@@ -676,30 +847,27 @@ async fn extract_rumor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Helper method to try unwrapping with different signers
|
/// Helper method to try unwrapping with different signers
|
||||||
async fn try_unwrap(
|
async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
|
||||||
client: &Client,
|
|
||||||
device_signer: &Option<Arc<dyn NostrSigner>>,
|
|
||||||
gift_wrap: &Event,
|
|
||||||
) -> Result<UnwrappedGift, Error> {
|
|
||||||
// Try with the device signer first
|
// Try with the device signer first
|
||||||
if let Some(signer) = device_signer {
|
if let Some(signer) = signer.get_encryption_signer().await {
|
||||||
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, signer).await {
|
log::info!("trying with encryption key");
|
||||||
|
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, &signer).await {
|
||||||
return Ok(unwrapped);
|
return Ok(unwrapped);
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
// Try with the user's signer
|
// Fallback to the user's signer
|
||||||
let user_signer = client.signer().context("Signer not found")?;
|
let user_signer = signer.get().await;
|
||||||
let unwrapped = try_unwrap_with(gift_wrap, user_signer).await?;
|
let unwrapped = try_unwrap_with(gift_wrap, &user_signer).await?;
|
||||||
|
|
||||||
Ok(unwrapped)
|
Ok(unwrapped)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attempts to unwrap a gift wrap event with a given signer.
|
/// Attempts to unwrap a gift wrap event with a given signer.
|
||||||
async fn try_unwrap_with(
|
async fn try_unwrap_with<T>(gift_wrap: &Event, signer: &T) -> Result<UnwrappedGift, Error>
|
||||||
gift_wrap: &Event,
|
where
|
||||||
signer: &Arc<dyn NostrSigner>,
|
T: NostrSigner + 'static,
|
||||||
) -> Result<UnwrappedGift, Error> {
|
{
|
||||||
// Get the sealed event
|
// Get the sealed event
|
||||||
let seal = signer
|
let seal = signer
|
||||||
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)
|
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
use common::{EventUtils, NostrParser};
|
use common::{EventExt, NostrParser};
|
||||||
|
use gpui::SharedString;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
/// New message.
|
/// New message.
|
||||||
@@ -24,6 +25,25 @@ impl NewMessage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Trash message.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct FailedMessage {
|
||||||
|
pub raw_event: SharedString,
|
||||||
|
pub reason: SharedString,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FailedMessage {
|
||||||
|
pub fn new<T>(event: &Event, reason: T) -> Self
|
||||||
|
where
|
||||||
|
T: Into<SharedString>,
|
||||||
|
{
|
||||||
|
Self {
|
||||||
|
raw_event: SharedString::from(event.as_json()),
|
||||||
|
reason: reason.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Message.
|
/// Message.
|
||||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||||
pub enum Message {
|
pub enum Message {
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ use std::cmp::Ordering;
|
|||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::Error;
|
use anyhow::{Error, anyhow};
|
||||||
use common::EventUtils;
|
use common::EventExt;
|
||||||
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
|
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
@@ -354,17 +354,7 @@ impl Room {
|
|||||||
pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> {
|
pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
let members = self.members();
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
let sender = signer.public_key();
|
|
||||||
|
|
||||||
// Get all members, excluding the sender
|
|
||||||
let members: Vec<PublicKey> = self
|
|
||||||
.members
|
|
||||||
.iter()
|
|
||||||
.filter(|public_key| Some(**public_key) != sender)
|
|
||||||
.copied()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let opts = SubscribeAutoCloseOptions::default()
|
let opts = SubscribeAutoCloseOptions::default()
|
||||||
@@ -515,45 +505,46 @@ impl Room {
|
|||||||
|
|
||||||
// Handle encryption signer requirements
|
// Handle encryption signer requirements
|
||||||
if signer_kind.encryption() {
|
if signer_kind.encryption() {
|
||||||
|
// Receiver didn't set up a decoupled encryption key
|
||||||
if announcement.is_none() {
|
if announcement.is_none() {
|
||||||
reports.push(SendReport::new(public_key).error(NO_DEKEY));
|
reports.push(SendReport::new(public_key).error(NO_DEKEY));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sender didn't set up a decoupled encryption key
|
||||||
if encryption_signer.is_none() {
|
if encryption_signer.is_none() {
|
||||||
reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY));
|
reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine receiver and signer
|
// Determine the signer to use
|
||||||
let (receiver, signer) = match signer_kind {
|
let signer = match signer_kind {
|
||||||
SignerKind::Auto => {
|
SignerKind::Auto => {
|
||||||
if let Some(announcement) = announcement {
|
if announcement.is_some()
|
||||||
if let Some(enc_signer) = encryption_signer.as_ref() {
|
&& let Some(encryption_signer) = encryption_signer.clone()
|
||||||
(announcement.public_key(), enc_signer.clone())
|
{
|
||||||
} else {
|
// Safe to unwrap due to earlier checks
|
||||||
(member.public_key(), user_signer.clone())
|
encryption_signer
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
(member.public_key(), user_signer.clone())
|
user_signer.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SignerKind::Encryption => {
|
SignerKind::Encryption => {
|
||||||
// Safe to unwrap due to earlier checks
|
// Safe to unwrap due to earlier checks
|
||||||
(
|
encryption_signer.as_ref().unwrap().clone()
|
||||||
announcement.unwrap().public_key(),
|
|
||||||
encryption_signer.as_ref().unwrap().clone(),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
SignerKind::User => (member.public_key(), user_signer.clone()),
|
SignerKind::User => user_signer.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
match send_gift_wrap(&client, &signer, &receiver, &rumor, public_key).await {
|
// Send the gift wrap event and collect the report
|
||||||
Ok((report, _)) => {
|
match send_gift_wrap(&client, &signer, &member, &rumor, signer_kind).await {
|
||||||
|
Ok(report) => {
|
||||||
reports.push(report);
|
reports.push(report);
|
||||||
sents += 1;
|
sents += 1;
|
||||||
}
|
}
|
||||||
Err(report) => {
|
Err(error) => {
|
||||||
|
let report = SendReport::new(public_key).error(error.to_string());
|
||||||
reports.push(report);
|
reports.push(report);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -562,11 +553,32 @@ impl Room {
|
|||||||
// Send backup to current user if needed
|
// Send backup to current user if needed
|
||||||
if backup && sents >= 1 {
|
if backup && sents >= 1 {
|
||||||
let public_key = sender.public_key();
|
let public_key = sender.public_key();
|
||||||
let signer = encryption_signer.as_ref().unwrap_or(&user_signer);
|
|
||||||
|
|
||||||
match send_gift_wrap(&client, signer, &public_key, &rumor, public_key).await {
|
// Determine the signer to use
|
||||||
Ok((report, _)) => reports.push(report),
|
let signer = match signer_kind {
|
||||||
Err(report) => reports.push(report),
|
SignerKind::Auto => {
|
||||||
|
if sender.announcement().is_some()
|
||||||
|
&& let Some(encryption_signer) = encryption_signer.clone()
|
||||||
|
{
|
||||||
|
// Safe to unwrap due to earlier checks
|
||||||
|
encryption_signer
|
||||||
|
} else {
|
||||||
|
user_signer.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SignerKind::Encryption => {
|
||||||
|
// Safe to unwrap due to earlier checks
|
||||||
|
encryption_signer.as_ref().unwrap().clone()
|
||||||
|
}
|
||||||
|
SignerKind::User => user_signer.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
match send_gift_wrap(&client, &signer, &sender, &rumor, signer_kind).await {
|
||||||
|
Ok(report) => reports.push(report),
|
||||||
|
Err(error) => {
|
||||||
|
let report = SendReport::new(public_key).error(error.to_string());
|
||||||
|
reports.push(report);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -579,30 +591,50 @@ impl Room {
|
|||||||
async fn send_gift_wrap<T>(
|
async fn send_gift_wrap<T>(
|
||||||
client: &Client,
|
client: &Client,
|
||||||
signer: &T,
|
signer: &T,
|
||||||
receiver: &PublicKey,
|
receiver: &Person,
|
||||||
rumor: &UnsignedEvent,
|
rumor: &UnsignedEvent,
|
||||||
public_key: PublicKey,
|
config: &SignerKind,
|
||||||
) -> Result<(SendReport, bool), SendReport>
|
) -> Result<SendReport, Error>
|
||||||
where
|
where
|
||||||
T: NostrSigner + 'static,
|
T: NostrSigner + 'static,
|
||||||
{
|
{
|
||||||
match EventBuilder::gift_wrap(signer, receiver, rumor.clone(), []).await {
|
let mut extra_tags = vec![];
|
||||||
Ok(event) => {
|
|
||||||
match client
|
// Determine the receiver public key based on the config
|
||||||
.send_event(&event)
|
let receiver = match config {
|
||||||
.to_nip17()
|
SignerKind::Auto => {
|
||||||
.ack_policy(AckPolicy::none())
|
if let Some(announcement) = receiver.announcement().as_ref() {
|
||||||
.await
|
extra_tags.push(Tag::public_key(receiver.public_key()));
|
||||||
{
|
announcement.public_key()
|
||||||
Ok(output) => Ok((
|
} else {
|
||||||
SendReport::new(public_key)
|
receiver.public_key()
|
||||||
.gift_wrap_id(event.id)
|
|
||||||
.output(output),
|
|
||||||
true,
|
|
||||||
)),
|
|
||||||
Err(e) => Err(SendReport::new(public_key).error(e.to_string())),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => Err(SendReport::new(public_key).error(e.to_string())),
|
SignerKind::Encryption => {
|
||||||
}
|
if let Some(announcement) = receiver.announcement().as_ref() {
|
||||||
|
extra_tags.push(Tag::public_key(receiver.public_key()));
|
||||||
|
announcement.public_key()
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!("User has no encryption announcement"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SignerKind::User => receiver.public_key(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Construct the gift wrap event
|
||||||
|
let event = EventBuilder::gift_wrap(signer, &receiver, rumor.clone(), extra_tags).await?;
|
||||||
|
|
||||||
|
// Send the gift wrap event and collect the report
|
||||||
|
let report = client
|
||||||
|
.send_event(&event)
|
||||||
|
.to_nip17()
|
||||||
|
.ack_policy(AckPolicy::none())
|
||||||
|
.await
|
||||||
|
.map(|output| {
|
||||||
|
SendReport::new(receiver)
|
||||||
|
.gift_wrap_id(event.id)
|
||||||
|
.output(output)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(report)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ 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),
|
||||||
|
Trace(EventId),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
pub use actions::*;
|
pub use actions::*;
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error};
|
||||||
use chat::{Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus};
|
use chat::{ChatRegistry, Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus};
|
||||||
use common::RenderedTimestamp;
|
use common::TimestampExt;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||||
@@ -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);
|
||||||
@@ -192,15 +201,12 @@ impl ChatPanel {
|
|||||||
let mut notifications = client.notifications();
|
let mut notifications = client.notifications();
|
||||||
|
|
||||||
while let Some(notification) = notifications.next().await {
|
while let Some(notification) = notifications.next().await {
|
||||||
if let ClientNotification::Message {
|
if let ClientNotification::Message { message, relay_url } = notification
|
||||||
message:
|
&& let RelayMessage::Ok {
|
||||||
RelayMessage::Ok {
|
event_id,
|
||||||
event_id,
|
status,
|
||||||
status,
|
message,
|
||||||
message,
|
} = *message
|
||||||
},
|
|
||||||
relay_url,
|
|
||||||
} = notification
|
|
||||||
{
|
{
|
||||||
let sent_ids = sent_ids.read().await;
|
let sent_ids = sent_ids.read().await;
|
||||||
|
|
||||||
@@ -247,11 +253,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 +268,8 @@ impl ChatPanel {
|
|||||||
this.get_messages(window, cx);
|
this.get_messages(window, cx);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}),
|
},
|
||||||
);
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,9 +376,13 @@ impl ChatPanel {
|
|||||||
/// Send message in the background and wait for the response
|
/// Send message in the background and wait for the response
|
||||||
fn send_and_wait(&mut self, rumor: UnsignedEvent, window: &mut Window, cx: &mut Context<Self>) {
|
fn send_and_wait(&mut self, rumor: UnsignedEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let sent_ids = self.sent_ids.clone();
|
let sent_ids = self.sent_ids.clone();
|
||||||
|
|
||||||
// This can't fail, because we already ensured that the ID is set
|
// This can't fail, because we already ensured that the ID is set
|
||||||
let id = rumor.id.unwrap();
|
let id = rumor.id.unwrap();
|
||||||
|
|
||||||
|
// Add empty reports
|
||||||
|
self.insert_reports(id, vec![], cx);
|
||||||
|
|
||||||
// Upgrade room reference
|
// Upgrade room reference
|
||||||
let Some(room) = self.room.upgrade() else {
|
let Some(room) = self.room.upgrade() else {
|
||||||
return;
|
return;
|
||||||
@@ -419,7 +431,7 @@ impl ChatPanel {
|
|||||||
/// Insert reports
|
/// Insert reports
|
||||||
fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) {
|
fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) {
|
||||||
self.reports_by_id.update(cx, |this, cx| {
|
self.reports_by_id.update(cx, |this, cx| {
|
||||||
this.insert(id, reports);
|
this.entry(id).or_default().extend(reports);
|
||||||
cx.notify();
|
cx.notify();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -454,19 +466,17 @@ impl ChatPanel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if a message is pending
|
|
||||||
fn sent_pending(&self, id: &EventId, cx: &App) -> bool {
|
|
||||||
self.reports_by_id
|
|
||||||
.read(cx)
|
|
||||||
.get(id)
|
|
||||||
.is_some_and(|reports| reports.iter().all(|r| r.pending()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if a message has any reports
|
/// Check if a message has any reports
|
||||||
fn has_reports(&self, id: &EventId, cx: &App) -> bool {
|
fn has_reports(&self, id: &EventId, cx: &App) -> bool {
|
||||||
self.reports_by_id.read(cx).get(id).is_some()
|
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
|
/// Get all sent reports for a message by its ID
|
||||||
fn sent_reports(&self, id: &EventId, cx: &App) -> Option<Vec<SendReport>> {
|
fn sent_reports(&self, id: &EventId, cx: &App) -> Option<Vec<SendReport>> {
|
||||||
self.reports_by_id.read(cx).get(id).cloned()
|
self.reports_by_id.read(cx).get(id).cloned()
|
||||||
@@ -475,10 +485,10 @@ impl ChatPanel {
|
|||||||
/// Get a message by its ID
|
/// Get a message by its ID
|
||||||
fn message(&self, id: &EventId) -> Option<&RenderedMessage> {
|
fn message(&self, id: &EventId) -> Option<&RenderedMessage> {
|
||||||
self.messages.iter().find_map(|msg| {
|
self.messages.iter().find_map(|msg| {
|
||||||
if let Message::User(rendered) = msg {
|
if let Message::User(rendered) = msg
|
||||||
if &rendered.id == id {
|
&& &rendered.id == id
|
||||||
return Some(rendered);
|
{
|
||||||
}
|
return Some(rendered);
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
})
|
})
|
||||||
@@ -645,9 +655,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);
|
||||||
}
|
}
|
||||||
@@ -657,47 +664,53 @@ impl ChatPanel {
|
|||||||
Command::Njump(public_key) => {
|
Command::Njump(public_key) => {
|
||||||
self.open_njump(public_key, cx);
|
self.open_njump(public_key, cx);
|
||||||
}
|
}
|
||||||
|
Command::Trace(id) => {
|
||||||
|
self.open_trace(id, window, cx);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_subject(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn open_trace(&mut self, id: &EventId, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let subject_input = self.subject_input.clone();
|
let chat = ChatRegistry::global(cx);
|
||||||
|
let seen_on = chat.read(cx).rumor_seen_on(id);
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, cx| {
|
window.open_modal(cx, move |this, _window, cx| {
|
||||||
let subject = subject_input.read(cx).value();
|
this.title("Seen on").show_close(true).child(
|
||||||
|
v_flex()
|
||||||
this.title("Change subject")
|
.gap_1()
|
||||||
.show_close(true)
|
.when_none(&seen_on, |this| {
|
||||||
.confirm()
|
this.child(
|
||||||
.child(
|
h_flex()
|
||||||
v_flex()
|
.h_10()
|
||||||
.gap_2()
|
.justify_center()
|
||||||
.child(
|
.text_sm()
|
||||||
v_flex()
|
.bg(cx.theme().elevated_surface_background)
|
||||||
.gap_1p5()
|
.rounded(cx.theme().radius)
|
||||||
.child(
|
.child("Message isn't traced yet"),
|
||||||
div()
|
|
||||||
.text_sm()
|
|
||||||
.text_color(cx.theme().text_muted)
|
|
||||||
.child(SharedString::from("Subject:")),
|
|
||||||
)
|
|
||||||
.child(TextInput::new(&subject_input).small()),
|
|
||||||
)
|
)
|
||||||
.child(
|
})
|
||||||
div()
|
.when_some(seen_on.as_ref(), |this, relays| {
|
||||||
.italic()
|
this.children({
|
||||||
.text_xs()
|
let mut items = vec![];
|
||||||
.text_color(cx.theme().text_placeholder)
|
|
||||||
.child(SharedString::from(
|
for url in relays.iter() {
|
||||||
"Subject will be updated when you send a new message.",
|
items.push(
|
||||||
)),
|
h_flex()
|
||||||
),
|
.h_7()
|
||||||
)
|
.px_2()
|
||||||
.on_ok(move |_ev, window, cx| {
|
.gap_2()
|
||||||
window
|
.bg(cx.theme().elevated_surface_background)
|
||||||
.dispatch_action(Box::new(Command::ChangeSubject(subject.to_string())), cx);
|
.rounded(cx.theme().radius)
|
||||||
true
|
.text_sm()
|
||||||
})
|
.child(div().size_1p5().rounded_full().bg(gpui::green()))
|
||||||
|
.child(SharedString::from(url.to_string())),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
items
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -835,9 +848,8 @@ impl ChatPanel {
|
|||||||
|
|
||||||
let replies = message.replies_to.as_slice();
|
let replies = message.replies_to.as_slice();
|
||||||
let has_replies = !replies.is_empty();
|
let has_replies = !replies.is_empty();
|
||||||
|
|
||||||
let sent_pending = self.sent_pending(&id, cx);
|
|
||||||
let has_reports = self.has_reports(&id, cx);
|
let has_reports = self.has_reports(&id, cx);
|
||||||
|
let encrypted_by_dekey = self.encrypted_by_dekey(&id, cx);
|
||||||
|
|
||||||
// Hide avatar setting
|
// Hide avatar setting
|
||||||
let hide_avatar = AppSettings::get_hide_avatar(cx);
|
let hide_avatar = AppSettings::get_hide_avatar(cx);
|
||||||
@@ -883,10 +895,18 @@ impl ChatPanel {
|
|||||||
.text_color(cx.theme().text)
|
.text_color(cx.theme().text)
|
||||||
.child(author.name()),
|
.child(author.name()),
|
||||||
)
|
)
|
||||||
.child(message.created_at.to_human_time())
|
.when(encrypted_by_dekey, |this| {
|
||||||
.when(sent_pending, |this| {
|
this.child(
|
||||||
this.child(SharedString::from("• Sending..."))
|
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| {
|
.when(has_reports, |this| {
|
||||||
this.child(deferred(self.render_sent_reports(&id, cx)))
|
this.child(deferred(self.render_sent_reports(&id, cx)))
|
||||||
}),
|
}),
|
||||||
@@ -970,20 +990,26 @@ impl ChatPanel {
|
|||||||
fn render_sent_reports(&self, id: &EventId, cx: &App) -> impl IntoElement {
|
fn render_sent_reports(&self, id: &EventId, cx: &App) -> impl IntoElement {
|
||||||
let reports = self.sent_reports(id, cx);
|
let reports = self.sent_reports(id, cx);
|
||||||
|
|
||||||
|
let pending = reports
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|reports| reports.is_empty() || reports.iter().any(|r| r.pending()));
|
||||||
|
|
||||||
let success = reports
|
let success = reports
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|reports| reports.iter().any(|r| r.success()));
|
.is_some_and(|reports| !reports.is_empty() && reports.iter().any(|r| r.success()));
|
||||||
|
|
||||||
let failed = reports
|
let failed = reports
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|reports| reports.iter().all(|r| r.failed()));
|
.is_some_and(|reports| !reports.is_empty() && reports.iter().all(|r| r.failed()));
|
||||||
|
|
||||||
let label = if success {
|
let label = if success {
|
||||||
SharedString::from("• Sent")
|
SharedString::from("• Sent")
|
||||||
} else if failed {
|
} else if failed {
|
||||||
SharedString::from("• Failed")
|
SharedString::from("• Error")
|
||||||
} else {
|
} else if pending {
|
||||||
SharedString::from("• Sending...")
|
SharedString::from("• Sending...")
|
||||||
|
} else {
|
||||||
|
SharedString::from("• Unknown")
|
||||||
};
|
};
|
||||||
|
|
||||||
div()
|
div()
|
||||||
@@ -991,22 +1017,24 @@ impl ChatPanel {
|
|||||||
.child(label)
|
.child(label)
|
||||||
.when(failed, |this| this.text_color(cx.theme().text_danger))
|
.when(failed, |this| this.text_color(cx.theme().text_danger))
|
||||||
.when_some(reports, |this, reports| {
|
.when_some(reports, |this, reports| {
|
||||||
this.on_click(move |_e, window, cx| {
|
this.when(!pending, |this| {
|
||||||
let reports = reports.clone();
|
this.on_click(move |_e, window, cx| {
|
||||||
|
let reports = reports.clone();
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, cx| {
|
window.open_modal(cx, move |this, _window, cx| {
|
||||||
this.title(SharedString::from("Sent Reports"))
|
this.title(SharedString::from("Sent Reports"))
|
||||||
.show_close(true)
|
.show_close(true)
|
||||||
.child(v_flex().gap_4().children({
|
.child(v_flex().gap_4().children({
|
||||||
let mut items = Vec::with_capacity(reports.len());
|
let mut items = Vec::with_capacity(reports.len());
|
||||||
|
|
||||||
for report in reports.iter() {
|
for report in reports.iter() {
|
||||||
items.push(Self::render_report(report, cx))
|
items.push(Self::render_report(report, cx))
|
||||||
}
|
}
|
||||||
|
|
||||||
items
|
items
|
||||||
}))
|
}))
|
||||||
});
|
});
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1168,15 +1196,10 @@ impl ChatPanel {
|
|||||||
.ghost()
|
.ghost()
|
||||||
.dropdown_menu({
|
.dropdown_menu({
|
||||||
let public_key = *public_key;
|
let public_key = *public_key;
|
||||||
let _id = *id;
|
let id = *id;
|
||||||
move |this, _window, _cx| {
|
move |this, _window, _cx| {
|
||||||
this.menu("Copy author", Box::new(Command::Copy(public_key)))
|
this.menu("Copy author", Box::new(Command::Copy(public_key)))
|
||||||
/*
|
.menu("Seen on", Box::new(Command::Trace(id)))
|
||||||
.menu(
|
|
||||||
"Trace",
|
|
||||||
Box::new(Command::Trace(id)),
|
|
||||||
)
|
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use anyhow::{Error, anyhow};
|
|
||||||
use chrono::{Local, TimeZone};
|
use chrono::{Local, TimeZone};
|
||||||
use gpui::{Image, ImageFormat, SharedString};
|
use gpui::{Image, ImageFormat, SharedString};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use qrcode::render::svg;
|
|
||||||
use qrcode::QrCode;
|
use qrcode::QrCode;
|
||||||
|
use qrcode::render::svg;
|
||||||
|
|
||||||
const NOW: &str = "now";
|
const NOW: &str = "now";
|
||||||
const SECONDS_IN_MINUTE: i64 = 60;
|
const SECONDS_IN_MINUTE: i64 = 60;
|
||||||
@@ -13,12 +12,12 @@ const MINUTES_IN_HOUR: i64 = 60;
|
|||||||
const HOURS_IN_DAY: i64 = 24;
|
const HOURS_IN_DAY: i64 = 24;
|
||||||
const DAYS_IN_MONTH: i64 = 30;
|
const DAYS_IN_MONTH: i64 = 30;
|
||||||
|
|
||||||
pub trait RenderedTimestamp {
|
pub trait TimestampExt {
|
||||||
fn to_human_time(&self) -> SharedString;
|
fn to_human_time(&self) -> SharedString;
|
||||||
fn to_ago(&self) -> SharedString;
|
fn to_ago(&self) -> SharedString;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderedTimestamp for Timestamp {
|
impl TimestampExt for Timestamp {
|
||||||
fn to_human_time(&self) -> SharedString {
|
fn to_human_time(&self) -> SharedString {
|
||||||
let input_time = match Local.timestamp_opt(self.as_secs() as i64, 0) {
|
let input_time = match Local.timestamp_opt(self.as_secs() as i64, 0) {
|
||||||
chrono::LocalResult::Single(time) => time,
|
chrono::LocalResult::Single(time) => time,
|
||||||
@@ -61,23 +60,11 @@ impl RenderedTimestamp for Timestamp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait TextUtils {
|
pub trait StringExt {
|
||||||
fn to_public_key(&self) -> Result<PublicKey, Error>;
|
|
||||||
fn to_qr(&self) -> Option<Arc<Image>>;
|
fn to_qr(&self) -> Option<Arc<Image>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsRef<str>> TextUtils for T {
|
impl<T: AsRef<str>> StringExt for T {
|
||||||
fn to_public_key(&self) -> Result<PublicKey, Error> {
|
|
||||||
let s = self.as_ref();
|
|
||||||
if s.starts_with("nprofile1") {
|
|
||||||
Ok(Nip19Profile::from_bech32(s)?.public_key)
|
|
||||||
} else if s.starts_with("npub1") {
|
|
||||||
Ok(PublicKey::parse(s)?)
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("Invalid public key"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_qr(&self) -> Option<Arc<Image>> {
|
fn to_qr(&self) -> Option<Arc<Image>> {
|
||||||
let s = self.as_ref();
|
let s = self.as_ref();
|
||||||
let code = QrCode::new(s).unwrap();
|
let code = QrCode::new(s).unwrap();
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ use std::hash::{DefaultHasher, Hash, Hasher};
|
|||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
pub trait EventUtils {
|
pub trait EventExt {
|
||||||
fn uniq_id(&self) -> u64;
|
fn uniq_id(&self) -> u64;
|
||||||
fn extract_public_keys(&self) -> Vec<PublicKey>;
|
fn extract_public_keys(&self) -> Vec<PublicKey>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventUtils for Event {
|
impl EventExt for Event {
|
||||||
fn uniq_id(&self) -> u64 {
|
fn uniq_id(&self) -> u64 {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
let mut pubkeys: Vec<PublicKey> = self.extract_public_keys();
|
let mut pubkeys: Vec<PublicKey> = self.extract_public_keys();
|
||||||
@@ -25,7 +25,7 @@ impl EventUtils for Event {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventUtils for UnsignedEvent {
|
impl EventExt for UnsignedEvent {
|
||||||
fn uniq_id(&self) -> u64 {
|
fn uniq_id(&self) -> u64 {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
let mut pubkeys: Vec<PublicKey> = vec![];
|
let mut pubkeys: Vec<PublicKey> = vec![];
|
||||||
|
|||||||
@@ -7,6 +7,13 @@ pub fn home_dir() -> &'static PathBuf {
|
|||||||
HOME_DIR.get_or_init(|| dirs::home_dir().expect("failed to determine home directory"))
|
HOME_DIR.get_or_init(|| dirs::home_dir().expect("failed to determine home directory"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the path to the user's download directory.
|
||||||
|
pub fn download_dir() -> &'static PathBuf {
|
||||||
|
static DOWNLOAD_DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||||
|
DOWNLOAD_DIR
|
||||||
|
.get_or_init(|| dirs::download_dir().expect("failed to determine download directory"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the path to the configuration directory used by Coop.
|
/// Returns the path to the configuration directory used by Coop.
|
||||||
pub fn config_dir() -> &'static PathBuf {
|
pub fn config_dir() -> &'static PathBuf {
|
||||||
static CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
|
static CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||||
@@ -56,9 +63,3 @@ pub fn support_dir() -> &'static PathBuf {
|
|||||||
config_dir().clone()
|
config_dir().clone()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the path to the `nostr` file.
|
|
||||||
pub fn nostr_file() -> &'static PathBuf {
|
|
||||||
static NOSTR_FILE: OnceLock<PathBuf> = OnceLock::new();
|
|
||||||
NOSTR_FILE.get_or_init(|| support_dir().join("nostr-db"))
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ product-name = "Coop"
|
|||||||
description = "Chat Freely, Stay Private on Nostr"
|
description = "Chat Freely, Stay Private on Nostr"
|
||||||
identifier = "su.reya.coop"
|
identifier = "su.reya.coop"
|
||||||
category = "SocialNetworking"
|
category = "SocialNetworking"
|
||||||
version = "1.0.0-beta1"
|
version = "1.0.0-beta3"
|
||||||
out-dir = "../../dist"
|
out-dir = "../../dist"
|
||||||
before-packaging-command = "cargo build --release"
|
before-packaging-command = "cargo build --release"
|
||||||
resources = ["Cargo.toml", "src"]
|
resources = ["Cargo.toml", "src"]
|
||||||
@@ -62,9 +62,9 @@ smol.workspace = true
|
|||||||
futures.workspace = true
|
futures.workspace = true
|
||||||
oneshot.workspace = true
|
oneshot.workspace = true
|
||||||
webbrowser.workspace = true
|
webbrowser.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
||||||
indexset = "0.12.3"
|
indexset = "0.12.3"
|
||||||
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
# Temporary workaround https://github.com/zed-industries/zed/issues/47168
|
# Temporary workaround https://github.com/zed-industries/zed/issues/47168
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ impl AccountSelector {
|
|||||||
|
|
||||||
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let task = nostr.read(cx).get_signer(&public_key, cx);
|
let task = nostr.read(cx).get_secret(public_key, cx);
|
||||||
|
|
||||||
// Mark the public key as being logged in
|
// Mark the public key as being logged in
|
||||||
self.set_logging_in(public_key, cx);
|
self.set_logging_in(public_key, cx);
|
||||||
@@ -117,7 +117,7 @@ impl AccountSelector {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
|
||||||
nostr.update(cx, |this, cx| {
|
nostr.update(cx, |this, cx| {
|
||||||
this.remove_signer(&public_key, cx);
|
this.remove_secret(&public_key, cx);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use common::TextUtils;
|
use common::StringExt;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,
|
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||||
|
|||||||
@@ -242,7 +242,6 @@ impl Render for ImportKey {
|
|||||||
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
v_flex()
|
v_flex()
|
||||||
.size_full()
|
.size_full()
|
||||||
.p_4()
|
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.text_sm()
|
.text_sm()
|
||||||
.child(
|
.child(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
pub mod accounts;
|
pub mod accounts;
|
||||||
|
pub mod connect;
|
||||||
|
pub mod import;
|
||||||
|
pub mod restore;
|
||||||
pub mod screening;
|
pub mod screening;
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
|
|
||||||
mod connect;
|
|
||||||
mod import;
|
|
||||||
|
|||||||
130
crates/coop/src/dialogs/restore.rs
Normal file
130
crates/coop/src/dialogs/restore.rs
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use anyhow::Error;
|
||||||
|
use device::DeviceRegistry;
|
||||||
|
use gpui::prelude::FluentBuilder;
|
||||||
|
use gpui::{
|
||||||
|
AppContext, Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||||
|
Subscription, Task, Window, div,
|
||||||
|
};
|
||||||
|
use nostr_connect::prelude::*;
|
||||||
|
use theme::ActiveTheme;
|
||||||
|
use ui::button::{Button, ButtonVariants};
|
||||||
|
use ui::input::{InputEvent, InputState, TextInput};
|
||||||
|
use ui::{WindowExtension, v_flex};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RestoreEncryption {
|
||||||
|
/// Secret key input
|
||||||
|
key_input: Entity<InputState>,
|
||||||
|
|
||||||
|
/// Error message
|
||||||
|
error: Entity<Option<SharedString>>,
|
||||||
|
|
||||||
|
/// Async tasks
|
||||||
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
|
|
||||||
|
/// Event subscription
|
||||||
|
_subscription: Option<Subscription>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RestoreEncryption {
|
||||||
|
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
|
let key_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||||
|
let error = cx.new(|_| None);
|
||||||
|
|
||||||
|
let subscription =
|
||||||
|
cx.subscribe_in(&key_input, window, |this, _input, event, window, cx| {
|
||||||
|
if let InputEvent::PressEnter { .. } = event {
|
||||||
|
this.restore(window, cx);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
|
key_input,
|
||||||
|
error,
|
||||||
|
tasks: vec![],
|
||||||
|
_subscription: Some(subscription),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
|
let device = DeviceRegistry::global(cx);
|
||||||
|
let content = self.key_input.read(cx).value();
|
||||||
|
|
||||||
|
if !content.is_empty() {
|
||||||
|
self.set_error("Secret Key cannot be empty.", cx);
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(secret) = SecretKey::parse(&content) else {
|
||||||
|
self.set_error("Secret Key is invalid.", cx);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
device.update(cx, |this, cx| {
|
||||||
|
this.set_announcement(Keys::new(secret), cx);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close the current modal
|
||||||
|
window.close_modal(cx);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_error<S>(&mut self, message: S, cx: &mut Context<Self>)
|
||||||
|
where
|
||||||
|
S: Into<SharedString>,
|
||||||
|
{
|
||||||
|
// Update error message
|
||||||
|
self.error.update(cx, |this, cx| {
|
||||||
|
*this = Some(message.into());
|
||||||
|
cx.notify();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Clear the error message after 3 secs
|
||||||
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
|
cx.background_executor().timer(Duration::from_secs(3)).await;
|
||||||
|
|
||||||
|
this.update(cx, |this, cx| {
|
||||||
|
this.error.update(cx, |this, cx| {
|
||||||
|
*this = None;
|
||||||
|
cx.notify();
|
||||||
|
});
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Render for RestoreEncryption {
|
||||||
|
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
|
v_flex()
|
||||||
|
.size_full()
|
||||||
|
.gap_2()
|
||||||
|
.text_sm()
|
||||||
|
.child(
|
||||||
|
v_flex()
|
||||||
|
.gap_1()
|
||||||
|
.text_sm()
|
||||||
|
.text_color(cx.theme().text_muted)
|
||||||
|
.child("Secret Key")
|
||||||
|
.child(TextInput::new(&self.key_input)),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
Button::new("restore")
|
||||||
|
.label("Restore")
|
||||||
|
.primary()
|
||||||
|
.on_click(cx.listener(move |this, _, window, cx| {
|
||||||
|
this.restore(window, cx);
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.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()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,21 +2,21 @@ use std::collections::HashMap;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error};
|
||||||
use common::RenderedTimestamp;
|
use common::TimestampExt;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
div, px, relative, uniform_list, App, AppContext, Context, Div, Entity, InteractiveElement,
|
App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, Render,
|
||||||
IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Task, Window,
|
SharedString, Styled, Subscription, Task, Window, div, px, relative, uniform_list,
|
||||||
};
|
};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::{shorten_pubkey, Person, PersonRegistry};
|
use person::{Person, PersonRegistry, shorten_pubkey};
|
||||||
use smallvec::{smallvec, SmallVec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{NostrAddress, NostrRegistry, BOOTSTRAP_RELAYS, TIMEOUT};
|
use state::{BOOTSTRAP_RELAYS, NostrAddress, NostrRegistry, TIMEOUT};
|
||||||
use theme::ActiveTheme;
|
use theme::ActiveTheme;
|
||||||
use ui::avatar::Avatar;
|
use ui::avatar::Avatar;
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::{Button, ButtonVariants};
|
||||||
use ui::indicator::Indicator;
|
use ui::indicator::Indicator;
|
||||||
use ui::{h_flex, v_flex, Icon, IconName, Sizable, StyledExt, WindowExtension};
|
use ui::{Icon, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
|
||||||
|
|
||||||
pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<Screening> {
|
pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<Screening> {
|
||||||
cx.new(|cx| Screening::new(public_key, window, cx))
|
cx.new(|cx| Screening::new(public_key, window, cx))
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use gpui::{
|
|||||||
Window, div, px,
|
Window, div, px,
|
||||||
};
|
};
|
||||||
use settings::{AppSettings, AuthMode};
|
use settings::{AppSettings, AuthMode};
|
||||||
use theme::{ActiveTheme, ThemeMode};
|
use theme::{ActiveTheme, Theme, ThemeMode};
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::{Button, ButtonVariants};
|
||||||
use ui::group_box::{GroupBox, GroupBoxVariants};
|
use ui::group_box::{GroupBox, GroupBoxVariants};
|
||||||
use ui::input::{InputState, TextInput};
|
use ui::input::{InputState, TextInput};
|
||||||
@@ -33,6 +33,7 @@ impl Preferences {
|
|||||||
Self { file_input }
|
Self { file_input }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Update the file server (blossom) URL
|
||||||
fn update_file_server(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn update_file_server(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let value = self.file_input.read(cx).value();
|
let value = self.file_input.read(cx).value();
|
||||||
|
|
||||||
@@ -45,6 +46,12 @@ impl Preferences {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set the theme mode (light or dark)
|
||||||
|
fn set_theme_mode(mode: ThemeMode, window: &mut Window, cx: &mut App) {
|
||||||
|
AppSettings::update_theme_mode(mode, cx);
|
||||||
|
Theme::change(mode, Some(window), cx);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Render for Preferences {
|
impl Render for Preferences {
|
||||||
@@ -160,23 +167,16 @@ impl Render for Preferences {
|
|||||||
.ghost_alt()
|
.ghost_alt()
|
||||||
.small()
|
.small()
|
||||||
.dropdown_menu(|this, _window, _cx| {
|
.dropdown_menu(|this, _window, _cx| {
|
||||||
this.min_w(px(256.))
|
this.item(PopupMenuItem::new("Light").on_click(
|
||||||
.item(PopupMenuItem::new("Light").on_click(
|
|_, window, cx| {
|
||||||
|_ev, _window, cx| {
|
Self::set_theme_mode(ThemeMode::Light, window, cx);
|
||||||
AppSettings::update_theme_mode(
|
},
|
||||||
ThemeMode::Light,
|
))
|
||||||
cx,
|
.item(
|
||||||
);
|
PopupMenuItem::new("Dark").on_click(|_, window, cx| {
|
||||||
},
|
Self::set_theme_mode(ThemeMode::Dark, window, cx);
|
||||||
))
|
}),
|
||||||
.item(PopupMenuItem::new("Dark").on_click(
|
)
|
||||||
|_ev, _window, cx| {
|
|
||||||
AppSettings::update_theme_mode(
|
|
||||||
ThemeMode::Dark,
|
|
||||||
cx,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ fn main() {
|
|||||||
cx.set_menus(vec![Menu {
|
cx.set_menus(vec![Menu {
|
||||||
name: "Coop".into(),
|
name: "Coop".into(),
|
||||||
items: vec![MenuItem::action("Quit", Quit)],
|
items: vec![MenuItem::action("Quit", Quit)],
|
||||||
|
disabled: false,
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
// Set up the window bounds
|
// Set up the window bounds
|
||||||
@@ -91,14 +92,14 @@ fn main() {
|
|||||||
// Initialize relay auth registry
|
// Initialize relay auth registry
|
||||||
relay_auth::init(window, cx);
|
relay_auth::init(window, cx);
|
||||||
|
|
||||||
// Initialize app registry
|
|
||||||
chat::init(window, cx);
|
|
||||||
|
|
||||||
// Initialize device signer
|
// Initialize device signer
|
||||||
//
|
//
|
||||||
// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
|
// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
|
||||||
device::init(window, cx);
|
device::init(window, cx);
|
||||||
|
|
||||||
|
// Initialize app registry
|
||||||
|
chat::init(window, cx);
|
||||||
|
|
||||||
// Initialize auto update
|
// Initialize auto update
|
||||||
auto_update::init(window, cx);
|
auto_update::init(window, cx);
|
||||||
|
|
||||||
|
|||||||
@@ -84,11 +84,6 @@ impl BackupPanel {
|
|||||||
fn copy_secret(&mut self, cx: &mut Context<Self>) {
|
fn copy_secret(&mut self, cx: &mut Context<Self>) {
|
||||||
let value = self.nsec_input.read(cx).value();
|
let value = self.nsec_input.read(cx).value();
|
||||||
let item = ClipboardItem::new_string(value.to_string());
|
let item = ClipboardItem::new_string(value.to_string());
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
cx.write_to_primary(item);
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
|
||||||
cx.write_to_clipboard(item);
|
cx.write_to_clipboard(item);
|
||||||
|
|
||||||
// Set the copied status to true
|
// Set the copied status to true
|
||||||
|
|||||||
@@ -4,3 +4,4 @@ pub mod greeter;
|
|||||||
pub mod messaging_relays;
|
pub mod messaging_relays;
|
||||||
pub mod profile;
|
pub mod profile;
|
||||||
pub mod relay_list;
|
pub mod relay_list;
|
||||||
|
pub mod trash;
|
||||||
|
|||||||
152
crates/coop/src/panels/trash.rs
Normal file
152
crates/coop/src/panels/trash.rs
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
use chat::ChatRegistry;
|
||||||
|
use gpui::{
|
||||||
|
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||||
|
Focusable, InteractiveElement, IntoElement, ListAlignment, ListState, ParentElement, Render,
|
||||||
|
SharedString, Styled, Window, div, list, px, relative,
|
||||||
|
};
|
||||||
|
use theme::ActiveTheme;
|
||||||
|
use ui::button::{Button, ButtonVariants};
|
||||||
|
use ui::dock::{Panel, PanelEvent};
|
||||||
|
use ui::scroll::Scrollbar;
|
||||||
|
use ui::{Icon, IconName, Sizable, h_flex, v_flex};
|
||||||
|
|
||||||
|
pub fn init(window: &mut Window, cx: &mut App) -> Entity<TrashPanel> {
|
||||||
|
cx.new(|cx| TrashPanel::new(window, cx))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TrashPanel {
|
||||||
|
name: SharedString,
|
||||||
|
focus_handle: FocusHandle,
|
||||||
|
|
||||||
|
/// List state for messages
|
||||||
|
list_state: ListState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TrashPanel {
|
||||||
|
fn new(_window: &mut Window, cx: &mut App) -> Self {
|
||||||
|
let chat = ChatRegistry::global(cx);
|
||||||
|
let count = chat.read(cx).count_trash_messages(cx);
|
||||||
|
let list_state = ListState::new(count, ListAlignment::Bottom, px(1024.));
|
||||||
|
|
||||||
|
Self {
|
||||||
|
name: "Trash".into(),
|
||||||
|
focus_handle: cx.focus_handle(),
|
||||||
|
list_state,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy(&self, ix: usize, cx: &App) {
|
||||||
|
let chat = ChatRegistry::global(cx);
|
||||||
|
let trashes = chat.read(cx).trashes();
|
||||||
|
|
||||||
|
if let Some(message) = trashes.read(cx).iter().nth(ix) {
|
||||||
|
let item = ClipboardItem::new_string(message.raw_event.to_string());
|
||||||
|
cx.write_to_clipboard(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_list_item(
|
||||||
|
&mut self,
|
||||||
|
ix: usize,
|
||||||
|
_window: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) -> AnyElement {
|
||||||
|
let chat = ChatRegistry::global(cx);
|
||||||
|
let trashes = chat.read(cx).trashes();
|
||||||
|
|
||||||
|
if let Some(message) = trashes.read(cx).iter().nth(ix) {
|
||||||
|
v_flex()
|
||||||
|
.id(ix)
|
||||||
|
.p_2()
|
||||||
|
.w_full()
|
||||||
|
.child(
|
||||||
|
v_flex()
|
||||||
|
.p_2()
|
||||||
|
.w_full()
|
||||||
|
.gap_1()
|
||||||
|
.rounded(cx.theme().radius_lg)
|
||||||
|
.bg(cx.theme().surface_background)
|
||||||
|
.text_sm()
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.text_color(cx.theme().text_danger)
|
||||||
|
.child(message.reason.clone()),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
h_flex()
|
||||||
|
.h_10()
|
||||||
|
.w_full()
|
||||||
|
.px_2()
|
||||||
|
.justify_between()
|
||||||
|
.bg(cx.theme().elevated_surface_background)
|
||||||
|
.border_1()
|
||||||
|
.border_color(cx.theme().border)
|
||||||
|
.rounded(cx.theme().radius)
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.truncate()
|
||||||
|
.text_ellipsis()
|
||||||
|
.text_xs()
|
||||||
|
.line_height(relative(1.))
|
||||||
|
.child(message.raw_event.clone()),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
Button::new(format!("copy-{ix}"))
|
||||||
|
.icon(IconName::Copy)
|
||||||
|
.ghost()
|
||||||
|
.small()
|
||||||
|
.on_click(cx.listener(move |this, _ev, _window, cx| {
|
||||||
|
this.copy(ix, cx);
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.into_any_element()
|
||||||
|
} else {
|
||||||
|
div().id(ix).into_any_element()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Panel for TrashPanel {
|
||||||
|
fn panel_id(&self) -> SharedString {
|
||||||
|
self.name.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self, _cx: &App) -> AnyElement {
|
||||||
|
h_flex()
|
||||||
|
.gap_1()
|
||||||
|
.text_sm()
|
||||||
|
.child(Icon::new(IconName::Warning).small())
|
||||||
|
.child("Errors")
|
||||||
|
.into_any_element()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventEmitter<PanelEvent> for TrashPanel {}
|
||||||
|
|
||||||
|
impl Focusable for TrashPanel {
|
||||||
|
fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
|
||||||
|
self.focus_handle.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Render for TrashPanel {
|
||||||
|
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
|
v_flex().size_full().relative().child(
|
||||||
|
v_flex()
|
||||||
|
.flex_1()
|
||||||
|
.relative()
|
||||||
|
.child(
|
||||||
|
list(
|
||||||
|
self.list_state.clone(),
|
||||||
|
cx.processor(move |this, ix, window, cx| {
|
||||||
|
this.render_list_item(ix, window, cx)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.size_full(),
|
||||||
|
)
|
||||||
|
.child(Scrollbar::vertical(&self.list_state)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -148,26 +148,27 @@ impl RenderOnce for RoomEntry {
|
|||||||
this.on_click(move |event, window, cx| {
|
this.on_click(move |event, window, cx| {
|
||||||
handler(event, window, cx);
|
handler(event, window, cx);
|
||||||
|
|
||||||
if let Some(public_key) = public_key {
|
if let Some(public_key) = public_key
|
||||||
if self.kind != Some(RoomKind::Ongoing) && screening {
|
&& self.kind != Some(RoomKind::Ongoing)
|
||||||
let screening = screening::init(public_key, window, cx);
|
&& screening
|
||||||
|
{
|
||||||
|
let screening = screening::init(public_key, window, cx);
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, _cx| {
|
window.open_modal(cx, move |this, _window, _cx| {
|
||||||
this.confirm()
|
this.confirm()
|
||||||
.child(screening.clone())
|
.child(screening.clone())
|
||||||
.button_props(
|
.button_props(
|
||||||
ModalButtonProps::default()
|
ModalButtonProps::default()
|
||||||
.cancel_text("Ignore")
|
.cancel_text("Ignore")
|
||||||
.ok_text("Response"),
|
.ok_text("Response"),
|
||||||
)
|
)
|
||||||
.on_cancel(move |_event, window, cx| {
|
.on_cancel(move |_event, window, cx| {
|
||||||
window.dispatch_action(Box::new(ClosePanel), cx);
|
window.dispatch_action(Box::new(ClosePanel), cx);
|
||||||
// Prevent closing the modal on click
|
// Prevent closing the modal on click
|
||||||
// modal will be automatically closed after closing panel
|
// modal will be automatically closed after closing panel
|
||||||
false
|
false
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error};
|
||||||
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
||||||
use common::{DebouncedDelay, RenderedTimestamp};
|
use common::{DebouncedDelay, TimestampExt};
|
||||||
use entry::RoomEntry;
|
use entry::RoomEntry;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
@@ -366,7 +366,11 @@ impl Sidebar {
|
|||||||
self.new_requests = false;
|
self.new_requests = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_list_items(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> {
|
fn render_list_items(
|
||||||
|
&self,
|
||||||
|
range: Range<usize>,
|
||||||
|
cx: &Context<Self>,
|
||||||
|
) -> Vec<impl IntoElement + use<>> {
|
||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
let rooms = chat.read(cx).rooms(self.filter.read(cx), cx);
|
let rooms = chat.read(cx).rooms(self.filter.read(cx), cx);
|
||||||
|
|
||||||
@@ -398,7 +402,11 @@ impl Sidebar {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Render the contact list
|
/// Render the contact list
|
||||||
fn render_results(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> {
|
fn render_results(
|
||||||
|
&self,
|
||||||
|
range: Range<usize>,
|
||||||
|
cx: &Context<Self>,
|
||||||
|
) -> Vec<impl IntoElement + use<>> {
|
||||||
let persons = PersonRegistry::global(cx);
|
let persons = PersonRegistry::global(cx);
|
||||||
|
|
||||||
// Get the contact list
|
// Get the contact list
|
||||||
@@ -431,7 +439,11 @@ impl Sidebar {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Render the contact list
|
/// Render the contact list
|
||||||
fn render_contacts(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> {
|
fn render_contacts(
|
||||||
|
&self,
|
||||||
|
range: Range<usize>,
|
||||||
|
cx: &Context<Self>,
|
||||||
|
) -> Vec<impl IntoElement + use<>> {
|
||||||
let persons = PersonRegistry::global(cx);
|
let persons = PersonRegistry::global(cx);
|
||||||
|
|
||||||
// Get the contact list
|
// Get the contact list
|
||||||
@@ -641,7 +653,7 @@ impl Render for Sidebar {
|
|||||||
uniform_list(
|
uniform_list(
|
||||||
"rooms",
|
"rooms",
|
||||||
results.len(),
|
results.len(),
|
||||||
cx.processor(|this, range, _window, cx| {
|
cx.processor(move |this, range, _window, cx| {
|
||||||
this.render_results(range, cx)
|
this.render_results(range, cx)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -668,7 +680,7 @@ impl Render for Sidebar {
|
|||||||
uniform_list(
|
uniform_list(
|
||||||
"contacts",
|
"contacts",
|
||||||
contacts.len(),
|
contacts.len(),
|
||||||
cx.processor(move |this, range, _window, cx| {
|
cx.processor(|this, range, _window, cx| {
|
||||||
this.render_contacts(range, cx)
|
this.render_contacts(range, cx)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
use std::cell::Cell;
|
|
||||||
use std::rc::Rc;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use ::settings::AppSettings;
|
use ::settings::AppSettings;
|
||||||
use chat::{ChatEvent, ChatRegistry};
|
use chat::{ChatEvent, ChatRegistry};
|
||||||
|
use common::download_dir;
|
||||||
use device::{DeviceEvent, DeviceRegistry};
|
use device::{DeviceEvent, DeviceRegistry};
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Action, App, AppContext, Axis, Context, Entity, InteractiveElement, IntoElement, ParentElement,
|
Action, App, AppContext, Axis, Context, Entity, InteractiveElement, IntoElement, ParentElement,
|
||||||
Render, SharedString, Styled, Subscription, Window, div, px,
|
Render, SharedString, StatefulInteractiveElement, Styled, Subscription, Window, div, px,
|
||||||
|
relative,
|
||||||
};
|
};
|
||||||
use person::PersonRegistry;
|
use nostr_sdk::prelude::*;
|
||||||
|
use person::{PersonRegistry, shorten_pubkey};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{NostrRegistry, StateEvent};
|
use state::{NostrRegistry, StateEvent};
|
||||||
@@ -21,15 +22,16 @@ use ui::button::{Button, ButtonVariants};
|
|||||||
use ui::dock::{ClosePanel, DockArea, DockItem, DockPlacement, PanelView};
|
use ui::dock::{ClosePanel, DockArea, DockItem, DockPlacement, PanelView};
|
||||||
use ui::menu::{DropdownMenu, PopupMenuItem};
|
use ui::menu::{DropdownMenu, PopupMenuItem};
|
||||||
use ui::notification::{Notification, NotificationKind};
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Disableable, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
use ui::{Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
||||||
|
|
||||||
|
use crate::dialogs::restore::RestoreEncryption;
|
||||||
use crate::dialogs::{accounts, settings};
|
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, trash};
|
||||||
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 +39,8 @@ 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 DeviceNotifcation;
|
||||||
|
struct SignerNotifcation;
|
||||||
struct RelayNotifcation;
|
struct RelayNotifcation;
|
||||||
|
|
||||||
#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
|
#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
|
||||||
@@ -45,9 +49,10 @@ enum Command {
|
|||||||
ToggleTheme,
|
ToggleTheme,
|
||||||
ToggleAccount,
|
ToggleAccount,
|
||||||
|
|
||||||
RefreshEncryption,
|
|
||||||
RefreshRelayList,
|
|
||||||
RefreshMessagingRelays,
|
RefreshMessagingRelays,
|
||||||
|
BackupEncryption,
|
||||||
|
ImportEncryption,
|
||||||
|
RefreshEncryption,
|
||||||
ResetEncryption,
|
ResetEncryption,
|
||||||
|
|
||||||
ShowRelayList,
|
ShowRelayList,
|
||||||
@@ -65,14 +70,8 @@ pub struct Workspace {
|
|||||||
/// App's Dock Area
|
/// App's Dock Area
|
||||||
dock: Entity<DockArea>,
|
dock: Entity<DockArea>,
|
||||||
|
|
||||||
/// Whether a user's relay list is connected
|
|
||||||
relay_connected: bool,
|
|
||||||
|
|
||||||
/// Whether the inbox is connected
|
|
||||||
inbox_connected: bool,
|
|
||||||
|
|
||||||
/// Event subscriptions
|
/// Event subscriptions
|
||||||
_subscriptions: SmallVec<[Subscription; 6]>,
|
_subscriptions: SmallVec<[Subscription; 5]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Workspace {
|
impl Workspace {
|
||||||
@@ -80,7 +79,6 @@ impl Workspace {
|
|||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
let device = DeviceRegistry::global(cx);
|
let device = DeviceRegistry::global(cx);
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let npubs = nostr.read(cx).npubs();
|
|
||||||
|
|
||||||
let titlebar = cx.new(|_| TitleBar::new());
|
let titlebar = cx.new(|_| TitleBar::new());
|
||||||
let dock = cx.new(|cx| DockArea::new(window, cx));
|
let dock = cx.new(|cx| DockArea::new(window, cx));
|
||||||
@@ -94,48 +92,43 @@ impl Workspace {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
subscriptions.push(
|
|
||||||
// Observe the npubs entity
|
|
||||||
cx.observe_in(&npubs, window, move |this, npubs, window, cx| {
|
|
||||||
if !npubs.read(cx).is_empty() {
|
|
||||||
this.account_selector(window, cx);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// 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);
|
window.push_notification(note, cx);
|
||||||
}
|
}
|
||||||
StateEvent::RelayNotConfigured => {
|
|
||||||
this.relay_notification(window, cx);
|
|
||||||
}
|
|
||||||
StateEvent::RelayConnected => {
|
|
||||||
window.clear_notification::<RelayNotifcation>(cx);
|
|
||||||
this.set_relay_connected(true, cx);
|
|
||||||
}
|
|
||||||
StateEvent::SignerSet => {
|
StateEvent::SignerSet => {
|
||||||
this.set_center_layout(window, cx);
|
this.set_center_layout(window, cx);
|
||||||
this.set_relay_connected(false, cx);
|
// Clear the signer notification
|
||||||
this.set_inbox_connected(false, cx);
|
window.clear_notification::<SignerNotifcation>(cx);
|
||||||
|
}
|
||||||
|
StateEvent::Show => {
|
||||||
|
this.account_selector(window, cx);
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
@@ -144,13 +137,37 @@ impl Workspace {
|
|||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// Observe all events emitted by the device registry
|
// Observe all events emitted by the device registry
|
||||||
cx.subscribe_in(&device, window, |_this, _device, ev, window, cx| {
|
cx.subscribe_in(&device, window, |_this, _device, event, window, cx| {
|
||||||
match ev {
|
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.";
|
||||||
|
|
||||||
|
let note = Notification::new()
|
||||||
|
.id::<DeviceNotifcation>()
|
||||||
|
.autohide(false)
|
||||||
|
.title("Wait for approval")
|
||||||
|
.message(MSG)
|
||||||
|
.with_kind(NotificationKind::Info);
|
||||||
|
|
||||||
|
window.push_notification(note, cx);
|
||||||
|
}
|
||||||
|
DeviceEvent::Creating => {
|
||||||
|
let note = Notification::new()
|
||||||
|
.id::<DeviceNotifcation>()
|
||||||
|
.autohide(false)
|
||||||
|
.message("Creating encryption key")
|
||||||
|
.with_kind(NotificationKind::Info);
|
||||||
|
|
||||||
|
window.push_notification(note, cx);
|
||||||
|
}
|
||||||
DeviceEvent::Set => {
|
DeviceEvent::Set => {
|
||||||
window.push_notification(
|
let note = Notification::new()
|
||||||
Notification::success("Encryption Key has been set"),
|
.id::<DeviceNotifcation>()
|
||||||
cx,
|
.message("Encryption Key has been set")
|
||||||
);
|
.with_kind(NotificationKind::Success);
|
||||||
|
|
||||||
|
window.push_notification(note, cx);
|
||||||
}
|
}
|
||||||
DeviceEvent::Error(error) => {
|
DeviceEvent::Error(error) => {
|
||||||
window.push_notification(Notification::error(error).autohide(false), cx);
|
window.push_notification(Notification::error(error).autohide(false), cx);
|
||||||
@@ -187,9 +204,6 @@ impl Workspace {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
ChatEvent::Subscribed => {
|
|
||||||
this.set_inbox_connected(true, cx);
|
|
||||||
}
|
|
||||||
ChatEvent::Error(error) => {
|
ChatEvent::Error(error) => {
|
||||||
window.push_notification(Notification::error(error).autohide(false), cx);
|
window.push_notification(Notification::error(error).autohide(false), cx);
|
||||||
}
|
}
|
||||||
@@ -217,8 +231,6 @@ impl Workspace {
|
|||||||
Self {
|
Self {
|
||||||
titlebar,
|
titlebar,
|
||||||
dock,
|
dock,
|
||||||
relay_connected: false,
|
|
||||||
inbox_connected: false,
|
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,14 +240,14 @@ impl Workspace {
|
|||||||
where
|
where
|
||||||
P: PanelView,
|
P: PanelView,
|
||||||
{
|
{
|
||||||
if let Some(root) = window.root::<Root>().flatten() {
|
if let Some(root) = window.root::<Root>().flatten()
|
||||||
if let Ok(workspace) = root.read(cx).view().clone().downcast::<Self>() {
|
&& let Ok(workspace) = root.read(cx).view().clone().downcast::<Self>()
|
||||||
workspace.update(cx, |this, cx| {
|
{
|
||||||
this.dock.update(cx, |this, cx| {
|
workspace.update(cx, |this, cx| {
|
||||||
this.add_panel(Arc::new(panel), placement, window, cx);
|
this.dock.update(cx, |this, cx| {
|
||||||
});
|
this.add_panel(Arc::new(panel), placement, window, cx);
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,18 +262,6 @@ impl Workspace {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set whether the relay list is connected
|
|
||||||
fn set_relay_connected(&mut self, connected: bool, cx: &mut Context<Self>) {
|
|
||||||
self.relay_connected = connected;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set whether the inbox is connected
|
|
||||||
fn set_inbox_connected(&mut self, connected: bool, cx: &mut Context<Self>) {
|
|
||||||
self.inbox_connected = connected;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the dock layout
|
/// Set the dock layout
|
||||||
fn set_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn set_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let left = DockItem::panel(Arc::new(sidebar::init(window, cx)));
|
let left = DockItem::panel(Arc::new(sidebar::init(window, cx)));
|
||||||
@@ -346,8 +346,9 @@ impl Workspace {
|
|||||||
}
|
}
|
||||||
Command::RefreshMessagingRelays => {
|
Command::RefreshMessagingRelays => {
|
||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
|
// Trigger a refresh of the chat registry
|
||||||
chat.update(cx, |this, cx| {
|
chat.update(cx, |this, cx| {
|
||||||
this.get_messages(cx);
|
this.refresh(window, cx);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Command::ShowRelayList => {
|
Command::ShowRelayList => {
|
||||||
@@ -360,16 +361,6 @@ impl Workspace {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Command::RefreshRelayList => {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
if let Some(public_key) = signer.public_key() {
|
|
||||||
nostr.update(cx, |this, cx| {
|
|
||||||
this.ensure_relay_list(&public_key, cx);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Command::RefreshEncryption => {
|
Command::RefreshEncryption => {
|
||||||
let device = DeviceRegistry::global(cx);
|
let device = DeviceRegistry::global(cx);
|
||||||
device.update(cx, |this, cx| {
|
device.update(cx, |this, cx| {
|
||||||
@@ -385,14 +376,57 @@ impl Workspace {
|
|||||||
Command::ToggleAccount => {
|
Command::ToggleAccount => {
|
||||||
self.account_selector(window, cx);
|
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"));
|
||||||
|
|
||||||
|
cx.spawn_in(window, async move |_this, cx| {
|
||||||
|
// Get the output path from the save dialog
|
||||||
|
let output_path = match save_dialog.await {
|
||||||
|
Ok(Ok(Some(path))) => path,
|
||||||
|
Ok(Ok(None)) | Err(_) => return Ok(()),
|
||||||
|
Ok(Err(error)) => {
|
||||||
|
cx.update(|window, cx| {
|
||||||
|
let message = format!("Failed to pick save location: {error:#}");
|
||||||
|
let note = Notification::error(message).autohide(false);
|
||||||
|
window.push_notification(note, cx);
|
||||||
|
})?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get the backup task
|
||||||
|
let backup =
|
||||||
|
device.read_with(cx, |this, cx| this.backup(output_path.clone(), cx))?;
|
||||||
|
|
||||||
|
// Run the backup task
|
||||||
|
backup.await?;
|
||||||
|
|
||||||
|
// Open the backup file with the system's default application
|
||||||
|
cx.update(|_window, cx| {
|
||||||
|
cx.open_with_system(output_path.as_path());
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok::<_, anyhow::Error>(())
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
}
|
||||||
|
Command::ImportEncryption => {
|
||||||
|
self.import_encryption(window, cx);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn confirm_reset_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn confirm_reset_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
window.open_modal(cx, |this, _window, cx| {
|
let device = DeviceRegistry::global(cx);
|
||||||
|
let ent = device.downgrade();
|
||||||
|
|
||||||
|
window.open_modal(cx, move |this, _window, cx| {
|
||||||
|
let ent = ent.clone();
|
||||||
|
|
||||||
this.confirm()
|
this.confirm()
|
||||||
.show_close(true)
|
.show_close(true)
|
||||||
.title("Reset Encryption Keys")
|
.title("Reset Encryption Key")
|
||||||
.child(
|
.child(
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_1()
|
.gap_1()
|
||||||
@@ -401,43 +435,31 @@ impl Workspace {
|
|||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.italic()
|
.italic()
|
||||||
.text_color(cx.theme().warning_active)
|
.text_color(cx.theme().text_danger)
|
||||||
.child(SharedString::from(ENC_WARN)),
|
.child(SharedString::from(ENC_WARN)),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.on_ok(move |_ev, window, cx| {
|
.on_ok(move |_ev, _window, cx| {
|
||||||
let device = DeviceRegistry::global(cx);
|
ent.update(cx, |this, cx| {
|
||||||
let task = device.read(cx).create_encryption(cx);
|
this.set_announcement(Keys::generate(), cx);
|
||||||
|
})
|
||||||
window
|
.ok();
|
||||||
.spawn(cx, async move |cx| {
|
// true to close modal
|
||||||
let result = task.await;
|
true
|
||||||
|
|
||||||
cx.update(|window, cx| match result {
|
|
||||||
Ok(keys) => {
|
|
||||||
device.update(cx, |this, cx| {
|
|
||||||
this.set_signer(keys, cx);
|
|
||||||
this.listen_request(cx);
|
|
||||||
});
|
|
||||||
window.close_modal(cx);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
window.push_notification(
|
|
||||||
Notification::error(e.to_string()).autohide(false),
|
|
||||||
cx,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
|
|
||||||
// false to keep modal open
|
|
||||||
false
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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.))
|
||||||
|
.title("Restore Encryption")
|
||||||
|
.child(restore.clone())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn account_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn account_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let accounts = accounts::init(window, cx);
|
let accounts = accounts::init(window, cx);
|
||||||
|
|
||||||
@@ -447,7 +469,6 @@ impl Workspace {
|
|||||||
.show_close(false)
|
.show_close(false)
|
||||||
.keyboard(false)
|
.keyboard(false)
|
||||||
.overlay_closable(false)
|
.overlay_closable(false)
|
||||||
.pb_2()
|
|
||||||
.child(accounts.clone())
|
.child(accounts.clone())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -460,7 +481,6 @@ impl Workspace {
|
|||||||
this.width(px(520.))
|
this.width(px(520.))
|
||||||
.show_close(true)
|
.show_close(true)
|
||||||
.title("Select theme")
|
.title("Select theme")
|
||||||
.pb_2()
|
|
||||||
.child(v_flex().gap_2().w_full().children({
|
.child(v_flex().gap_2().w_full().children({
|
||||||
let mut items = vec![];
|
let mut items = vec![];
|
||||||
|
|
||||||
@@ -533,56 +553,7 @@ impl Workspace {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn relay_notification(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
const BODY: &str = "Coop cannot found your gossip relay list. \
|
|
||||||
Maybe you haven't set it yet or relay not responsed";
|
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
let Some(public_key) = signer.public_key() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let entity = nostr.downgrade();
|
|
||||||
let loading = Rc::new(Cell::new(false));
|
|
||||||
|
|
||||||
let note = Notification::new()
|
|
||||||
.autohide(false)
|
|
||||||
.id::<RelayNotifcation>()
|
|
||||||
.icon(IconName::Relay)
|
|
||||||
.title("Gossip Relays are required")
|
|
||||||
.message(BODY)
|
|
||||||
.action(move |_this, _window, _cx| {
|
|
||||||
let entity = entity.clone();
|
|
||||||
let public_key = public_key.to_owned();
|
|
||||||
|
|
||||||
Button::new("retry")
|
|
||||||
.label("Retry")
|
|
||||||
.small()
|
|
||||||
.primary()
|
|
||||||
.loading(loading.get())
|
|
||||||
.disabled(loading.get())
|
|
||||||
.on_click({
|
|
||||||
let loading = Rc::clone(&loading);
|
|
||||||
|
|
||||||
move |_ev, _window, cx| {
|
|
||||||
// Set loading state to true
|
|
||||||
loading.set(true);
|
|
||||||
// Retry
|
|
||||||
entity
|
|
||||||
.update(cx, |this, cx| {
|
|
||||||
this.ensure_relay_list(&public_key, cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
window.push_notification(note, cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn titlebar_left(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
let current_user = signer.public_key();
|
let current_user = signer.public_key();
|
||||||
@@ -661,9 +632,13 @@ impl Workspace {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn titlebar_right(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let relay_connected = self.relay_connected;
|
let chat = ChatRegistry::global(cx);
|
||||||
let inbox_connected = self.inbox_connected;
|
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 nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
@@ -672,37 +647,98 @@ impl Workspace {
|
|||||||
return div();
|
return div();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let persons = PersonRegistry::global(cx);
|
||||||
|
let profile = persons.read(cx).get(&public_key, cx);
|
||||||
|
let announcement = profile.announcement();
|
||||||
|
|
||||||
h_flex()
|
h_flex()
|
||||||
.when(!cx.theme().platform.is_mac(), |this| this.pr_2())
|
.when(!cx.theme().platform.is_mac(), |this| this.pr_2())
|
||||||
.gap_3()
|
.gap_2()
|
||||||
|
.when(trash_messages > 0, |this| {
|
||||||
|
this.child(
|
||||||
|
h_flex()
|
||||||
|
.id("trash-messages")
|
||||||
|
.h_6()
|
||||||
|
.px_1()
|
||||||
|
.gap_1()
|
||||||
|
.rounded(cx.theme().radius)
|
||||||
|
.hover(|this| this.bg(cx.theme().ghost_element_hover))
|
||||||
|
.child(
|
||||||
|
Icon::new(IconName::Warning)
|
||||||
|
.small()
|
||||||
|
.text_color(cx.theme().text_danger),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.text_xs()
|
||||||
|
.line_height(relative(1.))
|
||||||
|
.child(format!("{trash_messages}")),
|
||||||
|
)
|
||||||
|
.on_click(move |_ev, window, cx| {
|
||||||
|
cx.stop_propagation();
|
||||||
|
// Add the trash panel to the center workspace
|
||||||
|
Self::add_panel(
|
||||||
|
trash::init(window, cx),
|
||||||
|
DockPlacement::Center,
|
||||||
|
window,
|
||||||
|
cx,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
.child(
|
.child(
|
||||||
Button::new("key")
|
Button::new("key")
|
||||||
.icon(IconName::UserKey)
|
.icon(IconName::UserKey)
|
||||||
.tooltip("Decoupled encryption key")
|
.tooltip("Decoupled encryption key")
|
||||||
.small()
|
.small()
|
||||||
.ghost()
|
.ghost()
|
||||||
.dropdown_menu(move |this, _window, cx| {
|
.loading(device_initializing)
|
||||||
let device = DeviceRegistry::global(cx);
|
.when(device_initializing, |this| {
|
||||||
let state = device.read(cx).state();
|
this.label("Dekey")
|
||||||
|
.xsmall()
|
||||||
|
.tooltip("Loading decoupled encryption key...")
|
||||||
|
})
|
||||||
|
.dropdown_menu(move |this, _window, _cx| {
|
||||||
this.min_w(px(260.))
|
this.min_w(px(260.))
|
||||||
.item(PopupMenuItem::element(move |_window, cx| {
|
.label("Encryption Key")
|
||||||
h_flex()
|
.when_some(announcement.as_ref(), |this, announcement| {
|
||||||
.px_1()
|
let name = announcement.client_name();
|
||||||
.w_full()
|
let pkey = shorten_pubkey(announcement.public_key(), 8);
|
||||||
.gap_2()
|
|
||||||
.text_sm()
|
this.item(PopupMenuItem::element(move |_window, cx| {
|
||||||
.child(
|
h_flex()
|
||||||
div()
|
.gap_1()
|
||||||
.size_1p5()
|
.text_sm()
|
||||||
.rounded_full()
|
.child(
|
||||||
.when(state.set(), |this| this.bg(gpui::green()))
|
Icon::new(IconName::Device)
|
||||||
.when(state.requesting(), |this| {
|
.small()
|
||||||
this.bg(cx.theme().icon_accent)
|
.text_color(cx.theme().icon_muted),
|
||||||
}),
|
)
|
||||||
)
|
.child(name.clone())
|
||||||
.child(SharedString::from(state.to_string()))
|
}))
|
||||||
}))
|
.item(PopupMenuItem::element(move |_window, cx| {
|
||||||
|
h_flex()
|
||||||
|
.gap_1()
|
||||||
|
.text_sm()
|
||||||
|
.child(
|
||||||
|
Icon::new(IconName::UserKey)
|
||||||
|
.small()
|
||||||
|
.text_color(cx.theme().icon_muted),
|
||||||
|
)
|
||||||
|
.child(SharedString::from(pkey.clone()))
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
.separator()
|
||||||
|
.menu_with_icon(
|
||||||
|
"Backup",
|
||||||
|
IconName::Shield,
|
||||||
|
Box::new(Command::BackupEncryption),
|
||||||
|
)
|
||||||
|
.menu_with_icon(
|
||||||
|
"Restore from secret key",
|
||||||
|
IconName::Usb,
|
||||||
|
Box::new(Command::ImportEncryption),
|
||||||
|
)
|
||||||
.separator()
|
.separator()
|
||||||
.menu_with_icon(
|
.menu_with_icon(
|
||||||
"Reload",
|
"Reload",
|
||||||
@@ -721,35 +757,52 @@ impl Workspace {
|
|||||||
.icon(IconName::Inbox)
|
.icon(IconName::Inbox)
|
||||||
.small()
|
.small()
|
||||||
.ghost()
|
.ghost()
|
||||||
.loading(!inbox_connected)
|
.loading(initializing)
|
||||||
.disabled(!inbox_connected)
|
.when(initializing, |this| {
|
||||||
.when(!inbox_connected, |this| {
|
this.label("Inbox")
|
||||||
this.tooltip("Connecting to user's messaging relays...")
|
.xsmall()
|
||||||
|
.tooltip("Getting inbox messages...")
|
||||||
})
|
})
|
||||||
.when(inbox_connected, |this| this.indicator())
|
|
||||||
.dropdown_menu(move |this, _window, cx| {
|
.dropdown_menu(move |this, _window, cx| {
|
||||||
let persons = PersonRegistry::global(cx);
|
let urls: Vec<(SharedString, SharedString)> = profile
|
||||||
let profile = persons.read(cx).get(&public_key, cx);
|
|
||||||
|
|
||||||
let urls: Vec<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()),
|
||||||
|
)
|
||||||
}))
|
}))
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -761,38 +814,17 @@ impl Workspace {
|
|||||||
Box::new(Command::RefreshMessagingRelays),
|
Box::new(Command::RefreshMessagingRelays),
|
||||||
)
|
)
|
||||||
.menu_with_icon(
|
.menu_with_icon(
|
||||||
"Update relays",
|
"Manage gossip relays",
|
||||||
|
IconName::Relay,
|
||||||
|
Box::new(Command::ShowRelayList),
|
||||||
|
)
|
||||||
|
.menu_with_icon(
|
||||||
|
"Manage messaging relays",
|
||||||
IconName::Settings,
|
IconName::Settings,
|
||||||
Box::new(Command::ShowMessaging),
|
Box::new(Command::ShowMessaging),
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.child(
|
|
||||||
Button::new("relay-list")
|
|
||||||
.icon(IconName::Relay)
|
|
||||||
.small()
|
|
||||||
.ghost()
|
|
||||||
.loading(!relay_connected)
|
|
||||||
.disabled(!relay_connected)
|
|
||||||
.when(!relay_connected, |this| {
|
|
||||||
this.tooltip("Connecting to user's relay list...")
|
|
||||||
})
|
|
||||||
.when(relay_connected, |this| this.indicator())
|
|
||||||
.dropdown_menu(move |this, _window, _cx| {
|
|
||||||
this.label("User's Relay List")
|
|
||||||
.separator()
|
|
||||||
.menu_with_icon(
|
|
||||||
"Reload",
|
|
||||||
IconName::Refresh,
|
|
||||||
Box::new(Command::RefreshRelayList),
|
|
||||||
)
|
|
||||||
.menu_with_icon(
|
|
||||||
"Update",
|
|
||||||
IconName::Settings,
|
|
||||||
Box::new(Command::ShowRelayList),
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -802,8 +834,8 @@ impl Render for Workspace {
|
|||||||
let notification_layer = Root::render_notification_layer(window, cx);
|
let notification_layer = Root::render_notification_layer(window, cx);
|
||||||
|
|
||||||
// Titlebar elements
|
// Titlebar elements
|
||||||
let left = self.titlebar_left(window, cx).into_any_element();
|
let left = self.titlebar_left(cx).into_any_element();
|
||||||
let right = self.titlebar_right(window, cx).into_any_element();
|
let right = self.titlebar_right(cx).into_any_element();
|
||||||
|
|
||||||
// Update title bar children
|
// Update title bar children
|
||||||
self.titlebar.update(cx, |this, _cx| {
|
self.titlebar.update(cx, |this, _cx| {
|
||||||
|
|||||||
36
crates/coop_mobile/Cargo.toml
Normal file
36
crates/coop_mobile/Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
[package]
|
||||||
|
name = "coop_mobile"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
assets = { path = "../assets" }
|
||||||
|
ui = { path = "../ui" }
|
||||||
|
theme = { path = "../theme" }
|
||||||
|
common = { path = "../common" }
|
||||||
|
state = { path = "../state" }
|
||||||
|
device = { path = "../device" }
|
||||||
|
chat = { path = "../chat" }
|
||||||
|
settings = { path = "../settings" }
|
||||||
|
person = { path = "../person" }
|
||||||
|
relay_auth = { path = "../relay_auth" }
|
||||||
|
|
||||||
|
gpui.workspace = true
|
||||||
|
gpui_platform.workspace = true
|
||||||
|
gpui_tokio.workspace = true
|
||||||
|
gpui-mobile = { git = "https://github.com/itsbalamurali/gpui-mobile" }
|
||||||
|
|
||||||
|
nostr-connect.workspace = true
|
||||||
|
nostr-sdk.workspace = true
|
||||||
|
|
||||||
|
anyhow.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
itertools.workspace = true
|
||||||
|
log.workspace = true
|
||||||
|
smallvec.workspace = true
|
||||||
|
smol.workspace = true
|
||||||
|
futures.workspace = true
|
||||||
|
oneshot.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
0
crates/coop_mobile/src/lib.rs
Normal file
0
crates/coop_mobile/src/lib.rs
Normal file
42
crates/coop_web/Cargo.toml
Normal file
42
crates/coop_web/Cargo.toml
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
[package]
|
||||||
|
name = "coop_web"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
assets = { path = "../assets" }
|
||||||
|
ui = { path = "../ui" }
|
||||||
|
theme = { path = "../theme" }
|
||||||
|
common = { path = "../common" }
|
||||||
|
state = { path = "../state" }
|
||||||
|
device = { path = "../device" }
|
||||||
|
chat = { path = "../chat" }
|
||||||
|
settings = { path = "../settings" }
|
||||||
|
person = { path = "../person" }
|
||||||
|
relay_auth = { path = "../relay_auth" }
|
||||||
|
|
||||||
|
gpui.workspace = true
|
||||||
|
gpui_platform.workspace = true
|
||||||
|
gpui_tokio.workspace = true
|
||||||
|
gpui_web = { git = "https://github.com/zed-industries/zed" }
|
||||||
|
|
||||||
|
nostr-connect.workspace = true
|
||||||
|
nostr-sdk.workspace = true
|
||||||
|
|
||||||
|
anyhow.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
itertools.workspace = true
|
||||||
|
log.workspace = true
|
||||||
|
smallvec.workspace = true
|
||||||
|
smol.workspace = true
|
||||||
|
futures.workspace = true
|
||||||
|
oneshot.workspace = true
|
||||||
|
webbrowser.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
||||||
|
console_error_panic_hook = "0.1"
|
||||||
|
tracing-wasm = "0.2"
|
||||||
|
console_log = "1.0"
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
26
crates/coop_web/src/lib.rs
Normal file
26
crates/coop_web/src/lib.rs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
use gpui::*;
|
||||||
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn run() -> Result<(), JsValue> {
|
||||||
|
console_error_panic_hook::set_once();
|
||||||
|
|
||||||
|
// Initialize logging to browser console
|
||||||
|
console_log::init_with_level(log::Level::Info).expect("Failed to initialize logger");
|
||||||
|
|
||||||
|
// Also initialize tracing for WASM
|
||||||
|
tracing_wasm::set_as_global_default();
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
gpui_platform::web_init();
|
||||||
|
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
let app = gpui_platform::application();
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
let app = gpui_platform::single_threaded_web();
|
||||||
|
|
||||||
|
app.run(|_cx| {});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
77
crates/coop_web/src/www/index.html
Normal file
77
crates/coop_web/src/www/index.html
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Coop</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family:
|
||||||
|
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||||
|
Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue",
|
||||||
|
sans-serif;
|
||||||
|
overflow: hidden;
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
#app {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
#canvas {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
#loading {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner {
|
||||||
|
border: 4px solid rgba(0, 0, 0, 0.1);
|
||||||
|
border-left-color: #000;
|
||||||
|
border-radius: 50%;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
animation: spin 1s linear infinite;
|
||||||
|
margin: 0 auto 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #d32f2f;
|
||||||
|
padding: 20px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app">
|
||||||
|
<canvas id="canvas"></canvas>
|
||||||
|
<div id="loading">
|
||||||
|
<div class="spinner"></div>
|
||||||
|
<p>Loading Coop...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,21 +1,22 @@
|
|||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::HashSet;
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
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, 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;
|
||||||
use ui::notification::Notification;
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Disableable, IconName, Sizable, WindowExtension, h_flex, v_flex};
|
use ui::{Disableable, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
|
||||||
|
|
||||||
const IDENTIFIER: &str = "coop:device";
|
const IDENTIFIER: &str = "coop:device";
|
||||||
const MSG: &str = "You've requested an encryption key from another device. \
|
const MSG: &str = "You've requested an encryption key from another device. \
|
||||||
@@ -34,20 +35,39 @@ impl Global for GlobalDeviceRegistry {}
|
|||||||
pub enum DeviceEvent {
|
pub enum DeviceEvent {
|
||||||
/// A new encryption signer has been set
|
/// A new encryption signer has been set
|
||||||
Set,
|
Set,
|
||||||
|
/// The device is requesting an encryption key
|
||||||
|
Requesting,
|
||||||
|
/// The device is creating a new encryption key
|
||||||
|
Creating,
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
Error(SharedString),
|
Error(SharedString),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl DeviceEvent {
|
||||||
|
pub fn error<T>(error: T) -> Self
|
||||||
|
where
|
||||||
|
T: Into<SharedString>,
|
||||||
|
{
|
||||||
|
Self::Error(error.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Device Registry
|
/// Device Registry
|
||||||
///
|
///
|
||||||
/// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
|
/// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct DeviceRegistry {
|
pub struct DeviceRegistry {
|
||||||
/// Device state
|
/// Whether the registry is currently initializing
|
||||||
state: DeviceState,
|
pub initializing: bool,
|
||||||
|
|
||||||
|
/// Whether there is a pending request for encryption key approval
|
||||||
|
pub pending_request: bool,
|
||||||
|
|
||||||
/// 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 +85,25 @@ 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 state = DeviceState::default();
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
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,
|
initializing: true,
|
||||||
|
pending_request: false,
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
|
_subscription: Some(subscription),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,10 +117,8 @@ impl DeviceRegistry {
|
|||||||
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 {
|
||||||
if let ClientNotification::Message {
|
if let ClientNotification::Message { message, .. } = notification
|
||||||
message: RelayMessage::Event { event, .. },
|
&& let RelayMessage::Event { event, .. } = *message
|
||||||
..
|
|
||||||
} = notification
|
|
||||||
{
|
{
|
||||||
if !processed_events.insert(event.id) {
|
if !processed_events.insert(event.id) {
|
||||||
// Skip if the event has already been processed
|
// Skip if the event has already been processed
|
||||||
@@ -120,13 +147,13 @@ impl DeviceRegistry {
|
|||||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||||
while let Ok(event) = rx.recv_async().await {
|
while let Ok(event) = rx.recv_async().await {
|
||||||
match event.kind {
|
match event.kind {
|
||||||
// New request event
|
// New request event from other device
|
||||||
Kind::Custom(4454) => {
|
Kind::Custom(4454) => {
|
||||||
this.update_in(cx, |this, window, cx| {
|
this.update_in(cx, |this, window, cx| {
|
||||||
this.ask_for_approval(event, window, cx);
|
this.ask_for_approval(event, window, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
// New response event
|
// New response event from the master device
|
||||||
Kind::Custom(4455) => {
|
Kind::Custom(4455) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.extract_encryption(event, cx);
|
this.extract_encryption(event, cx);
|
||||||
@@ -135,24 +162,24 @@ impl DeviceRegistry {
|
|||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the device state
|
/// Set whether the registry is currently initializing
|
||||||
pub fn state(&self) -> DeviceState {
|
fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
|
||||||
self.state.clone()
|
self.initializing = initializing;
|
||||||
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the device state
|
/// Set whether there is a pending request for encryption key approval
|
||||||
fn set_state(&mut self, state: DeviceState, cx: &mut Context<Self>) {
|
fn set_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
|
||||||
self.state = state;
|
self.pending_request = pending;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the decoupled encryption key for the current user
|
/// Set the decoupled encryption key for the current user
|
||||||
pub fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
|
fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
|
||||||
where
|
where
|
||||||
S: NostrSigner + 'static,
|
S: NostrSigner + 'static,
|
||||||
{
|
{
|
||||||
@@ -164,86 +191,24 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
// Update state
|
// Update state
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_state(DeviceState::Set, cx);
|
this.set_initializing(false, cx);
|
||||||
this.get_messages(cx);
|
cx.emit(DeviceEvent::Set);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reset the device state
|
/// Backup the encryption's secret key to a file
|
||||||
fn reset(&mut self, cx: &mut Context<Self>) {
|
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
|
||||||
self.state = DeviceState::Idle;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get all messages for encryption keys
|
|
||||||
fn get_messages(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let task = self.subscribe_to_giftwrap_events(cx);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
if let Err(e) = task.await {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(DeviceEvent::Error(SharedString::from(e.to_string())));
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the messaging relays for the current user
|
|
||||||
fn get_user_messaging_relays(&self, cx: &App) -> Task<Result<Vec<RelayUrl>, Error>> {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let keys = get_keys(&client).await?;
|
||||||
let filter = Filter::new()
|
let content = keys.secret_key().to_bech32()?;
|
||||||
.kind(Kind::InboxRelays)
|
|
||||||
.author(public_key)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
smol::fs::write(path, &content).await?;
|
||||||
// Extract relay URLs from the event
|
|
||||||
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
|
|
||||||
|
|
||||||
// Ensure all relays are connected
|
|
||||||
for url in urls.iter() {
|
|
||||||
client.add_relay(url).and_connect().await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(urls)
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("Relays not found"))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Continuously get gift wrap events for the current user in their messaging relays
|
|
||||||
fn subscribe_to_giftwrap_events(&self, cx: &App) -> Task<Result<(), Error>> {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let client = nostr.read(cx).client();
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
let urls = self.get_user_messaging_relays(cx);
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
|
||||||
let urls = urls.await?;
|
|
||||||
let encryption = signer.get_encryption_signer().await.context("not found")?;
|
|
||||||
let public_key = encryption.get_public_key().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
|
||||||
let id = SubscriptionId::new(DEVICE_GIFTWRAP);
|
|
||||||
|
|
||||||
// Construct target for subscription
|
|
||||||
let target: HashMap<RelayUrl, Filter> = urls
|
|
||||||
.into_iter()
|
|
||||||
.map(|relay| (relay, filter.clone()))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Subscribe
|
|
||||||
client.subscribe(target).with_id(id).await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
@@ -254,9 +219,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?;
|
||||||
@@ -285,13 +247,15 @@ impl DeviceRegistry {
|
|||||||
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(event) => {
|
Ok(event) => {
|
||||||
|
// Set encryption key from the announcement event
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.new_signer(&event, cx);
|
this.set_encryption(&event, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
|
// User has no announcement, create a new one
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.announce(cx);
|
this.set_announcement(Keys::generate(), cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -300,26 +264,55 @@ impl DeviceRegistry {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new encryption keys
|
/// Create a new device signer and announce it to user's relay list
|
||||||
pub fn create_encryption(&self, cx: &App) -> Task<Result<Keys, Error>> {
|
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) => {
|
||||||
|
this.update(cx, |this, cx| {
|
||||||
|
this.set_signer(keys, cx);
|
||||||
|
this.wait_for_request(cx);
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
cx.emit(DeviceEvent::error(e.to_string()));
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create new encryption key and announce it to user's relay list
|
||||||
|
fn create_encryption(&self, keys: Keys, cx: &App) -> Task<Result<Keys, Error>> {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
let keys = Keys::generate();
|
|
||||||
let secret = keys.secret_key().to_secret_hex();
|
let secret = keys.secret_key().to_secret_hex();
|
||||||
let n = keys.public_key();
|
let n = keys.public_key();
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
// Construct an announcement event
|
// Construct an announcement event
|
||||||
let event = client
|
let builder = EventBuilder::new(Kind::Custom(10044), "").tags(vec![
|
||||||
.sign_event_builder(EventBuilder::new(Kind::Custom(10044), "").tags(vec![
|
Tag::custom(TagKind::custom("n"), vec![n]),
|
||||||
Tag::custom(TagKind::custom("n"), vec![n]),
|
Tag::client(app_name()),
|
||||||
Tag::client(app_name()),
|
]);
|
||||||
]))
|
|
||||||
.await?;
|
// Sign the event with user's signer
|
||||||
|
let event = client.sign_event_builder(builder).await?;
|
||||||
|
|
||||||
// Publish announcement
|
// Publish announcement
|
||||||
client.send_event(&event).to_nip65().await?;
|
client
|
||||||
|
.send_event(&event)
|
||||||
|
.to_nip65()
|
||||||
|
.ack_policy(AckPolicy::none())
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Save device keys to the database
|
// Save device keys to the database
|
||||||
set_keys(&client, &secret).await?;
|
set_keys(&client, &secret).await?;
|
||||||
@@ -328,116 +321,66 @@ impl DeviceRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new device signer and announce it
|
/// Set encryption key from the announcement event
|
||||||
fn announce(&mut self, cx: &mut Context<Self>) {
|
fn set_encryption(&mut self, event: &Event, cx: &mut Context<Self>) {
|
||||||
let task = self.create_encryption(cx);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let keys = task.await?;
|
|
||||||
|
|
||||||
// Update signer
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_signer(keys, cx);
|
|
||||||
this.listen_request(cx);
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initialize device signer (decoupled encryption key) for the current user
|
|
||||||
pub fn new_signer(&mut self, event: &Event, cx: &mut Context<Self>) {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
let announcement = Announcement::from(event);
|
let announcement = Announcement::from(event);
|
||||||
let device_pubkey = announcement.public_key();
|
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 task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
||||||
if let Ok(keys) = get_keys(&client).await {
|
let keys = get_keys(&client).await?;
|
||||||
if keys.public_key() != device_pubkey {
|
|
||||||
return Err(anyhow!("Key mismatch"));
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(keys)
|
// Compare the public key from the announcement with the one from the database
|
||||||
} else {
|
if keys.public_key() != device_pubkey {
|
||||||
Err(anyhow!("Key not found"))
|
return Err(anyhow!("Encryption Key doesn't match the announcement"));
|
||||||
}
|
};
|
||||||
|
|
||||||
|
Ok(keys)
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
match task.await {
|
if let Ok(keys) = task.await {
|
||||||
Ok(keys) => {
|
this.update(cx, |this, cx| {
|
||||||
this.update(cx, |this, cx| {
|
this.set_signer(keys, cx);
|
||||||
this.set_signer(keys, cx);
|
this.wait_for_request(cx);
|
||||||
this.listen_request(cx);
|
})?;
|
||||||
})?;
|
} else {
|
||||||
}
|
this.update(cx, |this, cx| {
|
||||||
Err(e) => {
|
this.request(cx);
|
||||||
log::warn!("Failed to initialize device signer: {e}");
|
})?;
|
||||||
this.update(cx, |this, cx| {
|
}
|
||||||
this.request(cx);
|
|
||||||
this.listen_approval(cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Listen for device key requests on user's write relays
|
/// Wait for encryption key requests from now on
|
||||||
pub fn listen_request(&mut self, cx: &mut Context<Self>) {
|
fn wait_for_request(&mut self, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
|
|
||||||
let Some(public_key) = signer.public_key() else {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
return;
|
let public_key = signer.get_public_key().await?;
|
||||||
};
|
let id = SubscriptionId::new("dekey-requests");
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
// Construct a filter for encryption key requests
|
||||||
// Construct a filter for device key requests
|
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::Custom(4454))
|
.kind(Kind::Custom(4454))
|
||||||
.author(public_key)
|
.author(public_key)
|
||||||
.since(Timestamp::now());
|
.since(Timestamp::now());
|
||||||
|
|
||||||
// Subscribe to the device key requests on user's write relays
|
// Subscribe to the device key requests on user's write relays
|
||||||
client.subscribe(filter).await?;
|
client.subscribe(vec![filter]).with_id(id).await?;
|
||||||
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
task.detach();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Listen for device key approvals on user's write relays
|
|
||||||
fn listen_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(public_key) = signer.public_key() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
|
||||||
// Construct a filter for device key requests
|
|
||||||
let filter = Filter::new()
|
|
||||||
.kind(Kind::Custom(4455))
|
|
||||||
.author(public_key)
|
|
||||||
.since(Timestamp::now());
|
|
||||||
|
|
||||||
// Subscribe to the device key requests on user's write relays
|
|
||||||
client.subscribe(filter).await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Request encryption keys from other device
|
/// Request encryption keys from other device
|
||||||
fn request(&mut self, cx: &mut Context<Self>) {
|
pub fn request(&mut self, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
@@ -445,9 +388,10 @@ impl DeviceRegistry {
|
|||||||
let app_keys = nostr.read(cx).keys();
|
let app_keys = nostr.read(cx).keys();
|
||||||
let app_pubkey = app_keys.public_key();
|
let app_pubkey = app_keys.public_key();
|
||||||
|
|
||||||
let task: Task<Result<Option<Keys>, Error>> = cx.background_spawn(async move {
|
let task: Task<Result<Option<Event>, Error>> = cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key().await?;
|
||||||
|
|
||||||
|
// Construct a filter to get the latest approval event
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::Custom(4455))
|
.kind(Kind::Custom(4455))
|
||||||
.author(public_key)
|
.author(public_key)
|
||||||
@@ -455,30 +399,18 @@ impl DeviceRegistry {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
match client.database().query(filter).await?.first_owned() {
|
match client.database().query(filter).await?.first_owned() {
|
||||||
Some(event) => {
|
// Found an approval event
|
||||||
let root_device = event
|
Some(event) => Ok(Some(event)),
|
||||||
.tags
|
// No approval event found, construct a request event
|
||||||
.find(TagKind::custom("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(&root_device, payload).await?;
|
|
||||||
|
|
||||||
let secret = SecretKey::from_hex(&decrypted)?;
|
|
||||||
let keys = Keys::new(secret);
|
|
||||||
|
|
||||||
Ok(Some(keys))
|
|
||||||
}
|
|
||||||
None => {
|
None => {
|
||||||
// Construct an event for device key request
|
// Construct an event for device key request
|
||||||
let event = client
|
let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
|
||||||
.sign_event_builder(EventBuilder::new(Kind::Custom(4454), "").tags(vec![
|
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
|
||||||
Tag::client(app_name()),
|
Tag::client(app_name()),
|
||||||
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
|
]);
|
||||||
]))
|
|
||||||
.await?;
|
// Sign the event with user's signer
|
||||||
|
let event = client.sign_event_builder(builder).await?;
|
||||||
|
|
||||||
// Send the event to write relays
|
// Send the event to write relays
|
||||||
client.send_event(&event).to_nip65().await?;
|
client.send_event(&event).to_nip65().await?;
|
||||||
@@ -490,32 +422,58 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
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(Some(keys)) => {
|
Ok(Some(event)) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.extract_encryption(event, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_state(DeviceState::Requesting, cx);
|
this.set_initializing(false, cx);
|
||||||
|
this.wait_for_approval(cx);
|
||||||
|
|
||||||
|
cx.emit(DeviceEvent::Requesting);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("Failed to request the encryption key: {e}");
|
this.update(cx, |_this, cx| {
|
||||||
|
cx.emit(DeviceEvent::error(e.to_string()));
|
||||||
|
})?;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for encryption key approvals
|
||||||
|
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();
|
||||||
|
|
||||||
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
|
let public_key = signer.get_public_key().await?;
|
||||||
|
|
||||||
|
// Construct a filter for device key requests
|
||||||
|
let filter = Filter::new()
|
||||||
|
.kind(Kind::Custom(4455))
|
||||||
|
.author(public_key)
|
||||||
|
.since(Timestamp::now());
|
||||||
|
|
||||||
|
// Subscribe to the device key requests on user's write relays
|
||||||
|
client.subscribe(filter).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse the response event for device keys from other devices
|
/// Parse the approval event to get encryption key then set it
|
||||||
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
|
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let app_keys = nostr.read(cx).keys();
|
let app_keys = nostr.read(cx).keys();
|
||||||
|
|
||||||
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
||||||
let root_device = event
|
let master = event
|
||||||
.tags
|
.tags
|
||||||
.find(TagKind::custom("P"))
|
.find(TagKind::custom("P"))
|
||||||
.and_then(|tag| tag.content())
|
.and_then(|tag| tag.content())
|
||||||
@@ -523,7 +481,7 @@ impl DeviceRegistry {
|
|||||||
.context("Invalid event's tags")?;
|
.context("Invalid event's tags")?;
|
||||||
|
|
||||||
let payload = event.content.as_str();
|
let payload = event.content.as_str();
|
||||||
let decrypted = app_keys.nip44_decrypt(&root_device, payload).await?;
|
let decrypted = app_keys.nip44_decrypt(&master, payload).await?;
|
||||||
|
|
||||||
let secret = SecretKey::from_hex(&decrypted)?;
|
let secret = SecretKey::from_hex(&decrypted)?;
|
||||||
let keys = Keys::new(secret);
|
let keys = Keys::new(secret);
|
||||||
@@ -532,13 +490,18 @@ impl DeviceRegistry {
|
|||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
let keys = task.await?;
|
match task.await {
|
||||||
|
Ok(keys) => {
|
||||||
// Update signer
|
this.update(cx, |this, cx| {
|
||||||
this.update(cx, |this, cx| {
|
this.set_signer(keys, cx);
|
||||||
this.set_signer(keys, cx);
|
})?;
|
||||||
})?;
|
}
|
||||||
|
Err(e) => {
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
cx.emit(DeviceEvent::error(e.to_string()));
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -547,7 +510,6 @@ impl DeviceRegistry {
|
|||||||
fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) {
|
fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
// Get user's write relays
|
// Get user's write relays
|
||||||
let event = event.clone();
|
let event = event.clone();
|
||||||
@@ -567,14 +529,14 @@ impl DeviceRegistry {
|
|||||||
.context("Target is not a valid public key")?;
|
.context("Target is not a valid public key")?;
|
||||||
|
|
||||||
// Encrypt the device keys with the user's signer
|
// Encrypt the device keys with the user's signer
|
||||||
let payload = signer.nip44_encrypt(&target, &secret).await?;
|
let payload = keys.nip44_encrypt(&target, &secret).await?;
|
||||||
|
|
||||||
// Construct the response event
|
// Construct the response event
|
||||||
//
|
//
|
||||||
// P tag: the current device's public key
|
// P tag: the current device's public key
|
||||||
// p tag: the requester's public key
|
// p tag: the requester's public key
|
||||||
let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![
|
let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![
|
||||||
Tag::custom(TagKind::custom("P"), vec![keys.public_key()]),
|
Tag::custom(TagKind::custom("P"), vec![keys.public_key().to_hex()]),
|
||||||
Tag::public_key(target),
|
Tag::public_key(target),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -611,15 +573,15 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
/// Handle encryption request
|
/// Handle encryption request
|
||||||
fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) {
|
fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let notification = self.notification(event, cx);
|
// Ignore if there is already a pending request
|
||||||
|
if self.pending_request {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.set_pending_request(true, cx);
|
||||||
|
|
||||||
cx.spawn_in(window, async move |_this, cx| {
|
// Show notification
|
||||||
cx.update(|window, cx| {
|
let notification = self.notification(event, cx);
|
||||||
window.push_notification(notification, cx);
|
window.push_notification(notification, cx);
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build a notification for the encryption request.
|
/// Build a notification for the encryption request.
|
||||||
@@ -635,8 +597,8 @@ impl DeviceRegistry {
|
|||||||
Notification::new()
|
Notification::new()
|
||||||
.type_id::<DeviceNotification>(key)
|
.type_id::<DeviceNotification>(key)
|
||||||
.autohide(false)
|
.autohide(false)
|
||||||
.icon(IconName::UserKey)
|
.with_kind(NotificationKind::Info)
|
||||||
.title(SharedString::from("New request"))
|
.title("Encryption Key Request")
|
||||||
.content(move |_this, _window, cx| {
|
.content(move |_this, _window, cx| {
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
@@ -656,13 +618,14 @@ impl DeviceRegistry {
|
|||||||
.text_sm()
|
.text_sm()
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
|
.font_semibold()
|
||||||
.text_xs()
|
.text_xs()
|
||||||
.text_color(cx.theme().text_muted)
|
.text_color(cx.theme().text_muted)
|
||||||
.child(SharedString::from("Requester:")),
|
.child(SharedString::from("From:")),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.h_7()
|
.h_8()
|
||||||
.w_full()
|
.w_full()
|
||||||
.px_2()
|
.px_2()
|
||||||
.rounded(cx.theme().radius)
|
.rounded(cx.theme().radius)
|
||||||
@@ -681,13 +644,14 @@ impl DeviceRegistry {
|
|||||||
.text_sm()
|
.text_sm()
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
|
.font_semibold()
|
||||||
.text_xs()
|
.text_xs()
|
||||||
.text_color(cx.theme().text_muted)
|
.text_color(cx.theme().text_muted)
|
||||||
.child(SharedString::from("Client:")),
|
.child(SharedString::from("Client:")),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.h_7()
|
.h_8()
|
||||||
.w_full()
|
.w_full()
|
||||||
.px_2()
|
.px_2()
|
||||||
.rounded(cx.theme().radius)
|
.rounded(cx.theme().radius)
|
||||||
@@ -704,8 +668,6 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
Button::new("approve")
|
Button::new("approve")
|
||||||
.label("Approve")
|
.label("Approve")
|
||||||
.small()
|
|
||||||
.primary()
|
|
||||||
.loading(loading.get())
|
.loading(loading.get())
|
||||||
.disabled(loading.get())
|
.disabled(loading.get())
|
||||||
.on_click({
|
.on_click({
|
||||||
@@ -728,10 +690,10 @@ struct DeviceNotification;
|
|||||||
|
|
||||||
/// Verify the author of an event
|
/// Verify the author of an event
|
||||||
async fn verify_author(client: &Client, event: &Event) -> bool {
|
async fn verify_author(client: &Client, event: &Event) -> bool {
|
||||||
if let Some(signer) = client.signer() {
|
if let Some(signer) = client.signer()
|
||||||
if let Ok(public_key) = signer.get_public_key().await {
|
&& let Ok(public_key) = signer.get_public_key().await
|
||||||
return public_key == event.pubkey;
|
{
|
||||||
}
|
return public_key == event.pubkey;
|
||||||
}
|
}
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::rc::Rc;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Error, anyhow};
|
use anyhow::{Error, anyhow};
|
||||||
use common::EventUtils;
|
use common::EventExt;
|
||||||
use gpui::{App, AppContext, Context, Entity, Global, Task, Window};
|
use gpui::{App, AppContext, Context, Entity, Global, Task, Window};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
@@ -135,7 +135,7 @@ impl PersonRegistry {
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
if let RelayMessage::Event { event, .. } = message {
|
if let RelayMessage::Event { event, .. } = *message {
|
||||||
// Skip if the event has already been processed
|
// Skip if the event has already been processed
|
||||||
if !processed.insert(event.id) {
|
if !processed.insert(event.id) {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -123,16 +123,16 @@ impl Person {
|
|||||||
|
|
||||||
/// Get profile name
|
/// Get profile name
|
||||||
pub fn name(&self) -> SharedString {
|
pub fn name(&self) -> SharedString {
|
||||||
if let Some(display_name) = self.metadata().display_name.as_ref() {
|
if let Some(display_name) = self.metadata().display_name.as_ref()
|
||||||
if !display_name.is_empty() {
|
&& !display_name.is_empty()
|
||||||
return SharedString::from(display_name);
|
{
|
||||||
}
|
return SharedString::from(display_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(name) = self.metadata().name.as_ref() {
|
if let Some(name) = self.metadata().name.as_ref()
|
||||||
if !name.is_empty() {
|
&& !name.is_empty()
|
||||||
return SharedString::from(name);
|
{
|
||||||
}
|
return SharedString::from(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
SharedString::from(shorten_pubkey(self.public_key(), 4))
|
SharedString::from(shorten_pubkey(self.public_key(), 4))
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ use settings::{AppSettings, AuthMode};
|
|||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::NostrRegistry;
|
use state::NostrRegistry;
|
||||||
use theme::ActiveTheme;
|
use theme::ActiveTheme;
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::Button;
|
||||||
use ui::notification::Notification;
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Disableable, IconName, Sizable, WindowExtension, v_flex};
|
use ui::{Disableable, 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.";
|
||||||
@@ -100,7 +100,7 @@ impl RelayAuth {
|
|||||||
|
|
||||||
while let Some(notification) = notifications.next().await {
|
while let Some(notification) = notifications.next().await {
|
||||||
if let ClientNotification::Message { relay_url, message } = notification {
|
if let ClientNotification::Message { relay_url, message } = notification {
|
||||||
match message {
|
match *message {
|
||||||
RelayMessage::Auth { challenge } => {
|
RelayMessage::Auth { challenge } => {
|
||||||
if challenges.insert(challenge.clone()) {
|
if challenges.insert(challenge.clone()) {
|
||||||
let request = Arc::new(AuthRequest::new(challenge, relay_url));
|
let request = Arc::new(AuthRequest::new(challenge, relay_url));
|
||||||
@@ -221,31 +221,31 @@ impl RelayAuth {
|
|||||||
|
|
||||||
while let Some(notification) = notifications.next().await {
|
while let Some(notification) = notifications.next().await {
|
||||||
match notification {
|
match notification {
|
||||||
RelayNotification::Message {
|
RelayNotification::Message { message } => {
|
||||||
message: RelayMessage::Ok { event_id, .. },
|
if let RelayMessage::Ok { event_id, .. } = *message {
|
||||||
} => {
|
if id != event_id {
|
||||||
if id != event_id {
|
continue;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all subscriptions
|
|
||||||
let subscriptions = relay.subscriptions().await;
|
|
||||||
|
|
||||||
// Re-subscribe to previous subscriptions
|
|
||||||
for (id, filters) in subscriptions.into_iter() {
|
|
||||||
if !filters.is_empty() {
|
|
||||||
relay.send_msg(ClientMessage::req(id, filters)).await?;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Re-send pending events
|
// Get all subscriptions
|
||||||
for id in pending_events {
|
let subscriptions = relay.subscriptions().await;
|
||||||
if let Some(event) = client.database().event_by_id(&id).await? {
|
|
||||||
relay.send_event(&event).await?;
|
// Re-subscribe to previous subscriptions
|
||||||
|
for (id, filters) in subscriptions.into_iter() {
|
||||||
|
if !filters.is_empty() {
|
||||||
|
relay.send_msg(ClientMessage::req(id, filters)).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(());
|
// Re-send pending events
|
||||||
|
for id in pending_events {
|
||||||
|
if let Some(event) = client.database().event_by_id(&id).await? {
|
||||||
|
relay.send_event(&event).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
RelayNotification::AuthenticationFailed => break,
|
RelayNotification::AuthenticationFailed => break,
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -327,8 +327,8 @@ impl RelayAuth {
|
|||||||
Notification::new()
|
Notification::new()
|
||||||
.type_id::<AuthNotification>(challenge)
|
.type_id::<AuthNotification>(challenge)
|
||||||
.autohide(false)
|
.autohide(false)
|
||||||
.icon(IconName::Warning)
|
.with_kind(NotificationKind::Info)
|
||||||
.title(SharedString::from("Authentication Required"))
|
.title("Authentication Required")
|
||||||
.content(move |_this, _window, cx| {
|
.content(move |_this, _window, cx| {
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
@@ -345,7 +345,7 @@ impl RelayAuth {
|
|||||||
.rounded_sm()
|
.rounded_sm()
|
||||||
.text_xs()
|
.text_xs()
|
||||||
.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()
|
||||||
@@ -356,8 +356,6 @@ impl RelayAuth {
|
|||||||
|
|
||||||
Button::new("approve")
|
Button::new("approve")
|
||||||
.label("Approve")
|
.label("Approve")
|
||||||
.small()
|
|
||||||
.primary()
|
|
||||||
.loading(loading.get())
|
.loading(loading.get())
|
||||||
.disabled(loading.get())
|
.disabled(loading.get())
|
||||||
.on_click({
|
.on_click({
|
||||||
|
|||||||
@@ -277,17 +277,6 @@ impl AppSettings {
|
|||||||
self.apply_theme(window, cx);
|
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() {
|
|
||||||
if let Ok(new_theme) = ThemeFamily::from_assets(name) {
|
|
||||||
Theme::apply_theme(Rc::new(new_theme), Some(window), cx);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Theme::apply_theme(Rc::new(ThemeFamily::default()), Some(window), cx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reset theme
|
/// Reset theme
|
||||||
pub fn reset_theme(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
pub fn reset_theme(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
self.values.theme = None;
|
self.values.theme = None;
|
||||||
@@ -296,6 +285,22 @@ impl AppSettings {
|
|||||||
self.apply_theme(window, cx);
|
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 Ok(new_theme) = ThemeFamily::from_assets(name) {
|
||||||
|
Theme::apply_theme(Rc::new(new_theme), Some(window), cx);
|
||||||
|
Theme::change(mode, Some(window), cx);
|
||||||
|
} else {
|
||||||
|
log::info!("Failed to load theme: {name}");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Theme::apply_theme(Rc::new(ThemeFamily::default()), Some(window), cx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Check if the given relay is already authenticated
|
/// Check if the given relay is already authenticated
|
||||||
pub fn trusted_relay(&self, url: &RelayUrl, _cx: &App) -> bool {
|
pub fn trusted_relay(&self, url: &RelayUrl, _cx: &App) -> bool {
|
||||||
self.values.trusted_relays.iter().any(|relay| {
|
self.values.trusted_relays.iter().any(|relay| {
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ common = { path = "../common" }
|
|||||||
nostr.workspace = true
|
nostr.workspace = true
|
||||||
nostr-sdk.workspace = true
|
nostr-sdk.workspace = true
|
||||||
nostr-lmdb.workspace = true
|
nostr-lmdb.workspace = true
|
||||||
nostr-memory.workspace = true
|
nostr-gossip-memory.workspace = true
|
||||||
nostr-gossip-sqlite.workspace = true
|
|
||||||
nostr-connect.workspace = true
|
nostr-connect.workspace = true
|
||||||
nostr-blossom.workspace = true
|
nostr-blossom.workspace = true
|
||||||
|
|
||||||
|
|||||||
@@ -36,14 +36,16 @@ pub const NOSTR_CONNECT_RELAY: &str = "wss://relay.nip46.com";
|
|||||||
/// Default vertex relays
|
/// Default vertex relays
|
||||||
pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"];
|
pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"];
|
||||||
|
|
||||||
|
/// Default search relays
|
||||||
|
pub const INDEXER_RELAYS: [&str; 1] = ["wss://indexer.coracle.social"];
|
||||||
|
|
||||||
/// Default search relays
|
/// Default search relays
|
||||||
pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.today"];
|
pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.today"];
|
||||||
|
|
||||||
/// Default bootstrap relays
|
/// Default bootstrap relays
|
||||||
pub const BOOTSTRAP_RELAYS: [&str; 4] = [
|
pub const BOOTSTRAP_RELAYS: [&str; 3] = [
|
||||||
"wss://relay.damus.io",
|
"wss://relay.damus.io",
|
||||||
"wss://relay.primal.net",
|
"wss://relay.primal.net",
|
||||||
"wss://indexer.coracle.social",
|
|
||||||
"wss://user.kindpag.es",
|
"wss://user.kindpag.es",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,40 +1,6 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use gpui::SharedString;
|
use gpui::SharedString;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
|
||||||
pub enum DeviceState {
|
|
||||||
#[default]
|
|
||||||
Idle,
|
|
||||||
Requesting,
|
|
||||||
Set,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for DeviceState {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
DeviceState::Idle => write!(f, "Idle"),
|
|
||||||
DeviceState::Requesting => write!(f, "Wait for approval"),
|
|
||||||
DeviceState::Set => write!(f, "Encryption Key is ready"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeviceState {
|
|
||||||
pub fn idle(&self) -> bool {
|
|
||||||
matches!(self, DeviceState::Idle)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn requesting(&self) -> bool {
|
|
||||||
matches!(self, DeviceState::Requesting)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set(&self) -> bool {
|
|
||||||
matches!(self, DeviceState::Set)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Announcement
|
/// Announcement
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub struct Announcement {
|
pub struct Announcement {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -6,9 +7,8 @@ use anyhow::{Context as AnyhowContext, Error, anyhow};
|
|||||||
use common::config_dir;
|
use common::config_dir;
|
||||||
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
|
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
|
||||||
use nostr_connect::prelude::*;
|
use nostr_connect::prelude::*;
|
||||||
use nostr_gossip_sqlite::prelude::*;
|
use nostr_gossip_memory::prelude::*;
|
||||||
use nostr_lmdb::prelude::*;
|
use nostr_lmdb::prelude::*;
|
||||||
use nostr_memory::prelude::*;
|
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
mod blossom;
|
mod blossom;
|
||||||
@@ -48,16 +48,25 @@ pub enum StateEvent {
|
|||||||
Connecting,
|
Connecting,
|
||||||
/// Connected to the bootstrapping relay
|
/// Connected to the bootstrapping relay
|
||||||
Connected,
|
Connected,
|
||||||
/// User has not set up NIP-65 relays
|
/// Creating the signer
|
||||||
RelayNotConfigured,
|
Creating,
|
||||||
/// Connected to NIP-65 relays
|
/// Show the identity dialog
|
||||||
RelayConnected,
|
Show,
|
||||||
/// A new signer has been set
|
/// A new signer has been set
|
||||||
SignerSet,
|
SignerSet,
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
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 {
|
||||||
@@ -67,16 +76,19 @@ pub struct NostrRegistry {
|
|||||||
/// Nostr signer
|
/// Nostr signer
|
||||||
signer: Arc<CoopSigner>,
|
signer: Arc<CoopSigner>,
|
||||||
|
|
||||||
/// Local public keys
|
/// All local stored identities
|
||||||
npubs: Entity<Vec<PublicKey>>,
|
npubs: Entity<Vec<PublicKey>>,
|
||||||
|
|
||||||
/// App keys
|
/// Keys directory
|
||||||
|
key_dir: PathBuf,
|
||||||
|
|
||||||
|
/// Master app keys used for various operations.
|
||||||
///
|
///
|
||||||
/// Used for Nostr Connect and NIP-4e operations
|
/// Example: Nostr Connect and NIP-4e operations
|
||||||
app_keys: Keys,
|
app_keys: Keys,
|
||||||
|
|
||||||
/// Tasks for asynchronous operations
|
/// Tasks for asynchronous operations
|
||||||
tasks: Vec<Task<()>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventEmitter<StateEvent> for NostrRegistry {}
|
impl EventEmitter<StateEvent> for NostrRegistry {}
|
||||||
@@ -94,56 +106,57 @@ impl NostrRegistry {
|
|||||||
|
|
||||||
/// Create a new nostr instance
|
/// Create a new nostr instance
|
||||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
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
|
// Construct the nostr signer
|
||||||
let app_keys = get_or_init_app_keys().unwrap_or(Keys::generate());
|
|
||||||
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
|
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
|
||||||
|
|
||||||
// Construct the nostr npubs entity
|
// Get all local stored npubs
|
||||||
let npubs = cx.new(|_| vec![]);
|
let npubs = cx.new(|_| match Self::discover(&key_dir) {
|
||||||
|
Ok(npubs) => npubs,
|
||||||
// Construct the nostr gossip instance
|
Err(e) => {
|
||||||
let gossip = cx.foreground_executor().block_on(async move {
|
log::error!("Failed to discover npubs: {e}");
|
||||||
NostrGossipSqlite::open(config_dir().join("gossip"))
|
vec![]
|
||||||
.await
|
}
|
||||||
.expect("Failed to initialize gossip instance")
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Construct the nostr client builder
|
// Construct the nostr lmdb instance
|
||||||
let mut builder = ClientBuilder::default()
|
let lmdb = cx.foreground_executor().block_on(async move {
|
||||||
|
NostrLmdb::open(config_dir().join("nostr"))
|
||||||
|
.await
|
||||||
|
.expect("Failed to initialize database")
|
||||||
|
});
|
||||||
|
|
||||||
|
// Construct the nostr client
|
||||||
|
let client = ClientBuilder::default()
|
||||||
.signer(signer.clone())
|
.signer(signer.clone())
|
||||||
.gossip(gossip)
|
.database(lmdb)
|
||||||
|
.gossip(NostrGossipMemory::unbounded())
|
||||||
.automatic_authentication(false)
|
.automatic_authentication(false)
|
||||||
.verify_subscriptions(false)
|
.connect_timeout(Duration::from_secs(10))
|
||||||
.connect_timeout(Duration::from_secs(TIMEOUT))
|
|
||||||
.sleep_when_idle(SleepWhenIdle::Enabled {
|
.sleep_when_idle(SleepWhenIdle::Enabled {
|
||||||
timeout: Duration::from_secs(600),
|
timeout: Duration::from_secs(600),
|
||||||
});
|
})
|
||||||
|
.build();
|
||||||
// Add database if not in debug mode
|
|
||||||
if !cfg!(debug_assertions) {
|
|
||||||
// Construct the nostr lmdb instance
|
|
||||||
let lmdb = cx.foreground_executor().block_on(async move {
|
|
||||||
NostrLmdb::open(config_dir().join("nostr"))
|
|
||||||
.await
|
|
||||||
.expect("Failed to initialize database")
|
|
||||||
});
|
|
||||||
builder = builder.database(lmdb);
|
|
||||||
} else {
|
|
||||||
builder = builder.database(MemoryDatabase::unbounded())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build the nostr client
|
|
||||||
let client = builder.build();
|
|
||||||
|
|
||||||
// Run at the end of current cycle
|
// Run at the end of current cycle
|
||||||
cx.defer_in(window, |this, _window, cx| {
|
cx.defer_in(window, |this, _window, cx| {
|
||||||
this.connect(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 {
|
Self {
|
||||||
client,
|
client,
|
||||||
signer,
|
signer,
|
||||||
npubs,
|
npubs,
|
||||||
|
key_dir,
|
||||||
app_keys,
|
app_keys,
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
}
|
}
|
||||||
@@ -169,6 +182,33 @@ impl NostrRegistry {
|
|||||||
self.app_keys.clone()
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
/// Connect to the bootstrapping relays
|
/// Connect to the bootstrapping relays
|
||||||
fn connect(&mut self, cx: &mut Context<Self>) {
|
fn connect(&mut self, cx: &mut Context<Self>) {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
@@ -176,7 +216,18 @@ impl NostrRegistry {
|
|||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
// Add search relay to the relay pool
|
// Add search relay to the relay pool
|
||||||
for url in SEARCH_RELAYS.into_iter() {
|
for url in SEARCH_RELAYS.into_iter() {
|
||||||
client.add_relay(url).await?;
|
client
|
||||||
|
.add_relay(url)
|
||||||
|
.capabilities(RelayCapabilities::READ)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add indexer relay to the relay pool
|
||||||
|
for url in INDEXER_RELAYS.into_iter() {
|
||||||
|
client
|
||||||
|
.add_relay(url)
|
||||||
|
.capabilities(RelayCapabilities::DISCOVERY)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add bootstrap relay to the relay pool
|
// Add bootstrap relay to the relay pool
|
||||||
@@ -185,7 +236,10 @@ impl NostrRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Connect to all added relays
|
// Connect to all added relays
|
||||||
client.connect().await;
|
client
|
||||||
|
.connect()
|
||||||
|
.and_wait(Duration::from_secs(TIMEOUT))
|
||||||
|
.await;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
@@ -193,101 +247,142 @@ impl NostrRegistry {
|
|||||||
// Emit connecting event
|
// Emit connecting event
|
||||||
cx.emit(StateEvent::Connecting);
|
cx.emit(StateEvent::Connecting);
|
||||||
|
|
||||||
self.tasks
|
|
||||||
.push(cx.spawn(async move |this, cx| match task.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
cx.emit(StateEvent::Connected);
|
|
||||||
this.get_npubs(cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::Error(SharedString::from(e.to_string())));
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get all used npubs
|
|
||||||
fn get_npubs(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let npubs = self.npubs.downgrade();
|
|
||||||
|
|
||||||
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
|
|
||||||
let dir = config_dir().join("keys");
|
|
||||||
// Ensure keys directory exists
|
|
||||||
smol::fs::create_dir_all(&dir).await?;
|
|
||||||
|
|
||||||
let mut files = smol::fs::read_dir(&dir).await?;
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
while let Some(Ok(entry)) = files.next().await {
|
|
||||||
let metadata = entry.metadata().await?;
|
|
||||||
let modified_time = metadata.modified()?;
|
|
||||||
let name = entry
|
|
||||||
.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));
|
|
||||||
|
|
||||||
let mut npubs = Vec::new();
|
|
||||||
|
|
||||||
for (_, name) in entries {
|
|
||||||
let public_key = PublicKey::parse(&name)?;
|
|
||||||
npubs.push(public_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(npubs)
|
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
match task.await {
|
if let Err(e) = task.await {
|
||||||
Ok(public_keys) => match public_keys.is_empty() {
|
this.update(cx, |_this, cx| {
|
||||||
true => {
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
this.update(cx, |this, cx| {
|
})?;
|
||||||
this.create_identity(cx);
|
} else {
|
||||||
})
|
this.update(cx, |_this, cx| {
|
||||||
.ok();
|
cx.emit(StateEvent::Connected);
|
||||||
}
|
})?;
|
||||||
false => {
|
|
||||||
// TODO: auto login
|
|
||||||
npubs
|
|
||||||
.update(cx, |this, cx| {
|
|
||||||
this.extend(public_keys);
|
|
||||||
cx.notify();
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::Error(SharedString::from(e.to_string())));
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
/// Create a new identity
|
||||||
fn create_identity(&mut self, cx: &mut Context<Self>) {
|
pub fn create_identity(&mut self, cx: &mut Context<Self>) {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
let keys = Keys::generate();
|
let keys = Keys::generate();
|
||||||
let async_keys = keys.clone();
|
let async_keys = keys.clone();
|
||||||
|
|
||||||
let username = keys.public_key().to_bech32().unwrap();
|
// Emit creating event
|
||||||
let secret = keys.secret_key().to_secret_bytes();
|
cx.emit(StateEvent::Creating);
|
||||||
|
|
||||||
// Create a write credential task
|
// Create the write secret task
|
||||||
let write_credential = cx.write_credentials(&username, &username, &secret);
|
let write_secret =
|
||||||
|
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
||||||
|
|
||||||
// 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 {
|
||||||
@@ -301,7 +396,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
|
||||||
@@ -333,14 +428,10 @@ impl NostrRegistry {
|
|||||||
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
|
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
|
||||||
|
|
||||||
// Publish messaging relay list event
|
// Publish messaging relay list event
|
||||||
client
|
client.send_event(&event).to_nip65().await?;
|
||||||
.send_event(&event)
|
|
||||||
.to_nip65()
|
|
||||||
.ack_policy(AckPolicy::none())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Write user's credentials to the system keyring
|
// Write user's credentials to the system keyring
|
||||||
write_credential.await?;
|
write_secret.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
@@ -350,58 +441,19 @@ impl NostrRegistry {
|
|||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
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(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the signer in keyring by username
|
|
||||||
pub fn get_signer(
|
|
||||||
&self,
|
|
||||||
public_key: &PublicKey,
|
|
||||||
cx: &App,
|
|
||||||
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
|
||||||
let username = public_key.to_bech32().unwrap();
|
|
||||||
let app_keys = self.app_keys.clone();
|
|
||||||
let read_credential = cx.read_credentials(&username);
|
|
||||||
|
|
||||||
cx.spawn(async move |_cx| {
|
|
||||||
let (_, secret) = read_credential
|
|
||||||
.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())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the signer for the nostr client and verify the public key
|
/// 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>)
|
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
|
||||||
where
|
where
|
||||||
@@ -420,15 +472,6 @@ impl NostrRegistry {
|
|||||||
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?;
|
||||||
|
|
||||||
let npub = public_key.to_bech32().unwrap();
|
|
||||||
let keys_dir = config_dir().join("keys");
|
|
||||||
|
|
||||||
// Ensure keys directory exists
|
|
||||||
smol::fs::create_dir_all(&keys_dir).await?;
|
|
||||||
|
|
||||||
let key_path = keys_dir.join(format!("{}.npub", npub));
|
|
||||||
smol::fs::write(key_path, "").await?;
|
|
||||||
|
|
||||||
log::info!("Signer's public key: {}", public_key);
|
log::info!("Signer's public key: {}", public_key);
|
||||||
Ok(public_key)
|
Ok(public_key)
|
||||||
});
|
});
|
||||||
@@ -436,9 +479,7 @@ impl NostrRegistry {
|
|||||||
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(public_key) => {
|
Ok(public_key) => {
|
||||||
// Update states
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.ensure_relay_list(&public_key, cx);
|
|
||||||
// Add public key to npubs if not already present
|
// Add public key to npubs if not already present
|
||||||
this.npubs.update(cx, |this, cx| {
|
this.npubs.update(cx, |this, cx| {
|
||||||
if !this.contains(&public_key) {
|
if !this.contains(&public_key) {
|
||||||
@@ -446,65 +487,43 @@ impl NostrRegistry {
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Emit signer changed event
|
// Emit signer changed event
|
||||||
cx.emit(StateEvent::SignerSet);
|
cx.emit(StateEvent::SignerSet);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove a signer from the keyring
|
Ok(())
|
||||||
pub fn remove_signer(&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");
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let key_path = keys_dir.join(format!("{}.npub", npub));
|
|
||||||
smol::fs::remove_file(key_path).await.ok();
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.npubs().update(cx, |this, cx| {
|
|
||||||
this.retain(|k| k != &public_key);
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add a key signer to keyring
|
/// Add a key signer to keyring
|
||||||
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
|
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
|
||||||
let keys = keys.clone();
|
let keys = keys.clone();
|
||||||
let username = keys.public_key().to_bech32().unwrap();
|
let write_secret =
|
||||||
let secret = keys.secret_key().to_secret_bytes();
|
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
||||||
|
|
||||||
// Write the credential to the keyring
|
|
||||||
let write_credential = cx.write_credentials(&username, "keys", &secret);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
match write_credential.await {
|
match write_secret.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
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(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,91 +544,35 @@ impl NostrRegistry {
|
|||||||
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((public_key, uri)) => {
|
Ok((public_key, uri)) => {
|
||||||
let username = public_key.to_bech32().unwrap();
|
// Create the write secret task
|
||||||
let write_credential = this
|
let write_secret = this.read_with(cx, |this, cx| {
|
||||||
.read_with(cx, |_this, cx| {
|
this.write_secret(public_key, uri.to_string(), cx)
|
||||||
cx.write_credentials(
|
})?;
|
||||||
&username,
|
|
||||||
"nostrconnect",
|
|
||||||
uri.to_string().as_bytes(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
match write_credential.await {
|
match write_secret.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(nip46, cx);
|
this.set_signer(nip46, cx);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ensure_relay_list(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
|
|
||||||
let task = self.get_event(public_key, Kind::RelayList, cx);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
match task.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::RelayConnected);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::RelayNotConfigured);
|
|
||||||
cx.emit(StateEvent::Error(SharedString::from(e.to_string())));
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get an event with the given author and kind.
|
|
||||||
pub fn get_event(
|
|
||||||
&self,
|
|
||||||
author: &PublicKey,
|
|
||||||
kind: Kind,
|
|
||||||
cx: &App,
|
|
||||||
) -> Task<Result<Event, Error>> {
|
|
||||||
let client = self.client();
|
|
||||||
let public_key = *author;
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
|
||||||
let filter = Filter::new().kind(kind).author(public_key).limit(1);
|
|
||||||
let mut stream = client
|
|
||||||
.stream_events(filter)
|
|
||||||
.timeout(Duration::from_millis(800))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
while let Some((_url, res)) = stream.next().await {
|
|
||||||
if let Ok(event) = res {
|
|
||||||
return Ok(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(anyhow!("No event found"))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the public key of a NIP-05 address
|
/// Get the public key of a NIP-05 address
|
||||||
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
@@ -657,11 +620,11 @@ impl NostrRegistry {
|
|||||||
let mut results: Vec<PublicKey> = Vec::with_capacity(FIND_LIMIT);
|
let mut results: Vec<PublicKey> = Vec::with_capacity(FIND_LIMIT);
|
||||||
|
|
||||||
// Return early if the query is a valid NIP-05 address
|
// Return early if the query is a valid NIP-05 address
|
||||||
if let Some(task) = address_task {
|
if let Some(task) = address_task
|
||||||
if let Ok(public_key) = task.await {
|
&& let Ok(public_key) = task.await
|
||||||
results.push(public_key);
|
{
|
||||||
return Ok(results);
|
results.push(public_key);
|
||||||
}
|
return Ok(results);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return early if the query is a valid public key
|
// Return early if the query is a valid public key
|
||||||
@@ -765,29 +728,33 @@ impl NostrRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get or create a new app keys
|
/// Get or create new app keys
|
||||||
fn get_or_init_app_keys() -> Result<Keys, Error> {
|
fn get_or_init_app_keys(cx: &App) -> Result<Keys, Error> {
|
||||||
let dir = config_dir().join(".app_keys");
|
let read = cx.read_credentials(CLIENT_NAME);
|
||||||
|
let stored_keys: Option<Keys> = cx.foreground_executor().block_on(async move {
|
||||||
let content = match std::fs::read(&dir) {
|
if let Ok(Some((_, secret))) = read.await {
|
||||||
Ok(content) => content,
|
SecretKey::from_slice(&secret).map(Keys::new).ok()
|
||||||
Err(_) => {
|
} else {
|
||||||
// Generate new keys if file doesn't exist
|
None
|
||||||
let keys = Keys::generate();
|
|
||||||
let secret_key = keys.secret_key();
|
|
||||||
|
|
||||||
// Create directory and write secret key
|
|
||||||
std::fs::create_dir_all(dir.parent().unwrap())?;
|
|
||||||
std::fs::write(&dir, secret_key.to_secret_bytes())?;
|
|
||||||
|
|
||||||
return Ok(keys);
|
|
||||||
}
|
}
|
||||||
};
|
});
|
||||||
|
|
||||||
let secret_key = SecretKey::from_slice(&content)?;
|
if let Some(keys) = stored_keys {
|
||||||
let keys = Keys::new(secret_key);
|
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);
|
||||||
|
|
||||||
Ok(keys)
|
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>)> {
|
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
|
||||||
@@ -819,7 +786,7 @@ fn default_messaging_relays() -> Vec<RelayUrl> {
|
|||||||
vec![
|
vec![
|
||||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
RelayUrl::parse("wss://nos.lol").unwrap(),
|
||||||
RelayUrl::parse("wss://nip17.com").unwrap(),
|
RelayUrl::parse("wss://nip17.com").unwrap(),
|
||||||
RelayUrl::parse("wss://relay.0xchat.com").unwrap(),
|
RelayUrl::parse("wss://auth.nostr1.com").unwrap(),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ impl CoopSigner {
|
|||||||
/// Get public key
|
/// Get public key
|
||||||
///
|
///
|
||||||
/// Ensure to call this method after the signer has been initialized.
|
/// Ensure to call this method after the signer has been initialized.
|
||||||
/// Otherwise, this method will panic.
|
/// Otherwise, it will panic.
|
||||||
pub fn public_key(&self) -> Option<PublicKey> {
|
pub fn public_key(&self) -> Option<PublicKey> {
|
||||||
*self.signer_pkey.read_blocking()
|
*self.signer_pkey.read_blocking()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -271,22 +271,22 @@ impl Dock {
|
|||||||
let mut right_dock_size = px(0.0);
|
let mut right_dock_size = px(0.0);
|
||||||
|
|
||||||
// Get the size of the left dock if it's open and not the current dock
|
// Get the size of the left dock if it's open and not the current dock
|
||||||
if let Some(left_dock) = &dock_area.left_dock {
|
if let Some(left_dock) = &dock_area.left_dock
|
||||||
if left_dock.entity_id() != cx.entity().entity_id() {
|
&& left_dock.entity_id() != cx.entity().entity_id()
|
||||||
let left_dock_read = left_dock.read(cx);
|
{
|
||||||
if left_dock_read.is_open() {
|
let left_dock_read = left_dock.read(cx);
|
||||||
left_dock_size = left_dock_read.size;
|
if left_dock_read.is_open() {
|
||||||
}
|
left_dock_size = left_dock_read.size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the size of the right dock if it's open and not the current dock
|
// Get the size of the right dock if it's open and not the current dock
|
||||||
if let Some(right_dock) = &dock_area.right_dock {
|
if let Some(right_dock) = &dock_area.right_dock
|
||||||
if right_dock.entity_id() != cx.entity().entity_id() {
|
&& right_dock.entity_id() != cx.entity().entity_id()
|
||||||
let right_dock_read = right_dock.read(cx);
|
{
|
||||||
if right_dock_read.is_open() {
|
let right_dock_read = right_dock.read(cx);
|
||||||
right_dock_size = right_dock_read.size;
|
if right_dock_read.is_open() {
|
||||||
}
|
right_dock_size = right_dock_read.size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -70,10 +70,10 @@ impl StackPanel {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(parent) = &self.parent {
|
if let Some(parent) = &self.parent
|
||||||
if let Some(parent) = parent.upgrade() {
|
&& let Some(parent) = parent.upgrade()
|
||||||
return parent.read(cx).is_last_panel(cx);
|
{
|
||||||
}
|
return parent.read(cx).is_last_panel(cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
@@ -297,12 +297,11 @@ impl StackPanel {
|
|||||||
|
|
||||||
/// Find the first top left in the stack.
|
/// Find the first top left in the stack.
|
||||||
pub fn left_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> {
|
pub fn left_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> {
|
||||||
if check_parent {
|
if check_parent
|
||||||
if let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade()) {
|
&& let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade())
|
||||||
if let Some(panel) = parent.read(cx).left_top_tab_panel(true, cx) {
|
&& let Some(panel) = parent.read(cx).left_top_tab_panel(true, cx)
|
||||||
return Some(panel);
|
{
|
||||||
}
|
return Some(panel);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let first_panel = self.panels.first();
|
let first_panel = self.panels.first();
|
||||||
@@ -321,12 +320,11 @@ impl StackPanel {
|
|||||||
|
|
||||||
/// Find the first top right in the stack.
|
/// Find the first top right in the stack.
|
||||||
pub fn right_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> {
|
pub fn right_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> {
|
||||||
if check_parent {
|
if check_parent
|
||||||
if let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade()) {
|
&& let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade())
|
||||||
if let Some(panel) = parent.read(cx).right_top_tab_panel(true, cx) {
|
&& let Some(panel) = parent.read(cx).right_top_tab_panel(true, cx)
|
||||||
return Some(panel);
|
{
|
||||||
}
|
return Some(panel);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let panel = if self.axis.is_vertical() {
|
let panel = if self.axis.is_vertical() {
|
||||||
|
|||||||
@@ -232,14 +232,13 @@ impl TabPanel {
|
|||||||
.any(|p| p.panel_id(cx) == panel.panel_id(cx))
|
.any(|p| p.panel_id(cx) == panel.panel_id(cx))
|
||||||
{
|
{
|
||||||
// Set the active panel to the matched panel
|
// Set the active panel to the matched panel
|
||||||
if active {
|
if active
|
||||||
if let Some(ix) = self
|
&& let Some(ix) = self
|
||||||
.panels
|
.panels
|
||||||
.iter()
|
.iter()
|
||||||
.position(|p| p.panel_id(cx) == panel.panel_id(cx))
|
.position(|p| p.panel_id(cx) == panel.panel_id(cx))
|
||||||
{
|
{
|
||||||
self.set_active_ix(ix, window, cx);
|
self.set_active_ix(ix, window, cx);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
@@ -372,12 +371,11 @@ impl TabPanel {
|
|||||||
|
|
||||||
/// Return true if self or parent only have last panel.
|
/// Return true if self or parent only have last panel.
|
||||||
fn is_last_panel(&self, cx: &App) -> bool {
|
fn is_last_panel(&self, cx: &App) -> bool {
|
||||||
if let Some(parent) = &self.stack_panel {
|
if let Some(parent) = &self.stack_panel
|
||||||
if let Some(stack_panel) = parent.upgrade() {
|
&& let Some(stack_panel) = parent.upgrade()
|
||||||
if !stack_panel.read(cx).is_last_panel(cx) {
|
&& !stack_panel.read(cx).is_last_panel(cx)
|
||||||
return false;
|
{
|
||||||
}
|
return false;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.panels.len() <= 1
|
self.panels.len() <= 1
|
||||||
@@ -1103,10 +1101,10 @@ impl TabPanel {
|
|||||||
window: &mut Window,
|
window: &mut Window,
|
||||||
cx: &mut Context<Self>,
|
cx: &mut Context<Self>,
|
||||||
) {
|
) {
|
||||||
if self.panels.len() > 1 {
|
if self.panels.len() > 1
|
||||||
if let Some(panel) = self.active_panel(cx) {
|
&& let Some(panel) = self.active_panel(cx)
|
||||||
self.remove_panel(&panel, window, cx);
|
{
|
||||||
}
|
self.remove_panel(&panel, window, cx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ use std::ops::Range;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use gpui::{
|
use gpui::{
|
||||||
fill, point, px, relative, size, App, Bounds, Corners, Element, ElementId, ElementInputHandler,
|
App, Bounds, Corners, Element, ElementId, ElementInputHandler, Entity, GlobalElementId, Hitbox,
|
||||||
Entity, GlobalElementId, Hitbox, IntoElement, LayoutId, MouseButton, MouseMoveEvent, Path,
|
IntoElement, LayoutId, MouseButton, MouseMoveEvent, Path, Pixels, Point, ShapedLine,
|
||||||
Pixels, Point, ShapedLine, SharedString, Size, Style, TextAlign, TextRun, UnderlineStyle,
|
SharedString, Size, Style, TextAlign, TextRun, UnderlineStyle, Window, fill, point, px,
|
||||||
Window,
|
relative, size,
|
||||||
};
|
};
|
||||||
use rope::Rope;
|
use rope::Rope;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
@@ -348,10 +348,10 @@ impl TextElement {
|
|||||||
let mut rev_line_corners = line_corners.iter().rev().peekable();
|
let mut rev_line_corners = line_corners.iter().rev().peekable();
|
||||||
while let Some(corners) = rev_line_corners.next() {
|
while let Some(corners) = rev_line_corners.next() {
|
||||||
points.push(corners.top_left);
|
points.push(corners.top_left);
|
||||||
if let Some(next) = rev_line_corners.peek() {
|
if let Some(next) = rev_line_corners.peek()
|
||||||
if next.top_left.x > corners.top_left.x {
|
&& next.top_left.x > corners.top_left.x
|
||||||
points.push(point(next.top_left.x, corners.top_left.y));
|
{
|
||||||
}
|
points.push(point(next.top_left.x, corners.top_left.y));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -376,10 +376,10 @@ impl TextElement {
|
|||||||
) -> Option<Path<Pixels>> {
|
) -> Option<Path<Pixels>> {
|
||||||
let state = self.state.read(cx);
|
let state = self.state.read(cx);
|
||||||
let mut selected_range = state.selected_range;
|
let mut selected_range = state.selected_range;
|
||||||
if let Some(ime_marked_range) = &state.ime_marked_range {
|
if let Some(ime_marked_range) = &state.ime_marked_range
|
||||||
if !ime_marked_range.is_empty() {
|
&& !ime_marked_range.is_empty()
|
||||||
selected_range = (ime_marked_range.end..ime_marked_range.end).into();
|
{
|
||||||
}
|
selected_range = (ime_marked_range.end..ime_marked_range.end).into();
|
||||||
}
|
}
|
||||||
if selected_range.is_empty() {
|
if selected_range.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
@@ -830,11 +830,12 @@ impl Element for TextElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Paint blinking cursor
|
// Paint blinking cursor
|
||||||
if focused && show_cursor {
|
if focused
|
||||||
if let Some(mut cursor_bounds) = prepaint.cursor_bounds.take() {
|
&& show_cursor
|
||||||
cursor_bounds.origin.y += prepaint.cursor_scroll_offset.y;
|
&& let Some(mut cursor_bounds) = prepaint.cursor_bounds.take()
|
||||||
window.paint_quad(fill(cursor_bounds, cx.theme().cursor));
|
{
|
||||||
}
|
cursor_bounds.origin.y += prepaint.cursor_scroll_offset.y;
|
||||||
|
window.paint_quad(fill(cursor_bounds, cx.theme().cursor));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Paint line numbers
|
// Paint line numbers
|
||||||
|
|||||||
@@ -225,13 +225,12 @@ impl MaskPattern {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// check if the fraction part is valid
|
// check if the fraction part is valid
|
||||||
if let Some(frac) = frac_part {
|
if let Some(frac) = frac_part
|
||||||
if !frac
|
&& !frac
|
||||||
.chars()
|
.chars()
|
||||||
.all(|ch| ch.is_ascii_digit() || Some(ch) == *separator)
|
.all(|ch| ch.is_ascii_digit() || Some(ch) == *separator)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
@@ -255,10 +254,10 @@ impl MaskPattern {
|
|||||||
|
|
||||||
if token.is_sep() {
|
if token.is_sep() {
|
||||||
// If next token is match, it's valid
|
// If next token is match, it's valid
|
||||||
if let Some(next_token) = tokens.get(pos + 1) {
|
if let Some(next_token) = tokens.get(pos + 1)
|
||||||
if next_token.is_match(ch) {
|
&& next_token.is_match(ch)
|
||||||
return true;
|
{
|
||||||
}
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder as _;
|
use gpui::prelude::FluentBuilder as _;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
actions, div, point, px, Action, App, AppContext, Bounds, ClipboardItem, Context, Entity,
|
Action, App, AppContext, Bounds, ClipboardItem, Context, Entity, EntityInputHandler,
|
||||||
EntityInputHandler, EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement,
|
EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding,
|
||||||
KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
|
KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
|
||||||
ParentElement as _, Pixels, Point, Render, ScrollHandle, ScrollWheelEvent, SharedString,
|
Pixels, Point, Render, ScrollHandle, ScrollWheelEvent, SharedString, Styled as _, Subscription,
|
||||||
Styled as _, Subscription, UTF16Selection, Window, WrappedLine,
|
UTF16Selection, Window, WrappedLine, actions, div, point, px,
|
||||||
};
|
};
|
||||||
use lsp_types::Position;
|
use lsp_types::Position;
|
||||||
use rope::{OffsetUtf16, Rope};
|
use rope::{OffsetUtf16, Rope};
|
||||||
@@ -25,9 +25,9 @@ use super::mask_pattern::MaskPattern;
|
|||||||
use super::mode::{InputMode, TabSize};
|
use super::mode::{InputMode, TabSize};
|
||||||
use super::rope_ext::RopeExt;
|
use super::rope_ext::RopeExt;
|
||||||
use super::text_wrapper::{LineItem, TextWrapper};
|
use super::text_wrapper::{LineItem, TextWrapper};
|
||||||
|
use crate::Root;
|
||||||
use crate::history::History;
|
use crate::history::History;
|
||||||
use crate::input::element::RIGHT_MARGIN;
|
use crate::input::element::RIGHT_MARGIN;
|
||||||
use crate::Root;
|
|
||||||
|
|
||||||
#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
|
#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
|
||||||
#[action(namespace = input, no_json)]
|
#[action(namespace = input, no_json)]
|
||||||
@@ -521,16 +521,16 @@ impl InputState {
|
|||||||
let new_row = new_row as usize;
|
let new_row = new_row as usize;
|
||||||
if new_row >= last_layout.visible_range.start {
|
if new_row >= last_layout.visible_range.start {
|
||||||
let visible_row = new_row.saturating_sub(last_layout.visible_range.start);
|
let visible_row = new_row.saturating_sub(last_layout.visible_range.start);
|
||||||
if let Some(line) = last_layout.lines.get(visible_row) {
|
if let Some(line) = last_layout.lines.get(visible_row)
|
||||||
if let Ok(x) = line.closest_index_for_position(
|
&& let Ok(x) = line.closest_index_for_position(
|
||||||
Point {
|
Point {
|
||||||
x: preferred_x,
|
x: preferred_x,
|
||||||
y: px(0.),
|
y: px(0.),
|
||||||
},
|
},
|
||||||
last_layout.line_height,
|
last_layout.line_height,
|
||||||
) {
|
)
|
||||||
new_offset = line_start_offset + x;
|
{
|
||||||
}
|
new_offset = line_start_offset + x;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1355,10 +1355,10 @@ impl InputState {
|
|||||||
) {
|
) {
|
||||||
// If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
|
// If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
|
||||||
// Clear the marked range.
|
// Clear the marked range.
|
||||||
if let Some(ime_marked_range) = &self.ime_marked_range {
|
if let Some(ime_marked_range) = &self.ime_marked_range
|
||||||
if ime_marked_range.is_empty() {
|
&& ime_marked_range.is_empty()
|
||||||
self.ime_marked_range = None;
|
{
|
||||||
}
|
self.ime_marked_range = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.selecting = true;
|
self.selecting = true;
|
||||||
@@ -1842,23 +1842,21 @@ impl InputState {
|
|||||||
|
|
||||||
fn previous_boundary(&self, offset: usize) -> usize {
|
fn previous_boundary(&self, offset: usize) -> usize {
|
||||||
let mut offset = self.text.clip_offset(offset.saturating_sub(1), Bias::Left);
|
let mut offset = self.text.clip_offset(offset.saturating_sub(1), Bias::Left);
|
||||||
if let Some(ch) = self.text.char_at(offset) {
|
if let Some(ch) = self.text.char_at(offset)
|
||||||
if ch == '\r' {
|
&& ch == '\r'
|
||||||
offset -= 1;
|
{
|
||||||
}
|
offset -= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
offset
|
offset
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next_boundary(&self, offset: usize) -> usize {
|
fn next_boundary(&self, offset: usize) -> usize {
|
||||||
let mut offset = self.text.clip_offset(offset + 1, Bias::Right);
|
let mut offset = self.text.clip_offset(offset + 1, Bias::Right);
|
||||||
if let Some(ch) = self.text.char_at(offset) {
|
if let Some(ch) = self.text.char_at(offset)
|
||||||
if ch == '\r' {
|
&& ch == '\r'
|
||||||
offset += 1;
|
{
|
||||||
}
|
offset += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
offset
|
offset
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1927,10 +1925,10 @@ impl InputState {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(validate) = &self.validate {
|
if let Some(validate) = &self.validate
|
||||||
if !validate(new_text, cx) {
|
&& !validate(new_text, cx)
|
||||||
return false;
|
{
|
||||||
}
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.mask_pattern.is_valid(new_text) {
|
if !self.mask_pattern.is_valid(new_text) {
|
||||||
@@ -1979,19 +1977,19 @@ impl InputState {
|
|||||||
self.input_bounds = new_bounds;
|
self.input_bounds = new_bounds;
|
||||||
|
|
||||||
// Update text_wrapper wrap_width if changed.
|
// Update text_wrapper wrap_width if changed.
|
||||||
if let Some(last_layout) = self.last_layout.as_ref() {
|
if let Some(last_layout) = self.last_layout.as_ref()
|
||||||
if wrap_width_changed {
|
&& wrap_width_changed
|
||||||
let wrap_width = if !self.soft_wrap {
|
{
|
||||||
// None to disable wrapping (will use Pixels::MAX)
|
let wrap_width = if !self.soft_wrap {
|
||||||
None
|
// None to disable wrapping (will use Pixels::MAX)
|
||||||
} else {
|
None
|
||||||
last_layout.wrap_width
|
} else {
|
||||||
};
|
last_layout.wrap_width
|
||||||
|
};
|
||||||
|
|
||||||
self.text_wrapper.set_wrap_width(wrap_width, cx);
|
self.text_wrapper.set_wrap_width(wrap_width, cx);
|
||||||
self.mode.update_auto_grow(&self.text_wrapper);
|
self.mode.update_auto_grow(&self.text_wrapper);
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2209,20 +2207,18 @@ impl EntityInputHandler for InputState {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if start_origin.is_none() {
|
if start_origin.is_none()
|
||||||
if let Some(p) =
|
&& let Some(p) =
|
||||||
line.position_for_index(range.start.saturating_sub(index_offset), line_height)
|
line.position_for_index(range.start.saturating_sub(index_offset), line_height)
|
||||||
{
|
{
|
||||||
start_origin = Some(p + point(px(0.), y_offset));
|
start_origin = Some(p + point(px(0.), y_offset));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if end_origin.is_none() {
|
if end_origin.is_none()
|
||||||
if let Some(p) =
|
&& let Some(p) =
|
||||||
line.position_for_index(range.end.saturating_sub(index_offset), line_height)
|
line.position_for_index(range.end.saturating_sub(index_offset), line_height)
|
||||||
{
|
{
|
||||||
end_origin = Some(p + point(px(0.), y_offset));
|
end_origin = Some(p + point(px(0.), y_offset));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
index_offset += line.len() + 1;
|
index_offset += line.len() + 1;
|
||||||
|
|||||||
@@ -3,21 +3,21 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
div, px, size, uniform_list, App, AppContext, AvailableSpace, ClickEvent, Context,
|
App, AppContext, AvailableSpace, ClickEvent, Context, DefiniteLength, EdgesRefinement, Entity,
|
||||||
DefiniteLength, EdgesRefinement, Entity, EventEmitter, FocusHandle, Focusable,
|
EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding, Length,
|
||||||
InteractiveElement, IntoElement, KeyBinding, Length, ListSizingBehavior, MouseButton,
|
ListSizingBehavior, MouseButton, ParentElement, Render, RenderOnce, ScrollStrategy,
|
||||||
ParentElement, Render, RenderOnce, ScrollStrategy, SharedString, StatefulInteractiveElement,
|
SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Task,
|
||||||
StyleRefinement, Styled, Subscription, Task, UniformListScrollHandle, Window,
|
UniformListScrollHandle, Window, div, px, size, uniform_list,
|
||||||
};
|
};
|
||||||
use smol::Timer;
|
use smol::Timer;
|
||||||
use theme::ActiveTheme;
|
use theme::ActiveTheme;
|
||||||
|
|
||||||
use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
|
use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
|
||||||
use crate::input::{InputEvent, InputState, TextInput};
|
use crate::input::{InputEvent, InputState, TextInput};
|
||||||
use crate::list::cache::{MeasuredEntrySize, RowEntry, RowsCache};
|
|
||||||
use crate::list::ListDelegate;
|
use crate::list::ListDelegate;
|
||||||
|
use crate::list::cache::{MeasuredEntrySize, RowEntry, RowsCache};
|
||||||
use crate::scroll::{Scrollbar, ScrollbarHandle};
|
use crate::scroll::{Scrollbar, ScrollbarHandle};
|
||||||
use crate::{v_flex, Icon, IconName, IndexPath, Selectable, Sizable, Size, StyledExt};
|
use crate::{Icon, IconName, IndexPath, Selectable, Sizable, Size, StyledExt, v_flex};
|
||||||
|
|
||||||
pub(crate) fn init(cx: &mut App) {
|
pub(crate) fn init(cx: &mut App) {
|
||||||
let context: Option<&str> = Some("List");
|
let context: Option<&str> = Some("List");
|
||||||
@@ -578,10 +578,10 @@ where
|
|||||||
self.prepare_items_if_needed(window, cx);
|
self.prepare_items_if_needed(window, cx);
|
||||||
|
|
||||||
// Scroll to the selected item if it is set.
|
// Scroll to the selected item if it is set.
|
||||||
if let Some((ix, strategy)) = self.deferred_scroll_to_index.take() {
|
if let Some((ix, strategy)) = self.deferred_scroll_to_index.take()
|
||||||
if let Some(item_ix) = self.rows_cache.position_of(&ix) {
|
&& let Some(item_ix) = self.rows_cache.position_of(&ix)
|
||||||
self.scroll_handle.scroll_to_item(item_ix, strategy);
|
{
|
||||||
}
|
self.scroll_handle.scroll_to_item(item_ix, strategy);
|
||||||
}
|
}
|
||||||
|
|
||||||
let loading = self.delegate().loading(cx);
|
let loading = self.delegate().loading(cx);
|
||||||
|
|||||||
@@ -719,13 +719,13 @@ impl PopupMenu {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> {
|
pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> {
|
||||||
if let Some(ix) = self.selected_index {
|
if let Some(ix) = self.selected_index
|
||||||
if let Some(item) = self.menu_items.get(ix) {
|
&& let Some(item) = self.menu_items.get(ix)
|
||||||
return match item {
|
{
|
||||||
PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()),
|
return match item {
|
||||||
_ => None,
|
PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()),
|
||||||
};
|
_ => None,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
@@ -965,12 +965,11 @@ impl PopupMenu {
|
|||||||
cx: &mut Context<Self>,
|
cx: &mut Context<Self>,
|
||||||
) {
|
) {
|
||||||
// Do not dismiss, if click inside the parent menu
|
// Do not dismiss, if click inside the parent menu
|
||||||
if let Some(parent) = self.parent_menu.as_ref() {
|
if let Some(parent) = self.parent_menu.as_ref()
|
||||||
if let Some(parent) = parent.upgrade() {
|
&& let Some(parent) = parent.upgrade()
|
||||||
if parent.read(cx).bounds.contains(position) {
|
&& parent.read(cx).bounds.contains(position)
|
||||||
return;
|
{
|
||||||
}
|
return;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.dismiss(&Cancel, window, cx);
|
self.dismiss(&Cancel, window, cx);
|
||||||
|
|||||||
@@ -296,10 +296,10 @@ impl RenderOnce for Modal {
|
|||||||
let on_close = on_close.clone();
|
let on_close = on_close.clone();
|
||||||
|
|
||||||
move |_, window, cx| {
|
move |_, window, cx| {
|
||||||
if let Some(on_ok) = &on_ok {
|
if let Some(on_ok) = &on_ok
|
||||||
if !on_ok(&ClickEvent::default(), window, cx) {
|
&& !on_ok(&ClickEvent::default(), window, cx)
|
||||||
return;
|
{
|
||||||
}
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
on_close(&ClickEvent::default(), window, cx);
|
on_close(&ClickEvent::default(), window, cx);
|
||||||
|
|||||||
@@ -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,18 +290,18 @@ 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()
|
||||||
.map(|builder| builder(self, window, cx));
|
.map(|builder| builder(self, window, cx));
|
||||||
|
|
||||||
let action = self
|
let action = self.action_builder.clone().map(|builder| {
|
||||||
.action_builder
|
builder(self, window, cx)
|
||||||
.clone()
|
.xsmall()
|
||||||
.map(|builder| builder(self, window, cx).small().mr_3p5());
|
.primary()
|
||||||
|
.px_3()
|
||||||
|
.font_semibold()
|
||||||
|
});
|
||||||
|
|
||||||
let icon = match self.kind {
|
let icon = match self.kind {
|
||||||
None => self.icon.clone(),
|
None => self.icon.clone(),
|
||||||
@@ -312,6 +318,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 +339,32 @@ 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.gap_2()
|
||||||
|
.child(h_flex().w_full().flex_1().justify_end().child(action))
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
use gpui::{
|
use gpui::{
|
||||||
px, Along, App, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window,
|
Along, App, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px,
|
||||||
};
|
};
|
||||||
|
|
||||||
mod panel;
|
mod panel;
|
||||||
@@ -142,10 +142,10 @@ impl ResizableState {
|
|||||||
pub(crate) fn remove_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
|
pub(crate) fn remove_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
|
||||||
self.panels.remove(panel_ix);
|
self.panels.remove(panel_ix);
|
||||||
self.sizes.remove(panel_ix);
|
self.sizes.remove(panel_ix);
|
||||||
if let Some(resizing_panel_ix) = self.resizing_panel_ix {
|
if let Some(resizing_panel_ix) = self.resizing_panel_ix
|
||||||
if resizing_panel_ix > panel_ix {
|
&& resizing_panel_ix > panel_ix
|
||||||
self.resizing_panel_ix = Some(resizing_panel_ix - 1);
|
{
|
||||||
}
|
self.resizing_panel_ix = Some(resizing_panel_ix - 1);
|
||||||
}
|
}
|
||||||
self.adjust_to_container_size(cx);
|
self.adjust_to_container_size(cx);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ impl Root {
|
|||||||
pub fn render_notification_layer(
|
pub fn render_notification_layer(
|
||||||
window: &mut Window,
|
window: &mut Window,
|
||||||
cx: &mut App,
|
cx: &mut App,
|
||||||
) -> Option<impl IntoElement> {
|
) -> Option<impl IntoElement + use<>> {
|
||||||
let root = window.root::<Root>()??;
|
let root = window.root::<Root>()??;
|
||||||
|
|
||||||
Some(
|
Some(
|
||||||
@@ -105,7 +105,10 @@ impl Root {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Render the modal layer.
|
/// Render the modal layer.
|
||||||
pub fn render_modal_layer(window: &mut Window, cx: &mut App) -> Option<impl IntoElement> {
|
pub fn render_modal_layer(
|
||||||
|
window: &mut Window,
|
||||||
|
cx: &mut App,
|
||||||
|
) -> Option<impl IntoElement + use<>> {
|
||||||
let root = window.root::<Root>()??;
|
let root = window.root::<Root>()??;
|
||||||
let active_modals = root.read(cx).active_modals.clone();
|
let active_modals = root.read(cx).active_modals.clone();
|
||||||
|
|
||||||
@@ -139,10 +142,10 @@ impl Root {
|
|||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
if let Some(ix) = show_overlay_ix {
|
if let Some(ix) = show_overlay_ix
|
||||||
if let Some(modal) = modals.get_mut(ix) {
|
&& let Some(modal) = modals.get_mut(ix)
|
||||||
modal.overlay_visible = true;
|
{
|
||||||
}
|
modal.overlay_visible = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(div().children(modals))
|
Some(div().children(modals))
|
||||||
|
|||||||
14
flathub/.gitignore
vendored
Normal file
14
flathub/.gitignore
vendored
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# Generated files - do not commit to main repo
|
||||||
|
# These are generated by prepare-flathub.sh
|
||||||
|
vendor/
|
||||||
|
vendor.tar.gz
|
||||||
|
su.reya.coop.yml
|
||||||
|
su.reya.coop.metainfo.xml
|
||||||
|
release-info.xml
|
||||||
|
cargo-config.toml
|
||||||
|
build/
|
||||||
|
repo/
|
||||||
|
|
||||||
|
# Keep the README and this .gitignore
|
||||||
|
!README.md
|
||||||
|
!.gitignore
|
||||||
129
flathub/README.md
Normal file
129
flathub/README.md
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
# Flathub Submission for Coop
|
||||||
|
|
||||||
|
This directory contains the files needed to submit Coop to Flathub.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Flatpak installed
|
||||||
|
- `flatpak-builder` installed
|
||||||
|
- Rust/Cargo installed (for vendoring)
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
Run the preparation script from the repo root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./script/prepare-flathub.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
This will:
|
||||||
|
1. Vendor all Rust dependencies (crates.io + git)
|
||||||
|
2. Generate the metainfo.xml with proper release info
|
||||||
|
3. Create `su.reya.coop.yml` - the Flatpak manifest for Flathub
|
||||||
|
|
||||||
|
## Files Generated
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `su.reya.coop.yml` | Main Flatpak manifest (submit this to Flathub) |
|
||||||
|
| `su.reya.coop.metainfo.xml` | AppStream metadata with release info |
|
||||||
|
| `vendor.tar.gz` | Vendored Rust dependencies |
|
||||||
|
| `cargo-config.toml` | Cargo configuration for offline builds |
|
||||||
|
| `release-info.xml` | Release info snippet for metainfo |
|
||||||
|
|
||||||
|
## Testing Locally
|
||||||
|
|
||||||
|
Before submitting to Flathub, test the build:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd flathub
|
||||||
|
|
||||||
|
# Build and install locally
|
||||||
|
flatpak-builder --user --install --force-clean build su.reya.coop.yml
|
||||||
|
|
||||||
|
# Test the app
|
||||||
|
flatpak run su.reya.coop
|
||||||
|
|
||||||
|
# Run the Flathub linter (must pass!)
|
||||||
|
flatpak run --command=flatpak-builder-lint org.flatpak.Builder manifest su.reya.coop.yml
|
||||||
|
flatpak run --command=flatpak-builder-lint org.flatpak.Builder repo repo
|
||||||
|
```
|
||||||
|
|
||||||
|
## Submitting to Flathub
|
||||||
|
|
||||||
|
### 1. Prepare Your Release
|
||||||
|
|
||||||
|
Ensure you have:
|
||||||
|
- [ ] Committed all changes
|
||||||
|
- [ ] Tagged the release: `git tag -a v1.0.0-beta2 -m "Release v1.0.0-beta2"`
|
||||||
|
- [ ] Pushed the tag: `git push origin v1.0.0-beta2`
|
||||||
|
- [ ] Run `./script/prepare-flathub.sh` to regenerate files
|
||||||
|
|
||||||
|
### 2. Fork and Submit
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Fork https://github.com/flathub/flathub on GitHub first
|
||||||
|
|
||||||
|
# Clone your fork (use the new-pr branch!)
|
||||||
|
git clone --branch=new-pr git@github.com:YOUR_USERNAME/flathub.git
|
||||||
|
cd flathub
|
||||||
|
|
||||||
|
# Create a new branch
|
||||||
|
git checkout -b su.reya.coop
|
||||||
|
|
||||||
|
# Copy ONLY the manifest file from your project
|
||||||
|
cp /path/to/coop/flathub/su.reya.coop.yml .
|
||||||
|
|
||||||
|
# Commit and push
|
||||||
|
git add su.reya.coop.yml
|
||||||
|
git commit -m "Add su.reya.coop"
|
||||||
|
git push origin su.reya.coop
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Open Pull Request
|
||||||
|
|
||||||
|
1. Go to your fork on GitHub
|
||||||
|
2. Click "Compare & pull request"
|
||||||
|
3. **Important:** Set base branch to `new-pr` (not `master`!)
|
||||||
|
4. Fill in the PR template
|
||||||
|
5. Submit and wait for review
|
||||||
|
|
||||||
|
## What Happens Next?
|
||||||
|
|
||||||
|
1. Flathub's automated CI will build your app
|
||||||
|
2. A maintainer will review your submission
|
||||||
|
3. Once approved, a new repo `flathub/su.reya.coop` will be created
|
||||||
|
4. You'll get write access to maintain the app
|
||||||
|
5. Future updates: Push new commits to `flathub/su.reya.coop`
|
||||||
|
|
||||||
|
## Updating the App
|
||||||
|
|
||||||
|
To release a new version:
|
||||||
|
|
||||||
|
1. Update version in workspace `Cargo.toml`
|
||||||
|
2. Tag the new release: `git tag -a v1.0.0-beta3 -m "Release v1.0.0-beta3"`
|
||||||
|
3. Push the tag: `git push origin v1.0.0-beta3`
|
||||||
|
4. Run `./script/prepare-flathub.sh` to regenerate
|
||||||
|
5. Clone the flathub repo: `git clone https://github.com/flathub/su.reya.coop.git`
|
||||||
|
6. Update the manifest with new commit/tag and hashes
|
||||||
|
7. Submit PR to `flathub/su.reya.coop`
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Build fails with "network access not allowed"
|
||||||
|
- Make sure `CARGO_NET_OFFLINE=true` is set in the manifest
|
||||||
|
- Ensure `vendor.tar.gz` is properly extracted before building
|
||||||
|
|
||||||
|
### Linter complains about metainfo
|
||||||
|
- Ensure `su.reya.coop.metainfo.xml` has at least one `<release>` entry
|
||||||
|
- Check that screenshots are accessible URLs
|
||||||
|
|
||||||
|
### Missing dependencies
|
||||||
|
- If new git dependencies are added, re-run `prepare-flathub.sh`
|
||||||
|
- The script vendors all dependencies from `Cargo.lock`
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [Flathub Submission Docs](https://docs.flathub.org/docs/for-app-authors/submission)
|
||||||
|
- [Flatpak Manifest Reference](https://docs.flatpak.org/en/latest/manifests.html)
|
||||||
|
- [AppStream Metainfo Guide](https://www.freedesktop.org/software/appstream/docs/chap-Metadata.html)
|
||||||
@@ -8,4 +8,7 @@ targets = [
|
|||||||
"x86_64-unknown-linux-gnu",
|
"x86_64-unknown-linux-gnu",
|
||||||
"x86_64-pc-windows-msvc",
|
"x86_64-pc-windows-msvc",
|
||||||
"aarch64-pc-windows-msvc",
|
"aarch64-pc-windows-msvc",
|
||||||
|
"aarch64-apple-ios",
|
||||||
|
"aarch64-linux-android",
|
||||||
|
"wasm32-unknown-unknown"
|
||||||
]
|
]
|
||||||
|
|||||||
245
script/prepare-flathub
Executable file
245
script/prepare-flathub
Executable file
@@ -0,0 +1,245 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Prepare Flathub submission for Coop
|
||||||
|
# This script:
|
||||||
|
# 1. Vendors all Rust dependencies (crates.io + git)
|
||||||
|
# 2. Generates release info for metainfo.xml
|
||||||
|
# 3. Creates the Flathub manifest (su.reya.coop.yml)
|
||||||
|
#
|
||||||
|
# Usage: ./script/prepare-flathub [--release-date YYYY-MM-DD]
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
APP_ID="su.reya.coop"
|
||||||
|
APP_NAME="Coop"
|
||||||
|
REPO_URL="https://git.reya.su/reya/coop"
|
||||||
|
BRANDING_LIGHT="#FFE629"
|
||||||
|
BRANDING_DARK="#FFE629"
|
||||||
|
|
||||||
|
# Parse arguments
|
||||||
|
RELEASE_DATE=""
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case $1 in
|
||||||
|
--release-date)
|
||||||
|
RELEASE_DATE="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-h|--help)
|
||||||
|
echo "Usage: ${0##*/} [options]"
|
||||||
|
echo ""
|
||||||
|
echo "Options:"
|
||||||
|
echo " --release-date DATE Release date in YYYY-MM-DD format (default: today)"
|
||||||
|
echo " -h, --help Display this help and exit"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Unknown option: $1" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Get version from workspace
|
||||||
|
VERSION=$(script/get-crate-version coop)
|
||||||
|
if [[ -z "$RELEASE_DATE" ]]; then
|
||||||
|
RELEASE_DATE=$(date +%Y-%m-%d)
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Preparing Flathub submission for $APP_NAME v$VERSION ==="
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Create flathub directory
|
||||||
|
mkdir -p flathub
|
||||||
|
echo "[1/5] Created flathub/ directory"
|
||||||
|
|
||||||
|
# Step 2: Vendor all dependencies
|
||||||
|
echo "[2/5] Vendoring Rust dependencies..."
|
||||||
|
if [[ -d vendor ]]; then
|
||||||
|
echo " Removing old vendor directory..."
|
||||||
|
rm -rf vendor
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create cargo config for vendoring
|
||||||
|
mkdir -p .cargo
|
||||||
|
cat > .cargo/config.toml << 'EOF'
|
||||||
|
[source.crates-io]
|
||||||
|
replace-with = "vendored"
|
||||||
|
|
||||||
|
[source.vendored]
|
||||||
|
directory = "vendor"
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Vendor all dependencies (crates.io + git)
|
||||||
|
cargo vendor --locked vendor/
|
||||||
|
echo " Vendored dependencies to vendor/"
|
||||||
|
|
||||||
|
# Create tarball of vendored deps
|
||||||
|
tar -czf flathub/vendor.tar.gz vendor/
|
||||||
|
echo " Created flathub/vendor.tar.gz"
|
||||||
|
|
||||||
|
# Step 3: Generate release info for metainfo
|
||||||
|
echo "[3/5] Generating release info..."
|
||||||
|
cat > flathub/release-info.xml << EOF
|
||||||
|
<release version="${VERSION}" date="${RELEASE_DATE}">
|
||||||
|
<description>
|
||||||
|
<p>Release version ${VERSION}</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
EOF
|
||||||
|
echo " Created flathub/release-info.xml"
|
||||||
|
|
||||||
|
# Step 4: Generate the metainfo file with release info
|
||||||
|
echo "[4/5] Generating metainfo.xml..."
|
||||||
|
export APP_ID APP_NAME BRANDING_LIGHT BRANDING_DARK
|
||||||
|
cat crates/coop/resources/flatpak/coop.metainfo.xml.in | \
|
||||||
|
sed -e "/@release_info@/r flathub/release-info.xml" -e '/@release_info@/d' \
|
||||||
|
> flathub/${APP_ID}.metainfo.xml
|
||||||
|
echo " Created flathub/${APP_ID}.metainfo.xml"
|
||||||
|
|
||||||
|
# Step 5: Generate the Flatpak manifest
|
||||||
|
echo "[5/5] Generating Flatpak manifest..."
|
||||||
|
|
||||||
|
# Get current commit hash
|
||||||
|
COMMIT=$(git rev-parse HEAD)
|
||||||
|
|
||||||
|
# Generate the YAML manifest
|
||||||
|
cat > flathub/${APP_ID}.yml << 'MANIFEST_EOF'
|
||||||
|
id: su.reya.coop
|
||||||
|
runtime: org.freedesktop.Platform
|
||||||
|
runtime-version: "24.08"
|
||||||
|
sdk: org.freedesktop.Sdk
|
||||||
|
sdk-extensions:
|
||||||
|
- org.freedesktop.Sdk.Extension.rust-stable
|
||||||
|
- org.freedesktop.Sdk.Extension.llvm18
|
||||||
|
command: coop
|
||||||
|
finish-args:
|
||||||
|
- --talk-name=org.freedesktop.Flatpak
|
||||||
|
- --device=dri
|
||||||
|
- --share=ipc
|
||||||
|
- --share=network
|
||||||
|
- --socket=wayland
|
||||||
|
- --socket=fallback-x11
|
||||||
|
- --socket=pulseaudio
|
||||||
|
- --filesystem=host
|
||||||
|
|
||||||
|
build-options:
|
||||||
|
append-path: /usr/lib/sdk/rust-stable/bin:/usr/lib/sdk/llvm18/bin
|
||||||
|
env:
|
||||||
|
CC: clang
|
||||||
|
CXX: clang++
|
||||||
|
|
||||||
|
modules:
|
||||||
|
- name: coop
|
||||||
|
buildsystem: simple
|
||||||
|
build-options:
|
||||||
|
env:
|
||||||
|
CARGO_HOME: /run/build/coop/cargo
|
||||||
|
CARGO_NET_OFFLINE: "true"
|
||||||
|
RELEASE_VERSION: "@VERSION@"
|
||||||
|
build-commands:
|
||||||
|
# Setup vendored dependencies
|
||||||
|
- mkdir -p .cargo
|
||||||
|
- cp cargo-config.toml .cargo/config.toml
|
||||||
|
|
||||||
|
# Extract vendored deps
|
||||||
|
- tar -xzf vendor.tar.gz
|
||||||
|
|
||||||
|
# Build the project (entire workspace, then install coop binary)
|
||||||
|
- cargo build --release --offline --package coop
|
||||||
|
|
||||||
|
# Install binary
|
||||||
|
- install -Dm755 target/release/coop /app/bin/coop
|
||||||
|
|
||||||
|
# Install icons
|
||||||
|
- install -Dm644 crates/coop/resources/icon.png /app/share/icons/hicolor/512x512/apps/su.reya.coop.png
|
||||||
|
- install -Dm644 crates/coop/resources/icon@2x.png /app/share/icons/hicolor/1024x1024/apps/su.reya.coop.png
|
||||||
|
|
||||||
|
# Install desktop file
|
||||||
|
- |
|
||||||
|
export APP_ID="su.reya.coop"
|
||||||
|
export APP_ICON="su.reya.coop"
|
||||||
|
export APP_NAME="Coop"
|
||||||
|
export APP_CLI="coop"
|
||||||
|
export APP_ARGS="%U"
|
||||||
|
export DO_STARTUP_NOTIFY="true"
|
||||||
|
envsubst < crates/coop/resources/coop.desktop.in > coop.desktop
|
||||||
|
install -Dm644 coop.desktop /app/share/applications/su.reya.coop.desktop
|
||||||
|
|
||||||
|
# Install metainfo (use pre-generated one with release info)
|
||||||
|
- install -Dm644 su.reya.coop.metainfo.xml /app/share/metainfo/su.reya.coop.metainfo.xml
|
||||||
|
|
||||||
|
sources:
|
||||||
|
# Main source code - specific commit
|
||||||
|
- type: git
|
||||||
|
url: https://git.reya.su/reya/coop.git
|
||||||
|
commit: "@COMMIT@"
|
||||||
|
tag: "v@VERSION@"
|
||||||
|
|
||||||
|
# Vendored dependencies tarball (generated by this script)
|
||||||
|
- type: file
|
||||||
|
path: vendor.tar.gz
|
||||||
|
sha256: "@VENDOR_SHA256@"
|
||||||
|
|
||||||
|
# Pre-generated metainfo with release info
|
||||||
|
- type: file
|
||||||
|
path: su.reya.coop.metainfo.xml
|
||||||
|
sha256: "@METAINFO_SHA256@"
|
||||||
|
|
||||||
|
# Cargo config for vendoring
|
||||||
|
- type: file
|
||||||
|
path: cargo-config.toml
|
||||||
|
sha256: "@CARGO_CONFIG_SHA256@"
|
||||||
|
MANIFEST_EOF
|
||||||
|
|
||||||
|
# Calculate SHA256 hashes
|
||||||
|
VENDOR_SHA256=$(sha256sum flathub/vendor.tar.gz | cut -d' ' -f1)
|
||||||
|
METAINFO_SHA256=$(sha256sum flathub/${APP_ID}.metainfo.xml | cut -d' ' -f1)
|
||||||
|
|
||||||
|
# Create cargo-config.toml
|
||||||
|
mkdir -p flathub
|
||||||
|
cat > flathub/cargo-config.toml << 'EOF'
|
||||||
|
[source.crates-io]
|
||||||
|
replace-with = "vendored"
|
||||||
|
|
||||||
|
[source.vendored]
|
||||||
|
directory = "vendor"
|
||||||
|
EOF
|
||||||
|
CARGO_CONFIG_SHA256=$(sha256sum flathub/cargo-config.toml | cut -d' ' -f1)
|
||||||
|
|
||||||
|
# Substitute values into the manifest
|
||||||
|
sed -i \
|
||||||
|
-e "s/@VERSION@/${VERSION}/g" \
|
||||||
|
-e "s/@COMMIT@/${COMMIT}/g" \
|
||||||
|
-e "s/@VENDOR_SHA256@/${VENDOR_SHA256}/g" \
|
||||||
|
-e "s/@METAINFO_SHA256@/${METAINFO_SHA256}/g" \
|
||||||
|
-e "s/@CARGO_CONFIG_SHA256@/${CARGO_CONFIG_SHA256}/g" \
|
||||||
|
flathub/${APP_ID}.yml
|
||||||
|
|
||||||
|
echo " Created flathub/${APP_ID}.yml"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Flathub preparation complete! ==="
|
||||||
|
echo ""
|
||||||
|
echo "Files generated in flathub/:"
|
||||||
|
echo " - ${APP_ID}.yml # Main Flatpak manifest (submit this to Flathub)"
|
||||||
|
echo " - ${APP_ID}.metainfo.xml # AppStream metadata with release info"
|
||||||
|
echo " - vendor.tar.gz # Vendored Rust dependencies"
|
||||||
|
echo " - cargo-config.toml # Cargo configuration for vendoring"
|
||||||
|
echo " - release-info.xml # Release info snippet"
|
||||||
|
echo ""
|
||||||
|
echo "Next steps:"
|
||||||
|
echo " 1. Test the build locally:"
|
||||||
|
echo " cd flathub && flatpak-builder --user --install --force-clean build ${APP_ID}.yml"
|
||||||
|
echo ""
|
||||||
|
echo " 2. If build succeeds, submit to Flathub:"
|
||||||
|
echo " - Fork https://github.com/flathub/flathub"
|
||||||
|
echo " - Clone: git clone --branch=new-pr git@github.com:YOUR_USERNAME/flathub.git"
|
||||||
|
echo " - Copy ONLY ${APP_ID}.yml to the repo"
|
||||||
|
echo " - Submit PR against flathub/flathub:new-pr"
|
||||||
|
echo ""
|
||||||
|
echo "Note: Make sure you have:"
|
||||||
|
echo " - Committed all changes (commit: ${COMMIT})"
|
||||||
|
echo " - Tagged the release (tag: v${VERSION})"
|
||||||
|
echo " - Pushed the tag to GitHub"
|
||||||
Reference in New Issue
Block a user