diff --git a/CHANGELOG.md b/CHANGELOG.md index 173278f..d1b817f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,13 @@ Changes people using Tightbeam will notice. Add a line under **Unreleased** as t ## Unreleased +- Send any file, not just pictures: pick files with the paperclip, or drop them on the window. Files up to 1 GB go straight from disk, so big ones don't slow the app down. Changing or moving the original afterwards doesn't affect what was sent. The other side needs version 0.7 or later. +- More kinds of received files open in their app with one click: PDFs, text and Office documents, audio and video, as well as pictures. Programs, scripts, web pages and archives can only be shown in their folder. - After unpairing and pairing with someone new, they get only the messages written from then on. Before, they also received every message sent to the previous person. Editing or deleting those older messages stays on your computer. - Messages from someone you were paired with before keep their name, instead of showing the name of whoever you're paired with now. - Clicking the quote in a reply jumps to the original message even when it's further back than the history loaded so far. Before, it did nothing until you'd scrolled back that far. - A reply quoting a vanishing message shows "Message vanished" as soon as it vanishes, instead of "Deleted message" until the app restarts. +- A problem with what you're sending, like a file that's too big or a message that didn't go, shows just above the message box instead of at the top of the window. ## 0.7.0 — 2026-11-24 diff --git a/README.md b/README.md index 2d3ffe4..5f749fc 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Windows and macOS. Rust + [Tauri](https://tauri.app) for the app, [iroh](https:/ **Commands:** type `/` in the message box for a list. `/clear` erases the conversation on this computer; the other person keeps their copy, and your messages that haven't reached them yet stay so they still get delivered. The erased messages are overwritten in the database file, not just marked free. `/nudge` shakes the other person's window and plays a sound, or shows a notification if Tightbeam is in their tray. `/away lunch` shows the other person "Away · lunch" (the note is optional) until `/back` or your next message. After 10 minutes without keyboard or mouse input anywhere on the computer, you show as away until you're back at it. `/dnd 2h` turns on do not disturb: no notifications or nudge sounds, the other person sees it, and their nudges are paused; `/dnd off` ends it early. `/vanish 1m the code is 4321` sends a message that erases itself from both computers a minute after the other person sees it (both apps need 0.6 or later). `/me waves` shows "Alex waves"; `/shrug`, `/tableflip` and `/unflip` add the face to your message. `/status` shows the connection's address and round-trip time, and both apps' versions. To send a message that starts with a slash, begin it with `//`. -**Pictures:** paste a screenshot, drop pictures on the window, or use the picture button beside the message box; what you type goes with them as a caption. Each picture can be up to 1 GB. The message syncs like any other, carrying the picture's name, size, BLAKE3 hash and a tiny preview, shown blurred until the picture arrives. The picture itself travels on a QUIC stream of its own, so a big one never holds up messages: the receiving app asks for it, checks the whole file against the hash, and keeps it in the data folder under `files/`. A transfer that breaks off picks up where it stopped. Click a picture to see it full size, open it in its default app, save a copy somewhere else, or show it in its folder. The data folder is the app's own: a file moved out of it, or changed in it, is fetched again from the other computer (it's checked against its hash before it's sent), or shows as no longer available if neither has it intact. One this computer can't display, such as HEIC on Windows, shows as a file. Deleting the message or `/clear` removes the file once no message has it, though as an ordinary file delete: unlike message text, it isn't overwritten on disk. Both apps need 0.7 or later. +**Files and pictures:** pick files with the paperclip beside the message box, drop them on the window, or paste a screenshot; what you type goes with them as a caption. Each file can be up to 1 GB. Picked and dropped files go straight from disk by path, never through the webview, and the app keeps its own copy, so changing or moving the original afterwards doesn't affect what was sent. The message syncs like any other, carrying the file's name, size, type and BLAKE3 hash, and for a picture its dimensions and a tiny preview, shown blurred until the picture arrives. The file itself travels on a QUIC stream of its own, so a big one never holds up messages: the receiving app asks for it, checks the whole file against the hash, and keeps it in the data folder under `files/`. A transfer that breaks off picks up where it stopped. Click a picture to see it full size. Pictures, PDFs, text and Office documents, audio and video open in their default app; anything else, such as a program, a script, a web page or an archive, can only be shown in its folder. Any file can be saved as a copy somewhere else. The data folder is the app's own: a file moved out of it, or changed in it, is fetched again from the other computer (it's checked against its hash before it's sent), or shows as no longer available if neither has it intact. One this computer can't display, such as HEIC on Windows, shows as a file. Deleting the message or `/clear` removes the file once no message has it, though as an ordinary file delete: unlike message text, it isn't overwritten on disk. Both apps need 0.7 or later. **Search:** the magnifier in the header, Ctrl+F (Cmd+F on macOS), or `/search words`. Each word matches words that start with it, ignoring case and accents, and a message must match them all. Matches are listed newest first; picking one scrolls to it, loading older history if needed. The index (SQLite FTS5) holds each message's current text, so edits are found by their new text and deleted or cleared messages aren't found at all. @@ -45,6 +45,7 @@ src-tauri/src/net.rs the network the engine runs on: iroh and mDNS, or in m src-tauri/src/clock.rs wall-clock time, which tests move with tokio's paused clock src-tauri/src/entry.rs log entries: each kind, its wire form, admission of a peer's src-tauri/src/db.rs SQLite storage and history paging +src-tauri/src/files.rs the file store: files in the data folder, what's kept, what may open src-tauri/src/lib.rs Tauri commands and events src-tauri/src/desktop.rs tray, unread count, notifications src-tauri/src/updates.rs automatic updates diff --git a/ROADMAP.md b/ROADMAP.md index 0edc2aa..914d627 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -55,7 +55,8 @@ New frame types or message kinds. The per-author append-only log stays as it is: ## 3. Bigger pieces - [x] **Pictures**, including pasted screenshots. `Msg` carries a `file` (BLAKE3 hash, name, size, type, and for images the size and a tiny preview), sent only to peers whose `Hello` lists the `files` feature. The bytes go on QUIC streams of their own: the receiver asks for a file from the first byte it lacks, checks the whole file against the hash, and keeps it as `files//` in the data folder, with a `files` table saying which have arrived. Written directly rather than with `iroh-blobs`, which would bring a second store whose deletes we wouldn't control. Files go when no message has them any more. The webview loads them through a `tbfile` protocol that serves only those, uncached. -- [ ] **Any file.** The transfer already handles any file; the UI only offers pictures. A file picker and drop for other kinds, sent by path rather than through the webview, so a big one isn't read into memory. Received files open only if they're a known safe kind; anything else is "Show in folder". +- [x] **Any file.** A file picker (the paperclip) and drag and drop with paths (Tauri's), so files go from disk by path and a big one is never read into the webview. The store copies a sent file in while hashing it. A staged picture's preview is made from its bytes, which Rust hands over only for pictures up to 50 MB. Pasting still goes as bytes, up to 100 MB. Received files open only if they're a known safe kind (`files::may_open`); anything else is "Show in folder". +- [ ] **Remove from this computer.** An action on a received file that frees its space on this side only: the message stays and shows "Removed from this computer", and it isn't fetched again. Also a deliberate way to take a file out of the data folder, which today makes the app fetch it again. Nothing is cleared automatically, and never on the other side. - [x] **Automatic builds.** GitHub Actions (free for public repos, macOS included): - `ci.yml` runs the UI checks, plus rustfmt, clippy and the tests on Windows and macOS, for each push to main and each pull request. - `release.yml` runs CI on the tagged commit, then builds the Windows installer and the macOS `.dmg` into a draft release when a `v*` tag is pushed (`scripts/release.ps1`). The release text comes from `CHANGELOG.md`. diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index 6f771e1..a2bc135 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}, }; @@ -137,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, @@ -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, @@ -540,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!( @@ -555,26 +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.")?; - 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)?; - } + 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) }) } @@ -585,23 +591,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 +1362,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 +1424,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 +1460,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 +1640,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 { @@ -1763,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. @@ -1924,22 +1843,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..c52f9c4 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; @@ -966,3 +969,38 @@ 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)); + assert!(file.openable, "a PDF opens in its app"); + + // 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/db.rs b/src-tauri/src/db.rs index a0b1d44..eb05589 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -28,8 +28,8 @@ use anyhow::{Result, bail}; use rusqlite::{Connection, OptionalExtension, params}; use serde::{Deserialize, Serialize}; -use crate::clock::Clock; use crate::entry::{DELETE, EDIT, Entry, FileInfo, Kind, MESSAGE, REACTION, Ref}; +use crate::{clock::Clock, files::may_open}; /// Where a message's file has got to on this computer. #[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] @@ -49,6 +49,9 @@ pub struct Attachment { #[serde(flatten)] pub info: FileInfo, pub state: FileState, + /// Whether it may open in its default app (`files::may_open`); if not, it can only be + /// shown in its folder. + pub openable: bool, } /// A file that's here: its name in the data folder, its type, and its size in bytes. @@ -774,7 +777,10 @@ impl Db { None => None, }; let file = match file { - Some(info) => Some(Attachment { state: self.file_state(&info.hash)?, info }), + Some(info) => { + let (state, openable) = (self.file_state(&info.hash)?, may_open(&info.name)); + Some(Attachment { info, state, openable }) + } None => None, }; let reactions = self.reactions(&at)?; diff --git a/src-tauri/src/files.rs b/src-tauri/src/files.rs new file mode 100644 index 0000000..01c84dd --- /dev/null +++ b/src-tauri/src/files.rs @@ -0,0 +1,588 @@ +//! 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::{ + 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, 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, +} + +/// 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 { + /// 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 { + 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 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. + 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 }) + } +} + +/// 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", + } +} + +/// Whether a file may open in its default app, by the end of its name. Opening runs that +/// app on it, so this is an allow-list: pictures, documents without macros, audio and +/// video. Anything else (programs, scripts, shortcuts, web pages, SVG, Office files with +/// macros, disk images, archives) can only be shown in its folder. +pub(crate) fn may_open(name: &str) -> bool { + const OPENABLE: &[&str] = &[ + // Pictures. + "jpg", "jpeg", "png", "gif", "webp", "avif", "bmp", "heic", "heif", "tif", "tiff", + // Documents. + "pdf", "txt", "md", "csv", "docx", "xlsx", "pptx", "odt", "ods", "odp", + // Audio. + "mp3", "m4a", "aac", "wav", "flac", "ogg", // Video. + "mp4", "m4v", "mov", "webm", "mkv", + ]; + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + OPENABLE.contains(&ext.as_str()) +} + +/// 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)?)?; + 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_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 only_known_kinds_open() { + for name in ["beach.JPG", "Report.pdf", "notes.md", "budget.xlsx", "song.flac", "clip.mov"] + { + assert!(may_open(name), "{name}"); + } + let unsafe_kinds = [ + "setup.exe", + "install.msi", + "run.bat", + "script.ps1", + "link.lnk", + "site.url", + "page.html", + "logo.svg", + "macros.docm", + "sheet.xlsm", + "disk.iso", + "disk.dmg", + "archive.zip", + "Tool.app", + "go.command", + "go.sh", + "app.jar", + "no extension", + "trick.pdf.exe", + ]; + for name in unsafe_kinds { + assert!(!may_open(name), "{name}"); + } + } + + #[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"); + 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..a5e0659 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,16 +3,21 @@ mod clock; pub mod db; mod desktop; pub mod entry; +mod files; 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, @@ -113,18 +118,155 @@ async fn send_file( .map_err(err) } -/// Kinds of file that open in their default app. Anything else, like a program, can only -/// be shown in its folder. -const OPENABLE: &[&str] = - &["jpg", "jpeg", "png", "gif", "webp", "avif", "bmp", "heic", "heif", "tif", "tiff"]; +/// 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, +} -/// Opens a received or sent picture in its default app. +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() +} + +/// Opens a received or sent file in its default app, if it's a kind that may open +/// (`files::may_open`). #[tauri::command] fn open_file(app: tauri::AppHandle, core: CoreState, hash: String) -> Result<(), String> { let (path, _) = core.file(&hash).map_err(err)?.ok_or(MISSING)?; - let ext = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_lowercase(); - if !OPENABLE.contains(&ext.as_str()) { - return Err("Only pictures can be opened from here. Use Show in folder.".into()); + let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default(); + if !files::may_open(&name) { + return Err("That kind of file can't be opened from here. Use Show in folder.".into()); } app.opener().open_path(path.to_string_lossy(), None::<&str>).map_err(err) } @@ -171,38 +313,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()), @@ -402,6 +523,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 { @@ -448,6 +570,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..57e7a44 100644 --- a/ui/src/api.ts +++ b/ui/src/api.ts @@ -94,6 +94,22 @@ export interface FileInfo { /** A message's file on this computer: still to come, here, or gone from the sender. */ export interface Attachment extends FileInfo { state: 'pending' | 'done' | 'gone' + /** It may open in its default app; if not, it can only be shown in its folder. */ + openable: boolean +} + +/** 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. */ @@ -202,6 +218,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..be77a81 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, @@ -17,6 +18,7 @@ import { api, type Message as ChatMessage, type Quote, type Reaction } from '@/a import { type Command, parse, suggest } from '@/commands' import { describeFile, FileView, StagedFiles, Viewer } from '@/components/Files' import { Linkified } from '@/components/Linkified' +import { NoteCard } from '@/components/Notice' import { SearchBar, SearchResults } from '@/components/Search' import { SettingsMenu } from '@/components/SettingsMenu' import { StatusDialog } from '@/components/StatusDialog' @@ -57,11 +59,14 @@ import { clearHistory, loadOlder, openSearch, + pickFiles, reveal, run, setDeleting, setEditing, + setHint, setReplyingTo, + stageDropped, stageFiles, store, unstageFile, @@ -74,9 +79,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 +93,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 +122,7 @@ export function Chat() { {dragging && (
- Drop pictures to send + Drop files to send
)}
@@ -737,19 +732,18 @@ function fit(el: HTMLTextAreaElement) { function Composer() { const [text, setText] = useState('') - const [hint, setHint] = useState(null) // Which suggestion is highlighted, and whether Escape closed the list. const [active, setActive] = useState(0) const [dismissed, setDismissed] = useState(false) 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( + const { replyingTo, editing, peerName, myId, away, dndUntil, staged, hint } = useSelector( store, (s) => ({ + hint: s.hint, replyingTo: s.replyingTo, editing: s.editing, peerName: s.status?.peer?.name || 'them', @@ -765,6 +759,9 @@ function Composer() { // What was in the box before editing started; it comes back when editing ends. const draftRef = useRef(null) + // A hint is about this message box; it doesn't outlive it. + useEffect(() => () => setHint(null), []) + // Choosing Reply on a message: start typing straight away. useEffect(() => { if (replyingTo) textRef.current?.focus() @@ -838,6 +835,7 @@ function Composer() { } const saved = await run( api.editMessage({ author: of.author, seq: of.seq }, value).then(() => true), + 'composer', ) if (saved) setEditing(null) } @@ -867,10 +865,14 @@ 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), + 'composer', ) if (!sent) { if (first) { @@ -893,7 +895,7 @@ function Composer() { setReplyingTo(null) typingSentRef.current = 0 // the next message signals typing right away const to = reply ? { author: reply.author, seq: reply.seq } : undefined - const sent = await run(api.sendMessage(value, to, vanish)) + const sent = await run(api.sendMessage(value, to, vanish), 'composer') if (sent) { addMessage(sent) scrollToEnd({ behavior: 'smooth' }) @@ -968,9 +970,12 @@ function Composer() { /> )} {hint && ( -

+ setHint(null)} + > {hint} -

+ )} {dnd && dndUntil !== null && (
@@ -1049,23 +1054,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 - }} - /> )}