Compare commits

..

9 Commits

Author SHA1 Message Date
sigoden
54df4633e1 chore: upgrade version 2022-05-30 16:06:31 +08:00
sigoden
6b293c0f2e chore: rename src/static to src/assets 2022-05-30 14:32:41 +08:00
sigoden
62696b45fd feat: unzip zip file when unload 2022-05-30 14:30:08 +08:00
sigoden
d9547ad00b feat: add no-auth-read options 2022-05-30 12:40:57 +08:00
sigoden
8fbc742c52 chore: reorganize web static files 2022-05-30 12:31:29 +08:00
sigoden
d8d5aae898 feat: add mime and cache headers to response 2022-05-30 11:22:28 +08:00
sigoden
a263d18963 chore: upgrade version 2022-05-29 20:50:47 +08:00
sigoden
10aabcb2f2 feat: add cors 2022-05-29 17:33:21 +08:00
sigoden
06ce7b0175 feat: replace --static option to --no-edit 2022-05-29 17:01:30 +08:00
10 changed files with 567 additions and 344 deletions

125
Cargo.lock generated
View File

@@ -130,6 +130,15 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "block-buffer"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324"
dependencies = [
"generic-array",
]
[[package]] [[package]]
name = "blocking" name = "blocking"
version = "1.2.0" version = "1.2.0"
@@ -247,6 +256,15 @@ dependencies = [
"cache-padded", "cache-padded",
] ]
[[package]]
name = "cpufeatures"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.3.2" version = "1.3.2"
@@ -256,17 +274,39 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "crypto-common"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]] [[package]]
name = "duf" name = "duf"
version = "0.3.0" version = "0.5.0"
dependencies = [ dependencies = [
"async-walkdir", "async-walkdir",
"async_zip", "async_zip",
"base64", "base64",
"clap", "clap",
"futures", "futures",
"headers",
"hyper", "hyper",
"log", "log",
"mime_guess",
"percent-encoding", "percent-encoding",
"serde", "serde",
"serde_json", "serde_json",
@@ -412,12 +452,47 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "generic-array"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803"
dependencies = [
"typenum",
"version_check",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.11.2" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]]
name = "headers"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cff78e5788be1e0ab65b04d306b2ed5092c815ec97ec70f4ebd5aee158aa55d"
dependencies = [
"base64",
"bitflags",
"bytes",
"headers-core",
"http",
"httpdate",
"mime",
"sha-1",
]
[[package]]
name = "headers-core"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429"
dependencies = [
"http",
]
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.1.19" version = "0.1.19"
@@ -556,6 +631,22 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "mime"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
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"
@@ -712,6 +803,17 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "sha-1"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "simple_logger" name = "simple_logger"
version = "2.1.0" version = "2.1.0"
@@ -894,12 +996,33 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
[[package]]
name = "typenum"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
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"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee" checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]] [[package]]
name = "waker-fn" name = "waker-fn"
version = "1.1.0" version = "1.1.0"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "duf" name = "duf"
version = "0.3.0" version = "0.5.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."
@@ -25,6 +25,8 @@ log = "0.4"
simple_logger = "2.1.0" 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"
mime_guess = "2.0.4"
[profile.release] [profile.release]
lto = true lto = true

View File

@@ -15,6 +15,7 @@ Duf is a simple file server.
- Upload files - Upload files
- Delete files - Delete files
- Basic authentication - Basic authentication
- Unzip zip file when upload
- Easy to use with curl - Easy to use with curl
## Install ## Install
@@ -43,9 +44,9 @@ duf
duf folder_name duf folder_name
``` ```
Only serve static files, disable upload and delete operations Only serve static files, disable editing operations such as update or delete
``` ```
duf --static duf --readonly
``` ```
Finally, run this command to see a list of all available option Finally, run this command to see a list of all available option
@@ -71,6 +72,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
``` ```

View File

@@ -10,47 +10,53 @@ use crate::BoxResult;
const ABOUT: &str = concat!("\n", crate_description!()); // Add extra newline. const ABOUT: &str = concat!("\n", crate_description!()); // Add extra newline.
fn app() -> clap::Command<'static> { fn app() -> clap::Command<'static> {
let arg_port = Arg::new("port") clap::command!()
.short('p') .about(ABOUT)
.long("port") .arg(
.default_value("5000") Arg::new("address")
.help("Specify port to listen on")
.value_name("port");
let arg_address = Arg::new("address")
.short('b') .short('b')
.long("bind") .long("bind")
.default_value("127.0.0.1") .default_value("127.0.0.1")
.help("Specify bind address") .help("Specify bind address")
.value_name("address"); .value_name("address"),
)
let arg_path = Arg::new("path") .arg(
Arg::new("port")
.short('p')
.long("port")
.default_value("5000")
.help("Specify port to listen on")
.value_name("port"),
)
.arg(
Arg::new("path")
.default_value(".") .default_value(".")
.allow_invalid_utf8(true) .allow_invalid_utf8(true)
.help("Path to a directory for serving files"); .help("Path to a directory for serving files"),
)
let arg_static = Arg::new("static") .arg(
.long("static") Arg::new("readonly")
.help("Only serve static files, disable upload and delete operations"); .short('r')
.long("readonly")
let arg_auth = Arg::new("auth") .help("Disable change operations such as update or delete"),
)
.arg(
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"),
)
let arg_no_log = Arg::new("no-log") .arg(
.long("--no-log") Arg::new("no-auth-read")
.help("Don't log any request/response information."); .long("no-auth-read")
.help("Do not authenticate read operations like static serving"),
clap::command!() )
.about(ABOUT) .arg(
.arg(arg_address) Arg::new("cors")
.arg(arg_port) .long("cors")
.arg(arg_path) .help("Enable CORS, sets `Access-Control-Allow-Origin: *`"),
.arg(arg_static) )
.arg(arg_auth)
.arg(arg_no_log)
} }
pub fn matches() -> ArgMatches { pub fn matches() -> ArgMatches {
@@ -64,7 +70,8 @@ pub struct Args {
pub path: PathBuf, pub path: PathBuf,
pub readonly: bool, pub readonly: bool,
pub auth: Option<String>, pub auth: Option<String>,
pub log: bool, pub no_auth_read: bool,
pub cors: bool,
} }
impl Args { impl Args {
@@ -77,9 +84,10 @@ impl Args {
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 = matches.value_of_os("path").unwrap_or_default();
let path = Args::parse_path(path)?; let path = Args::parse_path(path)?;
let readonly = matches.is_present("static"); let readonly = matches.is_present("readonly");
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 log = !matches.is_present("no-log"); let no_auth_read = matches.is_present("no-auth-read");
Ok(Args { Ok(Args {
address, address,
@@ -87,7 +95,8 @@ impl Args {
path, path,
readonly, readonly,
auth, auth,
log, no_auth_read,
cors,
}) })
} }

View File

@@ -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;
} }

53
src/assets/index.html Normal file
View File

@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
__SLOB__
</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 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>
</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>

191
src/assets/index.js Normal file
View File

@@ -0,0 +1,191 @@
var $toolbox, $tbody, $breadcrumb, $uploaders, $uploadControl;
var uploaderIdx = 0;
var baseDir;
class Uploader {
idx = 0;
file;
$elem;
constructor(idx, file) {
this.idx = idx;
this.file = file;
}
upload() {
var { file, idx } = this;
var url = getUrl(file.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}">${file.name} (0%)</a>
</div>`);
this.$elem = document.getElementById(`file${idx}`);
var 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) {
var 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) {
var parts = value.split("/").filter(v => !!v);
var len = parts.length;
var path = "";
for (var i = 0; i < len; i++) {
var 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) {
var url = getUrl(file.name)
var actionDelete = "";
var 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.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>`;
}
var 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) {
var file = DATA.paths[index];
if (!file) return;
var 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 getUrl(name) {
var 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 ""
var date = new Date(mtime);
var year = date.getFullYear();
var month = padZero(date.getMonth() + 1, 2);
var day = padZero(date.getDate(), 2);
var hours = padZero(date.getHours(), 2);
var 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 ""
var sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (size == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function ready() {
$toolbox = document.querySelector(".toolbox");
$tbody = document.querySelector(".main tbody");
$breadcrumb = document.querySelector(".breadcrumb");
$uploaders = document.querySelector(".uploaders");
addBreadcrumb(DATA.breadcrumb);
DATA.paths.forEach((file, index) => addPath(file, index));
if (!DATA.readonly) {
document.querySelector(".upload-control").classList.remove(["hidden"]);
document.getElementById("file").addEventListener("change", e => {
var files = e.target.files;
for (var file of files) {
uploaderIdx += 1;
var uploader = new Uploader(uploaderIdx, file);
uploader.upload();
}
});
}
}

View File

@@ -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>

View File

@@ -28,13 +28,8 @@ async fn run() -> BoxResult<()> {
if std::env::var("RUST_LOG").is_ok() { if std::env::var("RUST_LOG").is_ok() {
simple_logger::init()?; simple_logger::init()?;
} else { } else {
let level = if args.log {
LevelFilter::Info
} else {
LevelFilter::Error
};
simple_logger::SimpleLogger::default() simple_logger::SimpleLogger::default()
.with_level(level) .with_level(LevelFilter::Info)
.init()?; .init()?;
} }
serve(args).await serve(args).await

View File

@@ -1,11 +1,16 @@
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 hyper::header::HeaderValue; use headers::{
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentType, ETag, HeaderMapExt,
IfModifiedSince, IfNoneMatch, LastModified,
};
use hyper::header::{HeaderValue, ACCEPT, 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;
@@ -32,8 +37,9 @@ macro_rules! status_code {
}; };
} }
const INDEX_HTML: &str = include_str!("index.html"); const INDEX_HTML: &str = include_str!("assets/index.html");
const INDEX_CSS: &str = include_str!("index.css"); const INDEX_CSS: &str = include_str!("assets/index.css");
const INDEX_JS: &str = include_str!("assets/index.js");
const BUF_SIZE: usize = 1024 * 16; const BUF_SIZE: usize = 1024 * 16;
pub async fn serve(args: Args) -> BoxResult<()> { pub async fn serve(args: Args) -> BoxResult<()> {
@@ -69,11 +75,15 @@ impl InnerService {
pub async fn call(self: Arc<Self>, req: Request) -> Result<Response, hyper::Error> { pub async fn call(self: Arc<Self>, req: Request) -> Result<Response, hyper::Error> {
let method = req.method().clone(); let method = req.method().clone();
let uri = req.uri().clone(); let uri = req.uri().clone();
let res = self let cors = self.args.cors;
let mut res = self
.handle(req) .handle(req)
.await .await
.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR)); .unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR));
info!(r#""{} {}" - {}"#, method, uri, res.status()); info!(r#""{} {}" - {}"#, method, uri, res.status());
if cors {
add_cors(&mut res);
}
Ok(res) Ok(res)
} }
@@ -81,21 +91,20 @@ impl InnerService {
if !self.auth_guard(&req).unwrap_or_default() { if !self.auth_guard(&req).unwrap_or_default() {
let mut res = status_code!(StatusCode::UNAUTHORIZED); let mut res = status_code!(StatusCode::UNAUTHORIZED);
res.headers_mut() res.headers_mut()
.insert("WWW-Authenticate", HeaderValue::from_static("Basic")); .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
return Ok(res); return Ok(res);
} }
match *req.method() {
if req.method() == Method::GET { Method::GET => self.handle_static(req).await,
self.handle_static(req).await Method::PUT => {
} else if req.method() == Method::PUT {
if self.args.readonly { if self.args.readonly {
return Ok(status_code!(StatusCode::FORBIDDEN)); return Ok(status_code!(StatusCode::FORBIDDEN));
} }
self.handle_upload(req).await self.handle_upload(req).await
} else if req.method() == Method::DELETE { }
self.handle_delete(req).await Method::OPTIONS => Ok(status_code!(StatusCode::NO_CONTENT)),
} else { Method::DELETE => self.handle_delete(req).await,
return Ok(status_code!(StatusCode::NOT_FOUND)); _ => Ok(status_code!(StatusCode::NOT_FOUND)),
} }
} }
@@ -117,7 +126,7 @@ impl InnerService {
} }
self.handle_ls_dir(path.as_path(), true).await self.handle_ls_dir(path.as_path(), true).await
} else { } else {
self.handle_send_file(path.as_path()).await self.handle_send_file(&req, path.as_path()).await
} }
} }
Err(_) => { Err(_) => {
@@ -149,7 +158,7 @@ impl InnerService {
None => return Ok(forbidden), None => return Ok(forbidden),
} }
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()
@@ -161,6 +170,30 @@ impl InnerService {
io::copy(&mut body_reader, &mut file).await?; io::copy(&mut body_reader, &mut file).await?;
let req_query = req.uri().query().unwrap_or_default();
if req_query == "unzip" {
let root = path.parent().unwrap();
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
for i in 0..zip.entries().len() {
let entry = &zip.entries()[i];
let entry_name = entry.name();
let entry_path = root.join(entry_name);
if entry_name.ends_with('/') {
fs::create_dir_all(entry_path).await?;
} else {
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?;
}
return Ok(status_code!(StatusCode::OK)); return Ok(status_code!(StatusCode::OK));
} }
@@ -230,27 +263,72 @@ impl InnerService {
Ok(Response::new(body)) Ok(Response::new(body))
} }
async fn handle_send_file(&self, path: &Path) -> BoxResult<Response> { async fn handle_send_file(&self, req: &Request, path: &Path) -> BoxResult<Response> {
let file = fs::File::open(path).await?; let (file, meta) = tokio::join!(fs::File::open(path), fs::metadata(path),);
let (file, meta) = (file?, meta?);
let mut res = Response::default();
if let Ok(mtime) = meta.modified() {
let timestamp = get_timestamp(&mtime);
let size = meta.len();
let etag = format!(r#""{}-{}""#, timestamp, size)
.parse::<ETag>()
.unwrap();
let last_modified = LastModified::from(mtime);
let fresh = {
// `If-None-Match` takes presedence over `If-Modified-Since`.
if let Some(if_none_match) = req.headers().typed_get::<IfNoneMatch>() {
!if_none_match.precondition_passes(&etag)
} else if let Some(if_modified_since) = req.headers().typed_get::<IfModifiedSince>()
{
!if_modified_since.is_modified(mtime)
} else {
false
}
};
res.headers_mut().typed_insert(last_modified);
res.headers_mut().typed_insert(etag);
if fresh {
*res.status_mut() = StatusCode::NOT_MODIFIED;
return Ok(res);
}
}
if let Some(mime) = mime_guess::from_path(&path).first() {
res.headers_mut().typed_insert(ContentType::from(mime));
}
let stream = FramedRead::new(file, BytesCodec::new()); let stream = FramedRead::new(file, BytesCodec::new());
let body = Body::wrap_stream(stream); let body = Body::wrap_stream(stream);
Ok(Response::new(body)) *res.body_mut() = body;
Ok(res)
} }
fn send_index(&self, path: &Path, mut paths: Vec<PathItem>) -> BoxResult<Response> { fn send_index(&self, path: &Path, mut paths: Vec<PathItem>) -> BoxResult<Response> {
paths.sort_unstable(); paths.sort_unstable();
let breadcrumb = self.get_breadcrumb(path); let rel_path = match self.args.path.parent() {
Some(p) => path.strip_prefix(p).unwrap(),
None => path,
};
let data = IndexData { let data = IndexData {
breadcrumb, breadcrumb: normalize_path(rel_path),
paths, paths,
readonly: self.args.readonly, readonly: self.args.readonly,
}; };
let data = serde_json::to_string(&data).unwrap(); let data = serde_json::to_string(&data).unwrap();
let mut output = let output = INDEX_HTML.replace(
INDEX_HTML.replace("__STYLE__", &format!("<style>\n{}</style>", INDEX_CSS)); "__SLOB__",
output = output.replace("__DATA__", &data); &format!(
r#"
<title>Files in {} - Duf/</title>
<style>{}</style>
<script>var DATA = {}; {}</script>
"#,
rel_path.display(),
INDEX_CSS,
data,
INDEX_JS
),
);
Ok(hyper::Response::builder().body(output.into()).unwrap()) Ok(Response::new(output.into()))
} }
fn auth_guard(&self, req: &Request) -> BoxResult<bool> { fn auth_guard(&self, req: &Request) -> BoxResult<bool> {
@@ -266,20 +344,15 @@ impl InnerService {
let value = std::str::from_utf8(&value)?; let value = std::str::from_utf8(&value)?;
return Ok(value == auth); return Ok(value == auth);
} else { } else {
if self.args.no_auth_read && req.method() == Method::GET {
return Ok(true);
}
return Ok(false); return Ok(false);
} }
} }
Ok(true) Ok(true)
} }
fn get_breadcrumb(&self, path: &Path) -> String {
let path = match self.args.path.parent() {
Some(p) => path.strip_prefix(p).unwrap(),
None => path,
};
normalize_path(path)
}
fn get_file_path(&self, path: &str) -> BoxResult<Option<PathBuf>> { fn get_file_path(&self, path: &str) -> BoxResult<Option<PathBuf>> {
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?; let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?;
let slashes_switched = if cfg!(windows) { let slashes_switched = if cfg!(windows) {
@@ -307,7 +380,7 @@ struct IndexData {
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>,
} }
@@ -322,21 +395,17 @@ enum PathType {
async fn get_path_item<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathItem> { async fn get_path_item<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 = get_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()),
@@ -350,6 +419,12 @@ async fn get_path_item<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathI
}) })
} }
fn get_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) {
@@ -359,6 +434,16 @@ fn normalize_path<P: AsRef<Path>>(path: P) -> String {
} }
} }
fn add_cors(res: &mut Response) {
res.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
res.headers_mut().typed_insert(
vec![RANGE, CONTENT_TYPE, ACCEPT, ORIGIN, WWW_AUTHENTICATE]
.into_iter()
.collect::<AccessControlAllowHeaders>(),
);
}
async fn dir_zip<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> { async fn dir_zip<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> {
let mut writer = ZipFileWriter::new(writer); let mut writer = ZipFileWriter::new(writer);
let mut walkdir = WalkDir::new(dir); let mut walkdir = WalkDir::new(dir);