feat: make the web version fully working (#67)
Reviewed-on: #67
This commit was merged in pull request #67.
This commit is contained in:
+204
-62
@@ -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> {
|
||||
|
||||
Reference in New Issue
Block a user