wip
This commit is contained in:
543
Cargo.lock
generated
543
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
12
Cargo.toml
12
Cargo.toml
@@ -19,12 +19,12 @@ gpui_tokio = { git = "https://github.com/zed-industries/zed" }
|
|||||||
reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
||||||
|
|
||||||
# Nostr
|
# Nostr
|
||||||
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr", }
|
||||||
nostr-connect = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr-blossom = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr", rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ], rev = "46d66396467e07c3dfb71e5102104ecb7e9c6b64" }
|
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44" ] }
|
||||||
|
|
||||||
# Others
|
# Others
|
||||||
anyhow = "1.0.44"
|
anyhow = "1.0.44"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ use gpui::{
|
|||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use smol::lock::RwLock;
|
use smol::lock::RwLock;
|
||||||
use state::{CoopSigner, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, USER_GIFTWRAP};
|
use state::{DEVICE_GIFTWRAP, NostrRegistry, USER_GIFTWRAP};
|
||||||
|
|
||||||
mod message;
|
mod message;
|
||||||
mod room;
|
mod room;
|
||||||
@@ -137,15 +137,17 @@ 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 user_signer = nostr.read(cx).signer.clone();
|
||||||
|
|
||||||
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.observe(&user_signer, |this, signer, cx| {
|
||||||
if event == &StateEvent::SignerSet {
|
if let Some(keys) = signer.read(cx).clone() {
|
||||||
this.reset(cx);
|
this.reset(cx);
|
||||||
|
this.handle_notifications(keys, cx);
|
||||||
this.get_metadata(cx);
|
this.get_metadata(cx);
|
||||||
this.get_rooms(cx);
|
this.get_rooms(cx);
|
||||||
};
|
};
|
||||||
@@ -154,7 +156,6 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
// Run at the end of the current cycle
|
// Run at the end of the current cycle
|
||||||
cx.defer_in(window, |this, _window, cx| {
|
cx.defer_in(window, |this, _window, cx| {
|
||||||
this.handle_notifications(cx);
|
|
||||||
this.tracking(cx);
|
this.tracking(cx);
|
||||||
this.get_rooms(cx);
|
this.get_rooms(cx);
|
||||||
});
|
});
|
||||||
@@ -174,10 +175,9 @@ impl ChatRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Handle nostr notifications
|
/// Handle nostr notifications
|
||||||
fn handle_notifications(&mut self, cx: &mut Context<Self>) {
|
fn handle_notifications(&mut self, signer: Keys, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
let tracking = self.tracking.clone();
|
let tracking = self.tracking.clone();
|
||||||
let msg_relays_existed = self.msg_relays_existed.clone();
|
let msg_relays_existed = self.msg_relays_existed.clone();
|
||||||
@@ -219,7 +219,7 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
// Handle msg relays event to determine when the app is ready to subscribe
|
// Handle msg relays event to determine when the app is ready to subscribe
|
||||||
if event.kind == Kind::InboxRelays {
|
if event.kind == Kind::InboxRelays {
|
||||||
let current_user = signer.get_public_key().await?;
|
let current_user = signer.get_public_key_async().await?;
|
||||||
|
|
||||||
if event.pubkey == current_user {
|
if event.pubkey == current_user {
|
||||||
// Mark that the msg relays have been found
|
// Mark that the msg relays have been found
|
||||||
@@ -265,10 +265,10 @@ impl ChatRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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?;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@@ -337,9 +337,8 @@ impl ChatRegistry {
|
|||||||
pub fn get_metadata(&mut self, cx: &mut Context<Self>) {
|
pub fn get_metadata(&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 Some(public_key) = signer.public_key() else {
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -392,11 +391,14 @@ impl ChatRegistry {
|
|||||||
fn get_messages(&mut self, msg_relays: &Event, cx: &mut Context<Self>) {
|
fn get_messages(&mut self, msg_relays: &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 signer = nostr.read(cx).signer();
|
let urls: Vec<RelayUrl> = nip17::extract_relay_list(msg_relays).collect();
|
||||||
let urls: Vec<RelayUrl> = nip17::extract_relay_list(msg_relays).cloned().collect();
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key_async().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(format!("{}-msg", public_key.to_hex()));
|
let id = SubscriptionId::new(format!("{}-msg", public_key.to_hex()));
|
||||||
|
|
||||||
@@ -510,11 +512,12 @@ impl ChatRegistry {
|
|||||||
I: Into<Room> + 'static,
|
I: Into<Room> + 'static,
|
||||||
{
|
{
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
|
||||||
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let signer = client.signer()?;
|
|
||||||
let public_key = signer.get_public_key().await.ok()?;
|
|
||||||
let room: Room = room.into().organize(&public_key);
|
let room: Room = room.into().organize(&public_key);
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
@@ -643,10 +646,11 @@ impl ChatRegistry {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
return Task::ready(Err(anyhow!("Signer is required")));
|
||||||
let public_key = signer.get_public_key().await?;
|
};
|
||||||
|
|
||||||
|
cx.background_spawn(async move {
|
||||||
// Get contacts
|
// Get contacts
|
||||||
let contacts = client
|
let contacts = client
|
||||||
.database()
|
.database()
|
||||||
@@ -723,15 +727,15 @@ impl ChatRegistry {
|
|||||||
/// Updates room ordering based on the most recent messages.
|
/// Updates room ordering based on the most recent messages.
|
||||||
pub fn new_message(&mut self, message: NewMessage, cx: &mut Context<Self>) {
|
pub fn new_message(&mut self, message: NewMessage, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
match self.rooms.iter().find(|e| e.read(cx).id == message.room) {
|
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 && message.rumor.pubkey == public_key {
|
||||||
&& let Some(public_key) = signer.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);
|
||||||
@@ -760,7 +764,7 @@ 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,
|
||||||
signer: &Arc<CoopSigner>,
|
signer: &Keys,
|
||||||
gift_wrap: &Event,
|
gift_wrap: &Event,
|
||||||
) -> Result<UnsignedEvent, Error> {
|
) -> Result<UnsignedEvent, Error> {
|
||||||
// Try to get cached rumor first
|
// Try to get cached rumor first
|
||||||
@@ -784,8 +788,9 @@ async fn extract_rumor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Helper method to try unwrapping with different signers
|
/// Helper method to try unwrapping with different signers
|
||||||
async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
|
async fn try_unwrap(signer: &Keys, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
|
||||||
// Try with the device signer first
|
/*
|
||||||
|
* // Try with the device signer first
|
||||||
if let Some(signer) = signer.get_encryption_signer().await {
|
if let Some(signer) = signer.get_encryption_signer().await {
|
||||||
log::info!("trying with encryption key");
|
log::info!("trying with encryption key");
|
||||||
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, &signer).await {
|
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, &signer).await {
|
||||||
@@ -795,19 +800,17 @@ async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<Unwra
|
|||||||
|
|
||||||
// Fallback to the user's signer
|
// Fallback to the user's signer
|
||||||
let user_signer = signer.get().await;
|
let user_signer = signer.get().await;
|
||||||
let unwrapped = try_unwrap_with(gift_wrap, &user_signer).await?;
|
*/
|
||||||
|
let unwrapped = try_unwrap_with(gift_wrap, signer).await?;
|
||||||
|
|
||||||
Ok(unwrapped)
|
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<T>(gift_wrap: &Event, signer: &T) -> Result<UnwrappedGift, Error>
|
async fn try_unwrap_with(gift_wrap: &Event, signer: &Keys) -> Result<UnwrappedGift, Error> {
|
||||||
where
|
|
||||||
T: NostrSigner + 'static,
|
|
||||||
{
|
|
||||||
// Get the sealed event
|
// Get the sealed event
|
||||||
let seal = signer
|
let seal = signer
|
||||||
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)
|
.nip44_decrypt_async(&gift_wrap.pubkey, &gift_wrap.content)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Verify the sealed event
|
// Verify the sealed event
|
||||||
@@ -815,7 +818,10 @@ where
|
|||||||
seal.verify_with_ctx(&SECP256K1)?;
|
seal.verify_with_ctx(&SECP256K1)?;
|
||||||
|
|
||||||
// Get the rumor event
|
// Get the rumor event
|
||||||
let rumor = signer.nip44_decrypt(&seal.pubkey, &seal.content).await?;
|
let rumor = signer
|
||||||
|
.nip44_decrypt_async(&seal.pubkey, &seal.content)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let rumor = UnsignedEvent::from_json(rumor)?;
|
let rumor = UnsignedEvent::from_json(rumor)?;
|
||||||
|
|
||||||
Ok(UnwrappedGift {
|
Ok(UnwrappedGift {
|
||||||
@@ -836,26 +842,17 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
|
|||||||
tags.push(Tag::identifier(id));
|
tags.push(Tag::identifier(id));
|
||||||
|
|
||||||
// Add a reference to the rumor's author
|
// Add a reference to the rumor's author
|
||||||
tags.push(Tag::custom(
|
tags.push(Tag::custom("a", [author]));
|
||||||
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::A)),
|
|
||||||
[author],
|
|
||||||
));
|
|
||||||
|
|
||||||
// Add a conversation id
|
// Add a conversation id
|
||||||
tags.push(Tag::custom(
|
tags.push(Tag::custom("c", [conversation.to_string()]));
|
||||||
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::C)),
|
|
||||||
[conversation.to_string()],
|
|
||||||
));
|
|
||||||
|
|
||||||
// Add a reference to the rumor's id
|
// Add a reference to the rumor's id
|
||||||
tags.push(Tag::event(rumor_id));
|
tags.push(Tag::event(rumor_id));
|
||||||
|
|
||||||
// Add references to the rumor's participants
|
// Add references to the rumor's participants
|
||||||
for receiver in rumor.tags.public_keys().copied() {
|
for receiver in rumor.tags.public_keys() {
|
||||||
tags.push(Tag::custom(
|
tags.push(Tag::custom("P", [receiver]));
|
||||||
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::P)),
|
|
||||||
[receiver],
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert rumor to json
|
// Convert rumor to json
|
||||||
@@ -864,7 +861,7 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
|
|||||||
// Construct the event
|
// Construct the event
|
||||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
||||||
.tags(tags)
|
.tags(tags)
|
||||||
.sign(&Keys::generate())
|
.finalize_async(&Keys::generate())
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Save the event to the database
|
// Save the event to the database
|
||||||
@@ -890,7 +887,7 @@ async fn get_rumor(client: &Client, gift_wrap: EventId) -> Result<UnsignedEvent,
|
|||||||
/// Get the conversation ID for a given rumor (message).
|
/// Get the conversation ID for a given rumor (message).
|
||||||
fn conversation_id(rumor: &UnsignedEvent) -> u64 {
|
fn conversation_id(rumor: &UnsignedEvent) -> u64 {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
let mut pubkeys: Vec<PublicKey> = rumor.tags.public_keys().copied().collect();
|
let mut pubkeys: Vec<PublicKey> = rumor.tags.public_keys().collect();
|
||||||
pubkeys.push(rumor.pubkey);
|
pubkeys.push(rumor.pubkey);
|
||||||
pubkeys.sort();
|
pubkeys.sort();
|
||||||
pubkeys.dedup();
|
pubkeys.dedup();
|
||||||
|
|||||||
@@ -242,13 +242,13 @@ fn extract_mentions(content: &str) -> Vec<Mention> {
|
|||||||
fn extract_reply_ids(inner: &Tags) -> Vec<EventId> {
|
fn extract_reply_ids(inner: &Tags) -> Vec<EventId> {
|
||||||
let mut replies_to = vec![];
|
let mut replies_to = vec![];
|
||||||
|
|
||||||
for tag in inner.filter(TagKind::e()) {
|
for tag in inner.iter().filter(|tag| tag.kind() == "e") {
|
||||||
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
||||||
replies_to.push(id);
|
replies_to.push(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for tag in inner.filter(TagKind::q()) {
|
for tag in inner.iter().filter(|tag| tag.kind() == "q") {
|
||||||
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
||||||
replies_to.push(id);
|
replies_to.push(id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use anyhow::{Error, anyhow};
|
use anyhow::{Error, anyhow};
|
||||||
use common::EventExt;
|
use common::EventExt;
|
||||||
|
use device::DeviceRegistry;
|
||||||
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::*;
|
||||||
@@ -21,7 +22,7 @@ pub struct SendReport {
|
|||||||
pub receiver: PublicKey,
|
pub receiver: PublicKey,
|
||||||
pub gift_wrap_id: Option<EventId>,
|
pub gift_wrap_id: Option<EventId>,
|
||||||
pub error: Option<SharedString>,
|
pub error: Option<SharedString>,
|
||||||
pub output: Option<Output<EventId>>,
|
pub output: Option<Output<EventId, EventSendStatus>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SendReport {
|
impl SendReport {
|
||||||
@@ -41,7 +42,7 @@ impl SendReport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Set the output.
|
/// Set the output.
|
||||||
pub fn output(mut self, output: Output<EventId>) -> Self {
|
pub fn output(mut self, output: Output<EventId, EventSendStatus>) -> Self {
|
||||||
self.output = Some(output);
|
self.output = Some(output);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@@ -171,7 +172,8 @@ impl From<&UnsignedEvent> for Room {
|
|||||||
let members = val.extract_public_keys();
|
let members = val.extract_public_keys();
|
||||||
let subject = val
|
let subject = val
|
||||||
.tags
|
.tags
|
||||||
.find(TagKind::Subject)
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "subject")
|
||||||
.and_then(|tag| tag.content().map(|s| s.to_owned().into()));
|
.and_then(|tag| tag.content().map(|s| s.to_owned().into()));
|
||||||
|
|
||||||
Room {
|
Room {
|
||||||
@@ -205,7 +207,7 @@ impl Room {
|
|||||||
// WARNING: never sign this event
|
// WARNING: never sign this event
|
||||||
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, "")
|
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, "")
|
||||||
.tags(tags)
|
.tags(tags)
|
||||||
.build(author);
|
.finalize_unsigned(author);
|
||||||
|
|
||||||
// Ensure that the ID is set
|
// Ensure that the ID is set
|
||||||
event.ensure_id();
|
event.ensure_id();
|
||||||
@@ -425,7 +427,7 @@ impl Room {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
|
||||||
// Get current user's public key
|
// Get current user's public key
|
||||||
let sender = nostr.read(cx).signer().public_key()?;
|
let sender = nostr.read(cx).signer_pubkey(cx)?;
|
||||||
|
|
||||||
// Get all members, excluding the sender
|
// Get all members, excluding the sender
|
||||||
let members: Vec<Person> = self
|
let members: Vec<Person> = self
|
||||||
@@ -440,9 +442,7 @@ impl Room {
|
|||||||
|
|
||||||
// Add subject tag if present
|
// Add subject tag if present
|
||||||
if let Some(value) = self.subject.as_ref() {
|
if let Some(value) = self.subject.as_ref() {
|
||||||
tags.push(Tag::from_standardized_without_cell(TagStandard::Subject(
|
tags.push(Tag::custom("subject", vec![value.to_string()]));
|
||||||
value.to_string(),
|
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add all reply tags
|
// Add all reply tags
|
||||||
@@ -452,19 +452,20 @@ impl Room {
|
|||||||
|
|
||||||
// Add all receiver tags
|
// Add all receiver tags
|
||||||
for member in members.into_iter() {
|
for member in members.into_iter() {
|
||||||
tags.push(Tag::from_standardized_without_cell(
|
tags.push(
|
||||||
TagStandard::PublicKey {
|
Nip01Tag::PublicKey {
|
||||||
public_key: member.public_key(),
|
public_key: member.public_key(),
|
||||||
relay_url: member.messaging_relay_hint(),
|
relay_hint: member.messaging_relay_hint(),
|
||||||
alias: None,
|
}
|
||||||
uppercase: false,
|
.to_tag(),
|
||||||
},
|
);
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Construct a direct message rumor event
|
// Construct a direct message rumor event
|
||||||
// WARNING: never sign and send this event to relays
|
// WARNING: never sign and send this event to relays
|
||||||
let mut event = EventBuilder::new(kind, content).tags(tags).build(sender);
|
let mut event = EventBuilder::new(kind, content)
|
||||||
|
.tags(tags)
|
||||||
|
.finalize_unsigned(sender);
|
||||||
|
|
||||||
// Ensure that the ID is set
|
// Ensure that the ID is set
|
||||||
event.ensure_id();
|
event.ensure_id();
|
||||||
@@ -475,13 +476,18 @@ impl Room {
|
|||||||
/// Send rumor event to all members's messaging relays
|
/// Send rumor event to all members's messaging relays
|
||||||
pub fn send(&self, rumor: UnsignedEvent, cx: &App) -> Option<Task<Vec<SendReport>>> {
|
pub fn send(&self, rumor: UnsignedEvent, cx: &App) -> Option<Task<Vec<SendReport>>> {
|
||||||
let config = self.config.clone();
|
let config = self.config.clone();
|
||||||
let persons = PersonRegistry::global(cx);
|
|
||||||
|
let device = DeviceRegistry::global(cx);
|
||||||
|
let encryption_signer = device.read(cx).signer(cx);
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
// Get current user's public key
|
// Get current user's public key
|
||||||
let public_key = nostr.read(cx).signer().public_key()?;
|
let user_signer = nostr.read(cx).signer(cx)?;
|
||||||
|
let public_key = nostr.read(cx).signer_pubkey(cx)?;
|
||||||
|
|
||||||
|
let persons = PersonRegistry::global(cx);
|
||||||
let sender = persons.read(cx).get(&public_key, cx);
|
let sender = persons.read(cx).get(&public_key, cx);
|
||||||
|
|
||||||
// Get all members (excluding sender)
|
// Get all members (excluding sender)
|
||||||
@@ -496,9 +502,6 @@ impl Room {
|
|||||||
let signer_kind = config.signer_kind();
|
let signer_kind = config.signer_kind();
|
||||||
let backup = config.backup();
|
let backup = config.backup();
|
||||||
|
|
||||||
let user_signer = signer.get().await;
|
|
||||||
let encryption_signer = signer.get_encryption_signer().await;
|
|
||||||
|
|
||||||
let mut sents = 0;
|
let mut sents = 0;
|
||||||
let mut reports = Vec::new();
|
let mut reports = Vec::new();
|
||||||
|
|
||||||
@@ -592,17 +595,14 @@ impl Room {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to send a gift-wrapped event
|
// Helper function to send a gift-wrapped event
|
||||||
async fn send_gift_wrap<T>(
|
async fn send_gift_wrap(
|
||||||
client: &Client,
|
client: &Client,
|
||||||
signer: &T,
|
signer: &Keys,
|
||||||
receiver: &Person,
|
receiver: &Person,
|
||||||
rumor: &UnsignedEvent,
|
rumor: &UnsignedEvent,
|
||||||
config: &SignerKind,
|
config: &SignerKind,
|
||||||
) -> Result<SendReport, Error>
|
) -> Result<SendReport, Error> {
|
||||||
where
|
let k_tag = Tag::custom("k", vec!["14"]);
|
||||||
T: NostrSigner + 'static,
|
|
||||||
{
|
|
||||||
let k_tag = Tag::custom(TagKind::k(), vec!["14"]);
|
|
||||||
let mut extra_tags = vec![k_tag];
|
let mut extra_tags = vec![k_tag];
|
||||||
|
|
||||||
// Determine the receiver public key based on the config
|
// Determine the receiver public key based on the config
|
||||||
@@ -627,7 +627,10 @@ where
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Construct the gift wrap event
|
// Construct the gift wrap event
|
||||||
let event = EventBuilder::gift_wrap(signer, &receiver, rumor.clone(), extra_tags).await?;
|
let event = nip59::GiftWrapBuilder::new(receiver, rumor.clone())
|
||||||
|
.extra_tags(extra_tags)
|
||||||
|
.finalize_async(signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Send the gift wrap event and collect the report
|
// Send the gift wrap event and collect the report
|
||||||
let report = client
|
let report = client
|
||||||
|
|||||||
@@ -234,7 +234,7 @@ impl ChatPanel {
|
|||||||
match &*status {
|
match &*status {
|
||||||
SendStatus::Ok { id, relay } => {
|
SendStatus::Ok { id, relay } => {
|
||||||
if output.id() == id {
|
if output.id() == id {
|
||||||
output.success.insert(relay.clone());
|
output.success.insert(relay.clone(), EventSendStatus::Sent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SendStatus::Failed { id, relay, message } => {
|
SendStatus::Failed { id, relay, message } => {
|
||||||
@@ -1158,7 +1158,7 @@ impl ChatPanel {
|
|||||||
.text_xs()
|
.text_xs()
|
||||||
.font_semibold()
|
.font_semibold()
|
||||||
.line_height(relative(1.25))
|
.line_height(relative(1.25))
|
||||||
.child(SharedString::from(url.to_string())),
|
.child(SharedString::from(url.0.to_string())),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ impl EventExt for Event {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn extract_public_keys(&self) -> Vec<PublicKey> {
|
fn extract_public_keys(&self) -> Vec<PublicKey> {
|
||||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
|
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().collect();
|
||||||
public_keys.push(self.pubkey);
|
public_keys.push(self.pubkey);
|
||||||
|
|
||||||
public_keys.into_iter().unique().collect()
|
public_keys.into_iter().unique().collect()
|
||||||
@@ -46,7 +46,7 @@ impl EventExt for UnsignedEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn extract_public_keys(&self) -> Vec<PublicKey> {
|
fn extract_public_keys(&self) -> Vec<PublicKey> {
|
||||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
|
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().collect();
|
||||||
public_keys.push(self.pubkey);
|
public_keys.push(self.pubkey);
|
||||||
public_keys.into_iter().unique().sorted().collect()
|
public_keys.into_iter().unique().sorted().collect()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,6 +65,9 @@ pub struct DeviceRegistry {
|
|||||||
/// Whether an announcement has been made for this device
|
/// Whether an announcement has been made for this device
|
||||||
pub announcement_existed: Arc<AtomicBool>,
|
pub announcement_existed: Arc<AtomicBool>,
|
||||||
|
|
||||||
|
/// Signer
|
||||||
|
signer: Entity<Option<Keys>>,
|
||||||
|
|
||||||
/// Async tasks
|
/// Async tasks
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
|
|
||||||
@@ -87,7 +90,10 @@ 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 signer = cx.new(|_| None);
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
let user_signer = nostr.read(cx).signer.clone();
|
||||||
|
|
||||||
let settings = AppSettings::global(cx);
|
let settings = AppSettings::global(cx);
|
||||||
let is_nip4e_enabled = settings.read(cx).is_nip4e_enabled(cx);
|
let is_nip4e_enabled = settings.read(cx).is_nip4e_enabled(cx);
|
||||||
|
|
||||||
@@ -104,8 +110,8 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// Subscribe to nostr state events
|
// Subscribe to nostr state events
|
||||||
cx.subscribe(&nostr, move |this, _e, event, cx| {
|
cx.observe(&user_signer, move |this, signer, cx| {
|
||||||
if event == &StateEvent::SignerSet && is_nip4e_enabled {
|
if signer.read(cx).is_some() && is_nip4e_enabled {
|
||||||
this.get_announcement(cx);
|
this.get_announcement(cx);
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
@@ -116,6 +122,7 @@ impl DeviceRegistry {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
|
signer,
|
||||||
pending_request: false,
|
pending_request: false,
|
||||||
announcement_existed: Arc::new(AtomicBool::new(false)),
|
announcement_existed: Arc::new(AtomicBool::new(false)),
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
@@ -126,13 +133,15 @@ impl DeviceRegistry {
|
|||||||
fn handle_notifications(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn handle_notifications(&mut self, 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();
|
|
||||||
|
|
||||||
let announcement_existed = self.announcement_existed.clone();
|
let announcement_existed = self.announcement_existed.clone();
|
||||||
let (tx, rx) = flume::bounded::<Event>(100);
|
let (tx, rx) = flume::bounded::<Event>(100);
|
||||||
|
|
||||||
|
let Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
let current_user = signer.get_public_key().await?;
|
|
||||||
let mut notifications = client.notifications();
|
let mut notifications = client.notifications();
|
||||||
let mut processed_events = HashSet::new();
|
let mut processed_events = HashSet::new();
|
||||||
|
|
||||||
@@ -203,24 +212,18 @@ impl DeviceRegistry {
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the signer
|
||||||
|
pub fn signer(&self, cx: &App) -> Option<Keys> {
|
||||||
|
self.signer.read(cx).clone()
|
||||||
|
}
|
||||||
|
|
||||||
/// Set the decoupled encryption key for the current user
|
/// Set the decoupled encryption key for the current user
|
||||||
fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
|
fn set_signer(&mut self, new: Keys, cx: &mut Context<Self>) {
|
||||||
where
|
self.signer.update(cx, |this, cx| {
|
||||||
S: NostrSigner + 'static,
|
*this = Some(new);
|
||||||
{
|
cx.notify();
|
||||||
let nostr = NostrRegistry::global(cx);
|
});
|
||||||
let signer = nostr.read(cx).signer();
|
cx.emit(DeviceEvent::Set);
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
signer.set_encryption_signer(new).await;
|
|
||||||
|
|
||||||
// Notify the UI via event
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(DeviceEvent::Set);
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Backup the encryption's secret key to a file
|
/// Backup the encryption's secret key to a file
|
||||||
@@ -228,8 +231,12 @@ impl DeviceRegistry {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return Task::ready(Err(anyhow!("Signer is required")));
|
||||||
|
};
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let keys = get_keys(&client).await?;
|
let keys = get_keys(&client, &signer).await?;
|
||||||
let content = keys.secret_key().to_bech32()?;
|
let content = keys.secret_key().to_bech32()?;
|
||||||
|
|
||||||
smol::fs::write(path, &content).await?;
|
smol::fs::write(path, &content).await?;
|
||||||
@@ -242,16 +249,18 @@ impl DeviceRegistry {
|
|||||||
pub fn get_announcement(&mut self, cx: &mut Context<Self>) {
|
pub fn get_announcement(&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 Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
|
||||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||||
|
|
||||||
// Construct the filter for the device announcement event
|
// Construct the filter for the device announcement event
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::Custom(10044))
|
.kind(Kind::Custom(10044))
|
||||||
.author(public_key)
|
.author(current_user)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
client
|
client
|
||||||
@@ -319,15 +328,19 @@ impl DeviceRegistry {
|
|||||||
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();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return Task::ready(Err(anyhow!("Signer is required")));
|
||||||
|
};
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
// Construct an announcement event
|
// Construct an announcement event
|
||||||
let builder = EventBuilder::new(Kind::Custom(10044), "").tags(vec![
|
let event = EventBuilder::new(Kind::Custom(10044), "")
|
||||||
Tag::custom(TagKind::custom("n"), vec![n]),
|
.tags(vec![
|
||||||
Tag::client(CLIENT_NAME),
|
Tag::custom("n", vec![n]),
|
||||||
]);
|
Tag::custom("client", vec![CLIENT_NAME]),
|
||||||
|
])
|
||||||
// Sign the event with user's signer
|
.finalize_async(&signer)
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.await?;
|
||||||
|
|
||||||
// Publish announcement
|
// Publish announcement
|
||||||
client
|
client
|
||||||
@@ -337,7 +350,7 @@ impl DeviceRegistry {
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Save device keys to the database
|
// Save device keys to the database
|
||||||
set_keys(&client, &secret).await?;
|
set_keys(&client, &signer, &secret).await?;
|
||||||
|
|
||||||
Ok(keys)
|
Ok(keys)
|
||||||
})
|
})
|
||||||
@@ -348,12 +361,16 @@ impl DeviceRegistry {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
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
|
// 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 {
|
||||||
let keys = get_keys(&client).await?;
|
let keys = get_keys(&client, &signer).await?;
|
||||||
|
|
||||||
// Compare the public key from the announcement with the one from the database
|
// Compare the public key from the announcement with the one from the database
|
||||||
if keys.public_key() != device_pubkey {
|
if keys.public_key() != device_pubkey {
|
||||||
@@ -382,10 +399,13 @@ impl DeviceRegistry {
|
|||||||
fn wait_for_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 Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key_async().await?;
|
||||||
let id = SubscriptionId::new("dekey-requests");
|
let id = SubscriptionId::new("dekey-requests");
|
||||||
|
|
||||||
// Construct a filter for encryption key requests
|
// Construct a filter for encryption key requests
|
||||||
@@ -405,13 +425,16 @@ impl DeviceRegistry {
|
|||||||
pub 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 app_keys = nostr.read(cx).keys();
|
let app_keys = Keys::generate();
|
||||||
let app_pubkey = app_keys.public_key();
|
let app_pubkey = app_keys.public_key();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
let task: Task<Result<Option<Event>, 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_async().await?;
|
||||||
|
|
||||||
// Construct a filter to get the latest approval event
|
// Construct a filter to get the latest approval event
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
@@ -426,13 +449,13 @@ impl DeviceRegistry {
|
|||||||
// No approval event found, construct a request event
|
// No approval event found, construct a request event
|
||||||
None => {
|
None => {
|
||||||
// Construct an event for device key request
|
// Construct an event for device key request
|
||||||
let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
|
let event = EventBuilder::new(Kind::Custom(4454), "")
|
||||||
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
|
.tags(vec![
|
||||||
Tag::client(CLIENT_NAME),
|
Tag::custom("P", vec![app_pubkey]),
|
||||||
]);
|
Tag::custom("client", vec![CLIENT_NAME]),
|
||||||
|
])
|
||||||
// Sign the event with user's signer
|
.finalize_async(&signer)
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.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?;
|
||||||
@@ -468,12 +491,15 @@ impl DeviceRegistry {
|
|||||||
fn wait_for_approval(&mut self, cx: &mut Context<Self>) {
|
fn wait_for_approval(&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 Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
cx.emit(DeviceEvent::Requesting);
|
cx.emit(DeviceEvent::Requesting);
|
||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key_async().await?;
|
||||||
|
|
||||||
// Construct a filter for device key requests
|
// Construct a filter for device key requests
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
@@ -491,18 +517,19 @@ impl DeviceRegistry {
|
|||||||
/// Parse the approval event to get encryption key then set it
|
/// 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 = Keys::generate();
|
||||||
|
|
||||||
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
|
||||||
let master = event
|
let master = event
|
||||||
.tags
|
.tags
|
||||||
.find(TagKind::custom("P"))
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "P")
|
||||||
.and_then(|tag| tag.content())
|
.and_then(|tag| tag.content())
|
||||||
.and_then(|content| PublicKey::parse(content).ok())
|
.and_then(|content| PublicKey::parse(content).ok())
|
||||||
.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(&master, payload).await?;
|
let decrypted = app_keys.nip44_decrypt_async(&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,37 +559,42 @@ impl DeviceRegistry {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
// Get user's write relays
|
// Get user's write relays
|
||||||
let event = event.clone();
|
let event = event.clone();
|
||||||
let id: SharedString = event.id.to_hex().into();
|
let id: SharedString = event.id.to_hex().into();
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
// Get device keys
|
// Get device keys
|
||||||
let keys = get_keys(&client).await?;
|
let keys = get_keys(&client, &signer).await?;
|
||||||
let secret = keys.secret_key().to_secret_hex();
|
let secret = keys.secret_key().to_secret_hex();
|
||||||
|
|
||||||
// Extract the target public key from the event tags
|
// Extract the target public key from the event tags
|
||||||
let target = event
|
let target = event
|
||||||
.tags
|
.tags
|
||||||
.find(TagKind::custom("P"))
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "P")
|
||||||
.and_then(|tag| tag.content())
|
.and_then(|tag| tag.content())
|
||||||
.and_then(|content| PublicKey::parse(content).ok())
|
.and_then(|content| PublicKey::parse(content).ok())
|
||||||
.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 = keys.nip44_encrypt(&target, &secret).await?;
|
let payload = keys.nip44_encrypt_async(&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 event = EventBuilder::new(Kind::Custom(4455), payload)
|
||||||
Tag::custom(TagKind::custom("P"), vec![keys.public_key().to_hex()]),
|
.tags(vec![
|
||||||
Tag::public_key(target),
|
Tag::custom("P", vec![keys.public_key().to_hex()]),
|
||||||
]);
|
Tag::public_key(target),
|
||||||
|
])
|
||||||
// Sign the builder
|
.finalize_async(&signer)
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.await?;
|
||||||
|
|
||||||
// Send the response event to the user's relay list
|
// Send the response event to the user's relay list
|
||||||
client.send_event(&event).to_nip65().await?;
|
client.send_event(&event).to_nip65().await?;
|
||||||
@@ -713,18 +745,14 @@ impl DeviceRegistry {
|
|||||||
struct DeviceNotification;
|
struct DeviceNotification;
|
||||||
|
|
||||||
/// Encrypt and store device keys in the local database.
|
/// Encrypt and store device keys in the local database.
|
||||||
async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
|
async fn set_keys(client: &Client, signer: &Keys, secret: &str) -> Result<(), Error> {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
let public_key = signer.get_public_key_async().await?;
|
||||||
let public_key = signer.get_public_key().await?;
|
let content = signer.nip44_encrypt_async(&public_key, secret).await?;
|
||||||
|
|
||||||
// Encrypt the value
|
|
||||||
let content = signer.nip44_encrypt(&public_key, secret).await?;
|
|
||||||
|
|
||||||
// Construct the application data event
|
// Construct the application data event
|
||||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
|
||||||
.tag(Tag::identifier(IDENTIFIER))
|
.tag(Tag::identifier(IDENTIFIER))
|
||||||
.build(public_key)
|
.finalize_async(signer)
|
||||||
.sign(&Keys::generate())
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Save the event to the database
|
// Save the event to the database
|
||||||
@@ -734,9 +762,8 @@ async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get device keys from the local database.
|
/// Get device keys from the local database.
|
||||||
async fn get_keys(client: &Client) -> Result<Keys, Error> {
|
async fn get_keys(client: &Client, signer: &Keys) -> Result<Keys, Error> {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
let public_key = signer.get_public_key_async().await?;
|
||||||
let public_key = signer.get_public_key().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::ApplicationSpecificData)
|
.kind(Kind::ApplicationSpecificData)
|
||||||
@@ -744,7 +771,10 @@ async fn get_keys(client: &Client) -> Result<Keys, Error> {
|
|||||||
.author(public_key);
|
.author(public_key);
|
||||||
|
|
||||||
if let Some(event) = client.database().query(filter).await?.first() {
|
if let Some(event) = client.database().query(filter).await?.first() {
|
||||||
let content = signer.nip44_decrypt(&public_key, &event.content).await?;
|
let content = signer
|
||||||
|
.nip44_decrypt_async(&public_key, &event.content)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let secret = SecretKey::parse(&content)?;
|
let secret = SecretKey::parse(&content)?;
|
||||||
let keys = Keys::new(secret);
|
let keys = Keys::new(secret);
|
||||||
|
|
||||||
|
|||||||
@@ -242,7 +242,7 @@ impl PersonRegistry {
|
|||||||
|
|
||||||
/// Set messaging relays for a person
|
/// Set messaging relays for a person
|
||||||
fn set_messaging_relays(&mut self, event: &Event, cx: &mut App) {
|
fn set_messaging_relays(&mut self, event: &Event, cx: &mut App) {
|
||||||
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).cloned().collect();
|
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).collect();
|
||||||
|
|
||||||
if let Some(person) = self.persons.get(&event.pubkey) {
|
if let Some(person) = self.persons.get(&event.pubkey) {
|
||||||
person.update(cx, |person, cx| {
|
person.update(cx, |person, cx| {
|
||||||
|
|||||||
@@ -193,15 +193,20 @@ impl RelayAuth {
|
|||||||
fn auth(&self, req: &Arc<AuthRequest>, cx: &App) -> Task<Result<(), Error>> {
|
fn auth(&self, req: &Arc<AuthRequest>, 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 req = req.clone();
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return Task::ready(Err(anyhow!("Signer is required")));
|
||||||
|
};
|
||||||
|
|
||||||
// Get all pending events for the relay
|
// Get all pending events for the relay
|
||||||
|
let req = req.clone();
|
||||||
let pending_events = self.get_pending_events(req.url(), cx);
|
let pending_events = self.get_pending_events(req.url(), cx);
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
// Construct event
|
// Construct event
|
||||||
let builder = EventBuilder::auth(req.challenge(), req.url().clone());
|
let event = EventBuilder::auth(req.challenge(), req.url().clone())
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Get the event ID
|
// Get the event ID
|
||||||
let id = event.id;
|
let id = event.id;
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
use anyhow::{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::*;
|
||||||
@@ -15,13 +13,11 @@ mod blossom;
|
|||||||
mod constants;
|
mod constants;
|
||||||
mod nip05;
|
mod nip05;
|
||||||
mod nip4e;
|
mod nip4e;
|
||||||
mod signer;
|
|
||||||
|
|
||||||
pub use blossom::*;
|
pub use blossom::*;
|
||||||
pub use constants::*;
|
pub use constants::*;
|
||||||
pub use nip4e::*;
|
pub use nip4e::*;
|
||||||
pub use nip05::*;
|
pub use nip05::*;
|
||||||
pub use signer::*;
|
|
||||||
|
|
||||||
pub fn init(window: &mut Window, cx: &mut App) {
|
pub fn init(window: &mut Window, cx: &mut App) {
|
||||||
// rustls uses the `aws_lc_rs` provider by default
|
// rustls uses the `aws_lc_rs` provider by default
|
||||||
@@ -48,12 +44,6 @@ pub enum StateEvent {
|
|||||||
Connecting,
|
Connecting,
|
||||||
/// Connected to the bootstrapping relay
|
/// Connected to the bootstrapping relay
|
||||||
Connected,
|
Connected,
|
||||||
/// Creating the signer
|
|
||||||
Creating,
|
|
||||||
/// Show the identity dialog
|
|
||||||
Show,
|
|
||||||
/// A new signer has been set
|
|
||||||
SignerSet,
|
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
Error(SharedString),
|
Error(SharedString),
|
||||||
}
|
}
|
||||||
@@ -73,19 +63,8 @@ pub struct NostrRegistry {
|
|||||||
/// Nostr client
|
/// Nostr client
|
||||||
client: Client,
|
client: Client,
|
||||||
|
|
||||||
/// Nostr signer
|
/// Currently active signer
|
||||||
signer: Arc<CoopSigner>,
|
pub signer: Entity<Option<Keys>>,
|
||||||
|
|
||||||
/// All local stored identities
|
|
||||||
npubs: Entity<Vec<PublicKey>>,
|
|
||||||
|
|
||||||
/// Keys directory
|
|
||||||
key_dir: PathBuf,
|
|
||||||
|
|
||||||
/// Master app keys used for various operations.
|
|
||||||
///
|
|
||||||
/// Example: Nostr Connect and NIP-4e operations
|
|
||||||
app_keys: Keys,
|
|
||||||
|
|
||||||
/// Tasks for asynchronous operations
|
/// Tasks for asynchronous operations
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
@@ -106,20 +85,7 @@ 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 signer = cx.new(|_| None);
|
||||||
let app_keys = get_or_init_app_keys(cx).unwrap_or(Keys::generate());
|
|
||||||
|
|
||||||
// Construct the nostr signer
|
|
||||||
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
|
|
||||||
|
|
||||||
// Get all local stored npubs
|
|
||||||
let npubs = cx.new(|_| match Self::discover(&key_dir) {
|
|
||||||
Ok(npubs) => npubs,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to discover npubs: {e}");
|
|
||||||
vec![]
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Construct the nostr lmdb instance
|
// Construct the nostr lmdb instance
|
||||||
let lmdb = cx.foreground_executor().block_on(async move {
|
let lmdb = cx.foreground_executor().block_on(async move {
|
||||||
@@ -130,7 +96,6 @@ impl NostrRegistry {
|
|||||||
|
|
||||||
// Construct the nostr client
|
// Construct the nostr client
|
||||||
let client = ClientBuilder::default()
|
let client = ClientBuilder::default()
|
||||||
.signer(signer.clone())
|
|
||||||
.database(lmdb)
|
.database(lmdb)
|
||||||
.gossip(NostrGossipMemory::unbounded())
|
.gossip(NostrGossipMemory::unbounded())
|
||||||
.gossip_config(
|
.gossip_config(
|
||||||
@@ -139,7 +104,6 @@ impl NostrRegistry {
|
|||||||
.sync_idle_timeout(Duration::from_millis(100))
|
.sync_idle_timeout(Duration::from_millis(100))
|
||||||
.no_background_refresh(),
|
.no_background_refresh(),
|
||||||
)
|
)
|
||||||
.automatic_authentication(false)
|
|
||||||
.connect_timeout(Duration::from_secs(10))
|
.connect_timeout(Duration::from_secs(10))
|
||||||
.sleep_when_idle(SleepWhenIdle::Enabled {
|
.sleep_when_idle(SleepWhenIdle::Enabled {
|
||||||
timeout: Duration::from_secs(600),
|
timeout: Duration::from_secs(600),
|
||||||
@@ -149,22 +113,11 @@ impl NostrRegistry {
|
|||||||
// 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);
|
||||||
|
|
||||||
if this.npubs.read(cx).is_empty() {
|
|
||||||
// Create an identity if none exists
|
|
||||||
this.create_identity(cx);
|
|
||||||
} else {
|
|
||||||
// Show the account selector dialog
|
|
||||||
cx.emit(StateEvent::Show);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
client,
|
client,
|
||||||
signer,
|
signer,
|
||||||
npubs,
|
|
||||||
key_dir,
|
|
||||||
app_keys,
|
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -174,46 +127,22 @@ impl NostrRegistry {
|
|||||||
self.client.clone()
|
self.client.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the nostr signer
|
/// Get the signer
|
||||||
pub fn signer(&self) -> Arc<CoopSigner> {
|
pub fn signer(&self, cx: &App) -> Option<Keys> {
|
||||||
self.signer.clone()
|
self.signer.read(cx).clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the npubs entity
|
/// Get the public key of the signer
|
||||||
pub fn npubs(&self) -> Entity<Vec<PublicKey>> {
|
pub fn signer_pubkey(&self, cx: &App) -> Option<PublicKey> {
|
||||||
self.npubs.clone()
|
self.signer.read(cx).as_ref().map(|s| s.public_key())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the app keys
|
/// Set the signer to the given keys
|
||||||
pub fn keys(&self) -> Keys {
|
pub fn set_signer(&mut self, new_keys: Keys, cx: &mut Context<Self>) {
|
||||||
self.app_keys.clone()
|
self.signer.update(cx, |this, cx| {
|
||||||
}
|
*this = Some(new_keys);
|
||||||
|
cx.notify();
|
||||||
/// 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
|
||||||
@@ -258,278 +187,8 @@ impl NostrRegistry {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the secret for a given npub.
|
|
||||||
pub fn get_secret(
|
|
||||||
&self,
|
|
||||||
public_key: PublicKey,
|
|
||||||
cx: &App,
|
|
||||||
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
|
||||||
let npub = public_key.to_bech32().unwrap();
|
|
||||||
let key_path = self.key_dir.join(format!("{}.npub", npub));
|
|
||||||
let app_keys = self.app_keys.clone();
|
|
||||||
|
|
||||||
if let Ok(payload) = std::fs::read_to_string(key_path)
|
|
||||||
&& !payload.is_empty()
|
|
||||||
{
|
|
||||||
return 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())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Task::ready(Err(anyhow::anyhow!("No secret found")))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add a new npub to the keys directory
|
|
||||||
fn write_secret(
|
|
||||||
&self,
|
|
||||||
public_key: PublicKey,
|
|
||||||
secret: String,
|
|
||||||
cx: &App,
|
|
||||||
) -> Task<Result<(), Error>> {
|
|
||||||
let npub = public_key.to_bech32().unwrap();
|
|
||||||
let key_path = self.key_dir.join(format!("{}.npub", npub));
|
|
||||||
let app_keys = self.app_keys.clone();
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
|
||||||
// If the secret starts with "bunker://" (nostr connect), use it directly; otherwise, encrypt it
|
|
||||||
let content = if secret.starts_with("bunker://") {
|
|
||||||
secret
|
|
||||||
} else {
|
|
||||||
app_keys.nip44_encrypt(&public_key, &secret).await?
|
|
||||||
};
|
|
||||||
|
|
||||||
// Write the encrypted secret to the keys directory
|
|
||||||
smol::fs::write(key_path, &content).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove a secret
|
|
||||||
pub fn remove_secret(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
|
|
||||||
let public_key = public_key.to_owned();
|
|
||||||
let npub = public_key.to_bech32().unwrap();
|
|
||||||
|
|
||||||
let keys_dir = config_dir().join("keys");
|
|
||||||
let key_path = keys_dir.join(format!("{}.npub", npub));
|
|
||||||
|
|
||||||
// Remove the secret file from the keys directory
|
|
||||||
std::fs::remove_file(key_path).ok();
|
|
||||||
|
|
||||||
self.npubs.update(cx, |this, cx| {
|
|
||||||
this.retain(|k| k != &public_key);
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a new identity
|
|
||||||
pub fn create_identity(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let client = self.client();
|
|
||||||
let keys = Keys::generate();
|
|
||||||
let async_keys = keys.clone();
|
|
||||||
|
|
||||||
// Emit creating event
|
|
||||||
cx.emit(StateEvent::Creating);
|
|
||||||
|
|
||||||
// Create the write secret task
|
|
||||||
let write_secret =
|
|
||||||
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
|
||||||
|
|
||||||
// Run async tasks in background
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
|
||||||
let signer = async_keys.into_nostr_signer();
|
|
||||||
|
|
||||||
// Construct relay list event
|
|
||||||
let relay_list = default_relay_list();
|
|
||||||
let event = EventBuilder::relay_list(relay_list).sign(&signer).await?;
|
|
||||||
|
|
||||||
// Publish relay list
|
|
||||||
client
|
|
||||||
.send_event(&event)
|
|
||||||
.to(BOOTSTRAP_RELAYS)
|
|
||||||
.ack_policy(AckPolicy::none())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Construct the default metadata
|
|
||||||
let name = petname::petname(2, "-").unwrap_or("Cooper".to_string());
|
|
||||||
let avatar = Url::parse(&format!("https://avatar.vercel.sh/{name}")).unwrap();
|
|
||||||
let metadata = Metadata::new().display_name(&name).picture(avatar);
|
|
||||||
let event = EventBuilder::metadata(&metadata).sign(&signer).await?;
|
|
||||||
|
|
||||||
// Publish metadata event
|
|
||||||
client
|
|
||||||
.send_event(&event)
|
|
||||||
.to_nip65()
|
|
||||||
.ack_policy(AckPolicy::none())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Construct the default contact list
|
|
||||||
let contacts = vec![Contact::new(PublicKey::parse(COOP_PUBKEY).unwrap())];
|
|
||||||
let event = EventBuilder::contact_list(contacts).sign(&signer).await?;
|
|
||||||
|
|
||||||
// Publish contact list event
|
|
||||||
client
|
|
||||||
.send_event(&event)
|
|
||||||
.to_nip65()
|
|
||||||
.ack_policy(AckPolicy::none())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Construct the default messaging relay list
|
|
||||||
let relays = default_messaging_relays();
|
|
||||||
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
|
|
||||||
|
|
||||||
// Publish messaging relay list event
|
|
||||||
client.send_event(&event).to_nip65().await?;
|
|
||||||
|
|
||||||
// Write user's credentials to the system keyring
|
|
||||||
write_secret.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
match task.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_signer(keys, cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the signer for the nostr client and verify the public key
|
|
||||||
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
|
|
||||||
where
|
|
||||||
T: NostrSigner + 'static,
|
|
||||||
{
|
|
||||||
let client = self.client();
|
|
||||||
let signer = self.signer();
|
|
||||||
|
|
||||||
// Create a task to update the signer and verify the public key
|
|
||||||
let task: Task<Result<PublicKey, Error>> = cx.background_spawn(async move {
|
|
||||||
// Update signer and unsubscribe
|
|
||||||
signer.switch(new).await;
|
|
||||||
client.unsubscribe_all().await?;
|
|
||||||
|
|
||||||
// Verify and get public key
|
|
||||||
let signer = client.signer().context("Signer not found")?;
|
|
||||||
let public_key = signer.get_public_key().await?;
|
|
||||||
|
|
||||||
log::info!("Signer's public key: {}", public_key);
|
|
||||||
Ok(public_key)
|
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
match task.await {
|
|
||||||
Ok(public_key) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
// Add public key to npubs if not already present
|
|
||||||
this.npubs.update(cx, |this, cx| {
|
|
||||||
if !this.contains(&public_key) {
|
|
||||||
this.push(public_key);
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Emit signer changed event
|
|
||||||
cx.emit(StateEvent::SignerSet);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add a key signer to keyring
|
|
||||||
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
|
|
||||||
let keys = keys.clone();
|
|
||||||
let write_secret =
|
|
||||||
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
match write_secret.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_signer(keys, cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add a nostr connect signer to keyring
|
|
||||||
pub fn add_nip46_signer(&mut self, nip46: &NostrConnect, cx: &mut Context<Self>) {
|
|
||||||
let nip46 = nip46.clone();
|
|
||||||
let async_nip46 = nip46.clone();
|
|
||||||
|
|
||||||
// Connect and verify the remote signer
|
|
||||||
let task: Task<Result<(PublicKey, NostrConnectUri), Error>> =
|
|
||||||
cx.background_spawn(async move {
|
|
||||||
let uri = async_nip46.bunker_uri().await?;
|
|
||||||
let public_key = async_nip46.get_public_key().await?;
|
|
||||||
|
|
||||||
Ok((public_key, uri))
|
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
match task.await {
|
|
||||||
Ok((public_key, uri)) => {
|
|
||||||
// Create the write secret task
|
|
||||||
let write_secret = this.read_with(cx, |this, cx| {
|
|
||||||
this.write_secret(public_key, uri.to_string(), cx)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
match write_secret.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_signer(nip46, cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the public key of a NIP-05 address
|
/// Get the public key of a NIP-05 address
|
||||||
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
pub fn query_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
let http_client = cx.http_client();
|
let http_client = cx.http_client();
|
||||||
|
|
||||||
@@ -566,7 +225,7 @@ impl NostrRegistry {
|
|||||||
|
|
||||||
// Get the address task if the query is a valid NIP-05 address
|
// Get the address task if the query is a valid NIP-05 address
|
||||||
let address_task = if let Ok(addr) = Nip05Address::parse(&query) {
|
let address_task = if let Ok(addr) = Nip05Address::parse(&query) {
|
||||||
Some(self.get_address(addr, cx))
|
Some(self.query_address(addr, cx))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@@ -638,13 +297,19 @@ impl NostrRegistry {
|
|||||||
let client = self.client();
|
let client = self.client();
|
||||||
let query = query.to_string();
|
let query = query.to_string();
|
||||||
|
|
||||||
|
let Some(signer) = self.signer.read(cx).clone() else {
|
||||||
|
return Task::ready(Err(anyhow!("Signer is required")));
|
||||||
|
};
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
// Construct a vertex request event
|
// Construct a vertex request event
|
||||||
let builder = EventBuilder::new(Kind::Custom(5315), "").tags(vec![
|
let event = EventBuilder::new(Kind::Custom(5315), "")
|
||||||
Tag::custom(TagKind::custom("param"), vec!["search", &query]),
|
.tags(vec![
|
||||||
Tag::custom(TagKind::custom("param"), vec!["limit", "10"]),
|
Tag::custom("param", vec!["search", &query]),
|
||||||
]);
|
Tag::custom("param", vec!["limit", "10"]),
|
||||||
let event = client.sign_event_builder(builder).await?;
|
])
|
||||||
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Send the event to vertex relays
|
// Send the event to vertex relays
|
||||||
let output = client.send_event(&event).to(WOT_RELAYS).await?;
|
let output = client.send_event(&event).to(WOT_RELAYS).await?;
|
||||||
@@ -694,78 +359,3 @@ impl NostrRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get or create new app keys
|
|
||||||
fn get_or_init_app_keys(cx: &App) -> Result<Keys, Error> {
|
|
||||||
let read = cx.read_credentials(CLIENT_NAME);
|
|
||||||
let stored_keys: Option<Keys> = cx.foreground_executor().block_on(async move {
|
|
||||||
if let Ok(Some((_, secret))) = read.await {
|
|
||||||
SecretKey::from_slice(&secret).map(Keys::new).ok()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Some(keys) = stored_keys {
|
|
||||||
Ok(keys)
|
|
||||||
} else {
|
|
||||||
let keys = Keys::generate();
|
|
||||||
let user = keys.public_key().to_hex();
|
|
||||||
let secret = keys.secret_key().to_secret_bytes();
|
|
||||||
let write = cx.write_credentials(CLIENT_NAME, &user, &secret);
|
|
||||||
|
|
||||||
cx.foreground_executor().block_on(async move {
|
|
||||||
if let Err(e) = write.await {
|
|
||||||
log::error!("Keyring not available or panic: {e}")
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(keys)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
|
|
||||||
vec![
|
|
||||||
(
|
|
||||||
RelayUrl::parse("wss://relay.nostr.net").unwrap(),
|
|
||||||
Some(RelayMetadata::Write),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
RelayUrl::parse("wss://relay.primal.net").unwrap(),
|
|
||||||
Some(RelayMetadata::Write),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
RelayUrl::parse("wss://relay.damus.io").unwrap(),
|
|
||||||
Some(RelayMetadata::Read),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
|
||||||
Some(RelayMetadata::Read),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
RelayUrl::parse("wss://nostr.superfriends.online").unwrap(),
|
|
||||||
None,
|
|
||||||
),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_messaging_relays() -> Vec<RelayUrl> {
|
|
||||||
vec![
|
|
||||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
|
||||||
RelayUrl::parse("wss://nip17.com").unwrap(),
|
|
||||||
RelayUrl::parse("wss://auth.nostr1.com").unwrap(),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct CoopAuthUrlHandler;
|
|
||||||
|
|
||||||
impl AuthUrlHandler for CoopAuthUrlHandler {
|
|
||||||
#[allow(mismatched_lifetime_syntaxes)]
|
|
||||||
fn on_auth_url(&self, auth_url: Url) -> BoxedFuture<Result<()>> {
|
|
||||||
Box::pin(async move {
|
|
||||||
webbrowser::open(auth_url.as_str())?;
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -16,14 +16,15 @@ impl From<&Event> for Announcement {
|
|||||||
let public_key = val
|
let public_key = val
|
||||||
.tags
|
.tags
|
||||||
.iter()
|
.iter()
|
||||||
.find(|tag| tag.kind().as_str() == "n")
|
.find(|tag| tag.kind() == "n")
|
||||||
.and_then(|tag| tag.content())
|
.and_then(|tag| tag.content())
|
||||||
.and_then(|c| PublicKey::parse(c).ok())
|
.and_then(|c| PublicKey::parse(c).ok())
|
||||||
.unwrap_or(val.pubkey);
|
.unwrap_or(val.pubkey);
|
||||||
|
|
||||||
let client_name = val
|
let client_name = val
|
||||||
.tags
|
.tags
|
||||||
.find(TagKind::Client)
|
.iter()
|
||||||
|
.find(|tag| tag.kind() == "client")
|
||||||
.and_then(|tag| tag.content())
|
.and_then(|tag| tag.content())
|
||||||
.map(|c| c.to_string());
|
.map(|c| c.to_string());
|
||||||
|
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
use std::borrow::Cow;
|
|
||||||
use std::result::Result;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use nostr_sdk::prelude::*;
|
|
||||||
use smol::lock::RwLock;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct CoopSigner {
|
|
||||||
/// User's signer
|
|
||||||
signer: RwLock<Arc<dyn NostrSigner>>,
|
|
||||||
|
|
||||||
/// User's signer public key
|
|
||||||
signer_pkey: RwLock<Option<PublicKey>>,
|
|
||||||
|
|
||||||
/// Specific signer for encryption purposes
|
|
||||||
encryption_signer: RwLock<Option<Arc<dyn NostrSigner>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CoopSigner {
|
|
||||||
pub fn new<T>(signer: T) -> Self
|
|
||||||
where
|
|
||||||
T: IntoNostrSigner,
|
|
||||||
{
|
|
||||||
Self {
|
|
||||||
signer: RwLock::new(signer.into_nostr_signer()),
|
|
||||||
signer_pkey: RwLock::new(None),
|
|
||||||
encryption_signer: RwLock::new(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the current signer.
|
|
||||||
pub async fn get(&self) -> Arc<dyn NostrSigner> {
|
|
||||||
self.signer.read().await.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the encryption signer.
|
|
||||||
pub async fn get_encryption_signer(&self) -> Option<Arc<dyn NostrSigner>> {
|
|
||||||
self.encryption_signer.read().await.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get public key
|
|
||||||
///
|
|
||||||
/// Ensure to call this method after the signer has been initialized.
|
|
||||||
/// Otherwise, it will panic.
|
|
||||||
pub fn public_key(&self) -> Option<PublicKey> {
|
|
||||||
*self.signer_pkey.read_blocking()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Switch the current signer to a new signer.
|
|
||||||
pub async fn switch<T>(&self, new: T)
|
|
||||||
where
|
|
||||||
T: IntoNostrSigner,
|
|
||||||
{
|
|
||||||
let new_signer = new.into_nostr_signer();
|
|
||||||
let public_key = new_signer.get_public_key().await.ok();
|
|
||||||
let mut signer = self.signer.write().await;
|
|
||||||
let mut signer_pkey = self.signer_pkey.write().await;
|
|
||||||
let mut encryption_signer = self.encryption_signer.write().await;
|
|
||||||
|
|
||||||
// Switch to the new signer
|
|
||||||
*signer = new_signer;
|
|
||||||
|
|
||||||
// Update the public key
|
|
||||||
*signer_pkey = public_key;
|
|
||||||
|
|
||||||
// Reset the encryption signer
|
|
||||||
*encryption_signer = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the encryption signer.
|
|
||||||
pub async fn set_encryption_signer<T>(&self, new: T)
|
|
||||||
where
|
|
||||||
T: IntoNostrSigner,
|
|
||||||
{
|
|
||||||
let mut encryption_signer = self.encryption_signer.write().await;
|
|
||||||
*encryption_signer = Some(new.into_nostr_signer());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NostrSigner for CoopSigner {
|
|
||||||
#[allow(mismatched_lifetime_syntaxes)]
|
|
||||||
fn backend(&self) -> SignerBackend {
|
|
||||||
SignerBackend::Custom(Cow::Borrowed("custom"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_public_key<'a>(&'a self) -> BoxedFuture<'a, Result<PublicKey, SignerError>> {
|
|
||||||
Box::pin(async move { self.get().await.get_public_key().await })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sign_event<'a>(
|
|
||||||
&'a self,
|
|
||||||
unsigned: UnsignedEvent,
|
|
||||||
) -> BoxedFuture<'a, Result<Event, SignerError>> {
|
|
||||||
Box::pin(async move { self.get().await.sign_event(unsigned).await })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nip04_encrypt<'a>(
|
|
||||||
&'a self,
|
|
||||||
public_key: &'a PublicKey,
|
|
||||||
content: &'a str,
|
|
||||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
|
||||||
Box::pin(async move { self.get().await.nip04_encrypt(public_key, content).await })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nip04_decrypt<'a>(
|
|
||||||
&'a self,
|
|
||||||
public_key: &'a PublicKey,
|
|
||||||
encrypted_content: &'a str,
|
|
||||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
|
||||||
Box::pin(async move {
|
|
||||||
self.get()
|
|
||||||
.await
|
|
||||||
.nip04_decrypt(public_key, encrypted_content)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nip44_encrypt<'a>(
|
|
||||||
&'a self,
|
|
||||||
public_key: &'a PublicKey,
|
|
||||||
content: &'a str,
|
|
||||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
|
||||||
Box::pin(async move { self.get().await.nip44_encrypt(public_key, content).await })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nip44_decrypt<'a>(
|
|
||||||
&'a self,
|
|
||||||
public_key: &'a PublicKey,
|
|
||||||
payload: &'a str,
|
|
||||||
) -> BoxedFuture<'a, Result<String, SignerError>> {
|
|
||||||
Box::pin(async move { self.get().await.nip44_decrypt(public_key, payload).await })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
use anyhow::Error;
|
|
||||||
use gpui::prelude::FluentBuilder;
|
|
||||||
use gpui::{
|
|
||||||
App, AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,
|
|
||||||
SharedString, StatefulInteractiveElement, Styled, Subscription, Task, Window, div, px,
|
|
||||||
};
|
|
||||||
use nostr_sdk::prelude::*;
|
|
||||||
use person::PersonRegistry;
|
|
||||||
use state::{NostrRegistry, StateEvent};
|
|
||||||
use theme::ActiveTheme;
|
|
||||||
use ui::avatar::Avatar;
|
|
||||||
use ui::button::{Button, ButtonVariants};
|
|
||||||
use ui::indicator::Indicator;
|
|
||||||
use ui::{Disableable, Icon, IconName, Sizable, WindowExtension, h_flex, v_flex};
|
|
||||||
|
|
||||||
use crate::dialogs::connect::ConnectSigner;
|
|
||||||
use crate::dialogs::import::ImportKey;
|
|
||||||
|
|
||||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<AccountSelector> {
|
|
||||||
cx.new(|cx| AccountSelector::new(window, cx))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Account selector
|
|
||||||
pub struct AccountSelector {
|
|
||||||
/// Public key currently being chosen for login
|
|
||||||
logging_in: Entity<Option<PublicKey>>,
|
|
||||||
|
|
||||||
/// The error message displayed when an error occurs.
|
|
||||||
error: Entity<Option<SharedString>>,
|
|
||||||
|
|
||||||
/// Async tasks
|
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
|
|
||||||
/// Subscription to the signer events
|
|
||||||
_subscription: Option<Subscription>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountSelector {
|
|
||||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
|
||||||
let logging_in = cx.new(|_| None);
|
|
||||||
let error = cx.new(|_| None);
|
|
||||||
|
|
||||||
// Subscribe to the signer events
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let subscription = cx.subscribe_in(&nostr, window, |this, _state, event, window, cx| {
|
|
||||||
match event {
|
|
||||||
StateEvent::SignerSet => {
|
|
||||||
window.close_all_modals(cx);
|
|
||||||
window.refresh();
|
|
||||||
}
|
|
||||||
StateEvent::Error(e) => {
|
|
||||||
this.set_error(e.to_string(), cx);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
Self {
|
|
||||||
logging_in,
|
|
||||||
error,
|
|
||||||
tasks: vec![],
|
|
||||||
_subscription: Some(subscription),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn logging_in(&self, public_key: &PublicKey, cx: &App) -> bool {
|
|
||||||
self.logging_in.read(cx) == &Some(*public_key)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_logging_in(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
|
||||||
self.logging_in.update(cx, |this, cx| {
|
|
||||||
*this = Some(public_key);
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_error<T>(&mut self, error: T, cx: &mut Context<Self>)
|
|
||||||
where
|
|
||||||
T: Into<SharedString>,
|
|
||||||
{
|
|
||||||
self.error.update(cx, |this, cx| {
|
|
||||||
*this = Some(error.into());
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
|
|
||||||
self.logging_in.update(cx, |this, cx| {
|
|
||||||
*this = None;
|
|
||||||
cx.notify();
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let task = nostr.read(cx).get_secret(public_key, cx);
|
|
||||||
|
|
||||||
// Mark the public key as being logged in
|
|
||||||
self.set_logging_in(public_key, cx);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
|
||||||
match task.await {
|
|
||||||
Ok(signer) => {
|
|
||||||
nostr.update(cx, |this, cx| {
|
|
||||||
this.set_signer(signer, cx);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_error(e.to_string(), cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
|
|
||||||
nostr.update(cx, |this, cx| {
|
|
||||||
this.remove_secret(&public_key, cx);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
|
||||||
let import = cx.new(|cx| ImportKey::new(window, cx));
|
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, _cx| {
|
|
||||||
this.width(px(460.))
|
|
||||||
.title("Import a Secret Key or Bunker Connection")
|
|
||||||
.show_close(true)
|
|
||||||
.pb_2()
|
|
||||||
.child(import.clone())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_connect(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
|
||||||
let connect = cx.new(|cx| ConnectSigner::new(window, cx));
|
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, _cx| {
|
|
||||||
this.width(px(460.))
|
|
||||||
.title("Scan QR Code to Connect")
|
|
||||||
.show_close(true)
|
|
||||||
.pb_2()
|
|
||||||
.child(connect.clone())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Render for AccountSelector {
|
|
||||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
||||||
let persons = PersonRegistry::global(cx);
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let npubs = nostr.read(cx).npubs();
|
|
||||||
let loading = self.logging_in.read(cx).is_some();
|
|
||||||
|
|
||||||
v_flex()
|
|
||||||
.size_full()
|
|
||||||
.gap_2()
|
|
||||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
|
||||||
this.child(
|
|
||||||
div()
|
|
||||||
.italic()
|
|
||||||
.text_xs()
|
|
||||||
.text_center()
|
|
||||||
.text_color(cx.theme().text_danger)
|
|
||||||
.child(error.clone()),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.children({
|
|
||||||
let mut items = vec![];
|
|
||||||
|
|
||||||
for (ix, public_key) in npubs.read(cx).iter().enumerate() {
|
|
||||||
let profile = persons.read(cx).get(public_key, cx);
|
|
||||||
let logging_in = self.logging_in(public_key, cx);
|
|
||||||
|
|
||||||
items.push(
|
|
||||||
h_flex()
|
|
||||||
.id(ix)
|
|
||||||
.group("")
|
|
||||||
.px_2()
|
|
||||||
.h_10()
|
|
||||||
.justify_between()
|
|
||||||
.w_full()
|
|
||||||
.rounded(cx.theme().radius)
|
|
||||||
.bg(cx.theme().ghost_element_background)
|
|
||||||
.hover(|this| this.bg(cx.theme().ghost_element_hover))
|
|
||||||
.child(
|
|
||||||
h_flex()
|
|
||||||
.gap_2()
|
|
||||||
.child(Avatar::new(profile.avatar()).small())
|
|
||||||
.child(div().text_sm().child(profile.name())),
|
|
||||||
)
|
|
||||||
.when(logging_in, |this| this.child(Indicator::new().small()))
|
|
||||||
.when(!logging_in, |this| {
|
|
||||||
this.child(
|
|
||||||
h_flex()
|
|
||||||
.gap_1()
|
|
||||||
.invisible()
|
|
||||||
.group_hover("", |this| this.visible())
|
|
||||||
.child(
|
|
||||||
Button::new(format!("del-{ix}"))
|
|
||||||
.icon(IconName::Close)
|
|
||||||
.ghost()
|
|
||||||
.small()
|
|
||||||
.disabled(logging_in)
|
|
||||||
.on_click(cx.listener({
|
|
||||||
let public_key = *public_key;
|
|
||||||
move |this, _ev, _window, cx| {
|
|
||||||
cx.stop_propagation();
|
|
||||||
this.remove(public_key, cx);
|
|
||||||
}
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.when(!logging_in, |this| {
|
|
||||||
let public_key = *public_key;
|
|
||||||
this.on_click(cx.listener(move |this, _ev, window, cx| {
|
|
||||||
this.login(public_key, window, cx);
|
|
||||||
}))
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
items
|
|
||||||
})
|
|
||||||
.child(div().w_full().h_px().bg(cx.theme().border_variant))
|
|
||||||
.child(
|
|
||||||
h_flex()
|
|
||||||
.gap_1()
|
|
||||||
.justify_end()
|
|
||||||
.w_full()
|
|
||||||
.child(
|
|
||||||
Button::new("input")
|
|
||||||
.icon(Icon::new(IconName::Usb))
|
|
||||||
.label("Import")
|
|
||||||
.ghost()
|
|
||||||
.small()
|
|
||||||
.disabled(loading)
|
|
||||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
|
||||||
this.open_import(window, cx);
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
Button::new("qr")
|
|
||||||
.icon(Icon::new(IconName::Scan))
|
|
||||||
.label("Scan QR to connect")
|
|
||||||
.ghost()
|
|
||||||
.small()
|
|
||||||
.disabled(loading)
|
|
||||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
|
||||||
this.open_connect(window, cx);
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use common::StringExt;
|
|
||||||
use gpui::prelude::FluentBuilder;
|
|
||||||
use gpui::{
|
|
||||||
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,
|
|
||||||
Subscription, Window, div, img, px,
|
|
||||||
};
|
|
||||||
use nostr_connect::prelude::*;
|
|
||||||
use state::{
|
|
||||||
CLIENT_NAME, CoopAuthUrlHandler, NOSTR_CONNECT_RELAY, NOSTR_CONNECT_TIMEOUT, NostrRegistry,
|
|
||||||
StateEvent,
|
|
||||||
};
|
|
||||||
use theme::ActiveTheme;
|
|
||||||
use ui::v_flex;
|
|
||||||
|
|
||||||
pub struct ConnectSigner {
|
|
||||||
/// QR Code
|
|
||||||
qr_code: Option<Arc<Image>>,
|
|
||||||
|
|
||||||
/// Error message
|
|
||||||
error: Entity<Option<SharedString>>,
|
|
||||||
|
|
||||||
/// Subscription to the signer event
|
|
||||||
_subscription: Option<Subscription>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ConnectSigner {
|
|
||||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
|
||||||
let error = cx.new(|_| None);
|
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let app_keys = nostr.read(cx).keys();
|
|
||||||
|
|
||||||
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
|
|
||||||
let relay = RelayUrl::parse(NOSTR_CONNECT_RELAY).unwrap();
|
|
||||||
|
|
||||||
// Generate the nostr connect uri
|
|
||||||
let uri = NostrConnectUri::client(app_keys.public_key(), vec![relay], CLIENT_NAME);
|
|
||||||
|
|
||||||
// Generate the nostr connect
|
|
||||||
let mut signer = NostrConnect::new(uri.clone(), app_keys.clone(), timeout, None).unwrap();
|
|
||||||
|
|
||||||
// Handle the auth request
|
|
||||||
signer.auth_url_handler(CoopAuthUrlHandler);
|
|
||||||
|
|
||||||
// Generate a QR code for quick connection
|
|
||||||
let qr_code = uri.to_string().to_qr();
|
|
||||||
|
|
||||||
// Set signer in the background
|
|
||||||
nostr.update(cx, |this, cx| {
|
|
||||||
this.add_nip46_signer(&signer, cx);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Subscribe to the signer event
|
|
||||||
let subscription = cx.subscribe_in(&nostr, window, |this, _state, event, _window, cx| {
|
|
||||||
if let StateEvent::Error(e) = event {
|
|
||||||
this.set_error(e, cx);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Self {
|
|
||||||
qr_code,
|
|
||||||
error,
|
|
||||||
_subscription: Some(subscription),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_error<S>(&mut self, message: S, cx: &mut Context<Self>)
|
|
||||||
where
|
|
||||||
S: Into<SharedString>,
|
|
||||||
{
|
|
||||||
self.error.update(cx, |this, cx| {
|
|
||||||
*this = Some(message.into());
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Render for ConnectSigner {
|
|
||||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
||||||
const MSG: &str = "Scan with any Nostr Connect-compatible app to connect";
|
|
||||||
|
|
||||||
v_flex()
|
|
||||||
.size_full()
|
|
||||||
.items_center()
|
|
||||||
.justify_center()
|
|
||||||
.p_4()
|
|
||||||
.when_some(self.qr_code.as_ref(), |this, qr| {
|
|
||||||
this.child(
|
|
||||||
img(qr.clone())
|
|
||||||
.size(px(256.))
|
|
||||||
.rounded(cx.theme().radius_lg)
|
|
||||||
.border_1()
|
|
||||||
.border_color(cx.theme().border),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
|
||||||
this.child(
|
|
||||||
div()
|
|
||||||
.text_xs()
|
|
||||||
.text_center()
|
|
||||||
.text_color(cx.theme().text_danger)
|
|
||||||
.child(error.clone()),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.child(
|
|
||||||
div()
|
|
||||||
.text_xs()
|
|
||||||
.text_color(cx.theme().text_muted)
|
|
||||||
.child(SharedString::from(MSG)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,15 +7,14 @@ use gpui::{
|
|||||||
Subscription, Task, Window, div,
|
Subscription, Task, Window, div,
|
||||||
};
|
};
|
||||||
use nostr_connect::prelude::*;
|
use nostr_connect::prelude::*;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use state::NostrRegistry;
|
||||||
use state::{CoopAuthUrlHandler, NostrRegistry, StateEvent};
|
|
||||||
use theme::ActiveTheme;
|
use theme::ActiveTheme;
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::{Button, ButtonVariants};
|
||||||
use ui::input::{Input, InputEvent, InputState};
|
use ui::input::{Input, InputEvent, InputState};
|
||||||
use ui::{Disableable, v_flex};
|
use ui::{Disableable, v_flex};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ImportKey {
|
pub struct ImportIdentity {
|
||||||
/// Secret key input
|
/// Secret key input
|
||||||
key_input: Entity<InputState>,
|
key_input: Entity<InputState>,
|
||||||
|
|
||||||
@@ -25,73 +24,43 @@ pub struct ImportKey {
|
|||||||
/// Error message
|
/// Error message
|
||||||
error: Entity<Option<SharedString>>,
|
error: Entity<Option<SharedString>>,
|
||||||
|
|
||||||
/// Countdown timer for nostr connect
|
|
||||||
countdown: Entity<Option<u64>>,
|
|
||||||
|
|
||||||
/// Whether the user is currently loading
|
/// Whether the user is currently loading
|
||||||
loading: bool,
|
loading: bool,
|
||||||
|
|
||||||
/// Async tasks
|
/// Async tasks
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
|
|
||||||
/// Event subscriptions
|
/// Input subscription
|
||||||
_subscriptions: SmallVec<[Subscription; 2]>,
|
_subscription: Option<Subscription>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ImportKey {
|
impl ImportIdentity {
|
||||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let key_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
let key_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||||
let pass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
let pass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
|
||||||
let error = cx.new(|_| None);
|
let error = cx.new(|_| None);
|
||||||
let countdown = cx.new(|_| None);
|
|
||||||
|
|
||||||
let mut subscriptions = smallvec![];
|
let input_subscription =
|
||||||
|
|
||||||
subscriptions.push(
|
|
||||||
// Subscribe to key input events and process login when the user presses enter
|
|
||||||
cx.subscribe_in(&key_input, window, |this, _input, event, window, cx| {
|
cx.subscribe_in(&key_input, window, |this, _input, event, window, cx| {
|
||||||
if let InputEvent::PressEnter { .. } = event {
|
if let InputEvent::PressEnter { .. } = event {
|
||||||
this.login(window, cx);
|
this.login(window, cx);
|
||||||
};
|
};
|
||||||
}),
|
});
|
||||||
);
|
|
||||||
|
|
||||||
subscriptions.push(
|
|
||||||
// Subscribe to the nostr signer event
|
|
||||||
cx.subscribe_in(&nostr, window, |this, _state, event, _window, cx| {
|
|
||||||
if let StateEvent::Error(e) = event {
|
|
||||||
this.set_error(e, cx);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
key_input,
|
key_input,
|
||||||
pass_input,
|
pass_input,
|
||||||
error,
|
error,
|
||||||
countdown,
|
|
||||||
loading: false,
|
loading: false,
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
_subscriptions: subscriptions,
|
_subscription: Some(input_subscription),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn login(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn login(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
if self.loading {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
// Prevent duplicate login requests
|
|
||||||
self.set_loading(true, cx);
|
|
||||||
|
|
||||||
let value = self.key_input.read(cx).value();
|
let value = self.key_input.read(cx).value();
|
||||||
let password = self.pass_input.read(cx).value();
|
let password = self.pass_input.read(cx).value();
|
||||||
|
|
||||||
if value.starts_with("bunker://") {
|
|
||||||
self.bunker(&value, window, cx);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if value.starts_with("ncryptsec1") {
|
if value.starts_with("ncryptsec1") {
|
||||||
self.ncryptsec(value, password, window, cx);
|
self.ncryptsec(value, password, window, cx);
|
||||||
return;
|
return;
|
||||||
@@ -103,52 +72,13 @@ impl ImportKey {
|
|||||||
|
|
||||||
// Update the signer
|
// Update the signer
|
||||||
nostr.update(cx, |this, cx| {
|
nostr.update(cx, |this, cx| {
|
||||||
this.add_key_signer(&keys, cx);
|
this.set_signer(keys, cx);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
self.set_error("Invalid key", cx);
|
self.set_error("Invalid key", cx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bunker(&mut self, content: &str, window: &mut Window, cx: &mut Context<Self>) {
|
|
||||||
let Ok(uri) = NostrConnectUri::parse(content) else {
|
|
||||||
self.set_error("Bunker is not valid", cx);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let app_keys = nostr.read(cx).keys();
|
|
||||||
let timeout = Duration::from_secs(30);
|
|
||||||
|
|
||||||
// Construct the nostr connect signer
|
|
||||||
let mut signer = NostrConnect::new(uri, app_keys.clone(), timeout, None).unwrap();
|
|
||||||
|
|
||||||
// Handle auth url with the default browser
|
|
||||||
signer.auth_url_handler(CoopAuthUrlHandler);
|
|
||||||
|
|
||||||
// Set signer in the background
|
|
||||||
nostr.update(cx, |this, cx| {
|
|
||||||
this.add_nip46_signer(&signer, cx);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start countdown
|
|
||||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
|
||||||
for i in (0..=30).rev() {
|
|
||||||
if i == 0 {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_countdown(None, cx);
|
|
||||||
})?;
|
|
||||||
} else {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_countdown(Some(i), cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
cx.background_executor().timer(Duration::from_secs(1)).await;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ncryptsec<S>(&mut self, content: S, pwd: S, window: &mut Window, cx: &mut Context<Self>)
|
fn ncryptsec<S>(&mut self, content: S, pwd: S, window: &mut Window, cx: &mut Context<Self>)
|
||||||
where
|
where
|
||||||
S: Into<String>,
|
S: Into<String>,
|
||||||
@@ -180,7 +110,7 @@ impl ImportKey {
|
|||||||
match task.await {
|
match task.await {
|
||||||
Ok(keys) => {
|
Ok(keys) => {
|
||||||
nostr.update(cx, |this, cx| {
|
nostr.update(cx, |this, cx| {
|
||||||
this.add_key_signer(&keys, cx);
|
this.set_signer(keys, cx);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -198,12 +128,6 @@ impl ImportKey {
|
|||||||
where
|
where
|
||||||
S: Into<SharedString>,
|
S: Into<SharedString>,
|
||||||
{
|
{
|
||||||
// Reset the log in state
|
|
||||||
self.set_loading(false, cx);
|
|
||||||
|
|
||||||
// Reset the countdown
|
|
||||||
self.set_countdown(None, cx);
|
|
||||||
|
|
||||||
// Update error message
|
// Update error message
|
||||||
self.error.update(cx, |this, cx| {
|
self.error.update(cx, |this, cx| {
|
||||||
*this = Some(message.into());
|
*this = Some(message.into());
|
||||||
@@ -224,22 +148,12 @@ impl ImportKey {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_loading(&mut self, status: bool, cx: &mut Context<Self>) {
|
|
||||||
self.loading = status;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_countdown(&mut self, i: Option<u64>, cx: &mut Context<Self>) {
|
|
||||||
self.countdown.update(cx, |this, cx| {
|
|
||||||
*this = i;
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Render for ImportKey {
|
impl Render for ImportIdentity {
|
||||||
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
|
const MSG: &str = "Coop isn't stored your identity secret in local device. Everything will be reset on the next login.";
|
||||||
|
|
||||||
v_flex()
|
v_flex()
|
||||||
.size_full()
|
.size_full()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
@@ -249,7 +163,7 @@ impl Render for ImportKey {
|
|||||||
.gap_1()
|
.gap_1()
|
||||||
.text_sm()
|
.text_sm()
|
||||||
.text_color(cx.theme().text_muted)
|
.text_color(cx.theme().text_muted)
|
||||||
.child("nsec or bunker://")
|
.child("nsec or ncryptsec://")
|
||||||
.child(Input::new(&self.key_input)),
|
.child(Input::new(&self.key_input)),
|
||||||
)
|
)
|
||||||
.when(
|
.when(
|
||||||
@@ -265,6 +179,7 @@ impl Render for ImportKey {
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
.child(div().text_xs().text_color(cx.theme().text_muted).child(MSG))
|
||||||
.child(
|
.child(
|
||||||
Button::new("login")
|
Button::new("login")
|
||||||
.label("Continue")
|
.label("Continue")
|
||||||
@@ -275,18 +190,6 @@ impl Render for ImportKey {
|
|||||||
this.login(window, cx);
|
this.login(window, cx);
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
.when_some(self.countdown.read(cx).as_ref(), |this, i| {
|
|
||||||
this.child(
|
|
||||||
div()
|
|
||||||
.text_xs()
|
|
||||||
.text_center()
|
|
||||||
.text_color(cx.theme().text_muted)
|
|
||||||
.child(SharedString::from(format!(
|
|
||||||
"Approve connection request from your signer in {} seconds",
|
|
||||||
i
|
|
||||||
))),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
.when_some(self.error.read(cx).as_ref(), |this, error| {
|
||||||
this.child(
|
this.child(
|
||||||
div()
|
div()
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
pub mod accounts;
|
|
||||||
pub mod connect;
|
|
||||||
pub mod import;
|
pub mod import;
|
||||||
pub mod restore;
|
pub mod restore;
|
||||||
pub mod screening;
|
pub mod screening;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::Error;
|
||||||
use common::TimestampExt;
|
use common::TimestampExt;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
@@ -78,12 +78,13 @@ impl Screening {
|
|||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let public_key = self.public_key;
|
let public_key = self.public_key;
|
||||||
|
|
||||||
let task: Task<Result<bool, Error>> = cx.background_spawn(async move {
|
let Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
return;
|
||||||
let signer_pubkey = signer.get_public_key().await?;
|
};
|
||||||
|
|
||||||
|
let task: Task<Result<bool, Error>> = cx.background_spawn(async move {
|
||||||
// Check if user is in contact list
|
// Check if user is in contact list
|
||||||
let contacts = client.database().contacts_public_keys(signer_pubkey).await;
|
let contacts = client.database().contacts_public_keys(current_user).await;
|
||||||
let followed = contacts.unwrap_or_default().contains(&public_key);
|
let followed = contacts.unwrap_or_default().contains(&public_key);
|
||||||
|
|
||||||
Ok(followed)
|
Ok(followed)
|
||||||
@@ -105,16 +106,17 @@ impl Screening {
|
|||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let public_key = self.public_key;
|
let public_key = self.public_key;
|
||||||
|
|
||||||
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
|
let Some(current_user) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
return;
|
||||||
let signer_pubkey = signer.get_public_key().await?;
|
};
|
||||||
|
|
||||||
|
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||||
// Check mutual contacts
|
// Check mutual contacts
|
||||||
let filter = Filter::new().kind(Kind::ContactList).pubkey(public_key);
|
let filter = Filter::new().kind(Kind::ContactList).pubkey(public_key);
|
||||||
let mut mutual_contacts = vec![];
|
let mut mutual_contacts = vec![];
|
||||||
|
|
||||||
if let Ok(events) = client.database().query(filter).await {
|
if let Ok(events) = client.database().query(filter).await {
|
||||||
for event in events.into_iter().filter(|ev| ev.pubkey != signer_pubkey) {
|
for event in events.into_iter().filter(|ev| ev.pubkey != current_user) {
|
||||||
mutual_contacts.push(event.pubkey);
|
mutual_contacts.push(event.pubkey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,10 +226,20 @@ impl Screening {
|
|||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let public_key = self.public_key;
|
let public_key = self.public_key;
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
let tag = Tag::public_key_report(public_key, Report::Impersonation);
|
let tag = Nip56Tag::PublicKey {
|
||||||
let builder = EventBuilder::report(vec![tag], "");
|
public_key,
|
||||||
let event = client.sign_event_builder(builder).await?;
|
report: Report::Impersonation,
|
||||||
|
}
|
||||||
|
.to_tag();
|
||||||
|
|
||||||
|
let event = EventBuilder::report(vec![tag], "")
|
||||||
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Send the report to the public relays
|
// Send the report to the public relays
|
||||||
client.send_event(&event).to(BOOTSTRAP_RELAYS).await?;
|
client.send_event(&event).to(BOOTSTRAP_RELAYS).await?;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::Error;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
||||||
@@ -82,11 +82,12 @@ impl ContactListPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
return;
|
||||||
let public_key = signer.get_public_key().await?;
|
};
|
||||||
let contact_list = client.database().contacts_public_keys(public_key).await?;
|
|
||||||
|
|
||||||
|
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||||
|
let contact_list = client.database().contacts_public_keys(public_key).await?;
|
||||||
Ok(contact_list)
|
Ok(contact_list)
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -157,6 +158,10 @@ impl ContactListPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
// Get contacts
|
// Get contacts
|
||||||
let contacts: Vec<Contact> = self
|
let contacts: Vec<Contact> = self
|
||||||
.contacts
|
.contacts
|
||||||
@@ -169,8 +174,9 @@ impl ContactListPanel {
|
|||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
// Construct contact list event builder
|
// Construct contact list event builder
|
||||||
let builder = EventBuilder::contact_list(contacts);
|
let event = ContactListBuilder::new(contacts)
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Set contact list
|
// Set contact list
|
||||||
client.send_event(&event).to_nip65().await?;
|
client.send_event(&event).to_nip65().await?;
|
||||||
|
|||||||
@@ -30,9 +30,8 @@ impl GreeterPanel {
|
|||||||
|
|
||||||
fn add_profile_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn add_profile_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
if let Some(public_key) = signer.public_key() {
|
if let Some(public_key) = nostr.read(cx).signer_pubkey(cx) {
|
||||||
cx.spawn_in(window, async move |_this, cx| {
|
cx.spawn_in(window, async move |_this, cx| {
|
||||||
cx.update(|window, cx| {
|
cx.update(|window, cx| {
|
||||||
Workspace::add_panel(
|
Workspace::add_panel(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
use anyhow::{Error, anyhow};
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
||||||
@@ -83,17 +83,18 @@ impl MessagingRelayPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
let task: Task<Result<Vec<RelayUrl>, Error>> = cx.background_spawn(async move {
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
return;
|
||||||
let public_key = signer.get_public_key().await?;
|
};
|
||||||
|
|
||||||
|
let task: Task<Result<Vec<RelayUrl>, Error>> = cx.background_spawn(async move {
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::InboxRelays)
|
.kind(Kind::InboxRelays)
|
||||||
.author(public_key)
|
.author(public_key)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||||
Ok(nip17::extract_owned_relay_list(event).collect())
|
Ok(nip17::extract_relay_list(&event).collect())
|
||||||
} else {
|
} else {
|
||||||
Err(anyhow!("Not found."))
|
Err(anyhow!("Not found."))
|
||||||
}
|
}
|
||||||
@@ -171,11 +172,15 @@ impl MessagingRelayPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
// Construct event tags
|
// Construct event tags
|
||||||
let tags: Vec<Tag> = self
|
let tags: Vec<Tag> = self
|
||||||
.relays
|
.relays
|
||||||
.iter()
|
.iter()
|
||||||
.map(|relay| Tag::relay(relay.clone()))
|
.map(|relay| Nip17Tag::Relay(relay.to_owned()).to_tag())
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// Set updating state
|
// Set updating state
|
||||||
@@ -183,8 +188,10 @@ impl MessagingRelayPanel {
|
|||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
// Construct nip17 event builder
|
// Construct nip17 event builder
|
||||||
let builder = EventBuilder::new(Kind::InboxRelays, "").tags(tags);
|
let event = EventBuilder::new(Kind::InboxRelays, "")
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.tags(tags)
|
||||||
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Set messaging relays
|
// Set messaging relays
|
||||||
client.send_event(&event).to_nip65().await?;
|
client.send_event(&event).to_nip65().await?;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||||
Focusable, IntoElement, ParentElement, PathPromptOptions, Render, SharedString, Styled, Task,
|
Focusable, IntoElement, ParentElement, PathPromptOptions, Render, SharedString, Styled, Task,
|
||||||
@@ -209,10 +209,15 @@ impl ProfilePanel {
|
|||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
let metadata = metadata.clone();
|
let metadata = metadata.clone();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return Task::ready(Err(anyhow!("Signer is required")));
|
||||||
|
};
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
// Build and sign the metadata event
|
// Build and sign the metadata event
|
||||||
let builder = EventBuilder::metadata(&metadata);
|
let event = EventBuilder::metadata(&metadata)
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Send event to user's relays
|
// Send event to user's relays
|
||||||
client.send_event(&event).await?;
|
client.send_event(&event).await?;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
use anyhow::{Error, anyhow};
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Action, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
Action, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
|
||||||
@@ -100,18 +100,19 @@ impl RelayListPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
let task: Task<Result<Vec<(RelayUrl, Option<RelayMetadata>)>, Error>> = cx
|
let task: Task<Result<Vec<(RelayUrl, Option<RelayMetadata>)>, Error>> = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
|
||||||
let public_key = signer.get_public_key().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
.kind(Kind::RelayList)
|
.kind(Kind::RelayList)
|
||||||
.author(public_key)
|
.author(public_key)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||||
Ok(nip65::extract_owned_relay_list(event).collect())
|
Ok(nip65::extract_relay_list(&event).collect())
|
||||||
} else {
|
} else {
|
||||||
Err(anyhow!("Not found."))
|
Err(anyhow!("Not found."))
|
||||||
}
|
}
|
||||||
@@ -207,6 +208,10 @@ impl RelayListPanel {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
|
let Some(signer) = nostr.read(cx).signer(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
// Get all relays
|
// Get all relays
|
||||||
let relays = self.relays.clone();
|
let relays = self.relays.clone();
|
||||||
|
|
||||||
@@ -214,8 +219,9 @@ impl RelayListPanel {
|
|||||||
self.set_updating(true, cx);
|
self.set_updating(true, cx);
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||||
let builder = EventBuilder::relay_list(relays);
|
let event = EventBuilder::relay_list(relays)
|
||||||
let event = client.sign_event_builder(builder).await?;
|
.finalize_async(&signer)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// Set relay list for current user
|
// Set relay list for current user
|
||||||
client.send_event(&event).await?;
|
client.send_event(&event).await?;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
|||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::Error;
|
||||||
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
||||||
use common::{DebouncedDelay, TimestampExt, coop_cache};
|
use common::{DebouncedDelay, TimestampExt, coop_cache};
|
||||||
use entry::RoomEntry;
|
use entry::RoomEntry;
|
||||||
@@ -159,11 +159,12 @@ impl Sidebar {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let client = nostr.read(cx).client();
|
let client = nostr.read(cx).client();
|
||||||
|
|
||||||
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
let signer = client.signer().context("Signer not found")?;
|
return;
|
||||||
let public_key = signer.get_public_key().await?;
|
};
|
||||||
let contacts = client.database().contacts_public_keys(public_key).await?;
|
|
||||||
|
|
||||||
|
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
|
||||||
|
let contacts = client.database().contacts_public_keys(public_key).await?;
|
||||||
Ok(contacts)
|
Ok(contacts)
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -319,14 +320,14 @@ impl Sidebar {
|
|||||||
let async_chat = chat.downgrade();
|
let async_chat = chat.downgrade();
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
// Get all selected public keys
|
// Get all selected public keys
|
||||||
let receivers = self.get_selected(cx);
|
let receivers = self.get_selected(cx);
|
||||||
|
|
||||||
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
|
||||||
let public_key = signer.get_public_key().await?;
|
|
||||||
|
|
||||||
// Create a new room and emit it
|
// Create a new room and emit it
|
||||||
async_chat.update_in(cx, |this, _window, cx| {
|
async_chat.update_in(cx, |this, _window, cx| {
|
||||||
let room = cx.new(|_| {
|
let room = cx.new(|_| {
|
||||||
|
|||||||
@@ -24,23 +24,17 @@ use ui::menu::{DropdownMenu, PopupMenuItem};
|
|||||||
use ui::notification::{Notification, NotificationKind};
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
use ui::{Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
||||||
|
|
||||||
|
use crate::dialogs::import::ImportIdentity;
|
||||||
use crate::dialogs::restore::RestoreEncryption;
|
use crate::dialogs::restore::RestoreEncryption;
|
||||||
use crate::dialogs::{accounts, settings};
|
use crate::dialogs::settings;
|
||||||
use crate::panels::{backup, contact_list, greeter, messaging_relays, profile, relay_list, trash};
|
use crate::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. \
|
|
||||||
Your identity is completely decoupled from all encryption processes to protect your privacy.";
|
|
||||||
const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \
|
|
||||||
all your encrypted messages before. This action cannot be undone.";
|
|
||||||
|
|
||||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Workspace> {
|
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 DeviceNotifcation;
|
||||||
struct SignerNotifcation;
|
|
||||||
struct RelayNotifcation;
|
struct RelayNotifcation;
|
||||||
struct MsgRelayNotification;
|
struct MsgRelayNotification;
|
||||||
|
|
||||||
@@ -48,7 +42,6 @@ struct MsgRelayNotification;
|
|||||||
#[action(namespace = workspace, no_json)]
|
#[action(namespace = workspace, no_json)]
|
||||||
enum Command {
|
enum Command {
|
||||||
ToggleTheme,
|
ToggleTheme,
|
||||||
ToggleAccount,
|
|
||||||
|
|
||||||
RefreshMessagingRelays,
|
RefreshMessagingRelays,
|
||||||
BackupEncryption,
|
BackupEncryption,
|
||||||
@@ -75,7 +68,7 @@ pub struct Workspace {
|
|||||||
image_cache: Entity<CoopImageCache>,
|
image_cache: Entity<CoopImageCache>,
|
||||||
|
|
||||||
/// Event subscriptions
|
/// Event subscriptions
|
||||||
_subscriptions: SmallVec<[Subscription; 5]>,
|
_subscriptions: SmallVec<[Subscription; 6]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Workspace {
|
impl Workspace {
|
||||||
@@ -83,6 +76,7 @@ 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 signer = nostr.read(cx).signer.clone();
|
||||||
|
|
||||||
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));
|
||||||
@@ -98,19 +92,20 @@ impl Workspace {
|
|||||||
);
|
);
|
||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// Subscribe to the signer events
|
// Observe the signer
|
||||||
cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| {
|
cx.observe_in(&signer, window, |this, signer, window, cx| {
|
||||||
match event {
|
if signer.read(cx).is_some() {
|
||||||
StateEvent::Creating => {
|
this.set_center_layout(window, cx);
|
||||||
let note = Notification::new()
|
} else {
|
||||||
.id::<SignerNotifcation>()
|
this.import_identity(window, cx);
|
||||||
.title("Preparing a new identity")
|
}
|
||||||
.message(PREPARE_MSG)
|
}),
|
||||||
.autohide(false)
|
);
|
||||||
.with_kind(NotificationKind::Info);
|
|
||||||
|
|
||||||
window.push_notification(note, cx);
|
subscriptions.push(
|
||||||
}
|
// Subscribe to the nostr events
|
||||||
|
cx.subscribe_in(&nostr, window, move |this, state, event, window, cx| {
|
||||||
|
match event {
|
||||||
StateEvent::Connecting => {
|
StateEvent::Connecting => {
|
||||||
let note = Notification::new()
|
let note = Notification::new()
|
||||||
.id::<RelayNotifcation>()
|
.id::<RelayNotifcation>()
|
||||||
@@ -126,14 +121,10 @@ impl Workspace {
|
|||||||
.with_kind(NotificationKind::Success);
|
.with_kind(NotificationKind::Success);
|
||||||
|
|
||||||
window.push_notification(note, cx);
|
window.push_notification(note, cx);
|
||||||
}
|
|
||||||
StateEvent::SignerSet => {
|
if state.read(cx).signer.read(cx).is_none() {
|
||||||
this.set_center_layout(window, cx);
|
this.import_identity(window, cx);
|
||||||
// Clear the signer notification
|
}
|
||||||
window.clear_notification::<SignerNotifcation>(cx);
|
|
||||||
}
|
|
||||||
StateEvent::Show => {
|
|
||||||
this.account_selector(window, cx);
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
@@ -341,9 +332,8 @@ impl Workspace {
|
|||||||
}
|
}
|
||||||
Command::ShowProfile => {
|
Command::ShowProfile => {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
if let Some(public_key) = signer.public_key() {
|
if let Some(public_key) = nostr.read(cx).signer_pubkey(cx) {
|
||||||
self.dock.update(cx, |this, cx| {
|
self.dock.update(cx, |this, cx| {
|
||||||
this.add_panel(
|
this.add_panel(
|
||||||
Arc::new(profile::init(public_key, window, cx)),
|
Arc::new(profile::init(public_key, window, cx)),
|
||||||
@@ -413,9 +403,6 @@ impl Workspace {
|
|||||||
Command::ToggleTheme => {
|
Command::ToggleTheme => {
|
||||||
self.theme_selector(window, cx);
|
self.theme_selector(window, cx);
|
||||||
}
|
}
|
||||||
Command::ToggleAccount => {
|
|
||||||
self.account_selector(window, cx);
|
|
||||||
}
|
|
||||||
Command::BackupEncryption => {
|
Command::BackupEncryption => {
|
||||||
let device = DeviceRegistry::global(cx).downgrade();
|
let device = DeviceRegistry::global(cx).downgrade();
|
||||||
let save_dialog = cx.prompt_for_new_path(download_dir(), Some("encryption.txt"));
|
let save_dialog = cx.prompt_for_new_path(download_dir(), Some("encryption.txt"));
|
||||||
@@ -458,6 +445,12 @@ impl Workspace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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>) {
|
||||||
|
const ENC_MSG: &str = "Encryption Key is a special key that used to encrypt and decrypt your messages. \
|
||||||
|
Your identity is completely decoupled from all encryption processes to protect your privacy.";
|
||||||
|
|
||||||
|
const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \
|
||||||
|
all your encrypted messages before. This action cannot be undone.";
|
||||||
|
|
||||||
let device = DeviceRegistry::global(cx);
|
let device = DeviceRegistry::global(cx);
|
||||||
let ent = device.downgrade();
|
let ent = device.downgrade();
|
||||||
|
|
||||||
@@ -492,24 +485,21 @@ impl Workspace {
|
|||||||
|
|
||||||
fn import_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn import_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let restore = cx.new(|cx| RestoreEncryption::new(window, cx));
|
let restore = cx.new(|cx| RestoreEncryption::new(window, cx));
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, _cx| {
|
window.open_modal(cx, move |this, _window, _cx| {
|
||||||
this.width(px(520.))
|
this.width(px(420.))
|
||||||
.title("Restore Encryption")
|
.title("Restore Encryption")
|
||||||
.child(restore.clone())
|
.child(restore.clone())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn account_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn import_identity(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let accounts = accounts::init(window, cx);
|
let import = cx.new(|cx| ImportIdentity::new(window, cx));
|
||||||
|
|
||||||
window.open_modal(cx, move |this, _window, _cx| {
|
window.open_modal(cx, move |this, _window, _cx| {
|
||||||
this.width(px(520.))
|
this.width(px(420.))
|
||||||
.title("Continue with")
|
|
||||||
.show_close(false)
|
.show_close(false)
|
||||||
.keyboard(false)
|
.title("Import Identity")
|
||||||
.overlay_closable(false)
|
.child(import.clone())
|
||||||
.child(accounts.clone())
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -595,8 +585,7 @@ impl Workspace {
|
|||||||
|
|
||||||
fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
let current_user = nostr.read(cx).signer_pubkey(cx);
|
||||||
let current_user = signer.public_key();
|
|
||||||
|
|
||||||
h_flex()
|
h_flex()
|
||||||
.flex_shrink_0()
|
.flex_shrink_0()
|
||||||
@@ -606,7 +595,7 @@ impl Workspace {
|
|||||||
div()
|
div()
|
||||||
.text_xs()
|
.text_xs()
|
||||||
.text_color(cx.theme().text_muted)
|
.text_color(cx.theme().text_muted)
|
||||||
.child(SharedString::from("Choose an account to continue...")),
|
.child(SharedString::from("Import your identity to continue")),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.when_some(current_user.as_ref(), |this, public_key| {
|
.when_some(current_user.as_ref(), |this, public_key| {
|
||||||
@@ -657,11 +646,6 @@ impl Workspace {
|
|||||||
Box::new(Command::ToggleTheme),
|
Box::new(Command::ToggleTheme),
|
||||||
)
|
)
|
||||||
.separator()
|
.separator()
|
||||||
.menu_with_icon(
|
|
||||||
"Accounts",
|
|
||||||
IconName::Group,
|
|
||||||
Box::new(Command::ToggleAccount),
|
|
||||||
)
|
|
||||||
.menu_with_icon(
|
.menu_with_icon(
|
||||||
"Settings",
|
"Settings",
|
||||||
IconName::Settings,
|
IconName::Settings,
|
||||||
@@ -676,11 +660,9 @@ impl Workspace {
|
|||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
let trash_messages = chat.read(cx).count_trash_messages(cx);
|
let trash_messages = chat.read(cx).count_trash_messages(cx);
|
||||||
let is_nip4e_enabled = AppSettings::get_encryption_key(cx);
|
let is_nip4e_enabled = AppSettings::get_encryption_key(cx);
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
let Some(public_key) = signer.public_key() else {
|
let Some(public_key) = nostr.read(cx).signer_pubkey(cx) else {
|
||||||
return div();
|
return div();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "1.92"
|
channel = "1.96"
|
||||||
profile = "minimal"
|
profile = "minimal"
|
||||||
components = ["rustfmt", "clippy"]
|
components = ["rustfmt", "clippy"]
|
||||||
targets = [
|
targets = [
|
||||||
|
|||||||
Reference in New Issue
Block a user