An open-source cross-platform alternative to AirDrop
feat(cli): send text with --text (#3538)
Tien Do Nam07c15bdb339a
diff --git a/README.md b/README.mdindex 3f427a26..772c49ce 100644--- a/README.md+++ b/README.md@@ -189,6 +189,17 @@ localsend-cli send --to 192.168.27.26 report.pdfAn alias must uniquely identify a discovered device. An IP address is probed directlyover HTTPS on LocalSend's default port (`53317`).+To send a text message instead of files, use `--text` together with `--to`.+Pass `-` to read the text from stdin:++```shell+localsend-cli send --to "Cute Tomato" --text "https://localsend.org"+echo "Hello" | localsend-cli send --to "Cute Tomato" --text -+```++A single trailing line break is dropped from stdin. Text longer than 64 KB is sent as+a `.txt` file instead. Stdin must be UTF-8 and at most 16 MB; send other data as a file.+Directories are collected recursively. Their selected root names and nested pathsare preserved on the receiver. Empty directories are not sent because LocalSendtransfers file entries rather than directory entries.diff --git a/cli/build.rs b/cli/build.rsindex df70d9df..7149bdaa 100644--- a/cli/build.rs+++ b/cli/build.rs@@ -12,4 +12,4 @@ fn main() {// FileVersion/ProductVersion are derived from CARGO_PKG_VERSION automatically.res.compile().expect("failed to compile Windows resources");}-}\ No newline at end of file+}diff --git a/cli/src/app/headless.rs b/cli/src/app/headless.rsindex c2ef9da2..065e7a62 100644--- a/cli/src/app/headless.rs+++ b/cli/src/app/headless.rs@@ -1,9 +1,9 @@-//! The headless `send --to` mode: discover the destination, send the files,-//! exit with the transfer result. There is no keyboard and no overlay — only+//! The headless `send --to` mode: discover the destination, send the files+//! or the text message, exit with the transfer result. There is no keyboard and no overlay — only//! the network events a send needs are handled, and incoming transfer//! requests are declined.-use super::sending::{self, SendState};+use super::sending::{self, Payload, SendState};use super::status;use super::target::TargetSelector;use super::{AppEvent, Network, discovery, spawn_staged_discovery, start_network, stop_network};@@ -13,7 +13,6 @@ use crate::ui::{Category, Ui};use crate::util;use localsend::discovery::{DiscoveryEvent, DiscoveryHandle};use localsend::http::server::v2::{PrepareUploadDecisionV2, ServerEventV2};-use std::path::PathBuf;use std::sync::Arc;use std::sync::atomic::Ordering;use std::time::Duration;@@ -22,7 +21,7 @@ use tokio::sync::mpsc;pub(super) async fn run(mut storage: Repository,target: TargetSelector,- paths: Vec<PathBuf>,+ payload: Payload,) -> anyhow::Result<()> {let mut ui = Ui::new();let identity = storage.identity.clone();@@ -73,14 +72,7 @@ pub(super) async fn run(AppEvent::Tick => render_progress(&mut ui, &mut send),AppEvent::Log { category, text } => ui.log(category, &text),AppEvent::DiscoveryFinished => {- match start_send(- &mut ui,- &storage,- &discovery,- &target,- paths.clone(),- &events_tx,- ) {+ match start_send(&mut ui, &storage, &discovery, &target, &payload, &events_tx) {Ok(state) => send = Some(state),Err(reason) => break Err(anyhow::anyhow!(reason)),}@@ -117,20 +109,29 @@ fn start_send(storage: &Repository,discovery: &DiscoveryHandle,target: &TargetSelector,- paths: Vec<PathBuf>,+ payload: &Payload,events_tx: &mpsc::Sender<AppEvent>,) -> Result<SendState, String> {let fingerprint = target.resolve(&discovery.devices())?;let device = discovery.device_by_fingerprint(&fingerprint).ok_or_else(|| format!("Destination {target} was not discovered"))?;- sending::spawn_send(- ui,- storage.identity.clone(),- device,- paths,- events_tx.clone(),- )+ match payload {+ Payload::Files(paths) => sending::spawn_send(+ ui,+ storage.identity.clone(),+ device,+ paths.clone(),+ events_tx.clone(),+ ),+ Payload::Text(text) => sending::spawn_send_text(+ ui,+ storage.identity.clone(),+ device,+ text.clone(),+ events_tx.clone(),+ ),+ }}fn handle_server_event(diff --git a/cli/src/app/mod.rs b/cli/src/app/mod.rsindex c505a306..6cd09718 100644--- a/cli/src/app/mod.rs+++ b/cli/src/app/mod.rs@@ -27,7 +27,7 @@ use localsend::model::discovery::ProtocolType;use localsend::multicast::{DEFAULT_MULTICAST_GROUP, DEFAULT_MULTICAST_GROUP_V6, DEFAULT_PORT};use localsend::util::interface::{InterfaceFilter, local_interface_addresses};use receive::{Answer, PendingReceive, ReceiveSession};-use sending::SendState;+use sending::{Payload, SendState};use std::path::PathBuf;use std::sync::Arc;use std::time::Duration;@@ -75,24 +75,34 @@ pub enum AppEvent {}pub async fn run(args: Args) -> anyhow::Result<()> {- let (preselected, target) = match &args.command {- Some(Command::Send { to, paths }) => (- paths.clone(),- to.as_deref().map(TargetSelector::parse).transpose()?,- ),- None => (Vec::new(), None),+ let (payload, target) = match &args.command {+ Some(Command::Send { to, text, paths }) => {+ let payload = match text {+ Some(text) => Payload::Text(sending::read_text(text)?),+ None => Payload::Files(paths.clone()),+ };+ (+ payload,+ to.as_deref().map(TargetSelector::parse).transpose()?,+ )+ }+ None => (Payload::Files(Vec::new()), None),};- for path in &preselected {- anyhow::ensure!(- path.is_file() || path.is_dir(),- "Not a file or directory: {}",- path.display()- );+ if let Payload::Files(paths) = &payload {+ for path in paths {+ anyhow::ensure!(+ path.is_file() || path.is_dir(),+ "Not a file or directory: {}",+ path.display()+ );+ }}let storage = storage::Repository::load(&args)?;- match target {- Some(target) => headless::run(storage, target, preselected).await,- None => run_interactive(storage, preselected).await,+ match (target, payload) {+ (Some(target), payload) => headless::run(storage, target, payload).await,+ (None, Payload::Files(preselected)) => run_interactive(storage, preselected).await,+ // clap only accepts `--text` together with `--to`.+ (None, Payload::Text(_)) => unreachable!("--text requires --to"),}}diff --git a/cli/src/app/receive.rs b/cli/src/app/receive.rsindex 65166c22..6180148e 100644--- a/cli/src/app/receive.rs+++ b/cli/src/app/receive.rs@@ -137,7 +137,10 @@ impl App {let _ = decision_tx.send(PrepareUploadDecisionV2::Accept(HashSet::new()));self.ui.log(Category::Receive,- &format!("{alias}: Message received\n{}", sanitize::multi_line(message)),+ &format!(+ "{alias}: Message received\n{}",+ sanitize::multi_line(message)+ ),);return;}diff --git a/cli/src/app/sending.rs b/cli/src/app/sending.rsindex 36635496..ce5ad528 100644--- a/cli/src/app/sending.rs+++ b/cli/src/app/sending.rs@@ -4,14 +4,16 @@use super::{App, AppEvent, Overlay};use crate::picker::{Picker, PickerOutcome, PickerTarget};use crate::sanitize;-use crate::send_task;+use crate::send_task::{self, FileSource};use crate::storage::Identity;use crate::ui::{Category, Ui};use crate::util::SpeedMeter;+use bytes::Bytes;use crossterm::event::KeyEvent;use localsend::discovery::StatefulDevice;use localsend::model::transfer::{FileDto, FileMetadata};use std::collections::HashMap;+use std::io::{IsTerminal, Read};use std::path::{Component, Path, PathBuf};use std::sync::Arc;use std::sync::atomic::AtomicU64;@@ -21,6 +23,102 @@ use walkdir::WalkDir;type CollectedPath = Result<(PathBuf, String), (PathBuf, String)>;+/// Transfer metadata keyed by file ID, the content under the same IDs, and+/// the total byte count.+type Transfer = (HashMap<String, FileDto>, HashMap<String, FileSource>, u64);++/// Largest text sent as a message (embedded in the request as a preview).+/// Longer text is sent as a `.txt` file instead.+const MAX_MESSAGE_BYTES: usize = 64_000;++/// Largest input read from stdin, which is held in memory until sent.+const MAX_STDIN_BYTES: u64 = 16_000_000;++/// What the headless mode sends.+pub(super) enum Payload {+ Files(Vec<PathBuf>),+ Text(Bytes),+}++/// Returns the `--text` argument, or stdin when it is `-`. A single trailing+/// line break is dropped from stdin, like shell command substitution does, so+/// that `echo hi | localsend-cli send --text -` sends "hi".+pub(super) fn read_text(arg: &str) -> anyhow::Result<Bytes> {+ let text = match arg {+ "-" => {+ let stdin = std::io::stdin();+ if stdin.is_terminal() {+ eprintln!(+ "Reading the text from stdin, end it with Ctrl+D (Ctrl+Z, Enter on Windows)"+ );+ }+ read_stdin(stdin.lock())?+ }+ text => text.as_bytes().to_vec(),+ };+ anyhow::ensure!(!text.is_empty(), "Nothing to send: the text is empty");+ Ok(text.into())+}++fn read_stdin(reader: impl Read) -> anyhow::Result<Vec<u8>> {+ let mut text = Vec::new();+ reader.take(MAX_STDIN_BYTES + 1).read_to_end(&mut text)?;+ anyhow::ensure!(+ text.len() as u64 <= MAX_STDIN_BYTES,+ "Input is longer than {} MB; save it to a file and send the file instead",+ MAX_STDIN_BYTES / 1_000_000+ );+ anyhow::ensure!(+ std::str::from_utf8(&text).is_ok(),+ "Input is not UTF-8 text; save it to a file and send the file instead"+ );+ strip_trailing_line_break(&mut text);+ Ok(text)+}++fn strip_trailing_line_break(text: &mut Vec<u8>) {+ if text.ends_with(b"\n") {+ text.pop();+ if text.ends_with(b"\r") {+ text.pop();+ }+ }+}++/// Builds the transfer of a text: a message carried by the preview of a+/// single text file, so the receiver has nothing left to download. Text that+/// is too long becomes a `.txt` file instead.+///+/// `text` is UTF-8, as checked by [`read_text`].+fn text_transfer(ui: &mut Ui, text: Bytes) -> Transfer {+ let id = Uuid::new_v4().to_string();+ let size = text.len() as u64;+ let preview = match text.len() <= MAX_MESSAGE_BYTES {+ true => Some(String::from_utf8_lossy(&text).into_owned()),+ false => {+ ui.log(+ Category::Send,+ "Text too long for a message, sending it as a file",+ );+ None+ }+ };+ let file = FileDto {+ id: id.clone(),+ file_name: format!("{id}.txt"),+ size,+ file_type: "text/plain".to_string(),+ sha256: None,+ preview,+ metadata: None,+ };+ (+ HashMap::from([(id.clone(), file)]),+ HashMap::from([(id, FileSource::Bytes(text))]),+ size,+ )+}+/// An outgoing transfer driven by the send task.pub(super) struct SendState {pub(super) session_id: Option<String>,@@ -116,22 +214,59 @@ pub(super) fn spawn_send(picked: Vec<PathBuf>,events_tx: mpsc::Sender<AppEvent>,) -> Result<SendState, String> {- let Some(host) = device- .get_best_channel()- .and_then(|channel| channel.http())- .map(|http| http.host.clone())- else {- return Err(format!(- "{}: No dialable address",- sanitize::single_line(&device.device.alias)- ));- };-+ let host = dialable_host(&device)?;let (files, paths, total_bytes) = collect_files(ui, picked);if files.is_empty() {return Err("No files selected".to_string());}+ let sources = paths+ .into_iter()+ .map(|(id, path)| (id, FileSource::Path(path)))+ .collect();+ spawn_transfer(+ identity,+ device,+ host,+ (files, sources, total_bytes),+ events_tx,+ )+}++/// Spawns the send task delivering `text` to `device`, as a message when it+/// fits. Returns the state tracking the transfer, or the reason the transfer+/// could not start.+pub(super) fn spawn_send_text(+ ui: &mut Ui,+ identity: Arc<Identity>,+ device: StatefulDevice,+ text: Bytes,+ events_tx: mpsc::Sender<AppEvent>,+) -> Result<SendState, String> {+ let host = dialable_host(&device)?;+ let transfer = text_transfer(ui, text);+ spawn_transfer(identity, device, host, transfer, events_tx)+}+fn dialable_host(device: &StatefulDevice) -> Result<String, String> {+ device+ .get_best_channel()+ .and_then(|channel| channel.http())+ .map(|http| http.host.clone())+ .ok_or_else(|| {+ format!(+ "{}: No dialable address",+ sanitize::single_line(&device.device.alias)+ )+ })+}++fn spawn_transfer(+ identity: Arc<Identity>,+ device: StatefulDevice,+ host: String,+ (files, sources, total_bytes): Transfer,+ events_tx: mpsc::Sender<AppEvent>,+) -> Result<SendState, String> {let progress = Arc::new(AtomicU64::new(0));let cancel = send_task::SendCancel::new();let state = SendState {@@ -144,7 +279,7 @@ pub(super) fn spawn_send(speed: SpeedMeter::new(),};tokio::spawn(send_task::run_send(- identity, device, files, paths, progress, cancel, events_tx,+ identity, device, files, sources, progress, cancel, events_tx,));Ok(state)}@@ -307,8 +442,14 @@ impl App {#[cfg(test)]mod tests {- use super::collect_path;+ use super::{+ MAX_MESSAGE_BYTES, MAX_STDIN_BYTES, collect_path, read_stdin, strip_trailing_line_break,+ text_transfer,+ };+ use crate::ui::Ui;+ use bytes::Bytes;use std::fs;+ use std::io::Read;use std::path::{Path, PathBuf};use std::time::{SystemTime, UNIX_EPOCH};@@ -391,4 +532,61 @@ mod tests {assert!(collect_path(&root).is_empty());}++ #[test]+ fn strips_one_trailing_line_break() {+ for (input, expected) in [+ (&b"hi\n"[..], &b"hi"[..]),+ (b"hi\r\n", b"hi"),+ (b"hi\n\n", b"hi\n"),+ (b"hi", b"hi"),+ (b"\n", b""),+ ] {+ let mut text = input.to_vec();+ strip_trailing_line_break(&mut text);+ assert_eq!(text, expected);+ }+ }++ #[test]+ fn sends_short_text_as_a_message() {+ let (files, sources, total_bytes) =+ text_transfer(&mut Ui::new(), Bytes::from_static(b"hello"));++ assert_eq!(files.len(), 1);+ let file = files.values().next().unwrap();+ assert_eq!(file.file_type, "text/plain");+ assert_eq!(file.preview.as_deref(), Some("hello"));+ assert_eq!(file.size, 5);+ assert_eq!(total_bytes, 5);+ assert!(sources.contains_key(&file.id));+ }++ #[test]+ fn sends_long_text_as_a_file() {+ let (files, _, _) = text_transfer(&mut Ui::new(), vec![b'a'; MAX_MESSAGE_BYTES + 1].into());++ let file = files.values().next().unwrap();+ assert_eq!(file.file_type, "text/plain");+ assert!(file.file_name.ends_with(".txt"));+ assert_eq!(file.preview, None);+ }++ #[test]+ fn rejects_non_utf8_stdin() {+ assert!(read_stdin(&[0xff, 0xfe, 0x00][..]).is_err());+ }++ #[test]+ fn reads_stdin_up_to_the_limit() {+ let text = read_stdin(std::io::repeat(b'a').take(MAX_STDIN_BYTES)).unwrap();++ assert_eq!(text.len() as u64, MAX_STDIN_BYTES);+ }++ #[test]+ fn rejects_stdin_over_the_limit() {+ // An endless stream must fail instead of filling memory.+ assert!(read_stdin(std::io::repeat(b'a')).is_err());+ }}diff --git a/cli/src/main.rs b/cli/src/main.rsindex d5277777..71b3bb65 100644--- a/cli/src/main.rs+++ b/cli/src/main.rs@@ -14,14 +14,18 @@ use std::path::PathBuf;#[derive(Subcommand)]pub enum Command {- /// Send one or more files or directories+ /// Send one or more files or directories, or a text messageSend {/// Destination device: an exact alias or IP address#[arg(long, value_name = "TARGET")]to: Option<String>,+ /// Send this text as a message instead of files; `-` reads it from stdin+ #[arg(long, value_name = "TEXT", requires = "to", conflicts_with = "paths")]+ text: Option<String>,+/// Files or directories to send (directories are collected recursively)- #[arg(value_name = "PATH", required = true, num_args = 1..)]+ #[arg(value_name = "PATH", required_unless_present = "text", num_args = 1..)]paths: Vec<PathBuf>,},}@@ -76,7 +80,7 @@ mod tests {let args = Args::try_parse_from(["localsend-cli", "send", "one.txt", "two.txt", "backup"]).unwrap();- let Some(Command::Send { to, paths }) = args.command else {+ let Some(Command::Send { to, paths, .. }) = args.command else {panic!("expected the send command");};assert_eq!(to, None);@@ -96,7 +100,7 @@ mod tests {Args::try_parse_from(["localsend-cli", "send", "--to", "Cute Tomato", "one.txt"]).unwrap();- let Some(Command::Send { to, paths }) = args.command else {+ let Some(Command::Send { to, paths, .. }) = args.command else {panic!("expected the send command");};assert_eq!(to.as_deref(), Some("Cute Tomato"));@@ -109,7 +113,7 @@ mod tests {Args::try_parse_from(["localsend-cli", "send", "--to", "192.168.27.26", "one.txt"]).unwrap();- let Some(Command::Send { to, paths }) = args.command else {+ let Some(Command::Send { to, paths, .. }) = args.command else {panic!("expected the send command");};assert_eq!(to.as_deref(), Some("192.168.27.26"));@@ -121,6 +125,41 @@ mod tests {assert!(Args::try_parse_from(["localsend-cli", "send"]).is_err());}+ #[test]+ fn accepts_a_text_message() {+ let args =+ Args::try_parse_from(["localsend-cli", "send", "--to", "Phone", "--text", "hello"])+ .unwrap();++ let Some(Command::Send { to, text, paths }) = args.command else {+ panic!("expected the send command");+ };+ assert_eq!(to.as_deref(), Some("Phone"));+ assert_eq!(text.as_deref(), Some("hello"));+ assert!(paths.is_empty());+ }++ #[test]+ fn rejects_text_together_with_paths() {+ assert!(+ Args::try_parse_from([+ "localsend-cli",+ "send",+ "--to",+ "Phone",+ "--text",+ "hello",+ "one.txt"+ ])+ .is_err()+ );+ }++ #[test]+ fn requires_a_destination_for_text() {+ assert!(Args::try_parse_from(["localsend-cli", "send", "--text", "hello"]).is_err());+ }+#[test]fn accepts_interactive_mode_without_a_command() {let args = Args::try_parse_from(["localsend-cli"]).unwrap();diff --git a/cli/src/send_task.rs b/cli/src/send_task.rsindex b119e21d..6165460d 100644--- a/cli/src/send_task.rs+++ b/cli/src/send_task.rs@@ -20,6 +20,12 @@ use std::time::Instant;use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;+/// Where the content of an outgoing file comes from.+pub enum FileSource {+ Path(PathBuf),+ Bytes(Bytes),+}+/// Cancellation state of a send, shared between the app and the send task.#[derive(Clone)]pub struct SendCancel {@@ -42,19 +48,21 @@ impl SendCancel {/// Sends the given files to a device: prepare-upload, then one upload request/// per accepted file. Progress is reported through `progress` (cumulative-/// bytes over all files) and log lines through `events`.+/// bytes over all files) and log lines through `events`. A message (a single+/// file with a preview) usually ends after prepare-upload, as the receiver+/// has nothing left to download.////// Always ends by emitting [AppEvent::SendEnded] with the transfer result.pub async fn run_send(identity: Arc<Identity>,device: StatefulDevice,files: HashMap<String, FileDto>,- paths: HashMap<String, PathBuf>,+ sources: HashMap<String, FileSource>,progress: Arc<AtomicU64>,cancel: SendCancel,events: mpsc::Sender<AppEvent>,) {- let success = send_inner(identity, device, files, paths, progress, cancel, &events).await;+ let success = send_inner(identity, device, files, sources, progress, cancel, &events).await;let _ = events.send(AppEvent::SendEnded { success }).await;}@@ -62,7 +70,7 @@ async fn send_inner(identity: Arc<Identity>,device: StatefulDevice,files: HashMap<String, FileDto>,- paths: HashMap<String, PathBuf>,+ mut sources: HashMap<String, FileSource>,progress: Arc<AtomicU64>,cancel: SendCancel,events: &mpsc::Sender<AppEvent>,@@ -106,6 +114,7 @@ async fn send_inner(};let offered = files.len();+ let is_message = offered == 1 && files.values().all(|file| file.preview.is_some());let payload = PrepareUploadRequestDtoV2 {info: identity.register_dto(),files: files.clone(),@@ -150,9 +159,24 @@ async fn send_inner(};let Some(response) = prepared.response else {+ if is_message {+ log(format!("{alias}: Message sent")).await;+ return true;+ }log(format!("{alias}: all files were declined")).await;return false;};+ if prepared.status_code != 200+ || response.session_id.is_empty()+ || response.files.is_empty()+ || response+ .files+ .iter()+ .any(|(id, token)| !files.contains_key(id) || token.is_empty())+ {+ log(format!("{alias}: Invalid prepare-upload response")).await;+ return false;+ }let accepted_bytes: u64 = response.files@@ -184,12 +208,20 @@ async fn send_inner(for file_id in file_ids {let token = &response.files[file_id];let file = &files[file_id];- let path = paths[file_id].clone();+ let content = match sources.remove(file_id.as_str()) {+ Some(FileSource::Path(path)) => FileContent::Path(path),+ Some(FileSource::Bytes(bytes)) => {+ let (tx, rx) = mpsc::channel(1);+ let _ = tx.try_send(bytes);+ FileContent::Stream(rx)+ }+ None => unreachable!("every offered file has a source"),+ };let body = {let progress = progress.clone();let base = sent_bytes;- upload_body(FileContent::Path(path), move |bytes_of_file| {+ upload_body(content, move |bytes_of_file| {progress.store(base + bytes_of_file, Ordering::Relaxed);})};@@ -252,6 +284,10 @@ async fn send_inner(}}+ if is_message && sent_files == 1 {+ log(format!("{alias}: Message sent")).await;+ return true;+ }log(format!("{alias}: Sent {sent_files} file{} ({}, took {})",if sent_files == 1 { "" } else { "s" },