Skip to content

An open-source cross-platform alternative to AirDrop

feat(cli): W+R, W+S hotkeys

Tien Do Nam90fd1e3ab0d3
diff --git a/Cargo.lock b/Cargo.lock
index 1db71260..7c67337b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2244,6 +2244,7 @@ dependencies = [
"localsend",
"mime_guess",
"pem 4.0.0",
+ "qrcode",
"ratatui",
"ratatui-explorer",
"rcgen 0.14.8",
@@ -2917,6 +2918,12 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "qrcode"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
+
[[package]]
name = "quote"
version = "1.0.47"
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index 2cec36da..609ed798 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -18,6 +18,7 @@ futures-util = "0.3"
gethostname = "1.0"
mime_guess = "2.0"
pem = "4.0"
+qrcode = { version = "0.14", default-features = false }
ratatui = "0.30"
ratatui-explorer = "0.3"
rcgen = "0.14"
diff --git a/cli/src/app/devices.rs b/cli/src/app/devices.rs
index 4d97ae30..9cab0966 100644
--- a/cli/src/app/devices.rs
+++ b/cli/src/app/devices.rs
@@ -3,6 +3,7 @@
use super::App;
use crate::device_list::{DeviceList, DeviceListOutcome, DeviceRow, Row};
+use crate::picker::PickerTarget;
use crate::storage::PairedChannel;
use crate::ui::Category;
use crossterm::event::KeyEvent;
@@ -86,7 +87,10 @@ impl App {
{
// The list stays open until the picker takes over its
// alternate screen, so the main screen never shows.
- self.open_picker(device);
+ self.open_picker(PickerTarget::Device {
+ fingerprint: device.device.fingerprint.clone(),
+ alias: device.device.alias.clone(),
+ });
} else {
self.close_device_list();
if !self.preselected.is_empty() {
diff --git a/cli/src/app/discovery.rs b/cli/src/app/discovery.rs
index a0fe4ee8..4e6f2734 100644
--- a/cli/src/app/discovery.rs
+++ b/cli/src/app/discovery.rs
@@ -3,6 +3,7 @@
//! hotkey slot to every device entering the store.
use super::App;
+use super::web_link::WebMode;
use crate::slots::slot_label;
use crate::storage::PairedChannel;
use crate::ui::Category;
@@ -20,6 +21,11 @@ impl App {
return;
};
let slot = self.slots.assign(&device.fingerprint);
+ if matches!(self.web, Some(WebMode::Receive)) {
+ // Every browser opening the upload page registers like a device;
+ // those lines would just interleave the transfer prompts.
+ return;
+ }
let host = device
.http()
.map(|http| http.host.as_str())
diff --git a/cli/src/app/mod.rs b/cli/src/app/mod.rs
index 81c237be..aba0b647 100644
--- a/cli/src/app/mod.rs
+++ b/cli/src/app/mod.rs
@@ -3,6 +3,7 @@ mod discovery;
mod receive;
mod sending;
mod status;
+mod web_link;
use crate::Args;
use crate::device_list::DeviceList;
@@ -15,6 +16,7 @@ use localsend::discovery::{
DEFAULT_DISCOVERY_TIMEOUT, DeviceIdentity, DiscoveryConfig, DiscoveryEvent, DiscoveryHandle,
};
use localsend::http::server::v2::ServerEventV2;
+use localsend::http::server::web::WebSendEvent;
use localsend::http::server::{ServerConfigV2, ServerHandle, start_with_port};
use localsend::model::discovery::ProtocolType;
use localsend::multicast::{DEFAULT_MULTICAST_GROUP, DEFAULT_MULTICAST_GROUP_V6, DEFAULT_PORT};
@@ -55,6 +57,23 @@ struct App {
ui: Ui,
server: Arc<ServerHandle>,
+ /// Stops the running server. Consumed on shutdown and whenever the server
+ /// is restarted for the web share toggle.
+ server_stop_tx: Option<oneshot::Sender<()>>,
+
+ /// Event senders handed to every (re)started server, so the receivers in
+ /// [run]'s select loop survive server restarts.
+ server_tx: mpsc::Sender<ServerEventV2>,
+ web_tx: mpsc::Sender<WebSendEvent>,
+
+ /// The active web link mode ("share via link" / "receive via link");
+ /// `Some` while the server runs in plain-HTTP mode for browsers.
+ web: Option<web_link::WebMode>,
+
+ /// Whether the previously pressed key was `W`, the first half of the
+ /// W+S / W+R chords toggling the web links.
+ chord_w: bool,
+
/// The core discovery: the store of confirmed devices, and the multicast
/// side when it could be started.
discovery: Arc<DiscoveryHandle>,
@@ -85,8 +104,9 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
let identity = storage.identity.clone();
let (events_tx, mut events_rx) = mpsc::channel::<AppEvent>(64);
- // HTTP server (always TLS, like the app).
+ // HTTP server (TLS, like the app, until "share via link" drops it).
let (server_tx, mut server_rx) = mpsc::channel::<ServerEventV2>(16);
+ let (web_tx, mut web_rx) = mpsc::channel::<WebSendEvent>(16);
let (server_stop_tx, server_stop_rx) = oneshot::channel::<()>();
let server = start_with_port(
identity.port,
@@ -96,7 +116,7 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
Some(ServerConfigV2 {
pin: None,
verify_checksums: true,
- event_tx: server_tx,
+ event_tx: server_tx.clone(),
}),
None,
server_stop_rx,
@@ -184,7 +204,12 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
let mut app = App {
ui: Ui::new(),
- server: server.clone(),
+ server,
+ server_stop_tx: Some(server_stop_tx),
+ server_tx,
+ web_tx,
+ web: None,
+ chord_w: false,
discovery: discovery.clone(),
slots: Slots::new(),
storage,
@@ -216,6 +241,9 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
Some(event) = server_rx.recv() => {
app.handle_server_event(event);
}
+ Some(event) = web_rx.recv() => {
+ app.handle_web_event(event);
+ }
Some(event) = discovery_rx.recv() => {
app.handle_discovery(event);
}
@@ -234,9 +262,11 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
app.close_device_list();
app.ui.set_status(None);
let _ = crossterm::terminal::disable_raw_mode();
- let _ = server_stop_tx.send(());
+ 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), server.wait_stopped()).await;
+ 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(())
}
@@ -245,7 +275,7 @@ impl App {
/// Handles an event; returns `true` when the application should quit.
async fn handle_event(&mut self, event: AppEvent) -> bool {
match event {
- AppEvent::Key(key) => return self.handle_key(key),
+ AppEvent::Key(key) => return self.handle_key(key).await,
AppEvent::ReceiveFileResult {
session_id,
file_id,
@@ -271,14 +301,15 @@ impl App {
false
}
- fn handle_key(&mut self, key: KeyEvent) -> bool {
+ async fn handle_key(&mut self, key: KeyEvent) -> bool {
if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
+ self.chord_w = false;
return self.handle_ctrl_c();
}
// While the picker or the device list is open it consumes every key.
if self.picker.is_some() {
- self.handle_picker_key(key);
+ self.handle_picker_key(key).await;
return false;
}
if self.device_list.is_some() {
@@ -286,7 +317,11 @@ impl App {
}
if let KeyCode::Char(c) = key.code {
+ let chord_w = std::mem::replace(&mut self.chord_w, false);
match c.to_ascii_lowercase() {
+ 's' if chord_w => self.toggle_web_share().await,
+ 'r' if chord_w => self.toggle_web_receive().await,
+ 'w' => self.chord_w = true,
'y' => self.answer_pending(Answer::Accept),
'n' => self.answer_pending(Answer::Decline),
'p' => self.answer_pending(Answer::AcceptAndPair),
diff --git a/cli/src/app/receive.rs b/cli/src/app/receive.rs
index cdd565d9..2f6bc8f2 100644
--- a/cli/src/app/receive.rs
+++ b/cli/src/app/receive.rs
@@ -2,6 +2,7 @@
//! active receive session.
use super::App;
+use super::web_link::WebMode;
use crate::ui::Category;
use crate::util::{self, SpeedMeter};
use localsend::http::client::v2::LsHttpClientV2;
@@ -158,7 +159,10 @@ impl App {
}
} else {
let total: u64 = files.values().map(|file| file.size).sum();
- let mut lines = vec![info.alias.clone(), format!("\nFiles ({}, {}):", files.len(), util::format_bytes(total))];
+ let mut lines = vec![
+ info.alias.clone(),
+ format!("\nFiles ({}, {}):", files.len(), util::format_bytes(total)),
+ ];
let mut sorted: Vec<&FileDto> = files.values().collect();
sorted.sort_by_key(|file| std::cmp::Reverse(file.size));
for file in sorted.iter().take(MAX_LISTED_FILES) {
@@ -169,9 +173,18 @@ impl App {
));
}
if sorted.len() > MAX_LISTED_FILES {
- lines.push(format!(" ... and {} more", sorted.len() - MAX_LISTED_FILES));
+ lines.push(format!(
+ " ... and {} more",
+ sorted.len() - MAX_LISTED_FILES
+ ));
}
- lines.push("\nAccept? Y/N/P (P = accept and pair)".to_string());
+ // Web senders have no stable identity worth pairing: the
+ // fingerprint is an unverified payload value.
+ let prompt = match self.web {
+ Some(WebMode::Receive) => "\nAccept? Y/N",
+ _ => "\nAccept? Y/N/P (P = accept and pair)",
+ };
+ lines.push(prompt.to_string());
self.ui.log(Category::Receive, &lines.join("\n"));
self.pending = Some(PendingReceive {
session_id,
@@ -416,13 +429,21 @@ impl App {
match answer {
Answer::Decline => {
let _ = pending.decision_tx.send(PrepareUploadDecisionV2::Decline);
- self.ui
- .log(Category::Receive, &format!("{}: You declined", pending.alias));
+ self.ui.log(
+ Category::Receive,
+ &format!("{}: You declined", pending.alias),
+ );
}
Answer::Accept | Answer::AcceptAndPair => {
- self.ui
- .log(Category::Receive, &format!("{}: You accepted", pending.alias));
- if matches!(answer, Answer::AcceptAndPair) {
+ self.ui.log(
+ Category::Receive,
+ &format!("{}: You accepted", pending.alias),
+ );
+ // While "receive via link" is on, P was not offered; a stray
+ // press still accepts, but never pairs.
+ if matches!(answer, Answer::AcceptAndPair)
+ && !matches!(self.web, Some(WebMode::Receive))
+ {
let channels = self
.discovery
.device_by_fingerprint(&pending.sender.fingerprint)
diff --git a/cli/src/app/sending.rs b/cli/src/app/sending.rs
index 00622292..ee4bce64 100644
--- a/cli/src/app/sending.rs
+++ b/cli/src/app/sending.rs
@@ -2,12 +2,11 @@
//! transfer driven by the [`crate::send_task`].
use super::App;
-use crate::picker::{Picker, PickerOutcome};
+use crate::picker::{Picker, PickerOutcome, PickerTarget};
use crate::send_task;
use crate::ui::Category;
use crate::util::SpeedMeter;
use crossterm::event::KeyEvent;
-use localsend::discovery::StatefulDevice;
use localsend::model::transfer::{FileDto, FileMetadata};
use std::collections::HashMap;
use std::path::PathBuf;
@@ -41,11 +40,14 @@ impl App {
self.start_send(&device.device.fingerprint, self.preselected.clone());
return;
}
- self.open_picker(device);
+ self.open_picker(PickerTarget::Device {
+ fingerprint: device.device.fingerprint.clone(),
+ alias: device.device.alias.clone(),
+ });
}
- pub(super) fn open_picker(&mut self, device: StatefulDevice) {
- if self.send.is_some() {
+ pub(super) fn open_picker(&mut self, target: PickerTarget) {
+ if matches!(target, PickerTarget::Device { .. }) && self.send.is_some() {
self.close_device_list();
self.ui.log(Category::Send, "A send is already in progress");
return;
@@ -60,14 +62,8 @@ impl App {
None => false,
};
let opened = match handoff {
- true => Picker::open_on_alternate_screen(
- device.device.fingerprint.clone(),
- device.device.alias.clone(),
- ),
- false => Picker::open(
- device.device.fingerprint.clone(),
- device.device.alias.clone(),
- ),
+ true => Picker::open_on_alternate_screen(target),
+ false => Picker::open(target),
};
match opened {
Ok(picker) => {
@@ -81,16 +77,13 @@ impl App {
}
self.ui.log(
Category::Send,
- &format!(
- "{}: could not open the file picker: {err}",
- device.device.alias
- ),
+ &format!("Could not open the file picker: {err}"),
);
}
}
}
- pub(super) fn handle_picker_key(&mut self, key: KeyEvent) {
+ pub(super) async fn handle_picker_key(&mut self, key: KeyEvent) {
let Some(picker) = &mut self.picker else {
return;
};
@@ -98,10 +91,15 @@ impl App {
PickerOutcome::Open => {}
PickerOutcome::Picked(files) => {
let picker = self.picker.take().unwrap();
- let fingerprint = picker.fingerprint.clone();
+ let target = picker.target.clone();
picker.close();
self.ui.resume();
- self.start_send(&fingerprint, files);
+ match target {
+ PickerTarget::Device { fingerprint, .. } => {
+ self.start_send(&fingerprint, files)
+ }
+ PickerTarget::WebShare => self.enable_web_share(files).await,
+ }
}
PickerOutcome::Cancelled => {
let picker = self.picker.take().unwrap();
@@ -131,6 +129,42 @@ impl App {
return;
};
+ let (files, paths, total_bytes) = self.collect_files(picked);
+ if files.is_empty() {
+ self.ui.log(Category::Send, "No files selected");
+ return;
+ }
+
+ let progress = Arc::new(AtomicU64::new(0));
+ let cancel = send_task::SendCancel::new();
+ self.send = Some(SendState {
+ session_id: None,
+ alias: device.device.alias.clone(),
+ host,
+ total_bytes,
+ sent: progress.clone(),
+ cancel: cancel.clone(),
+ speed: SpeedMeter::new(),
+ });
+
+ tokio::spawn(send_task::run_send(
+ self.storage.identity.clone(),
+ device,
+ files,
+ paths,
+ progress,
+ cancel,
+ self.events_tx.clone(),
+ ));
+ }
+
+ /// 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.
+ pub(super) fn collect_files(
+ &mut self,
+ picked: Vec<PathBuf>,
+ ) -> (HashMap<String, FileDto>, HashMap<String, PathBuf>, u64) {
let mut files = HashMap::new();
let mut paths = HashMap::new();
let mut total_bytes = 0u64;
@@ -167,31 +201,6 @@ impl App {
);
paths.insert(id, path);
}
- if files.is_empty() {
- self.ui.log(Category::Send, "No files selected");
- return;
- }
-
- let progress = Arc::new(AtomicU64::new(0));
- let cancel = send_task::SendCancel::new();
- self.send = Some(SendState {
- session_id: None,
- alias: device.device.alias.clone(),
- host,
- total_bytes,
- sent: progress.clone(),
- cancel: cancel.clone(),
- speed: SpeedMeter::new(),
- });
-
- tokio::spawn(send_task::run_send(
- self.storage.identity.clone(),
- device,
- files,
- paths,
- progress,
- cancel,
- self.events_tx.clone(),
- ));
+ (files, paths, total_bytes)
}
}
diff --git a/cli/src/app/web_link.rs b/cli/src/app/web_link.rs
new file mode 100644
index 00000000..6e085541
--- /dev/null
+++ b/cli/src/app/web_link.rs
@@ -0,0 +1,270 @@
+//! "Share via link" (W+S) and "Receive via link" (W+R): serving the web
+//! pages so browsers can download from or upload to this device.
+//!
+//! Browsers cannot verify the self-signed certificate, so while a link is
+//! active the server is restarted without TLS and the links use plain
+//! `http://`. Toggling off restarts the encrypted server.
+
+use super::App;
+use crate::picker::PickerTarget;
+use crate::ui::Category;
+use crate::util;
+use localsend::http::server::web::{WebConfig, WebI18n, WebSendConfig, WebSendEvent};
+use localsend::http::server::{ServerConfigV2, start_with_port};
+use localsend::model::transfer::FileContent;
+use qrcode::{EcLevel, QrCode};
+use qrcode::render::unicode;
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::sync::oneshot;
+
+/// The active web link mode. Only one at a time: the download page would
+/// shadow the upload page at `/`.
+pub(super) enum WebMode {
+ /// "Share via link": the served files' paths, keyed by file ID.
+ Share { paths: HashMap<String, PathBuf> },
+
+ /// "Receive via link": browsers upload through the regular v2 endpoints,
+ /// so incoming requests go through the usual Y/N/P prompt.
+ Receive,
+}
+
+impl App {
+ pub(super) async fn toggle_web_share(&mut self) {
+ match &self.web {
+ Some(WebMode::Share { .. }) => {
+ self.disable_web(Category::Send, "Share via link").await;
+ return;
+ }
+ Some(WebMode::Receive) => {
+ self.ui.log(
+ Category::Send,
+ "Receive via link is active, press W+R to stop it first",
+ );
+ return;
+ }
+ None => {}
+ }
+ if self.pending.is_some() || self.receive.is_some() {
+ self.ui.log(
+ Category::Send,
+ "Share via link: not while a receive is active (the server would restart)",
+ );
+ return;
+ }
+ match self.preselected.is_empty() {
+ true => self.open_picker(PickerTarget::WebShare),
+ false => self.enable_web_share(self.preselected.clone()).await,
+ }
+ }
+
+ pub(super) async fn toggle_web_receive(&mut self) {
+ match &self.web {
+ Some(WebMode::Receive) => {
+ self.disable_web(Category::Receive, "Receive via link")
+ .await;
+ return;
+ }
+ Some(WebMode::Share { .. }) => {
+ self.ui.log(
+ Category::Receive,
+ "Share via link is active, press W+S to stop it first",
+ );
+ return;
+ }
+ None => {}
+ }
+ if self.pending.is_some() || self.receive.is_some() {
+ self.ui.log(
+ Category::Receive,
+ "Receive via link: not while a receive is active (the server would restart)",
+ );
+ return;
+ }
+ let web_config = WebConfig {
+ send: None,
+ upload: true,
+ i18n: WebI18n::default(),
+ };
+ if let Err(err) = self.restart_server(Some(web_config)).await {
+ self.ui.log(
+ Category::Receive,
+ &format!("Receive via link: could not restart the server: {err:#}"),
+ );
+ self.restore_encrypted_server().await;
+ return;
+ }
+ self.web = Some(WebMode::Receive);
+ let mut text = format!(
+ "Receive via link enabled, encryption is off\nOpen in a browser to upload files here:\n{}\n",
+ self.web_links(),
+ );
+ if let Some(qr) = self.web_qr() {
+ text.push_str(&format!("\n{qr}\n"));
+ }
+ text.push_str("Press W+R again to stop.\n\n");
+ self.ui.log(Category::Receive, &text);
+ }
+
+ /// Restarts the server in plain-HTTP mode offering `picked` for download
+ /// and prints the links to open in a browser.
+ pub(super) async fn enable_web_share(&mut self, picked: Vec<PathBuf>) {
+ let (files, paths, total_bytes) = self.collect_files(picked);
+ if files.is_empty() {
+ self.ui.log(Category::Send, "No files selected");
+ return;
+ }
+ let count = files.len();
+ let web_config = WebConfig {
+ send: Some(WebSendConfig {
+ files,
+ pin: None,
+ event_tx: self.web_tx.clone(),
+ }),
+ upload: false,
+ i18n: WebI18n::default(),
+ };
+ if let Err(err) = self.restart_server(Some(web_config)).await {
+ self.ui.log(
+ Category::Send,
+ &format!("Share via link: could not restart the server: {err:#}"),
+ );
+ self.restore_encrypted_server().await;
+ return;
+ }
+ self.web = Some(WebMode::Share { paths });
+ let mut text = format!(
+ "Share via link enabled: {count} file{} ({}), encryption is off\nOpen in a browser:\n{}\n",
+ if count == 1 { "" } else { "s" },
+ util::format_bytes(total_bytes),
+ self.web_links(),
+ );
+ if let Some(qr) = self.web_qr() {
+ text.push_str(&format!("\n{qr}\n"));
+ }
+ text.push_str("Press W+S again to stop sharing.\n\n");
+ self.ui.log(Category::Send, &text);
+ }
+
+ /// The plain-HTTP links of the running server, one per line.
+ fn web_links(&self) -> String {
+ match crate::banner::listening_lines(&self.server.local_addresses(), "http") {
+ lines if lines.is_empty() => " - (no network interface found)".to_string(),
+ lines => lines.join("\n"),
+ }
+ }
+
+ /// The first link as a QR code in half-block characters, scannable
+ /// straight from the terminal. `None` when there is no address.
+ ///
+ /// Only the modules are drawn, in the terminal's foreground color; the
+ /// rest stays the plain background. On dark terminals that inverts the
+ /// code (light on dark), which phone scanners accept.
+ fn web_qr(&self) -> Option<String> {
+ let address = self.server.local_addresses().into_iter().next()?;
+ let code = QrCode::with_error_correction_level(format!("http://{address}"), EcLevel::L).ok()?;
+ Some(code.render::<unicode::Dense1x2>().quiet_zone(false).build())
+ }
+
+ async fn disable_web(&mut self, category: Category, feature: &str) {
+ self.web = None;
+ match self.restart_server(None).await {
+ Ok(()) => self.ui.log(
+ category,
+ &format!("{feature} disabled, encryption is back on"),
+ ),
+ Err(err) => self.ui.log(
+ category,
+ &format!("{feature} disabled, but the server could not be restarted: {err:#}"),
+ ),
+ }
+ }
+
+ /// Best effort after a failed plain-HTTP restart: get back to the normal
+ /// encrypted server.
+ async fn restore_encrypted_server(&mut self) {
+ if let Err(err) = self.restart_server(None).await {
+ self.ui.log(
+ Category::Send,
+ &format!("Could not restore the encrypted server: {err:#}"),
+ );
+ }
+ }
+
+ /// Stops the running server and starts a fresh one on the same port:
+ /// the normal encrypted one, or, when `web_config` is given, a plain-HTTP
+ /// one that additionally serves that web page.
+ async fn restart_server(&mut self, web_config: Option<WebConfig>) -> anyhow::Result<()> {
+ if let Some(stop_tx) = self.server_stop_tx.take() {
+ let _ = stop_tx.send(());
+ }
+ let _ = tokio::time::timeout(Duration::from_secs(3), self.server.wait_stopped()).await;
+
+ let identity = &self.storage.identity;
+ let tls_config = match web_config.is_some() {
+ true => None,
+ false => Some(identity.tls_config()),
+ };
+ let (stop_tx, stop_rx) = oneshot::channel::<()>();
+ let server = start_with_port(
+ identity.port,
+ tls_config,
+ identity.client_info(),
+ None,
+ Some(ServerConfigV2 {
+ pin: None,
+ verify_checksums: true,
+ event_tx: self.server_tx.clone(),
+ }),
+ web_config,
+ stop_rx,
+ )
+ .await?;
+ self.server = Arc::new(server);
+ self.server_stop_tx = Some(stop_tx);
+ Ok(())
+ }
+
+ pub(super) fn handle_web_event(&mut self, event: WebSendEvent) {
+ match event {
+ WebSendEvent::PrepareDownload {
+ ip,
+ user_agent,
+ decision_tx,
+ ..
+ } => {
+ // For now every browser is accepted without asking.
+ let _ = decision_tx.send(true);
+ let agent = user_agent
+ .map(|agent| format!(" ({agent})"))
+ .unwrap_or_default();
+ self.ui.log(
+ Category::Send,
+ &format!("Web: {ip} opened the shared link{agent}"),
+ );
+ }
+ WebSendEvent::FileDownload {
+ session_id,
+ file_id,
+ file,
+ content_tx,
+ } => {
+ let path = match &self.web {
+ Some(WebMode::Share { paths }) => paths.get(&file_id),
+ _ => None,
+ };
+ let Some(path) = path else {
+ // Sharing ended: dropping the responder fails the download.
+ return;
+ };
+ let _ = content_tx.send(FileContent::Path(path.clone()));
+ self.ui.log(
+ Category::Send,
+ &format!("Web: {session_id} downloads {}", file.file_name),
+ );
+ }
+ }
+ }
+}
diff --git a/cli/src/banner.rs b/cli/src/banner.rs
index 2a03366d..e740cd39 100644
--- a/cli/src/banner.rs
+++ b/cli/src/banner.rs
@@ -26,7 +26,7 @@ pub fn render(storage: &Repository, server: &ServerHandle) -> String {
.collect::<Vec<_>>()
.join("\n");
- let listening = match listening_lines(&server.local_addresses()) {
+ let listening = match listening_lines(&server.local_addresses(), "https") {
lines if lines.is_empty() => " - (no network interface found)".to_string(),
lines => lines.join("\n"),
};
@@ -52,19 +52,19 @@ pub fn render(storage: &Repository, server: &ServerHandle) -> String {
///
/// IPv6 addresses render bracketed ("[::1]:53317"), as a URL needs them.
/// Relies on the addresses being sorted, so that each scope is contiguous.
-fn listening_lines(addresses: &[SocketAddr]) -> Vec<String> {
+pub fn listening_lines(addresses: &[SocketAddr], scheme: &str) -> Vec<String> {
let mut lines: Vec<(String, usize)> = Vec::new();
let mut current_scope: Option<bool> = None;
for address in addresses {
match address {
- SocketAddr::V4(_) => lines.push((format!(" - https://{address}"), 0)),
+ SocketAddr::V4(_) => lines.push((format!(" - {scheme}://{address}"), 0)),
SocketAddr::V6(v6) => {
let scope = v6.ip().is_unique_local();
match current_scope == Some(scope) {
true => lines.last_mut().unwrap().1 += 1,
false => {
current_scope = Some(scope);
- lines.push((format!(" - https://{address}"), 0));
+ lines.push((format!(" - {scheme}://{address}"), 0));
}
}
}
@@ -90,23 +90,32 @@ mod tests {
#[test]
fn test_every_ipv4_gets_a_line() {
- let lines = listening_lines(&[address("10.0.0.1"), address("192.168.0.1")]);
+ let lines = listening_lines(&[address("10.0.0.1"), address("192.168.0.1")], "https");
assert_eq!(
lines,
[" - https://10.0.0.1:53317", " - https://192.168.0.1:53317"]
);
}
+ #[test]
+ fn test_scheme_is_configurable() {
+ let lines = listening_lines(&[address("10.0.0.1")], "http");
+ assert_eq!(lines, [" - http://10.0.0.1:53317"]);
+ }
+
#[test]
fn test_ipv6_collapses_per_scope() {
- let lines = listening_lines(&[
- address("192.168.0.1"),
- address("2a02::1"),
- address("2a02::2"),
- address("2a02::3"),
- address("fd44::1"),
- address("fd44::2"),
- ]);
+ let lines = listening_lines(
+ &[
+ address("192.168.0.1"),
+ address("2a02::1"),
+ address("2a02::2"),
+ address("2a02::3"),
+ address("fd44::1"),
+ address("fd44::2"),
+ ],
+ "https",
+ );
assert_eq!(
lines,
[
@@ -119,7 +128,7 @@ mod tests {
#[test]
fn test_single_ipv6_has_no_suffix() {
- let lines = listening_lines(&[address("2a02::1")]);
+ let lines = listening_lines(&[address("2a02::1")], "https");
assert_eq!(lines, [" - https://[2a02::1]:53317"]);
}
}
diff --git a/cli/src/main.rs b/cli/src/main.rs
index 4b25b03e..b6343b0f 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -39,6 +39,8 @@ const HELP_SECTIONS: &str = "Events:\n \
\nHotkeys:\n \
1-9 Send files to the device with that number\n \
D Show the paired and discovered devices\n \
+ W+S Toggle share via link: serve files to browsers over plain HTTP\n \
+ W+R Toggle receive via link: let browsers upload files over plain HTTP\n \
Y/N/P Accept / Decline / Accept-and-Pair an incoming request\n \
Ctrl+C Cancel the current transfer or request, or quit when idle\n \
\nEnvironment Variables:\n \
diff --git a/cli/src/picker.rs b/cli/src/picker.rs
index 2f07f060..3407ffec 100644
--- a/cli/src/picker.rs
+++ b/cli/src/picker.rs
@@ -24,11 +24,8 @@ const SCROLL_COUNT: usize = 12;
/// The explorer only supplies the directory listing; navigation and rendering
/// are done here so that the filter can hide entries.
pub struct Picker {
- /// The fingerprint of the device the picked files will be sent to.
- pub fingerprint: String,
-
- /// The alias of that device, shown in the title.
- alias: String,
+ /// What the picked files are for; decides the title and what confirming does.
+ pub target: PickerTarget,
explorer: FileExplorer,
terminal: Terminal<CrosstermBackend<Stdout>>,
@@ -52,6 +49,16 @@ pub struct Picker {
list_state: ListState,
}
+/// What the picked files are for.
+#[derive(Clone)]
+pub enum PickerTarget {
+ /// Send the files to the device with this fingerprint.
+ Device { fingerprint: String, alias: String },
+
+ /// Offer the files for download via "share via link".
+ WebShare,
+}
+
/// What a key press did to the picker.
pub enum PickerOutcome {
/// The picker stays open.
@@ -67,26 +74,25 @@ pub enum PickerOutcome {
impl Picker {
/// Enters the alternate screen and shows the picker.
/// The caller must suspend the log UI first and resume it after [Picker::close].
- pub fn open(fingerprint: String, alias: String) -> anyhow::Result<Self> {
+ pub fn open(target: PickerTarget) -> anyhow::Result<Self> {
let explorer = FileExplorer::new()?;
util::enter_alternate_screen()?;
- Self::show(fingerprint, alias, explorer)
+ Self::show(target, explorer)
}
/// Shows the picker on the blank alternate screen a previous modal left
/// behind (see [crate::device_list::DeviceList::close_keeping_screen]);
/// [Picker::close] leaves it as usual. When this fails, the caller must
/// leave the alternate screen itself.
- pub fn open_on_alternate_screen(fingerprint: String, alias: String) -> anyhow::Result<Self> {
+ pub fn open_on_alternate_screen(target: PickerTarget) -> anyhow::Result<Self> {
let explorer = FileExplorer::new()?;
- Self::show(fingerprint, alias, explorer)
+ Self::show(target, explorer)
}
- fn show(fingerprint: String, alias: String, explorer: FileExplorer) -> anyhow::Result<Self> {
+ fn show(target: PickerTarget, explorer: FileExplorer) -> anyhow::Result<Self> {
let terminal = Terminal::new(CrosstermBackend::new(std::io::stdout()))?;
let mut picker = Self {
- fingerprint,
- alias,
+ target,
explorer,
terminal,
selected: Vec::new(),
@@ -292,7 +298,7 @@ impl Picker {
pub fn draw(&mut self) {
let Self {
- alias,
+ target,
explorer,
terminal,
selected,
@@ -313,10 +319,14 @@ impl Picker {
])
.areas(frame.area());
+ let title = match target {
+ PickerTarget::Device { alias, .. } => format!(" To: {alias} "),
+ PickerTarget::WebShare => " Share via link ".to_string(),
+ };
let mut block = Block::default()
.borders(Borders::ALL)
.title_top(format!(" {} ", explorer.cwd().display()))
- .title_top(Line::from(format!(" To: {alias} ")).right_aligned());
+ .title_top(Line::from(title).right_aligned());
if !query.is_empty() {
let hits = match matches.is_empty() {
true => " no matches".to_string(),
diff --git a/cli/src/storage/paired.rs b/cli/src/storage/paired.rs
index aec92962..a34443a8 100644
--- a/cli/src/storage/paired.rs
+++ b/cli/src/storage/paired.rs
@@ -232,5 +232,4 @@ mod tests {
.collect();
assert_eq!(hosts, ["fe80::1%3", "192.168.0.10"]);
}
-
}