Replace the fixed access-level table so new project levels are labelled correctly and configurable through the CLI, matching the Python client's project-aware behavior. - Build labels from restrict, project, and password bits, and show meaningless values as Unknown (0x...) - Read project names from users/current once for each ls run and use them in plain and JSON output - Parse composable chacl keys, list available projects on invalid input, and reject public and storage before API requests - Remove the obsolete 5kikan access-level key
399 lines
13 KiB
Rust
399 lines
13 KiB
Rust
use crate::cache::{Cache, create_readonly_conn};
|
|
use crate::commands::shared::{fmt_datetime, resolve_remote_folder};
|
|
use crate::connection::MDRSConnection;
|
|
use crate::models::file::File;
|
|
use crate::models::folder::{FolderDetail, FolderSimple, ProjectNames};
|
|
use serde_json::{Value, json};
|
|
use std::collections::HashMap;
|
|
use std::future::Future;
|
|
use std::pin::Pin;
|
|
|
|
/// Laboratory names by id, for the JSON output's per-folder `laboratory` field.
|
|
type LaboratoryNames = HashMap<u32, String>;
|
|
|
|
/// Shown for a folder whose laboratory the client cannot name, matching the Python client.
|
|
const UNKNOWN_LABORATORY: &str = "(invalid)";
|
|
|
|
pub async fn ls(
|
|
remote_path: &str,
|
|
password: Option<&str>,
|
|
is_json: bool,
|
|
is_recursive: bool,
|
|
is_quiet: bool,
|
|
) -> Result<(), anyhow::Error> {
|
|
let remote = remote_path
|
|
.split(':')
|
|
.next()
|
|
.ok_or_else(|| anyhow::anyhow!("Invalid remote path"))?;
|
|
let (conn, cache) = create_readonly_conn(remote).await?;
|
|
let (folder, lab) =
|
|
resolve_remote_folder(&conn, cache.as_ref(), None, remote_path, password).await?;
|
|
let labname = lab.name;
|
|
let projects = conn.get_project_names().await?;
|
|
|
|
if is_json {
|
|
let names = laboratory_names(&conn, cache.as_ref()).await;
|
|
let output = if is_recursive {
|
|
build_folder_json_recursive(&conn, folder, &names, &projects, password).await?
|
|
} else {
|
|
build_folder_json_flat(&conn, &folder, &names, &projects).await?
|
|
};
|
|
println!("{}", serde_json::to_string(&output)?);
|
|
} else if is_recursive {
|
|
let prefix = format!("{}:/{}", conn.remote.as_deref().unwrap_or(""), labname);
|
|
ls_plain_recursive(&conn, folder, &labname, &prefix, &projects, password).await?;
|
|
} else {
|
|
let files = conn.list_all_files(&folder.id).await?;
|
|
let mut sub_folders = folder.sub_folders.clone();
|
|
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let mut files_sorted = files;
|
|
files_sorted.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let access = folder.access_level_label(&projects);
|
|
print_folder_plain(
|
|
&sub_folders,
|
|
&files_sorted,
|
|
&access,
|
|
&labname,
|
|
&projects,
|
|
!is_quiet,
|
|
);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Plain-text output helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
fn print_folder_plain(
|
|
sub_folders: &[FolderSimple],
|
|
files: &[File],
|
|
folder_access: &str,
|
|
labname: &str,
|
|
projects: &ProjectNames,
|
|
show_header: bool,
|
|
) {
|
|
let header = ("Type", "Access", "Laboratory", "Size", "Date", "Name");
|
|
let mut w_type = header.0.len();
|
|
let mut w_access = header.1.len();
|
|
let w_lab = header.2.len().max(labname.len());
|
|
let mut w_size = header.3.len();
|
|
let mut w_date = header.4.len();
|
|
let mut w_name = header.5.len();
|
|
|
|
// [d], [l], [f] are each 3 chars; ensure w_type accommodates them
|
|
w_type = w_type.max(3);
|
|
|
|
for sf in sub_folders {
|
|
w_access = w_access.max(sf.access_level_label(projects).len());
|
|
w_size = w_size.max(sf.size.to_string().len());
|
|
w_date = w_date.max(fmt_datetime(&sf.updated_at).len());
|
|
w_name = w_name.max(sf.name.len());
|
|
}
|
|
for f in files {
|
|
w_access = w_access.max(folder_access.len());
|
|
w_size = w_size.max(f.size.to_string().len());
|
|
w_date = w_date.max(fmt_datetime(&f.updated_at).len());
|
|
w_name = w_name.max(f.name.len());
|
|
}
|
|
|
|
if show_header {
|
|
println!(
|
|
"{:<w_type$} {:<w_access$} {:<w_lab$} {:>w_size$} {:<w_date$} {:<w_name$}",
|
|
header.0,
|
|
header.1,
|
|
header.2,
|
|
header.3,
|
|
header.4,
|
|
header.5,
|
|
w_type = w_type,
|
|
w_access = w_access,
|
|
w_lab = w_lab,
|
|
w_size = w_size,
|
|
w_date = w_date,
|
|
w_name = w_name,
|
|
);
|
|
let line_len = w_type + 2 + w_access + 2 + w_lab + 2 + w_size + 2 + w_date + 2 + w_name;
|
|
println!("{}", "-".repeat(line_len));
|
|
}
|
|
|
|
for sf in sub_folders {
|
|
let folder_type = if sf.lock { "[l]" } else { "[d]" };
|
|
println!(
|
|
"{:<w_type$} {:<w_access$} {:<w_lab$} {:>w_size$} {:<w_date$} {:<w_name$}",
|
|
folder_type,
|
|
sf.access_level_label(projects),
|
|
labname,
|
|
sf.size,
|
|
fmt_datetime(&sf.updated_at),
|
|
sf.name,
|
|
w_type = w_type,
|
|
w_access = w_access,
|
|
w_lab = w_lab,
|
|
w_size = w_size,
|
|
w_date = w_date,
|
|
w_name = w_name,
|
|
);
|
|
}
|
|
|
|
for f in files {
|
|
println!(
|
|
"{:<w_type$} {:<w_access$} {:<w_lab$} {:>w_size$} {:<w_date$} {:<w_name$}",
|
|
"[f]",
|
|
folder_access,
|
|
labname,
|
|
f.size,
|
|
fmt_datetime(&f.updated_at),
|
|
f.name,
|
|
w_type = w_type,
|
|
w_access = w_access,
|
|
w_lab = w_lab,
|
|
w_size = w_size,
|
|
w_date = w_date,
|
|
w_name = w_name,
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Recursively list folder contents in plain-text mode (no header, path prefix per folder).
|
|
fn ls_plain_recursive<'a>(
|
|
conn: &'a MDRSConnection,
|
|
folder: FolderDetail,
|
|
labname: &'a str,
|
|
prefix: &'a str,
|
|
projects: &'a ProjectNames,
|
|
password: Option<&'a str>,
|
|
) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + 'a>> {
|
|
Box::pin(async move {
|
|
let files = conn.list_all_files(&folder.id).await?;
|
|
let total_size: u64 = files.iter().map(|f| f.size).sum();
|
|
|
|
println!("{}{}:", prefix, folder.path);
|
|
println!("total {}", total_size);
|
|
|
|
let access = folder.access_level_label(projects);
|
|
let mut sub_folders = folder.sub_folders.clone();
|
|
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let mut files_sorted = files;
|
|
files_sorted.sort_by(|a, b| a.name.cmp(&b.name));
|
|
|
|
print_folder_plain(
|
|
&sub_folders,
|
|
&files_sorted,
|
|
&access,
|
|
labname,
|
|
projects,
|
|
false,
|
|
);
|
|
|
|
println!();
|
|
|
|
for sf in sub_folders {
|
|
if sf.lock {
|
|
match password {
|
|
None => continue,
|
|
Some(pw) => {
|
|
if conn.folder_auth(&sf.id, pw).await.is_err() {
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
match conn.retrieve_folder(&sf.id).await {
|
|
Ok(sub_detail) => {
|
|
ls_plain_recursive(conn, sub_detail, labname, prefix, projects, password)
|
|
.await?;
|
|
}
|
|
Err(_) => continue,
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
})
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// JSON output helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
async fn get_folder_metadata(
|
|
conn: &MDRSConnection,
|
|
folder_id: &str,
|
|
) -> Result<Value, anyhow::Error> {
|
|
let resp = conn
|
|
.get(&format!("v3/folders/{}/metadata/", folder_id))
|
|
.await?;
|
|
if resp.status().is_success() {
|
|
Ok(resp.json::<Value>().await?)
|
|
} else {
|
|
Ok(json!({}))
|
|
}
|
|
}
|
|
|
|
fn file_to_json(f: &File, base_url: &str) -> Value {
|
|
let download_url = if f.download_url.starts_with("http") {
|
|
f.download_url.clone()
|
|
} else {
|
|
// The API answers with a relative path and no leading separator, so supply one
|
|
// rather than running the two together.
|
|
format!(
|
|
"{}/{}",
|
|
base_url.trim_end_matches('/'),
|
|
f.download_url.trim_start_matches('/')
|
|
)
|
|
};
|
|
json!({
|
|
"id": f.id,
|
|
"name": f.name,
|
|
"type": f.r#type,
|
|
"size": f.size,
|
|
"description": f.description,
|
|
"metadata": f.metadata,
|
|
"download_url": download_url,
|
|
"created_at": f.created_at,
|
|
"updated_at": f.updated_at,
|
|
})
|
|
}
|
|
|
|
fn folder_simple_to_json(
|
|
sf: &FolderSimple,
|
|
names: &LaboratoryNames,
|
|
projects: &ProjectNames,
|
|
) -> Value {
|
|
json!({
|
|
"id": sf.id,
|
|
"pid": sf.pid,
|
|
"name": sf.name,
|
|
"access_level": sf.access_level_label(projects),
|
|
"lock": sf.lock,
|
|
"size": sf.size,
|
|
"laboratory": laboratory_name(names, sf.laboratory_id),
|
|
"description": sf.description,
|
|
"created_at": sf.created_at,
|
|
"updated_at": sf.updated_at,
|
|
})
|
|
}
|
|
|
|
/// Name the laboratory a folder belongs to, so a listing does not hand out an id the
|
|
/// reader has no way to resolve.
|
|
fn laboratory_name(names: &LaboratoryNames, id: u32) -> String {
|
|
names
|
|
.get(&id)
|
|
.cloned()
|
|
.unwrap_or_else(|| UNKNOWN_LABORATORY.to_string())
|
|
}
|
|
|
|
/// Collect laboratory names, preferring what the login cache already holds so a listing
|
|
/// does not pay for a request it does not need.
|
|
async fn laboratory_names(conn: &MDRSConnection, cache: Option<&Cache>) -> LaboratoryNames {
|
|
if let Some(cache) = cache.filter(|c| !c.laboratories.items.is_empty()) {
|
|
return cache
|
|
.laboratories
|
|
.items
|
|
.iter()
|
|
.map(|lab| (lab.id, lab.name.clone()))
|
|
.collect();
|
|
}
|
|
match conn.list_laboratories().await {
|
|
Ok(labs) => labs
|
|
.items
|
|
.into_iter()
|
|
.map(|lab| (lab.id, lab.name))
|
|
.collect(),
|
|
Err(_) => LaboratoryNames::new(),
|
|
}
|
|
}
|
|
|
|
/// Build JSON for the top-level folder without recursing into sub-folders.
|
|
async fn build_folder_json_flat(
|
|
conn: &MDRSConnection,
|
|
folder: &FolderDetail,
|
|
names: &LaboratoryNames,
|
|
projects: &ProjectNames,
|
|
) -> Result<Value, anyhow::Error> {
|
|
let metadata = get_folder_metadata(conn, &folder.id).await?;
|
|
let mut files = conn.list_all_files(&folder.id).await?;
|
|
files.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let files_json: Vec<Value> = files.iter().map(|f| file_to_json(f, &conn.url)).collect();
|
|
let mut sub_folders = folder.sub_folders.clone();
|
|
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let sub_folders_json: Vec<Value> = sub_folders
|
|
.iter()
|
|
.map(|sf| folder_simple_to_json(sf, names, projects))
|
|
.collect();
|
|
|
|
Ok(json!({
|
|
"id": folder.id,
|
|
"pid": folder.pid,
|
|
"name": folder.name,
|
|
"size": folder.size,
|
|
"access_level": folder.access_level_label(projects),
|
|
"lock": folder.lock,
|
|
"laboratory": laboratory_name(names, folder.laboratory_id),
|
|
"description": folder.description,
|
|
"created_at": folder.created_at,
|
|
"updated_at": folder.updated_at,
|
|
"metadata": metadata,
|
|
"sub_folders": sub_folders_json,
|
|
"files": files_json,
|
|
}))
|
|
}
|
|
|
|
/// Build JSON for a folder, recursively expanding every sub-folder.
|
|
fn build_folder_json_recursive<'a>(
|
|
conn: &'a MDRSConnection,
|
|
folder: FolderDetail,
|
|
names: &'a LaboratoryNames,
|
|
projects: &'a ProjectNames,
|
|
password: Option<&'a str>,
|
|
) -> Pin<Box<dyn Future<Output = Result<Value, anyhow::Error>> + 'a>> {
|
|
Box::pin(async move {
|
|
let metadata = get_folder_metadata(conn, &folder.id).await?;
|
|
let mut files = conn.list_all_files(&folder.id).await?;
|
|
files.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let files_json: Vec<Value> = files.iter().map(|f| file_to_json(f, &conn.url)).collect();
|
|
|
|
let mut sub_folders = folder.sub_folders.clone();
|
|
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
|
|
let mut sub_folders_json = Vec::new();
|
|
for sf in &sub_folders {
|
|
// A folder the caller cannot unlock is left out rather than ending the whole
|
|
// listing: a tree usually holds a locked folder or two, and the rest of it is
|
|
// still what the user asked to see. Anything else is reported, because a
|
|
// listing that quietly drops a branch cannot be told from one where the
|
|
// branch is empty, and this output is read by programs.
|
|
if sf.lock {
|
|
match password {
|
|
None => continue,
|
|
Some(pw) => {
|
|
if conn.folder_auth(&sf.id, pw).await.is_err() {
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let sf_detail = conn.retrieve_folder(&sf.id).await?;
|
|
let sf_json =
|
|
build_folder_json_recursive(conn, sf_detail, names, projects, password).await?;
|
|
sub_folders_json.push(sf_json);
|
|
}
|
|
|
|
Ok(json!({
|
|
"id": folder.id,
|
|
"pid": folder.pid,
|
|
"name": folder.name,
|
|
"size": folder.size,
|
|
"access_level": folder.access_level_label(projects),
|
|
"lock": folder.lock,
|
|
"laboratory": laboratory_name(names, folder.laboratory_id),
|
|
"description": folder.description,
|
|
"created_at": folder.created_at,
|
|
"updated_at": folder.updated_at,
|
|
"metadata": metadata,
|
|
"sub_folders": sub_folders_json,
|
|
"files": files_json,
|
|
}))
|
|
})
|
|
}
|