Merge branch 'develop' into feat/tui-results-navigation

This commit is contained in:
Michel de Graaf
2026-09-06 21:53:36 +02:00
37 changed files with 1136 additions and 101 deletions
+39
View File
@@ -416,6 +416,18 @@
],
"type": "object"
},
{
"properties": {
"state": {
"const": "cancelled",
"type": "string"
}
},
"required": [
"state"
],
"type": "object"
},
{
"properties": {
"reason": {
@@ -1648,6 +1660,33 @@
},
"summary": "Drop a transfer that has not started."
},
{
"name": "download.cancel",
"paramStructure": "by-name",
"params": [
{
"name": "filename",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "username",
"required": true,
"schema": {
"type": "string"
}
}
],
"result": {
"name": "result",
"schema": {
"$ref": "#/components/schemas/Ack"
}
},
"summary": "Stop a download, queued or in progress; its partial file is deleted."
},
{
"name": "download.set_dir",
"paramStructure": "by-name",
+5
View File
@@ -108,6 +108,11 @@ per finished transfer: `user`, `path`, `size`, `file` (the local path written).
`<file>.part` behind; re-running the same command resumes from it rather than
starting over, so retrying a failed download is cheap.
**`transfer cancel <user> <path>`** — stop a download (queued or in progress;
its `<file>.part` is deleted) or an upload being served. Prints nothing; exit 0
is the confirmation, exit 4 means nothing by that name was in flight. Only
useful against a daemon, since a one-shot `download` ends with its own run.
**`get <query>`** — search, pick, and download in one step. `--pick
best|first|all`, `-n/--limit`, plus every filter `search` accepts. Use it when
any copy will do. It ranks on free slot, bitrate and peer speed, so it cannot
+5
View File
@@ -116,6 +116,7 @@ pub trait SessionApi: Send + Sync {
fn resume_download(&self, username: &str, filename: &str) -> bool;
fn remove_queued_download(&self, username: &str, filename: &str) -> bool;
fn remove_download(&self, username: &str, filename: &str) -> bool;
fn cancel_download(&self, username: &str, filename: &str) -> bool;
fn uploads(&self) -> Vec<UploadInfo>;
fn take_upload_events(&self) -> Vec<UploadInfo>;
@@ -301,6 +302,10 @@ impl SessionApi for Client {
Self::remove_download(self, username, filename)
}
fn cancel_download(&self, username: &str, filename: &str) -> bool {
Self::cancel_download(self, username, filename)
}
fn uploads(&self) -> Vec<UploadInfo> {
Self::uploads(self)
}
+16
View File
@@ -180,6 +180,10 @@ pub enum Commands {
/// Download files by user and remote path
Download(DownloadArgs),
/// Transfers in flight
#[command(subcommand)]
Transfer(TransferCommand),
/// Search, pick automatically, and download in one step
Get(GetArgs),
@@ -575,6 +579,18 @@ pub struct WishRunArgs {
pub sort: SortKey,
}
#[derive(Subcommand, Debug)]
pub enum TransferCommand {
/// Stop a download or upload; a cancelled download's partial file is
/// deleted
Cancel {
/// The other side of the transfer
user: String,
/// Remote path exactly as printed by `search`, `browse`, or `serve`
path: String,
},
}
/// Watching only lasts as long as the session doing it, so these are aimed at
/// a running daemon: it stays connected and keeps receiving the status pushes.
#[derive(Subcommand, Debug)]
+4 -1
View File
@@ -15,7 +15,7 @@ pub mod transfer;
pub mod wish;
use crate::api::SessionApi;
use crate::cli::{Commands, MessageCommand, RoomCommand};
use crate::cli::{Commands, MessageCommand, RoomCommand, TransferCommand};
use crate::output::{CliError, CliResult, Exit, Out, PortmapRecord};
use crate::port_mapping::{self, PortMapper};
use crate::remote::{Endpoint, RemoteSession};
@@ -286,6 +286,9 @@ fn dispatch(ctx: &Ctx, command: Commands) -> CliResult {
match command {
Commands::Search(args) => transfer::search(ctx, &args),
Commands::Download(args) => transfer::download(ctx, &args),
Commands::Transfer(TransferCommand::Cancel { user, path }) => {
transfer::cancel(ctx, &user, &path)
}
Commands::Get(args) => transfer::get(ctx, &args),
Commands::Browse(args) => social::browse(ctx, &args),
Commands::Room(RoomCommand::List { timeout }) => {
+16
View File
@@ -553,6 +553,9 @@ fn download_one(
reason.unwrap_or_else(|| "the transfer failed".to_string()),
));
}
Ok(DownloadStatus::Cancelled) => {
return Err(CliError::transfer("the transfer was cancelled"));
}
Ok(DownloadStatus::Queued) => {
out.status(&format!(
"queued behind {}'s uploads",
@@ -585,6 +588,19 @@ fn download_one(
}
}
pub fn cancel(ctx: &Ctx, user: &str, path: &str) -> CliResult {
let session = Session::open(ctx)?;
if session.client.cancel_download(user, path)
| session.client.cancel_upload(user, path)
{
ctx.out.status(&format!("cancelled {path} ({user})"));
return Ok(());
}
Err(CliError::no_results(format!(
"no download or upload of {path} with {user}"
)))
}
/// Parse `search`/`browse` output back into download requests.
///
/// Both shapes this program emits are accepted: a JSON object per line, or
+1 -10
View File
@@ -469,16 +469,7 @@ fn save(
let downloads: Vec<PersistedDownload> = session
.get_all_downloads()
.iter()
.map(|download| PersistedDownload {
username: download.username.clone(),
filename: download.filename.clone(),
size: download.size,
download_directory: download.download_directory.clone(),
completed: matches!(
download.status,
soulseek_rs::DownloadStatus::Completed
),
})
.filter_map(PersistedDownload::capture)
.collect();
let _ = store.save_downloads(&downloads);
+5
View File
@@ -44,6 +44,7 @@ fn params_schema(method: Method, generator: &mut SchemaGenerator) -> Value {
| Method::DownloadResume
| Method::DownloadRemove
| Method::DownloadRemoveQueued
| Method::DownloadCancel
| Method::UploadCancel => schema_of::<TransferRef>(generator),
Method::DownloadSetDir => schema_of::<DirectoryParams>(generator),
Method::UploadSlots => schema_of::<SlotsParams>(generator),
@@ -108,6 +109,7 @@ fn result_schema(method: Method, generator: &mut SchemaGenerator) -> Value {
| Method::DownloadResume
| Method::DownloadRemove
| Method::DownloadRemoveQueued
| Method::DownloadCancel
| Method::DownloadSetDir
| Method::UploadCancel
| Method::UploadSlots
@@ -162,6 +164,9 @@ fn summary(method: Method) -> &'static str {
Method::DownloadResume => "Resume a paused transfer.",
Method::DownloadRemove => "Forget a transfer entirely.",
Method::DownloadRemoveQueued => "Drop a transfer that has not started.",
Method::DownloadCancel => {
"Stop a download, queued or in progress; its partial file is deleted."
}
Method::DownloadSetDir => {
"Land future transfers in a different folder on the daemon's host."
}
+3
View File
@@ -111,6 +111,7 @@ pub enum DownloadStatusDto {
total_bytes: u64,
},
Completed,
Cancelled,
Failed {
reason: Option<String>,
},
@@ -138,6 +139,7 @@ impl From<&DownloadStatus> for DownloadStatusDto {
total_bytes: *total_bytes,
},
DownloadStatus::Completed => Self::Completed,
DownloadStatus::Cancelled => Self::Cancelled,
DownloadStatus::Failed(reason) => Self::Failed {
reason: reason.clone(),
},
@@ -167,6 +169,7 @@ impl From<DownloadStatusDto> for DownloadStatus {
total_bytes,
},
DownloadStatusDto::Completed => Self::Completed,
DownloadStatusDto::Cancelled => Self::Cancelled,
DownloadStatusDto::Failed { reason } => Self::Failed(reason),
DownloadStatusDto::TimedOut => Self::TimedOut,
}
+2
View File
@@ -90,6 +90,7 @@ wire_vocabulary! {
DownloadResume => "download.resume",
DownloadRemove => "download.remove",
DownloadRemoveQueued => "download.remove_queued",
DownloadCancel => "download.cancel",
DownloadSetDir => "download.set_dir",
UploadList => "upload.list",
UploadCancel => "upload.cancel",
@@ -194,6 +195,7 @@ mod tests {
total_bytes: 100,
},
DownloadStatus::Completed,
DownloadStatus::Cancelled,
DownloadStatus::Failed(Some("gone".into())),
DownloadStatus::Failed(None),
DownloadStatus::TimedOut,
+12
View File
@@ -184,6 +184,15 @@ impl Daemon {
),
})
}
Method::DownloadCancel => {
let transfer: TransferRef = parse(params)?;
ok(Ack {
ok: self.session.cancel_download(
&transfer.username,
&transfer.filename,
),
})
}
Method::UploadList => ok(Uploads {
uploads: self
@@ -846,6 +855,9 @@ mod tests {
fn cancel_upload(&self, _username: &str, _filename: &str) -> bool {
false
}
fn cancel_download(&self, _username: &str, _filename: &str) -> bool {
false
}
fn set_upload_slots(&self, _slots: usize) {}
fn check_privileges(&self) -> soulseek_rs::Result<()> {
Ok(())
+24 -11
View File
@@ -6,7 +6,6 @@ use super::state::{PersistedDownload, PersistedMessage};
use crate::models::{
AppState, ChatMessage, MessageDirection, SearchEntry, SearchStatus,
};
use soulseek_rs::DownloadStatus;
/// How much private-message history survives a restart.
/// a flat cap on the whole log rather than per conversation; make
@@ -34,16 +33,7 @@ impl Snapshot {
let downloads = state
.downloads
.iter()
.map(|entry| PersistedDownload {
username: entry.download.username.clone(),
filename: entry.download.filename.clone(),
size: entry.download.size,
download_directory: entry.download.download_directory.clone(),
completed: matches!(
entry.download.status,
DownloadStatus::Completed
),
})
.filter_map(|entry| PersistedDownload::capture(&entry.download))
.collect();
let mut queries: Vec<String> = Vec::new();
@@ -121,6 +111,7 @@ pub fn restore_searches(state: &mut AppState, queries: &[String]) {
mod tests {
use super::*;
use crate::models::DownloadEntry;
use soulseek_rs::DownloadStatus;
use soulseek_rs::types::{Download, DownloadMetadata};
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, mpsc};
@@ -188,6 +179,28 @@ mod tests {
assert_eq!(snapshot.downloads[0].download_directory, "/music");
}
#[test]
fn a_cancelled_download_is_not_captured() {
let mut state = AppState::new();
state
.downloads
.push(download("gone.mp3", DownloadStatus::Cancelled));
state
.downloads
.push(download("queued.mp3", DownloadStatus::Queued));
let snapshot = Snapshot::capture(&state);
assert_eq!(
snapshot
.downloads
.iter()
.map(|d| d.filename.as_str())
.collect::<Vec<_>>(),
vec!["queued.mp3"],
"a cancel must not come back as a retry after a restart"
);
}
#[test]
fn capture_takes_queries_in_order_without_duplicates() {
let mut state = AppState::new();
+17
View File
@@ -9,6 +9,7 @@
use color_eyre::Result;
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
use soulseek_rs::{DownloadStatus, types::Download};
use std::path::{Path, PathBuf};
/// The shape every file is written in today. Bump it — and convert the older
@@ -24,6 +25,22 @@ pub struct PersistedDownload {
pub completed: bool,
}
impl PersistedDownload {
#[must_use]
pub fn capture(download: &Download) -> Option<Self> {
if matches!(download.status, DownloadStatus::Cancelled) {
return None;
}
Some(Self {
username: download.username.clone(),
filename: download.filename.clone(),
size: download.size,
download_directory: download.download_directory.clone(),
completed: matches!(download.status, DownloadStatus::Completed),
})
}
}
/// One line of private-message history.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct PersistedMessage {
+1 -6
View File
@@ -106,12 +106,7 @@ impl Mirror {
fn route(buffers: &mut Buffers, update: DownloadStatusEvent) {
let key = (update.username, update.filename);
let status = DownloadStatus::from(update.status);
let terminal = matches!(
status,
DownloadStatus::Completed
| DownloadStatus::Failed(_)
| DownloadStatus::TimedOut
);
let terminal = status.is_terminal();
let Some(sender) = buffers.downloads.get(&key) else {
return;
};
+4
View File
@@ -639,6 +639,10 @@ impl SessionApi for RemoteSession {
self.ask(Method::DownloadRemove, Self::transfer(username, filename))
}
fn cancel_download(&self, username: &str, filename: &str) -> bool {
self.ask(Method::DownloadCancel, Self::transfer(username, filename))
}
fn uploads(&self) -> Vec<UploadInfo> {
self.request::<_, Uploads>(Method::UploadList, ())
.map(|listed| listed.uploads.into_iter().map(Into::into).collect())
+42 -36
View File
@@ -1,18 +1,10 @@
use super::MainTui;
use crate::models::{DownloadEntry, FileDisplayData};
use crate::ui::panes::{InfoSubject, selected_transfer};
use soulseek_rs::types::UploadStatus;
use soulseek_rs::{DownloadStatus, types::Download};
use std::{sync::mpsc, thread};
/// Done, given up, or ran out of time: the row is all that is left.
const fn is_finished(download: &Download) -> bool {
matches!(
download.status,
DownloadStatus::Completed
| DownloadStatus::Failed(_)
| DownloadStatus::TimedOut
)
}
impl MainTui {
/// Channel for queued downloads, created on first use.
pub(super) fn downloads_sender(
@@ -73,7 +65,7 @@ impl MainTui {
// session holds, so dropping them only here would last until the next
// poll put them straight back.
for entry in &self.state.downloads {
if is_finished(&entry.download) {
if entry.download.is_finished() {
self.client.remove_download(
&entry.download.username,
&entry.download.filename,
@@ -82,7 +74,7 @@ impl MainTui {
}
self.state
.downloads
.retain(|entry| !is_finished(&entry.download));
.retain(|entry| !entry.download.is_finished());
let len = self.state.downloads.len();
if len == 0 {
self.state.downloads_table_state.select(None);
@@ -139,7 +131,7 @@ impl MainTui {
// A finished transfer may exist only in this window (restored from
// an earlier run), so the session's "nothing to forget" is not a
// reason to keep the row.
DownloadStatus::Completed => {
DownloadStatus::Completed | DownloadStatus::Cancelled => {
self.client
.remove_download(&download.username, &download.filename);
true
@@ -214,29 +206,43 @@ impl MainTui {
self.state.results_selected_indices.clear();
}
/// Cancel the selected transfer when it is an upload row (uploads are
/// listed after the downloads in the shared pane).
pub(super) fn cancel_selected_upload(&self) {
let Some(index) = self.state.downloads_table_state.selected() else {
return;
};
let Some(upload) = self
.state
.uploads
.get(index.wrapping_sub(self.state.downloads.len()))
else {
return;
};
if upload.status == soulseek_rs::types::UploadStatus::InProgress
&& !self
.client
.cancel_upload(&upload.username, &upload.filename)
{
soulseek_rs::warn!(
"No in-progress upload of {} to {} to cancel",
upload.filename,
upload.username
);
pub(super) fn cancel_selected_transfer(&self) {
let selected = selected_transfer(
self.state.downloads_table_state.selected(),
&self.state.downloads,
&self.state.uploads,
);
match selected {
Some(InfoSubject::Download(entry))
if !entry.download.is_finished() =>
{
let download = &entry.download;
if !self
.client
.cancel_download(&download.username, &download.filename)
{
soulseek_rs::warn!(
"No download of {} from {} to cancel",
download.filename,
download.username
);
}
}
Some(InfoSubject::Upload(upload))
if upload.status == UploadStatus::InProgress =>
{
let cancelled = self
.client
.cancel_upload(&upload.username, &upload.filename);
if !cancelled {
soulseek_rs::warn!(
"No in-progress upload of {} to {} to cancel",
upload.filename,
upload.username
);
}
}
_ => {}
}
}
+1 -1
View File
@@ -465,7 +465,7 @@ impl MainTui {
cycle(&mut self.state.downloads_table_state, rows, true);
}
KeyCode::Char('x') => {
self.cancel_selected_upload();
self.cancel_selected_transfer();
}
KeyCode::Char('p') => {
self.toggle_selected_download_pause();
+111 -2
View File
@@ -289,6 +289,8 @@ mod tests {
download_dir_set: std::sync::Mutex<Option<String>>,
/// What `set_shared_directories` was last asked for, if anything.
shares_set: std::sync::Mutex<Option<Vec<String>>>,
download_cancelled: std::sync::Mutex<Option<(String, String)>>,
upload_cancelled: std::sync::Mutex<Option<(String, String)>>,
}
fn queued(username: &str, filename: &str) -> soulseek_rs::types::Download {
@@ -432,8 +434,15 @@ mod tests {
fn take_upload_events(&self) -> Vec<soulseek_rs::UploadInfo> {
Vec::new()
}
fn cancel_upload(&self, _u: &str, _f: &str) -> bool {
false
fn cancel_upload(&self, u: &str, f: &str) -> bool {
*self.upload_cancelled.lock().expect("not poisoned") =
Some((u.to_string(), f.to_string()));
true
}
fn cancel_download(&self, u: &str, f: &str) -> bool {
*self.download_cancelled.lock().expect("not poisoned") =
Some((u.to_string(), f.to_string()));
true
}
fn set_upload_slots(&self, _slots: usize) {}
fn check_privileges(&self) -> soulseek_rs::Result<()> {
@@ -558,6 +567,106 @@ mod tests {
}
}
#[test]
fn x_cancels_the_highlighted_download() {
let session = Arc::new(TalkativeSession::default());
let mut tui = attach(session.clone());
tui.state.downloads.push(crate::models::DownloadEntry {
download: at_status(
"bob",
"song.mp3",
soulseek_rs::DownloadStatus::InProgress {
bytes_downloaded: 1,
total_bytes: 4096,
speed_bytes_per_sec: 1.0,
},
),
receiver: None,
});
tui.state.downloads_table_state.select(Some(0));
tui.state.focused_pane = FocusedPane::Downloads;
tui.handle_key_event(key('x'));
assert_eq!(
*session.download_cancelled.lock().expect("not poisoned"),
Some(("bob".to_string(), "song.mp3".to_string()))
);
assert_eq!(
*session.upload_cancelled.lock().expect("not poisoned"),
None
);
}
#[test]
fn d_clears_a_cancelled_row() {
let mut tui = with_session(TalkativeSession::default());
tui.state.downloads.push(crate::models::DownloadEntry {
download: at_status(
"bob",
"gone.mp3",
soulseek_rs::DownloadStatus::Cancelled,
),
receiver: None,
});
tui.state.downloads_table_state.select(Some(0));
tui.state.focused_pane = FocusedPane::Downloads;
tui.handle_key_event(key('d'));
assert!(tui.state.downloads.is_empty(), "the row goes");
}
#[test]
fn x_on_a_finished_download_asks_nothing() {
let session = Arc::new(TalkativeSession::default());
let mut tui = attach(session.clone());
tui.state.downloads.push(crate::models::DownloadEntry {
download: completed("bob", "done.mp3"),
receiver: None,
});
tui.state.downloads_table_state.select(Some(0));
tui.state.focused_pane = FocusedPane::Downloads;
tui.handle_key_event(key('x'));
assert_eq!(
*session.download_cancelled.lock().expect("not poisoned"),
None
);
}
#[test]
fn x_on_an_upload_row_still_cancels_the_upload() {
let session = Arc::new(TalkativeSession::default());
let mut tui = attach(session.clone());
tui.state.downloads.push(crate::models::DownloadEntry {
download: queued("bob", "song.mp3"),
receiver: None,
});
tui.state.uploads.push(soulseek_rs::types::UploadInfo {
username: "alice".to_string(),
filename: "served.mp3".to_string(),
size: 10,
bytes_sent: 1,
speed_bytes_per_sec: 1.0,
status: soulseek_rs::types::UploadStatus::InProgress,
});
tui.state.downloads_table_state.select(Some(1));
tui.state.focused_pane = FocusedPane::Downloads;
tui.handle_key_event(key('x'));
assert_eq!(
*session.upload_cancelled.lock().expect("not poisoned"),
Some(("alice".to_string(), "served.mp3".to_string()))
);
assert_eq!(
*session.download_cancelled.lock().expect("not poisoned"),
None
);
}
fn with_session(session: TalkativeSession) -> MainTui {
attach(Arc::new(session))
}
+1
View File
@@ -402,6 +402,7 @@ impl MainTui {
FocusedPane::Downloads => {
vec![
("p", "pause/resume"),
("x", "cancel"),
("r", "retry failed"),
("d", "delete queued/done"),
("c", "clear finished"),
@@ -222,6 +222,9 @@ fn build_info_lines(
}
DownloadStatus::Paused { .. } => ("Paused".to_string(), info_style()),
DownloadStatus::Completed => ("Completed".to_string(), success_style()),
DownloadStatus::Cancelled => {
("Cancelled".to_string(), inactive_style())
}
DownloadStatus::Failed(_) => ("Failed".to_string(), error_style()),
DownloadStatus::TimedOut => ("Timed out".to_string(), error_style()),
};
@@ -305,7 +308,9 @@ fn build_info_lines(
)));
}
}
DownloadStatus::Completed | DownloadStatus::TimedOut => {}
DownloadStatus::Completed
| DownloadStatus::Cancelled
| DownloadStatus::TimedOut => {}
}
lines
+4 -1
View File
@@ -81,6 +81,7 @@ pub fn render_downloads_pane(
)
}
DownloadStatus::Completed => "Completed".to_string(),
DownloadStatus::Cancelled => "Cancelled".to_string(),
DownloadStatus::Failed(_) => "Failed".to_string(),
DownloadStatus::TimedOut => "Timed out".to_string(),
};
@@ -97,7 +98,9 @@ pub fn render_downloads_pane(
DownloadStatus::Failed(_) | DownloadStatus::TimedOut => {
error_style()
}
DownloadStatus::Queued => inactive_style(),
DownloadStatus::Queued | DownloadStatus::Cancelled => {
inactive_style()
}
_ => primary_style(),
};
+2
View File
@@ -152,6 +152,7 @@ pub fn download_status_glyph(status: &DownloadStatus) -> (&'static str, Style) {
DownloadStatus::InProgress { .. } => (GLYPH_ACTIVE, accent_style()),
DownloadStatus::Paused { .. } => (GLYPH_PAUSED, info_style()),
DownloadStatus::Completed => (GLYPH_DONE, success_style()),
DownloadStatus::Cancelled => (GLYPH_FAILED, inactive_style()),
DownloadStatus::Failed(_) => (GLYPH_FAILED, error_style()),
DownloadStatus::TimedOut => (GLYPH_TIMED_OUT, error_style()),
}
@@ -237,6 +238,7 @@ mod tests {
(DownloadStatus::Completed, GLYPH_DONE, PHOSPHOR),
(DownloadStatus::Failed(None), GLYPH_FAILED, ALARM),
(DownloadStatus::TimedOut, GLYPH_TIMED_OUT, ALARM),
(DownloadStatus::Cancelled, GLYPH_FAILED, COLOR_INACTIVE),
] {
let (got_glyph, style) = download_status_glyph(&status);
assert_eq!(got_glyph, glyph);
+74
View File
@@ -27,6 +27,7 @@ const EXIT_OK: i32 = 0;
const EXIT_USAGE: i32 = 2;
const EXIT_CONNECTION: i32 = 3;
const EXIT_NO_RESULTS: i32 = 4;
const EXIT_TRANSFER: i32 = 6;
const EXIT_SESSION_LOST: i32 = 7;
/// Build a command for the binary, isolated from the developer's environment
@@ -1554,6 +1555,79 @@ fn browse_lists_shares_as_paths_download_understands() {
assert_eq!(fields[1], probe_bytes().len().to_string());
}
#[test]
fn transfer_cancel_without_a_matching_transfer_is_the_no_results_verdict() {
let server = server_or_skip!();
let output = cli(
&server,
"cli_e2e_canceller",
&["transfer", "cancel", "nobody", "nothing.mp3"],
);
assert_eq!(
code(&output),
EXIT_NO_RESULTS,
"stderr: {}",
stderr(&output)
);
assert!(
stderr(&output).contains("nothing.mp3"),
"the verdict names the transfer: {}",
stderr(&output)
);
}
#[test]
fn transfer_cancel_stops_a_download_another_client_is_waiting_on() {
if mode() != Mode::Daemon {
println!("skipped: a one-shot download owns its own session");
return;
}
let server = server_or_skip!();
let mut all = server.args("cli_e2e_cancel_waiter");
all.extend(
[
"download",
"e2e_ghost_peer",
"@@ghost\\never.mp3",
"--size",
"10",
"--timeout",
"60",
]
.iter()
.map(|a| (*a).to_string()),
);
let refs: Vec<&str> = all.iter().map(String::as_str).collect();
let waiting = command(&refs)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("the binary should start");
let deadline = Instant::now() + Duration::from_secs(15);
let mut cancelled = None;
while Instant::now() < deadline {
let output = cli(
&server,
"cli_e2e_cancel_waiter",
&["transfer", "cancel", "e2e_ghost_peer", "@@ghost\\never.mp3"],
);
if code(&output) == EXIT_OK {
cancelled = Some(output);
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
cancelled.is_some(),
"the queued transfer should be cancellable"
);
let waited = waiting.wait_with_output().expect("wait");
assert_eq!(code(&waited), EXIT_TRANSFER, "stderr: {}", stderr(&waited));
assert!(stderr(&waited).contains("cancelled"), "{}", stderr(&waited));
}
#[test]
fn download_fetches_a_file_and_prints_where_it_landed() {
let server = server_or_skip!();
+42
View File
@@ -905,6 +905,48 @@ fn a_wishlist_search_is_reported_as_just_started() {
);
}
#[test]
fn a_queued_download_is_cancelled_and_listed_as_such() {
let daemon = daemon_or_skip!();
let mut connection = daemon.connect_tcp().expect("tcp");
connection
.authenticate(Some(&daemon.token()))
.expect("an answer");
let started = connection
.call(
r#"{"jsonrpc":"2.0","id":2,"method":"download.start","params":{"username":"e2e_ghost_peer","filename":"@@ghost\\never.mp3","size":10}}"#,
)
.expect("an answer");
assert!(!started.contains("error"), "got {started}");
let reply = connection
.call(
r#"{"jsonrpc":"2.0","id":3,"method":"download.cancel","params":{"username":"e2e_ghost_peer","filename":"@@ghost\\never.mp3"}}"#,
)
.expect("an answer");
assert!(reply.contains(r#""ok":true"#), "got {reply}");
let listed = connection
.call(
r#"{"jsonrpc":"2.0","id":4,"method":"download.list","params":{}}"#,
)
.expect("an answer");
assert!(listed.contains(r#""state":"cancelled""#), "got {listed}");
}
#[test]
fn cancelling_an_unknown_download_is_answered_with_a_plain_no() {
let daemon = daemon_or_skip!();
let mut connection = daemon.connect_tcp().expect("tcp");
connection
.authenticate(Some(&daemon.token()))
.expect("an answer");
let reply = connection
.call(
r#"{"jsonrpc":"2.0","id":2,"method":"download.cancel","params":{"username":"nobody","filename":"nothing.mp3"}}"#,
)
.expect("an answer");
assert!(reply.contains(r#""ok":false"#), "got {reply}");
}
/// The upload-slot limit is retunable on a live session.
#[test]
fn the_upload_slot_limit_can_be_retuned_live() {