Compare commits
16 Commits
0.1.3-alph
...
0.1.4-alph
| Author | SHA1 | Date | |
|---|---|---|---|
| 348dc496a6 | |||
| 09df38a3b2 | |||
| cae96157ca | |||
| 0a7f0475a4 | |||
| 8156d9d046 | |||
| b92d446184 | |||
| 73b8a1a6da | |||
| ba0b377cee | |||
| 0822b46596 | |||
| d93cecbea3 | |||
| 0887970374 | |||
|
|
a53b2181ab | ||
| 81664e3d4e | |||
| 29ec6da872 | |||
| 111ab3b082 | |||
| 1c4806bd92 |
804
Cargo.lock
generated
804
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -11,9 +11,9 @@ gpui = { git = "https://github.com/zed-industries/zed" }
|
||||
reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
||||
|
||||
# Nostr
|
||||
nostr-relay-builder = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr", features = [
|
||||
nostr-relay-builder = { git = "https://github.com/reyamir/nostr", branch = "feat/improve-nip17" }
|
||||
nostr-connect = { git = "https://github.com/reyamir/nostr", branch = "feat/improve-nip17" }
|
||||
nostr-sdk = { git = "https://github.com/reyamir/nostr", branch = "feat/improve-nip17", features = [
|
||||
"lmdb",
|
||||
"nip96",
|
||||
"nip59",
|
||||
|
||||
@@ -2,7 +2,7 @@ name = "coop"
|
||||
description = "Coop is a cross-platform Nostr client designed for secure communication focus on simplicity and customizability."
|
||||
product-name = "Coop"
|
||||
identifier = "su.reya.coop"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
resources = ["assets/*/*", "Cargo.toml", "./LICENSE", "./README.md"]
|
||||
icons = [
|
||||
"assets/brand/32x32.png",
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "account"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../common" }
|
||||
state = { path = "../state" }
|
||||
|
||||
gpui.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
anyhow.workspace = true
|
||||
smol.workspace = true
|
||||
oneshot.workspace = true
|
||||
log.workspace = true
|
||||
@@ -1 +0,0 @@
|
||||
pub mod registry;
|
||||
@@ -1,117 +0,0 @@
|
||||
use anyhow::anyhow;
|
||||
use common::{
|
||||
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
|
||||
profile::NostrProfile,
|
||||
};
|
||||
use gpui::{App, AppContext, AsyncApp, Context, Entity, Global, Task};
|
||||
use nostr_sdk::prelude::*;
|
||||
use state::get_client;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
struct GlobalAccount(Entity<Account>);
|
||||
|
||||
impl Global for GlobalAccount {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Account {
|
||||
profile: NostrProfile,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
pub fn global(cx: &App) -> Option<Entity<Self>> {
|
||||
cx.try_global::<GlobalAccount>()
|
||||
.map(|model| model.0.clone())
|
||||
}
|
||||
|
||||
pub fn set_global(account: Entity<Self>, cx: &mut App) {
|
||||
cx.set_global(GlobalAccount(account));
|
||||
}
|
||||
|
||||
pub fn login(signer: Arc<dyn NostrSigner>, cx: &AsyncApp) -> Task<Result<(), anyhow::Error>> {
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Option<NostrProfile>>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
// Update nostr signer
|
||||
_ = client.set_signer(signer).await;
|
||||
// Verify nostr signer and get public key
|
||||
let result = async {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let metadata = client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await
|
||||
.ok()
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok::<_, anyhow::Error>(NostrProfile::new(public_key, metadata))
|
||||
}
|
||||
.await;
|
||||
|
||||
tx.send(result.ok()).ok();
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|cx| async move {
|
||||
if let Ok(Some(profile)) = rx.await {
|
||||
cx.update(|cx| {
|
||||
let this = cx.new(|cx| {
|
||||
let this = Account { profile };
|
||||
// Run initial sync data for this account
|
||||
if let Some(task) = this.sync(cx) {
|
||||
task.detach();
|
||||
}
|
||||
// Return
|
||||
this
|
||||
});
|
||||
|
||||
Self::set_global(this, cx)
|
||||
})
|
||||
} else {
|
||||
Err(anyhow!("Login failed"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get(&self) -> &NostrProfile {
|
||||
&self.profile
|
||||
}
|
||||
|
||||
fn sync(&self, cx: &mut Context<Self>) -> Option<Task<()>> {
|
||||
let client = get_client();
|
||||
let public_key = self.profile.public_key();
|
||||
|
||||
let task = cx.background_spawn(async move {
|
||||
// Set the default options for this task
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
// Create a filter to get contact list
|
||||
let contact_list = Filter::new()
|
||||
.kind(Kind::ContactList)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
if let Err(e) = client.subscribe(contact_list, Some(opts)).await {
|
||||
log::error!("Failed to subscribe to contact list: {}", e);
|
||||
}
|
||||
|
||||
// Create a filter for getting all gift wrapped events send to current user
|
||||
let msg = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
||||
let id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
|
||||
|
||||
if let Err(e) = client.subscribe_with_id(id, msg.clone(), Some(opts)).await {
|
||||
log::error!("Failed to subscribe to all messages: {}", e);
|
||||
}
|
||||
|
||||
// Create a filter to continuously receive new messages.
|
||||
let new_msg = msg.limit(0);
|
||||
let id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
|
||||
|
||||
if let Err(e) = client.subscribe_with_id(id, new_msg, None).await {
|
||||
log::error!("Failed to subscribe to new messages: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
Some(task)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "coop"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
@@ -11,9 +11,8 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
ui = { path = "../ui" }
|
||||
common = { path = "../common" }
|
||||
state = { path = "../state" }
|
||||
global = { path = "../global" }
|
||||
chats = { path = "../chats" }
|
||||
account = { path = "../account" }
|
||||
|
||||
gpui.workspace = true
|
||||
reqwest_client.workspace = true
|
||||
@@ -27,6 +26,7 @@ itertools.workspace = true
|
||||
dirs.workspace = true
|
||||
rust-embed.workspace = true
|
||||
log.workspace = true
|
||||
smallvec.workspace = true
|
||||
smol.workspace = true
|
||||
oneshot.workspace = true
|
||||
|
||||
|
||||
916
crates/app/src/device.rs
Normal file
916
crates/app/src/device.rs
Normal file
@@ -0,0 +1,916 @@
|
||||
use std::{collections::HashSet, str::FromStr, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{anyhow, Error};
|
||||
use common::profile::NostrProfile;
|
||||
use global::{
|
||||
constants::{
|
||||
ALL_MESSAGES_SUB_ID, CLIENT_KEYRING, DEVICE_ANNOUNCEMENT_KIND, DEVICE_REQUEST_KIND,
|
||||
DEVICE_RESPONSE_KIND, DEVICE_SUB_ID, MASTER_KEYRING, NEW_MESSAGE_SUB_ID,
|
||||
},
|
||||
get_app_name, get_client, get_device_keys, get_device_name, set_device_keys,
|
||||
};
|
||||
use gpui::{
|
||||
div, px, relative, App, AppContext, Context, Entity, Global, ParentElement, Styled, Task,
|
||||
Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use smallvec::SmallVec;
|
||||
use ui::{
|
||||
button::{Button, ButtonRounded, ButtonVariants},
|
||||
indicator::Indicator,
|
||||
notification::Notification,
|
||||
theme::{scale::ColorScaleStep, ActiveTheme},
|
||||
ContextModal, Root, Sizable, StyledExt,
|
||||
};
|
||||
|
||||
use crate::views::{app, onboarding, relays};
|
||||
|
||||
struct GlobalDevice(Entity<Device>);
|
||||
|
||||
impl Global for GlobalDevice {}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub enum DeviceState {
|
||||
Master,
|
||||
Minion,
|
||||
#[default]
|
||||
None,
|
||||
}
|
||||
|
||||
impl DeviceState {
|
||||
pub fn subscribe(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
match self {
|
||||
Self::Master => {
|
||||
let client = get_client();
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let opts =
|
||||
SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Custom(DEVICE_REQUEST_KIND))
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
// Subscribe for the latest request
|
||||
client.subscribe(filter, Some(opts)).await?;
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Custom(DEVICE_REQUEST_KIND))
|
||||
.author(public_key)
|
||||
.since(Timestamp::now());
|
||||
|
||||
// Subscribe for new device requests
|
||||
client.subscribe(filter, None).await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
cx.spawn_in(window, |_, _cx| async move {
|
||||
if let Err(err) = task.await {
|
||||
log::error!("Failed to subscribe for device requests: {}", err);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
Self::Minion => {
|
||||
let client = get_client();
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let opts =
|
||||
SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Custom(DEVICE_RESPONSE_KIND))
|
||||
.author(public_key);
|
||||
|
||||
// Getting all previous approvals
|
||||
client.subscribe(filter.clone(), Some(opts)).await?;
|
||||
|
||||
// Continously receive the request approval
|
||||
client
|
||||
.subscribe(filter.since(Timestamp::now()), None)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
cx.spawn_in(window, |_, _cx| async move {
|
||||
if let Err(err) = task.await {
|
||||
log::error!("Failed to subscribe for device approval: {}", err);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Current Device (Client)
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
#[derive(Debug)]
|
||||
pub struct Device {
|
||||
/// Profile (Metadata) of current user
|
||||
profile: Option<NostrProfile>,
|
||||
/// Client Keys
|
||||
client_keys: Arc<Keys>,
|
||||
/// Device State
|
||||
state: Entity<DeviceState>,
|
||||
requesters: Entity<HashSet<PublicKey>>,
|
||||
is_processing: bool,
|
||||
}
|
||||
|
||||
pub fn init(window: &mut Window, cx: &App) {
|
||||
// Initialize client keys
|
||||
let read_keys = cx.read_credentials(CLIENT_KEYRING);
|
||||
let window_handle = window.window_handle();
|
||||
|
||||
cx.spawn(|cx| async move {
|
||||
let client_keys = if let Ok(Some((_, secret))) = read_keys.await {
|
||||
let secret_key = SecretKey::from_slice(&secret).unwrap();
|
||||
|
||||
Arc::new(Keys::new(secret_key))
|
||||
} else {
|
||||
// Generate new keys and save them to keyring
|
||||
let keys = Keys::generate();
|
||||
|
||||
if let Ok(write_keys) = cx.update(|cx| {
|
||||
cx.write_credentials(
|
||||
CLIENT_KEYRING,
|
||||
keys.public_key.to_hex().as_str(),
|
||||
keys.secret_key().as_secret_bytes(),
|
||||
)
|
||||
}) {
|
||||
_ = write_keys.await;
|
||||
};
|
||||
|
||||
Arc::new(keys)
|
||||
};
|
||||
|
||||
cx.update(|cx| {
|
||||
let state = cx.new(|_| DeviceState::None);
|
||||
let weak_state = state.downgrade();
|
||||
let requesters = cx.new(|_| HashSet::new());
|
||||
let entity = cx.new(|_| Device {
|
||||
profile: None,
|
||||
is_processing: false,
|
||||
state,
|
||||
client_keys,
|
||||
requesters,
|
||||
});
|
||||
|
||||
window_handle
|
||||
.update(cx, |_, window, cx| {
|
||||
// Open the onboarding view
|
||||
Root::update(window, cx, |this, window, cx| {
|
||||
this.replace_view(onboarding::init(window, cx).into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Observe the DeviceState changes
|
||||
if let Some(state) = weak_state.upgrade() {
|
||||
window
|
||||
.observe(&state, cx, |this, window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.subscribe(window, cx);
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
};
|
||||
|
||||
// Observe the Device changes
|
||||
window
|
||||
.observe(&entity, cx, |this, window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.on_device_change(window, cx);
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
})
|
||||
.ok();
|
||||
|
||||
Device::set_global(entity, cx)
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
impl Device {
|
||||
pub fn global(cx: &App) -> Option<Entity<Self>> {
|
||||
cx.try_global::<GlobalDevice>().map(|model| model.0.clone())
|
||||
}
|
||||
|
||||
pub fn set_global(device: Entity<Self>, cx: &mut App) {
|
||||
cx.set_global(GlobalDevice(device));
|
||||
}
|
||||
|
||||
pub fn client_keys(&self) -> Arc<Keys> {
|
||||
self.client_keys.clone()
|
||||
}
|
||||
|
||||
pub fn profile(&self) -> Option<&NostrProfile> {
|
||||
self.profile.as_ref()
|
||||
}
|
||||
|
||||
pub fn set_profile(&mut self, profile: NostrProfile, cx: &mut Context<Self>) {
|
||||
self.profile = Some(profile);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn set_state(&mut self, state: DeviceState, cx: &mut Context<Self>) {
|
||||
self.state.update(cx, |this, cx| {
|
||||
*this = state;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_processing(&mut self, is_processing: bool, cx: &mut Context<Self>) {
|
||||
self.is_processing = is_processing;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn add_requester(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||
self.requesters.update(cx, |this, cx| {
|
||||
this.insert(public_key);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
/// Login and set user signer
|
||||
pub fn login<T>(&self, signer: T, cx: &mut Context<Self>) -> Task<Result<(), Error>>
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
let client = get_client();
|
||||
|
||||
// Set the user's signer as the main signer
|
||||
let login: Task<Result<NostrProfile, Error>> = cx.background_spawn(async move {
|
||||
// Use user's signer for main signer
|
||||
_ = client.set_signer(signer).await;
|
||||
|
||||
// Verify nostr signer and get public key
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
// Fetch user's metadata
|
||||
let metadata = client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
|
||||
// Get user's inbox relays
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
let relays = if let Some(event) = client
|
||||
.fetch_events(filter, Duration::from_secs(2))
|
||||
.await?
|
||||
.first_owned()
|
||||
{
|
||||
let relays = event
|
||||
.tags
|
||||
.filter_standardized(TagKind::Relay)
|
||||
.filter_map(|t| {
|
||||
if let TagStandard::Relay(url) = t {
|
||||
Some(url.to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<SmallVec<[RelayUrl; 3]>>();
|
||||
|
||||
Some(relays)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let profile = NostrProfile::new(public_key, metadata).relays(relays);
|
||||
|
||||
Ok(profile)
|
||||
});
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
match login.await {
|
||||
Ok(user) => {
|
||||
cx.update(|cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.profile = Some(user);
|
||||
cx.notify();
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// This function is called whenever the device is changed
|
||||
fn on_device_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(profile) = self.profile.as_ref() else {
|
||||
// User not logged in, render the Onboarding View
|
||||
Root::update(window, cx, |this, window, cx| {
|
||||
this.replace_view(onboarding::init(window, cx).into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
// Replace the Onboarding View with the Dock View
|
||||
Root::update(window, cx, |this, window, cx| {
|
||||
this.replace_view(app::init(window, cx).into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Get the user's messaging relays
|
||||
// If it is empty, user must setup relays
|
||||
let ready = profile.messaging_relays.is_some();
|
||||
|
||||
cx.spawn_in(window, |this, mut cx| async move {
|
||||
cx.update(|window, cx| {
|
||||
if !ready {
|
||||
this.update(cx, |this, cx| {
|
||||
this.render_setup_relays(window, cx);
|
||||
})
|
||||
.ok();
|
||||
} else {
|
||||
this.update(cx, |this, cx| {
|
||||
this.start_subscription(cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Initialize subscription for current user
|
||||
pub fn start_subscription(&self, cx: &Context<Self>) {
|
||||
if self.is_processing {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(profile) = self.profile() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let user = profile.public_key;
|
||||
let client = get_client();
|
||||
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
let device_kind = Kind::Custom(DEVICE_ANNOUNCEMENT_KIND);
|
||||
|
||||
// Create a device announcement filter
|
||||
let device = Filter::new().kind(device_kind).author(user).limit(1);
|
||||
|
||||
// Create a contact list filter
|
||||
let contacts = Filter::new().kind(Kind::ContactList).author(user).limit(1);
|
||||
|
||||
// Create a user's data filter
|
||||
let data = Filter::new()
|
||||
.author(user)
|
||||
.since(Timestamp::now())
|
||||
.kinds(vec![
|
||||
Kind::Metadata,
|
||||
Kind::InboxRelays,
|
||||
Kind::RelayList,
|
||||
device_kind,
|
||||
]);
|
||||
|
||||
// Create a filter for getting all gift wrapped events send to current user
|
||||
let msg = Filter::new().kind(Kind::GiftWrap).pubkey(user);
|
||||
|
||||
// Create a filter to continuously receive new messages.
|
||||
let new_msg = Filter::new().kind(Kind::GiftWrap).pubkey(user).limit(0);
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
// Only subscribe to the latest device announcement
|
||||
let sub_id = SubscriptionId::new(DEVICE_SUB_ID);
|
||||
client.subscribe_with_id(sub_id, device, Some(opts)).await?;
|
||||
|
||||
// Only subscribe to the latest contact list
|
||||
client.subscribe(contacts, Some(opts)).await?;
|
||||
|
||||
// Continuously receive new user's data since now
|
||||
client.subscribe(data, None).await?;
|
||||
|
||||
let sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
|
||||
client.subscribe_with_id(sub_id, msg, Some(opts)).await?;
|
||||
|
||||
let sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
|
||||
client.subscribe_with_id(sub_id, new_msg, None).await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
cx.spawn(|_, _| async move {
|
||||
if let Err(e) = task.await {
|
||||
log::error!("Subscription error: {}", e);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Setup Device
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn setup_device(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(profile) = self.profile().cloned() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// If processing, return early
|
||||
if self.is_processing {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only process if device keys are not set
|
||||
self.set_processing(true, cx);
|
||||
|
||||
let client = get_client();
|
||||
let public_key = profile.public_key;
|
||||
let kind = Kind::Custom(DEVICE_ANNOUNCEMENT_KIND);
|
||||
let filter = Filter::new().kind(kind).author(public_key).limit(1);
|
||||
|
||||
// Fetch device announcement events
|
||||
let fetch_announcement = cx.background_spawn(async move {
|
||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||
Ok(event)
|
||||
} else {
|
||||
Err(anyhow!("Device Announcement not found."))
|
||||
}
|
||||
});
|
||||
|
||||
cx.spawn_in(window, |this, mut cx| async move {
|
||||
// Device Keys has been set, no need to retrieve device announcement again
|
||||
if get_device_keys().await.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
match fetch_announcement.await {
|
||||
Ok(event) => {
|
||||
log::info!("Found a device announcement: {:?}", event);
|
||||
|
||||
let n_tag = event
|
||||
.tags
|
||||
.find(TagKind::custom("n"))
|
||||
.and_then(|t| t.content())
|
||||
.map(|hex| hex.to_owned());
|
||||
|
||||
let credentials_task =
|
||||
match cx.update(|_, cx| cx.read_credentials(MASTER_KEYRING)) {
|
||||
Ok(task) => task,
|
||||
Err(err) => {
|
||||
log::error!("Failed to read credentials: {:?}", err);
|
||||
log::info!("Trying to request keys from Master Device...");
|
||||
|
||||
cx.update(|window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.request_master_keys(window, cx);
|
||||
})
|
||||
})
|
||||
.ok();
|
||||
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
match credentials_task.await {
|
||||
Ok(Some((pubkey, secret))) if n_tag.as_deref() == Some(&pubkey) => {
|
||||
cx.update(|window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_master_keys(secret, window, cx);
|
||||
})
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
_ => {
|
||||
log::info!("This device is not the Master Device.");
|
||||
log::info!("Trying to request keys from Master Device...");
|
||||
|
||||
cx.update(|window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.request_master_keys(window, cx);
|
||||
})
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
log::info!("Device Announcement not found.");
|
||||
log::info!("Appoint this device as Master Device.");
|
||||
|
||||
cx.update(|window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_new_master_keys(window, cx);
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Create a new Master Keys, appointing this device as Master Device.
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn set_new_master_keys(&self, window: &mut Window, cx: &Context<Self>) {
|
||||
let client = get_client();
|
||||
let app_name = get_app_name();
|
||||
|
||||
let task: Task<Result<Arc<Keys>, Error>> = cx.background_spawn(async move {
|
||||
let keys = Keys::generate();
|
||||
let kind = Kind::Custom(DEVICE_ANNOUNCEMENT_KIND);
|
||||
let client_tag = Tag::client(app_name);
|
||||
let pubkey_tag = Tag::custom(TagKind::custom("n"), vec![keys.public_key().to_hex()]);
|
||||
|
||||
let event = EventBuilder::new(kind, "").tags(vec![client_tag, pubkey_tag]);
|
||||
|
||||
if let Err(e) = client.send_event_builder(event).await {
|
||||
log::error!("Failed to send Device Announcement: {}", e);
|
||||
} else {
|
||||
log::info!("Device Announcement has been sent");
|
||||
}
|
||||
|
||||
Ok(Arc::new(keys))
|
||||
});
|
||||
|
||||
cx.spawn_in(window, |this, mut cx| async move {
|
||||
if get_device_keys().await.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Ok(keys) = task.await {
|
||||
// Update global state
|
||||
set_device_keys(keys.clone()).await;
|
||||
|
||||
// Save keys
|
||||
if let Ok(task) = cx.update(|_, cx| {
|
||||
cx.write_credentials(
|
||||
MASTER_KEYRING,
|
||||
keys.public_key().to_hex().as_str(),
|
||||
keys.secret_key().as_secret_bytes(),
|
||||
)
|
||||
}) {
|
||||
if let Err(e) = task.await {
|
||||
log::error!("Failed to write device keys to keyring: {}", e);
|
||||
}
|
||||
};
|
||||
|
||||
cx.update(|_, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_state(DeviceState::Master, cx);
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Device already has Master Keys, re-appointing this device as Master Device.
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn set_master_keys(&self, secret: Vec<u8>, window: &mut Window, cx: &Context<Self>) {
|
||||
let Ok(secret_key) = SecretKey::from_slice(&secret) else {
|
||||
log::error!("Failed to parse secret key");
|
||||
return;
|
||||
};
|
||||
let keys = Arc::new(Keys::new(secret_key));
|
||||
|
||||
cx.spawn_in(window, |this, mut cx| async move {
|
||||
log::info!("Re-appointing this device as Master Device.");
|
||||
set_device_keys(keys).await;
|
||||
|
||||
cx.update(|_, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_state(DeviceState::Master, cx);
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Send a request to ask for device keys from the other Nostr client
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn request_master_keys(&self, window: &mut Window, cx: &Context<Self>) {
|
||||
let client = get_client();
|
||||
let app_name = get_app_name();
|
||||
let client_keys = self.client_keys.clone();
|
||||
|
||||
let kind = Kind::Custom(DEVICE_REQUEST_KIND);
|
||||
let client_tag = Tag::client(app_name);
|
||||
let pubkey_tag = Tag::custom(
|
||||
TagKind::custom("pubkey"),
|
||||
vec![client_keys.public_key().to_hex()],
|
||||
);
|
||||
|
||||
// Create a request event builder
|
||||
let builder = EventBuilder::new(kind, "").tags(vec![client_tag, pubkey_tag]);
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
log::info!("Sent a request to ask for device keys from the other Nostr client");
|
||||
|
||||
if let Err(e) = client.send_event_builder(builder).await {
|
||||
log::error!("Failed to send device keys request: {}", e);
|
||||
} else {
|
||||
log::info!("Waiting for response...");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
cx.spawn_in(window, |this, mut cx| async move {
|
||||
if task.await.is_ok() {
|
||||
cx.update(|window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_state(DeviceState::Minion, cx);
|
||||
this.render_waiting_modal(window, cx);
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Received Device Keys approval from Master Device,
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn recv_approval(&self, event: Event, window: &mut Window, cx: &Context<Self>) {
|
||||
let local_signer = self.client_keys.clone();
|
||||
|
||||
let task = cx.background_spawn(async move {
|
||||
if let Some(tag) = event
|
||||
.tags
|
||||
.find(TagKind::custom("P"))
|
||||
.and_then(|tag| tag.content())
|
||||
{
|
||||
if let Ok(public_key) = PublicKey::from_str(tag) {
|
||||
let secret = local_signer
|
||||
.nip44_decrypt(&public_key, &event.content)
|
||||
.await?;
|
||||
|
||||
let keys = Arc::new(Keys::parse(&secret)?);
|
||||
|
||||
// Update global state with new device keys
|
||||
set_device_keys(keys).await;
|
||||
log::info!("Received master keys");
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("Public Key is invalid"))
|
||||
}
|
||||
} else {
|
||||
Err(anyhow!("Failed to decrypt the Master Keys"))
|
||||
}
|
||||
});
|
||||
|
||||
cx.spawn_in(window, |_, mut cx| async move {
|
||||
// No need to update if device keys are already available
|
||||
if get_device_keys().await.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(e) = task.await {
|
||||
cx.update(|window, cx| {
|
||||
window.push_notification(
|
||||
Notification::error(format!("Failed to decrypt: {}", e)),
|
||||
cx,
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
} else {
|
||||
cx.update(|window, cx| {
|
||||
window.close_all_modals(cx);
|
||||
window.push_notification(
|
||||
Notification::success("Device Keys request has been approved"),
|
||||
cx,
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Received Master Keys request from other Nostr client
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn recv_request(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(target_pubkey) = event
|
||||
.tags
|
||||
.find(TagKind::custom("pubkey"))
|
||||
.and_then(|tag| tag.content())
|
||||
.and_then(|content| PublicKey::parse(content).ok())
|
||||
else {
|
||||
log::error!("Invalid public key.");
|
||||
return;
|
||||
};
|
||||
|
||||
// Prevent processing duplicate requests
|
||||
if self.requesters.read(cx).contains(&target_pubkey) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.add_requester(target_pubkey, cx);
|
||||
|
||||
let client = get_client();
|
||||
let read_keys = cx.read_credentials(MASTER_KEYRING);
|
||||
let local_signer = self.client_keys.clone();
|
||||
|
||||
let device_name = event
|
||||
.tags
|
||||
.find(TagKind::Client)
|
||||
.and_then(|tag| tag.content())
|
||||
.unwrap_or("Other Device")
|
||||
.to_owned();
|
||||
|
||||
let response = window.prompt(
|
||||
gpui::PromptLevel::Info,
|
||||
"Requesting Device Keys",
|
||||
Some(
|
||||
format!(
|
||||
"{} is requesting shared device keys stored in this device",
|
||||
device_name
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
&["Approve", "Deny"],
|
||||
cx,
|
||||
);
|
||||
|
||||
cx.spawn_in(window, |_, cx| async move {
|
||||
match response.await {
|
||||
Ok(0) => {
|
||||
if let Ok(Some((_, secret))) = read_keys.await {
|
||||
let local_pubkey = local_signer.get_public_key().await?;
|
||||
|
||||
// Get device's secret key
|
||||
let device_secret = SecretKey::from_slice(&secret)?;
|
||||
let device_secret_hex = device_secret.to_secret_hex();
|
||||
|
||||
// Encrypt device's secret key by using NIP-44
|
||||
let content = local_signer
|
||||
.nip44_encrypt(&target_pubkey, &device_secret_hex)
|
||||
.await?;
|
||||
|
||||
// Create pubkey tag for other device (lowercase p)
|
||||
let other_tag = Tag::public_key(target_pubkey);
|
||||
|
||||
// Create pubkey tag for this device (uppercase P)
|
||||
let local_tag = Tag::custom(
|
||||
TagKind::SingleLetter(SingleLetterTag::uppercase(Alphabet::P)),
|
||||
vec![local_pubkey.to_hex()],
|
||||
);
|
||||
|
||||
// Create event builder
|
||||
let kind = Kind::Custom(DEVICE_RESPONSE_KIND);
|
||||
let tags = vec![other_tag, local_tag];
|
||||
let builder = EventBuilder::new(kind, content).tags(tags);
|
||||
|
||||
cx.background_spawn(async move {
|
||||
if let Err(err) = client.send_event_builder(builder).await {
|
||||
log::error!("Failed to send device keys to other client: {}", err);
|
||||
} else {
|
||||
log::info!("Sent device keys to other client");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("Device Keys not found"))
|
||||
}
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Show setup relays modal
|
||||
///
|
||||
/// NIP-17: <https://github.com/nostr-protocol/nips/blob/master/17.md>
|
||||
pub fn render_setup_relays(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let relays = relays::init(window, cx);
|
||||
|
||||
window.open_modal(cx, move |this, window, cx| {
|
||||
let is_loading = relays.read(cx).loading();
|
||||
|
||||
this.keyboard(false)
|
||||
.closable(false)
|
||||
.width(px(430.))
|
||||
.title("Your Messaging Relays are not configured")
|
||||
.child(relays.clone())
|
||||
.footer(
|
||||
div()
|
||||
.p_2()
|
||||
.border_t_1()
|
||||
.border_color(cx.theme().base.step(cx, ColorScaleStep::FIVE))
|
||||
.child(
|
||||
Button::new("update_inbox_relays_btn")
|
||||
.label("Update")
|
||||
.primary()
|
||||
.bold()
|
||||
.rounded(ButtonRounded::Large)
|
||||
.w_full()
|
||||
.loading(is_loading)
|
||||
.on_click(window.listener_for(&relays, |this, _, window, cx| {
|
||||
this.update(window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// Show waiting modal
|
||||
///
|
||||
/// NIP-4e: <https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md>
|
||||
pub fn render_waiting_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
window.open_modal(cx, move |this, _window, cx| {
|
||||
let msg = format!(
|
||||
"Please open {} and approve sharing device keys request.",
|
||||
get_device_name()
|
||||
);
|
||||
|
||||
this.keyboard(false)
|
||||
.closable(false)
|
||||
.width(px(430.))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.size_full()
|
||||
.p_4()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.size_full()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.text_sm()
|
||||
.child(
|
||||
div()
|
||||
.font_semibold()
|
||||
.child("You're using a new device."),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_color(
|
||||
cx.theme()
|
||||
.base
|
||||
.step(cx, ColorScaleStep::ELEVEN),
|
||||
)
|
||||
.line_height(relative(1.3))
|
||||
.child(msg),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.footer(
|
||||
div()
|
||||
.p_4()
|
||||
.border_t_1()
|
||||
.border_color(cx.theme().base.step(cx, ColorScaleStep::FIVE))
|
||||
.w_full()
|
||||
.flex()
|
||||
.gap_2()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().base.step(cx, ColorScaleStep::ELEVEN))
|
||||
.child(Indicator::new().small())
|
||||
.child("Waiting for approval ..."),
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,46 +1,55 @@
|
||||
use anyhow::anyhow;
|
||||
use asset::Assets;
|
||||
use chats::registry::ChatRegistry;
|
||||
use common::constants::{
|
||||
ALL_MESSAGES_SUB_ID, APP_ID, APP_NAME, KEYRING_SERVICE, NEW_MESSAGE_SUB_ID,
|
||||
};
|
||||
use device::Device;
|
||||
use futures::{select, FutureExt};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
use global::constants::APP_NAME;
|
||||
use global::{
|
||||
constants::{
|
||||
ALL_MESSAGES_SUB_ID, APP_ID, BOOTSTRAP_RELAYS, DEVICE_ANNOUNCEMENT_KIND,
|
||||
DEVICE_REQUEST_KIND, DEVICE_RESPONSE_KIND, DEVICE_SUB_ID, NEW_MESSAGE_SUB_ID,
|
||||
},
|
||||
get_client, get_device_keys, set_device_name,
|
||||
};
|
||||
use gpui::{
|
||||
actions, px, size, App, AppContext, Application, AsyncApp, Bounds, KeyBinding, Menu, MenuItem,
|
||||
actions, px, size, App, AppContext, Application, Bounds, KeyBinding, Menu, MenuItem,
|
||||
WindowBounds, WindowKind, WindowOptions,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
use gpui::{point, SharedString, TitlebarOptions};
|
||||
#[cfg(target_os = "linux")]
|
||||
use gpui::{WindowBackgroundAppearance, WindowDecorations};
|
||||
use log::{error, info};
|
||||
use nostr_sdk::SubscriptionId;
|
||||
use nostr_sdk::{
|
||||
pool::prelude::ReqExitPolicy, Client, Event, Filter, Keys, Kind, PublicKey, RelayMessage,
|
||||
RelayPoolNotification, SubscribeAutoCloseOptions,
|
||||
nips::nip59::UnwrappedGift, pool::prelude::ReqExitPolicy, Event, Filter, Keys, Kind, PublicKey,
|
||||
RelayMessage, RelayPoolNotification, SubscribeAutoCloseOptions, SubscriptionId, TagKind,
|
||||
};
|
||||
use smol::Timer;
|
||||
use state::get_client;
|
||||
use std::{collections::HashSet, mem, sync::Arc, time::Duration};
|
||||
use ui::{theme::Theme, Root};
|
||||
use views::{app, onboarding};
|
||||
use views::startup;
|
||||
|
||||
mod asset;
|
||||
mod views;
|
||||
pub(crate) mod asset;
|
||||
pub(crate) mod device;
|
||||
pub(crate) mod views;
|
||||
|
||||
actions!(coop, [Quit]);
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Debug)]
|
||||
enum Signal {
|
||||
/// Receive event
|
||||
Event(Event),
|
||||
/// Receive request master key event
|
||||
RequestMasterKey(Event),
|
||||
/// Receive approve master key event
|
||||
ReceiveMasterKey(Event),
|
||||
/// Receive announcement event
|
||||
ReceiveAnnouncement,
|
||||
/// Receive EOSE
|
||||
Eose,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Fix crash on startup
|
||||
// TODO: why this is needed?
|
||||
_ = rustls::crypto::ring::default_provider().install_default();
|
||||
// Enable logging
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
@@ -58,11 +67,17 @@ fn main() {
|
||||
// Connect to default relays
|
||||
app.background_executor()
|
||||
.spawn(async {
|
||||
_ = client.add_relay("wss://relay.damus.io/").await;
|
||||
_ = client.add_relay("wss://relay.primal.net/").await;
|
||||
_ = client.add_relay("wss://user.kindpag.es/").await;
|
||||
_ = client.add_relay("wss://purplepag.es/").await;
|
||||
// Fix crash on startup
|
||||
// TODO: why this is needed?
|
||||
_ = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
||||
|
||||
for relay in BOOTSTRAP_RELAYS.into_iter() {
|
||||
_ = client.add_relay(relay).await;
|
||||
}
|
||||
|
||||
_ = client.add_discovery_relay("wss://relaydiscovery.com").await;
|
||||
_ = client.add_discovery_relay("wss://user.kindpag.es").await;
|
||||
|
||||
_ = client.connect().await
|
||||
})
|
||||
.detach();
|
||||
@@ -71,7 +86,7 @@ fn main() {
|
||||
app.background_executor()
|
||||
.spawn(async move {
|
||||
const BATCH_SIZE: usize = 20;
|
||||
const BATCH_TIMEOUT: Duration = Duration::from_millis(200);
|
||||
const BATCH_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
let mut batch: HashSet<PublicKey> = HashSet::new();
|
||||
|
||||
@@ -84,7 +99,7 @@ fn main() {
|
||||
Ok(keys) => {
|
||||
batch.extend(keys);
|
||||
if batch.len() >= BATCH_SIZE {
|
||||
sync_metadata(client, mem::take(&mut batch)).await;
|
||||
handle_metadata(mem::take(&mut batch)).await;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
@@ -92,7 +107,7 @@ fn main() {
|
||||
}
|
||||
_ = timeout => {
|
||||
if !batch.is_empty() {
|
||||
sync_metadata(client, mem::take(&mut batch)).await;
|
||||
handle_metadata(mem::take(&mut batch)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,6 +121,7 @@ fn main() {
|
||||
let rng_keys = Keys::generate();
|
||||
let all_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
|
||||
let new_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
|
||||
let device_id = SubscriptionId::new(DEVICE_SUB_ID);
|
||||
let mut notifications = client.notifications();
|
||||
|
||||
while let Ok(notification) = notifications.recv().await {
|
||||
@@ -117,52 +133,73 @@ fn main() {
|
||||
} => {
|
||||
match event.kind {
|
||||
Kind::GiftWrap => {
|
||||
if let Ok(gift) = client.unwrap_gift_wrap(&event).await {
|
||||
let mut pubkeys = vec![];
|
||||
|
||||
if let Ok(gift) = handle_gift_wrap(&event).await {
|
||||
// Sign the rumor with the generated keys,
|
||||
// this event will be used for internal only,
|
||||
// and NEVER send to relays.
|
||||
if let Ok(event) = gift.rumor.sign_with_keys(&rng_keys) {
|
||||
let mut pubkeys = vec![];
|
||||
pubkeys.extend(event.tags.public_keys());
|
||||
pubkeys.push(event.pubkey);
|
||||
|
||||
// Save the event to the database, use for query directly.
|
||||
if let Err(e) =
|
||||
client.database().save_event(&event).await
|
||||
{
|
||||
error!("Failed to save event: {}", e);
|
||||
}
|
||||
|
||||
// Send all pubkeys to the batch
|
||||
if let Err(e) = batch_tx.send(pubkeys).await {
|
||||
error!("Failed to send pubkeys to batch: {}", e)
|
||||
}
|
||||
_ = client.database().save_event(&event).await;
|
||||
|
||||
// Send this event to the GPUI
|
||||
if new_id == *subscription_id {
|
||||
if let Err(e) =
|
||||
event_tx.send(Signal::Event(event)).await
|
||||
{
|
||||
error!("Failed to send event to GPUI: {}", e)
|
||||
}
|
||||
_ = event_tx.send(Signal::Event(event)).await;
|
||||
}
|
||||
|
||||
// Send all pubkeys to the batch
|
||||
_ = batch_tx.send(pubkeys).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::ContactList => {
|
||||
let pubkeys =
|
||||
event.tags.public_keys().copied().collect::<HashSet<_>>();
|
||||
sync_metadata(client, pubkeys).await;
|
||||
|
||||
handle_metadata(pubkeys).await;
|
||||
}
|
||||
Kind::Custom(DEVICE_REQUEST_KIND) => {
|
||||
log::info!("Received device keys request");
|
||||
|
||||
_ = event_tx
|
||||
.send(Signal::RequestMasterKey(event.into_owned()))
|
||||
.await;
|
||||
}
|
||||
Kind::Custom(DEVICE_RESPONSE_KIND) => {
|
||||
log::info!("Received device keys approval");
|
||||
|
||||
_ = event_tx
|
||||
.send(Signal::ReceiveMasterKey(event.into_owned()))
|
||||
.await;
|
||||
}
|
||||
Kind::Custom(DEVICE_ANNOUNCEMENT_KIND) => {
|
||||
log::info!("Device Announcement received");
|
||||
|
||||
if let Ok(signer) = client.signer().await {
|
||||
if let Ok(public_key) = signer.get_public_key().await {
|
||||
if event.pubkey == public_key {
|
||||
if let Some(tag) = event
|
||||
.tags
|
||||
.find(TagKind::custom("client"))
|
||||
.and_then(|tag| tag.content())
|
||||
{
|
||||
set_device_name(tag).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
RelayMessage::EndOfStoredEvents(subscription_id) => {
|
||||
if all_id == *subscription_id {
|
||||
if let Err(e) = event_tx.send(Signal::Eose).await {
|
||||
error!("Failed to send eose: {}", e)
|
||||
};
|
||||
_ = event_tx.send(Signal::Eose).await;
|
||||
} else if device_id == *subscription_id {
|
||||
_ = event_tx.send(Signal::ReceiveAnnouncement).await;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -172,62 +209,24 @@ fn main() {
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Handle re-open window
|
||||
app.on_reopen(move |cx| {
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let is_login = client.signer().await.is_ok();
|
||||
_ = tx.send(is_login);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|mut cx| async move {
|
||||
if let Ok(is_login) = rx.await {
|
||||
_ = restore_window(is_login, &mut cx).await;
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
|
||||
app.run(move |cx| {
|
||||
// Initialize chat global state
|
||||
chats::registry::init(cx);
|
||||
// Initialize components
|
||||
ui::init(cx);
|
||||
// Bring the app to the foreground
|
||||
cx.activate(true);
|
||||
|
||||
// Register the `quit` function
|
||||
cx.on_action(quit);
|
||||
|
||||
// Register the `quit` function with CMD+Q
|
||||
cx.bind_keys([KeyBinding::new("cmd-q", Quit, None)]);
|
||||
|
||||
// Set menu items
|
||||
cx.set_menus(vec![Menu {
|
||||
name: "Coop".into(),
|
||||
items: vec![MenuItem::action("Quit", Quit)],
|
||||
}]);
|
||||
|
||||
// Spawn a task to handle events from nostr channel
|
||||
cx.spawn(|cx| async move {
|
||||
while let Ok(signal) = event_rx.recv().await {
|
||||
cx.update(|cx| {
|
||||
if let Some(chats) = ChatRegistry::global(cx) {
|
||||
match signal {
|
||||
Signal::Eose => chats.update(cx, |this, cx| this.load_chat_rooms(cx)),
|
||||
Signal::Event(event) => {
|
||||
chats.update(cx, |this, cx| this.push_message(event, cx))
|
||||
}
|
||||
};
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Set up the window options
|
||||
let window_opts = WindowOptions {
|
||||
let opts = WindowOptions {
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
titlebar: Some(TitlebarOptions {
|
||||
title: Some(SharedString::new_static(APP_NAME)),
|
||||
@@ -244,124 +243,118 @@ fn main() {
|
||||
#[cfg(target_os = "linux")]
|
||||
window_decorations: Some(WindowDecorations::Client),
|
||||
kind: WindowKind::Normal,
|
||||
app_id: Some(APP_ID.to_owned()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Create a task to read credentials from the keyring service
|
||||
let task = cx.read_credentials(KEYRING_SERVICE);
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
// Open a window with default options
|
||||
cx.open_window(opts, |window, cx| {
|
||||
// Automatically sync theme with system appearance
|
||||
window
|
||||
.observe_window_appearance(|window, cx| {
|
||||
Theme::sync_system_appearance(Some(window), cx);
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Read credential in OS Keyring
|
||||
cx.background_spawn(async {
|
||||
let is_ready = if let Ok(Some((_, secret))) = task.await {
|
||||
let result = async {
|
||||
let secret_hex = String::from_utf8(secret)?;
|
||||
let keys = Keys::parse(&secret_hex)?;
|
||||
// Initialize components
|
||||
ui::init(cx);
|
||||
|
||||
// Update nostr signer
|
||||
client.set_signer(keys).await;
|
||||
// Initialize chat global state
|
||||
chats::registry::init(cx);
|
||||
|
||||
Ok::<_, anyhow::Error>(true)
|
||||
}
|
||||
.await;
|
||||
// Initialize device
|
||||
device::init(window, cx);
|
||||
|
||||
result.is_ok()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
cx.new(|cx| {
|
||||
let root = Root::new(startup::init(window, cx).into(), window, cx);
|
||||
|
||||
_ = tx.send(is_ready)
|
||||
// Spawn a task to handle events from nostr channel
|
||||
cx.spawn_in(window, |_, mut cx| async move {
|
||||
while let Ok(signal) = event_rx.recv().await {
|
||||
cx.update(|window, cx| {
|
||||
match signal {
|
||||
Signal::Eose => {
|
||||
if let Some(chats) = ChatRegistry::global(cx) {
|
||||
chats.update(cx, |this, cx| this.load_chat_rooms(cx))
|
||||
}
|
||||
}
|
||||
Signal::Event(event) => {
|
||||
if let Some(chats) = ChatRegistry::global(cx) {
|
||||
chats.update(cx, |this, cx| this.push_message(event, cx))
|
||||
}
|
||||
}
|
||||
Signal::ReceiveAnnouncement => {
|
||||
if let Some(device) = Device::global(cx) {
|
||||
device.update(cx, |this, cx| {
|
||||
this.setup_device(window, cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
Signal::ReceiveMasterKey(event) => {
|
||||
if let Some(device) = Device::global(cx) {
|
||||
device.update(cx, |this, cx| {
|
||||
this.recv_approval(event, window, cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
Signal::RequestMasterKey(event) => {
|
||||
if let Some(device) = Device::global(cx) {
|
||||
device.update(cx, |this, cx| {
|
||||
this.recv_request(event, window, cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
root
|
||||
})
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|cx| async move {
|
||||
if let Ok(is_ready) = rx.await {
|
||||
if is_ready {
|
||||
// Open a App window
|
||||
cx.open_window(window_opts, |window, cx| {
|
||||
cx.new(|cx| Root::new(app::init(window, cx).into(), window, cx))
|
||||
})
|
||||
.expect("Failed to open window");
|
||||
} else {
|
||||
// Open a Onboarding window
|
||||
cx.open_window(window_opts, |window, cx| {
|
||||
cx.new(|cx| Root::new(onboarding::init(window, cx).into(), window, cx))
|
||||
})
|
||||
.expect("Failed to open window");
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
.expect("Failed to open window. Please restart the application.");
|
||||
});
|
||||
}
|
||||
|
||||
async fn sync_metadata(client: &Client, buffer: HashSet<PublicKey>) {
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
let filter = Filter::new()
|
||||
.authors(buffer.iter().cloned())
|
||||
.kind(Kind::Metadata)
|
||||
.limit(buffer.len());
|
||||
async fn handle_gift_wrap(gift_wrap: &Event) -> Result<UnwrappedGift, anyhow::Error> {
|
||||
let client = get_client();
|
||||
|
||||
if let Err(e) = client.subscribe(filter, Some(opts)).await {
|
||||
error!("Subscribe error: {e}");
|
||||
if let Some(device) = get_device_keys().await {
|
||||
// Try to unwrap with the device keys first
|
||||
match UnwrappedGift::from_gift_wrap(&device, gift_wrap).await {
|
||||
Ok(event) => Ok(event),
|
||||
Err(_) => {
|
||||
// Try to unwrap again with the user's signer
|
||||
let signer = client.signer().await?;
|
||||
let event = UnwrappedGift::from_gift_wrap(&signer, gift_wrap).await?;
|
||||
Ok(event)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(anyhow!("Signer not found"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn restore_window(is_login: bool, cx: &mut AsyncApp) -> anyhow::Result<()> {
|
||||
let opts = cx
|
||||
.update(|cx| WindowOptions {
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
titlebar: Some(TitlebarOptions {
|
||||
title: Some(SharedString::new_static(APP_NAME)),
|
||||
traffic_light_position: Some(point(px(9.0), px(9.0))),
|
||||
appears_transparent: true,
|
||||
}),
|
||||
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
|
||||
None,
|
||||
size(px(900.0), px(680.0)),
|
||||
cx,
|
||||
))),
|
||||
#[cfg(target_os = "linux")]
|
||||
window_background: WindowBackgroundAppearance::Transparent,
|
||||
#[cfg(target_os = "linux")]
|
||||
window_decorations: Some(WindowDecorations::Client),
|
||||
kind: WindowKind::Normal,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("Failed to set window options.");
|
||||
async fn handle_metadata(buffer: HashSet<PublicKey>) {
|
||||
let client = get_client();
|
||||
|
||||
if is_login {
|
||||
_ = cx.open_window(opts, |window, cx| {
|
||||
window.set_window_title(APP_NAME);
|
||||
window.set_app_id(APP_ID);
|
||||
let opts = SubscribeAutoCloseOptions::default()
|
||||
.exit_policy(ReqExitPolicy::ExitOnEOSE)
|
||||
.idle_timeout(Some(Duration::from_secs(2)));
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
window
|
||||
.observe_window_appearance(|window, cx| {
|
||||
Theme::sync_system_appearance(Some(window), cx);
|
||||
})
|
||||
.detach();
|
||||
let filter = Filter::new()
|
||||
.authors(buffer.iter().cloned())
|
||||
.limit(buffer.len() * 2)
|
||||
.kinds(vec![Kind::Metadata, Kind::Custom(DEVICE_ANNOUNCEMENT_KIND)]);
|
||||
|
||||
cx.new(|cx| Root::new(app::init(window, cx).into(), window, cx))
|
||||
});
|
||||
} else {
|
||||
_ = cx.open_window(opts, |window, cx| {
|
||||
window.set_window_title(APP_NAME);
|
||||
window.set_app_id(APP_ID);
|
||||
window
|
||||
.observe_window_appearance(|window, cx| {
|
||||
Theme::sync_system_appearance(Some(window), cx);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.new(|cx| Root::new(onboarding::init(window, cx).into(), window, cx))
|
||||
});
|
||||
};
|
||||
|
||||
Ok(())
|
||||
if let Err(e) = client.subscribe(filter, Some(opts)).await {
|
||||
log::error!("Failed to sync metadata: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn quit(_: &Quit, cx: &mut App) {
|
||||
info!("Gracefully quitting the application . . .");
|
||||
log::info!("Gracefully quitting the application . . .");
|
||||
cx.quit();
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use account::registry::Account;
|
||||
use global::get_client;
|
||||
use gpui::{
|
||||
actions, div, img, impl_internal_actions, prelude::FluentBuilder, px, App, AppContext, Axis,
|
||||
Context, Entity, InteractiveElement, IntoElement, ObjectFit, ParentElement, Render, Styled,
|
||||
StyledImage, Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use serde::Deserialize;
|
||||
use state::get_client;
|
||||
use std::sync::Arc;
|
||||
use ui::{
|
||||
button::{Button, ButtonRounded, ButtonVariants},
|
||||
@@ -16,7 +14,8 @@ use ui::{
|
||||
ContextModal, Icon, IconName, Root, Sizable, TitleBar,
|
||||
};
|
||||
|
||||
use super::{chat, contacts, onboarding, profile, relays::Relays, settings, sidebar, welcome};
|
||||
use super::{chat, contacts, onboarding, profile, relays, settings, sidebar, welcome};
|
||||
use crate::device::Device;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Deserialize)]
|
||||
pub enum PanelKind {
|
||||
@@ -40,6 +39,7 @@ impl AddPanel {
|
||||
|
||||
// Dock actions
|
||||
impl_internal_actions!(dock, [AddPanel]);
|
||||
|
||||
// Account actions
|
||||
actions!(account, [Logout]);
|
||||
|
||||
@@ -48,7 +48,6 @@ pub fn init(window: &mut Window, cx: &mut App) -> Entity<AppView> {
|
||||
}
|
||||
|
||||
pub struct AppView {
|
||||
relays: Entity<Option<Vec<String>>>,
|
||||
dock: Entity<DockArea>,
|
||||
}
|
||||
|
||||
@@ -83,85 +82,81 @@ impl AppView {
|
||||
view.set_center(center_panel, window, cx);
|
||||
});
|
||||
|
||||
cx.new(|cx| {
|
||||
let relays = cx.new(|_| None);
|
||||
let this = Self { relays, dock };
|
||||
|
||||
// Check user's messaging relays and determine user is ready for NIP17 or not.
|
||||
// If not, show the setup modal and instruct user setup inbox relays
|
||||
this.verify_user_relays(window, cx);
|
||||
|
||||
this
|
||||
})
|
||||
cx.new(|_| Self { dock })
|
||||
}
|
||||
|
||||
fn verify_user_relays(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(account) = Account::global(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let public_key = account.read(cx).get().public_key();
|
||||
let client = get_client();
|
||||
let window_handle = window.window_handle();
|
||||
let (tx, rx) = oneshot::channel::<Option<Vec<String>>>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
let relays = client
|
||||
.database()
|
||||
.query(filter)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|events| events.first_owned())
|
||||
.map(|event| {
|
||||
event
|
||||
.tags
|
||||
.filter_standardized(TagKind::Relay)
|
||||
.filter_map(|t| match t {
|
||||
TagStandard::Relay(url) => Some(url.to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
_ = tx.send(relays);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if let Ok(Some(relays)) = rx.await {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
let relays = cx.new(|_| Some(relays));
|
||||
this.relays = relays;
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
this.update(cx, |this: &mut Self, cx| {
|
||||
this.render_setup_relays(window, cx)
|
||||
})
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
fn render_mode_btn(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
Button::new("appearance")
|
||||
.xsmall()
|
||||
.ghost()
|
||||
.map(|this| {
|
||||
if cx.theme().appearance.is_dark() {
|
||||
this.icon(IconName::Sun)
|
||||
} else {
|
||||
this.icon(IconName::Moon)
|
||||
}
|
||||
})
|
||||
.on_click(cx.listener(|_, _, window, cx| {
|
||||
if cx.theme().appearance.is_dark() {
|
||||
Theme::change(Appearance::Light, Some(window), cx);
|
||||
} else {
|
||||
Theme::change(Appearance::Dark, Some(window), cx);
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn render_setup_relays(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let relays = cx.new(|cx| Relays::new(None, window, cx));
|
||||
fn render_account_btn(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
Button::new("account")
|
||||
.ghost()
|
||||
.xsmall()
|
||||
.reverse()
|
||||
.icon(Icon::new(IconName::ChevronDownSmall))
|
||||
.when_some(Device::global(cx), |this, account| {
|
||||
this.when_some(account.read(cx).profile(), |this, profile| {
|
||||
this.child(
|
||||
img(profile.avatar.clone())
|
||||
.size_5()
|
||||
.rounded_full()
|
||||
.object_fit(ObjectFit::Cover),
|
||||
)
|
||||
})
|
||||
})
|
||||
.popup_menu(move |this, _, _cx| {
|
||||
this.menu(
|
||||
"Profile",
|
||||
Box::new(AddPanel::new(PanelKind::Profile, DockPlacement::Right)),
|
||||
)
|
||||
.menu(
|
||||
"Contacts",
|
||||
Box::new(AddPanel::new(PanelKind::Contacts, DockPlacement::Right)),
|
||||
)
|
||||
.menu(
|
||||
"Settings",
|
||||
Box::new(AddPanel::new(PanelKind::Settings, DockPlacement::Center)),
|
||||
)
|
||||
.separator()
|
||||
.menu("Change account", Box::new(Logout))
|
||||
})
|
||||
}
|
||||
|
||||
fn render_relays_btn(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
Button::new("relays")
|
||||
.xsmall()
|
||||
.ghost()
|
||||
.icon(IconName::Relays)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.render_edit_relays(window, cx);
|
||||
}))
|
||||
}
|
||||
|
||||
fn render_edit_relays(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let relays = relays::init(window, cx);
|
||||
|
||||
window.open_modal(cx, move |this, window, cx| {
|
||||
let is_loading = relays.read(cx).loading();
|
||||
|
||||
this.keyboard(false)
|
||||
.closable(false)
|
||||
.width(px(420.))
|
||||
.title("Your Messaging Relays are not configured")
|
||||
this.width(px(420.))
|
||||
.title("Edit your Messaging Relays")
|
||||
.child(relays.clone())
|
||||
.footer(
|
||||
div()
|
||||
@@ -184,109 +179,6 @@ impl AppView {
|
||||
});
|
||||
}
|
||||
|
||||
fn render_edit_relay(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let relays = self.relays.read(cx).clone();
|
||||
let view = cx.new(|cx| Relays::new(relays, window, cx));
|
||||
|
||||
window.open_modal(cx, move |this, window, cx| {
|
||||
let is_loading = view.read(cx).loading();
|
||||
|
||||
this.width(px(420.))
|
||||
.title("Edit your Messaging Relays")
|
||||
.child(view.clone())
|
||||
.footer(
|
||||
div()
|
||||
.p_2()
|
||||
.border_t_1()
|
||||
.border_color(cx.theme().base.step(cx, ColorScaleStep::FIVE))
|
||||
.child(
|
||||
Button::new("update_inbox_relays_btn")
|
||||
.label("Update")
|
||||
.primary()
|
||||
.bold()
|
||||
.rounded(ButtonRounded::Large)
|
||||
.w_full()
|
||||
.loading(is_loading)
|
||||
.on_click(window.listener_for(&view, |this, _, window, cx| {
|
||||
this.update(window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
fn render_appearance_button(
|
||||
&self,
|
||||
_window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> impl IntoElement {
|
||||
Button::new("appearance")
|
||||
.xsmall()
|
||||
.ghost()
|
||||
.map(|this| {
|
||||
if cx.theme().appearance.is_dark() {
|
||||
this.icon(IconName::Sun)
|
||||
} else {
|
||||
this.icon(IconName::Moon)
|
||||
}
|
||||
})
|
||||
.on_click(cx.listener(|_, _, window, cx| {
|
||||
if cx.theme().appearance.is_dark() {
|
||||
Theme::change(Appearance::Light, Some(window), cx);
|
||||
} else {
|
||||
Theme::change(Appearance::Dark, Some(window), cx);
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn render_relays_button(
|
||||
&self,
|
||||
_window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> impl IntoElement {
|
||||
Button::new("relays")
|
||||
.xsmall()
|
||||
.ghost()
|
||||
.icon(IconName::Relays)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.render_edit_relay(window, cx);
|
||||
}))
|
||||
}
|
||||
|
||||
fn render_account(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
Button::new("account")
|
||||
.ghost()
|
||||
.xsmall()
|
||||
.reverse()
|
||||
.icon(Icon::new(IconName::ChevronDownSmall))
|
||||
.when_some(Account::global(cx), |this, account| {
|
||||
let profile = account.read(cx).get();
|
||||
|
||||
this.child(
|
||||
img(profile.avatar())
|
||||
.size_5()
|
||||
.rounded_full()
|
||||
.object_fit(ObjectFit::Cover),
|
||||
)
|
||||
})
|
||||
.popup_menu(move |this, _, _cx| {
|
||||
this.menu(
|
||||
"Profile",
|
||||
Box::new(AddPanel::new(PanelKind::Profile, DockPlacement::Right)),
|
||||
)
|
||||
.menu(
|
||||
"Contacts",
|
||||
Box::new(AddPanel::new(PanelKind::Contacts, DockPlacement::Right)),
|
||||
)
|
||||
.menu(
|
||||
"Settings",
|
||||
Box::new(AddPanel::new(PanelKind::Settings, DockPlacement::Center)),
|
||||
)
|
||||
.separator()
|
||||
.menu("Change account", Box::new(Logout))
|
||||
})
|
||||
}
|
||||
|
||||
fn on_panel_action(&mut self, action: &AddPanel, window: &mut Window, cx: &mut Context<Self>) {
|
||||
match &action.panel {
|
||||
PanelKind::Room(id) => {
|
||||
@@ -333,8 +225,9 @@ impl AppView {
|
||||
})
|
||||
.detach();
|
||||
|
||||
window.replace_root(cx, |window, cx| {
|
||||
Root::new(onboarding::init(window, cx).into(), window, cx)
|
||||
Root::update(window, cx, |this, window, cx| {
|
||||
this.replace_view(onboarding::init(window, cx).into());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -347,29 +240,37 @@ impl Render for AppView {
|
||||
div()
|
||||
.relative()
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
// Main
|
||||
.child(
|
||||
TitleBar::new()
|
||||
// Left side
|
||||
.child(div())
|
||||
// Right side
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.size_full()
|
||||
// Title Bar
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_end()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.child(self.render_appearance_button(window, cx))
|
||||
.child(self.render_relays_button(window, cx))
|
||||
.child(self.render_account(cx)),
|
||||
),
|
||||
TitleBar::new()
|
||||
// Left side
|
||||
.child(div())
|
||||
// Right side
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_end()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.child(self.render_mode_btn(cx))
|
||||
.child(self.render_relays_btn(cx))
|
||||
.child(self.render_account_btn(cx)),
|
||||
),
|
||||
)
|
||||
// Dock
|
||||
.child(self.dock.clone()),
|
||||
)
|
||||
.child(self.dock.clone())
|
||||
// Notifications
|
||||
.child(div().absolute().top_8().children(notification_layer))
|
||||
// Modals
|
||||
.children(modal_layer)
|
||||
// Actions
|
||||
.on_action(cx.listener(Self::on_panel_action))
|
||||
.on_action(cx.listener(Self::on_logout_action))
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use account::registry::Account;
|
||||
use anyhow::anyhow;
|
||||
use async_utility::task::spawn;
|
||||
use chats::{registry::ChatRegistry, room::Room};
|
||||
use common::{
|
||||
constants::IMAGE_SERVICE,
|
||||
last_seen::LastSeen,
|
||||
profile::NostrProfile,
|
||||
utils::{compare, nip96_upload},
|
||||
};
|
||||
use global::{constants::IMAGE_SERVICE, get_client};
|
||||
use gpui::{
|
||||
div, img, list, prelude::FluentBuilder, px, relative, svg, white, AnyElement, App, AppContext,
|
||||
Context, Element, Entity, EventEmitter, Flatten, FocusHandle, Focusable, InteractiveElement,
|
||||
@@ -18,7 +17,6 @@ use gpui::{
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
use smol::fs;
|
||||
use state::get_client;
|
||||
use std::sync::Arc;
|
||||
use ui::{
|
||||
button::{Button, ButtonRounded, ButtonVariants},
|
||||
@@ -30,7 +28,8 @@ use ui::{
|
||||
v_flex, ContextModal, Icon, IconName, Sizable, StyledExt,
|
||||
};
|
||||
|
||||
const ALERT: &str =
|
||||
const ALERT: &str = "has not set up Messaging (DM) Relays, so they will NOT receive your messages.";
|
||||
const DESCRIPTION: &str =
|
||||
"This conversation is private. Only members of this chat can see each other's messages.";
|
||||
|
||||
pub fn init(
|
||||
@@ -63,8 +62,8 @@ impl ParsedMessage {
|
||||
let created_at = LastSeen(created_at).human_readable();
|
||||
|
||||
Self {
|
||||
avatar: profile.avatar(),
|
||||
display_name: profile.name(),
|
||||
avatar: profile.avatar.clone(),
|
||||
display_name: profile.name.clone(),
|
||||
created_at,
|
||||
content,
|
||||
}
|
||||
@@ -99,7 +98,9 @@ pub struct Chat {
|
||||
// Chat Room
|
||||
room: WeakEntity<Room>,
|
||||
messages: Entity<Vec<Message>>,
|
||||
seens: Entity<Vec<EventId>>,
|
||||
list_state: ListState,
|
||||
#[allow(dead_code)]
|
||||
subscriptions: Vec<Subscription>,
|
||||
// New Message
|
||||
input: Entity<TextInput>,
|
||||
@@ -116,6 +117,7 @@ impl Chat {
|
||||
cx: &mut App,
|
||||
) -> Entity<Self> {
|
||||
let messages = cx.new(|_| vec![Message::placeholder()]);
|
||||
let seens = cx.new(|_| vec![]);
|
||||
let attaches = cx.new(|_| None);
|
||||
let input = cx.new(|cx| {
|
||||
TextInput::new(window, cx)
|
||||
@@ -125,15 +127,27 @@ impl Chat {
|
||||
});
|
||||
|
||||
cx.new(|cx| {
|
||||
let subscriptions = vec![cx.subscribe_in(
|
||||
let mut subscriptions = Vec::with_capacity(2);
|
||||
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&input,
|
||||
window,
|
||||
move |this: &mut Chat, _, input_event, window, cx| {
|
||||
if let InputEvent::PressEnter = input_event {
|
||||
move |this: &mut Self, _, event, window, cx| {
|
||||
if let InputEvent::PressEnter = event {
|
||||
this.send_message(window, cx);
|
||||
}
|
||||
},
|
||||
)];
|
||||
));
|
||||
|
||||
if let Some(room) = room.upgrade() {
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&room,
|
||||
window,
|
||||
move |this: &mut Self, _, event, window, cx| {
|
||||
this.push_message(&event.event, window, cx);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
// Initialize list state
|
||||
// [item_count] always equal to 1 at the beginning
|
||||
@@ -147,12 +161,13 @@ impl Chat {
|
||||
}
|
||||
});
|
||||
|
||||
let mut this = Self {
|
||||
let this = Self {
|
||||
focus_handle: cx.focus_handle(),
|
||||
is_uploading: false,
|
||||
id: id.to_string().into(),
|
||||
room,
|
||||
messages,
|
||||
seens,
|
||||
list_state,
|
||||
input,
|
||||
attaches,
|
||||
@@ -165,9 +180,6 @@ impl Chat {
|
||||
// Load all messages from database
|
||||
this.load_messages(cx);
|
||||
|
||||
// Subscribe and load new messages
|
||||
this.load_new_messages(cx);
|
||||
|
||||
this
|
||||
})
|
||||
}
|
||||
@@ -177,55 +189,25 @@ impl Chat {
|
||||
return;
|
||||
};
|
||||
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Vec<(PublicKey, bool)>>();
|
||||
|
||||
let pubkeys: Vec<PublicKey> = model
|
||||
.read(cx)
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| m.public_key())
|
||||
.collect();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let mut result = Vec::new();
|
||||
|
||||
for pubkey in pubkeys.into_iter() {
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(pubkey)
|
||||
.limit(1);
|
||||
|
||||
let is_ready = if let Ok(events) = client.database().query(filter).await {
|
||||
events.first_owned().is_some()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
result.push((pubkey, is_ready));
|
||||
}
|
||||
|
||||
_ = tx.send(result);
|
||||
})
|
||||
.detach();
|
||||
let room = model.read(cx);
|
||||
let task = room.verify_inbox_relays(cx);
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
if let Ok(result) = rx.await {
|
||||
if let Ok(result) = task.await {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
for item in result.into_iter() {
|
||||
result.into_iter().for_each(|item| {
|
||||
if !item.1 {
|
||||
let name = this
|
||||
.room
|
||||
.read_with(cx, |this, _| this.name().unwrap_or("Unnamed".into()))
|
||||
.unwrap_or("Unnamed".into());
|
||||
|
||||
this.push_system_message(
|
||||
format!("{} has not set up Messaging (DM) Relays, so they will NOT receive your messages.", name),
|
||||
cx,
|
||||
);
|
||||
if let Ok(Some(member)) =
|
||||
this.room.read_with(cx, |this, _| this.member(&item.0))
|
||||
{
|
||||
this.push_system_message(
|
||||
format!("{} {}", member.name, ALERT),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -239,30 +221,10 @@ impl Chat {
|
||||
};
|
||||
|
||||
let room = model.read(cx);
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Events>();
|
||||
|
||||
let pubkeys = room
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| m.public_key())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.authors(pubkeys.iter().copied())
|
||||
.pubkeys(pubkeys);
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let Ok(events) = client.database().query(filter).await else {
|
||||
return;
|
||||
};
|
||||
_ = tx.send(events);
|
||||
})
|
||||
.detach();
|
||||
let task = room.load_messages(cx);
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
if let Ok(events) = rx.await {
|
||||
if let Ok(events) = task.await {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.push_messages(events, cx);
|
||||
@@ -285,29 +247,36 @@ impl Chat {
|
||||
self.list_state.splice(old_len..old_len, 1);
|
||||
}
|
||||
|
||||
fn push_message(&self, content: String, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(account) = Account::global(cx) else {
|
||||
fn push_message(&mut self, event: &Event, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(model) = self.room.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let old_len = self.messages.read(cx).len();
|
||||
let profile = account.read(cx).get();
|
||||
let message = Message::new(ParsedMessage::new(profile, &content, Timestamp::now()));
|
||||
// Prevent duplicate messages
|
||||
if self.seens.read(cx).iter().any(|id| id == &event.id) {
|
||||
return;
|
||||
}
|
||||
// Add ID to seen list
|
||||
self.seen(event.id, cx);
|
||||
|
||||
let old_len = self.messages.read(cx).len();
|
||||
let room = model.read(cx);
|
||||
|
||||
let profile = room
|
||||
.member(&event.pubkey)
|
||||
.unwrap_or(NostrProfile::new(event.pubkey, Metadata::default()));
|
||||
|
||||
let message = Message::new(ParsedMessage::new(
|
||||
&profile,
|
||||
&event.content,
|
||||
Timestamp::now(),
|
||||
));
|
||||
|
||||
// Update message list
|
||||
cx.update_entity(&self.messages, |this, cx| {
|
||||
this.extend(vec![message]);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Reset message input
|
||||
cx.update_entity(&self.input, |this, cx| {
|
||||
this.set_loading(false, window, cx);
|
||||
this.set_disabled(false, window, cx);
|
||||
this.set_text("", window, cx);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
self.list_state.splice(old_len..old_len, 1);
|
||||
}
|
||||
|
||||
@@ -317,12 +286,7 @@ impl Chat {
|
||||
};
|
||||
|
||||
let room = model.read(cx);
|
||||
let pubkeys = room
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| m.public_key())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let pubkeys = room.public_keys();
|
||||
let old_len = self.messages.read(cx).len();
|
||||
|
||||
let (messages, new_len) = {
|
||||
@@ -339,7 +303,7 @@ impl Chat {
|
||||
|
||||
room.members
|
||||
.iter()
|
||||
.find(|m| m.public_key() == ev.pubkey)
|
||||
.find(|m| m.public_key == ev.pubkey)
|
||||
.map(|member| {
|
||||
Message::new(ParsedMessage::new(member, &ev.content, ev.created_at))
|
||||
})
|
||||
@@ -360,75 +324,13 @@ impl Chat {
|
||||
self.list_state.splice(old_len..old_len, new_len);
|
||||
}
|
||||
|
||||
fn load_new_messages(&mut self, cx: &mut Context<Self>) {
|
||||
let Some(room) = self.room.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let subscription = cx.observe(&room, |view, this, cx| {
|
||||
let room = this.read(cx);
|
||||
|
||||
if room.new_messages.is_empty() {
|
||||
return;
|
||||
};
|
||||
|
||||
let old_messages = view.messages.read(cx);
|
||||
let old_len = old_messages.len();
|
||||
|
||||
let items: Vec<Message> = this
|
||||
.read(cx)
|
||||
.new_messages
|
||||
.iter()
|
||||
.filter_map(|event| {
|
||||
if let Some(profile) = room.member(&event.pubkey) {
|
||||
let message = Message::new(ParsedMessage::new(
|
||||
&profile,
|
||||
&event.content,
|
||||
event.created_at,
|
||||
));
|
||||
|
||||
if !old_messages.iter().any(|old| old == &message) {
|
||||
Some(message)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let total = items.len();
|
||||
|
||||
cx.update_entity(&view.messages, |this, cx| {
|
||||
let messages: Vec<Message> = items
|
||||
.into_iter()
|
||||
.filter_map(|new| {
|
||||
if !this.iter().any(|old| old == &new) {
|
||||
Some(new)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
this.extend(messages);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
view.list_state.splice(old_len..old_len, total);
|
||||
});
|
||||
|
||||
self.subscriptions.push(subscription);
|
||||
}
|
||||
|
||||
fn send_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(model) = self.room.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Get message
|
||||
let mut content = self.input.read(cx).text();
|
||||
let mut content = self.input.read(cx).text().to_string();
|
||||
|
||||
// Get all attaches and merge its with message
|
||||
if let Some(attaches) = self.attaches.read(cx).as_ref() {
|
||||
@@ -438,7 +340,7 @@ impl Chat {
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
content = format!("{}\n{}", content, merged).into()
|
||||
content = format!("{}\n{}", content, merged)
|
||||
}
|
||||
|
||||
if content.is_empty() {
|
||||
@@ -453,57 +355,25 @@ impl Chat {
|
||||
});
|
||||
|
||||
let room = model.read(cx);
|
||||
// let subject = Tag::from_standardized_without_cell(TagStandard::Subject(room.title.clone()));
|
||||
let pubkeys = room.public_keys();
|
||||
let async_content = content.clone().to_string();
|
||||
|
||||
let client = get_client();
|
||||
let task = room.send_message(content, cx);
|
||||
let window_handle = window.window_handle();
|
||||
let (tx, rx) = oneshot::channel::<Vec<Error>>();
|
||||
|
||||
// Send message to all pubkeys
|
||||
cx.background_spawn(async move {
|
||||
let signer = client.signer().await.unwrap();
|
||||
let public_key = signer.get_public_key().await.unwrap();
|
||||
|
||||
let mut errors = Vec::new();
|
||||
|
||||
let tags: Vec<Tag> = pubkeys
|
||||
.iter()
|
||||
.filter_map(|pubkey| {
|
||||
if pubkey != &public_key {
|
||||
Some(Tag::public_key(*pubkey))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
for pubkey in pubkeys.iter() {
|
||||
if let Err(e) = client
|
||||
.send_private_msg(*pubkey, &async_content, tags.clone())
|
||||
.await
|
||||
{
|
||||
errors.push(e);
|
||||
}
|
||||
}
|
||||
|
||||
_ = tx.send(errors);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.push_message(content.to_string(), window, cx);
|
||||
});
|
||||
});
|
||||
|
||||
if let Ok(errors) = rx.await {
|
||||
if let Ok(msgs) = task.await {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
for error in errors.into_iter() {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
// Reset message input
|
||||
cx.update_entity(&this.input, |this, cx| {
|
||||
this.set_loading(false, window, cx);
|
||||
this.set_disabled(false, window, cx);
|
||||
this.set_text("", window, cx);
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
|
||||
for item in msgs.into_iter() {
|
||||
window.push_notification(
|
||||
Notification::error(error.to_string()).title("Message Failed to Send"),
|
||||
Notification::error(item).title("Message Failed to Send"),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
@@ -590,6 +460,13 @@ impl Chat {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn seen(&mut self, id: EventId, cx: &mut Context<Self>) {
|
||||
self.seens.update(cx, |this, cx| {
|
||||
this.push(id);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
fn render_message(
|
||||
&self,
|
||||
ix: usize,
|
||||
@@ -659,7 +536,7 @@ impl Chat {
|
||||
.group_hover("", |this| this.bg(cx.theme().danger)),
|
||||
)
|
||||
.child(
|
||||
img("brand/avatar.png")
|
||||
img("brand/avatar.jpg")
|
||||
.size_8()
|
||||
.rounded_full()
|
||||
.flex_shrink_0(),
|
||||
@@ -684,7 +561,7 @@ impl Chat {
|
||||
.size_8()
|
||||
.text_color(cx.theme().base.step(cx, ColorScaleStep::THREE)),
|
||||
)
|
||||
.child(ALERT),
|
||||
.child(DESCRIPTION),
|
||||
})
|
||||
} else {
|
||||
div()
|
||||
@@ -700,8 +577,11 @@ impl Panel for Chat {
|
||||
fn title(&self, cx: &App) -> AnyElement {
|
||||
self.room
|
||||
.read_with(cx, |this, _| {
|
||||
let facepill: Vec<SharedString> =
|
||||
this.members.iter().map(|member| member.avatar()).collect();
|
||||
let facepill: Vec<SharedString> = this
|
||||
.members
|
||||
.iter()
|
||||
.map(|member| member.avatar.clone())
|
||||
.collect();
|
||||
|
||||
div()
|
||||
.flex()
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use common::profile::NostrProfile;
|
||||
use global::get_client;
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, px, uniform_list, AnyElement, App, AppContext, Context,
|
||||
Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, ParentElement,
|
||||
Render, SharedString, Styled, Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use state::get_client;
|
||||
use ui::{
|
||||
button::Button,
|
||||
dock_area::panel::{Panel, PanelEvent},
|
||||
@@ -141,9 +141,9 @@ impl Render for Contacts {
|
||||
.child(
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.child(img(item.avatar()).size_6()),
|
||||
.child(img(item.avatar).size_6()),
|
||||
)
|
||||
.child(item.name()),
|
||||
.child(item.name),
|
||||
)
|
||||
.hover(|this| {
|
||||
this.bg(cx.theme().base.step(cx, ColorScaleStep::THREE))
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
mod chat;
|
||||
mod contacts;
|
||||
mod profile;
|
||||
mod relays;
|
||||
mod settings;
|
||||
mod sidebar;
|
||||
mod welcome;
|
||||
|
||||
pub mod app;
|
||||
pub mod onboarding;
|
||||
pub mod relays;
|
||||
pub mod startup;
|
||||
|
||||
@@ -1,185 +1,161 @@
|
||||
use account::registry::Account;
|
||||
use common::qr::create_qr;
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, relative, svg, App, AppContext, ClipboardItem, Context, Div,
|
||||
Entity, IntoElement, ParentElement, Render, Styled, Subscription, Window,
|
||||
div, img, prelude::FluentBuilder, relative, svg, App, AppContext, Context, Entity, IntoElement,
|
||||
ParentElement, Render, SharedString, Styled, Subscription, Window,
|
||||
};
|
||||
use nostr_connect::prelude::*;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use std::{path::PathBuf, sync::Arc, time::Duration};
|
||||
use ui::{
|
||||
button::{Button, ButtonCustomVariant, ButtonVariants},
|
||||
input::{InputEvent, TextInput},
|
||||
notification::NotificationType,
|
||||
theme::{scale::ColorScaleStep, ActiveTheme},
|
||||
ContextModal, Root, Size, StyledExt,
|
||||
Disableable, Size, StyledExt,
|
||||
};
|
||||
|
||||
use super::app;
|
||||
use crate::device::Device;
|
||||
|
||||
const LOGO_URL: &str = "brand/coop.svg";
|
||||
const TITLE: &str = "Welcome to Coop!";
|
||||
const SUBTITLE: &str = "A Nostr client for secure communication.";
|
||||
const ALPHA_MESSAGE: &str =
|
||||
"Coop is in the alpha stage of development; It may contain bugs, unfinished features, or unexpected behavior.";
|
||||
|
||||
const JOIN_URL: &str = "https://start.njump.me/";
|
||||
// TODO: Replace it with Persona Mobile App
|
||||
const NSTART_URL: &str =
|
||||
"https://start.njump.me?an=Coop&at=ios&ac=coop&afb=yes&asf=yes&aan=null&aac=null&arr=wss://relay.damus.io&awr=wss://relay.primal.net,wss://purplerelay.com,wss://offchain.pub";
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Onboarding> {
|
||||
Onboarding::new(window, cx)
|
||||
}
|
||||
|
||||
enum PageKind {
|
||||
Bunker,
|
||||
Connect,
|
||||
Selection,
|
||||
}
|
||||
|
||||
pub struct Onboarding {
|
||||
app_keys: Keys,
|
||||
connect_uri: NostrConnectURI,
|
||||
qr_path: Option<PathBuf>,
|
||||
nsec_input: Entity<TextInput>,
|
||||
use_connect: bool,
|
||||
use_privkey: bool,
|
||||
bunker_input: Entity<TextInput>,
|
||||
connect_url: Entity<Option<PathBuf>>,
|
||||
error_message: Entity<Option<SharedString>>,
|
||||
open: PageKind,
|
||||
is_loading: bool,
|
||||
#[allow(dead_code)]
|
||||
subscriptions: Vec<Subscription>,
|
||||
subscriptions: SmallVec<[Subscription; 1]>,
|
||||
}
|
||||
|
||||
impl Onboarding {
|
||||
pub fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
|
||||
let app_keys = Keys::generate();
|
||||
let connect_url = cx.new(|_| None);
|
||||
let error_message = cx.new(|_| None);
|
||||
let bunker_input = cx.new(|cx| {
|
||||
TextInput::new(window, cx)
|
||||
.text_size(Size::XSmall)
|
||||
.placeholder("bunker://<pubkey>?relay=wss://relay.example.com")
|
||||
});
|
||||
|
||||
let connect_uri = NostrConnectURI::client(
|
||||
cx.new(|cx| {
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&bunker_input,
|
||||
window,
|
||||
move |this: &mut Self, _, input_event, window, cx| {
|
||||
if let InputEvent::PressEnter = input_event {
|
||||
this.connect(window, cx);
|
||||
}
|
||||
},
|
||||
));
|
||||
|
||||
Self {
|
||||
bunker_input,
|
||||
connect_url,
|
||||
error_message,
|
||||
subscriptions,
|
||||
open: PageKind::Selection,
|
||||
is_loading: false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn login(&self, signer: NostrConnect, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(device) = Device::global(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let entity = cx.weak_entity();
|
||||
|
||||
device.update(cx, |this, cx| {
|
||||
let login = this.login(signer, cx);
|
||||
|
||||
cx.spawn(|_, cx| async move {
|
||||
if let Err(e) = login.await {
|
||||
cx.update(|cx| {
|
||||
entity
|
||||
.update(cx, |this, cx| {
|
||||
this.set_error(e.to_string(), cx);
|
||||
this.set_loading(false, cx);
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
}
|
||||
|
||||
fn connect(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(model) = Device::global(cx) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let text = self.bunker_input.read(cx).text().to_string();
|
||||
let keys = Arc::unwrap_or_clone(model.read(cx).client_keys());
|
||||
|
||||
self.set_loading(true, cx);
|
||||
|
||||
let Ok(uri) = NostrConnectURI::parse(text) else {
|
||||
self.set_loading(false, cx);
|
||||
self.set_error("Bunker URL is invalid".to_owned(), cx);
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(signer) = NostrConnect::new(uri, keys, Duration::from_secs(300), None) else {
|
||||
self.set_loading(false, cx);
|
||||
self.set_error("Failed to establish connection".to_owned(), cx);
|
||||
return;
|
||||
};
|
||||
|
||||
self.login(signer, window, cx);
|
||||
}
|
||||
|
||||
fn wait_for_connection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let app_keys = Keys::generate();
|
||||
let url = NostrConnectURI::client(
|
||||
app_keys.public_key(),
|
||||
vec![RelayUrl::parse("wss://relay.nsec.app").unwrap()],
|
||||
"Coop",
|
||||
);
|
||||
|
||||
let nsec_input = cx.new(|cx| {
|
||||
TextInput::new(window, cx)
|
||||
.text_size(Size::XSmall)
|
||||
.placeholder("nsec...")
|
||||
// Create QR code and save it to a app directory
|
||||
let qr_path = create_qr(url.to_string().as_str()).ok();
|
||||
|
||||
// Update QR code path
|
||||
self.connect_url.update(cx, |this, cx| {
|
||||
*this = qr_path;
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Save Connect URI as PNG file for display as QR Code
|
||||
let qr_path = create_qr(connect_uri.to_string().as_str()).ok();
|
||||
|
||||
cx.new(|cx| {
|
||||
// Handle Enter event for nsec input
|
||||
let subscriptions = vec![cx.subscribe_in(
|
||||
&nsec_input,
|
||||
window,
|
||||
move |this: &mut Self, _, input_event, window, cx| {
|
||||
if let InputEvent::PressEnter = input_event {
|
||||
this.login_with_private_key(window, cx);
|
||||
}
|
||||
},
|
||||
)];
|
||||
|
||||
Self {
|
||||
app_keys,
|
||||
connect_uri,
|
||||
qr_path,
|
||||
nsec_input,
|
||||
use_connect: false,
|
||||
use_privkey: false,
|
||||
is_loading: false,
|
||||
subscriptions,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn login_with_nostr_connect(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let uri = self.connect_uri.clone();
|
||||
let app_keys = self.app_keys.clone();
|
||||
let window_handle = window.window_handle();
|
||||
|
||||
// Show QR Code for login with Nostr Connect
|
||||
self.use_connect(window, cx);
|
||||
// Open Connect page
|
||||
self.open(PageKind::Connect, window, cx);
|
||||
|
||||
// Wait for connection
|
||||
let (tx, rx) = oneshot::channel::<NostrConnect>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
if let Ok(signer) = NostrConnect::new(uri, app_keys, Duration::from_secs(300), None) {
|
||||
tx.send(signer).ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
if let Ok(signer) = rx.await {
|
||||
cx.spawn(|mut cx| async move {
|
||||
let signer = Arc::new(signer);
|
||||
|
||||
if Account::login(signer, &cx).await.is_ok() {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
window.replace_root(cx, |window, cx| {
|
||||
Root::new(app::init(window, cx).into(), window, cx)
|
||||
});
|
||||
})
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
} else {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
});
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn login_with_private_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let value = self.nsec_input.read(cx).text().to_string();
|
||||
let window_handle = window.window_handle();
|
||||
|
||||
if !value.starts_with("nsec") || value.is_empty() {
|
||||
window.push_notification((NotificationType::Warning, "Private Key is required"), cx);
|
||||
return;
|
||||
}
|
||||
|
||||
let keys = if let Ok(keys) = Keys::parse(&value) {
|
||||
keys
|
||||
if let Ok(signer) = NostrConnect::new(url, app_keys, Duration::from_secs(300), None) {
|
||||
self.login(signer, window, cx);
|
||||
} else {
|
||||
window.push_notification((NotificationType::Warning, "Private Key isn't valid"), cx);
|
||||
return;
|
||||
};
|
||||
|
||||
// Show loading spinner
|
||||
self.set_loading(true, cx);
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
let signer = Arc::new(keys);
|
||||
|
||||
if Account::login(signer, &cx).await.is_ok() {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
window.replace_root(cx, |window, cx| {
|
||||
Root::new(app::init(window, cx).into(), window, cx)
|
||||
});
|
||||
})
|
||||
} else {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
});
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn use_connect(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.use_connect = true;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn use_privkey(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.use_privkey = true;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn reset(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.use_privkey = false;
|
||||
self.use_connect = false;
|
||||
cx.notify();
|
||||
self.set_loading(false, cx);
|
||||
self.set_error("Failed to establish connection".to_owned(), cx);
|
||||
self.open(PageKind::Selection, window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_loading(&mut self, status: bool, cx: &mut Context<Self>) {
|
||||
@@ -187,158 +163,31 @@ impl Onboarding {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn render_selection(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
|
||||
div()
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap_2()
|
||||
.child(
|
||||
Button::new("login_connect_btn")
|
||||
.label("Login with Nostr Connect")
|
||||
.primary()
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.login_with_nostr_connect(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
Button::new("login_privkey_btn")
|
||||
.label("Login with Private Key")
|
||||
.custom(
|
||||
ButtonCustomVariant::new(window, cx)
|
||||
.color(cx.theme().base.step(cx, ColorScaleStep::THREE))
|
||||
.border(cx.theme().base.step(cx, ColorScaleStep::THREE))
|
||||
.hover(cx.theme().base.step(cx, ColorScaleStep::FOUR))
|
||||
.active(cx.theme().base.step(cx, ColorScaleStep::FIVE))
|
||||
.foreground(cx.theme().base.step(cx, ColorScaleStep::TWELVE)),
|
||||
)
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.use_privkey(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.my_2()
|
||||
.h_px()
|
||||
.rounded_md()
|
||||
.w_full()
|
||||
.bg(cx.theme().base.step(cx, ColorScaleStep::THREE)),
|
||||
)
|
||||
.child(
|
||||
Button::new("join_btn")
|
||||
.label("Are you new? Join here!")
|
||||
.ghost()
|
||||
.w_full()
|
||||
.on_click(|_, _, cx| {
|
||||
cx.open_url(JOIN_URL);
|
||||
}),
|
||||
)
|
||||
fn set_error(&mut self, msg: String, cx: &mut Context<Self>) {
|
||||
self.error_message.update(cx, |this, cx| {
|
||||
*this = Some(msg.into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Dismiss error message after 3 seconds
|
||||
cx.spawn(|this, cx| async move {
|
||||
cx.background_executor().timer(Duration::from_secs(3)).await;
|
||||
|
||||
_ = cx.update(|cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.error_message.update(cx, |this, cx| {
|
||||
*this = None;
|
||||
cx.notify();
|
||||
})
|
||||
})
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn render_connect_login(&self, cx: &mut Context<Self>) -> Div {
|
||||
let connect_string = self.connect_uri.to_string();
|
||||
|
||||
div()
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap_2()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.child(
|
||||
div()
|
||||
.font_semibold()
|
||||
.line_height(relative(1.2))
|
||||
.child("Scan this QR Code in the Nostr Signer app"),
|
||||
)
|
||||
.child("Recommend: Amber (Android), nsec.app (web),..."),
|
||||
)
|
||||
.when_some(self.qr_path.clone(), |this, path| {
|
||||
this.child(
|
||||
div()
|
||||
.mb_2()
|
||||
.p_2()
|
||||
.size_72()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap_2()
|
||||
.rounded_lg()
|
||||
.shadow_lg()
|
||||
.when(cx.theme().appearance.is_dark(), |this| {
|
||||
this.shadow_none()
|
||||
.border_1()
|
||||
.border_color(cx.theme().base.step(cx, ColorScaleStep::SIX))
|
||||
})
|
||||
.bg(cx.theme().background)
|
||||
.child(img(path).h_64()),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
Button::new("copy")
|
||||
.label("Copy Connection String")
|
||||
.primary()
|
||||
.w_full()
|
||||
.on_click(move |_, _, cx| {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(connect_string.clone()))
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
Button::new("cancel")
|
||||
.label("Cancel")
|
||||
.ghost()
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.reset(window, cx);
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_privkey_login(&self, cx: &mut Context<Self>) -> Div {
|
||||
div()
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_2()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.text_xs()
|
||||
.child("Private Key:")
|
||||
.child(self.nsec_input.clone()),
|
||||
)
|
||||
.child(
|
||||
Button::new("login")
|
||||
.label("Login")
|
||||
.primary()
|
||||
.w_full()
|
||||
.loading(self.is_loading)
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.login_with_private_key(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
Button::new("cancel")
|
||||
.label("Cancel")
|
||||
.ghost()
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.reset(window, cx);
|
||||
})),
|
||||
)
|
||||
fn open(&mut self, kind: PageKind, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.open = kind;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,28 +237,163 @@ impl Render for Onboarding {
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.w_72()
|
||||
.map(|_| match (self.use_privkey, self.use_connect) {
|
||||
(true, _) => self.render_privkey_login(cx),
|
||||
(_, true) => self.render_connect_login(cx),
|
||||
_ => self.render_selection(window, cx),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.absolute()
|
||||
.bottom_2()
|
||||
.w_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.text_color(cx.theme().base.step(cx, ColorScaleStep::ELEVEN))
|
||||
.child(ALPHA_MESSAGE),
|
||||
.child(div().w_72().w_full().flex().flex_col().gap_2().map(|this| {
|
||||
match self.open {
|
||||
PageKind::Connect => this
|
||||
.when_some(self.connect_url.read(cx).as_ref(), |this, path| {
|
||||
this.child(
|
||||
div()
|
||||
.mb_2()
|
||||
.p_2()
|
||||
.size_72()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap_2()
|
||||
.rounded_lg()
|
||||
.shadow_md()
|
||||
.when(cx.theme().appearance.is_dark(), |this| {
|
||||
this.shadow_none().border_1().border_color(
|
||||
cx.theme().base.step(cx, ColorScaleStep::SIX),
|
||||
)
|
||||
})
|
||||
.bg(cx.theme().background)
|
||||
.child(img(path.as_path()).h_64()),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.font_semibold()
|
||||
.line_height(relative(1.2))
|
||||
.child("Scan this QR to connect"),
|
||||
)
|
||||
.child(
|
||||
Button::new("wait_for_connection")
|
||||
.label("Waiting for connection")
|
||||
.primary()
|
||||
.w_full()
|
||||
.loading(true)
|
||||
.disabled(true),
|
||||
)
|
||||
.child(
|
||||
Button::new("use_url")
|
||||
.label("Use Bunker URL")
|
||||
.custom(
|
||||
ButtonCustomVariant::new(window, cx)
|
||||
.color(
|
||||
cx.theme().base.step(cx, ColorScaleStep::THREE),
|
||||
)
|
||||
.border(
|
||||
cx.theme().base.step(cx, ColorScaleStep::THREE),
|
||||
)
|
||||
.hover(
|
||||
cx.theme().base.step(cx, ColorScaleStep::FOUR),
|
||||
)
|
||||
.active(
|
||||
cx.theme().base.step(cx, ColorScaleStep::FIVE),
|
||||
)
|
||||
.foreground(
|
||||
cx.theme()
|
||||
.base
|
||||
.step(cx, ColorScaleStep::TWELVE),
|
||||
),
|
||||
)
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.open(PageKind::Bunker, window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.my_2()
|
||||
.w_full()
|
||||
.h_px()
|
||||
.bg(cx.theme().base.step(cx, ColorScaleStep::THREE)),
|
||||
)
|
||||
.child(
|
||||
Button::new("cancel")
|
||||
.label("Cancel")
|
||||
.ghost()
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.open(PageKind::Selection, window, cx);
|
||||
})),
|
||||
),
|
||||
PageKind::Bunker => this
|
||||
.child(
|
||||
div()
|
||||
.mb_2()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.text_xs()
|
||||
.child("Bunker URL:")
|
||||
.child(self.bunker_input.clone())
|
||||
.when_some(
|
||||
self.error_message.read(cx).as_ref(),
|
||||
|this, error| {
|
||||
this.child(
|
||||
div()
|
||||
.my_1()
|
||||
.text_xs()
|
||||
.text_center()
|
||||
.text_color(cx.theme().danger)
|
||||
.child(error.clone()),
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
.child(
|
||||
Button::new("login")
|
||||
.label("Login")
|
||||
.primary()
|
||||
.w_full()
|
||||
.loading(self.is_loading)
|
||||
.disabled(self.is_loading)
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.connect(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.my_2()
|
||||
.w_full()
|
||||
.h_px()
|
||||
.bg(cx.theme().base.step(cx, ColorScaleStep::THREE)),
|
||||
)
|
||||
.child(
|
||||
Button::new("cancel")
|
||||
.label("Cancel")
|
||||
.ghost()
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.open(PageKind::Selection, window, cx);
|
||||
})),
|
||||
),
|
||||
PageKind::Selection => this
|
||||
.child(
|
||||
Button::new("login_connect_btn")
|
||||
.label("Login with Nostr Connect")
|
||||
.primary()
|
||||
.w_full()
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.wait_for_connection(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
Button::new("join_btn")
|
||||
.label("Are you new? Join here!")
|
||||
.ghost()
|
||||
.w_full()
|
||||
.on_click(|_, _, cx| {
|
||||
cx.open_url(NSTART_URL);
|
||||
}),
|
||||
),
|
||||
}
|
||||
})),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use async_utility::task::spawn;
|
||||
use common::{constants::IMAGE_SERVICE, utils::nip96_upload};
|
||||
use common::utils::nip96_upload;
|
||||
use global::{constants::IMAGE_SERVICE, get_client};
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, AnyElement, App, AppContext, Context, Entity, EventEmitter,
|
||||
Flatten, FocusHandle, Focusable, IntoElement, ParentElement, PathPromptOptions, Render,
|
||||
SharedString, Styled, Window,
|
||||
SharedString, Styled, Task, Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use smol::fs;
|
||||
use state::get_client;
|
||||
use std::{str::FromStr, sync::Arc, time::Duration};
|
||||
use ui::{
|
||||
button::{Button, ButtonVariants},
|
||||
@@ -49,7 +49,7 @@ impl Profile {
|
||||
TextInput::new(window, cx)
|
||||
.text_size(Size::XSmall)
|
||||
.small()
|
||||
.placeholder("https://example.com/avatar.png")
|
||||
.placeholder("https://example.com/avatar.jpg")
|
||||
});
|
||||
|
||||
let website_input = cx.new(|cx| {
|
||||
@@ -79,30 +79,18 @@ impl Profile {
|
||||
};
|
||||
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Option<Metadata>>();
|
||||
let task: Task<Result<Option<Metadata>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let metadata = client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await?;
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let result = async {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let metadata = client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await?;
|
||||
|
||||
Ok::<_, anyhow::Error>(metadata)
|
||||
}
|
||||
.await;
|
||||
|
||||
if let Ok(metadata) = result {
|
||||
_ = tx.send(Some(metadata));
|
||||
} else {
|
||||
_ = tx.send(None);
|
||||
};
|
||||
})
|
||||
.detach();
|
||||
Ok(metadata)
|
||||
});
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if let Ok(Some(metadata)) = rx.await {
|
||||
if let Ok(Some(metadata)) = task.await {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
_ = this.update(cx, |this: &mut Profile, cx| {
|
||||
this.avatar_input.update(cx, |this, cx| {
|
||||
@@ -309,7 +297,7 @@ impl Render for Profile {
|
||||
|
||||
if picture.is_empty() {
|
||||
this.child(
|
||||
img("brand/avatar.png")
|
||||
img("brand/avatar.jpg")
|
||||
.size_10()
|
||||
.rounded_full()
|
||||
.flex_shrink_0(),
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use anyhow::{anyhow, Error};
|
||||
use global::{constants::NEW_MESSAGE_SUB_ID, get_client};
|
||||
use gpui::{
|
||||
div, prelude::FluentBuilder, px, uniform_list, AppContext, Context, Entity, FocusHandle,
|
||||
InteractiveElement, IntoElement, ParentElement, Render, Styled, TextAlign, Window,
|
||||
div, prelude::FluentBuilder, px, uniform_list, App, AppContext, Context, Entity, FocusHandle,
|
||||
InteractiveElement, IntoElement, ParentElement, Render, Styled, Subscription, Task, TextAlign,
|
||||
Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use state::get_client;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use ui::{
|
||||
button::{Button, ButtonVariants},
|
||||
input::{InputEvent, TextInput},
|
||||
@@ -11,108 +14,189 @@ use ui::{
|
||||
ContextModal, IconName, Sizable,
|
||||
};
|
||||
|
||||
use crate::device::Device;
|
||||
|
||||
const MESSAGE: &str = "In order to receive messages from others, you need to setup Messaging Relays. You can use the recommend relays or add more.";
|
||||
const HELP_TEXT: &str = "Please add some relays.";
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Relays> {
|
||||
Relays::new(window, cx)
|
||||
}
|
||||
|
||||
pub struct Relays {
|
||||
relays: Entity<Vec<Url>>,
|
||||
relays: Entity<Vec<RelayUrl>>,
|
||||
input: Entity<TextInput>,
|
||||
focus_handle: FocusHandle,
|
||||
is_loading: bool,
|
||||
#[allow(dead_code)]
|
||||
subscriptions: SmallVec<[Subscription; 1]>,
|
||||
}
|
||||
|
||||
impl Relays {
|
||||
pub fn new(
|
||||
relays: Option<Vec<String>>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<'_, Self>,
|
||||
) -> Self {
|
||||
let relays = cx.new(|_| {
|
||||
if let Some(value) = relays {
|
||||
value.into_iter().map(|v| Url::parse(&v).unwrap()).collect()
|
||||
} else {
|
||||
vec![
|
||||
Url::parse("wss://auth.nostr1.com").unwrap(),
|
||||
Url::parse("wss://relay.0xchat.com").unwrap(),
|
||||
]
|
||||
}
|
||||
pub fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
|
||||
let client = get_client();
|
||||
|
||||
let relays = cx.new(|cx| {
|
||||
let relays = vec![
|
||||
RelayUrl::parse("wss://auth.nostr1.com").unwrap(),
|
||||
RelayUrl::parse("wss://relay.0xchat.com").unwrap(),
|
||||
];
|
||||
|
||||
let task: Task<Result<Vec<RelayUrl>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||
let relays = event
|
||||
.tags
|
||||
.filter_standardized(TagKind::Relay)
|
||||
.filter_map(|t| match t {
|
||||
TagStandard::Relay(url) => Some(url.to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(relays)
|
||||
} else {
|
||||
Err(anyhow!("Messaging Relays not found."))
|
||||
}
|
||||
});
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
if let Ok(relays) = task.await {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this: &mut Vec<RelayUrl>, cx| {
|
||||
*this = relays;
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
relays
|
||||
});
|
||||
|
||||
let input = cx.new(|cx| {
|
||||
TextInput::new(window, cx)
|
||||
.text_size(ui::Size::XSmall)
|
||||
.small()
|
||||
.placeholder("wss://...")
|
||||
.placeholder("wss://example.com")
|
||||
});
|
||||
|
||||
cx.subscribe_in(&input, window, move |this, _, input_event, window, cx| {
|
||||
if let InputEvent::PressEnter = input_event {
|
||||
this.add(window, cx);
|
||||
cx.new(|cx| {
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&input,
|
||||
window,
|
||||
move |this: &mut Relays, _, input_event, window, cx| {
|
||||
if let InputEvent::PressEnter = input_event {
|
||||
this.add(window, cx);
|
||||
}
|
||||
},
|
||||
));
|
||||
|
||||
Self {
|
||||
relays,
|
||||
input,
|
||||
subscriptions,
|
||||
is_loading: false,
|
||||
focus_handle: cx.focus_handle(),
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
Self {
|
||||
relays,
|
||||
input,
|
||||
is_loading: false,
|
||||
focus_handle: cx.focus_handle(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let relays = self.relays.read(cx).clone();
|
||||
let window_handle = window.window_handle();
|
||||
|
||||
// Show loading spinner
|
||||
self.set_loading(true, cx);
|
||||
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let signer = client.signer().await.expect("Signer is required");
|
||||
let public_key = signer
|
||||
.get_public_key()
|
||||
.await
|
||||
.expect("Cannot get public key");
|
||||
let task: Task<Result<EventId, Error>> = cx.background_spawn(async move {
|
||||
let client = get_client();
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
// If user didn't have any NIP-65 relays, add default ones
|
||||
// TODO: Is this really necessary?
|
||||
if let Ok(relay_list) = client.database().relay_list(public_key).await {
|
||||
if relay_list.is_empty() {
|
||||
let builder = EventBuilder::relay_list(vec![
|
||||
(RelayUrl::parse("wss://relay.damus.io/").unwrap(), None),
|
||||
(RelayUrl::parse("wss://relay.primal.net/").unwrap(), None),
|
||||
(RelayUrl::parse("wss://nos.lol/").unwrap(), None),
|
||||
]);
|
||||
if client.database().relay_list(public_key).await?.is_empty() {
|
||||
let builder = EventBuilder::relay_list(vec![
|
||||
(RelayUrl::parse("wss://relay.damus.io/").unwrap(), None),
|
||||
(RelayUrl::parse("wss://relay.primal.net/").unwrap(), None),
|
||||
]);
|
||||
|
||||
if let Err(e) = client.send_event_builder(builder).await {
|
||||
log::error!("Failed to send relay list event: {}", e)
|
||||
}
|
||||
if let Err(e) = client.send_event_builder(builder).await {
|
||||
log::error!("Failed to send relay list event: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
let tags: Vec<Tag> = relays
|
||||
.into_iter()
|
||||
.iter()
|
||||
.map(|relay| Tag::custom(TagKind::Relay, vec![relay.to_string()]))
|
||||
.collect();
|
||||
|
||||
let builder = EventBuilder::new(Kind::InboxRelays, "").tags(tags);
|
||||
let output = client.send_event_builder(builder).await?;
|
||||
|
||||
if let Ok(output) = client.send_event_builder(builder).await {
|
||||
_ = tx.send(output.val);
|
||||
};
|
||||
})
|
||||
.detach();
|
||||
// Connect to messaging relays
|
||||
for relay in relays.into_iter() {
|
||||
_ = client.add_relay(&relay).await;
|
||||
_ = client.connect_relay(&relay).await;
|
||||
}
|
||||
|
||||
let sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
|
||||
|
||||
// Close old subscription
|
||||
client.unsubscribe(&sub_id).await;
|
||||
|
||||
// Subscribe to new messages
|
||||
if let Err(e) = client
|
||||
.subscribe_with_id(
|
||||
sub_id,
|
||||
Filter::new()
|
||||
.kind(Kind::GiftWrap)
|
||||
.pubkey(public_key)
|
||||
.limit(0),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::error!("Failed to subscribe to new messages: {}", e);
|
||||
}
|
||||
|
||||
Ok(output.val)
|
||||
});
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if rx.await.is_ok() {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
if task.await.is_ok() {
|
||||
cx.update_window(window_handle, |_, window, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
if let Some(device) = Device::global(cx) {
|
||||
let relays = this
|
||||
.read_with(cx, |this, cx| this.relays.read(cx).clone())
|
||||
.unwrap();
|
||||
|
||||
device.update(cx, |this, cx| {
|
||||
if let Some(profile) = this.profile() {
|
||||
let new_profile = profile.clone().relays(Some(relays.into()));
|
||||
this.set_profile(new_profile, cx);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
window.close_modal(cx);
|
||||
});
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
@@ -134,7 +218,7 @@ impl Relays {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Ok(url) = Url::parse(&value) {
|
||||
if let Ok(url) = RelayUrl::parse(&value) {
|
||||
self.relays.update(cx, |this, cx| {
|
||||
if !this.contains(&url) {
|
||||
this.push(url);
|
||||
@@ -163,6 +247,7 @@ impl Render for Relays {
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_2()
|
||||
.w_full()
|
||||
.child(
|
||||
div()
|
||||
.px_2()
|
||||
@@ -173,6 +258,7 @@ impl Render for Relays {
|
||||
.child(
|
||||
div()
|
||||
.px_2()
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_2()
|
||||
@@ -180,6 +266,7 @@ impl Render for Relays {
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.w_full()
|
||||
.gap_2()
|
||||
.child(self.input.clone())
|
||||
.child(
|
||||
@@ -247,6 +334,7 @@ impl Render for Relays {
|
||||
items
|
||||
},
|
||||
)
|
||||
.w_full()
|
||||
.min_h(px(120.)),
|
||||
)
|
||||
} else {
|
||||
@@ -257,7 +345,7 @@ impl Render for Relays {
|
||||
.justify_center()
|
||||
.text_xs()
|
||||
.text_align(TextAlign::Center)
|
||||
.child("Please add some relays.")
|
||||
.child(HELP_TEXT)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use async_utility::task::spawn;
|
||||
use chats::{registry::ChatRegistry, room::Room};
|
||||
use common::{profile::NostrProfile, utils::random_name};
|
||||
use global::{constants::DEVICE_ANNOUNCEMENT_KIND, get_client};
|
||||
use gpui::{
|
||||
div, img, impl_internal_actions, prelude::FluentBuilder, px, relative, uniform_list, App,
|
||||
AppContext, Context, Entity, FocusHandle, InteractiveElement, IntoElement, ParentElement,
|
||||
Render, SharedString, StatefulInteractiveElement, Styled, Subscription, TextAlign, Window,
|
||||
Render, SharedString, StatefulInteractiveElement, Styled, Subscription, Task, TextAlign,
|
||||
Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use serde::Deserialize;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use smol::Timer;
|
||||
use state::get_client;
|
||||
use std::{collections::HashSet, time::Duration};
|
||||
use ui::{
|
||||
button::{Button, ButtonRounded},
|
||||
@@ -18,7 +19,7 @@ use ui::{
|
||||
ContextModal, Icon, IconName, Sizable, Size, StyledExt,
|
||||
};
|
||||
|
||||
const ALERT: &str =
|
||||
const DESCRIPTION: &str =
|
||||
"Start a conversation with someone using their npub or NIP-05 (like foo@bar.com).";
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Deserialize)]
|
||||
@@ -36,7 +37,7 @@ pub struct Compose {
|
||||
is_submitting: bool,
|
||||
error_message: Entity<Option<SharedString>>,
|
||||
#[allow(dead_code)]
|
||||
subscriptions: Vec<Subscription>,
|
||||
subscriptions: SmallVec<[Subscription; 1]>,
|
||||
}
|
||||
|
||||
impl Compose {
|
||||
@@ -44,7 +45,6 @@ impl Compose {
|
||||
let contacts = cx.new(|_| Vec::new());
|
||||
let selected = cx.new(|_| HashSet::new());
|
||||
let error_message = cx.new(|_| None);
|
||||
let mut subscriptions = Vec::new();
|
||||
|
||||
let title_input = cx.new(|cx| {
|
||||
let name = random_name(2);
|
||||
@@ -64,17 +64,15 @@ impl Compose {
|
||||
.placeholder("npub1...")
|
||||
});
|
||||
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
// Handle Enter event for user input
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&user_input,
|
||||
window,
|
||||
move |this, input, input_event, window, cx| {
|
||||
move |this, _, input_event, window, cx| {
|
||||
if let InputEvent::PressEnter = input_event {
|
||||
if input.read(cx).text().contains("@") {
|
||||
this.add_nip05(window, cx);
|
||||
} else {
|
||||
this.add_npub(window, cx)
|
||||
}
|
||||
this.add(window, cx);
|
||||
}
|
||||
},
|
||||
));
|
||||
@@ -148,50 +146,48 @@ impl Compose {
|
||||
}
|
||||
|
||||
let tags = Tags::from_list(tag_list);
|
||||
let client = get_client();
|
||||
let window_handle = window.window_handle();
|
||||
let (tx, rx) = oneshot::channel::<Event>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let signer = client.signer().await.expect("Signer is required");
|
||||
let event: Task<Result<Event, anyhow::Error>> = cx.background_spawn(async move {
|
||||
let client = get_client();
|
||||
let signer = client.signer().await?;
|
||||
// [IMPORTANT]
|
||||
// Make sure this event is never send,
|
||||
// this event existed just use for convert to Coop's Chat Room later.
|
||||
if let Ok(event) = EventBuilder::private_msg_rumor(*pubkeys.last().unwrap(), "")
|
||||
let event = EventBuilder::private_msg_rumor(*pubkeys.last().unwrap(), "")
|
||||
.tags(tags)
|
||||
.sign(&signer)
|
||||
.await
|
||||
{
|
||||
_ = tx.send(event)
|
||||
};
|
||||
})
|
||||
.detach();
|
||||
.await?;
|
||||
|
||||
Ok(event)
|
||||
});
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if let Ok(event) = rx.await {
|
||||
if let Ok(event) = event.await {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
// Stop loading spinner
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_submitting(false, cx);
|
||||
});
|
||||
|
||||
if let Some(chats) = ChatRegistry::global(cx) {
|
||||
let room = Room::new(&event, cx);
|
||||
let Some(chats) = ChatRegistry::global(cx) else {
|
||||
return;
|
||||
};
|
||||
let room = Room::new(&event, cx);
|
||||
|
||||
chats.update(cx, |state, cx| {
|
||||
match state.push_room(room, cx) {
|
||||
Ok(_) => {
|
||||
// TODO: open chat panel
|
||||
window.close_modal(cx);
|
||||
}
|
||||
Err(e) => {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_error(Some(e.to_string().into()), cx);
|
||||
});
|
||||
}
|
||||
chats.update(cx, |state, cx| {
|
||||
match state.push_room(room, cx) {
|
||||
Ok(_) => {
|
||||
// TODO: automatically open newly created chat panel
|
||||
window.close_modal(cx);
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_error(Some(e.to_string().into()), cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
})
|
||||
@@ -210,130 +206,97 @@ impl Compose {
|
||||
self.is_submitting
|
||||
}
|
||||
|
||||
fn add_npub(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
fn add(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let client = get_client();
|
||||
let window_handle = window.window_handle();
|
||||
let content = self.user_input.read(cx).text().to_string();
|
||||
|
||||
// Show loading spinner
|
||||
self.set_loading(true, cx);
|
||||
|
||||
let Ok(public_key) = PublicKey::parse(&content) else {
|
||||
self.set_loading(false, cx);
|
||||
self.set_error(Some("Public Key is not valid".into()), cx);
|
||||
return;
|
||||
let task: Task<Result<NostrProfile, anyhow::Error>> = if content.contains("@") {
|
||||
cx.background_spawn(async move {
|
||||
let profile = nip05::profile(&content, None).await?;
|
||||
let public_key = profile.public_key;
|
||||
|
||||
let metadata = client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(NostrProfile::new(public_key, metadata))
|
||||
})
|
||||
} else {
|
||||
let Ok(public_key) = PublicKey::parse(&content) else {
|
||||
self.set_loading(false, cx);
|
||||
self.set_error(Some("Public Key is not valid".into()), cx);
|
||||
return;
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let metadata = client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await?
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(NostrProfile::new(public_key, metadata))
|
||||
})
|
||||
};
|
||||
|
||||
if self
|
||||
.contacts
|
||||
.read(cx)
|
||||
.iter()
|
||||
.any(|c| c.public_key() == public_key)
|
||||
{
|
||||
self.set_loading(false, cx);
|
||||
return;
|
||||
};
|
||||
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Metadata>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let metadata = (client
|
||||
.fetch_metadata(public_key, Duration::from_secs(2))
|
||||
.await)
|
||||
.unwrap_or_default();
|
||||
|
||||
_ = tx.send(metadata);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if let Ok(metadata) = rx.await {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.contacts.update(cx, |this, cx| {
|
||||
this.insert(0, NostrProfile::new(public_key, metadata));
|
||||
cx.notify();
|
||||
});
|
||||
match task.await {
|
||||
Ok(profile) => {
|
||||
let public_key = profile.public_key;
|
||||
|
||||
this.selected.update(cx, |this, cx| {
|
||||
this.insert(public_key);
|
||||
cx.notify();
|
||||
});
|
||||
_ = cx
|
||||
.background_spawn(async move {
|
||||
let opts = SubscribeAutoCloseOptions::default()
|
||||
.exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
// Stop loading indicator
|
||||
this.set_loading(false, cx);
|
||||
// Create a device announcement filter
|
||||
let device = Filter::new()
|
||||
.kind(Kind::Custom(DEVICE_ANNOUNCEMENT_KIND))
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
// Clear input
|
||||
this.user_input.update(cx, |this, cx| {
|
||||
this.set_text("", window, cx);
|
||||
cx.notify();
|
||||
// Only subscribe to the latest device announcement
|
||||
client.subscribe(device, Some(opts)).await
|
||||
})
|
||||
.await;
|
||||
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
let public_key = profile.public_key;
|
||||
|
||||
this.contacts.update(cx, |this, cx| {
|
||||
this.insert(0, profile);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
this.selected.update(cx, |this, cx| {
|
||||
this.insert(public_key);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Stop loading indicator
|
||||
this.set_loading(false, cx);
|
||||
|
||||
// Clear input
|
||||
this.user_input.update(cx, |this, cx| {
|
||||
this.set_text("", window, cx);
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn add_nip05(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let window_handle = window.window_handle();
|
||||
let content = self.user_input.read(cx).text().to_string();
|
||||
|
||||
// Show loading spinner
|
||||
self.set_loading(true, cx);
|
||||
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Option<NostrProfile>>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
spawn(async move {
|
||||
if let Ok(profile) = nip05::profile(&content, None).await {
|
||||
let metadata = (client
|
||||
.fetch_metadata(profile.public_key, Duration::from_secs(2))
|
||||
.await)
|
||||
.unwrap_or_default();
|
||||
|
||||
_ = tx.send(Some(NostrProfile::new(profile.public_key, metadata)));
|
||||
} else {
|
||||
_ = tx.send(None);
|
||||
}
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
if let Ok(Some(profile)) = rx.await {
|
||||
_ = cx.update_window(window_handle, |_, window, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
let public_key = profile.public_key();
|
||||
|
||||
this.contacts.update(cx, |this, cx| {
|
||||
this.insert(0, profile);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
this.selected.update(cx, |this, cx| {
|
||||
this.insert(public_key);
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Stop loading indicator
|
||||
this.set_loading(false, cx);
|
||||
|
||||
// Clear input
|
||||
this.user_input.update(cx, |this, cx| {
|
||||
this.set_text("", window, cx);
|
||||
cx.notify();
|
||||
Err(e) => {
|
||||
_ = cx.update_window(window_handle, |_, _, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
this.set_error(Some(e.to_string().into()), cx);
|
||||
});
|
||||
});
|
||||
});
|
||||
} else {
|
||||
_ = cx.update_window(window_handle, |_, _, cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
this.set_error(Some("NIP-05 Address is not valid".into()), cx);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
@@ -398,7 +361,7 @@ impl Render for Compose {
|
||||
.px_2()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().base.step(cx, ColorScaleStep::ELEVEN))
|
||||
.child(ALERT),
|
||||
.child(DESCRIPTION),
|
||||
)
|
||||
.when_some(self.error_message.read(cx).as_ref(), |this, msg| {
|
||||
this.child(
|
||||
@@ -442,11 +405,7 @@ impl Render for Compose {
|
||||
.rounded(ButtonRounded::Size(px(9999.)))
|
||||
.loading(self.is_loading)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
if this.user_input.read(cx).text().contains("@") {
|
||||
this.add_nip05(window, cx);
|
||||
} else {
|
||||
this.add_npub(window, cx);
|
||||
}
|
||||
this.add(window, cx);
|
||||
})),
|
||||
)
|
||||
.child(self.user_input.clone()),
|
||||
@@ -493,7 +452,7 @@ impl Render for Compose {
|
||||
|
||||
for ix in range {
|
||||
let item = contacts.get(ix).unwrap().clone();
|
||||
let is_select = selected.contains(&item.public_key());
|
||||
let is_select = selected.contains(&item.public_key);
|
||||
|
||||
items.push(
|
||||
div()
|
||||
@@ -512,10 +471,10 @@ impl Render for Compose {
|
||||
.text_xs()
|
||||
.child(
|
||||
div().flex_shrink_0().child(
|
||||
img(item.avatar()).size_6(),
|
||||
img(item.avatar).size_6(),
|
||||
),
|
||||
)
|
||||
.child(item.name()),
|
||||
.child(item.name),
|
||||
)
|
||||
.when(is_select, |this| {
|
||||
this.child(
|
||||
@@ -536,7 +495,7 @@ impl Render for Compose {
|
||||
.on_click(move |_, window, cx| {
|
||||
window.dispatch_action(
|
||||
Box::new(SelectContact(
|
||||
item.public_key(),
|
||||
item.public_key,
|
||||
)),
|
||||
cx,
|
||||
);
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use chats::{registry::ChatRegistry, room::Room};
|
||||
use compose::Compose;
|
||||
use gpui::{
|
||||
div, img, percentage, prelude::FluentBuilder, px, uniform_list, AnyElement, App, AppContext,
|
||||
Context, Div, Empty, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
|
||||
IntoElement, ParentElement, Render, SharedString, Stateful, StatefulInteractiveElement, Styled,
|
||||
Window,
|
||||
div, img, percentage, prelude::FluentBuilder, px, relative, uniform_list, AnyElement, App,
|
||||
AppContext, Context, Div, Empty, Entity, EventEmitter, FocusHandle, Focusable,
|
||||
InteractiveElement, IntoElement, ParentElement, Render, SharedString, Stateful,
|
||||
StatefulInteractiveElement, Styled, Window,
|
||||
};
|
||||
use ui::{
|
||||
button::{Button, ButtonRounded, ButtonVariants},
|
||||
dock_area::panel::{Panel, PanelEvent},
|
||||
popup_menu::PopupMenu,
|
||||
skeleton::Skeleton,
|
||||
theme::{scale::ColorScaleStep, ActiveTheme},
|
||||
ContextModal, Disableable, Icon, IconName, Sizable, StyledExt,
|
||||
};
|
||||
@@ -116,8 +117,13 @@ impl Sidebar {
|
||||
this.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(img(member.avatar()).size_6().rounded_full().flex_shrink_0())
|
||||
.child(member.name())
|
||||
.child(
|
||||
img(member.avatar.clone())
|
||||
.size_6()
|
||||
.rounded_full()
|
||||
.flex_shrink_0(),
|
||||
)
|
||||
.child(member.name.clone())
|
||||
})
|
||||
}
|
||||
}))
|
||||
@@ -136,6 +142,20 @@ impl Sidebar {
|
||||
})
|
||||
}
|
||||
|
||||
fn render_skeleton(&self, total: i32) -> impl IntoIterator<Item = impl IntoElement> {
|
||||
(0..total).map(|_| {
|
||||
div()
|
||||
.h_8()
|
||||
.w_full()
|
||||
.px_1()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(Skeleton::new().flex_shrink_0().size_6().rounded_full())
|
||||
.child(Skeleton::new().w_20().h_3().rounded_sm())
|
||||
})
|
||||
}
|
||||
|
||||
fn open(&self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
|
||||
window.dispatch_action(
|
||||
Box::new(AddPanel::new(
|
||||
@@ -261,28 +281,65 @@ impl Render for Sidebar {
|
||||
this.flex_1()
|
||||
.w_full()
|
||||
.when_some(ChatRegistry::global(cx), |this, state| {
|
||||
let rooms = state.read(cx).rooms();
|
||||
let len = rooms.len();
|
||||
let is_loading = state.read(cx).is_loading();
|
||||
let len = state.read(cx).rooms().len();
|
||||
|
||||
this.child(
|
||||
uniform_list(
|
||||
entity,
|
||||
"rooms",
|
||||
len,
|
||||
move |this, range, _, cx| {
|
||||
let mut items = vec![];
|
||||
|
||||
for ix in range {
|
||||
if let Some(room) = rooms.get(ix) {
|
||||
items.push(this.render_room(ix, room, cx));
|
||||
}
|
||||
}
|
||||
|
||||
items
|
||||
},
|
||||
if is_loading {
|
||||
this.children(self.render_skeleton(5))
|
||||
} else if state.read(cx).rooms().is_empty() {
|
||||
this.child(
|
||||
div()
|
||||
.px_1()
|
||||
.w_full()
|
||||
.h_20()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_center()
|
||||
.rounded(px(cx.theme().radius))
|
||||
.bg(cx.theme().base.step(cx, ColorScaleStep::THREE))
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.line_height(relative(1.2))
|
||||
.child("No chats"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(
|
||||
cx.theme()
|
||||
.base
|
||||
.step(cx, ColorScaleStep::ELEVEN),
|
||||
)
|
||||
.child("Recent chats will appear here."),
|
||||
),
|
||||
)
|
||||
.size_full(),
|
||||
)
|
||||
} else {
|
||||
this.child(
|
||||
uniform_list(
|
||||
entity,
|
||||
"rooms",
|
||||
len,
|
||||
move |this, range, _, cx| {
|
||||
let mut items = vec![];
|
||||
|
||||
for ix in range {
|
||||
if let Some(room) =
|
||||
state.read(cx).rooms().get(ix)
|
||||
{
|
||||
items.push(this.render_room(ix, room, cx));
|
||||
}
|
||||
}
|
||||
|
||||
items
|
||||
},
|
||||
)
|
||||
.size_full(),
|
||||
)
|
||||
}
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
32
crates/app/src/views/startup.rs
Normal file
32
crates/app/src/views/startup.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use gpui::{
|
||||
div, svg, App, AppContext, Context, Entity, IntoElement, ParentElement, Render, Styled, Window,
|
||||
};
|
||||
use ui::theme::{scale::ColorScaleStep, ActiveTheme};
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Startup> {
|
||||
Startup::new(window, cx)
|
||||
}
|
||||
|
||||
pub struct Startup {}
|
||||
|
||||
impl Startup {
|
||||
pub fn new(_window: &mut Window, cx: &mut App) -> Entity<Self> {
|
||||
cx.new(|_| Self {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Startup {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.size_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.child(
|
||||
svg()
|
||||
.path("brand/coop.svg")
|
||||
.size_12()
|
||||
.text_color(cx.theme().base.step(cx, ColorScaleStep::THREE)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../common" }
|
||||
state = { path = "../state" }
|
||||
global = { path = "../global" }
|
||||
|
||||
gpui.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
@@ -16,3 +16,4 @@ chrono.workspace = true
|
||||
smallvec.workspace = true
|
||||
smol.workspace = true
|
||||
oneshot.workspace = true
|
||||
log.workspace = true
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::room::Room;
|
||||
use std::cmp::Reverse;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use common::{last_seen::LastSeen, utils::room_hash};
|
||||
use gpui::{App, AppContext, Context, Entity, Global, WeakEntity};
|
||||
use global::get_client;
|
||||
use gpui::{App, AppContext, Context, Entity, Global, Task, WeakEntity};
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
use state::get_client;
|
||||
use std::{cmp::Reverse, rc::Rc, sync::RwLock};
|
||||
|
||||
use crate::room::{IncomingEvent, Room};
|
||||
|
||||
pub fn init(cx: &mut App) {
|
||||
ChatRegistry::register(cx);
|
||||
@@ -16,7 +18,7 @@ struct GlobalChatRegistry(Entity<ChatRegistry>);
|
||||
impl Global for GlobalChatRegistry {}
|
||||
|
||||
pub struct ChatRegistry {
|
||||
rooms: Rc<RwLock<Vec<Entity<Room>>>>,
|
||||
rooms: Vec<Entity<Room>>,
|
||||
is_loading: bool,
|
||||
}
|
||||
|
||||
@@ -28,13 +30,7 @@ impl ChatRegistry {
|
||||
|
||||
pub fn register(cx: &mut App) -> Entity<Self> {
|
||||
Self::global(cx).unwrap_or_else(|| {
|
||||
let entity = cx.new(|cx| {
|
||||
let mut this = Self::new(cx);
|
||||
// Automatically load chat rooms the database when the registry is created
|
||||
this.load_chat_rooms(cx);
|
||||
|
||||
this
|
||||
});
|
||||
let entity = cx.new(Self::new);
|
||||
|
||||
// Set global state
|
||||
cx.set_global(GlobalChatRegistry(entity.clone()));
|
||||
@@ -45,71 +41,56 @@ impl ChatRegistry {
|
||||
|
||||
fn new(_cx: &mut Context<Self>) -> Self {
|
||||
Self {
|
||||
rooms: Rc::new(RwLock::new(vec![])),
|
||||
rooms: vec![],
|
||||
is_loading: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_rooms_ids(&self, cx: &mut Context<Self>) -> Vec<u64> {
|
||||
self.rooms
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|room| room.read(cx).id)
|
||||
.collect()
|
||||
self.rooms.iter().map(|room| room.read(cx).id).collect()
|
||||
}
|
||||
|
||||
pub fn load_chat_rooms(&mut self, cx: &mut Context<Self>) {
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Option<Vec<Event>>>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let result = async {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let task: Task<Result<Vec<Event>, Error>> = cx.background_spawn(async move {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let send = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.author(public_key);
|
||||
let send = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.author(public_key);
|
||||
|
||||
let recv = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.pubkey(public_key);
|
||||
let recv = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.pubkey(public_key);
|
||||
|
||||
let send_events = client.database().query(send).await?;
|
||||
let recv_events = client.database().query(recv).await?;
|
||||
let send_events = client.database().query(send).await?;
|
||||
let recv_events = client.database().query(recv).await?;
|
||||
let events = send_events.merge(recv_events);
|
||||
|
||||
Ok::<_, anyhow::Error>(send_events.merge(recv_events))
|
||||
}
|
||||
.await;
|
||||
let result: Vec<Event> = events
|
||||
.into_iter()
|
||||
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
|
||||
.unique_by(room_hash)
|
||||
.sorted_by_key(|ev| Reverse(ev.created_at))
|
||||
.collect();
|
||||
|
||||
if let Ok(events) = result {
|
||||
let result: Vec<Event> = events
|
||||
.into_iter()
|
||||
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
|
||||
.unique_by(room_hash)
|
||||
.sorted_by_key(|ev| Reverse(ev.created_at))
|
||||
.collect();
|
||||
|
||||
_ = tx.send(Some(result));
|
||||
} else {
|
||||
_ = tx.send(None);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
Ok(result)
|
||||
});
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
if let Ok(Some(events)) = rx.await {
|
||||
if !events.is_empty() {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
let current_rooms = this.current_rooms_ids(cx);
|
||||
if let Ok(events) = task.await {
|
||||
_ = cx.update(|cx| {
|
||||
_ = this.update(cx, |this, cx| {
|
||||
if !events.is_empty() {
|
||||
let current_ids = this.current_rooms_ids(cx);
|
||||
let items: Vec<Entity<Room>> = events
|
||||
.into_iter()
|
||||
.filter_map(|ev| {
|
||||
let new = room_hash(&ev);
|
||||
// Filter all seen events
|
||||
if !current_rooms.iter().any(|this| this == &new) {
|
||||
// Filter all seen rooms
|
||||
if !current_ids.iter().any(|this| this == &new) {
|
||||
Some(Room::new(&ev, cx))
|
||||
} else {
|
||||
None
|
||||
@@ -117,20 +98,25 @@ impl ChatRegistry {
|
||||
})
|
||||
.collect();
|
||||
|
||||
this.rooms.write().unwrap().extend(items);
|
||||
this.is_loading = false;
|
||||
|
||||
cx.notify();
|
||||
});
|
||||
this.rooms.extend(items);
|
||||
this.rooms
|
||||
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
|
||||
} else {
|
||||
this.is_loading = false;
|
||||
}
|
||||
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub fn rooms(&self) -> Vec<Entity<Room>> {
|
||||
self.rooms.read().unwrap().clone()
|
||||
pub fn rooms(&self) -> &[Entity<Room>] {
|
||||
&self.rooms
|
||||
}
|
||||
|
||||
pub fn is_loading(&self) -> bool {
|
||||
@@ -139,8 +125,6 @@ impl ChatRegistry {
|
||||
|
||||
pub fn get(&self, id: &u64, cx: &App) -> Option<WeakEntity<Room>> {
|
||||
self.rooms
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|model| model.read(cx).id == *id)
|
||||
.map(|room| room.downgrade())
|
||||
@@ -151,44 +135,40 @@ impl ChatRegistry {
|
||||
room: Entity<Room>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let mut rooms = self.rooms.write().unwrap();
|
||||
|
||||
if !rooms
|
||||
if !self
|
||||
.rooms
|
||||
.iter()
|
||||
.any(|current| current.read(cx) == room.read(cx))
|
||||
{
|
||||
rooms.insert(0, room);
|
||||
self.rooms.insert(0, room);
|
||||
cx.notify();
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("Room is existed"))
|
||||
Err(anyhow!("Room already exists"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_message(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||
let id = room_hash(&event);
|
||||
let mut rooms = self.rooms.write().unwrap();
|
||||
|
||||
if let Some(room) = rooms.iter().find(|room| room.read(cx).id == id) {
|
||||
if let Some(room) = self.rooms.iter().find(|room| room.read(cx).id == id) {
|
||||
room.update(cx, |this, cx| {
|
||||
if let Some(last_seen) = Rc::get_mut(&mut this.last_seen) {
|
||||
*last_seen = LastSeen(event.created_at);
|
||||
}
|
||||
this.new_messages.push(event);
|
||||
this.last_seen = LastSeen(event.created_at);
|
||||
cx.emit(IncomingEvent { event });
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Re sort rooms by last seen
|
||||
rooms.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
|
||||
|
||||
cx.notify();
|
||||
// Re-sort rooms by last seen
|
||||
self.rooms
|
||||
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
|
||||
} else {
|
||||
let mut rooms = self.rooms.write().unwrap();
|
||||
let new_room = Room::new(&event, cx);
|
||||
|
||||
rooms.insert(0, new_room);
|
||||
cx.notify();
|
||||
// Push the new room to the front of the list
|
||||
self.rooms.insert(0, new_room);
|
||||
}
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::{anyhow, Error};
|
||||
use common::{
|
||||
last_seen::LastSeen,
|
||||
profile::NostrProfile,
|
||||
utils::{random_name, room_hash},
|
||||
utils::{device_pubkey, room_hash},
|
||||
};
|
||||
use gpui::{App, AppContext, Entity, SharedString};
|
||||
use global::{constants::DEVICE_ANNOUNCEMENT_KIND, get_client, get_device_keys};
|
||||
use gpui::{App, AppContext, Entity, EventEmitter, SharedString, Task};
|
||||
use nostr_sdk::prelude::*;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use state::get_client;
|
||||
use std::{collections::HashSet, rc::Rc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IncomingEvent {
|
||||
pub event: Event,
|
||||
}
|
||||
|
||||
pub struct Room {
|
||||
pub id: u64,
|
||||
pub last_seen: Rc<LastSeen>,
|
||||
/// Subject of the room (Nostr)
|
||||
pub title: String,
|
||||
/// Display name of the room (used for display purposes in Coop)
|
||||
pub display_name: Option<SharedString>,
|
||||
pub last_seen: LastSeen,
|
||||
/// Subject of the room
|
||||
pub name: Option<SharedString>,
|
||||
/// All members of the room
|
||||
pub members: SmallVec<[NostrProfile; 2]>,
|
||||
/// Store all new messages
|
||||
pub new_messages: Vec<Event>,
|
||||
}
|
||||
|
||||
impl EventEmitter<IncomingEvent> for Room {}
|
||||
|
||||
impl PartialEq for Room {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
@@ -31,79 +36,48 @@ impl PartialEq for Room {
|
||||
impl Room {
|
||||
pub fn new(event: &Event, cx: &mut App) -> Entity<Self> {
|
||||
let id = room_hash(event);
|
||||
let last_seen = Rc::new(LastSeen(event.created_at));
|
||||
// Get the subject from the event's tags, or create a random subject if none is found
|
||||
let title = if let Some(tag) = event.tags.find(TagKind::Subject) {
|
||||
tag.content()
|
||||
.map(|s| s.to_owned())
|
||||
.unwrap_or(random_name(2))
|
||||
let last_seen = LastSeen(event.created_at);
|
||||
|
||||
// Get the subject from the event's tags
|
||||
let name = if let Some(tag) = event.tags.find(TagKind::Subject) {
|
||||
tag.content().map(|s| s.to_owned().into())
|
||||
} else {
|
||||
random_name(2)
|
||||
None
|
||||
};
|
||||
|
||||
// Create a task for loading metadata
|
||||
let load_metadata = Self::load_metadata(event, cx);
|
||||
|
||||
let room = cx.new(|cx| {
|
||||
let this = Self {
|
||||
id,
|
||||
last_seen,
|
||||
title,
|
||||
display_name: None,
|
||||
name,
|
||||
members: smallvec![],
|
||||
new_messages: vec![],
|
||||
};
|
||||
|
||||
let mut pubkeys = vec![];
|
||||
|
||||
// Get all pubkeys from event's tags
|
||||
pubkeys.extend(event.tags.public_keys().collect::<HashSet<_>>());
|
||||
pubkeys.push(event.pubkey);
|
||||
|
||||
let client = get_client();
|
||||
let (tx, rx) = oneshot::channel::<Vec<NostrProfile>>();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let signer = client.signer().await.unwrap();
|
||||
let signer_pubkey = signer.get_public_key().await.unwrap();
|
||||
let mut profiles = vec![];
|
||||
|
||||
for public_key in pubkeys.into_iter() {
|
||||
if let Ok(result) = client.database().metadata(public_key).await {
|
||||
let metadata = result.unwrap_or_default();
|
||||
let profile = NostrProfile::new(public_key, metadata);
|
||||
|
||||
if public_key == signer_pubkey {
|
||||
profiles.push(profile);
|
||||
} else {
|
||||
profiles.insert(0, profile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_ = tx.send(profiles);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(|this, cx| async move {
|
||||
if let Ok(profiles) = rx.await {
|
||||
if let Ok(profiles) = load_metadata.await {
|
||||
_ = cx.update(|cx| {
|
||||
let display_name = if profiles.len() > 2 {
|
||||
let merged = profiles
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|profile| profile.name().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
let name: SharedString =
|
||||
format!("{}, +{}", merged, profiles.len() - 2).into();
|
||||
|
||||
Some(name)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
_ = this.update(cx, |this: &mut Room, cx| {
|
||||
// Update the room's name if it's not already set
|
||||
if this.name.is_none() {
|
||||
let mut name = profiles
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|profile| profile.name.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
|
||||
if profiles.len() > 2 {
|
||||
name = format!("{}, +{}", name, profiles.len() - 2);
|
||||
}
|
||||
|
||||
this.name = Some(name.into())
|
||||
};
|
||||
// Update the room's members
|
||||
this.members.extend(profiles);
|
||||
this.display_name = display_name;
|
||||
|
||||
cx.notify();
|
||||
});
|
||||
});
|
||||
@@ -125,7 +99,7 @@ impl Room {
|
||||
pub fn member(&self, public_key: &PublicKey) -> Option<NostrProfile> {
|
||||
self.members
|
||||
.iter()
|
||||
.find(|m| &m.public_key() == public_key)
|
||||
.find(|m| &m.public_key == public_key)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
@@ -136,12 +110,12 @@ impl Room {
|
||||
|
||||
/// Collect room's member's public keys
|
||||
pub fn public_keys(&self) -> Vec<PublicKey> {
|
||||
self.members.iter().map(|m| m.public_key()).collect()
|
||||
self.members.iter().map(|m| m.public_key).collect()
|
||||
}
|
||||
|
||||
/// Get room's display name
|
||||
pub fn name(&self) -> Option<SharedString> {
|
||||
self.display_name.clone()
|
||||
self.name.clone()
|
||||
}
|
||||
|
||||
/// Determine if room is a group
|
||||
@@ -150,12 +124,159 @@ impl Room {
|
||||
}
|
||||
|
||||
/// Get room's last seen
|
||||
pub fn last_seen(&self) -> Rc<LastSeen> {
|
||||
self.last_seen.clone()
|
||||
pub fn last_seen(&self) -> LastSeen {
|
||||
self.last_seen
|
||||
}
|
||||
|
||||
/// Get room's last seen as ago format
|
||||
pub fn ago(&self) -> SharedString {
|
||||
self.last_seen.ago()
|
||||
}
|
||||
|
||||
/// Sync inbox relays for all room's members
|
||||
pub fn verify_inbox_relays(&self, cx: &App) -> Task<Result<Vec<(PublicKey, bool)>, Error>> {
|
||||
let client = get_client();
|
||||
let pubkeys = self.public_keys();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let mut result = Vec::with_capacity(pubkeys.len());
|
||||
|
||||
for pubkey in pubkeys.into_iter() {
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(pubkey)
|
||||
.limit(1);
|
||||
|
||||
let is_ready = client
|
||||
.database()
|
||||
.query(filter)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|events| events.first_owned())
|
||||
.is_some();
|
||||
|
||||
result.push((pubkey, is_ready));
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
})
|
||||
}
|
||||
|
||||
/// Send message to all room's members
|
||||
///
|
||||
/// NIP-4e: Message will be signed by the device signer
|
||||
pub fn send_message(&self, content: String, cx: &App) -> Task<Result<Vec<String>, Error>> {
|
||||
let client = get_client();
|
||||
let pubkeys = self.public_keys();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let Some(device) = get_device_keys().await else {
|
||||
return Err(anyhow!("Device not found. Please restart the application."));
|
||||
};
|
||||
|
||||
let user_signer = client.signer().await?;
|
||||
let user_pubkey = user_signer.get_public_key().await?;
|
||||
|
||||
let mut report = Vec::with_capacity(pubkeys.len());
|
||||
|
||||
let tags: Vec<Tag> = pubkeys
|
||||
.iter()
|
||||
.filter_map(|pubkey| {
|
||||
if pubkey != &user_pubkey {
|
||||
Some(Tag::public_key(*pubkey))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
for pubkey in pubkeys.iter() {
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Custom(DEVICE_ANNOUNCEMENT_KIND))
|
||||
.author(*pubkey)
|
||||
.limit(1);
|
||||
|
||||
// Check if the pubkey has a device announcement,
|
||||
// then choose the appropriate signer based on device presence
|
||||
let event = match client.database().query(filter).await?.first() {
|
||||
Some(event) => {
|
||||
log::info!("Use device signer to send message");
|
||||
let signer = &device;
|
||||
// Get the device's public key of other user
|
||||
let device_pubkey = device_pubkey(event)?;
|
||||
|
||||
let rumor = EventBuilder::private_msg_rumor(*pubkey, &content)
|
||||
.tags(tags.clone())
|
||||
.build(user_pubkey);
|
||||
|
||||
EventBuilder::gift_wrap(
|
||||
signer,
|
||||
&device_pubkey,
|
||||
rumor,
|
||||
vec![Tag::public_key(*pubkey)],
|
||||
)
|
||||
.await?
|
||||
}
|
||||
None => {
|
||||
log::info!("Use user signer to send message");
|
||||
let signer = client.signer().await?;
|
||||
|
||||
EventBuilder::private_msg(&signer, *pubkey, &content, tags.clone()).await?
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = client.send_event(&event).await {
|
||||
report.push(e.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
})
|
||||
}
|
||||
|
||||
/// Load metadata for all members
|
||||
pub fn load_messages(&self, cx: &App) -> Task<Result<Events, Error>> {
|
||||
let client = get_client();
|
||||
let pubkeys = self.public_keys();
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.authors(pubkeys.iter().copied())
|
||||
.pubkeys(pubkeys);
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let query = client.database().query(filter).await?;
|
||||
Ok(query)
|
||||
})
|
||||
}
|
||||
|
||||
/// Load metadata for all members
|
||||
fn load_metadata(event: &Event, cx: &App) -> Task<Result<Vec<NostrProfile>, Error>> {
|
||||
let client = get_client();
|
||||
let mut pubkeys = vec![];
|
||||
|
||||
// Get all pubkeys from event's tags
|
||||
pubkeys.extend(event.tags.public_keys().collect::<HashSet<_>>());
|
||||
pubkeys.push(event.pubkey);
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let signer = client.signer().await?;
|
||||
let signer_pubkey = signer.get_public_key().await?;
|
||||
let mut profiles = vec![];
|
||||
|
||||
for public_key in pubkeys.into_iter() {
|
||||
if let Ok(result) = client.database().metadata(public_key).await {
|
||||
let metadata = result.unwrap_or_default();
|
||||
let profile = NostrProfile::new(public_key, metadata);
|
||||
|
||||
if public_key == signer_pubkey {
|
||||
profiles.push(profile);
|
||||
} else {
|
||||
profiles.insert(0, profile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(profiles)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,15 @@ edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
global = { path = "../global" }
|
||||
|
||||
gpui.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
anyhow.workspace = true
|
||||
itertools.workspace = true
|
||||
chrono.workspace = true
|
||||
dirs.workspace = true
|
||||
smallvec.workspace = true
|
||||
|
||||
random_name_generator = "0.3.6"
|
||||
qrcode-generator = "5.0.0"
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod constants;
|
||||
pub mod last_seen;
|
||||
pub mod profile;
|
||||
pub mod qr;
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
use global::constants::IMAGE_SERVICE;
|
||||
use gpui::SharedString;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use crate::constants::IMAGE_SERVICE;
|
||||
use smallvec::SmallVec;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NostrProfile {
|
||||
public_key: PublicKey,
|
||||
avatar: SharedString,
|
||||
name: SharedString,
|
||||
pub public_key: PublicKey,
|
||||
pub avatar: SharedString,
|
||||
pub name: SharedString,
|
||||
pub messaging_relays: Option<SmallVec<[RelayUrl; 3]>>,
|
||||
}
|
||||
|
||||
impl NostrProfile {
|
||||
@@ -19,20 +20,14 @@ impl NostrProfile {
|
||||
public_key,
|
||||
name,
|
||||
avatar,
|
||||
messaging_relays: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get contact's public key
|
||||
pub fn public_key(&self) -> PublicKey {
|
||||
self.public_key
|
||||
}
|
||||
|
||||
pub fn avatar(&self) -> SharedString {
|
||||
self.avatar.clone()
|
||||
}
|
||||
|
||||
pub fn name(&self) -> SharedString {
|
||||
self.name.clone()
|
||||
/// Set contact's relays
|
||||
pub fn relays(mut self, relays: Option<SmallVec<[RelayUrl; 3]>>) -> Self {
|
||||
self.messaging_relays = relays;
|
||||
self
|
||||
}
|
||||
|
||||
fn extract_avatar(metadata: &Metadata) -> SharedString {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::constants::NIP96_SERVER;
|
||||
use anyhow::Context;
|
||||
use global::constants::NIP96_SERVER;
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
use rnglib::{Language, RNG};
|
||||
@@ -43,6 +44,14 @@ pub fn room_hash(event: &Event) -> u64 {
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
pub fn device_pubkey(event: &Event) -> Result<PublicKey, anyhow::Error> {
|
||||
let n_tag = event.tags.find(TagKind::custom("n")).context("Invalid")?;
|
||||
let hex = n_tag.content().context("Invalid")?;
|
||||
let pubkey = PublicKey::parse(hex)?;
|
||||
|
||||
Ok(pubkey)
|
||||
}
|
||||
|
||||
pub fn random_name(length: usize) -> String {
|
||||
let rng = RNG::from(&Language::Roman);
|
||||
rng.generate_names(length, true).join("-").to_lowercase()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "state"
|
||||
name = "global"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
@@ -7,3 +7,6 @@ publish = false
|
||||
[dependencies]
|
||||
nostr-sdk.workspace = true
|
||||
dirs.workspace = true
|
||||
smol.workspace = true
|
||||
|
||||
whoami = "1.5.2"
|
||||
@@ -1,10 +1,24 @@
|
||||
pub const KEYRING_SERVICE: &str = "Coop Safe Storage";
|
||||
pub const APP_NAME: &str = "Coop";
|
||||
pub const APP_ID: &str = "su.reya.coop";
|
||||
|
||||
pub const CLIENT_KEYRING: &str = "Coop Client Keys";
|
||||
pub const MASTER_KEYRING: &str = "Coop Master Keys";
|
||||
|
||||
pub const DEVICE_ANNOUNCEMENT_KIND: u16 = 10044;
|
||||
pub const DEVICE_REQUEST_KIND: u16 = 4454;
|
||||
pub const DEVICE_RESPONSE_KIND: u16 = 4455;
|
||||
|
||||
/// Bootstrap relays
|
||||
pub const BOOTSTRAP_RELAYS: [&str; 3] = [
|
||||
"wss://relay.damus.io",
|
||||
"wss://relay.primal.net",
|
||||
"wss://purplepag.es",
|
||||
];
|
||||
|
||||
/// Subscriptions
|
||||
pub const NEW_MESSAGE_SUB_ID: &str = "listen_new_giftwraps";
|
||||
pub const ALL_MESSAGES_SUB_ID: &str = "listen_all_giftwraps";
|
||||
pub const DEVICE_SUB_ID: &str = "listen_device_announcement";
|
||||
|
||||
/// Image Resizer Service
|
||||
pub const IMAGE_SERVICE: &str = "https://wsrv.nl";
|
||||
104
crates/global/src/lib.rs
Normal file
104
crates/global/src/lib.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
use constants::{ALL_MESSAGES_SUB_ID, APP_ID};
|
||||
use dirs::config_dir;
|
||||
use nostr_sdk::prelude::*;
|
||||
use smol::lock::Mutex;
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
sync::{Arc, OnceLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub mod constants;
|
||||
|
||||
/// Nostr Client
|
||||
static CLIENT: OnceLock<Client> = OnceLock::new();
|
||||
/// Current App Name
|
||||
static APP_NAME: OnceLock<Arc<str>> = OnceLock::new();
|
||||
/// NIP-4e: Device Keys, used for encryption
|
||||
static DEVICE_KEYS: Mutex<Option<Arc<dyn NostrSigner>>> = Mutex::new(None);
|
||||
/// NIP-4e: Device Name, used for display purposes
|
||||
static DEVICE_NAME: Mutex<Option<Arc<String>>> = Mutex::new(None);
|
||||
|
||||
/// Nostr Client instance
|
||||
pub fn get_client() -> &'static Client {
|
||||
CLIENT.get_or_init(|| {
|
||||
// Setup app data folder
|
||||
let config_dir = config_dir().expect("Config directory not found");
|
||||
let app_dir = config_dir.join(APP_ID);
|
||||
|
||||
// Create app directory if it doesn't exist
|
||||
_ = fs::create_dir_all(&app_dir);
|
||||
|
||||
// Setup database
|
||||
let lmdb = NostrLMDB::open(app_dir.join("nostr")).expect("Database is NOT initialized");
|
||||
|
||||
// Client options
|
||||
let opts = Options::new()
|
||||
// NIP-65
|
||||
.gossip(true)
|
||||
// Skip all very slow relays
|
||||
.max_avg_latency(Duration::from_secs(2));
|
||||
|
||||
// Setup Nostr Client
|
||||
ClientBuilder::default().database(lmdb).opts(opts).build()
|
||||
})
|
||||
}
|
||||
|
||||
/// Get app name
|
||||
pub fn get_app_name() -> &'static str {
|
||||
APP_NAME.get_or_init(|| {
|
||||
Arc::from(format!(
|
||||
"Coop on {} ({})",
|
||||
whoami::distro(),
|
||||
whoami::devicename()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Get device keys
|
||||
pub async fn get_device_keys() -> Option<Arc<dyn NostrSigner>> {
|
||||
let guard = DEVICE_KEYS.lock().await;
|
||||
guard.clone()
|
||||
}
|
||||
|
||||
/// Set device keys
|
||||
pub async fn set_device_keys<T>(signer: Arc<T>)
|
||||
where
|
||||
T: NostrSigner + 'static,
|
||||
{
|
||||
DEVICE_KEYS.lock().await.replace(signer);
|
||||
|
||||
// Re-subscribe to all messages
|
||||
smol::spawn(async move {
|
||||
let client = get_client();
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
if let Ok(signer) = client.signer().await {
|
||||
let public_key = signer.get_public_key().await.unwrap();
|
||||
|
||||
// Create a filter for getting all gift wrapped events send to current user
|
||||
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
||||
|
||||
let id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
|
||||
_ = client.unsubscribe(&id);
|
||||
_ = client.subscribe_with_id(id, filter, Some(opts)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Set master's device name
|
||||
pub async fn set_device_name(name: &str) {
|
||||
let mut guard = DEVICE_NAME.lock().await;
|
||||
|
||||
if guard.is_none() {
|
||||
guard.replace(Arc::new(name.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Get master's device name
|
||||
pub fn get_device_name() -> Arc<String> {
|
||||
let guard = DEVICE_NAME.lock_blocking();
|
||||
guard.clone().unwrap_or(Arc::new("Main Device".into()))
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
use dirs::config_dir;
|
||||
use nostr_sdk::prelude::*;
|
||||
use std::{fs, sync::OnceLock, time::Duration};
|
||||
|
||||
static CLIENT: OnceLock<Client> = OnceLock::new();
|
||||
|
||||
pub fn get_client() -> &'static Client {
|
||||
CLIENT.get_or_init(|| {
|
||||
// Setup app data folder
|
||||
let config_dir = config_dir().expect("Config directory not found");
|
||||
let app_dir = config_dir.join("Coop/");
|
||||
|
||||
// Create app directory if it doesn't exist
|
||||
_ = fs::create_dir_all(&app_dir);
|
||||
|
||||
// Setup database
|
||||
let lmdb = NostrLMDB::open(app_dir.join("nostr")).expect("Database is NOT initialized");
|
||||
|
||||
// Client options
|
||||
let opts = Options::new()
|
||||
// NIP-65
|
||||
.gossip(true)
|
||||
// Skip all very slow relays
|
||||
.max_avg_latency(Duration::from_millis(800));
|
||||
|
||||
// Setup Nostr Client
|
||||
ClientBuilder::default().database(lmdb).opts(opts).build()
|
||||
})
|
||||
}
|
||||
@@ -634,7 +634,18 @@ impl ButtonVariant {
|
||||
_ => cx.theme().base.step(cx, ColorScaleStep::THREE),
|
||||
};
|
||||
|
||||
let fg = cx.theme().base.step(cx, ColorScaleStep::ELEVEN);
|
||||
let fg = match self {
|
||||
ButtonVariant::Primary => match cx.theme().accent.name().to_string().as_str() {
|
||||
"Sky" => cx.theme().base.darken(cx),
|
||||
"Mint" => cx.theme().base.darken(cx),
|
||||
"Lime" => cx.theme().base.darken(cx),
|
||||
"Amber" => cx.theme().base.darken(cx),
|
||||
"Yellow" => cx.theme().base.darken(cx),
|
||||
_ => cx.theme().accent.step(cx, ColorScaleStep::ONE),
|
||||
},
|
||||
_ => cx.theme().base.step(cx, ColorScaleStep::ELEVEN),
|
||||
};
|
||||
|
||||
let border = bg;
|
||||
let underline = self.underline(window, cx);
|
||||
let shadow = false;
|
||||
|
||||
@@ -47,8 +47,7 @@ impl Modal {
|
||||
.border_1()
|
||||
.border_color(cx.theme().base.step(cx, ColorScaleStep::FIVE))
|
||||
.rounded_lg()
|
||||
.shadow_xl()
|
||||
.min_h_48();
|
||||
.shadow_xl();
|
||||
|
||||
Self {
|
||||
base,
|
||||
|
||||
@@ -212,6 +212,11 @@ impl Root {
|
||||
pub fn view(&self) -> &AnyView {
|
||||
&self.view
|
||||
}
|
||||
|
||||
/// Replace the root view of the Root.
|
||||
pub fn replace_view(&mut self, view: AnyView) {
|
||||
self.view = view;
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Root {
|
||||
|
||||
@@ -11,7 +11,7 @@ use gpui::{
|
||||
use std::rc::Rc;
|
||||
|
||||
const HEIGHT: Pixels = px(34.);
|
||||
const TITLE_BAR_HEIGHT: Pixels = px(35.);
|
||||
const TITLE_BAR_HEIGHT: Pixels = px(34.);
|
||||
#[cfg(target_os = "macos")]
|
||||
const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
|
||||
Reference in New Issue
Block a user