feat: make the web version fully working (#67)

Reviewed-on: #67
This commit was merged in pull request #67.
This commit is contained in:
2026-10-25 13:10:51 +00:00
parent 3212951ed4
commit 0824b1825b
42 changed files with 2948 additions and 936 deletions
+5
View File
@@ -9,3 +9,8 @@ gpui.workspace = true
anyhow.workspace = true
rust-embed.workspace = true
gpui-kit.workspace = true
# On wasm there is no filesystem to read from, so rust-embed's debug-mode
# disk loading returns nothing; embed the assets even in debug builds.
[target.'cfg(target_arch = "wasm32")'.dependencies]
rust-embed = { workspace = true, features = ["debug-embed"] }
+27
View File
@@ -20,12 +20,39 @@ impl AssetSource for CombinedAssets {
if let Ok(Some(data)) = Assets.load(path) {
return Ok(Some(data));
}
#[cfg(target_arch = "wasm32")]
{
// The kit bundle fetches icons over HTTP on the web; a single
// instance keeps its download cache alive across loads.
use std::sync::OnceLock;
static KIT_ASSETS: OnceLock<gpui_kit::assets::Assets> = OnceLock::new();
KIT_ASSETS
.get_or_init(gpui_kit::assets::Assets::default)
.load(path)
}
#[cfg(not(target_arch = "wasm32"))]
gpui_kit::assets::Assets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths = Assets.list(path).unwrap_or_default();
#[cfg(target_arch = "wasm32")]
{
use std::sync::OnceLock;
static KIT_ASSETS: OnceLock<gpui_kit::assets::Assets> = OnceLock::new();
paths.extend(
KIT_ASSETS
.get_or_init(gpui_kit::assets::Assets::default)
.list(path)?,
);
}
#[cfg(not(target_arch = "wasm32"))]
paths.extend(gpui_kit::assets::Assets.list(path)?);
Ok(paths)
}
}
+1
View File
@@ -11,6 +11,7 @@ serde.workspace = true
serde_json.workspace = true
futures.workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
gpui-updater-pre = "0.2"
[dev-dependencies]
+183 -94
View File
@@ -11,12 +11,12 @@ use gpui::{
App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Subscription, Task,
WeakEntity,
};
use instant::Duration;
use instant::{Duration, Instant};
use nip4e::{DeviceEvent, DeviceRegistry};
use nostr_sdk::prelude::*;
use person::PersonRegistry;
use smallvec::{SmallVec, smallvec};
use state::{DEVICE_GIFTWRAP, NostrRegistry, USER_GIFTWRAP};
use state::{DEVICE_GIFTWRAP, NostrRegistry, USER_GIFTWRAP, UniversalSigner};
mod message;
mod room;
@@ -29,7 +29,10 @@ pub use state::FileAttachment;
use crate::search::MessageSearchIndex;
/// A static keypair used only for signing locally-cached rumor events.
/// Upper bound on signals applied to the UI in a single update
const MAX_SIGNAL_BATCH: usize = 256;
/// Keypair used only for identifying locally-cached rumor events.
static LOCAL_KEYS: LazyLock<Keys> = LazyLock::new(Keys::generate);
pub fn init(cx: &mut App) {
@@ -74,6 +77,13 @@ impl Signal {
}
}
/// Which signer to attempt when unwrapping a gift wrap
enum UnwrapRoute {
User,
Device,
Both,
}
/// Chat Registry
#[derive(Debug)]
pub struct ChatRegistry {
@@ -216,32 +226,34 @@ impl ChatRegistry {
let tx = self.signal_tx.clone();
let rx = self.signal_rx.clone();
let executor = cx.background_executor().clone();
self.notification_listener = Some(cx.background_spawn(async move {
let mut notifications = client.notifications();
let mut processed_events = HashSet::new();
const MAX_PROCESSED: usize = 10_000;
let mut notifications = client.notifications();
let mut processed_events = HashSet::new();
let mut user_key = signer.get_public_key_async().await.ok();
let device_key = match device_signer.as_ref() {
Some(device) => device.get_public_key_async().await.ok(),
None => None,
};
let mut last_yield = Instant::now();
while let Some(notification) = notifications.next().await {
if last_yield.elapsed() >= Duration::from_millis(8) {
executor.timer(Duration::from_millis(0)).await;
last_yield = Instant::now();
}
let ClientNotification::Message { message, relay_url } = notification else {
continue;
};
match *message {
RelayMessage::Event {
subscription_id,
event,
..
} => {
let chat_sub = subscription_id.as_str() != sub_id1.as_str();
let device_sub = subscription_id.as_str() != sub_id2.as_str();
// Concord wraps are also kind 1059.
//
// Only the two gift wrap subscriptions carry NIP-59 wraps for this account.
if event.kind == Kind::GiftWrap && chat_sub && device_sub {
continue;
}
RelayMessage::Event { event, .. } => {
// Prune the dedup set before it grows unbounded
if processed_events.len() >= MAX_PROCESSED {
processed_events.clear();
@@ -253,8 +265,10 @@ impl ChatRegistry {
// Handle msg relays event to determine when the app is ready to subscribe
if event.kind == Kind::InboxRelays {
let current_user = signer.get_public_key_async().await?;
if event.pubkey == current_user {
if user_key.is_none() {
user_key = signer.get_public_key_async().await.ok();
}
if Some(event.pubkey) == user_key {
tx.send_async(Signal::InboxReady).await?;
}
}
@@ -270,15 +284,39 @@ impl ChatRegistry {
seen.entry(event.id).or_default().insert(relay_url);
}
// Route to the signer matching the recipient tag
// so a wrap is never decrypted twice.
let recipient = event.tags.public_keys().next();
let route = match recipient {
Some(key) if Some(key) == device_key => UnwrapRoute::Device,
Some(key) if Some(key) == user_key => UnwrapRoute::User,
Some(_) if user_key.is_some() && device_key.is_some() => continue,
_ => UnwrapRoute::Both,
};
// Extract the rumor from the gift wrap event
match extract_rumor(
&client,
&signer,
device_signer.as_ref(),
event.as_ref(),
)
.await
{
let result = match route {
UnwrapRoute::User => {
extract_rumor(&client, &signer, None, event.as_ref()).await
}
UnwrapRoute::Device => match device_signer.as_ref() {
Some(device) => {
extract_rumor(&client, device, None, event.as_ref()).await
}
None => continue,
},
UnwrapRoute::Both => {
extract_rumor(
&client,
&signer,
device_signer.as_ref(),
event.as_ref(),
)
.await
}
};
match result {
Ok(rumor) => {
let Some(rumor_id) = rumor.id else {
log::error!("Rumor missing id after ensure_id");
@@ -317,35 +355,56 @@ impl ChatRegistry {
Ok(())
}));
self.signal_consumer = Some(cx.spawn(async move |this, cx| {
while let Ok(message) = rx.recv_async().await {
match message {
Signal::Message(message) => {
this.update(cx, |this, cx| {
this.new_message(message, cx);
})?;
}
Signal::InboxReady => {
this.update(cx, |this, cx| {
this.get_messages(cx);
})?;
}
Signal::Eose => {
this.update(cx, |this, _cx| {
this.tracking.store(false, Ordering::Release);
})?;
let tracking = self.tracking.clone();
this.update(cx, |this, cx| {
this.get_rooms(cx);
})?;
self.signal_consumer = Some(cx.spawn(async move |this, cx| {
while let Ok(first) = rx.recv_async().await {
// Batch whatever has already arrived so the UI updates once per burst
let mut messages = Vec::new();
let mut errors = Vec::new();
let mut inbox_ready = false;
let mut eose = false;
let mut pending = Some(first);
while let Some(signal) = pending.take() {
match signal {
Signal::Message(message) => messages.push(message),
Signal::InboxReady => inbox_ready = true,
Signal::Eose => eose = true,
Signal::Error(failed) => errors.push(failed),
}
Signal::Error(failed) => {
trash.update(cx, |this, cx| {
this.insert(failed);
cx.notify();
})?;
if messages.len() + errors.len() >= MAX_SIGNAL_BATCH {
break;
}
};
pending = rx.try_recv().ok();
}
if inbox_ready {
this.update(cx, |this, cx| {
this.get_messages(cx);
})?;
}
if !messages.is_empty() {
this.update(cx, |this, cx| {
this.new_messages(messages, cx);
})?;
}
if !errors.is_empty() {
trash.update(cx, |trash, cx| {
trash.extend(errors);
cx.notify();
})?;
}
if eose && tracking.swap(false, Ordering::AcqRel) {
this.update(cx, |this, cx| {
this.get_rooms(cx);
})?;
}
}
Ok(())
@@ -669,6 +728,7 @@ impl ChatRegistry {
self.rooms.clear();
self.room_index.clear();
self.search.write().unwrap().clear();
self.tracking.store(true, Ordering::Release);
self.trash.update(cx, |this, cx| {
this.clear();
cx.notify();
@@ -748,6 +808,7 @@ impl ChatRegistry {
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let search = self.search.clone();
let executor = cx.background_executor().clone();
cx.background_spawn(async move {
let public_key = signer.get_public_key_async().await?;
@@ -775,7 +836,15 @@ impl ChatRegistry {
let events = client.database().query(filter).await?;
let mut grouped: HashMap<u64, Vec<UnsignedEvent>> = HashMap::new();
// Keep the single-threaded web event loop responsive during large rescans
let mut last_yield = Instant::now();
for raw in events.into_iter() {
if last_yield.elapsed() >= Duration::from_millis(8) {
executor.timer(Duration::from_millis(0)).await;
last_yield = Instant::now();
}
if let Ok(rumor) = UnsignedEvent::from_json(&raw.content)
&& rumor.tags.public_keys().next().is_some()
{
@@ -811,12 +880,17 @@ impl ChatRegistry {
})
}
/// Parse a nostr event into a message and push it to the belonging room
/// Parse nostr events into messages and push them to the belonging rooms
///
/// - If the room doesn't exist, it will be created.
/// - Updates room ordering based on the most recent messages.
pub(crate) fn new_message(&mut self, message: NewMessage, cx: &mut Context<Self>) {
self.search.write().unwrap().insert(&message.rumor);
/// - If a room doesn't exist, it will be created.
/// - Room ordering is updated once after the whole batch.
pub(crate) fn new_messages(&mut self, messages: Vec<NewMessage>, cx: &mut Context<Self>) {
{
let mut search = self.search.write().unwrap();
for message in &messages {
search.insert(&message.rumor);
}
}
let nostr = NostrRegistry::global(cx);
@@ -824,37 +898,42 @@ impl ChatRegistry {
return;
};
match self.room_index.get(&message.room).cloned() {
Some(room) => {
room.update(cx, |this, cx| {
if this.kind == RoomKind::Request
&& (message.rumor.pubkey == public_key || this.auto_trusted(public_key, cx))
{
this.set_ongoing(cx);
}
this.push_message(message, cx);
});
self.sort(cx);
}
None => {
// Push the new room to the front of the list
self.add_room(message.rumor, cx);
for message in messages {
match self.room_index.get(&message.room).cloned() {
Some(room) => {
room.update(cx, |this, cx| {
if this.kind == RoomKind::Request
&& (message.rumor.pubkey == public_key
|| this.auto_trusted(public_key, cx))
{
this.set_ongoing(cx);
}
this.push_message(message, cx);
});
}
None => {
// Push the new room to the front of the list
self.add_room(message.rumor, cx);
}
}
}
self.sort(cx);
}
/// Parse a nostr event into a message and push it to the belonging room
pub(crate) fn new_message(&mut self, message: NewMessage, cx: &mut Context<Self>) {
self.new_messages(vec![message], cx);
}
}
/// Unwraps a gift-wrapped event and processes its contents.
async fn extract_rumor<S, D>(
async fn extract_rumor(
client: &Client,
signer: &S,
device_signer: Option<&D>,
signer: &UniversalSigner,
device_signer: Option<&UniversalSigner>,
gift_wrap: &Event,
) -> Result<UnsignedEvent, Error>
where
S: AsyncNip44 + ?Sized,
D: AsyncNip44 + ?Sized,
{
) -> Result<UnsignedEvent, Error> {
// Try to get cached rumor first
if let Ok(rumor) = get_rumor(client, gift_wrap.id).await {
return Ok(rumor);
@@ -888,10 +967,10 @@ where
}
/// Attempts to unwrap a gift wrap event with a given signer.
async fn try_unwrap_with<S>(signer: &S, gift_wrap: &Event) -> Result<UnwrappedGift, Error>
where
S: AsyncNip44 + ?Sized,
{
async fn try_unwrap_with(
signer: &UniversalSigner,
gift_wrap: &Event,
) -> Result<UnwrappedGift, Error> {
// Get the sealed event
let seal = signer
.nip44_decrypt_async(&gift_wrap.pubkey, &gift_wrap.content)
@@ -926,17 +1005,27 @@ where
async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Result<(), Error> {
let room_id = rumor.uniq_id().to_string();
let tags = vec![
let tags = Tags::from_list(vec![
Tag::identifier(id),
Tag::public_key(rumor.pubkey),
Tag::custom("r", [room_id]),
Tag::custom("k", [rumor.kind.to_string()]),
];
]);
let event = EventBuilder::new(Kind::ApplicationSpecificData, rumor.as_json())
.tags(tags)
.finalize_async(&*LOCAL_KEYS)
.await?;
let public_key = LOCAL_KEYS.public_key();
let created_at = Timestamp::now();
let kind = Kind::ApplicationSpecificData;
let content = rumor.as_json();
let event = Event::new(
EventId::compute(&public_key, &created_at, &kind, &tags, &content),
public_key,
created_at,
kind,
tags,
content,
Signature::from_byte_array([0u8; 64]),
);
client.database().save_event(&event).await?;
+48 -10
View File
@@ -1,32 +1,70 @@
use std::path::{Path, PathBuf};
use chat::FileAttachment;
use anyhow::Error;
use gpui::SharedString;
use nostr_sdk::prelude::*;
use state::{FileAttachment, LocalFile, PickedFile};
/// A file attachment that has been uploaded, but not sent yet.
///
/// The local `path` is kept around so the composer can preview
/// The `local` handle is kept around so the composer can preview
/// the file without downloading and decrypting it again.
pub(crate) struct PendingFile {
pub file: FileAttachment,
pub path: PathBuf,
pub local: LocalFile,
}
/// State of the encrypted file attachment of a message
pub(crate) enum DecryptedFile {
Loading,
Ready(PathBuf),
Ready(LocalFile),
Failed(SharedString),
}
/// Result of an upload, either plain or encrypted
pub(crate) enum Uploaded {
Url(Url),
File(FileAttachment, PathBuf),
File(Box<UploadedFile>),
}
/// A `file://` url for a decrypted file, so it can be opened by the OS
pub(crate) fn file_url(path: &Path) -> String {
format!("file://{}", path.display())
/// An encrypted upload and the handle to preview it locally
pub(crate) struct UploadedFile {
pub file: FileAttachment,
pub local: LocalFile,
}
impl Uploaded {
/// Build the upload result for a picked file, encrypted when the
/// attachment is the whole message
pub(crate) async fn from_pick(
encrypted: bool,
server: Url,
picked: PickedFile,
cx: &gpui::AsyncApp,
) -> Result<Self, Error> {
if encrypted {
let UploadedFileParts { file, local } = upload_encrypted(server, picked, cx).await?;
Ok(Self::File(Box::new(UploadedFile { file, local })))
} else {
state::upload_file(server, picked, cx).await.map(Self::Url)
}
}
}
/// The pieces of an encrypted upload, split so the local handle survives the
/// picked file being consumed by the upload
struct UploadedFileParts {
file: FileAttachment,
local: LocalFile,
}
async fn upload_encrypted(
server: Url,
picked: PickedFile,
cx: &gpui::AsyncApp,
) -> Result<UploadedFileParts, Error> {
let local = picked.local.clone();
state::upload_encrypted_file(server, picked, cx)
.await
.map(|file| UploadedFileParts { file, local })
}
+45 -57
View File
@@ -1,5 +1,4 @@
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, LazyLock, RwLock};
pub use actions::*;
@@ -10,10 +9,9 @@ use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
Focusable, InteractiveElement, IntoElement, ListAlignment, ListOffset, ListState, MouseButton,
ObjectFit, ParentElement, PathPromptOptions, Render, SharedString, SharedUri,
StatefulInteractiveElement, Styled, StyledImage, Subscription, SystemNotification,
SystemNotificationAction, Task, WeakEntity, Window, div, img, list, px, red, relative,
retain_all, svg, white,
ObjectFit, ParentElement, Render, SharedString, SharedUri, StatefulInteractiveElement, Styled,
StyledImage, Subscription, SystemNotification, SystemNotificationAction, Task, WeakEntity,
Window, div, img, list, px, red, relative, retain_all, svg, white,
};
use gpui_kit::base::StyledExt as _;
use gpui_kit::component::button::{Button, ButtonVariants};
@@ -31,7 +29,7 @@ use regex::Regex;
use settings::{AppSettings, SignerKind};
use smallvec::{SmallVec, smallvec};
use state::{
FileAttachment, NostrRegistry, download_and_decrypt_to_file, upload, upload_encrypted,
FileAttachment, LocalFile, NostrRegistry, PickedFile, download_and_decrypt_file, pick_file,
};
use ui::{
Avatar, COMPACT_REACTION_EMOJIS, IconName, MessageActions, MessageMedia, MessageRow,
@@ -642,22 +640,17 @@ impl ChatPanel {
// Encrypt attachments which are not part of a message being written
let encrypted = self.input.read(cx).value().trim().is_empty();
// Ask user for file upload
let path = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
// Ask the user for a file to upload
let picker = pick_file(cx);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
// Selecting no file means the prompt was cancelled
let Some(path) = path.await??.and_then(|mut paths| paths.pop()) else {
let Some(picked) = picker.await? else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.upload_file(server, path, encrypted, window, cx);
this.upload_file(server, picked, encrypted, window, cx);
})?;
Ok(())
@@ -668,7 +661,7 @@ impl ChatPanel {
fn upload_file(
&mut self,
server: Url,
path: PathBuf,
picked: PickedFile,
encrypted: bool,
window: &mut Window,
cx: &mut Context<Self>,
@@ -676,25 +669,18 @@ impl ChatPanel {
self.set_uploading(true, cx);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
let result = if encrypted {
upload_encrypted(server.clone(), path.clone(), cx)
.await
.map(|file| Uploaded::File(file, path.clone()))
} else {
upload(server.clone(), path.clone(), cx)
.await
.map(Uploaded::Url)
};
let result = Uploaded::from_pick(encrypted, server.clone(), picked, cx).await;
this.update_in(cx, |this, window, cx| {
this.set_uploading(false, cx);
match result {
Ok(Uploaded::Url(url)) => this.add_attachment(url, cx),
Ok(Uploaded::File(file, path)) => this.add_pending_file(file, path, cx),
Err(e) if encrypted => {
this.report_encrypted_upload_error(server, path, e, window, cx)
Ok(Uploaded::File(uploaded)) => {
let UploadedFile { file, local } = *uploaded;
this.add_pending_file(file, local, cx);
}
Err(e) if encrypted => this.report_encrypted_upload_error(e, window, cx),
Err(e) => {
window.push_notification(
Notification::error(e.to_string()).autohide(false),
@@ -711,8 +697,6 @@ impl ChatPanel {
/// Report a failed encrypted upload, offering to retry it without encryption
fn report_encrypted_upload_error(
&mut self,
server: Url,
path: PathBuf,
error: Error,
window: &mut Window,
cx: &mut Context<Self>,
@@ -724,14 +708,12 @@ impl ChatPanel {
.title("Encrypted upload failed")
.action(move |_this, _window, _cx| {
let view = view.clone();
let server = server.clone();
let path = path.clone();
Button::new("retry-without-encryption")
.label("Upload without encryption")
.label("Pick the file again without encryption")
.on_click(move |_ev, window, cx| {
view.update(cx, |this, cx| {
this.upload_file(server.clone(), path.clone(), false, window, cx);
this.upload(window, cx);
})
.ok();
})
@@ -761,9 +743,9 @@ impl ChatPanel {
});
}
fn add_pending_file(&mut self, file: FileAttachment, path: PathBuf, cx: &mut Context<Self>) {
fn add_pending_file(&mut self, file: FileAttachment, local: LocalFile, cx: &mut Context<Self>) {
self.encrypted_attachments.update(cx, |this, cx| {
this.push(PendingFile { file, path });
this.push(PendingFile { file, local });
cx.notify();
});
}
@@ -782,12 +764,13 @@ impl ChatPanel {
self.decrypted_files.insert(id, DecryptedFile::Loading);
self.tasks.push(cx.spawn(async move |this, cx| {
let result = download_and_decrypt_to_file(&file, cx).await;
let result = download_and_decrypt_file(&file, cx).await;
this.update(cx, |this, cx| {
match result {
Ok(path) => {
this.decrypted_files.insert(id, DecryptedFile::Ready(path));
Ok(downloaded) => {
this.decrypted_files
.insert(id, DecryptedFile::Ready(downloaded.local));
}
Err(e) => {
this.decrypted_files
@@ -802,7 +785,7 @@ impl ChatPanel {
}));
}
/// Decrypt the attachment of a file message and open it with the OS
/// Decrypt the attachment of a file message and open it with the platform handler
fn open_file(
&mut self,
id: EventId,
@@ -810,25 +793,30 @@ impl ChatPanel {
window: &mut Window,
cx: &mut Context<Self>,
) {
match self.decrypted_files.get(&id) {
Some(DecryptedFile::Ready(path)) => {
cx.open_url(&file_url(path));
return;
}
Some(DecryptedFile::Loading) => return,
_ => {}
};
if let Some(DecryptedFile::Ready(local)) = self.decrypted_files.get(&id) {
let _ = local.open(cx).map_err(|e| {
window.push_notification(Notification::error(e.to_string()).autohide(false), cx);
});
return;
}
if let Some(DecryptedFile::Loading) = self.decrypted_files.get(&id) {
return;
}
self.decrypted_files.insert(id, DecryptedFile::Loading);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
let result = download_and_decrypt_to_file(&file, cx).await;
let result = download_and_decrypt_file(&file, cx).await;
this.update_in(cx, |this, _window, cx| {
this.update_in(cx, |this, window, cx| {
match result {
Ok(path) => {
cx.open_url(&file_url(&path));
this.decrypted_files.insert(id, DecryptedFile::Ready(path));
Ok(downloaded) => {
if let Err(e) = downloaded.open(cx) {
window.push_notification(Notification::error(e.to_string()), cx);
}
this.decrypted_files
.insert(id, DecryptedFile::Ready(downloaded.local));
}
Err(e) => {
this.decrypted_files
@@ -1475,16 +1463,16 @@ impl ChatPanel {
) -> AnyElement {
let state = self.decrypted_files.get(id);
if let Some(path) = state
if let Some(local) = state
.and_then(|state| match state {
DecryptedFile::Ready(path) => Some(path),
DecryptedFile::Ready(local) => Some(local),
_ => None,
})
.filter(|_| file.is_image())
{
return div()
.child(
img(path.clone())
img(local.image_source())
.border_1()
.border_color(cx.theme().border)
.h(px(250.))
@@ -1560,7 +1548,7 @@ impl ChatPanel {
.map(|this| {
if file.is_image() {
this.child(
img(pending.path.clone())
img(pending.local.image_source())
.size_16()
.when(cx.theme().shadow, |this| this.shadow_sm())
.rounded(cx.theme().radius)
+4
View File
@@ -16,3 +16,7 @@ futures.workspace = true
dirs = "5.0"
regex = "1.10"
anyhow.workspace = true
[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3", features = ["Window", "Storage"] }
+10 -7
View File
@@ -1,13 +1,16 @@
pub use debounced_delay::*;
pub use display::*;
pub use event::*;
pub use media_extractor::*;
pub use parser::*;
pub use paths::*;
mod debounced_delay;
mod display;
mod event;
mod media_extractor;
mod parser;
mod paths;
#[cfg(target_arch = "wasm32")]
pub mod web_store;
pub use debounced_delay::*;
pub use display::*;
pub use event::*;
pub use media_extractor::*;
pub use parser::*;
pub use paths::*;
+32
View File
@@ -0,0 +1,32 @@
use anyhow::{Error, anyhow};
const LOCAL_STORAGE: &str = "localStorage";
fn storage() -> Result<web_sys::Storage, Error> {
web_sys::window()
.ok_or_else(|| anyhow!("no browser window"))?
.local_storage()
.map_err(|e| anyhow!("{LOCAL_STORAGE} unavailable: {e:?}"))?
.ok_or_else(|| anyhow!("{LOCAL_STORAGE} unavailable"))
}
/// Read a value previously written with [`set`]
pub fn get(key: &str) -> Result<Option<String>, Error> {
storage()?
.get_item(key)
.map_err(|e| anyhow!("{LOCAL_STORAGE} read failed: {e:?}"))
}
/// Write a value, replacing any previous one
pub fn set(key: &str, value: &str) -> Result<(), Error> {
storage()?
.set_item(key, value)
.map_err(|e| anyhow!("{LOCAL_STORAGE} write failed: {e:?}"))
}
/// Remove a value if it exists
pub fn remove(key: &str) -> Result<(), Error> {
storage()?
.remove_item(key)
.map_err(|e| anyhow!("{LOCAL_STORAGE} delete failed: {e:?}"))
}
+6 -12
View File
@@ -4,9 +4,8 @@ use anyhow::Result;
use gpui::prelude::FluentBuilder;
use gpui::{
Action, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
FollowMode, IntoElement, ListAlignment, ListScrollEvent, ListState, ParentElement,
PathPromptOptions, Render, SharedString, Styled, Subscription, Task, WeakEntity, Window, div,
list, px,
FollowMode, IntoElement, ListAlignment, ListScrollEvent, ListState, ParentElement, Render,
SharedString, Styled, Subscription, Task, WeakEntity, Window, div, list, px,
};
use gpui_kit::assets::IconName;
use gpui_kit::base::StyledExt as _;
@@ -23,7 +22,7 @@ use person::Directory;
use serde::Deserialize;
use settings::AppSettings;
use smallvec::{SmallVec, smallvec};
use state::{NostrRegistry, upload};
use state::{NostrRegistry, pick_file, upload_file};
use ui::{Avatar, RenderedText, WelcomeMessage, rendered_text};
use util::{attachment_name, display_name, opens_run, pin_label, report};
@@ -553,22 +552,17 @@ impl GroupPanel {
fn upload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let server = AppSettings::get_file_server(cx);
let path = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
let picker = pick_file(cx);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
// Selecting no file means the prompt was cancelled
let Some(path) = path.await??.and_then(|mut paths| paths.pop()) else {
let Some(picked) = picker.await? else {
return Ok(());
};
this.update(cx, |this, cx| this.set_uploading(true, cx))?;
match upload(server, path, cx).await {
match upload_file(server, picked, cx).await {
Ok(url) => {
this.update_in(cx, |this, _window, cx| {
this.attachments.push(url);
+26 -14
View File
@@ -18,7 +18,7 @@ use nostr_sdk::prelude::*;
use person::Directory;
use settings::AppSettings;
use smallvec::{SmallVec, smallvec};
use state::{Announcement, CLIENT_NAME, NostrRegistry, UniversalSigner};
use state::{Announcement, NostrRegistry, UniversalSigner, credentials};
use ui::Avatar;
const IDENTIFIER: &str = "coop:device";
@@ -221,25 +221,38 @@ impl DeviceRegistry {
cx.emit(DeviceEvent::Set);
}
/// Backup the encryption's secret key to a file
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
/// Backup the encryption's secret key, returning the `nsec1...` content
pub fn backup_bytes(&self, cx: &App) -> Task<Result<String, Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
cx.background_spawn(async move {
let keys = get_keys(&client, &signer).await?;
let content = keys.secret_key().to_bech32()?;
Ok(keys.secret_key().to_bech32()?)
})
}
if cfg!(target_arch = "wasm32") {
return Err(anyhow!("Not supported"));
}
/// Backup the encryption's secret key to a file
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
let backup = self.backup_bytes(cx);
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(target_arch = "wasm32"))]
return cx.background_spawn(async move {
let content = backup.await?;
smol::fs::write(path, &content).await?;
Ok(())
})
});
#[cfg(target_arch = "wasm32")]
{
let _ = path;
cx.background_spawn(async move {
backup.await?;
Err(anyhow!("File backups are not supported on web; copy the key from the backup panel instead."))
})
}
}
/// Get device announcement for current user
@@ -827,10 +840,10 @@ fn authorization_code(public_key: &PublicKey) -> SharedString {
/// Get or create new app keys (async, returns a task)
fn get_or_init_app_keys(cx: &App) -> Task<Result<Keys, Error>> {
let read = cx.read_credentials(CLIENT_NAME);
let read = credentials::read_app_keys(cx);
cx.spawn(async move |cx| {
if let Ok(Some((_, secret))) = read.await
if let Ok(Some(secret)) = read.await
&& let Ok(keys) = SecretKey::from_slice(&secret).map(Keys::new)
{
return Ok(keys);
@@ -838,14 +851,13 @@ fn get_or_init_app_keys(cx: &App) -> Task<Result<Keys, Error>> {
// No stored keys found or invalid — generate new ones
let keys = Keys::generate();
let user = keys.public_key().to_hex();
let secret = keys.secret_key().to_secret_bytes();
cx.update(|cx| {
let write = cx.write_credentials(CLIENT_NAME, &user, &secret);
let write = credentials::write_app_keys(cx, &secret);
cx.background_spawn(async move {
if let Err(e) = write.await {
log::error!("Keyring not available or panic: {e}")
log::error!("Failed to persist app keys: {e}")
}
})
.detach();
+1
View File
@@ -8,6 +8,7 @@ publish.workspace = true
common = { path = "../common" }
state = { path = "../state" }
futures.workspace = true
gpui.workspace = true
nostr-sdk.workspace = true
instant.workspace = true
+35 -16
View File
@@ -3,7 +3,10 @@ use std::sync::RwLock;
use anyhow::{Error, anyhow};
use common::emojis_from_tags;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Subscription, Task};
use futures::{FutureExt, pin_mut};
use gpui::{
App, AppContext, BackgroundExecutor, Context, Entity, EventEmitter, Global, Subscription, Task,
};
use instant::Duration;
use nostr_sdk::prelude::*;
use smallvec::{SmallVec, smallvec};
@@ -98,8 +101,9 @@ impl PersonRegistry {
}));
let client3 = client.clone();
let executor = cx.background_executor().clone();
tasks.push(cx.background_spawn(async move {
Self::handle_requests(&client3, &metadata_rx).await;
Self::handle_requests(&client3, &metadata_rx, executor).await;
}));
tasks.push(cx.spawn(async move |this, cx| {
@@ -193,30 +197,45 @@ impl PersonRegistry {
}
/// Handle request for metadata
async fn handle_requests(client: &Client, rx: &flume::Receiver<PublicKey>) {
async fn handle_requests(
client: &Client,
rx: &flume::Receiver<PublicKey>,
executor: BackgroundExecutor,
) {
let mut batch: HashSet<PublicKey> = HashSet::new();
loop {
match flume::Selector::new()
.recv(rx, |result| result.ok())
.wait_timeout(Duration::from_secs(TIMEOUT))
{
Ok(Some(public_key)) => {
batch.insert(public_key);
// Process the batch if it's full
if batch.len() >= 20
&& let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await
{
log::warn!("Failed to get metadata batch: {e}");
let timer = executor.timer(Duration::from_secs(TIMEOUT)).fuse();
pin_mut!(timer);
let request = futures::select! {
result = rx.recv_async().fuse() => match result {
Ok(public_key) => public_key,
Err(_) => {
if !batch.is_empty()
&& let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await
{
log::warn!("Failed to get metadata batch: {e}");
}
return;
}
}
_ => {
},
() = timer => {
if !batch.is_empty()
&& let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await
{
log::warn!("Failed to get metadata batch: {e}");
}
continue;
}
};
batch.insert(request);
// Process the batch if it's full
if batch.len() >= 20
&& let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await
{
log::warn!("Failed to get metadata batch: {e}");
}
}
}
+32 -18
View File
@@ -1,12 +1,17 @@
use std::path::PathBuf;
use anyhow::{Error, anyhow};
#[cfg(not(target_arch = "wasm32"))]
use common::config_dir;
use gpui::{App, AppContext, Context, Entity, Global, ImageSource, Subscription, Task, px};
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use smallvec::{SmallVec, smallvec};
/// Browser storage key for the settings JSON
#[cfg(target_arch = "wasm32")]
const SETTINGS_KEY: &str = "coop.settings";
/// The user's appearance preference, persisted with the rest of the settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum AppearanceMode {
@@ -63,21 +68,21 @@ pub fn init(cx: &mut App) {
}
/// Read the persisted appearance mode synchronously.
///
/// The async load fills the global settings later; the native theme must be
/// applied before the first window opens, so boot reads the mode straight
/// from the settings file instead.
fn persisted_settings() -> Option<Settings> {
#[cfg(not(target_arch = "wasm32"))]
{
let path = config_dir().join(".settings");
if let Ok(content) = std::fs::read_to_string(path)
&& let Ok(settings) = serde_json::from_str::<Settings>(&content)
{
return Some(settings);
}
}
None
let content = persisted_content();
content.and_then(|content| serde_json::from_str(&content).ok())
}
/// The persisted settings JSON, from the config file or browser storage
#[cfg(not(target_arch = "wasm32"))]
fn persisted_content() -> Option<String> {
let path = config_dir().join(".settings");
std::fs::read_to_string(path).ok()
}
#[cfg(target_arch = "wasm32")]
fn persisted_content() -> Option<String> {
common::web_store::get(SETTINGS_KEY).ok().flatten()
}
pub fn persisted_appearance_mode() -> AppearanceMode {
@@ -87,10 +92,6 @@ pub fn persisted_appearance_mode() -> AppearanceMode {
}
/// Read the persisted theme tuning synchronously.
///
/// Like [`persisted_appearance_mode`], the native theme is applied before the
/// async settings load completes, so boot reads the tuning straight from the
/// settings file instead.
pub fn persisted_theme() -> ThemeSettings {
persisted_settings()
.map(|settings| settings.theme)
@@ -357,6 +358,14 @@ impl AppSettings {
return Ok(serde_json::from_str(&content)?);
}
}
#[cfg(target_arch = "wasm32")]
{
if let Some(content) = common::web_store::get(SETTINGS_KEY)? {
return Ok(serde_json::from_str(&content)?);
}
}
Err(anyhow!("Not found"))
});
@@ -389,6 +398,11 @@ impl AppSettings {
smol::fs::write(&path, content).await.ok();
})
.detach();
#[cfg(target_arch = "wasm32")]
if let Err(e) = common::web_store::set(SETTINGS_KEY, &content) {
log::warn!("failed to persist settings: {e}");
}
}
}
+18
View File
@@ -20,6 +20,7 @@ futures.workspace = true
anyhow.workspace = true
webbrowser.workspace = true
serde_json.workspace = true
log.workspace = true
mime_guess = "2.0.4"
@@ -28,7 +29,24 @@ sha2.workspace = true
data-encoding.workspace = true
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3"
nostr-browser-signer.workspace = true
nostr-memory.workspace = true
nostr-sqlite.workspace = true
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = [
"Blob",
"BlobPropertyBag",
"File",
"FileList",
"HtmlAnchorElement",
"HtmlInputElement",
"Url",
"Window",
] }
sqlite-wasm-rs = "0.5"
sqlite-wasm-vfs = "0.2"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
browser-signer-proxy = { path = "../browser-signer-proxy" }
+21 -18
View File
@@ -1,17 +1,10 @@
use std::path::PathBuf;
use anyhow::{Error, anyhow};
use gpui::AsyncApp;
#[cfg(not(target_arch = "wasm32"))]
use gpui_tokio::Tokio;
#[cfg(not(target_arch = "wasm32"))]
use mime_guess::from_path;
use nostr_blossom::prelude::*;
use nostr_sdk::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use crate::file::sha256_hex;
/// Upload a blob to a blossom server and return its URL
#[cfg(not(target_arch = "wasm32"))]
pub(crate) async fn upload_blob(
@@ -41,16 +34,26 @@ pub(crate) async fn upload_blob(
.map_err(|e| anyhow!("Upload error: {e}"))?
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn upload(server: Url, path: PathBuf, cx: &AsyncApp) -> Result<Url, Error> {
let content_type = from_path(&path).first_or_octet_stream().to_string();
let data = smol::fs::read(&path).await?;
let sha256 = sha256_hex(&data);
upload_blob(&server, data, &content_type, &sha256, cx).await
}
/// Upload a blob to a blossom server and return its URL.
#[cfg(target_arch = "wasm32")]
pub async fn upload(_server: Url, _path: PathBuf, _cx: &AsyncApp) -> Result<Url, Error> {
Err(anyhow!("File upload not supported on web"))
pub(crate) async fn upload_blob(
server: &Url,
data: Vec<u8>,
content_type: &str,
sha256: &str,
_cx: &AsyncApp,
) -> Result<Url, Error> {
let client = BlossomClient::new(server.clone());
let keys = Keys::generate();
let base = server.clone();
let hash = sha256.to_string();
match client
.upload_blob(data, Some(content_type.to_string()), None, Some(&keys))
.await
{
Ok(blob) => Ok(blob.url),
Err(e) if e.to_string().contains("201 Created") => Ok(base.join(&hash)?),
Err(e) => Err(anyhow!(e.to_string())),
}
}
+105
View File
@@ -0,0 +1,105 @@
use anyhow::Result;
#[cfg(target_arch = "wasm32")]
use common::web_store;
use gpui::{App, AppContext as _, Task};
use crate::USER_KEYRING;
/// The storage key for the NIP-4e app keys
const APP_KEYS_KEY: &str = "coop/nip4e/app-keys";
/// Read the stored credential as `(username, secret)`
#[allow(clippy::type_complexity)]
pub(crate) fn read(cx: &App) -> Task<Result<Option<(String, Vec<u8>)>>> {
#[cfg(not(target_arch = "wasm32"))]
return cx.read_credentials(USER_KEYRING);
#[cfg(target_arch = "wasm32")]
{
let _ = cx;
Task::ready(
web_store::get(USER_KEYRING)
.map(|stored| stored.map(|content| (String::new(), content.into_bytes()))),
)
}
}
/// Write the stored credential
pub(crate) fn write(cx: &App, username: &str, secret: &[u8]) -> Task<Result<()>> {
#[cfg(not(target_arch = "wasm32"))]
return cx.write_credentials(USER_KEYRING, username, secret);
#[cfg(target_arch = "wasm32")]
{
let _ = (cx, username);
let content = match std::str::from_utf8(secret) {
Ok(content) => content,
Err(e) => return Task::ready(Err(anyhow::anyhow!("credential is not UTF-8: {e}"))),
};
Task::ready(web_store::set(USER_KEYRING, content))
}
}
/// Delete the stored credential
pub(crate) fn delete(cx: &App) -> Task<Result<()>> {
#[cfg(not(target_arch = "wasm32"))]
return cx.delete_credentials(USER_KEYRING);
#[cfg(target_arch = "wasm32")]
{
let _ = cx;
Task::ready(web_store::remove(USER_KEYRING))
}
}
/// Read named bytes from the platform keyring,
/// falling back to browser storage on web where no keyring exists
fn read_named(cx: &App, key: &str) -> Task<Result<Option<Vec<u8>>>> {
#[cfg(not(target_arch = "wasm32"))]
{
let key = key.to_owned();
let read = cx.read_credentials(&key);
cx.background_spawn(async move { Ok(read.await?.map(|(_, secret)| secret)) })
}
#[cfg(target_arch = "wasm32")]
{
let _ = cx;
let stored = web_store::get(key).map(|content| content.map(|s| s.into_bytes()));
Task::ready(stored)
}
}
/// Write named bytes to the platform keyring,
/// falling back to browser storage on web where no keyring exists
fn write_named(cx: &App, key: &str, secret: &[u8]) -> Task<Result<()>> {
#[cfg(not(target_arch = "wasm32"))]
{
let key = key.to_owned();
let secret = secret.to_vec();
let write = cx.write_credentials(&key, "", &secret);
cx.background_spawn(write)
}
#[cfg(target_arch = "wasm32")]
{
let _ = cx;
let content = match std::str::from_utf8(secret) {
Ok(content) => content,
Err(e) => return Task::ready(Err(anyhow::anyhow!("secret is not UTF-8: {e}"))),
};
Task::ready(web_store::set(key, content))
}
}
/// Load the NIP-4e app keys from storage, as raw secret bytes
pub fn read_app_keys(cx: &App) -> Task<Result<Option<Vec<u8>>>> {
read_named(cx, APP_KEYS_KEY)
}
/// Persist the NIP-4e app keys, as raw secret bytes
pub fn write_app_keys(cx: &App, secret: &[u8]) -> Task<Result<()>> {
write_named(cx, APP_KEYS_KEY, secret)
}
+204 -62
View File
@@ -7,8 +7,10 @@ use aes_gcm::{Aes256Gcm, AesGcm, Nonce};
use anyhow::{Error, anyhow, bail};
use data_encoding::HEXLOWER;
use futures::AsyncReadExt;
#[cfg(not(target_arch = "wasm32"))]
use gpui::PathPromptOptions;
use gpui::http_client::AsyncBody;
use gpui::{AsyncApp, SharedString};
use gpui::{AppContext as _, AsyncApp, SharedString, SharedUri, Task};
#[cfg(not(target_arch = "wasm32"))]
use mime_guess::from_path;
use nostr::nips::nip94::Sha256Hash;
@@ -115,6 +117,56 @@ impl FileAttachment {
}
}
/// A file the user picked, read into memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PickedFile {
pub name: String,
pub mime: String,
pub data: Vec<u8>,
pub local: LocalFile,
}
/// A handle to a file stored on the user's device
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LocalFile {
/// A path on disk (desktop)
Path(PathBuf),
/// An in-memory blob URL (web)
Url(String),
}
impl LocalFile {
/// The source an `img` element can render
pub fn image_source(&self) -> gpui::ImageSource {
match self {
LocalFile::Path(path) => path.clone().into(),
LocalFile::Url(url) => SharedUri::from(url.clone()).into(),
}
}
/// The URL the platform opener understands
pub fn open_url(&self) -> String {
match self {
LocalFile::Path(path) => format!("file://{}", path.display()),
LocalFile::Url(url) => url.clone(),
}
}
/// Open the file with the platform handler
pub fn open(&self, cx: &gpui::App) -> Result<(), Error> {
match self {
LocalFile::Path(_) => {
cx.open_url(&self.open_url());
Ok(())
}
#[cfg(target_arch = "wasm32")]
LocalFile::Url(url) => crate::web_file::open_url(url),
#[cfg(not(target_arch = "wasm32"))]
LocalFile::Url(_) => Ok(()),
}
}
}
pub(crate) fn encrypt(data: &[u8]) -> Result<EncryptedFile, Error> {
let key = Aes256Gcm::generate_key(OsRng);
let nonce = AesGcm::<Aes256, U16>::generate_nonce(OsRng);
@@ -165,21 +217,63 @@ pub(crate) fn sha256_hex(data: &[u8]) -> String {
Sha256Hash::from_byte_array(hash).to_hex()
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn upload_encrypted(
/// Ask the user for a single file and read it into memory
pub fn pick_file(cx: &gpui::App) -> Task<Result<Option<PickedFile>, Error>> {
#[cfg(not(target_arch = "wasm32"))]
{
let dialog = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
cx.background_spawn(async move {
let Some(path) = dialog.await?? else {
return Ok(None);
};
let path = path.into_iter().next().ok_or_else(|| anyhow!("No file"))?;
let mime = from_path(&path).first_or_octet_stream().to_string();
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
let data = smol::fs::read(&path).await?;
Ok(Some(PickedFile {
name,
mime,
data,
local: LocalFile::Path(path),
}))
})
}
#[cfg(target_arch = "wasm32")]
{
let _ = cx;
cx.background_spawn(async move { crate::web_file::pick_file().await })
}
}
/// Upload a file unencrypted and return its URL
pub async fn upload_file(server: Url, file: PickedFile, cx: &AsyncApp) -> Result<Url, Error> {
let PickedFile { mime, data, .. } = file;
let sha256 = sha256_hex(&data);
crate::blossom::upload_blob(&server, data, &mime, &sha256, cx).await
}
/// Upload a file encrypted as an opaque blob, returning the attachment metadata
pub async fn upload_encrypted_file(
server: Url,
path: PathBuf,
file: PickedFile,
cx: &AsyncApp,
) -> Result<FileAttachment, Error> {
let mime = from_path(&path).first_or_octet_stream().to_string();
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned());
let data = smol::fs::read(&path).await?;
let encrypted = encrypt(&data)?;
let encrypted = encrypt(&file.data)?;
let sha256 = sha256_hex(&encrypted.data);
let original_sha256 = sha256_hex(&data);
let original_sha256 = sha256_hex(&file.data);
let size = encrypted.data.len() as u64;
let base_url = server.to_string();
@@ -207,26 +301,17 @@ pub async fn upload_encrypted(
Ok(FileAttachment {
url,
mime,
mime: file.mime,
key: encrypted.key,
nonce: encrypted.nonce,
sha256: Some(sha256),
original_sha256: Some(original_sha256),
size: Some(size),
dim: None,
name,
name: Some(file.name),
})
}
#[cfg(target_arch = "wasm32")]
pub async fn upload_encrypted(
_server: Url,
_path: PathBuf,
_cx: &AsyncApp,
) -> Result<FileAttachment, Error> {
Err(anyhow!("File upload not supported on web"))
}
pub(crate) async fn download_and_decrypt(
url: &Url,
key: &str,
@@ -261,33 +346,49 @@ pub(crate) async fn download_and_decrypt(
decrypt(&data, key, nonce)
}
/// Download and decrypt a file attachment into a temporary file.
///
/// The same attachment always maps to the same path, so callers can render the
/// result directly (e.g. with `img`) without downloading it more than once.
#[cfg(not(target_arch = "wasm32"))]
pub async fn download_and_decrypt_to_file(
file: &FileAttachment,
cx: &AsyncApp,
) -> Result<PathBuf, Error> {
let name = file
.sha256
.clone()
.unwrap_or_else(|| sha256_hex(file.url.as_str().as_bytes()));
/// A downloaded and decrypted attachment on the user's device
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DownloadedFile {
pub local: LocalFile,
pub mime: String,
pub name: String,
/// The decrypted bytes, kept so the web can offer them as a download
#[cfg(target_arch = "wasm32")]
pub(crate) data: Vec<u8>,
}
let extension = mime_guess::get_mime_extensions_str(&file.mime)
.and_then(|extensions| extensions.first())
.copied()
.unwrap_or("bin");
let path = std::env::temp_dir()
.join("coop-files")
.join(format!("{name}.{extension}"));
if smol::fs::metadata(&path).await.is_ok() {
return Ok(path);
impl DownloadedFile {
pub fn open(&self, cx: &gpui::App) -> Result<(), Error> {
match &self.local {
LocalFile::Path(path) => {
cx.open_with_system(path);
Ok(())
}
#[cfg(target_arch = "wasm32")]
LocalFile::Url(url) => {
if self.mime.starts_with("image/") {
crate::web_file::open_url(url)
} else {
crate::web_file::download(&self.name, &self.mime, &self.data)
}
}
#[cfg(not(target_arch = "wasm32"))]
LocalFile::Url(_) => Ok(()),
}
}
/// Save the file to the user's downloads (web)
#[cfg(target_arch = "wasm32")]
pub fn save(&self) -> Result<(), Error> {
crate::web_file::download(&self.name, &self.mime, &self.data)
}
}
/// Download and decrypt a file attachment to the user's device
pub async fn download_and_decrypt_file(
file: &FileAttachment,
cx: &AsyncApp,
) -> Result<DownloadedFile, Error> {
let data = download_and_decrypt(
&file.url,
&file.key,
@@ -297,25 +398,66 @@ pub async fn download_and_decrypt_to_file(
)
.await?;
let Some(parent) = path.parent() else {
bail!("Invalid file path");
};
smol::fs::create_dir_all(parent).await?;
let name = file
.name
.clone()
.unwrap_or_else(|| fallback_name(&file.url));
// Write under a temporary name first, so an interrupted download is never reused
let partial = path.with_extension("download");
smol::fs::write(&partial, data).await?;
smol::fs::rename(&partial, &path).await?;
let local = store_file(&name, &file.mime, &data).await?;
Ok(path)
Ok(DownloadedFile {
local,
mime: file.mime.clone(),
name,
#[cfg(target_arch = "wasm32")]
data,
})
}
#[cfg(target_arch = "wasm32")]
pub async fn download_and_decrypt_to_file(
_file: &FileAttachment,
_cx: &AsyncApp,
) -> Result<PathBuf, Error> {
Err(anyhow!("File download not supported on web"))
/// Persist decrypted bytes somewhere the platform can render or open them
async fn store_file(name: &str, mime: &str, data: &[u8]) -> Result<LocalFile, Error> {
#[cfg(not(target_arch = "wasm32"))]
{
let digest = sha256_hex(name.as_bytes());
let extension = mime_guess::get_mime_extensions_str(mime)
.and_then(|extensions| extensions.first())
.copied()
.unwrap_or("bin");
let path = std::env::temp_dir()
.join("coop-files")
.join(format!("{digest}.{extension}"));
if smol::fs::metadata(&path).await.is_err() {
let Some(parent) = path.parent() else {
bail!("Invalid file path");
};
smol::fs::create_dir_all(parent).await?;
// Write under a temporary name first, so an interrupted download is never reused
let partial = path.with_extension("download");
smol::fs::write(&partial, data).await?;
smol::fs::rename(&partial, &path).await?;
}
Ok(LocalFile::Path(path))
}
#[cfg(target_arch = "wasm32")]
{
let _ = name;
let url = crate::web_file::blob_url(mime, data)?;
Ok(LocalFile::Url(url))
}
}
/// A file name derived from the attachment URL's last path segment
fn fallback_name(url: &Url) -> String {
url.path()
.rsplit('/')
.find(|segment| !segment.is_empty())
.unwrap_or("attachment")
.to_string()
}
fn tag_value<'a>(tags: &'a Tags, name: &str) -> Option<&'a str> {
+63 -18
View File
@@ -4,26 +4,33 @@ use std::sync::Arc;
use anyhow::{Error, anyhow};
#[cfg(not(target_arch = "wasm32"))]
use browser_signer_proxy::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use common::config_dir;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task, TaskExt};
#[cfg(not(target_arch = "wasm32"))]
use gpui_tokio::Tokio;
use instant::Duration;
#[cfg(target_arch = "wasm32")]
use nostr_browser_signer::BrowserSigner;
use nostr_connect::prelude::*;
use nostr_gossip_memory::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use nostr_lmdb::prelude::*;
#[cfg(target_arch = "wasm32")]
use nostr_memory::prelude::*;
use nostr_sdk::prelude::*;
mod blossom;
mod constants;
pub mod credentials;
mod file;
mod nip05;
mod nip4e;
mod signer;
pub use blossom::*;
#[cfg(target_arch = "wasm32")]
pub mod web_database;
#[cfg(target_arch = "wasm32")]
pub mod web_file;
pub use constants::*;
pub use file::*;
pub use nip4e::*;
@@ -107,7 +114,6 @@ impl NostrRegistry {
let signer = UniversalSigner::new(Keys::generate());
let authenticator = SignerAuthenticator::new(signer.clone());
// Construct the nostr lmdb instance
#[cfg(not(target_arch = "wasm32"))]
let database = cx.foreground_executor().block_on(async move {
NostrLmdb::open(config_dir().join("nostr"))
@@ -116,7 +122,7 @@ impl NostrRegistry {
});
#[cfg(target_arch = "wasm32")]
let database = MemoryDatabase::unbounded();
let database = web_database::take();
// Construct the nostr client
let client = ClientBuilder::default()
@@ -137,9 +143,7 @@ impl NostrRegistry {
let _ = entity.update(cx, |this, cx| {
this.connect_bootstrap_relays(cx);
if cfg!(target_arch = "wasm32") {
cx.emit(StateEvent::NoSigner);
} else if let Some(secret) = cli_key {
if let Some(secret) = cli_key {
// Use CLI-provided key -- same path as restore_session
let keys = Keys::new(secret);
this.set_signer(keys, cx);
@@ -241,7 +245,7 @@ impl NostrRegistry {
/// Restore the signer from the stored credential
fn restore_session(&mut self, cx: &mut Context<Self>) {
let user_keyring = cx.read_credentials(USER_KEYRING);
let user_keyring = credentials::read(cx);
self.tasks.push(cx.spawn(async move |this, cx| {
let result = async {
@@ -278,6 +282,11 @@ impl NostrRegistry {
this.update(cx, |this, cx| {
this.connect_proxy(cx);
})?;
} else if content == "extension" {
#[cfg(target_arch = "wasm32")]
this.update(cx, |this, cx| {
this.connect_extension(cx);
})?;
} else {
this.update(cx, |_, cx| {
cx.emit(StateEvent::NoSigner);
@@ -313,7 +322,7 @@ impl NostrRegistry {
cx: &mut Context<Self>,
) -> Task<Result<PublicKey, Error>> {
let password = password.to_owned();
let user_keyring = cx.read_credentials(USER_KEYRING);
let user_keyring = credentials::read(cx);
cx.spawn(async move |this, cx| {
let content = user_keyring
@@ -372,9 +381,8 @@ impl NostrRegistry {
let (keys, ncryptsec) = job.await?;
let public_key = keys.public_key();
let write = cx.update(|cx| {
cx.write_credentials(USER_KEYRING, &public_key.to_hex(), ncryptsec.as_bytes())
});
let write =
cx.update(|cx| credentials::write(cx, &public_key.to_hex(), ncryptsec.as_bytes()));
write.await?;
this.update(cx, |this, cx| {
@@ -411,9 +419,8 @@ impl NostrRegistry {
let keys = decrypt_task.await?;
let public_key = keys.public_key();
let write = cx.update(|cx| {
cx.write_credentials(USER_KEYRING, &public_key.to_hex(), stored.as_bytes())
});
let write =
cx.update(|cx| credentials::write(cx, &public_key.to_hex(), stored.as_bytes()));
write.await?;
this.update(cx, |this, cx| {
@@ -439,7 +446,7 @@ impl NostrRegistry {
let keys = Keys::generate();
let credential = with_master_key(&uri_string, &keys);
let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes());
let write = credentials::write(cx, "bunker", credential.as_bytes());
cx.spawn(async move |this, cx| {
let signer = NostrConnect::builder(connect_uri, keys)
@@ -463,12 +470,50 @@ impl NostrRegistry {
self.current_user = None;
self.passphrase_required = false;
cx.delete_credentials(USER_KEYRING).detach_and_log_err(cx);
credentials::delete(cx).detach_and_log_err(cx);
cx.emit(StateEvent::SignerChanged);
cx.emit(StateEvent::NoSigner);
cx.notify();
}
/// Connect the browser extension signer (NIP-07).
#[cfg(target_arch = "wasm32")]
pub fn connect_extension(&mut self, cx: &mut Context<Self>) {
let signer = match BrowserSigner::new() {
Ok(signer) => signer,
Err(e) => {
cx.emit(StateEvent::error(format!("No Nostr extension found: {e}.")));
cx.emit(StateEvent::NoSigner);
return;
}
};
self.tasks.push(cx.spawn(async move |this, cx| {
match signer.get_public_key_async().await {
Ok(public_key) => {
this.update(cx, |this, cx| {
credentials::write(cx, "extension", b"extension").detach_and_log_err(cx);
this.signer.swap_inner(signer);
this.current_user = Some(public_key);
this.passphrase_required = false;
cx.emit(StateEvent::SignerChanged);
cx.notify();
})?;
}
Err(e) => {
this.update(cx, |_, cx| {
credentials::delete(cx).detach_and_log_err(cx);
cx.emit(StateEvent::error(e.to_string()));
cx.emit(StateEvent::NoSigner);
})?;
}
};
Ok(())
}));
}
/// Start the browser proxy
#[cfg(not(target_arch = "wasm32"))]
pub fn connect_proxy(&mut self, cx: &mut Context<Self>) {
+6
View File
@@ -188,7 +188,13 @@ impl AuthUrlHandler for CoopAuthUrlHandler {
auth_url: Url,
) -> Pin<Box<dyn Future<Output = Result<(), nostr_connect::error::Error>> + Send + '_>> {
Box::pin(async move {
#[cfg(not(target_arch = "wasm32"))]
webbrowser::open(auth_url.as_str()).map_err(nostr_connect::error::Error::other)?;
#[cfg(target_arch = "wasm32")]
crate::web_file::open_url(auth_url.as_str())
.map_err(nostr_connect::error::Error::other)?;
Ok(())
})
}
+62
View File
@@ -0,0 +1,62 @@
use std::cell::RefCell;
use std::sync::Arc;
use nostr_memory::prelude::*;
use nostr_sqlite::prelude::NostrSqlite;
use sqlite_wasm_rs::WasmOsCallback;
use sqlite_wasm_vfs::relaxed_idb;
const DATABASE_PATH: &str = "coop.sqlite3";
const VFS_NAME: &str = "coop-relaxed-idb";
thread_local! {
static DATABASE: RefCell<Option<NostrSqlite>> = const { RefCell::new(None) };
}
/// Install the IndexedDB storage backend and open the database.
pub async fn open() {
match open_persistent().await {
Some(database) => DATABASE.with(|slot| *slot.borrow_mut() = Some(database)),
None => log::error!("Falling back to the in-memory nostr database"),
}
}
/// Hand the opened database to the client constructor
pub(crate) fn take() -> Arc<dyn NostrDatabase> {
let database = DATABASE.with(|slot| slot.borrow_mut().take());
match database {
Some(database) => Arc::new(database),
None => {
log::error!("Persistent web database was not opened, falling back to memory");
Arc::new(MemoryDatabase::unbounded())
}
}
}
/// Open the database on IndexedDB storage, or `None` when unavailable
async fn open_persistent() -> Option<NostrSqlite> {
let options = relaxed_idb::RelaxedIdbCfgBuilder::new()
.vfs_name(VFS_NAME)
.build();
if let Err(e) = relaxed_idb::install::<WasmOsCallback>(&options, true).await {
log::warn!("IndexedDB storage unavailable: {e:?}");
return None;
}
match NostrSqlite::builder()
.persistent_with_vfs(DATABASE_PATH, VFS_NAME)
.build()
.await
{
Ok(database) => {
log::info!("Nostr database opened on IndexedDB storage");
Some(database)
}
Err(e) => {
log::error!("Failed to open the nostr database on IndexedDB: {e:?}");
None
}
}
}
+198
View File
@@ -0,0 +1,198 @@
//! Browser file interoperability: a persistent hidden `<input type="file">`
//! picker, blob URLs for rendering, and anchor-based downloads.
use std::cell::RefCell;
use anyhow::{Error, anyhow};
use flume::Sender;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
use web_sys::{File, HtmlAnchorElement, HtmlInputElement, Url as DomUrl, window as js_window};
use crate::file::PickedFile;
type PickResult = Result<Option<PickedFile>, Error>;
thread_local! {
/// The picker input lives for the whole page so its change closure does
/// not have to be leaked or re-registered on every pick
static PICKER: RefCell<Option<Picker>> = const { RefCell::new(None) };
/// The sender the active pick delivers through
static PENDING: RefCell<Option<Sender<PickResult>>> = const { RefCell::new(None) };
}
struct Picker {
input: HtmlInputElement,
/// Keep the change handler alive for the life of the page
_on_change: Closure<dyn FnMut()>,
}
/// Ask the user for a single file and read its bytes
pub async fn pick_file() -> PickResult {
let (sender, receiver) = flume::bounded(1);
PICKER.with(|picker| -> Result<(), Error> {
let mut picker = picker.borrow_mut();
if picker.is_none() {
*picker = Some(init_picker()?);
}
let picker = picker.as_ref().expect("picker just initialized");
PENDING.with(|pending| *pending.borrow_mut() = Some(sender));
picker.input.click();
Ok(())
})?;
receiver
.recv_async()
.await
.map_err(|_| anyhow!("File picker closed"))?
}
fn init_picker() -> Result<Picker, Error> {
let document = js_window()
.ok_or_else(|| anyhow!("no browser window"))?
.document()
.ok_or_else(|| anyhow!("no browser document"))?;
let input = document
.create_element("input")
.map_err(|e| anyhow!("failed to create file input: {e:?}"))?
.dyn_into::<HtmlInputElement>()
.map_err(|_| anyhow!("created element is not an input"))?;
input.set_type("file");
input.style().set_property("display", "none").ok();
let on_change = Closure::wrap(Box::new(move || {
let Some(sender) = PENDING.with(|pending| pending.borrow_mut().take()) else {
return;
};
wasm_bindgen_futures::spawn_local(async move {
sender.send_async(read_selected_file().await).await.ok();
});
}) as Box<dyn FnMut()>);
input.set_onchange(Some(on_change.as_ref().unchecked_ref()));
let body = document.body().ok_or_else(|| anyhow!("no browser body"))?;
body.append_child(&input)
.map_err(|e| anyhow!("failed to mount file input: {e:?}"))?;
Ok(Picker {
input,
_on_change: on_change,
})
}
/// Read the first file of the picker input, if one was chosen
async fn read_selected_file() -> PickResult {
let picker = PICKER
.with(|picker| picker.borrow().as_ref().map(|picker| picker.input.clone()))
.ok_or_else(|| anyhow!("file picker is not initialized"))?;
let Some(file) = picker.files().and_then(|files| files.get(0)) else {
// The dialog was dismissed without choosing a file
return Ok(None);
};
let mime = non_empty(file.type_());
let data = read_file_bytes(&file).await?;
let local = crate::file::LocalFile::Url(blob_url(&mime, &data)?);
Ok(Some(PickedFile {
name: file.name(),
mime,
data,
local,
}))
}
/// Read a browser `File` into memory
async fn read_file_bytes(file: &File) -> Result<Vec<u8>, Error> {
let promise = file.array_buffer();
let buffer = wasm_bindgen_futures::JsFuture::from(promise)
.await
.map_err(|e| anyhow!("failed to read file: {e:?}"))?;
Ok(js_sys::Uint8Array::new(&buffer).to_vec())
}
/// Create an object URL for bytes, so images and downloads render from memory
pub fn blob_url(mime: &str, data: &[u8]) -> Result<String, Error> {
let array = js_sys::Uint8Array::from(data);
let parts = js_sys::Array::new();
parts.push(&array);
let bag = web_sys::BlobPropertyBag::new();
bag.set_type(mime);
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts.into(), &bag)
.map_err(|e| anyhow!("failed to create blob: {e:?}"))?;
DomUrl::create_object_url_with_blob(&blob).map_err(|e| anyhow!("failed to create url: {e:?}"))
}
/// Offer bytes to the user as a browser download
pub fn download(name: &str, mime: &str, data: &[u8]) -> Result<(), Error> {
let window = js_window().ok_or_else(|| anyhow!("no browser window"))?;
let document = window
.document()
.ok_or_else(|| anyhow!("no browser document"))?;
let url = blob_url(mime, data)?;
let anchor: HtmlAnchorElement = document
.create_element("a")
.map_err(|e| anyhow!("failed to create download link: {e:?}"))?
.dyn_into()
.map_err(|_| anyhow!("created element is not an anchor"))?;
anchor.set_href(&url);
anchor.set_download(name);
anchor.style().set_property("display", "none").ok();
let body = document.body().ok_or_else(|| anyhow!("no browser body"))?;
body.append_child(&anchor)
.map_err(|e| anyhow!("failed to mount download link: {e:?}"))?;
anchor.click();
body.remove_child(&anchor)
.map_err(|e| anyhow!("failed to remove download link: {e:?}"))?;
// Keep the blob alive briefly so the download is not cancelled
let callback = Closure::wrap(Box::new(move || {
DomUrl::revoke_object_url(&url).ok();
}) as Box<dyn FnMut()>);
window
.set_timeout_with_callback_and_timeout_and_arguments_0(
callback.as_ref().unchecked_ref(),
10_000,
)
.map_err(|e| anyhow!("failed to schedule cleanup: {e:?}"))?;
// The closure only runs once, after which it can be released
callback.forget();
Ok(())
}
/// Open a URL in a new browser tab
pub fn open_url(url: &str) -> Result<(), Error> {
js_window()
.ok_or_else(|| anyhow!("no browser window"))?
.open_with_url_and_target(url, "_blank")
.map_err(|e| anyhow!("failed to open url: {e:?}"))?
.ok_or_else(|| anyhow!("the browser blocked opening the url"))?;
Ok(())
}
fn non_empty(value: impl Into<String>) -> String {
let value: String = value.into();
if value.is_empty() {
"application/octet-stream".to_string()
} else {
value
}
}
+55 -20
View File
@@ -9,7 +9,7 @@ use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::{ActiveTheme, Disableable, WindowExt, v_flex};
use instant::Duration;
use nostr_connect::prelude::*;
use state::NostrRegistry;
use state::{NostrRegistry, StateEvent};
pub fn open(window: &mut Window, cx: &mut App) {
let import = cx.new(|cx| ImportIdentity::new(window, cx));
@@ -73,12 +73,13 @@ impl ImportIdentity {
}
fn build(mode: Mode, window: &mut Window, cx: &mut Context<Self>) -> Self {
let nostr = NostrRegistry::global(cx);
let key_input = cx.new(|cx| InputState::new(window, cx).placeholder("secret or bunker://"));
let pass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
let repass_input = cx.new(|cx| InputState::new(window, cx).masked(true));
let error = cx.new(|_| None);
let subscriptions = vec![
let mut subscriptions = vec![
cx.subscribe_in(&key_input, window, |this, _input, event, _window, cx| {
if let InputEvent::PressEnter { .. } = event {
this.login(cx);
@@ -96,6 +97,14 @@ impl ImportIdentity {
}),
];
subscriptions.push(
cx.subscribe_in(&nostr, window, |this, _nostr, event, _window, cx| {
if let StateEvent::Error(error) = event {
this.set_error(error.clone(), cx);
}
}),
);
Self {
mode,
key_input,
@@ -188,6 +197,14 @@ impl ImportIdentity {
});
}
#[cfg(target_arch = "wasm32")]
fn extension(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
nostr.update(cx, |this, cx| {
this.connect_extension(cx);
});
}
fn set_loading(&mut self, status: bool, cx: &mut Context<Self>) {
self.loading = status;
cx.notify();
@@ -226,7 +243,6 @@ impl Render for ImportIdentity {
const BUNKER_WARN: &str = "Nostr Connect will usually take more time to get all your messages. Please keep your session open until you see all your messages.";
const KEY_WARN: &str = "Coop encrypts your key with your passphrase and stores it on this device. You only need the passphrase to sign in next time.";
let is_wasm = cfg!(target_arch = "wasm32");
let is_unlock = self.mode == Mode::Unlock;
let value = self.key_input.read(cx).value().trim().to_string();
@@ -305,26 +321,45 @@ impl Render for ImportIdentity {
)
}),
)
.child(
Button::new("login")
.label(if is_unlock { "Unlock" } else { "Continue" })
.primary()
.loading(self.loading)
.disabled(self.loading)
.on_click(cx.listener(move |this, _ev, _window, cx| {
this.login(cx);
})),
)
.when(!is_wasm && !is_unlock, |this| {
this.child(
Button::new("proxy")
.label("Connect via Web Extension (Experimental)")
.ghost()
.child({
let content = v_flex().child(
Button::new("login")
.label(if is_unlock { "Unlock" } else { "Continue" })
.primary()
.loading(self.loading)
.disabled(self.loading)
.on_click(cx.listener(move |this, _ev, _window, cx| {
this.proxy(cx);
this.login(cx);
})),
)
);
#[cfg(not(target_arch = "wasm32"))]
let content = content.when(!is_unlock, |this| {
this.child(
Button::new("proxy")
.label("Connect via Web Extension (Experimental)")
.ghost()
.disabled(self.loading)
.on_click(cx.listener(move |this, _ev, _window, cx| {
this.proxy(cx);
})),
)
});
#[cfg(target_arch = "wasm32")]
let content = content.when(!is_unlock, |this| {
this.child(
Button::new("extension")
.label("Continue with Browser Extension (NIP-07)")
.ghost()
.disabled(self.loading)
.on_click(cx.listener(move |this, _ev, _window, cx| {
this.extension(cx);
})),
)
});
content
})
.when_some(self.error.read(cx).as_ref(), |this, error| {
this.child(
+6 -11
View File
@@ -2,8 +2,8 @@ use anyhow::Error;
use gpui::prelude::FluentBuilder;
use gpui::{
App, AppContext, Context, Div, Entity, FocusHandle, InteractiveElement as _, IntoElement,
ParentElement, PathPromptOptions, Render, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, px, rems,
ParentElement, Render, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled,
Subscription, Task, WeakEntity, Window, div, px, rems,
};
use gpui_base::{Popup, Select};
use gpui_kit::assets::IconName;
@@ -18,7 +18,7 @@ use gpui_kit::component::{ActiveTheme, Disableable, Icon, Sizable, WindowExt, h_
use nip29::{GroupCreateOptions, GroupKey, GroupsEvent, GroupsRegistry};
use nostr_sdk::prelude::*;
use settings::AppSettings;
use state::upload;
use state::{pick_file, upload_file};
use ui::{Avatar, settings_row};
const DEFAULT_RELAYS: [&str; 2] = ["wss://relay.ditto.net", "wss://chat.wisp.talk"];
@@ -297,16 +297,11 @@ impl NewGroup {
fn upload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let server = AppSettings::get_file_server(cx);
let path = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
let picker = pick_file(cx);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
// Selecting no file means the prompt was cancelled
let Some(path) = path.await??.and_then(|mut paths| paths.pop()) else {
let Some(picked) = picker.await? else {
return Ok(());
};
@@ -314,7 +309,7 @@ impl NewGroup {
this.set_uploading(true, cx);
})?;
match upload(server, path, cx).await {
match upload_file(server, picked, cx).await {
Ok(url) => {
this.update(cx, |this, cx| {
this.picture = Some(url.to_string().into());
+7 -12
View File
@@ -4,8 +4,8 @@ use anyhow::Error;
use chat::{ChatRegistry, Room, RoomKind};
use gpui::prelude::FluentBuilder;
use gpui::{
App, AppContext, ClipboardItem, Context, Div, Entity, IntoElement, ParentElement,
PathPromptOptions, Render, SharedString, Styled, Task, Window, div, retain_all,
App, AppContext, ClipboardItem, Context, Div, Entity, IntoElement, ParentElement, Render,
SharedString, Styled, Task, Window, div, retain_all,
};
use gpui_kit::assets::IconName;
use gpui_kit::base::StyledExt as _;
@@ -18,7 +18,7 @@ use instant::Duration;
use nostr_sdk::prelude::*;
use person::{Directory, Person, PersonRegistry, shorten_pubkey};
use settings::AppSettings;
use state::{NostrRegistry, upload};
use state::{NostrRegistry, pick_file, upload_file};
use ui::Avatar;
use crate::Workspace;
@@ -179,17 +179,12 @@ impl ProfileDialog {
// Get the user's configured blossom server
let server = AppSettings::get_file_server(cx);
// Ask user for file upload
let path = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
// Ask the user for an image to upload
let picker = pick_file(cx);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
// Selecting no file means the prompt was cancelled
let Some(path) = path.await??.and_then(|mut paths| paths.pop()) else {
let Some(picked) = picker.await? else {
return Ok(());
};
@@ -198,7 +193,7 @@ impl ProfileDialog {
})?;
// Upload via blossom client
match upload(server, path, cx).await {
match upload_file(server, picked, cx).await {
Ok(url) => {
this.update_in(cx, |this, window, cx| {
this.avatar_input.update(cx, |this, cx| {
+39 -25
View File
@@ -1,7 +1,9 @@
#[cfg(not(target_arch = "wasm32"))]
use gpui::PathPromptOptions;
use gpui::http_client::Url;
use gpui::{
App, AppContext, Context, Entity, IntoElement, ParentElement, PathPromptOptions, Render,
Styled, Subscription, Window, div,
App, AppContext, Context, Entity, IntoElement, ParentElement, Render, Styled, Subscription,
Window, div,
};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants};
@@ -150,29 +152,41 @@ impl Preferences {
}
/// Ask the user for an image to show behind chat and group panels
fn choose_background(cx: &mut App) {
let task = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
fn choose_background(
#[cfg_attr(not(target_arch = "wasm32"), allow(unused_variables))] window: &mut Window,
cx: &mut App,
) {
#[cfg(target_arch = "wasm32")]
{
let note = Notification::warning("Background images are not supported on web yet.");
window.push_notification(note, cx);
}
cx.spawn(async move |cx| {
let Ok(Ok(Some(mut paths))) = task.await else {
return;
};
let Some(path) = paths.pop() else {
return;
};
cx.update(|cx| {
AppSettings::update_panel_background_path(Some(path), cx);
cx.refresh_windows();
#[cfg(not(target_arch = "wasm32"))]
{
let task = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: false,
prompt: None,
});
})
.detach();
cx.spawn(async move |cx| {
let Ok(Ok(Some(mut paths))) = task.await else {
return;
};
let Some(path) = paths.pop() else {
return;
};
cx.update(|cx| {
AppSettings::update_panel_background_path(Some(path), cx);
cx.refresh_windows();
});
})
.detach();
}
}
}
@@ -330,8 +344,8 @@ impl Render for Preferences {
.ghost()
.small()
.disabled(!panel_background)
.on_click(|_, _window, cx| {
Self::choose_background(cx);
.on_click(|_, window, cx| {
Self::choose_background(window, cx);
}),
)
.child(
+1
View File
@@ -54,6 +54,7 @@ impl Render for DragPanelPreview {
.cursor_grab()
.p_1()
.whitespace_nowrap()
.font_family(cx.theme().font_family.clone())
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().radius_lg)
+53 -26
View File
@@ -2,8 +2,10 @@ use std::sync::Arc;
use ::settings::{AppSettings, AppearanceMode};
use anyhow::Error;
#[cfg(not(target_arch = "wasm32"))]
use auto_update::AutoUpdater;
use chat::{ChatEvent, ChatRegistry};
#[cfg(not(target_arch = "wasm32"))]
use common::download_dir;
use gpui::{
Action, App, AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement,
@@ -337,34 +339,57 @@ impl Workspace {
}
Command::BackupEncryption => {
let device = DeviceRegistry::global(cx).downgrade();
let save_dialog = cx.prompt_for_new_path(download_dir(), Some("encryption.txt"));
#[cfg(not(target_arch = "wasm32"))]
{
let save_dialog =
cx.prompt_for_new_path(download_dir(), Some("encryption.txt"));
self.tasks.push(cx.spawn_in(window, async move |_this, cx| {
// Get the output path from the save dialog
let output_path = match save_dialog.await {
Ok(Ok(Some(path))) => path,
Ok(Ok(None)) | Err(_) => return Ok(()),
Ok(Err(error)) => {
cx.update(|window, cx| {
let message =
format!("Failed to pick save location: {error:#}");
let note = Notification::error(message).autohide(false);
window.push_notification(note, cx);
})?;
return Ok(());
}
};
// Get the backup task
let backup = device
.read_with(cx, |this, cx| this.backup(output_path.clone(), cx))?;
// Run the backup task
backup.await?;
// Open the backup file with the system's default application
cx.update(|_window, cx| {
cx.open_with_system(output_path.as_path());
})?;
Ok(())
}));
}
#[cfg(target_arch = "wasm32")]
self.tasks.push(cx.spawn_in(window, async move |_this, cx| {
// Get the output path from the save dialog
let output_path = match save_dialog.await {
Ok(Ok(Some(path))) => path,
Ok(Ok(None)) | Err(_) => return Ok(()),
Ok(Err(error)) => {
cx.update(|window, cx| {
let message = format!("Failed to pick save location: {error:#}");
let note = Notification::error(message).autohide(false);
window.push_notification(note, cx);
})?;
return Ok(());
}
};
let backup = device.read_with(cx, |this, cx| this.backup_bytes(cx))?;
let content = backup.await?;
// Get the backup task
let backup =
device.read_with(cx, |this, cx| this.backup(output_path.clone(), cx))?;
// Run the backup task
backup.await?;
// Open the backup file with the system's default application
cx.update(|_window, cx| {
cx.open_with_system(output_path.as_path());
})?;
cx.update(|_window, _cx| {
state::web_file::download(
"encryption.txt",
"text/plain",
content.as_bytes(),
)
})
.map_err(|e| anyhow::anyhow!(e))??;
Ok(())
}));
@@ -372,7 +397,9 @@ impl Workspace {
Command::ImportEncryption => {
self.import_encryption(window, cx);
}
Command::Update => {
Command::Update =>
{
#[cfg(not(target_arch = "wasm32"))]
if let Some(auto_updater) = AutoUpdater::try_global(cx) {
auto_updater.update(cx, |this, cx| this.check(cx));
}
+20 -13
View File
@@ -1,15 +1,17 @@
#[cfg(not(target_arch = "wasm32"))]
use auto_update::AutoUpdater;
use gpui::prelude::FluentBuilder;
#[cfg(not(target_arch = "wasm32"))]
use gpui::{AnyElement, Entity, IntoElement};
use gpui::{
AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement,
Stateful, Styled, Window, div, px,
App, Context, Div, InteractiveElement, ParentElement, Stateful, Styled, Window, div, px,
};
#[cfg(not(target_arch = "wasm32"))]
use gpui_kit::component::Disableable;
use gpui_kit::component::button::{Button, ButtonVariant, ButtonVariants};
use gpui_kit::component::dialog::DialogButtonProps;
use gpui_kit::component::menu::{DropdownMenu, PopupMenuItem};
use gpui_kit::component::{
ActiveTheme, Disableable, Icon, Selectable, Sizable, WindowExt, h_flex, v_flex,
};
use gpui_kit::component::{ActiveTheme, Icon, Selectable, Sizable, WindowExt, h_flex, v_flex};
use nostr_sdk::prelude::*;
use state::NostrRegistry;
use ui::{Avatar, IconName};
@@ -25,6 +27,7 @@ impl Sidebar {
current_user: &PublicKey,
cx: &mut Context<Self>,
) -> Stateful<Div> {
#[cfg(not(target_arch = "wasm32"))]
let updater = AutoUpdater::try_global(cx);
let profile = self.directory.read(cx).person(current_user, cx);
let avatar = profile.avatar();
@@ -62,12 +65,15 @@ impl Sidebar {
)
}),
)
.child(
h_flex()
.gap_1()
.when_some(updater, |this, updater| {
this.child(self.render_updater(updater, cx))
})
.child({
let actions = h_flex().gap_1();
#[cfg(not(target_arch = "wasm32"))]
let actions = actions.when_some(updater, |this, updater| {
this.child(self.render_updater(updater, cx))
});
actions
.child(
Button::new("sidebar-search")
.icon(IconName::Search)
@@ -104,8 +110,8 @@ impl Sidebar {
this.hide_group(cx);
})),
)
}),
)
})
})
}
/// The bottom navigation, pinned below the list like signed's sidebar.
@@ -128,6 +134,7 @@ impl Sidebar {
)
}
#[cfg(not(target_arch = "wasm32"))]
fn render_updater(&self, updater: Entity<AutoUpdater>, cx: &mut App) -> AnyElement {
let status = updater.read(cx).status();
let up_to_date = updater.read(cx).up_to_date();
+2 -7
View File
@@ -1,8 +1,7 @@
use std::time::{SystemTime, UNIX_EPOCH};
use gpui::{AnyElement, App, IntoElement, ParentElement, SharedString, Styled, Window, img};
use gpui_kit::component::button::{Button, ButtonVariants};
use gpui_kit::component::v_flex;
use instant::Instant;
use crate::dialogs::import;
@@ -11,12 +10,8 @@ const SIGNED_OUT_BANNERS: [&str; 2] = ["brand/bg1.jpg", "brand/bg2.jpg"];
/// Pick one of the signed-out backgrounds at random.
pub(super) fn pick_banner() -> SharedString {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.subsec_nanos())
.unwrap_or_default();
let nanos = Instant::now().elapsed().subsec_nanos();
let index = nanos as usize % SIGNED_OUT_BANNERS.len();
SIGNED_OUT_BANNERS[index].into()
}