mirror of
https://github.com/sigoden/dufs.git
synced 2026-04-09 17:13:02 +03:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
584d33940a | ||
|
|
fc090b6930 | ||
|
|
19d7b36462 | ||
|
|
755554d3f2 | ||
|
|
6a097e0496 | ||
|
|
412d42e338 | ||
|
|
ec60752ba2 | ||
|
|
ed7f5e425a | ||
|
|
3032052923 | ||
|
|
be3ae2fe00 | ||
|
|
fb03f7ddb8 | ||
|
|
54df4633e1 | ||
|
|
6b293c0f2e | ||
|
|
62696b45fd | ||
|
|
d9547ad00b | ||
|
|
8fbc742c52 | ||
|
|
d8d5aae898 |
22
Cargo.lock
generated
22
Cargo.lock
generated
@@ -296,7 +296,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.4.0"
|
version = "0.7.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-walkdir",
|
"async-walkdir",
|
||||||
"async_zip",
|
"async_zip",
|
||||||
@@ -306,6 +306,7 @@ dependencies = [
|
|||||||
"headers",
|
"headers",
|
||||||
"hyper",
|
"hyper",
|
||||||
"log",
|
"log",
|
||||||
|
"mime_guess",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -636,6 +637,16 @@ version = "0.3.16"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
|
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mime_guess"
|
||||||
|
version = "2.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
|
||||||
|
dependencies = [
|
||||||
|
"mime",
|
||||||
|
"unicase",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.5.1"
|
version = "0.5.1"
|
||||||
@@ -991,6 +1002,15 @@ version = "1.15.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
|
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicase"
|
||||||
|
version = "2.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
|
||||||
|
dependencies = [
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.4.0"
|
version = "0.7.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["sigoden <sigoden@gmail.com>"]
|
authors = ["sigoden <sigoden@gmail.com>"]
|
||||||
description = "Duf is a simple file server."
|
description = "Duf is a simple file server."
|
||||||
@@ -26,6 +26,7 @@ simple_logger = "2.1.0"
|
|||||||
async_zip = "0.0.7"
|
async_zip = "0.0.7"
|
||||||
async-walkdir = "0.2.0"
|
async-walkdir = "0.2.0"
|
||||||
headers = "0.3.7"
|
headers = "0.3.7"
|
||||||
|
mime_guess = "2.0.4"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
|
|||||||
28
README.md
28
README.md
@@ -12,9 +12,10 @@ Duf is a simple file server.
|
|||||||
- Serve static files
|
- Serve static files
|
||||||
- Download folder as zip file
|
- Download folder as zip file
|
||||||
- Search files
|
- Search files
|
||||||
- Upload files
|
- Upload files and folders
|
||||||
- Delete files
|
- Delete files
|
||||||
- Basic authentication
|
- Basic authentication
|
||||||
|
- Upload zip file then unzip
|
||||||
- Easy to use with curl
|
- Easy to use with curl
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
@@ -43,14 +44,25 @@ duf
|
|||||||
duf folder_name
|
duf folder_name
|
||||||
```
|
```
|
||||||
|
|
||||||
Only serve static files, disable editing operations such as update or delete
|
Allow all operations such as upload, delete
|
||||||
|
|
||||||
```
|
```
|
||||||
duf --no-change
|
duf --allow-all
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, run this command to see a list of all available option
|
Only allow upload operations
|
||||||
|
|
||||||
### Curl
|
```
|
||||||
|
duf --allow-upload
|
||||||
|
```
|
||||||
|
|
||||||
|
Use http authentication
|
||||||
|
|
||||||
|
```
|
||||||
|
duf --auth user:pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### Api
|
||||||
|
|
||||||
Download a file
|
Download a file
|
||||||
```
|
```
|
||||||
@@ -71,6 +83,12 @@ Upload a file
|
|||||||
curl --upload-file some-file http://127.0.0.1:5000/some-file
|
curl --upload-file some-file http://127.0.0.1:5000/some-file
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Unzip zip file when unload
|
||||||
|
|
||||||
|
```
|
||||||
|
curl --upload-file some-folder.zip http://127.0.0.1:5000/some-folder.zip?unzip
|
||||||
|
```
|
||||||
|
|
||||||
Delete a file/folder
|
Delete a file/folder
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
40
src/args.rs
40
src/args.rs
@@ -35,18 +35,33 @@ 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("no-change")
|
Arg::new("allow-all")
|
||||||
.short('C')
|
.short('A')
|
||||||
.long("no-change")
|
.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")
|
||||||
.short('a')
|
.short('a')
|
||||||
.long("auth")
|
.long("auth")
|
||||||
.help("Authenticate with user and pass")
|
.help("Use HTTP authentication for all operations")
|
||||||
.value_name("user:pass"),
|
.value_name("user:pass"),
|
||||||
)
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("no-auth-read")
|
||||||
|
.long("no-auth-read")
|
||||||
|
.help("Do not authenticate read operations like static serving"),
|
||||||
|
)
|
||||||
.arg(
|
.arg(
|
||||||
Arg::new("cors")
|
Arg::new("cors")
|
||||||
.long("cors")
|
.long("cors")
|
||||||
@@ -63,8 +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 allow_upload: bool,
|
||||||
|
pub allow_delete: bool,
|
||||||
pub cors: bool,
|
pub cors: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,19 +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("no-change");
|
|
||||||
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 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,
|
||||||
cors,
|
cors,
|
||||||
|
allow_delete,
|
||||||
|
allow_upload,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ body {
|
|||||||
width: 700px;
|
width: 700px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.head {
|
.head {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -115,7 +119,7 @@ body {
|
|||||||
|
|
||||||
.main .cell-size {
|
.main .cell-size {
|
||||||
text-align: right;
|
text-align: right;
|
||||||
width: 60px;
|
width: 70px;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,8 +159,6 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.uploaders {
|
.uploaders {
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
padding: 0.5em 0;
|
padding: 0.5em 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
53
src/assets/index.html
Normal file
53
src/assets/index.html
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width" />
|
||||||
|
__SLOT__
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="head">
|
||||||
|
<div class="breadcrumb"></div>
|
||||||
|
<div class="toolbox">
|
||||||
|
<div>
|
||||||
|
<a href="?zip" title="Download folder as a .zip file">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div class="upload-control hidden" title="Upload files">
|
||||||
|
<label for="file">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg>
|
||||||
|
</label>
|
||||||
|
<input type="file" id="file" name="file" multiple>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form class="searchbar">
|
||||||
|
<div class="icon">
|
||||||
|
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/></svg>
|
||||||
|
</div>
|
||||||
|
<input id="search" name="q" type="text" maxlength="128" autocomplete="off" tabindex="1">
|
||||||
|
<input type="submit" hidden />
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="main">
|
||||||
|
<div class="uploaders">
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="cell-name">Name</th>
|
||||||
|
<th class="cell-mtime">Date modify</th>
|
||||||
|
<th class="cell-size">Size</th>
|
||||||
|
<th class="cell-actions">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
window.addEventListener("DOMContentLoaded", ready);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
247
src/assets/index.js
Normal file
247
src/assets/index.js
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
let $tbody, $uploaders;
|
||||||
|
let baseDir;
|
||||||
|
|
||||||
|
class Uploader {
|
||||||
|
idx;
|
||||||
|
file;
|
||||||
|
name;
|
||||||
|
$elem;
|
||||||
|
static globalIdx = 0;
|
||||||
|
constructor(file, dirs) {
|
||||||
|
this.name = [...dirs, file.name].join("/");
|
||||||
|
this.idx = Uploader.globalIdx++;
|
||||||
|
this.file = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
upload() {
|
||||||
|
const { file, idx, name } = this;
|
||||||
|
let url = getUrl(name);
|
||||||
|
if (file.name == baseDir + ".zip") {
|
||||||
|
url += "?unzip";
|
||||||
|
}
|
||||||
|
$uploaders.insertAdjacentHTML("beforeend", `
|
||||||
|
<div class="uploader path">
|
||||||
|
<div><svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg></div>
|
||||||
|
<a href="${url}" id="file${idx}">${name} (0%)</a>
|
||||||
|
</div>`);
|
||||||
|
this.$elem = document.getElementById(`file${idx}`);
|
||||||
|
|
||||||
|
const ajax = new XMLHttpRequest();
|
||||||
|
ajax.upload.addEventListener("progress", e => this.progress(e), false);
|
||||||
|
ajax.addEventListener("readystatechange", () => {
|
||||||
|
if(ajax.readyState === 4) {
|
||||||
|
if (ajax.status == 200) {
|
||||||
|
this.complete();
|
||||||
|
} else {
|
||||||
|
this.fail();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
ajax.addEventListener("error", () => this.fail(), false);
|
||||||
|
ajax.addEventListener("abort", () => this.fail(), false);
|
||||||
|
ajax.open("PUT", url);
|
||||||
|
ajax.send(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress(event) {
|
||||||
|
const percent = (event.loaded / event.total) * 100;
|
||||||
|
this.$elem.innerHTML = `${this.name} (${percent.toFixed(2)}%)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
complete() {
|
||||||
|
this.$elem.innerHTML = `${this.name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
this.$elem.innerHTML = `<strike>${this.name}</strike>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addBreadcrumb(value) {
|
||||||
|
const $breadcrumb = document.querySelector(".breadcrumb");
|
||||||
|
const parts = value.split("/").filter(v => !!v);
|
||||||
|
const len = parts.length;
|
||||||
|
let path = "";
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
const name = parts[i];
|
||||||
|
if (i > 0) {
|
||||||
|
path += "/" + name;
|
||||||
|
}
|
||||||
|
if (i === len - 1) {
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<b>${name}</b>`);
|
||||||
|
baseDir = name;
|
||||||
|
} else if (i === 0) {
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="/"><b>${name}</b></a>`);
|
||||||
|
} else {
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="${encodeURI(path)}">${name}</a>`);
|
||||||
|
}
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<span class="separator">/</span>`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addPath(file, index) {
|
||||||
|
const url = getUrl(file.name)
|
||||||
|
let actionDelete = "";
|
||||||
|
let actionDownload = "";
|
||||||
|
if (file.path_type.endsWith("Dir")) {
|
||||||
|
actionDownload = `
|
||||||
|
<div class="action-btn">
|
||||||
|
<a href="${url}?zip" title="Download folder as a .zip file">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
||||||
|
</a>
|
||||||
|
</div>`;
|
||||||
|
} else {
|
||||||
|
actionDownload = `
|
||||||
|
<div class="action-btn" >
|
||||||
|
<a href="${url}" title="Download file" download>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
||||||
|
</a>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
if (DATA.allow_delete) {
|
||||||
|
actionDelete = `
|
||||||
|
<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>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
let actionCell = `
|
||||||
|
<td class="cell-actions">
|
||||||
|
${actionDownload}
|
||||||
|
${actionDelete}
|
||||||
|
</td>`
|
||||||
|
|
||||||
|
$tbody.insertAdjacentHTML("beforeend", `
|
||||||
|
<tr id="addPath${index}">
|
||||||
|
<td class="path cell-name">
|
||||||
|
<div>${getSvg(file.path_type)}</div>
|
||||||
|
<a href="${url}" title="${file.name}">${file.name}</a>
|
||||||
|
</td>
|
||||||
|
<td class="cell-mtime">${formatMtime(file.mtime)}</td>
|
||||||
|
<td class="cell-size">${formatSize(file.size)}</td>
|
||||||
|
${actionCell}
|
||||||
|
</tr>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deletePath(index) {
|
||||||
|
const file = DATA.paths[index];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
if (!confirm(`Delete \`${file.name}\`?`)) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(getUrl(file.name), {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
if (res.status === 200) {
|
||||||
|
document.getElementById(`addPath${index}`).remove();
|
||||||
|
} else {
|
||||||
|
throw new Error(await res.text())
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert(`Cannot delete \`${file.name}\`, ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropzone() {
|
||||||
|
["drag", "dragstart", "dragend", "dragover", "dragenter", "dragleave", "drop"].forEach(name => {
|
||||||
|
document.addEventListener(name, e => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
document.addEventListener("drop", e => {
|
||||||
|
if (!e.dataTransfer.items[0].webkitGetAsEntry) {
|
||||||
|
const files = e.dataTransfer.files.filter(v => v.size > 0);
|
||||||
|
for (const file of files) {
|
||||||
|
new Uploader(file, []).upload();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const entries = [];
|
||||||
|
const len = e.dataTransfer.items.length;
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
entries.push(e.dataTransfer.items[i].webkitGetAsEntry());
|
||||||
|
}
|
||||||
|
addFileEntries(entries, [])
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addFileEntries(entries, dirs) {
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.isFile) {
|
||||||
|
entry.file(file => {
|
||||||
|
new Uploader(file, dirs).upload();
|
||||||
|
});
|
||||||
|
} else if (entry.isDirectory) {
|
||||||
|
const dirReader = entry.createReader()
|
||||||
|
dirReader.readEntries(entries => addFileEntries(entries, [...dirs, entry.name]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function getUrl(name) {
|
||||||
|
let url = location.href.split('?')[0];
|
||||||
|
if (!url.endsWith("/")) url += "/";
|
||||||
|
url += encodeURI(name);
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSvg(path_type) {
|
||||||
|
switch (path_type) {
|
||||||
|
case "Dir":
|
||||||
|
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM6 4H1V3h5v1z"></path></svg>`;
|
||||||
|
case "File":
|
||||||
|
return `<svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg>`;
|
||||||
|
case "SymlinkDir":
|
||||||
|
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM1 3h5v1H1V3zm6 9v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73C4.86 8.43 5.82 8 7.01 8V6l4 3-4 3H7z"></path></svg>`;
|
||||||
|
default:
|
||||||
|
return `<svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM6 4.5l4 3-4 3v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73.73-.84 1.69-1.27 2.88-1.27v-2H6z"></path></svg>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMtime(mtime) {
|
||||||
|
if (!mtime) return ""
|
||||||
|
const date = new Date(mtime);
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = padZero(date.getMonth() + 1, 2);
|
||||||
|
const day = padZero(date.getDate(), 2);
|
||||||
|
const hours = padZero(date.getHours(), 2);
|
||||||
|
const minutes = padZero(date.getMinutes(), 2);
|
||||||
|
return `${year}/${month}/${day} ${hours}:${minutes}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function padZero(value, size) {
|
||||||
|
return ("0".repeat(size) + value).slice(-1 * size)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(size) {
|
||||||
|
if (!size) return ""
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
if (size == 0) return '0 Byte';
|
||||||
|
const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
|
||||||
|
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
function ready() {
|
||||||
|
$tbody = document.querySelector(".main tbody");
|
||||||
|
$uploaders = document.querySelector(".uploaders");
|
||||||
|
|
||||||
|
addBreadcrumb(DATA.breadcrumb);
|
||||||
|
if (Array.isArray(DATA.paths)) {
|
||||||
|
const len = DATA.paths.length;
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
addPath(DATA.paths[i], i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (DATA.allow_upload) {
|
||||||
|
dropzone();
|
||||||
|
document.querySelector(".upload-control").classList.remove(["hidden"]);
|
||||||
|
document.getElementById("file").addEventListener("change", e => {
|
||||||
|
const files = e.target.files;
|
||||||
|
for (let file of files) {
|
||||||
|
new Uploader(file, []).upload();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
246
src/index.html
246
src/index.html
@@ -1,246 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width" />
|
|
||||||
<title>Duf</title>
|
|
||||||
__STYLE__
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="head">
|
|
||||||
<div class="breadcrumb"></div>
|
|
||||||
<div class="toolbox">
|
|
||||||
<div>
|
|
||||||
<a href="?zip" title="Download folder as a .zip file">
|
|
||||||
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<form class="searchbar">
|
|
||||||
<div class="icon">
|
|
||||||
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/></svg>
|
|
||||||
</div>
|
|
||||||
<input id="search" name="q" type="text" maxlength="128" autocomplete="off" tabindex="1">
|
|
||||||
<input type="submit" hidden />
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
<div class="main">
|
|
||||||
<div class="uploaders">
|
|
||||||
</div>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th class="cell-name">Name</th>
|
|
||||||
<th class="cell-mtime">Date modify</th>
|
|
||||||
<th class="cell-size">Size</th>
|
|
||||||
<th class="cell-actions">Actions</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
|
|
||||||
const $toolbox = document.querySelector(".toolbox");
|
|
||||||
const $tbody = document.querySelector(".main tbody");
|
|
||||||
const $breadcrumb = document.querySelector(".breadcrumb");
|
|
||||||
const $uploaders = document.querySelector(".uploaders");
|
|
||||||
const $uploadControl = document.querySelector(".upload-control");
|
|
||||||
const { breadcrumb, paths, readonly } = __DATA__;
|
|
||||||
let uploaderIdx = 0;
|
|
||||||
|
|
||||||
class Uploader {
|
|
||||||
idx = 0;
|
|
||||||
file;
|
|
||||||
$elem;
|
|
||||||
constructor(idx, file) {
|
|
||||||
this.idx = idx;
|
|
||||||
this.file = file;
|
|
||||||
}
|
|
||||||
|
|
||||||
upload() {
|
|
||||||
const { file, idx } = this;
|
|
||||||
const url = getUrl(file.name);
|
|
||||||
$uploaders.insertAdjacentHTML("beforeend", `
|
|
||||||
<div class="uploader path">
|
|
||||||
<div><svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg></div>
|
|
||||||
<a href="${url}" id="file${idx}">${file.name} (0%)</a>
|
|
||||||
</div>`);
|
|
||||||
this.$elem = document.getElementById(`file${idx}`);
|
|
||||||
|
|
||||||
const ajax = new XMLHttpRequest();
|
|
||||||
ajax.upload.addEventListener("progress", e => this.progress(e), false);
|
|
||||||
ajax.addEventListener("load", e => this.complete(e), false);
|
|
||||||
ajax.addEventListener("error", e => this.fail(e), false);
|
|
||||||
ajax.addEventListener("abort", e => this.fail(e), false);
|
|
||||||
ajax.open("PUT", url);
|
|
||||||
ajax.send(file);
|
|
||||||
}
|
|
||||||
|
|
||||||
progress(event) {
|
|
||||||
const percent = (event.loaded / event.total) * 100;
|
|
||||||
this.$elem.innerHTML = `${this.file.name} (${percent.toFixed(2)}%)`;
|
|
||||||
}
|
|
||||||
|
|
||||||
complete(event) {
|
|
||||||
this.$elem.innerHTML = `${this.file.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
fail(event) {
|
|
||||||
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addBreadcrumb(value) {
|
|
||||||
const parts = value.split("/").filter(v => !!v);
|
|
||||||
const len = parts.length;
|
|
||||||
let path = "";
|
|
||||||
for (let i = 0; i < len; i++) {
|
|
||||||
const name = parts[i];
|
|
||||||
if (i > 0) {
|
|
||||||
path += "/" + name;
|
|
||||||
}
|
|
||||||
if (i === len - 1) {
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<b>${name}</b>`);
|
|
||||||
} else if (i === 0) {
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="/"><b>${name}</b></a>`);
|
|
||||||
} else {
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="${encodeURI(path)}">${name}</a>`);
|
|
||||||
}
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<span class="separator">/</span>`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addPath(file, index) {
|
|
||||||
const url = getUrl(file.name)
|
|
||||||
let actionDelete = "";
|
|
||||||
let actionDownload = "";
|
|
||||||
if (file.path_type.endsWith("Dir")) {
|
|
||||||
actionDownload = `
|
|
||||||
<div class="action-btn">
|
|
||||||
<a href="${url}?zip" title="Download folder as a .zip file">
|
|
||||||
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
|
||||||
</a>
|
|
||||||
</div>`;
|
|
||||||
} else {
|
|
||||||
actionDownload = `
|
|
||||||
<div class="action-btn" >
|
|
||||||
<a href="${url}" title="Download file" download>
|
|
||||||
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
|
||||||
</a>
|
|
||||||
</div>`;
|
|
||||||
}
|
|
||||||
if (!readonly) {
|
|
||||||
actionDelete = `
|
|
||||||
<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>
|
|
||||||
</div>`;
|
|
||||||
}
|
|
||||||
const actionCell = `
|
|
||||||
<td class="cell-actions">
|
|
||||||
${actionDownload}
|
|
||||||
${actionDelete}
|
|
||||||
</td>`
|
|
||||||
|
|
||||||
$tbody.insertAdjacentHTML("beforeend", `
|
|
||||||
<tr id="addPath${index}">
|
|
||||||
<td class="path cell-name">
|
|
||||||
<div>${getSvg(file.path_type)}</div>
|
|
||||||
<a href="${url}" title="${file.name}">${file.name}</a>
|
|
||||||
</td>
|
|
||||||
<td class="cell-mtime">${formatMtime(file.mtime)}</td>
|
|
||||||
<td class="cell-size">${formatSize(file.size)}</td>
|
|
||||||
${actionCell}
|
|
||||||
</tr>`)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deletePath(index) {
|
|
||||||
const file = paths[index];
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
const ajax = new XMLHttpRequest();
|
|
||||||
ajax.open("DELETE", getUrl(file.name));
|
|
||||||
ajax.addEventListener("readystatechange", function() {
|
|
||||||
if(ajax.readyState === 4 && ajax.status === 200) {
|
|
||||||
document.getElementById(`addPath${index}`).remove();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ajax.send();
|
|
||||||
}
|
|
||||||
|
|
||||||
function addUploadControl() {
|
|
||||||
$toolbox.insertAdjacentHTML("beforeend", `
|
|
||||||
<div class="upload-control" title="Upload file">
|
|
||||||
<label for="file">
|
|
||||||
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg>
|
|
||||||
</label>
|
|
||||||
<input type="file" id="file" name="file" multiple>
|
|
||||||
</div>
|
|
||||||
`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getUrl(name) {
|
|
||||||
let url = location.href.split('?')[0];
|
|
||||||
if (!url.endsWith("/")) url += "/";
|
|
||||||
url += encodeURI(name);
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSvg(path_type) {
|
|
||||||
switch (path_type) {
|
|
||||||
case "Dir":
|
|
||||||
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM6 4H1V3h5v1z"></path></svg>`;
|
|
||||||
case "File":
|
|
||||||
return `<svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg>`;
|
|
||||||
case "SymlinkDir":
|
|
||||||
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM1 3h5v1H1V3zm6 9v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73C4.86 8.43 5.82 8 7.01 8V6l4 3-4 3H7z"></path></svg>`;
|
|
||||||
default:
|
|
||||||
return `<svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM6 4.5l4 3-4 3v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73.73-.84 1.69-1.27 2.88-1.27v-2H6z"></path></svg>`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatMtime(mtime) {
|
|
||||||
if (!mtime) return ""
|
|
||||||
const date = new Date(mtime);
|
|
||||||
const year = date.getFullYear();
|
|
||||||
const month = padZero(date.getMonth() + 1, 2);
|
|
||||||
const day = padZero(date.getDate(), 2);
|
|
||||||
const hours = padZero(date.getHours(), 2);
|
|
||||||
const minutes = padZero(date.getMinutes(), 2);
|
|
||||||
return `${year}/${month}/${day} ${hours}:${minutes}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function padZero(value, size) {
|
|
||||||
return ("0".repeat(size) + value).slice(-1 * size)
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatSize(size) {
|
|
||||||
if (!size) return ""
|
|
||||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
|
||||||
if (size == 0) return '0 Byte';
|
|
||||||
const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
|
|
||||||
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
addBreadcrumb(breadcrumb);
|
|
||||||
paths.forEach((file, index) => addPath(file, index));
|
|
||||||
if (!readonly) {
|
|
||||||
addUploadControl();
|
|
||||||
document.getElementById("file").addEventListener("change", e => {
|
|
||||||
const files = e.target.files;
|
|
||||||
for (const file of files) {
|
|
||||||
uploaderIdx += 1;
|
|
||||||
const uploader = new Uploader(uploaderIdx, file);
|
|
||||||
uploader.upload();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
491
src/server.rs
491
src/server.rs
@@ -1,22 +1,30 @@
|
|||||||
use crate::{Args, BoxResult};
|
use crate::{Args, BoxResult};
|
||||||
|
|
||||||
use async_walkdir::WalkDir;
|
use async_walkdir::WalkDir;
|
||||||
|
use async_zip::read::seek::ZipFileReader;
|
||||||
use async_zip::write::{EntryOptions, ZipFileWriter};
|
use async_zip::write::{EntryOptions, ZipFileWriter};
|
||||||
use async_zip::Compression;
|
use async_zip::Compression;
|
||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
use headers::{AccessControlAllowHeaders, AccessControlAllowOrigin, HeaderMapExt};
|
use headers::{
|
||||||
use hyper::header::{HeaderValue, ACCEPT, CONTENT_TYPE, ORIGIN, RANGE, WWW_AUTHENTICATE};
|
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentRange, ContentType, ETag,
|
||||||
|
HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, LastModified, Range,
|
||||||
|
};
|
||||||
|
use hyper::header::{
|
||||||
|
HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_TYPE, ORIGIN, RANGE,
|
||||||
|
WWW_AUTHENTICATE,
|
||||||
|
};
|
||||||
use hyper::service::{make_service_fn, service_fn};
|
use hyper::service::{make_service_fn, service_fn};
|
||||||
use hyper::{Body, Method, StatusCode};
|
use hyper::{Body, Method, StatusCode};
|
||||||
use percent_encoding::percent_decode;
|
use percent_encoding::percent_decode;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::convert::Infallible;
|
use std::convert::Infallible;
|
||||||
|
use std::fs::Metadata;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
use tokio::fs::File;
|
use tokio::fs::File;
|
||||||
use tokio::io::AsyncWrite;
|
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWrite};
|
||||||
use tokio::{fs, io};
|
use tokio::{fs, io};
|
||||||
use tokio_util::codec::{BytesCodec, FramedRead};
|
use tokio_util::codec::{BytesCodec, FramedRead};
|
||||||
use tokio_util::io::{ReaderStream, StreamReader};
|
use tokio_util::io::{ReaderStream, StreamReader};
|
||||||
@@ -24,19 +32,18 @@ use tokio_util::io::{ReaderStream, StreamReader};
|
|||||||
type Request = hyper::Request<Body>;
|
type Request = hyper::Request<Body>;
|
||||||
type Response = hyper::Response<Body>;
|
type Response = hyper::Response<Body>;
|
||||||
|
|
||||||
macro_rules! status_code {
|
const INDEX_HTML: &str = include_str!("assets/index.html");
|
||||||
($status:expr) => {
|
const INDEX_CSS: &str = include_str!("assets/index.css");
|
||||||
hyper::Response::builder()
|
const INDEX_JS: &str = include_str!("assets/index.js");
|
||||||
.status($status)
|
const BUF_SIZE: usize = 1024 * 16;
|
||||||
.body($status.canonical_reason().unwrap_or_default().into())
|
|
||||||
.unwrap()
|
macro_rules! status {
|
||||||
|
($res:ident, $status:expr) => {
|
||||||
|
*$res.status_mut() = $status;
|
||||||
|
*$res.body_mut() = Body::from($status.canonical_reason().unwrap_or_default());
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const INDEX_HTML: &str = include_str!("index.html");
|
|
||||||
const INDEX_CSS: &str = include_str!("index.css");
|
|
||||||
const BUF_SIZE: usize = 1024 * 16;
|
|
||||||
|
|
||||||
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));
|
||||||
@@ -71,11 +78,20 @@ impl InnerService {
|
|||||||
let method = req.method().clone();
|
let method = req.method().clone();
|
||||||
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)
|
let mut res = match self.handle(req).await {
|
||||||
.await
|
Ok(res) => {
|
||||||
.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR));
|
|
||||||
info!(r#""{} {}" - {}"#, method, uri, res.status());
|
info!(r#""{} {}" - {}"#, method, uri, res.status());
|
||||||
|
res
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
let mut res = Response::default();
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
@@ -83,77 +99,90 @@ impl InnerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle(self: Arc<Self>, req: Request) -> BoxResult<Response> {
|
pub async fn handle(self: Arc<Self>, req: Request) -> BoxResult<Response> {
|
||||||
if !self.auth_guard(&req).unwrap_or_default() {
|
let mut res = Response::default();
|
||||||
let mut res = status_code!(StatusCode::UNAUTHORIZED);
|
|
||||||
res.headers_mut()
|
if !self.auth_guard(&req, &mut res) {
|
||||||
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
|
|
||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let path = req.uri().path();
|
||||||
|
|
||||||
|
let filepath = match self.extract_path(path) {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
return Ok(res);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let filepath = filepath.as_path();
|
||||||
|
|
||||||
|
let query = req.uri().query().unwrap_or_default();
|
||||||
|
|
||||||
|
let meta = fs::metadata(filepath).await.ok();
|
||||||
|
let is_miss = meta.is_none();
|
||||||
|
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
||||||
|
let is_file = !is_miss && !is_dir;
|
||||||
|
|
||||||
|
let allow_upload = self.args.allow_upload;
|
||||||
|
let allow_delete = self.args.allow_delete;
|
||||||
|
|
||||||
match *req.method() {
|
match *req.method() {
|
||||||
Method::GET => self.handle_static(req).await,
|
Method::GET if is_dir && query == "zip" => {
|
||||||
Method::PUT => {
|
self.handle_zip_dir(filepath, &mut res).await?
|
||||||
if self.args.readonly {
|
|
||||||
return Ok(status_code!(StatusCode::FORBIDDEN));
|
|
||||||
}
|
}
|
||||||
self.handle_upload(req).await
|
Method::GET if is_dir && query.starts_with("q=") => {
|
||||||
|
self.handle_query_dir(filepath, &query[3..], &mut res)
|
||||||
|
.await?
|
||||||
}
|
}
|
||||||
Method::OPTIONS => Ok(status_code!(StatusCode::NO_CONTENT)),
|
Method::GET if is_dir => self.handle_ls_dir(filepath, true, &mut res).await?,
|
||||||
Method::DELETE => self.handle_delete(req).await,
|
Method::GET if is_file => {
|
||||||
_ => Ok(status_code!(StatusCode::NOT_FOUND)),
|
self.handle_send_file(filepath, req.headers(), &mut res)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
Method::GET if allow_upload && is_miss && path.ends_with('/') => {
|
||||||
|
self.handle_ls_dir(filepath, false, &mut res).await?
|
||||||
|
}
|
||||||
|
Method::OPTIONS => {
|
||||||
|
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::DELETE if !allow_delete => {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
Method::DELETE if !is_miss => self.handle_delete(filepath, is_dir).await?,
|
||||||
|
_ => {
|
||||||
|
status!(res, StatusCode::NOT_FOUND);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_static(&self, req: Request) -> BoxResult<Response> {
|
Ok(res)
|
||||||
let req_path = req.uri().path();
|
|
||||||
let path = match self.get_file_path(req_path)? {
|
|
||||||
Some(path) => path,
|
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
|
||||||
};
|
|
||||||
match fs::metadata(&path).await {
|
|
||||||
Ok(meta) => {
|
|
||||||
if meta.is_dir() {
|
|
||||||
let req_query = req.uri().query().unwrap_or_default();
|
|
||||||
if req_query == "zip" {
|
|
||||||
return self.handle_send_dir_zip(path.as_path()).await;
|
|
||||||
}
|
|
||||||
if let Some(q) = req_query.strip_prefix("q=") {
|
|
||||||
return self.handle_query_dir(path.as_path(), q).await;
|
|
||||||
}
|
|
||||||
self.handle_ls_dir(path.as_path(), true).await
|
|
||||||
} else {
|
|
||||||
self.handle_send_file(path.as_path()).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
if req_path.ends_with('/') {
|
|
||||||
self.handle_ls_dir(path.as_path(), false).await
|
|
||||||
} else {
|
|
||||||
Ok(status_code!(StatusCode::NOT_FOUND))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_upload(&self, mut req: Request) -> BoxResult<Response> {
|
async fn handle_upload(
|
||||||
let forbidden = status_code!(StatusCode::FORBIDDEN);
|
&self,
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
path: &Path,
|
||||||
Some(path) => path,
|
mut req: Request,
|
||||||
None => return Ok(forbidden),
|
res: &mut Response,
|
||||||
};
|
) -> BoxResult<()> {
|
||||||
|
let ensure_parent = match path.parent() {
|
||||||
match path.parent() {
|
|
||||||
Some(parent) => match fs::metadata(parent).await {
|
Some(parent) => match fs::metadata(parent).await {
|
||||||
Ok(meta) => {
|
Ok(meta) => meta.is_dir(),
|
||||||
if !meta.is_dir() {
|
Err(_) => {
|
||||||
return Ok(forbidden);
|
fs::create_dir_all(parent).await?;
|
||||||
|
true
|
||||||
}
|
}
|
||||||
}
|
|
||||||
Err(_) => fs::create_dir_all(parent).await?,
|
|
||||||
},
|
},
|
||||||
None => return Ok(forbidden),
|
None => false,
|
||||||
|
};
|
||||||
|
if !ensure_parent {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut file = fs::File::create(path).await?;
|
let mut file = fs::File::create(&path).await?;
|
||||||
|
|
||||||
let body_with_io_error = req
|
let body_with_io_error = req
|
||||||
.body_mut()
|
.body_mut()
|
||||||
@@ -165,39 +194,64 @@ impl InnerService {
|
|||||||
|
|
||||||
io::copy(&mut body_reader, &mut file).await?;
|
io::copy(&mut body_reader, &mut file).await?;
|
||||||
|
|
||||||
return Ok(status_code!(StatusCode::OK));
|
let query = req.uri().query().unwrap_or_default();
|
||||||
}
|
if query == "unzip" {
|
||||||
|
let root = path.parent().unwrap();
|
||||||
async fn handle_delete(&self, req: Request) -> BoxResult<Response> {
|
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
for i in 0..zip.entries().len() {
|
||||||
Some(path) => path,
|
let entry = &zip.entries()[i];
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
let entry_name = entry.name();
|
||||||
};
|
let entry_path = root.join(entry_name);
|
||||||
|
if entry_name.ends_with('/') {
|
||||||
let meta = fs::metadata(&path).await?;
|
fs::create_dir_all(entry_path).await?;
|
||||||
if meta.is_file() {
|
|
||||||
fs::remove_file(path).await?;
|
|
||||||
} else {
|
} else {
|
||||||
fs::remove_dir_all(path).await?;
|
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
Ok(status_code!(StatusCode::OK))
|
if let Some(parent) = entry_path.parent() {
|
||||||
|
if fs::symlink_metadata(parent).await.is_err() {
|
||||||
|
fs::create_dir_all(&parent).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut outfile = fs::File::create(&entry_path).await?;
|
||||||
|
let mut reader = zip.entry_reader(i).await?;
|
||||||
|
io::copy(&mut reader, &mut outfile).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs::remove_file(&path).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_ls_dir(&self, path: &Path, exist: bool) -> BoxResult<Response> {
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_delete(&self, path: &Path, is_dir: bool) -> BoxResult<()> {
|
||||||
|
match is_dir {
|
||||||
|
true => fs::remove_dir_all(path).await?,
|
||||||
|
false => fs::remove_file(path).await?,
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> {
|
||||||
let mut paths: Vec<PathItem> = vec![];
|
let mut paths: Vec<PathItem> = vec![];
|
||||||
if exist {
|
if exist {
|
||||||
let mut rd = fs::read_dir(path).await?;
|
let mut rd = fs::read_dir(path).await?;
|
||||||
while let Some(entry) = rd.next_entry().await? {
|
while let Some(entry) = rd.next_entry().await? {
|
||||||
let entry_path = entry.path();
|
let entry_path = entry.path();
|
||||||
if let Ok(item) = get_path_item(entry_path, path.to_path_buf()).await {
|
if let Ok(item) = to_pathitem(entry_path, path.to_path_buf()).await {
|
||||||
paths.push(item);
|
paths.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.send_index(path, paths)
|
self.send_index(path, paths, res)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_query_dir(&self, path: &Path, q: &str) -> BoxResult<Response> {
|
async fn handle_query_dir(
|
||||||
|
&self,
|
||||||
|
path: &Path,
|
||||||
|
query: &str,
|
||||||
|
res: &mut Response,
|
||||||
|
) -> BoxResult<()> {
|
||||||
let mut paths: Vec<PathItem> = vec![];
|
let mut paths: Vec<PathItem> = vec![];
|
||||||
let mut walkdir = WalkDir::new(path);
|
let mut walkdir = WalkDir::new(path);
|
||||||
while let Some(entry) = walkdir.next().await {
|
while let Some(entry) = walkdir.next().await {
|
||||||
@@ -206,23 +260,24 @@ impl InnerService {
|
|||||||
.file_name()
|
.file_name()
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.to_lowercase()
|
.to_lowercase()
|
||||||
.contains(&q.to_lowercase())
|
.contains(&query.to_lowercase())
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if fs::symlink_metadata(entry.path()).await.is_err() {
|
if fs::symlink_metadata(entry.path()).await.is_err() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Ok(item) = get_path_item(entry.path(), path.to_path_buf()).await {
|
if let Ok(item) = to_pathitem(entry.path(), path.to_path_buf()).await {
|
||||||
paths.push(item);
|
paths.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.send_index(path, paths)
|
self.send_index(path, paths, res)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> {
|
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
|
||||||
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
||||||
|
let filename = path.file_name().unwrap().to_str().unwrap();
|
||||||
let path = path.to_owned();
|
let path = path.to_owned();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = dir_zip(&mut writer, &path).await {
|
if let Err(e) = dir_zip(&mut writer, &path).await {
|
||||||
@@ -230,72 +285,156 @@ impl InnerService {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
let stream = ReaderStream::new(reader);
|
let stream = ReaderStream::new(reader);
|
||||||
let body = Body::wrap_stream(stream);
|
*res.body_mut() = Body::wrap_stream(stream);
|
||||||
Ok(Response::new(body))
|
res.headers_mut().insert(
|
||||||
|
CONTENT_DISPOSITION,
|
||||||
|
HeaderValue::from_str(&format!("attachment; filename=\"{}.zip\"", filename,)).unwrap(),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_file(&self, path: &Path) -> BoxResult<Response> {
|
async fn handle_send_file(
|
||||||
let file = fs::File::open(path).await?;
|
&self,
|
||||||
|
path: &Path,
|
||||||
|
headers: &HeaderMap<HeaderValue>,
|
||||||
|
res: &mut Response,
|
||||||
|
) -> BoxResult<()> {
|
||||||
|
let (file, meta) = tokio::join!(fs::File::open(path), fs::metadata(path),);
|
||||||
|
let (mut file, meta) = (file?, meta?);
|
||||||
|
let mut maybe_range = true;
|
||||||
|
if let Some((etag, last_modified)) = extract_cache_headers(&meta) {
|
||||||
|
let cached = {
|
||||||
|
if let Some(if_none_match) = headers.typed_get::<IfNoneMatch>() {
|
||||||
|
!if_none_match.precondition_passes(&etag)
|
||||||
|
} else if let Some(if_modified_since) = headers.typed_get::<IfModifiedSince>() {
|
||||||
|
!if_modified_since.is_modified(last_modified.into())
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
res.headers_mut().typed_insert(last_modified);
|
||||||
|
res.headers_mut().typed_insert(etag.clone());
|
||||||
|
if cached {
|
||||||
|
status!(res, StatusCode::NOT_MODIFIED);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if headers.typed_get::<Range>().is_some() {
|
||||||
|
maybe_range = headers
|
||||||
|
.typed_get::<IfRange>()
|
||||||
|
.map(|if_range| !if_range.is_modified(Some(&etag), Some(&last_modified)))
|
||||||
|
// Always be fresh if there is no validators
|
||||||
|
.unwrap_or(true);
|
||||||
|
} else {
|
||||||
|
maybe_range = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let file_range = if maybe_range {
|
||||||
|
if let Some(content_range) = headers
|
||||||
|
.typed_get::<Range>()
|
||||||
|
.and_then(|range| to_content_range(&range, meta.len()))
|
||||||
|
{
|
||||||
|
res.headers_mut().typed_insert(content_range.clone());
|
||||||
|
*res.status_mut() = StatusCode::PARTIAL_CONTENT;
|
||||||
|
content_range.bytes_range()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(mime) = mime_guess::from_path(&path).first() {
|
||||||
|
res.headers_mut().typed_insert(ContentType::from(mime));
|
||||||
|
}
|
||||||
|
let body = if let Some((begin, end)) = file_range {
|
||||||
|
file.seek(io::SeekFrom::Start(begin)).await?;
|
||||||
|
let stream = FramedRead::new(file.take(end - begin + 1), BytesCodec::new());
|
||||||
|
Body::wrap_stream(stream)
|
||||||
|
} else {
|
||||||
let stream = FramedRead::new(file, BytesCodec::new());
|
let stream = FramedRead::new(file, BytesCodec::new());
|
||||||
let body = Body::wrap_stream(stream);
|
Body::wrap_stream(stream)
|
||||||
Ok(Response::new(body))
|
};
|
||||||
|
*res.body_mut() = body;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_index(&self, path: &Path, mut paths: Vec<PathItem>) -> BoxResult<Response> {
|
fn send_index(
|
||||||
|
&self,
|
||||||
|
path: &Path,
|
||||||
|
mut paths: Vec<PathItem>,
|
||||||
|
res: &mut Response,
|
||||||
|
) -> BoxResult<()> {
|
||||||
paths.sort_unstable();
|
paths.sort_unstable();
|
||||||
let breadcrumb = self.get_breadcrumb(path);
|
let rel_path = match self.args.path.parent() {
|
||||||
let data = IndexData {
|
|
||||||
breadcrumb,
|
|
||||||
paths,
|
|
||||||
readonly: self.args.readonly,
|
|
||||||
};
|
|
||||||
let data = serde_json::to_string(&data).unwrap();
|
|
||||||
let mut output =
|
|
||||||
INDEX_HTML.replace("__STYLE__", &format!("<style>\n{}</style>", INDEX_CSS));
|
|
||||||
output = output.replace("__DATA__", &data);
|
|
||||||
|
|
||||||
Ok(hyper::Response::builder().body(output.into()).unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn auth_guard(&self, req: &Request) -> BoxResult<bool> {
|
|
||||||
if let Some(auth) = &self.args.auth {
|
|
||||||
if let Some(value) = req.headers().get("Authorization") {
|
|
||||||
let value = value.to_str()?;
|
|
||||||
let value = if value.contains("Basic ") {
|
|
||||||
&value[6..]
|
|
||||||
} else {
|
|
||||||
return Ok(false);
|
|
||||||
};
|
|
||||||
let value = base64::decode(value)?;
|
|
||||||
let value = std::str::from_utf8(&value)?;
|
|
||||||
return Ok(value == auth);
|
|
||||||
} else {
|
|
||||||
return Ok(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_breadcrumb(&self, path: &Path) -> String {
|
|
||||||
let path = match self.args.path.parent() {
|
|
||||||
Some(p) => path.strip_prefix(p).unwrap(),
|
Some(p) => path.strip_prefix(p).unwrap(),
|
||||||
None => path,
|
None => path,
|
||||||
};
|
};
|
||||||
normalize_path(path)
|
let data = IndexData {
|
||||||
|
breadcrumb: normalize_path(rel_path),
|
||||||
|
paths,
|
||||||
|
allow_upload: self.args.allow_upload,
|
||||||
|
allow_delete: self.args.allow_delete,
|
||||||
|
};
|
||||||
|
let data = serde_json::to_string(&data).unwrap();
|
||||||
|
let output = INDEX_HTML.replace(
|
||||||
|
"__SLOT__",
|
||||||
|
&format!(
|
||||||
|
r#"
|
||||||
|
<title>Files in {}/ - Duf</title>
|
||||||
|
<style>{}</style>
|
||||||
|
<script>var DATA = {}; {}</script>
|
||||||
|
"#,
|
||||||
|
rel_path.display(),
|
||||||
|
INDEX_CSS,
|
||||||
|
data,
|
||||||
|
INDEX_JS
|
||||||
|
),
|
||||||
|
);
|
||||||
|
*res.body_mut() = output.into();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_file_path(&self, path: &str) -> BoxResult<Option<PathBuf>> {
|
fn auth_guard(&self, req: &Request, res: &mut Response) -> bool {
|
||||||
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?;
|
let pass = {
|
||||||
|
match &self.args.auth {
|
||||||
|
None => true,
|
||||||
|
Some(auth) => match req.headers().get(AUTHORIZATION) {
|
||||||
|
Some(value) => match value.to_str().ok().map(|v| {
|
||||||
|
let mut it = v.split(' ');
|
||||||
|
(it.next(), it.next())
|
||||||
|
}) {
|
||||||
|
Some((Some("Basic"), Some(tail))) => base64::decode(tail)
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| String::from_utf8(v).ok())
|
||||||
|
.map(|v| v.as_str() == auth)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
None => self.args.no_auth_read && req.method() == Method::GET,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !pass {
|
||||||
|
status!(res, StatusCode::UNAUTHORIZED);
|
||||||
|
res.headers_mut()
|
||||||
|
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
|
||||||
|
}
|
||||||
|
pass
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_path(&self, path: &str) -> Option<PathBuf> {
|
||||||
|
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
|
||||||
let slashes_switched = if cfg!(windows) {
|
let slashes_switched = if cfg!(windows) {
|
||||||
decoded_path.replace('/', "\\")
|
decoded_path.replace('/', "\\")
|
||||||
} else {
|
} else {
|
||||||
decoded_path.into_owned()
|
decoded_path.into_owned()
|
||||||
};
|
};
|
||||||
let path = self.args.path.join(&slashes_switched);
|
let full_path = self.args.path.join(&slashes_switched);
|
||||||
if path.starts_with(&self.args.path) {
|
if full_path.starts_with(&self.args.path) {
|
||||||
Ok(Some(path))
|
Some(full_path)
|
||||||
} else {
|
} else {
|
||||||
Ok(None)
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -304,14 +443,15 @@ 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)]
|
||||||
struct PathItem {
|
struct PathItem {
|
||||||
path_type: PathType,
|
path_type: PathType,
|
||||||
name: String,
|
name: String,
|
||||||
mtime: Option<u64>,
|
mtime: u64,
|
||||||
size: Option<u64>,
|
size: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,24 +463,20 @@ enum PathType {
|
|||||||
SymlinkFile,
|
SymlinkFile,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_path_item<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathItem> {
|
async fn to_pathitem<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathItem> {
|
||||||
let path = path.as_ref();
|
let path = path.as_ref();
|
||||||
let rel_path = path.strip_prefix(base_path).unwrap();
|
let rel_path = path.strip_prefix(base_path).unwrap();
|
||||||
let meta = fs::metadata(&path).await?;
|
let (meta, meta2) = tokio::join!(fs::metadata(&path), fs::symlink_metadata(&path));
|
||||||
let s_meta = fs::symlink_metadata(&path).await?;
|
let (meta, meta2) = (meta?, meta2?);
|
||||||
let is_dir = meta.is_dir();
|
let is_dir = meta.is_dir();
|
||||||
let is_symlink = s_meta.file_type().is_symlink();
|
let is_symlink = meta2.file_type().is_symlink();
|
||||||
let path_type = match (is_symlink, is_dir) {
|
let path_type = match (is_symlink, is_dir) {
|
||||||
(true, true) => PathType::SymlinkDir,
|
(true, true) => PathType::SymlinkDir,
|
||||||
(false, true) => PathType::Dir,
|
(false, true) => PathType::Dir,
|
||||||
(true, false) => PathType::SymlinkFile,
|
(true, false) => PathType::SymlinkFile,
|
||||||
(false, false) => PathType::File,
|
(false, false) => PathType::File,
|
||||||
};
|
};
|
||||||
let mtime = meta
|
let mtime = to_timestamp(&meta.modified()?);
|
||||||
.modified()?
|
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
|
||||||
.ok()
|
|
||||||
.map(|v| v.as_millis() as u64);
|
|
||||||
let size = match path_type {
|
let size = match path_type {
|
||||||
PathType::Dir | PathType::SymlinkDir => None,
|
PathType::Dir | PathType::SymlinkDir => None,
|
||||||
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
||||||
@@ -354,6 +490,12 @@ async fn get_path_item<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathI
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn to_timestamp(time: &SystemTime) -> u64 {
|
||||||
|
time.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_millis() as u64
|
||||||
|
}
|
||||||
|
|
||||||
fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
||||||
let path = path.as_ref().to_str().unwrap_or_default();
|
let path = path.as_ref().to_str().unwrap_or_default();
|
||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
@@ -399,3 +541,42 @@ async fn dir_zip<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult
|
|||||||
writer.close().await?;
|
writer.close().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn extract_cache_headers(meta: &Metadata) -> Option<(ETag, LastModified)> {
|
||||||
|
let mtime = meta.modified().ok()?;
|
||||||
|
let timestamp = to_timestamp(&mtime);
|
||||||
|
let size = meta.len();
|
||||||
|
let etag = format!(r#""{}-{}""#, timestamp, size)
|
||||||
|
.parse::<ETag>()
|
||||||
|
.unwrap();
|
||||||
|
let last_modified = LastModified::from(mtime);
|
||||||
|
Some((etag, last_modified))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_content_range(range: &Range, complete_length: u64) -> Option<ContentRange> {
|
||||||
|
use core::ops::Bound::{Included, Unbounded};
|
||||||
|
let mut iter = range.iter();
|
||||||
|
let bounds = iter.next();
|
||||||
|
|
||||||
|
if iter.next().is_some() {
|
||||||
|
// Found multiple byte-range-spec. Drop.
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
bounds.and_then(|b| match b {
|
||||||
|
(Included(start), Included(end)) if start <= end && start < complete_length => {
|
||||||
|
ContentRange::bytes(
|
||||||
|
start..=end.min(complete_length.saturating_sub(1)),
|
||||||
|
complete_length,
|
||||||
|
)
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
(Included(start), Unbounded) if start < complete_length => {
|
||||||
|
ContentRange::bytes(start.., complete_length).ok()
|
||||||
|
}
|
||||||
|
(Unbounded, Included(end)) if end > 0 => {
|
||||||
|
ContentRange::bytes(complete_length.saturating_sub(end).., complete_length).ok()
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user