Skip to content

An open-source cross-platform alternative to AirDrop

feat(cli): add universal send command (#3276)

Arman Yeghiazaryan0871065544d1
diff --git a/Cargo.lock b/Cargo.lock
index 030136fa..c9ca6d74 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2244,6 +2244,7 @@ dependencies = [
"toml",
"unicode-width",
"uuid",
+ "walkdir",
"winresource",
]
diff --git a/README.md b/README.md
index 5c260412..32138e2f 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,7 @@ LocalSend is a free, open-source app that allows you to securely share files and
- [How It Works](#how-it-works)
- [Dependency Hierarchy](#dependency-hierarchy)
- [Getting Started](#getting-started)
+- [Command Line Interface](#command-line-interface)
- [Contributing](#contributing)
- [Translation](#translation)
- [Bug Fixes and Improvements](#bug-fixes-and-improvements)
@@ -161,6 +162,35 @@ To compile LocalSend from the source code, follow these steps:
> To make development more consistent, LocalSend uses [fvm](https://fvm.app) to manage the project Flutter version.
> After installing `fvm`, run `fvm flutter` instead of `flutter`.
+## Command Line Interface
+
+The LocalSend CLI is a terminal client built on LocalSend Protocol v2.
+Run `localsend-cli --help` to see every available option and hotkey.
+
+Use the `send` command with one or more files, directories, or a mixture of both:
+
+```shell
+localsend-cli send report.pdf photo.jpg ./project-backup
+```
+
+The command opens the discovered-device list; select the destination interactively
+and press Enter to start the transfer.
+
+To select the destination without an interactive device list, pass its exact alias
+or IP address:
+
+```shell
+localsend-cli send --to "Cute Tomato" report.pdf
+localsend-cli send --to 192.168.27.26 report.pdf
+```
+
+An alias must uniquely identify a discovered device. An IP address is probed directly
+over HTTPS on LocalSend's default port (`53317`).
+
+Directories are collected recursively. Their selected root names and nested paths
+are preserved on the receiver. Empty directories are not sent because LocalSend
+transfers file entries rather than directory entries.
+
## Contributing
We welcome contributions from anyone interested in helping improve LocalSend. If you'd like to contribute, there are a few ways to get involved:
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index c7dc1697..bdc98cfd 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -30,6 +30,7 @@ tokio-util = { version = "0.7", features = ["rt"] }
toml = "1.1"
unicode-width = "0.2"
uuid = { version = "1", features = ["v4"] }
+walkdir = "2.5"
[build-dependencies]
winresource = "0.1"
diff --git a/cli/src/app/devices.rs b/cli/src/app/devices.rs
index 9cab0966..f57149d3 100644
--- a/cli/src/app/devices.rs
+++ b/cli/src/app/devices.rs
@@ -70,7 +70,7 @@ impl App {
}
/// Handles a key while the list is open; returns `true` when the
- /// application should quit (the list was cancelled in `--file` mode).
+ /// application should quit (the list was cancelled in `send` mode).
pub(super) fn handle_device_list_key(&mut self, key: KeyEvent) -> bool {
let Some(list) = &mut self.device_list else {
return false;
diff --git a/cli/src/app/mod.rs b/cli/src/app/mod.rs
index e28c4968..d685a82d 100644
--- a/cli/src/app/mod.rs
+++ b/cli/src/app/mod.rs
@@ -3,14 +3,15 @@ mod discovery;
mod receive;
mod sending;
mod status;
+mod target;
mod web_link;
-use crate::Args;
use crate::device_list::DeviceList;
use crate::picker::Picker;
use crate::slots::Slots;
use crate::storage;
use crate::ui::{Category, Ui};
+use crate::{Args, Command};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use localsend::discovery::{
DEFAULT_DISCOVERY_TIMEOUT, DeviceIdentity, DiscoveryConfig, DiscoveryEvent, DiscoveryHandle,
@@ -26,6 +27,7 @@ use sending::SendState;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
+use target::TargetSelector;
use tokio::sync::{mpsc, oneshot};
/// Events processed by the central application loop.
@@ -46,8 +48,11 @@ pub enum AppEvent {
accepted_bytes: u64,
},
- /// The send task ended (successfully or not).
- SendEnded,
+ /// The send task ended.
+ SendEnded { success: bool },
+
+ /// The staged startup discovery finished.
+ DiscoveryFinished,
/// A log line produced by a background task.
Log { category: Category, text: String },
@@ -90,15 +95,36 @@ struct App {
picker: Option<Picker>,
device_list: Option<DeviceList>,
- /// Files given via `-f`/`--file`; sending uses these instead of the picker.
+ /// Paths given to the `send` command; sending uses these instead of the
+ /// picker.
preselected: Vec<PathBuf>,
+ /// A destination selected by `send --to`; `None` keeps device selection
+ /// interactive.
+ target: Option<TargetSelector>,
+
+ /// Returned after network tasks have shut down when headless operation
+ /// could not complete.
+ exit_error: Option<anyhow::Error>,
+
events_tx: mpsc::Sender<AppEvent>,
}
pub async fn run(args: Args) -> anyhow::Result<()> {
- for path in &args.file {
- anyhow::ensure!(path.is_file(), "Not a file: {}", path.display());
+ 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 interactive = target.is_none();
+ for path in &preselected {
+ anyhow::ensure!(
+ path.is_file() || path.is_dir(),
+ "Not a file or directory: {}",
+ path.display()
+ );
}
let storage = storage::Repository::load(&args)?;
let identity = storage.identity.clone();
@@ -158,7 +184,12 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
let discovery = discovery.clone();
let events_tx = events_tx.clone();
let port = identity.port;
- let known_channels = storage.paired.known_http_channels();
+ let mut known_channels = storage.paired.known_http_channels();
+ if let Some(channel) = target.as_ref().and_then(TargetSelector::direct_channel)
+ && !known_channels.contains(&channel)
+ {
+ known_channels.insert(0, channel);
+ }
let interface_ips =
local_interface_addresses(&InterfaceFilter::default()).unwrap_or_default();
tokio::spawn(async move {
@@ -179,28 +210,31 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
})
.await;
}
+ let _ = events_tx.send(AppEvent::DiscoveryFinished).await;
});
}
- crossterm::terminal::enable_raw_mode()?;
-
- // Keyboard reader. The blocking thread ends with the process.
- std::thread::spawn({
- let events_tx = events_tx.clone();
- move || {
- loop {
- match crossterm::event::read() {
- Ok(Event::Key(key)) if key.kind == KeyEventKind::Press => {
- if events_tx.blocking_send(AppEvent::Key(key)).is_err() {
- return;
+ if interactive {
+ crossterm::terminal::enable_raw_mode()?;
+
+ // Keyboard reader. The blocking thread ends with the process.
+ std::thread::spawn({
+ let events_tx = events_tx.clone();
+ move || {
+ loop {
+ match crossterm::event::read() {
+ Ok(Event::Key(key)) if key.kind == KeyEventKind::Press => {
+ if events_tx.blocking_send(AppEvent::Key(key)).is_err() {
+ return;
+ }
}
+ Ok(_) => {}
+ Err(_) => return,
}
- Ok(_) => {}
- Err(_) => return,
}
}
- }
- });
+ });
+ }
let mut app = App {
ui: Ui::new(),
@@ -218,15 +252,20 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
send: None,
picker: None,
device_list: None,
- preselected: args.file,
+ preselected,
+ target,
+ exit_error: None,
events_tx: events_tx.clone(),
};
- match app.preselected.is_empty() {
- true => app
+ match (&app.target, app.preselected.is_empty()) {
+ (Some(target), _) => app
+ .ui
+ .log_plain(&format!("Discovering destination {target}...")),
+ (None, true) => app
.ui
.log_plain(&crate::banner::render(&app.storage, &app.server)),
- false => app.open_device_list(),
+ (None, false) => app.open_device_list(),
}
let mut tick = tokio::time::interval(Duration::from_millis(250));
@@ -261,14 +300,19 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
}
app.close_device_list();
app.ui.set_status(None);
- let _ = crossterm::terminal::disable_raw_mode();
+ if interactive {
+ let _ = crossterm::terminal::disable_raw_mode();
+ }
if let Some(stop_tx) = app.server_stop_tx.take() {
let _ = stop_tx.send(());
}
let _ = discovery_stop_tx.send(());
let _ = tokio::time::timeout(Duration::from_secs(1), app.server.wait_stopped()).await;
let _ = tokio::time::timeout(Duration::from_secs(1), discovery.wait_stopped()).await;
- Ok(())
+ match app.exit_error.take() {
+ Some(error) => Err(error),
+ None => Ok(()),
+ }
}
impl App {
@@ -290,12 +334,32 @@ impl App {
send.total_bytes = accepted_bytes;
}
}
- AppEvent::SendEnded => {
+ AppEvent::SendEnded { success } => {
self.send = None;
self.render_status();
- // In `--file` mode the transfer is the whole program.
+ if !success && !self.preselected.is_empty() {
+ self.exit_error = Some(anyhow::anyhow!("Transfer failed"));
+ }
+ // In `send` mode the transfer is the whole program.
return !self.preselected.is_empty();
}
+ AppEvent::DiscoveryFinished => {
+ let Some(target) = self.target.clone() else {
+ return false;
+ };
+ let fingerprint = match target.resolve(&self.discovery.devices()) {
+ Ok(fingerprint) => fingerprint,
+ Err(error) => {
+ self.exit_error = Some(anyhow::anyhow!(error));
+ return true;
+ }
+ };
+ self.start_send(&fingerprint, self.preselected.clone());
+ if self.send.is_none() {
+ self.exit_error = Some(anyhow::anyhow!("Could not start transfer to {target}"));
+ return true;
+ }
+ }
AppEvent::Log { category, text } => self.ui.log(category, &text),
}
false
@@ -344,7 +408,7 @@ impl App {
}
if self.device_list.is_some() {
self.close_device_list();
- // In `--file` mode the device list is the whole program.
+ // In `send` mode the device list is the whole program.
return !self.preselected.is_empty();
}
let mut cancelled = false;
diff --git a/cli/src/app/sending.rs b/cli/src/app/sending.rs
index ee4bce64..56bb3d2c 100644
--- a/cli/src/app/sending.rs
+++ b/cli/src/app/sending.rs
@@ -9,10 +9,13 @@ use crate::util::SpeedMeter;
use crossterm::event::KeyEvent;
use localsend::model::transfer::{FileDto, FileMetadata};
use std::collections::HashMap;
-use std::path::PathBuf;
+use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use uuid::Uuid;
+use walkdir::WalkDir;
+
+type CollectedPath = Result<(PathBuf, String), (PathBuf, String)>;
/// An outgoing transfer driven by the send task.
pub(super) struct SendState {
@@ -25,6 +28,81 @@ pub(super) struct SendState {
pub(super) speed: SpeedMeter,
}
+/// Expands a file or directory into local paths and protocol-v2 file names.
+/// Directory names include the selected root so receivers can reconstruct it.
+fn collect_path(path: &Path) -> Vec<CollectedPath> {
+ let metadata = match path.metadata() {
+ Ok(metadata) => metadata,
+ Err(error) => {
+ return vec![Err((path.to_path_buf(), error.to_string()))];
+ }
+ };
+ if metadata.is_file() {
+ let file_name = path
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "unnamed".to_string());
+ return vec![Ok((path.to_path_buf(), file_name))];
+ }
+ if !metadata.is_dir() {
+ return vec![Err((
+ path.to_path_buf(),
+ "not a regular file or directory".to_string(),
+ ))];
+ }
+
+ let root_name = path
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .or_else(|| {
+ path.canonicalize()
+ .ok()?
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ });
+ let Some(root_name) = root_name else {
+ return vec![Err((
+ path.to_path_buf(),
+ "directory has no transferable name".to_string(),
+ ))];
+ };
+
+ WalkDir::new(path)
+ .min_depth(1)
+ .sort_by_file_name()
+ .into_iter()
+ .filter_map(|entry| match entry {
+ Ok(entry) if entry.file_type().is_file() => {
+ let relative = match entry.path().strip_prefix(path) {
+ Ok(relative) => relative,
+ Err(error) => {
+ return Some(Err((entry.path().to_path_buf(), error.to_string())));
+ }
+ };
+ let file_name = std::iter::once(root_name.clone())
+ .chain(
+ relative
+ .components()
+ .filter_map(|component| match component {
+ Component::Normal(name) => {
+ Some(name.to_string_lossy().into_owned())
+ }
+ _ => None,
+ }),
+ )
+ .collect::<Vec<_>>()
+ .join("/");
+ Some(Ok((entry.path().to_path_buf(), file_name)))
+ }
+ Ok(_) => None,
+ Err(error) => Some(Err((
+ error.path().unwrap_or(path).to_path_buf(),
+ error.to_string(),
+ ))),
+ })
+ .collect()
+}
+
impl App {
pub(super) fn start_picking(&mut self, slot: u8) {
let device = self
@@ -158,9 +236,9 @@ impl App {
));
}
- /// Stats the picked paths into transfer metadata keyed by a fresh file ID,
- /// plus the paths under the same IDs and the total byte count. Entries
- /// that are not readable files are skipped with a log line.
+ /// Expands and stats picked files/directories into transfer metadata keyed
+ /// by a fresh file ID, plus paths under the same IDs and the total byte
+ /// count. Entries that are not readable files are skipped with a log line.
pub(super) fn collect_files(
&mut self,
picked: Vec<PathBuf>,
@@ -168,7 +246,17 @@ impl App {
let mut files = HashMap::new();
let mut paths = HashMap::new();
let mut total_bytes = 0u64;
- for path in picked {
+ for collected in picked.iter().flat_map(|path| collect_path(path)) {
+ let (path, file_name) = match collected {
+ Ok(collected) => collected,
+ Err((path, error)) => {
+ self.ui.log(
+ Category::Send,
+ &format!("Skipping unreadable path: {} ({error})", path.display()),
+ );
+ continue;
+ }
+ };
let metadata = match std::fs::metadata(&path) {
Ok(metadata) if metadata.is_file() => metadata,
_ => {
@@ -180,10 +268,6 @@ impl App {
}
};
let id = Uuid::new_v4().to_string();
- let file_name = path
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_else(|| "unnamed".to_string());
total_bytes += metadata.len();
files.insert(
id.clone(),
@@ -204,3 +288,91 @@ impl App {
(files, paths, total_bytes)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::collect_path;
+ use std::fs;
+ use std::path::{Path, PathBuf};
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ struct TestDirectory(PathBuf);
+
+ impl TestDirectory {
+ fn new(name: &str) -> Self {
+ let nonce = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let path = std::env::temp_dir().join(format!(
+ "localsend-cli-{name}-{}-{nonce}",
+ std::process::id()
+ ));
+ fs::create_dir_all(&path).unwrap();
+ Self(path)
+ }
+
+ fn path(&self) -> &Path {
+ &self.0
+ }
+ }
+
+ impl Drop for TestDirectory {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.0);
+ }
+ }
+
+ #[test]
+ fn keeps_an_individual_file_name() {
+ let temp = TestDirectory::new("single-file");
+ let file = temp.path().join("backup.sha256");
+ fs::write(&file, "hash").unwrap();
+
+ let collected = collect_path(&file)
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()
+ .unwrap();
+
+ assert_eq!(collected, vec![(file, "backup.sha256".to_string())]);
+ }
+
+ #[test]
+ fn expands_a_directory_with_its_root_and_relative_paths() {
+ let temp = TestDirectory::new("directory");
+ let root = temp.path().join("MLB-002");
+ let nested = root.join("checksums");
+ fs::create_dir_all(&nested).unwrap();
+ fs::write(root.join("backup.tar.zst"), "archive").unwrap();
+ fs::write(nested.join("backup.sha256"), "hash").unwrap();
+
+ let mut collected = collect_path(&root)
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()
+ .unwrap();
+ collected.sort_by(|left, right| left.1.cmp(&right.1));
+
+ assert_eq!(
+ collected,
+ vec![
+ (
+ root.join("backup.tar.zst"),
+ "MLB-002/backup.tar.zst".to_string()
+ ),
+ (
+ nested.join("backup.sha256"),
+ "MLB-002/checksums/backup.sha256".to_string(),
+ ),
+ ]
+ );
+ }
+
+ #[test]
+ fn ignores_empty_directories() {
+ let temp = TestDirectory::new("empty-directory");
+ let root = temp.path().join("empty");
+ fs::create_dir_all(&root).unwrap();
+
+ assert!(collect_path(&root).is_empty());
+ }
+}
diff --git a/cli/src/app/target.rs b/cli/src/app/target.rs
new file mode 100644
index 00000000..ec84e22d
--- /dev/null
+++ b/cli/src/app/target.rs
@@ -0,0 +1,190 @@
+use localsend::discovery::{HttpChannel, StatefulDevice};
+use localsend::model::discovery::ProtocolType;
+use localsend::multicast::DEFAULT_PORT;
+use std::net::IpAddr;
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub(super) enum TargetSelector {
+ Alias(String),
+ Ip(IpAddr),
+}
+
+impl TargetSelector {
+ pub(super) fn parse(value: &str) -> anyhow::Result<Self> {
+ let value = value.trim();
+ anyhow::ensure!(!value.is_empty(), "Destination cannot be empty");
+ Ok(match value.parse::<IpAddr>() {
+ Ok(ip) => Self::Ip(ip),
+ Err(_) => Self::Alias(value.to_string()),
+ })
+ }
+
+ pub(super) fn direct_channel(&self) -> Option<HttpChannel> {
+ let Self::Ip(ip) = self else {
+ return None;
+ };
+ Some(HttpChannel {
+ host: ip.to_string(),
+ port: DEFAULT_PORT,
+ protocol: ProtocolType::Https,
+ })
+ }
+
+ pub(super) fn resolve(&self, devices: &[StatefulDevice]) -> Result<String, String> {
+ let matching: Vec<&StatefulDevice> = devices
+ .iter()
+ .filter(|device| self.matches(device))
+ .collect();
+ match matching.as_slice() {
+ [] => Err(format!("Destination {self} was not discovered")),
+ [device] => Ok(device.device.fingerprint.clone()),
+ devices => Err(format!(
+ "Destination {self} is ambiguous ({} devices matched); use an IP address",
+ devices.len()
+ )),
+ }
+ }
+
+ fn matches(&self, device: &StatefulDevice) -> bool {
+ match self {
+ Self::Alias(alias) => device.device.alias == *alias,
+ Self::Ip(ip) => device.get_ranked_channels().into_iter().any(|channel| {
+ channel.http().is_some_and(|http| {
+ http.host
+ .split('%')
+ .next()
+ .and_then(|host| host.parse::<IpAddr>().ok())
+ == Some(*ip)
+ })
+ }),
+ }
+ }
+}
+
+impl std::fmt::Display for TargetSelector {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Alias(alias) => write!(formatter, "alias {alias:?}"),
+ Self::Ip(ip) => write!(formatter, "IP address {ip}"),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::TargetSelector;
+ use localsend::discovery::{
+ ChannelStatus, DeviceChannel, DiscoveredDevice, HttpChannel, StatefulDevice,
+ };
+ use localsend::model::discovery::ProtocolType;
+ use std::collections::HashMap;
+ use std::net::{IpAddr, Ipv4Addr};
+
+ fn device(alias: &str, fingerprint: &str, host: &str) -> StatefulDevice {
+ let channel = DeviceChannel::Http(HttpChannel {
+ host: host.to_string(),
+ port: 53317,
+ protocol: ProtocolType::Https,
+ });
+ StatefulDevice {
+ device: DiscoveredDevice {
+ alias: alias.to_string(),
+ version: "2.2".to_string(),
+ device_model: None,
+ device_type: None,
+ fingerprint: fingerprint.to_string(),
+ channel: channel.clone(),
+ download: false,
+ },
+ channels: HashMap::from([(channel, ChannelStatus::Available)]),
+ logs: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn parses_aliases_and_ip_addresses() {
+ assert_eq!(
+ TargetSelector::parse("Cute Tomato").unwrap(),
+ TargetSelector::Alias("Cute Tomato".to_string())
+ );
+ assert_eq!(
+ TargetSelector::parse("192.168.27.26").unwrap(),
+ TargetSelector::Ip(IpAddr::V4(Ipv4Addr::new(192, 168, 27, 26)))
+ );
+ }
+
+ #[test]
+ fn rejects_an_empty_destination() {
+ assert!(TargetSelector::parse(" ").is_err());
+ }
+
+ #[test]
+ fn creates_a_direct_https_channel_for_an_ip() {
+ let selector = TargetSelector::parse("192.168.27.26").unwrap();
+
+ assert_eq!(
+ selector.direct_channel(),
+ Some(HttpChannel {
+ host: "192.168.27.26".to_string(),
+ port: 53317,
+ protocol: ProtocolType::Https,
+ })
+ );
+ }
+
+ #[test]
+ fn resolves_an_exact_alias() {
+ let devices = vec![
+ device("Cute Tomato", "windows", "192.168.27.26"),
+ device("Wise Cherry", "linux", "192.168.27.33"),
+ ];
+
+ assert_eq!(
+ TargetSelector::parse("Cute Tomato")
+ .unwrap()
+ .resolve(&devices),
+ Ok("windows".to_string())
+ );
+ }
+
+ #[test]
+ fn resolves_an_ip_address() {
+ let devices = vec![device("Cute Tomato", "windows", "192.168.27.26")];
+
+ assert_eq!(
+ TargetSelector::parse("192.168.27.26")
+ .unwrap()
+ .resolve(&devices),
+ Ok("windows".to_string())
+ );
+ }
+
+ #[test]
+ fn rejects_an_ambiguous_alias() {
+ let devices = vec![
+ device("Cute Tomato", "first", "192.168.27.26"),
+ device("Cute Tomato", "second", "192.168.27.27"),
+ ];
+
+ assert!(
+ TargetSelector::parse("Cute Tomato")
+ .unwrap()
+ .resolve(&devices)
+ .unwrap_err()
+ .contains("ambiguous")
+ );
+ }
+
+ #[test]
+ fn rejects_a_destination_that_was_not_discovered() {
+ let devices = vec![device("Wise Cherry", "linux", "192.168.27.33")];
+
+ assert!(
+ TargetSelector::parse("Cute Tomato")
+ .unwrap()
+ .resolve(&devices)
+ .unwrap_err()
+ .contains("was not discovered")
+ );
+ }
+}
diff --git a/cli/src/main.rs b/cli/src/main.rs
index b6343b0f..c70b0a19 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -8,9 +8,23 @@ mod storage;
mod ui;
mod util;
-use clap::Parser;
+use clap::{Parser, Subcommand};
use std::path::PathBuf;
+#[derive(Subcommand)]
+pub enum Command {
+ /// Send one or more files or directories
+ Send {
+ /// Destination device: an exact alias or IP address
+ #[arg(long, value_name = "TARGET")]
+ to: Option<String>,
+
+ /// Files or directories to send (directories are collected recursively)
+ #[arg(value_name = "PATH", required = true, num_args = 1..)]
+ paths: Vec<PathBuf>,
+ },
+}
+
/// LocalSend CLI
#[derive(Parser)]
#[command(name = "localsend-cli", version, about, after_help = HELP_SECTIONS)]
@@ -27,9 +41,8 @@ pub struct Args {
#[arg(long, env = "LOCALSEND_DESTINATION")]
pub destination: Option<PathBuf>,
- /// File to send: opens the device list on start, selecting a device starts the transfer (repeatable)
- #[arg(short, long = "file", value_name = "PATH")]
- pub file: Vec<PathBuf>,
+ #[command(subcommand)]
+ pub command: Option<Command>,
}
const HELP_SECTIONS: &str = "Events:\n \
@@ -50,3 +63,67 @@ fn main() -> anyhow::Result<()> {
let args = Args::parse();
tokio::runtime::Runtime::new()?.block_on(app::run(args))
}
+
+#[cfg(test)]
+mod tests {
+ use super::{Args, Command};
+ use clap::Parser;
+ use std::path::PathBuf;
+
+ #[test]
+ fn accepts_mixed_send_paths() {
+ let args = Args::try_parse_from(["localsend-cli", "send", "one.txt", "two.txt", "backup"])
+ .unwrap();
+
+ let Some(Command::Send { to, paths }) = args.command else {
+ panic!("expected the send command");
+ };
+ assert_eq!(to, None);
+ assert_eq!(
+ paths,
+ vec![
+ PathBuf::from("one.txt"),
+ PathBuf::from("two.txt"),
+ PathBuf::from("backup"),
+ ]
+ );
+ }
+
+ #[test]
+ fn accepts_a_destination_alias() {
+ let args =
+ Args::try_parse_from(["localsend-cli", "send", "--to", "Cute Tomato", "one.txt"])
+ .unwrap();
+
+ let Some(Command::Send { to, paths }) = args.command else {
+ panic!("expected the send command");
+ };
+ assert_eq!(to.as_deref(), Some("Cute Tomato"));
+ assert_eq!(paths, vec![PathBuf::from("one.txt")]);
+ }
+
+ #[test]
+ fn accepts_a_destination_ip() {
+ let args =
+ Args::try_parse_from(["localsend-cli", "send", "--to", "192.168.27.26", "one.txt"])
+ .unwrap();
+
+ let Some(Command::Send { to, paths }) = args.command else {
+ panic!("expected the send command");
+ };
+ assert_eq!(to.as_deref(), Some("192.168.27.26"));
+ assert_eq!(paths, vec![PathBuf::from("one.txt")]);
+ }
+
+ #[test]
+ fn requires_at_least_one_send_path() {
+ assert!(Args::try_parse_from(["localsend-cli", "send"]).is_err());
+ }
+
+ #[test]
+ fn accepts_interactive_mode_without_a_command() {
+ let args = Args::try_parse_from(["localsend-cli"]).unwrap();
+
+ assert!(args.command.is_none());
+ }
+}
diff --git a/cli/src/send_task.rs b/cli/src/send_task.rs
index 4351401f..4c145d64 100644
--- a/cli/src/send_task.rs
+++ b/cli/src/send_task.rs
@@ -44,7 +44,7 @@ impl SendCancel {
/// per accepted file. Progress is reported through `progress` (cumulative
/// bytes over all files) and log lines through `events`.
///
-/// Always ends by emitting [AppEvent::SendEnded].
+/// Always ends by emitting [AppEvent::SendEnded] with the transfer result.
pub async fn run_send(
identity: Arc<Identity>,
device: StatefulDevice,
@@ -54,8 +54,8 @@ pub async fn run_send(
cancel: SendCancel,
events: mpsc::Sender<AppEvent>,
) {
- send_inner(identity, device, files, paths, progress, cancel, &events).await;
- let _ = events.send(AppEvent::SendEnded).await;
+ let success = send_inner(identity, device, files, paths, progress, cancel, &events).await;
+ let _ = events.send(AppEvent::SendEnded { success }).await;
}
async fn send_inner(
@@ -66,7 +66,7 @@ async fn send_inner(
progress: Arc<AtomicU64>,
cancel: SendCancel,
events: &mpsc::Sender<AppEvent>,
-) {
+) -> bool {
let alias = device.device.alias.clone();
let log = |text: String| {
let events = events.clone();
@@ -82,7 +82,7 @@ async fn send_inner(
let Some(http) = device.get_best_channel().and_then(|channel| channel.http()) else {
log(format!("{alias}: No dialable address")).await;
- return;
+ return false;
};
let protocol = match http.protocol {
ProtocolType::Http => ProtocolType::Http,
@@ -101,7 +101,7 @@ async fn send_inner(
Ok(client) => client,
Err(err) => {
log(format!("{alias}: Failed to create HTTP client: {err}")).await;
- return;
+ return false;
}
};
@@ -125,7 +125,7 @@ async fn send_inner(
Ok(prepared) => prepared,
Err(ClientError::Cancelled) => {
log(format!("{alias}: Cancelled")).await;
- return;
+ return false;
}
Err(ClientError::StatusCode(err)) => {
let reason = match err.status {
@@ -141,17 +141,17 @@ async fn send_inner(
),
};
log(format!("{alias}: {reason}")).await;
- return;
+ return false;
}
Err(err) => {
log(format!("{alias}: {err}")).await;
- return;
+ return false;
}
};
let Some(response) = prepared.response else {
log(format!("{alias}: all files were declined")).await;
- return;
+ return false;
};
let accepted_bytes: u64 = response
@@ -231,7 +231,7 @@ async fn send_inner(
.await;
log(format!("{alias}: Cancelled ({sent_files} file(s) sent)")).await;
}
- return;
+ return false;
}
Err(err) => {
log(format!(
@@ -247,7 +247,7 @@ async fn send_inner(
&response.session_id,
)
.await;
- return;
+ return false;
}
}
}
@@ -259,6 +259,7 @@ async fn send_inner(
util::format_duration(started.elapsed()),
))
.await;
+ true
}
/// Builds a streaming request body from the file content, invoking `progress`