feat: distinct upload and delete operation
This commit is contained in:
parent
be3ae2fe00
commit
3032052923
4 changed files with 83 additions and 37 deletions
19
README.md
19
README.md
|
@ -44,14 +44,25 @@ duf
|
||||||
duf folder_name
|
duf folder_name
|
||||||
```
|
```
|
||||||
|
|
||||||
Only serve static files, disable editing operations such as update or delete
|
Allow upload operations
|
||||||
|
|
||||||
```
|
```
|
||||||
duf --readonly
|
duf --allow-upload
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, run this command to see a list of all available option
|
Allow all operations
|
||||||
|
|
||||||
### Curl
|
```
|
||||||
|
duf --allow-all
|
||||||
|
```
|
||||||
|
|
||||||
|
Use http authentication
|
||||||
|
|
||||||
|
```
|
||||||
|
duf --auth user:pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### Api
|
||||||
|
|
||||||
Download a file
|
Download a file
|
||||||
```
|
```
|
||||||
|
|
30
src/args.rs
30
src/args.rs
|
@ -35,10 +35,20 @@ fn app() -> clap::Command<'static> {
|
||||||
.help("Path to a directory for serving files"),
|
.help("Path to a directory for serving files"),
|
||||||
)
|
)
|
||||||
.arg(
|
.arg(
|
||||||
Arg::new("readonly")
|
Arg::new("allow-all")
|
||||||
.short('r')
|
.short('A')
|
||||||
.long("readonly")
|
.long("allow-all")
|
||||||
.help("Disable change operations such as update or delete"),
|
.help("Allow all operations"),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("allow-upload")
|
||||||
|
.long("allow-upload")
|
||||||
|
.help("Allow upload operation"),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("allow-delete")
|
||||||
|
.long("allo-delete")
|
||||||
|
.help("Allow delete operation"),
|
||||||
)
|
)
|
||||||
.arg(
|
.arg(
|
||||||
Arg::new("auth")
|
Arg::new("auth")
|
||||||
|
@ -68,9 +78,10 @@ pub struct Args {
|
||||||
pub address: String,
|
pub address: String,
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
pub path: PathBuf,
|
pub path: PathBuf,
|
||||||
pub readonly: bool,
|
|
||||||
pub auth: Option<String>,
|
pub auth: Option<String>,
|
||||||
pub no_auth_read: bool,
|
pub no_auth_read: bool,
|
||||||
|
pub allow_upload: bool,
|
||||||
|
pub allow_delete: bool,
|
||||||
pub cors: bool,
|
pub cors: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -82,21 +93,22 @@ impl Args {
|
||||||
pub fn parse(matches: ArgMatches) -> BoxResult<Args> {
|
pub fn parse(matches: ArgMatches) -> BoxResult<Args> {
|
||||||
let address = matches.value_of("address").unwrap_or_default().to_owned();
|
let address = matches.value_of("address").unwrap_or_default().to_owned();
|
||||||
let port = matches.value_of_t::<u16>("port")?;
|
let port = matches.value_of_t::<u16>("port")?;
|
||||||
let path = matches.value_of_os("path").unwrap_or_default();
|
let path = Args::parse_path(matches.value_of_os("path").unwrap_or_default())?;
|
||||||
let path = Args::parse_path(path)?;
|
|
||||||
let readonly = matches.is_present("readonly");
|
|
||||||
let cors = matches.is_present("cors");
|
let cors = matches.is_present("cors");
|
||||||
let auth = matches.value_of("auth").map(|v| v.to_owned());
|
let auth = matches.value_of("auth").map(|v| v.to_owned());
|
||||||
let no_auth_read = matches.is_present("no-auth-read");
|
let no_auth_read = matches.is_present("no-auth-read");
|
||||||
|
let allow_upload = matches.is_present("allow-all") || matches.is_present("allow-upload");
|
||||||
|
let allow_delete = matches.is_present("allow-all") || matches.is_present("allow-delete");
|
||||||
|
|
||||||
Ok(Args {
|
Ok(Args {
|
||||||
address,
|
address,
|
||||||
port,
|
port,
|
||||||
path,
|
path,
|
||||||
readonly,
|
|
||||||
auth,
|
auth,
|
||||||
no_auth_read,
|
no_auth_read,
|
||||||
cors,
|
cors,
|
||||||
|
allow_delete,
|
||||||
|
allow_upload,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -97,7 +97,7 @@ function addPath(file, index) {
|
||||||
</a>
|
</a>
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
if (!DATA.readonly) {
|
if (DATA.allow_delete) {
|
||||||
actionDelete = `
|
actionDelete = `
|
||||||
<div onclick="deletePath(${index})" class="action-btn" id="deleteBtn${index}" title="Delete ${file.name}">
|
<div onclick="deletePath(${index})" class="action-btn" id="deleteBtn${index}" title="Delete ${file.name}">
|
||||||
<svg width="16" height="16" fill="currentColor"viewBox="0 0 16 16"><path d="M6.854 7.146a.5.5 0 1 0-.708.708L7.293 9l-1.147 1.146a.5.5 0 0 0 .708.708L8 9.707l1.146 1.147a.5.5 0 0 0 .708-.708L8.707 9l1.147-1.146a.5.5 0 0 0-.708-.708L8 8.293 6.854 7.146z"/><path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"/></svg>
|
<svg width="16" height="16" fill="currentColor"viewBox="0 0 16 16"><path d="M6.854 7.146a.5.5 0 1 0-.708.708L7.293 9l-1.147 1.146a.5.5 0 0 0 .708.708L8 9.707l1.146 1.147a.5.5 0 0 0 .708-.708L8.707 9l1.147-1.146a.5.5 0 0 0-.708-.708L8 8.293 6.854 7.146z"/><path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"/></svg>
|
||||||
|
@ -137,7 +137,7 @@ async function deletePath(index) {
|
||||||
throw new Error(await res.text())
|
throw new Error(await res.text())
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert(`Fail to delete ${file.name}, ${err.message}`);
|
alert(`Cannot delete \`${file.name}\`, ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -191,7 +191,7 @@ function ready() {
|
||||||
|
|
||||||
addBreadcrumb(DATA.breadcrumb);
|
addBreadcrumb(DATA.breadcrumb);
|
||||||
DATA.paths.forEach((file, index) => addPath(file, index));
|
DATA.paths.forEach((file, index) => addPath(file, index));
|
||||||
if (!DATA.readonly) {
|
if (DATA.allow_upload) {
|
||||||
document.querySelector(".upload-control").classList.remove(["hidden"]);
|
document.querySelector(".upload-control").classList.remove(["hidden"]);
|
||||||
document.getElementById("file").addEventListener("change", e => {
|
document.getElementById("file").addEventListener("change", e => {
|
||||||
const files = e.target.files;
|
const files = e.target.files;
|
||||||
|
|
|
@ -33,6 +33,13 @@ const INDEX_CSS: &str = include_str!("assets/index.css");
|
||||||
const INDEX_JS: &str = include_str!("assets/index.js");
|
const INDEX_JS: &str = include_str!("assets/index.js");
|
||||||
const BUF_SIZE: usize = 1024 * 16;
|
const BUF_SIZE: usize = 1024 * 16;
|
||||||
|
|
||||||
|
macro_rules! status {
|
||||||
|
($res:ident, $status:expr) => {
|
||||||
|
*$res.status_mut() = $status;
|
||||||
|
*$res.body_mut() = Body::from($status.canonical_reason().unwrap_or_default());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn serve(args: Args) -> BoxResult<()> {
|
pub async fn serve(args: Args) -> BoxResult<()> {
|
||||||
let address = args.address()?;
|
let address = args.address()?;
|
||||||
let inner = Arc::new(InnerService::new(args));
|
let inner = Arc::new(InnerService::new(args));
|
||||||
|
@ -68,14 +75,18 @@ impl InnerService {
|
||||||
let uri = req.uri().clone();
|
let uri = req.uri().clone();
|
||||||
let cors = self.args.cors;
|
let cors = self.args.cors;
|
||||||
|
|
||||||
let mut res = self.handle(req).await.unwrap_or_else(|e| {
|
let mut res = match self.handle(req).await {
|
||||||
let mut res = Response::default();
|
Ok(res) => {
|
||||||
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
info!(r#""{} {}" - {}"#, method, uri, res.status());
|
||||||
*res.body_mut() = Body::from(e.to_string());
|
res
|
||||||
res
|
}
|
||||||
});
|
Err(err) => {
|
||||||
|
let mut res = Response::default();
|
||||||
info!(r#""{} {}" - {}"#, method, uri, res.status());
|
status!(res, StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
error!(r#""{} {}" - {} {}"#, method, uri, res.status(), err);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if cors {
|
if cors {
|
||||||
add_cors(&mut res);
|
add_cors(&mut res);
|
||||||
|
@ -95,7 +106,7 @@ impl InnerService {
|
||||||
let filepath = match self.extract_path(path) {
|
let filepath = match self.extract_path(path) {
|
||||||
Some(v) => v,
|
Some(v) => v,
|
||||||
None => {
|
None => {
|
||||||
*res.status_mut() = StatusCode::FORBIDDEN;
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -106,8 +117,10 @@ impl InnerService {
|
||||||
let meta = fs::metadata(filepath).await.ok();
|
let meta = fs::metadata(filepath).await.ok();
|
||||||
let is_miss = meta.is_none();
|
let is_miss = meta.is_none();
|
||||||
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
||||||
|
let is_file = !is_miss && !is_dir;
|
||||||
|
|
||||||
let readonly = self.args.readonly;
|
let allow_upload = self.args.allow_upload;
|
||||||
|
let allow_delete = self.args.allow_delete;
|
||||||
|
|
||||||
match *req.method() {
|
match *req.method() {
|
||||||
Method::GET if is_dir && query == "zip" => {
|
Method::GET if is_dir && query == "zip" => {
|
||||||
|
@ -117,7 +130,7 @@ impl InnerService {
|
||||||
self.handle_query_dir(filepath, &query[3..], &mut res)
|
self.handle_query_dir(filepath, &query[3..], &mut res)
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
Method::GET if !is_dir && !is_miss => {
|
Method::GET if is_file => {
|
||||||
self.handle_send_file(filepath, req.headers(), &mut res)
|
self.handle_send_file(filepath, req.headers(), &mut res)
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
|
@ -125,12 +138,20 @@ impl InnerService {
|
||||||
self.handle_ls_dir(filepath, false, &mut res).await?
|
self.handle_ls_dir(filepath, false, &mut res).await?
|
||||||
}
|
}
|
||||||
Method::GET => self.handle_ls_dir(filepath, true, &mut res).await?,
|
Method::GET => self.handle_ls_dir(filepath, true, &mut res).await?,
|
||||||
Method::OPTIONS => *res.status_mut() = StatusCode::NO_CONTENT,
|
Method::OPTIONS => {
|
||||||
Method::PUT if readonly => *res.status_mut() = StatusCode::FORBIDDEN,
|
status!(res, StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
Method::PUT if !allow_upload || (!allow_delete && is_file) => {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
Method::PUT => self.handle_upload(filepath, req, &mut res).await?,
|
Method::PUT => self.handle_upload(filepath, req, &mut res).await?,
|
||||||
Method::DELETE if !is_miss && readonly => *res.status_mut() = StatusCode::FORBIDDEN,
|
Method::DELETE if !allow_delete => {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
Method::DELETE if !is_miss => self.handle_delete(filepath, is_dir).await?,
|
Method::DELETE if !is_miss => self.handle_delete(filepath, is_dir).await?,
|
||||||
_ => *res.status_mut() = StatusCode::NOT_FOUND,
|
_ => {
|
||||||
|
status!(res, StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(res)
|
Ok(res)
|
||||||
|
@ -153,7 +174,7 @@ impl InnerService {
|
||||||
None => false,
|
None => false,
|
||||||
};
|
};
|
||||||
if !ensure_parent {
|
if !ensure_parent {
|
||||||
*res.status_mut() = StatusCode::FORBIDDEN;
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -288,7 +309,7 @@ impl InnerService {
|
||||||
res.headers_mut().typed_insert(last_modified);
|
res.headers_mut().typed_insert(last_modified);
|
||||||
res.headers_mut().typed_insert(etag);
|
res.headers_mut().typed_insert(etag);
|
||||||
if fresh {
|
if fresh {
|
||||||
*res.status_mut() = StatusCode::NOT_MODIFIED;
|
status!(res, StatusCode::NOT_MODIFIED);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -316,7 +337,8 @@ impl InnerService {
|
||||||
let data = IndexData {
|
let data = IndexData {
|
||||||
breadcrumb: normalize_path(rel_path),
|
breadcrumb: normalize_path(rel_path),
|
||||||
paths,
|
paths,
|
||||||
readonly: self.args.readonly,
|
allow_upload: self.args.allow_upload,
|
||||||
|
allow_delete: self.args.allow_delete,
|
||||||
};
|
};
|
||||||
let data = serde_json::to_string(&data).unwrap();
|
let data = serde_json::to_string(&data).unwrap();
|
||||||
let output = INDEX_HTML.replace(
|
let output = INDEX_HTML.replace(
|
||||||
|
@ -347,7 +369,7 @@ impl InnerService {
|
||||||
let mut it = v.split(' ');
|
let mut it = v.split(' ');
|
||||||
(it.next(), it.next())
|
(it.next(), it.next())
|
||||||
}) {
|
}) {
|
||||||
Some((Some("Basic "), Some(tail))) => base64::decode(tail)
|
Some((Some("Basic"), Some(tail))) => base64::decode(tail)
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|v| String::from_utf8(v).ok())
|
.and_then(|v| String::from_utf8(v).ok())
|
||||||
.map(|v| v.as_str() == auth)
|
.map(|v| v.as_str() == auth)
|
||||||
|
@ -359,7 +381,7 @@ impl InnerService {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if !pass {
|
if !pass {
|
||||||
*res.status_mut() = StatusCode::UNAUTHORIZED;
|
status!(res, StatusCode::UNAUTHORIZED);
|
||||||
res.headers_mut()
|
res.headers_mut()
|
||||||
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
|
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
|
||||||
}
|
}
|
||||||
|
@ -386,7 +408,8 @@ impl InnerService {
|
||||||
struct IndexData {
|
struct IndexData {
|
||||||
breadcrumb: String,
|
breadcrumb: String,
|
||||||
paths: Vec<PathItem>,
|
paths: Vec<PathItem>,
|
||||||
readonly: bool,
|
allow_upload: bool,
|
||||||
|
allow_delete: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||||
|
|
Loading…
Reference in a new issue