From 69034f839c9a85b75804880806067d50db247bdc Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 12:21:06 -0800 Subject: [PATCH 1/5] refactor: one module for the file store files::FileStore owns the folder (`/`, `.part` while one arrives) and its rules: whether a file is intact, resuming, the hash check, keeping only what a message has, and pruning. Work that touches the database takes &Db; work that waits on the disk takes none, so Core never holds the lock across an await. Core keeps the transfer and what follows it (telling the UI, waking the fetcher). No change in behaviour: the protocol file tests pass as they were, and the store has unit tests of its own. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/chat.rs | 177 +++---------- src-tauri/src/chat/protocol_tests.rs | 7 +- src-tauri/src/files.rs | 359 +++++++++++++++++++++++++++ src-tauri/src/lib.rs | 1 + 4 files changed, 394 insertions(+), 150 deletions(-) create mode 100644 src-tauri/src/files.rs diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index 6f771e1..19e3937 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -15,7 +15,7 @@ use std::{ collections::{BTreeMap, HashSet}, - path::{Path, PathBuf}, + path::PathBuf, sync::{Arc, Mutex, MutexGuard}, time::{Duration, Instant}, }; @@ -24,18 +24,19 @@ use anyhow::{Context, Result, bail, ensure}; use iroh::{EndpointId, SecretKey}; use serde::{Deserialize, Serialize}; use tokio::{ - io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}, + io::{AsyncReadExt, AsyncSeekExt}, sync::{Notify, mpsc, oneshot}, time::timeout, }; use crate::{ clock::Clock, - db::{Cursor, Db, FileState, Hit, Message, Page}, + db::{Cursor, Db, Hit, Message, Page}, entry::{ Entry, FileInfo, Kind, MAX_EMOJI_CHARS, MAX_FILE_BYTES, MAX_TEXT_CHARS, Ref, VANISH_SECS, - Wire, checked_file, clean, is_hash, + Wire, checked_file, clean, }, + files::{FileStore, Found}, net::{Accepting, Conn, Discoveries, Discovery, Network, RecvStream, SendStream}, }; @@ -286,8 +287,8 @@ pub struct Core { db: Mutex, /// Wall-clock time, shared with `db`. clock: Clock, - /// Where files are kept: `/`, plus `.part` while one arrives. - files_dir: PathBuf, + /// The files messages carry. + files: FileStore, /// Wakes the session's downloader when a message with a file arrives. files_wanted: Notify, state: Mutex, @@ -363,7 +364,7 @@ impl Core { net, db: Mutex::new(db), clock, - files_dir: data_dir.join("files"), + files: FileStore::new(data_dir.join("files")), files_wanted: Notify::new(), state: Mutex::new(State { name, @@ -566,15 +567,7 @@ impl Core { preview: new.preview, }) .context("That file can't be sent.")?; - if self.db().file_state(&hash)? != FileState::Done { - let name = safe_name(&info.name); - let dir = self.files_dir.join(&hash); - std::fs::create_dir_all(&dir)?; - let part = self.files_dir.join(format!("{hash}.part")); - std::fs::write(&part, bytes)?; - std::fs::rename(&part, dir.join(&name))?; - self.db().set_file(&hash, &name, FileState::Done)?; - } + self.files.put_bytes(&self.db(), &info, bytes)?; let text = clean(&new.text, MAX_TEXT_CHARS); self.post(text, Kind::Message { reply_to: new.reply_to, vanish: None, file: Some(info) }) } @@ -585,23 +578,21 @@ impl Core { /// whose size changed, counts as not here: it goes back to waiting, and the /// downloader gets it again from the peer. pub fn file(&self, hash: &str) -> Result> { - if !is_hash(hash) { - return Ok(None); - } - let Some(stored) = self.db().stored_file(hash)? else { return Ok(None) }; - let path = self.files_dir.join(hash).join(&stored.name); - let intact = std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() == stored.size); - if !intact { - self.lost_file(hash)?; - return Ok(None); + let found = self.files.get(&self.db(), hash)?; + match found { + Found::Here { path, mime } => Ok(Some((path, mime))), + Found::Lost => { + self.lost_file(hash)?; + Ok(None) + } + Found::NotHere => Ok(None), } - Ok(Some((path, stored.mime))) } /// A file went missing or changed outside the app: wait for it again, from the peer. /// If they don't have it either, it ends up gone. fn lost_file(&self, hash: &str) -> Result<()> { - self.db().forget_file(hash)?; + self.files.lost(&self.db(), hash)?; self.file_changed(hash)?; self.files_wanted.notify_one(); Ok(()) @@ -1358,9 +1349,7 @@ impl Core { let request: FileRequest = read_json(&mut recv).await?; let found = match self.file(&request.hash)? { Some((path, _)) => { - let check = path.clone(); - let hash = tokio::task::spawn_blocking(move || hash_file(&check)).await??; - if hash == request.hash { + if self.files.unchanged(&path, &request.hash).await? { Some(path) } else { self.lost_file(&request.hash)?; @@ -1422,63 +1411,29 @@ impl Core { } async fn fetch_file(&self, conn: &Conn, file: &FileInfo) -> Result<()> { - tokio::fs::create_dir_all(&self.files_dir).await?; - let part_path = self.files_dir.join(format!("{}.part", file.hash)); - let mut part = tokio::fs::OpenOptions::new() - .create(true) - .truncate(false) - .write(true) - .open(&part_path) - .await?; - let mut have = part.metadata().await?.len(); - if have > file.size { - have = 0; - } - part.set_len(have).await?; - part.seek(std::io::SeekFrom::Start(have)).await?; - + let mut part = self.files.receive(file).await?; let (mut send, mut recv) = conn.open_bi().await?; - write_json(&mut send, &FileRequest { hash: file.hash.clone(), from: have }).await?; + write_json(&mut send, &FileRequest { hash: file.hash.clone(), from: part.have() }).await?; send.finish()?; let reply: FileReply = timeout(FILE_REPLY_TIMEOUT, read_json(&mut recv)) .await .context("no answer to a file request")??; if !reply.found { drop(part); - let _ = tokio::fs::remove_file(&part_path).await; - self.db().set_file(&file.hash, "", FileState::Gone)?; + self.files.gone(&self.db(), &file.hash)?; return self.file_changed(&file.hash); } - let mut progress = Progress::new(&file.hash, have, file.size, &self.emit); + let mut progress = Progress::new(&file.hash, part.have(), file.size, &self.emit); let mut buf = vec![0u8; 256 * 1024]; while let Some(n) = recv.read(&mut buf).await? { - have += n as u64; - ensure!(have <= file.size, "the file is bigger than they said"); - part.write_all(&buf[..n]).await?; + part.write(&buf[..n]).await?; progress.add(n as u64); } - part.flush().await?; - drop(part); - ensure!(have == file.size, "the file ended early"); - - let path = part_path.clone(); - let hash = tokio::task::spawn_blocking(move || hash_file(&path)).await??; - if hash != file.hash { - let _ = tokio::fs::remove_file(&part_path).await; - bail!("{} didn't match its hash", file.name); - } - // Deleted while it was on its way: don't keep it. - if !self.db().file_in_use(&file.hash)? { - let _ = tokio::fs::remove_file(&part_path).await; - return Ok(()); - } - let name = safe_name(&file.name); - let dir = self.files_dir.join(&file.hash); - tokio::fs::create_dir_all(&dir).await?; - tokio::fs::rename(&part_path, dir.join(&name)).await?; - self.db().set_file(&file.hash, &name, FileState::Done)?; + let arrived = part.finish().await?; + // Not kept if it was deleted while on its way. + let kept = self.files.keep(&self.db(), arrived)?; drop(progress); - self.file_changed(&file.hash) + if kept { self.file_changed(&file.hash) } else { Ok(()) } } /// Tells the UI about each message with this file. @@ -1492,28 +1447,7 @@ impl Core { /// Removes files no message has any more, and partial downloads of them. fn prune_files(&self) { - let result = (|| -> Result<()> { - let unused = self.db().unused_files()?; - for hash in unused { - let dir = self.files_dir.join(&hash); - if dir.exists() { - std::fs::remove_dir_all(&dir)?; - } - self.db().forget_file(&hash)?; - } - let Ok(entries) = std::fs::read_dir(&self.files_dir) else { return Ok(()) }; - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - if let Some(hash) = name.strip_suffix(".part") - && !self.db().file_in_use(hash)? - { - // Fails while it's still being written; the download checks again. - let _ = std::fs::remove_file(entry.path()); - } - } - Ok(()) - })(); - if let Err(e) = result { + if let Err(e) = self.files.prune(&self.db()) { eprintln!("removing unused files: {e:#}"); } } @@ -1693,41 +1627,6 @@ fn features_from(stored: Option<&str>) -> Vec { stored.split(',').filter(|f| !f.is_empty()).map(String::from).collect() } -fn hash_file(path: &Path) -> Result { - let mut hasher = blake3::Hasher::new(); - hasher.update_reader(std::fs::File::open(path)?)?; - Ok(hasher.finalize().to_hex().to_string()) -} - -/// A file name that's safe to store on Windows and macOS, keeping its extension. -fn safe_name(name: &str) -> String { - const MAX: usize = 100; - let name: String = name - .chars() - .map(|c| if c.is_control() || r#"<>:"/\|?*"#.contains(c) { '_' } else { c }) - .collect(); - let name = name.trim().trim_start_matches('.').trim_end_matches(['.', ' ']); - let (stem, ext) = match name.rsplit_once('.') { - Some((stem, ext)) if !stem.is_empty() && ext.chars().count() <= 10 => (stem, ext), - _ => (name, ""), - }; - let room = MAX - ext.chars().count() - 1; - let mut stem: String = stem.chars().take(room).collect::().trim_end().to_string(); - if stem.is_empty() { - stem = "file".into(); - } - // Names Windows reserves for devices, with or without an extension. - let device = stem.to_ascii_uppercase(); - let reserved = ["CON", "PRN", "AUX", "NUL"].contains(&device.as_str()) - || (device.len() == 4 - && (device.starts_with("COM") || device.starts_with("LPT")) - && device.as_bytes()[3].is_ascii_digit()); - if reserved { - stem.insert(0, '_'); - } - if ext.is_empty() { stem } else { format!("{stem}.{ext}") } -} - /// Reports a transfer's progress to the UI, a few times a second. Dropping it says the /// transfer is over, done or not, so a broken one doesn't look stuck. struct Progress { @@ -1924,22 +1823,4 @@ mod tests { r#"{"t":"msg","seq":8,"ts":1,"hlc":1,"text":"👍","react_to":{"author":"x","seq":2}}"# ); } - - #[test] - fn file_names_are_safe_to_store() { - assert_eq!(safe_name("beach.jpg"), "beach.jpg"); - assert_eq!(safe_name("../../etc/passwd"), "_.._etc_passwd"); - assert_eq!(safe_name(r"C:\Windows\a:b?.png"), "C__Windows_a_b_.png"); - assert_eq!(safe_name(".hidden"), "hidden"); - assert_eq!(safe_name("trailing. . "), "trailing"); - assert_eq!(safe_name("con.txt"), "_con.txt"); - assert_eq!(safe_name("COM1"), "_COM1"); - assert_eq!(safe_name("company.txt"), "company.txt"); - assert_eq!(safe_name("..."), "file"); - assert_eq!(safe_name(""), "file"); - let long = format!("{}.jpeg", "x".repeat(300)); - let safe = safe_name(&long); - assert_eq!(safe.chars().count(), 100); - assert!(safe.ends_with(".jpeg")); - } } diff --git a/src-tauri/src/chat/protocol_tests.rs b/src-tauri/src/chat/protocol_tests.rs index 2434525..f567609 100644 --- a/src-tauri/src/chat/protocol_tests.rs +++ b/src-tauri/src/chat/protocol_tests.rs @@ -4,10 +4,13 @@ //! //! `two_peers.rs` checks the same engine on the real network. -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::{ + path::Path, + sync::atomic::{AtomicUsize, Ordering}, +}; use super::*; -use crate::net::Lan; +use crate::{db::FileState, net::Lan}; /// Where the test clock starts: November 2027. const EPOCH_MS: i64 = 1_826_000_000_000; diff --git a/src-tauri/src/files.rs b/src-tauri/src/files.rs new file mode 100644 index 0000000..1de203d --- /dev/null +++ b/src-tauri/src/files.rs @@ -0,0 +1,359 @@ +//! The file store: the files messages carry, kept in the data folder. +//! +//! Each file lives at `/`, with `.part` while it arrives. The `files` +//! table (in `Db`) says which are here ('done') and which the sender no longer has +//! ('gone'). The rule this module keeps: a file stays exactly as long as some message has +//! it. Someone may move, delete or edit files in the folder by hand; a file that's +//! missing or changed counts as lost and is fetched again. +//! +//! Work that touches the database takes `&Db` and is quick. Work that waits on the disk +//! (hashing, a file arriving) takes no `Db`, so the caller never holds its lock across +//! an `await`. + +use std::path::{Path, PathBuf}; + +use anyhow::{Result, bail, ensure}; +use tokio::io::{AsyncSeekExt, AsyncWriteExt}; + +use crate::{ + db::{Db, FileState}, + entry::{FileInfo, is_hash}, +}; + +pub(crate) struct FileStore { + dir: PathBuf, +} + +/// What `FileStore::get` finds. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Found { + /// Here, intact: where it is, and its type. + Here { path: PathBuf, mime: String }, + /// Recorded as here, but missing or changed on disk. The caller forgets it + /// (`FileStore::lost`) so it's fetched again. + Lost, + /// Not here, or no message has it. + NotHere, +} + +impl FileStore { + pub fn new(dir: PathBuf) -> Self { + Self { dir } + } + + /// Keeps `bytes` as the file `info` describes, unless it's here already. Blocking. + pub fn put_bytes(&self, db: &Db, info: &FileInfo, bytes: &[u8]) -> Result<()> { + if db.file_state(&info.hash)? == FileState::Done { + return Ok(()); + } + let name = safe_name(&info.name); + let part = self.part_path(&info.hash); + std::fs::create_dir_all(self.dir.join(&info.hash))?; + std::fs::write(&part, bytes)?; + std::fs::rename(&part, self.dir.join(&info.hash).join(&name))?; + db.set_file(&info.hash, &name, FileState::Done) + } + + /// A file that's here and attached to a message. One that's gone, or whose size + /// changed, is `Lost`. + pub fn get(&self, db: &Db, hash: &str) -> Result { + if !is_hash(hash) { + return Ok(Found::NotHere); + } + let Some(stored) = db.stored_file(hash)? else { return Ok(Found::NotHere) }; + let path = self.dir.join(hash).join(&stored.name); + let intact = std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() == stored.size); + Ok(if intact { Found::Here { path, mime: stored.mime } } else { Found::Lost }) + } + + /// Forgets a lost file, so it's fetched again. + pub fn lost(&self, db: &Db, hash: &str) -> Result<()> { + db.forget_file(hash) + } + + /// Whether the file at `path` still has the contents `hash` names: one edited in place + /// keeps its size, so only hashing tells. + pub async fn unchanged(&self, path: &Path, hash: &str) -> Result { + let path = path.to_path_buf(); + Ok(tokio::task::spawn_blocking(move || hash_file(&path)).await?? == hash) + } + + /// Starts receiving `file`, from where an earlier attempt broke off. + pub async fn receive(&self, file: &FileInfo) -> Result { + tokio::fs::create_dir_all(&self.dir).await?; + let path = self.part_path(&file.hash); + let mut part = tokio::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .await?; + let mut have = part.metadata().await?.len(); + if have > file.size { + have = 0; + } + part.set_len(have).await?; + part.seek(std::io::SeekFrom::Start(have)).await?; + Ok(Part { file: Some(part), path, have, info: file.clone() }) + } + + /// Keeps a file that arrived whole, unless no message has it any more (deleted while + /// it was on its way). Returns whether it was kept. + pub fn keep(&self, db: &Db, arrived: Arrived) -> Result { + let Arrived { path, info } = arrived; + if !db.file_in_use(&info.hash)? { + let _ = std::fs::remove_file(&path); + return Ok(false); + } + let name = safe_name(&info.name); + let dir = self.dir.join(&info.hash); + std::fs::create_dir_all(&dir)?; + std::fs::rename(&path, dir.join(&name))?; + db.set_file(&info.hash, &name, FileState::Done)?; + Ok(true) + } + + /// The sender doesn't have the file any more. + pub fn gone(&self, db: &Db, hash: &str) -> Result<()> { + let _ = std::fs::remove_file(self.part_path(hash)); + db.set_file(hash, "", FileState::Gone) + } + + /// Removes files no message has any more, and partial downloads of them. + pub fn prune(&self, db: &Db) -> Result<()> { + for hash in db.unused_files()? { + let dir = self.dir.join(&hash); + if dir.exists() { + std::fs::remove_dir_all(&dir)?; + } + db.forget_file(&hash)?; + } + let Ok(entries) = std::fs::read_dir(&self.dir) else { return Ok(()) }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if let Some(hash) = name.strip_suffix(".part") + && !db.file_in_use(hash)? + { + // Fails while it's still being written; the download checks again. + let _ = std::fs::remove_file(entry.path()); + } + } + Ok(()) + } + + fn part_path(&self, hash: &str) -> PathBuf { + self.dir.join(format!("{hash}.part")) + } +} + +/// A file on its way in. +pub(crate) struct Part { + /// `None` once finished. + file: Option, + path: PathBuf, + have: u64, + info: FileInfo, +} + +/// A file that arrived whole and matches its hash, waiting to be kept (`FileStore::keep`). +pub(crate) struct Arrived { + path: PathBuf, + info: FileInfo, +} + +impl Part { + /// How many bytes are here already: where to ask the sender to start. + pub fn have(&self) -> u64 { + self.have + } + + pub async fn write(&mut self, buf: &[u8]) -> Result<()> { + self.have += buf.len() as u64; + ensure!(self.have <= self.info.size, "the file is bigger than they said"); + let Some(file) = &mut self.file else { bail!("already finished") }; + file.write_all(buf).await?; + Ok(()) + } + + /// Checks the whole file against its hash. One that doesn't match is removed, so the + /// next try starts over. + pub async fn finish(mut self) -> Result { + if let Some(mut file) = self.file.take() { + file.flush().await?; + } + ensure!(self.have == self.info.size, "the file ended early"); + let path = self.path.clone(); + let hash = tokio::task::spawn_blocking(move || hash_file(&path)).await??; + if hash != self.info.hash { + let _ = tokio::fs::remove_file(&self.path).await; + bail!("{} didn't match its hash", self.info.name); + } + Ok(Arrived { path: self.path, info: self.info }) + } +} + +fn hash_file(path: &Path) -> Result { + let mut hasher = blake3::Hasher::new(); + hasher.update_reader(std::fs::File::open(path)?)?; + Ok(hasher.finalize().to_hex().to_string()) +} + +/// A file name that's safe to store on Windows and macOS, keeping its extension. +fn safe_name(name: &str) -> String { + const MAX: usize = 100; + let name: String = name + .chars() + .map(|c| if c.is_control() || r#"<>:"/\|?*"#.contains(c) { '_' } else { c }) + .collect(); + let name = name.trim().trim_start_matches('.').trim_end_matches(['.', ' ']); + let (stem, ext) = match name.rsplit_once('.') { + Some((stem, ext)) if !stem.is_empty() && ext.chars().count() <= 10 => (stem, ext), + _ => (name, ""), + }; + let room = MAX - ext.chars().count() - 1; + let mut stem: String = stem.chars().take(room).collect::().trim_end().to_string(); + if stem.is_empty() { + stem = "file".into(); + } + // Names Windows reserves for devices, with or without an extension. + let device = stem.to_ascii_uppercase(); + let reserved = ["CON", "PRN", "AUX", "NUL"].contains(&device.as_str()) + || (device.len() == 4 + && (device.starts_with("COM") || device.starts_with("LPT")) + && device.as_bytes()[3].is_ascii_digit()); + if reserved { + stem.insert(0, '_'); + } + if ext.is_empty() { stem } else { format!("{stem}.{ext}") } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::entry::{Entry, Kind, Ref}; + + /// A store in a fresh folder, a log in memory, and a picture with its bytes. + fn setup(label: &str) -> (FileStore, Db, FileInfo, Vec, PathBuf) { + let nanos = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("tightbeam-files-{nanos}-{label}")); + let bytes: Vec = (0..300_000u32).map(|i| (i % 251) as u8).collect(); + let info = FileInfo { + hash: blake3::hash(&bytes).to_hex().to_string(), + name: "beach.jpg".into(), + size: bytes.len() as u64, + mime: "image/jpeg".into(), + width: None, + height: None, + preview: None, + }; + let db = Db::open(Path::new(":memory:")).unwrap(); + (FileStore::new(dir.clone()), db, info, bytes, dir) + } + + /// A message with the file, so the store keeps it. + fn attach(db: &Db, info: &FileInfo, seq: u64) { + let kind = Kind::Message { reply_to: None, vanish: None, file: Some(info.clone()) }; + db.insert(&Entry { kind, ..Entry::message("me", seq, 1, "") }).unwrap(); + } + + #[test] + fn a_kept_file_is_here_until_it_changes_on_disk() { + let (store, db, info, bytes, dir) = setup("get"); + attach(&db, &info, 1); + store.put_bytes(&db, &info, &bytes).unwrap(); + let path = dir.join(&info.hash).join("beach.jpg"); + let here = Found::Here { path: path.clone(), mime: "image/jpeg".into() }; + assert_eq!(store.get(&db, &info.hash).unwrap(), here); + assert_eq!(store.get(&db, "../x").unwrap(), Found::NotHere); + + std::fs::write(&path, b"cropped").unwrap(); // edited by hand + assert_eq!(store.get(&db, &info.hash).unwrap(), Found::Lost); + store.lost(&db, &info.hash).unwrap(); + assert_eq!(store.get(&db, &info.hash).unwrap(), Found::NotHere, "to be fetched again"); + assert_eq!(db.wanted_files().unwrap(), [info]); + let _ = std::fs::remove_dir_all(dir); + } + + #[tokio::test] + async fn an_arriving_file_resumes_and_is_checked() { + let (store, db, info, bytes, dir) = setup("receive"); + attach(&db, &info, 1); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(format!("{}.part", info.hash)), &bytes[..1000]).unwrap(); + + let mut part = store.receive(&info).await.unwrap(); + assert_eq!(part.have(), 1000, "picks up where it broke off"); + part.write(&bytes[1000..]).await.unwrap(); + let arrived = part.finish().await.unwrap(); + assert!(store.keep(&db, arrived).unwrap()); + assert!(matches!(store.get(&db, &info.hash).unwrap(), Found::Here { .. })); + + // Too many bytes, too few, or the wrong ones: nothing kept. + let other = FileInfo { hash: "ab".repeat(32), ..info.clone() }; + let mut part = store.receive(&other).await.unwrap(); + assert!(part.write(&vec![0; bytes.len() + 1]).await.is_err()); + let part = store.receive(&other).await.unwrap(); + assert!(part.finish().await.is_err(), "it ended early"); + let mut part = store.receive(&other).await.unwrap(); + part.write(&bytes).await.unwrap(); + assert!(part.finish().await.is_err(), "the hash doesn't match"); + assert!(!dir.join(format!("{}.part", other.hash)).exists(), "the next try starts over"); + let _ = std::fs::remove_dir_all(dir); + } + + #[tokio::test] + async fn a_file_no_message_has_is_not_kept_and_is_pruned() { + let (store, db, info, bytes, dir) = setup("prune"); + // Arrives after its message was deleted. + let mut part = store.receive(&info).await.unwrap(); + part.write(&bytes).await.unwrap(); + let arrived = part.finish().await.unwrap(); + assert!(!store.keep(&db, arrived).unwrap()); + assert!(!dir.join(&info.hash).exists()); + + // Kept while a message has it; pruned once none does, with any partial download. + attach(&db, &info, 1); + store.put_bytes(&db, &info, &bytes).unwrap(); + std::fs::write(dir.join(format!("{}.part", "cd".repeat(32))), b"half").unwrap(); + store.prune(&db).unwrap(); + assert!(dir.join(&info.hash).exists(), "still in use"); + assert!(!dir.join(format!("{}.part", "cd".repeat(32))).exists()); + db.scrub(&Ref { author: "me".into(), seq: 1 }).unwrap(); // deleted + store.prune(&db).unwrap(); + assert!(!dir.join(&info.hash).exists()); + assert_eq!(db.file_state(&info.hash).unwrap(), FileState::Pending, "forgotten"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_file_the_sender_lost_is_gone() { + let (store, db, info, _, dir) = setup("gone"); + attach(&db, &info, 1); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(format!("{}.part", info.hash)), b"some").unwrap(); + store.gone(&db, &info.hash).unwrap(); + assert_eq!(db.file_state(&info.hash).unwrap(), FileState::Gone); + assert!(!dir.join(format!("{}.part", info.hash)).exists()); + assert!(db.wanted_files().unwrap().is_empty(), "not asked for again"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn file_names_are_safe_to_store() { + assert_eq!(safe_name("beach.jpg"), "beach.jpg"); + assert_eq!(safe_name("../../etc/passwd"), "_.._etc_passwd"); + assert_eq!(safe_name(r"C:\Windows\a:b?.png"), "C__Windows_a_b_.png"); + assert_eq!(safe_name(".hidden"), "hidden"); + assert_eq!(safe_name("trailing. . "), "trailing"); + assert_eq!(safe_name("con.txt"), "_con.txt"); + assert_eq!(safe_name("COM1"), "_COM1"); + assert_eq!(safe_name("company.txt"), "company.txt"); + assert_eq!(safe_name("..."), "file"); + assert_eq!(safe_name(""), "file"); + let long = format!("{}.jpeg", "x".repeat(300)); + let safe = safe_name(&long); + assert_eq!(safe.chars().count(), 100); + assert!(safe.ends_with(".jpeg")); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cfe8b41..6c396ff 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ mod clock; pub mod db; mod desktop; pub mod entry; +mod files; mod idle; mod net; mod updates; From 4610e0b88bccc1e9a0dd7733da8dc78481bbd824 Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 12:26:27 -0800 Subject: [PATCH 2/5] feat: send any file from disk by path The paperclip opens the system's file picker, and files dropped on the window come with their paths (Tauri's drag and drop): either way Rust stages them and they go by path, never read into the webview, so a big one isn't held in memory. The store copies a sent file in while hashing it, so changing or moving the original afterwards makes no difference. A staged picture's preview is made from tbstaged://, which serves only staged pictures up to 50 MB. Pasting still goes as bytes, now for any file up to 100 MB. Folders, empty files and anything over 1 GB are turned away with a note. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/chat.rs | 48 +++++-- src-tauri/src/chat/protocol_tests.rs | 34 +++++ src-tauri/src/files.rs | 183 ++++++++++++++++++++++++++- src-tauri/src/lib.rs | 180 ++++++++++++++++++++++---- src-tauri/tauri.conf.json | 2 +- ui/src/api.ts | 24 ++++ ui/src/components/Chat.tsx | 74 +++++------ ui/src/components/Files.tsx | 16 +-- ui/src/lib/files.ts | 106 ++++++++++------ ui/src/store.ts | 53 ++++++-- 10 files changed, 572 insertions(+), 148 deletions(-) diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index 19e3937..a2bc135 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -138,7 +138,7 @@ struct FileReply { } /// What the UI says about a file it sends. The bytes come separately. -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Deserialize)] pub struct NewFile { pub name: String, pub mime: String, @@ -541,9 +541,30 @@ impl Core { /// Sends a file, with `new.text` as its caption. Blocking: it hashes and stores the /// file, so call it off the UI thread. pub fn send_file(&self, bytes: &[u8], new: NewFile) -> Result { - let peer = self.peer_id().context("not paired with anyone yet")?; + self.may_send_file(&new)?; ensure!(!bytes.is_empty(), "That file is empty."); ensure!(bytes.len() as u64 <= MAX_FILE_BYTES, "Files can be up to 1 GB."); + let hash = blake3::hash(bytes).to_hex().to_string(); + let info = described(new.clone(), hash, bytes.len() as u64)?; + self.files.put_bytes(&self.db(), &info, bytes)?; + self.post_file(new, info) + } + + /// Sends the file at `path`, with `new.text` as its caption. The store copies it in, + /// so changing or moving the original afterwards makes no difference. Blocking: it + /// hashes and copies the file, so call it off the UI thread. + pub fn send_file_from(&self, path: &std::path::Path, new: NewFile) -> Result { + self.may_send_file(&new)?; + let copied = self.files.copy_in(path)?; + let info = described(new.clone(), copied.hash.clone(), copied.size)?; + self.files.adopt(&self.db(), copied, &info.name)?; + self.post_file(new, info) + } + + /// Whether a file can go to the peer now: their build takes files, and a reply is to + /// one of us. + fn may_send_file(&self, new: &NewFile) -> Result<()> { + let peer = self.peer_id().context("not paired with anyone yet")?; { let st = self.state(); ensure!( @@ -556,18 +577,10 @@ impl Core { if let Some(to) = &new.reply_to { ensure!(self.is_ours(to, &peer.to_string()), "can't reply to that"); } - let hash = blake3::hash(bytes).to_hex().to_string(); - let info = checked_file(FileInfo { - hash: hash.clone(), - name: new.name, - size: bytes.len() as u64, - mime: new.mime, - width: new.width, - height: new.height, - preview: new.preview, - }) - .context("That file can't be sent.")?; - self.files.put_bytes(&self.db(), &info, bytes)?; + Ok(()) + } + + fn post_file(&self, new: NewFile, info: FileInfo) -> Result { let text = clean(&new.text, MAX_TEXT_CHARS); self.post(text, Kind::Message { reply_to: new.reply_to, vanish: None, file: Some(info) }) } @@ -1662,6 +1675,13 @@ impl Drop for Progress { } } +/// What a file I'm sending says about itself, checked like one that arrives. +fn described(new: NewFile, hash: String, size: u64) -> Result { + let NewFile { name, mime, width, height, preview, .. } = new; + checked_file(FileInfo { hash, name, size, mime, width, height, preview }) + .context("That file can't be sent.") +} + /// Whether one of my entries goes to `peer`: only what I wrote after pairing with them /// (`shared_after`), and only about messages they have, theirs or mine since then. A /// reply always goes: its text is new, and a quote they don't have shows as missing. diff --git a/src-tauri/src/chat/protocol_tests.rs b/src-tauri/src/chat/protocol_tests.rs index f567609..262affd 100644 --- a/src-tauri/src/chat/protocol_tests.rs +++ b/src-tauri/src/chat/protocol_tests.rs @@ -969,3 +969,37 @@ async fn a_new_pairing_starts_clean() { assert!(alice.send_file(b"png", picture()).is_err(), "no files"); assert_eq!((alice.status().peer_has, alice.status().peer_seen), (0, 0)); } + +#[tokio::test(start_paused = true)] +async fn any_file_goes_from_disk_by_path() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + let bytes = photo_bytes(); + let original = world.root.join("Report.pdf"); + std::fs::write(&original, &bytes).unwrap(); + let new = NewFile { + name: "Report.pdf".into(), + mime: "application/pdf".into(), + width: None, + height: None, + preview: None, + text: "the numbers".into(), + reply_to: None, + }; + let sent = alice.send_file_from(&original, new).unwrap(); + let file = sent.file.unwrap(); + assert_eq!((file.state, file.info.size), (FileState::Done, bytes.len() as u64)); + + // Her copy is the store's own: changing the original afterwards changes nothing. + std::fs::write(&original, b"edited").unwrap(); + let at = Ref { author: alice.id(), seq: sent.seq }; + until("bob has it", || file_state(&bob, &at) == Some(FileState::Done)).await; + let (path, mime) = bob.file(&file.info.hash).unwrap().unwrap(); + assert_eq!((std::fs::read(&path).unwrap(), mime.as_str()), (bytes, "application/pdf")); + assert_eq!(path.file_name().unwrap(), "Report.pdf"); + assert_eq!(bob.find(&at).unwrap().text, "the numbers"); + + let missing = world.root.join("not there.pdf"); + assert!(alice.send_file_from(&missing, picture()).is_err()); +} diff --git a/src-tauri/src/files.rs b/src-tauri/src/files.rs index 1de203d..a7e6262 100644 --- a/src-tauri/src/files.rs +++ b/src-tauri/src/files.rs @@ -10,16 +10,23 @@ //! (hashing, a file arriving) takes no `Db`, so the caller never holds its lock across //! an `await`. -use std::path::{Path, PathBuf}; +use std::{ + io::{Read, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; use anyhow::{Result, bail, ensure}; use tokio::io::{AsyncSeekExt, AsyncWriteExt}; use crate::{ db::{Db, FileState}, - entry::{FileInfo, is_hash}, + entry::{FileInfo, MAX_FILE_BYTES, is_hash}, }; +/// While a file from disk is copied in, before its hash is known. +const ADDING: &str = ".adding"; + pub(crate) struct FileStore { dir: PathBuf, } @@ -37,10 +44,64 @@ pub(crate) enum Found { } impl FileStore { + /// The store in `dir`. Copies left half-done when the app last closed are removed. pub fn new(dir: PathBuf) -> Self { + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + if entry.file_name().to_string_lossy().ends_with(ADDING) { + let _ = std::fs::remove_file(entry.path()); + } + } + } Self { dir } } + /// Copies a file from disk into the folder, hashing it on the way, never all in + /// memory. Blocking, and it doesn't touch the log, so it can take its time; then + /// `adopt` keeps it. + pub fn copy_in(&self, from: &Path) -> Result { + static NEXT: AtomicU64 = AtomicU64::new(0); + let mut source = std::fs::File::open(from)?; + let size = source.metadata()?.len(); + ensure!(size > 0, "That file is empty."); + ensure!(size <= MAX_FILE_BYTES, "Files can be up to 1 GB."); + std::fs::create_dir_all(&self.dir)?; + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let temp = self.dir.join(format!("{}-{n}{ADDING}", std::process::id())); + // Removes the copy if anything below fails. + let mut copied = Copied { temp: Some(temp.clone()), hash: String::new(), size: 0 }; + let mut out = std::io::BufWriter::new(std::fs::File::create(&temp)?); + let (mut hasher, mut buf, mut total) = (blake3::Hasher::new(), vec![0u8; 256 * 1024], 0); + loop { + let n = source.read(&mut buf)?; + if n == 0 { + break; + } + total += n as u64; + ensure!(total <= MAX_FILE_BYTES, "Files can be up to 1 GB."); + hasher.update(&buf[..n]); + out.write_all(&buf[..n])?; + } + out.flush()?; + ensure!(total > 0, "That file is empty."); + (copied.hash, copied.size) = (hasher.finalize().to_hex().to_string(), total); + Ok(copied) + } + + /// Keeps a copied file under `name`, unless the same file is here already. + pub fn adopt(&self, db: &Db, mut copied: Copied, name: &str) -> Result<()> { + let Some(temp) = copied.temp.take() else { bail!("already kept") }; + if db.file_state(&copied.hash)? == FileState::Done { + let _ = std::fs::remove_file(&temp); + return Ok(()); + } + let name = safe_name(name); + let dir = self.dir.join(&copied.hash); + std::fs::create_dir_all(&dir)?; + std::fs::rename(&temp, dir.join(&name))?; + db.set_file(&copied.hash, &name, FileState::Done) + } + /// Keeps `bytes` as the file `info` describes, unless it's here already. Blocking. pub fn put_bytes(&self, db: &Db, info: &FileInfo, bytes: &[u8]) -> Result<()> { if db.file_state(&info.hash)? == FileState::Done { @@ -146,6 +207,22 @@ impl FileStore { } } +/// A file from disk, copied in and hashed (`FileStore::copy_in`). Removed if dropped +/// before it's kept. +pub(crate) struct Copied { + temp: Option, + pub hash: String, + pub size: u64, +} + +impl Drop for Copied { + fn drop(&mut self) { + if let Some(temp) = &self.temp { + let _ = std::fs::remove_file(temp); + } + } +} + /// A file on its way in. pub(crate) struct Part { /// `None` once finished. @@ -192,6 +269,61 @@ impl Part { } } +/// A file's type, from the end of its name, for files from disk. Others are just bytes. +pub(crate) fn mime_for(name: &str) -> &'static str { + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + match ext.as_str() { + "jpg" | "jpeg" => "image/jpeg", + "png" => "image/png", + "gif" => "image/gif", + "webp" => "image/webp", + "avif" => "image/avif", + "bmp" => "image/bmp", + "heic" => "image/heic", + "heif" => "image/heif", + "tif" | "tiff" => "image/tiff", + "svg" => "image/svg+xml", + "pdf" => "application/pdf", + "txt" => "text/plain", + "md" => "text/markdown", + "csv" => "text/csv", + "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "odt" => "application/vnd.oasis.opendocument.text", + "ods" => "application/vnd.oasis.opendocument.spreadsheet", + "odp" => "application/vnd.oasis.opendocument.presentation", + "mp3" => "audio/mpeg", + "m4a" => "audio/mp4", + "aac" => "audio/aac", + "wav" => "audio/wav", + "flac" => "audio/flac", + "ogg" => "audio/ogg", + "mp4" => "video/mp4", + "m4v" => "video/x-m4v", + "mov" => "video/quicktime", + "webm" => "video/webm", + "mkv" => "video/x-matroska", + "zip" => "application/zip", + _ => "application/octet-stream", + } +} + +/// Types the webview may show as an image. Not SVG, which can carry scripts. +pub(crate) fn may_show(mime: &str) -> bool { + const SHOWABLE: &[&str] = &[ + "image/jpeg", + "image/png", + "image/gif", + "image/webp", + "image/avif", + "image/bmp", + "image/heic", + "image/heif", + ]; + SHOWABLE.contains(&mime) +} + fn hash_file(path: &Path) -> Result { let mut hasher = blake3::Hasher::new(); hasher.update_reader(std::fs::File::open(path)?)?; @@ -326,6 +458,53 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn a_file_from_disk_is_copied_in_and_kept_once() { + let (store, db, info, bytes, dir) = setup("copy"); + let original = dir.with_extension("original.jpg"); + std::fs::write(&original, &bytes).unwrap(); + let copied = store.copy_in(&original).unwrap(); + assert_eq!((copied.hash.as_str(), copied.size), (info.hash.as_str(), info.size)); + attach(&db, &info, 1); + store.adopt(&db, copied, "beach.jpg").unwrap(); + assert!(matches!(store.get(&db, &info.hash).unwrap(), Found::Here { .. })); + + // The original can change or go: the store has its own copy. + std::fs::remove_file(&original).unwrap(); + assert!(matches!(store.get(&db, &info.hash).unwrap(), Found::Here { .. })); + + // Copying the same file again keeps the one copy; one never kept leaves nothing. + std::fs::write(&original, &bytes).unwrap(); + let again = store.copy_in(&original).unwrap(); + store.adopt(&db, again, "beach.jpg").unwrap(); + drop(store.copy_in(&original).unwrap()); + let adding = |dir: &Path| { + std::fs::read_dir(dir) + .unwrap() + .flatten() + .any(|e| e.file_name().to_string_lossy().ends_with(ADDING)) + }; + assert!(!adding(&dir), "nothing half-copied left behind"); + + std::fs::write(&original, b"").unwrap(); + let refused = store.copy_in(&original).err().unwrap().to_string(); + assert_eq!(refused, "That file is empty."); + std::fs::write(dir.join(format!("9-9{ADDING}")), b"interrupted").unwrap(); + let _ = FileStore::new(dir.clone()); + assert!(!adding(&dir), "an interrupted copy goes at the next start"); + let _ = std::fs::remove_file(original); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn types_come_from_the_name() { + assert_eq!(mime_for("Report.PDF"), "application/pdf"); + assert_eq!(mime_for("song.flac"), "audio/flac"); + assert_eq!(mime_for("setup.exe"), "application/octet-stream"); + assert_eq!(mime_for("no extension"), "application/octet-stream"); + assert!(may_show("image/png") && !may_show("image/svg+xml") && !may_show("text/html")); + } + #[test] fn a_file_the_sender_lost_is_gone() { let (store, db, info, _, dir) = setup("gone"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6c396ff..b3d9c83 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -8,12 +8,16 @@ mod idle; mod net; mod updates; -use std::{path::PathBuf, sync::Arc}; +use std::{ + collections::HashMap, + path::PathBuf, + sync::{Arc, Mutex}, +}; use chat::{ConnectionInfo, Core, Emit, Event, NewFile, Status}; use db::{Cursor, Hit, Message, Page}; use desktop::{Desktop, MAIN_WINDOW, MINIMIZED_ARG}; -use entry::Ref; +use entry::{MAX_FILE_BYTES, Ref}; use serde::Serialize; use tauri::{ Emitter, Manager, RunEvent, State, WindowEvent, @@ -114,6 +118,147 @@ async fn send_file( .map_err(err) } +/// Files from disk waiting in the message box, by id. They go by path, never through the +/// webview, so a big one isn't read into memory. +#[derive(Default)] +struct Staging(Mutex); + +#[derive(Default)] +struct StagingState { + next: u64, + files: HashMap, +} + +struct Staged { + path: PathBuf, + mime: &'static str, + size: u64, +} + +/// A file from disk, staged, as the UI sees it. +#[derive(Serialize)] +struct StagedFile { + id: u64, + name: String, + size: u64, + mime: String, +} + +/// What came of staging some paths: the ones staged, and why the others weren't. +#[derive(Serialize)] +struct StagedFiles { + staged: Vec, + refused: Vec, +} + +impl Staging { + fn add(&self, paths: impl IntoIterator) -> StagedFiles { + let (mut staged, mut refused) = (Vec::new(), Vec::new()); + let mut st = self.0.lock().unwrap(); + for path in paths { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + let name = name.unwrap_or_else(|| path.to_string_lossy().into_owned()); + match std::fs::metadata(&path) { + Ok(m) if m.is_dir() => { + refused.push(format!("{name} is a folder. Only files can be sent.")) + } + Ok(m) if m.len() == 0 => refused.push(format!("{name} is empty.")), + Ok(m) if m.len() > MAX_FILE_BYTES => { + refused.push(format!("{name} is too big. Files can be up to 1 GB.")) + } + Ok(m) => { + st.next += 1; + let (id, mime, size) = (st.next, files::mime_for(&name), m.len()); + st.files.insert(id, Staged { path, mime, size }); + staged.push(StagedFile { id, name, size, mime: mime.into() }); + } + Err(_) => refused.push(format!("{name} can't be read.")), + } + } + StagedFiles { staged, refused } + } +} + +/// Stages files dropped on the window. +#[tauri::command] +fn stage_paths(staging: State, paths: Vec) -> StagedFiles { + staging.add(paths) +} + +/// Asks which files to send, then stages them. +#[tauri::command] +async fn pick_files( + app: tauri::AppHandle, + staging: State<'_, Staging>, +) -> Result { + let (tx, rx) = tokio::sync::oneshot::channel(); + app.dialog().file().set_title("Send files").pick_files(move |chosen| { + let _ = tx.send(chosen); + }); + let chosen = rx.await.map_err(err)?.unwrap_or_default(); + Ok(staging.add(chosen.into_iter().filter_map(|p| p.into_path().ok()))) +} + +/// Sends a staged file. It stays staged if that fails, so it can be tried again. +#[tauri::command] +async fn send_staged( + core: State<'_, Arc>, + staging: State<'_, Staging>, + id: u64, + details: NewFile, +) -> Result { + let path = staging.0.lock().unwrap().files.get(&id).map(|s| s.path.clone()); + let path = path.ok_or("That file isn't waiting to be sent any more.")?; + let core = core.inner().clone(); + // Hashing and copying a big file takes a moment. + let sent = tauri::async_runtime::spawn_blocking(move || core.send_file_from(&path, details)) + .await + .map_err(err)? + .map_err(err)?; + staging.0.lock().unwrap().files.remove(&id); + Ok(sent) +} + +/// Takes a file out of the message box. +#[tauri::command] +fn unstage(staging: State, id: u64) { + staging.0.lock().unwrap().files.remove(&id); +} + +/// Previews of staged pictures are made from at most this much. +const MAX_PREVIEW_SOURCE: u64 = 50 * 1024 * 1024; + +/// A staged picture's bytes, for the webview to make its preview. Only pictures it can +/// show, up to 50 MB; nothing else on disk. Raw bytes over IPC, not a fetch from a URI +/// scheme: that would be cross-origin, and the webview would refuse it without CORS. +#[tauri::command] +async fn staged_picture( + staging: State<'_, Staging>, + id: u64, +) -> Result { + let path = { + let st = staging.0.lock().unwrap(); + let s = st.files.get(&id).ok_or("That file isn't waiting to be sent any more.")?; + let fits = files::may_show(s.mime) && s.size <= MAX_PREVIEW_SOURCE; + fits.then(|| s.path.clone()).ok_or("That file has no preview.")? + }; + let bytes = tauri::async_runtime::spawn_blocking(move || std::fs::read(path)) + .await + .map_err(err)? + .map_err(err)?; + Ok(tauri::ipc::Response::new(bytes)) +} + +fn uncached(status: StatusCode, mime: &str, body: Vec) -> Response> { + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, mime) + .header(header::CACHE_CONTROL, "no-store") + .header("X-Content-Type-Options", "nosniff") + .body(body) + .unwrap_or_default() +} + /// Kinds of file that open in their default app. Anything else, like a program, can only /// be shown in its folder. const OPENABLE: &[&str] = @@ -172,38 +317,17 @@ async fn save_file_copy( const MISSING: &str = "That file was moved or changed outside Tightbeam, so it's being fetched again."; -/// Types the webview may show as an image. Not SVG, which can carry scripts. -const SHOWABLE: &[&str] = &[ - "image/jpeg", - "image/png", - "image/gif", - "image/webp", - "image/avif", - "image/bmp", - "image/heic", - "image/heif", -]; - /// `tbfile://localhost/` (`http://tbfile.localhost/` on Windows): a stored /// file, for the webview to show. Only files still attached to a message, and never /// cached, so a deleted picture doesn't linger in the webview's cache. fn file_response(app: &tauri::AppHandle, path: &str) -> Response> { - let respond = |status: StatusCode, mime: &str, body: Vec| { - Response::builder() - .status(status) - .header(header::CONTENT_TYPE, mime) - .header(header::CACHE_CONTROL, "no-store") - .header("X-Content-Type-Options", "nosniff") - .body(body) - .unwrap_or_default() - }; + let respond = uncached; let hash = path.trim_start_matches('/'); let found = app.try_state::>().and_then(|core| core.file(hash).ok().flatten()); let Some((file, mime)) = found else { return respond(StatusCode::NOT_FOUND, "text/plain", Vec::new()); }; - let mime = - if SHOWABLE.contains(&mime.as_str()) { mime } else { "application/octet-stream".into() }; + let mime = if files::may_show(&mime) { mime } else { "application/octet-stream".into() }; match std::fs::read(file) { Ok(bytes) => respond(StatusCode::OK, &mime, bytes), Err(_) => respond(StatusCode::NOT_FOUND, "text/plain", Vec::new()), @@ -403,6 +527,7 @@ pub fn run() { let loopback = std::env::var_os("TIGHTBEAM_LOOPBACK").is_some(); app.manage(Desktop::new()); + app.manage(Staging::default()); let handle = app.handle().clone(); let emit: Emit = Arc::new(move |event| { match &event { @@ -449,6 +574,11 @@ pub fn run() { set_name, send_message, send_file, + stage_paths, + pick_files, + send_staged, + staged_picture, + unstage, open_file, show_file, save_file_copy, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 618c2b3..f91d4f4 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -18,7 +18,7 @@ "height": 680, "minWidth": 340, "minHeight": 420, - "dragDropEnabled": false + "dragDropEnabled": true } ], "security": { diff --git a/ui/src/api.ts b/ui/src/api.ts index 6e369d2..abd2c38 100644 --- a/ui/src/api.ts +++ b/ui/src/api.ts @@ -96,6 +96,20 @@ export interface Attachment extends FileInfo { state: 'pending' | 'done' | 'gone' } +/** A file from disk, staged in Rust to be sent by path. */ +export interface StagedFile { + id: number + name: string + size: number + mime: string +} + +/** What came of staging files from disk: the ones staged, and why the others weren't. */ +export interface StagedFiles { + staged: StagedFile[] + refused: string[] +} + /** What the UI says about a file it sends, besides the bytes. */ export interface NewFile { name: string @@ -202,6 +216,16 @@ export const api = { invoke('send_file', bytes, { headers: { 'x-tightbeam-file': asciiJson({ ...file, text, reply_to: replyTo ?? null }) }, }), + /** Stages files dropped on the window. */ + stagePaths: (paths: string[]) => invoke('stage_paths', { paths }), + /** Asks which files to send, then stages them. */ + pickFiles: () => invoke('pick_files'), + /** Sends a staged file, by path. */ + sendStaged: (id: number, file: NewFile, text: string, replyTo?: Ref) => + invoke('send_staged', { id, details: { ...file, text, reply_to: replyTo ?? null } }), + unstage: (id: number) => invoke('unstage', { id }), + /** A staged picture's bytes, to make its preview. */ + stagedPicture: (id: number) => invoke('staged_picture', { id }), /** Where the webview loads a file that's here. */ fileUrl: (hash: string) => convertFileSrc(hash, 'tbfile'), /** Opens a picture in its default app. */ diff --git a/ui/src/components/Chat.tsx b/ui/src/components/Chat.tsx index 4a512be..90735af 100644 --- a/ui/src/components/Chat.tsx +++ b/ui/src/components/Chat.tsx @@ -1,8 +1,9 @@ import { shallow, useSelector } from '@tanstack/react-store' import { useVirtualizer } from '@tanstack/react-virtual' +import { getCurrentWebview } from '@tauri-apps/api/webview' import { EllipsisIcon, - ImagePlusIcon, + PaperclipIcon, PencilIcon, ReplyIcon, SearchIcon, @@ -57,11 +58,13 @@ import { clearHistory, loadOlder, openSearch, + pickFiles, reveal, run, setDeleting, setEditing, setReplyingTo, + stageDropped, stageFiles, store, unstageFile, @@ -74,9 +77,6 @@ const EMOJI = ['👍', '❤️', '😂', '😮', '😢', '🎉'] /** While typing, tell the peer this often. Their "typing…" lapses a little after. */ const TYPING_EVERY_MS = 2500 -/** Whether something dragged over the window is files. */ -const carriesFiles = (e: React.DragEvent) => e.dataTransfer.types.includes('Files') - /** Paired: the conversation. */ export function Chat() { // Ctrl+F (Cmd+F on macOS) opens search. @@ -91,31 +91,24 @@ export function Chat() { return () => window.removeEventListener('keydown', onKey) }, []) - // Pictures dragged onto the window go in the message box. + // Files dragged onto the window go in the message box. Tauri hands over their paths, + // so they're sent from disk, not read into the webview. const [dragging, setDragging] = useState(false) + useEffect(() => { + const stop = getCurrentWebview().onDragDropEvent(({ payload }) => { + if (payload.type === 'enter' || payload.type === 'over') setDragging(true) + else if (payload.type === 'leave') setDragging(false) + else { + setDragging(false) + if (payload.paths.length) void stageDropped(payload.paths) + } + }) + return () => void stop.then((unlisten) => unlisten()) + }, []) return ( -
{ - if (!carriesFiles(e)) return - e.preventDefault() - e.dataTransfer.dropEffect = 'copy' - setDragging(true) - }} - onDragLeave={(e) => { - // Leaving the window, not just moving between the elements inside it. - const to = e.relatedTarget - if (!(to instanceof Node && e.currentTarget.contains(to))) setDragging(false) - }} - onDrop={(e) => { - if (!carriesFiles(e)) return - e.preventDefault() - setDragging(false) - void stageFiles([...e.dataTransfer.files]) - }} - > +
@@ -127,7 +120,7 @@ export function Chat() { {dragging && (
- Drop pictures to send + Drop files to send
)}
@@ -744,7 +737,6 @@ function Composer() { const [clearing, setClearing] = useState(false) const [sending, setSending] = useState(false) const textRef = useRef(null) - const pickerRef = useRef(null) const typingSentRef = useRef(0) const { scrollToEnd } = useMessageScroller() const { replyingTo, editing, peerName, myId, away, dndUntil, staged } = useSelector( @@ -867,10 +859,13 @@ function Composer() { for (const [i, s] of store.state.staged.entries()) { const first = i === 0 const to = first && reply ? { author: reply.author, seq: reply.seq } : undefined + const withText = first ? caption : '' const sent = await run( - s.file - .arrayBuffer() - .then((bytes) => api.sendFile(bytes, s.details, first ? caption : '', to)), + 'pasted' in s.source + ? s.source.pasted + .arrayBuffer() + .then((bytes) => api.sendFile(bytes, s.details, withText, to)) + : api.sendStaged(s.source.disk, s.details, withText, to), ) if (!sent) { if (first) { @@ -1049,23 +1044,12 @@ function Composer() { type="button" variant="ghost" size="icon-lg" - aria-label="Add pictures" - title="Add pictures (or paste, or drop them here)" - onClick={() => pickerRef.current?.click()} + aria-label="Attach files" + title="Attach files (or drop them here, or paste a picture)" + onClick={() => void pickFiles()} > - + - { - void stageFiles([...(e.target.files ?? [])]) - e.target.value = '' // so the same picture can be chosen again - }} - /> )}