A review against the Python client, which shares this client's config and login cache, found the transfers holding whole files in memory and several commands answering differently from their Python counterparts. - Stream uploads and downloads instead of buffering the whole file, so memory no longer scales with file size times concurrency. Uploads still declare a Content-Length rather than going out chunked. - Write a download beside its destination and move it into place once complete, and refuse a destination that cannot be written, so a failed transfer leaves what was already there untouched. - Report the server's own error detail instead of the bare status. - List locked sub-folders in `ls --json --recursive` using the given password and skip only those that cannot be unlocked, instead of failing the whole listing. - Name each folder's laboratory in JSON output and sort its entries, matching the Python client's schema and order. - Ask the server who is logged in for `whoami`, rather than trusting the cached name. - Collapse repeated separators and refuse `..` in remote paths. - Fall back to the API when a laboratory is missing from the cache, so a newly added one no longer needs a fresh login. - Verify the login cache digest on read, as the Python client does. - Accept `-e` as the short form of `--exclude`. - Satisfy clippy and rustfmt across the crate.
337 lines
11 KiB
Rust
337 lines
11 KiB
Rust
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
|
|
use crate::commands::shared::{
|
|
find_file_by_name, find_folder_limited, find_laboratory, nfc, parse_remote_path,
|
|
};
|
|
use crate::connection::{ApiRequestLimiter, MDRSConnection};
|
|
use crate::models::folder::FolderSimple;
|
|
use anyhow::{anyhow, bail};
|
|
use std::path::PathBuf;
|
|
use std::sync::Arc;
|
|
use tokio::fs;
|
|
use tokio::task::JoinSet;
|
|
|
|
pub async fn upload(
|
|
local_path: &str,
|
|
remote_path: &str,
|
|
recursive: bool,
|
|
skip_if_exists: bool,
|
|
) -> Result<(), anyhow::Error> {
|
|
let (remote, labname, r_path) = parse_remote_path(remote_path)?;
|
|
let cache = load_cache_with_token_refresh(&remote).await?;
|
|
let conn = Arc::new(create_authenticated_conn(&remote, &cache)?);
|
|
let limiter = ApiRequestLimiter::new(crate::settings::SETTINGS.concurrent);
|
|
let lab = find_laboratory(&conn, Some(&cache), &labname).await?;
|
|
let dest_folder = find_folder_limited(&conn, &limiter, lab.id, &r_path, None).await?;
|
|
|
|
// Normalize local_path: resolve to an absolute canonical path so that
|
|
// trailing slashes and "./" prefixes are handled consistently (matching
|
|
// Python's os.path.abspath behaviour).
|
|
let local_abs = std::fs::canonicalize(local_path)
|
|
.map_err(|_| anyhow!("File or directory `{}` not found.", local_path))?;
|
|
let local = local_abs.as_path();
|
|
|
|
if local.is_file() {
|
|
let filename = local.file_name().unwrap().to_string_lossy().to_string();
|
|
let remote_files = conn
|
|
.list_all_files_limited(&dest_folder.id, &limiter)
|
|
.await?;
|
|
if skip_if_exists
|
|
&& let Some(rf) = find_file_by_name(&remote_files, &filename)
|
|
&& rf.size == std::fs::metadata(local)?.len()
|
|
{
|
|
println!("{}{}", dest_folder.path, filename);
|
|
return Ok(());
|
|
}
|
|
conn.upload_file_limited(&dest_folder.id, &local.to_string_lossy(), &limiter)
|
|
.await?;
|
|
println!("{}{}", dest_folder.path, filename);
|
|
} else if local.is_dir() {
|
|
if !recursive {
|
|
bail!("Cannot upload `{}`: Is a directory.", local_path);
|
|
}
|
|
// Python always creates a sub-folder named after the local directory inside
|
|
// remote_path. E.g. `upload ./mydir remote:/lab/path/` creates
|
|
// `/lab/path/mydir/` on the remote and uploads into that folder.
|
|
let local_basename = local.file_name().unwrap().to_string_lossy().to_string();
|
|
let top_remote_id = find_or_create_folder(
|
|
&conn,
|
|
&limiter,
|
|
&dest_folder.id,
|
|
&dest_folder.sub_folders,
|
|
&local_basename,
|
|
)
|
|
.await?;
|
|
println!(
|
|
"{}",
|
|
format!("{}{}", dest_folder.path, local_basename).trim_end_matches('/')
|
|
);
|
|
|
|
let mut folder_tasks: JoinSet<Result<UploadFolderTaskResult, anyhow::Error>> =
|
|
JoinSet::new();
|
|
let mut upload_tasks: JoinSet<Result<(), anyhow::Error>> = JoinSet::new();
|
|
let mut errors = Vec::new();
|
|
|
|
spawn_upload_folder_task(
|
|
&mut folder_tasks,
|
|
conn.clone(),
|
|
limiter.clone(),
|
|
local.to_path_buf(),
|
|
top_remote_id,
|
|
skip_if_exists,
|
|
);
|
|
|
|
drive_upload_tasks(
|
|
&mut folder_tasks,
|
|
&mut upload_tasks,
|
|
&mut errors,
|
|
conn.clone(),
|
|
limiter,
|
|
skip_if_exists,
|
|
)
|
|
.await;
|
|
|
|
if !errors.is_empty() {
|
|
bail!(errors.join("\n"));
|
|
}
|
|
} else {
|
|
bail!("File or directory `{}` not found.", local_path);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Find an existing sub-folder by name or create it, returning its ID.
|
|
async fn find_or_create_folder(
|
|
conn: &MDRSConnection,
|
|
limiter: &ApiRequestLimiter,
|
|
parent_id: &str,
|
|
existing: &[FolderSimple],
|
|
name: &str,
|
|
) -> Result<String, anyhow::Error> {
|
|
if let Some(sf) = existing
|
|
.iter()
|
|
.find(|f| nfc(&f.name).to_lowercase() == nfc(name).to_lowercase())
|
|
{
|
|
return Ok(sf.id.clone());
|
|
}
|
|
conn.create_folder_id_limited(parent_id, &nfc(name), limiter)
|
|
.await
|
|
}
|
|
|
|
struct UploadFolderTaskResult {
|
|
child_folders: Vec<(PathBuf, String)>,
|
|
upload_jobs: Vec<UploadJob>,
|
|
}
|
|
|
|
struct UploadJob {
|
|
folder_id: String,
|
|
file_path: String,
|
|
remote_path: String,
|
|
}
|
|
|
|
fn spawn_upload_folder_task(
|
|
folder_tasks: &mut JoinSet<Result<UploadFolderTaskResult, anyhow::Error>>,
|
|
conn: Arc<MDRSConnection>,
|
|
limiter: ApiRequestLimiter,
|
|
local_dir: PathBuf,
|
|
remote_id: String,
|
|
skip_if_exists: bool,
|
|
) {
|
|
folder_tasks.spawn(async move {
|
|
process_upload_folder(conn, limiter, local_dir, remote_id, skip_if_exists).await
|
|
});
|
|
}
|
|
|
|
fn spawn_upload_task(
|
|
upload_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
|
|
conn: Arc<MDRSConnection>,
|
|
limiter: ApiRequestLimiter,
|
|
job: UploadJob,
|
|
) {
|
|
upload_tasks.spawn(async move {
|
|
conn.upload_file_limited(&job.folder_id, &job.file_path, &limiter)
|
|
.await?;
|
|
println!("{}", job.remote_path);
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
async fn process_upload_folder(
|
|
conn: Arc<MDRSConnection>,
|
|
limiter: ApiRequestLimiter,
|
|
local_dir: PathBuf,
|
|
remote_id: String,
|
|
skip_if_exists: bool,
|
|
) -> Result<UploadFolderTaskResult, anyhow::Error> {
|
|
let (folder_detail, remote_files) = tokio::try_join!(
|
|
conn.retrieve_folder_limited(&remote_id, &limiter),
|
|
conn.list_all_files_limited(&remote_id, &limiter),
|
|
)?;
|
|
|
|
let mut entries = fs::read_dir(&local_dir).await?;
|
|
let mut subdirs: Vec<PathBuf> = Vec::new();
|
|
let mut files: Vec<PathBuf> = Vec::new();
|
|
while let Some(entry) = entries.next_entry().await? {
|
|
let path = entry.path();
|
|
if path.is_dir() {
|
|
subdirs.push(path);
|
|
} else {
|
|
files.push(path);
|
|
}
|
|
}
|
|
|
|
let mut subdir_tasks: JoinSet<Result<(PathBuf, String, String), anyhow::Error>> =
|
|
JoinSet::new();
|
|
let existing_subfolders = Arc::new(folder_detail.sub_folders.clone());
|
|
let folder_path_prefix = folder_detail.path.clone();
|
|
for subdir in subdirs {
|
|
let conn = conn.clone();
|
|
let limiter = limiter.clone();
|
|
let remote_id = remote_id.clone();
|
|
let existing_subfolders = existing_subfolders.clone();
|
|
let folder_path_prefix = folder_path_prefix.clone();
|
|
subdir_tasks.spawn(async move {
|
|
let dirname = subdir.file_name().unwrap().to_string_lossy().to_string();
|
|
let sub_remote_id = find_or_create_folder(
|
|
&conn,
|
|
&limiter,
|
|
&remote_id,
|
|
existing_subfolders.as_slice(),
|
|
&dirname,
|
|
)
|
|
.await?;
|
|
Ok((
|
|
subdir,
|
|
sub_remote_id,
|
|
format!("{}{}", folder_path_prefix, dirname),
|
|
))
|
|
});
|
|
}
|
|
|
|
let mut child_folders = Vec::new();
|
|
while let Some(result) = subdir_tasks.join_next().await {
|
|
let (subdir, sub_remote_id, remote_path) = flatten_join_result(result)?;
|
|
println!("{}", remote_path.trim_end_matches('/'));
|
|
child_folders.push((subdir, sub_remote_id));
|
|
}
|
|
|
|
let mut upload_jobs = Vec::new();
|
|
for file_path in files {
|
|
let filename = file_path.file_name().unwrap().to_string_lossy().to_string();
|
|
if skip_if_exists
|
|
&& let Some(rf) = find_file_by_name(&remote_files, &filename)
|
|
&& let Ok(meta) = std::fs::metadata(&file_path)
|
|
&& rf.size == meta.len()
|
|
{
|
|
println!("{}{}", folder_detail.path, filename);
|
|
continue;
|
|
}
|
|
upload_jobs.push(UploadJob {
|
|
folder_id: remote_id.clone(),
|
|
file_path: file_path.to_string_lossy().to_string(),
|
|
remote_path: format!("{}{}", folder_detail.path, filename),
|
|
});
|
|
}
|
|
|
|
Ok(UploadFolderTaskResult {
|
|
child_folders,
|
|
upload_jobs,
|
|
})
|
|
}
|
|
|
|
async fn drive_upload_tasks(
|
|
folder_tasks: &mut JoinSet<Result<UploadFolderTaskResult, anyhow::Error>>,
|
|
upload_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
|
|
errors: &mut Vec<String>,
|
|
conn: Arc<MDRSConnection>,
|
|
limiter: ApiRequestLimiter,
|
|
skip_if_exists: bool,
|
|
) {
|
|
loop {
|
|
match (folder_tasks.is_empty(), upload_tasks.is_empty()) {
|
|
(true, true) => break,
|
|
(false, true) => {
|
|
if let Some(result) = folder_tasks.join_next().await {
|
|
handle_upload_folder_result(
|
|
result,
|
|
folder_tasks,
|
|
upload_tasks,
|
|
errors,
|
|
conn.clone(),
|
|
limiter.clone(),
|
|
skip_if_exists,
|
|
);
|
|
}
|
|
}
|
|
(true, false) => {
|
|
if let Some(result) = upload_tasks.join_next().await
|
|
&& let Err(err) = flatten_join_result(result)
|
|
{
|
|
errors.push(err.to_string());
|
|
}
|
|
}
|
|
(false, false) => {
|
|
tokio::select! {
|
|
result = folder_tasks.join_next() => {
|
|
if let Some(result) = result {
|
|
handle_upload_folder_result(
|
|
result,
|
|
folder_tasks,
|
|
upload_tasks,
|
|
errors,
|
|
conn.clone(),
|
|
limiter.clone(),
|
|
skip_if_exists,
|
|
);
|
|
}
|
|
}
|
|
result = upload_tasks.join_next() => {
|
|
if let Some(result) = result
|
|
&& let Err(err) = flatten_join_result(result) {
|
|
errors.push(err.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn handle_upload_folder_result(
|
|
result: Result<Result<UploadFolderTaskResult, anyhow::Error>, tokio::task::JoinError>,
|
|
folder_tasks: &mut JoinSet<Result<UploadFolderTaskResult, anyhow::Error>>,
|
|
upload_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
|
|
errors: &mut Vec<String>,
|
|
conn: Arc<MDRSConnection>,
|
|
limiter: ApiRequestLimiter,
|
|
skip_if_exists: bool,
|
|
) {
|
|
match flatten_join_result(result) {
|
|
Ok(task_result) => {
|
|
for (local_dir, remote_id) in task_result.child_folders {
|
|
spawn_upload_folder_task(
|
|
folder_tasks,
|
|
conn.clone(),
|
|
limiter.clone(),
|
|
local_dir,
|
|
remote_id,
|
|
skip_if_exists,
|
|
);
|
|
}
|
|
for job in task_result.upload_jobs {
|
|
spawn_upload_task(upload_tasks, conn.clone(), limiter.clone(), job);
|
|
}
|
|
}
|
|
Err(err) => errors.push(err.to_string()),
|
|
}
|
|
}
|
|
|
|
fn flatten_join_result<T>(
|
|
result: Result<Result<T, anyhow::Error>, tokio::task::JoinError>,
|
|
) -> Result<T, anyhow::Error> {
|
|
match result {
|
|
Ok(inner) => inner,
|
|
Err(err) => Err(anyhow!("Task join failed: {}", err)),
|
|
}
|
|
}
|