mirror of
https://github.com/sigoden/dufs.git
synced 2026-04-09 09:09:03 +03:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a263d18963 | ||
|
|
10aabcb2f2 | ||
|
|
06ce7b0175 | ||
|
|
4841ebb76d | ||
|
|
586b209c89 | ||
|
|
2eba975066 | ||
|
|
c8a25b54ab | ||
|
|
8900dde7e7 | ||
|
|
06d2b81824 | ||
|
|
3673a64ec7 | ||
|
|
d9a917176a | ||
|
|
cdb7b5fc87 |
105
Cargo.lock
generated
105
Cargo.lock
generated
@@ -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,15 +274,36 @@ 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.2.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-walkdir",
|
"async-walkdir",
|
||||||
"async_zip",
|
"async_zip",
|
||||||
"base64",
|
"base64",
|
||||||
"clap",
|
"clap",
|
||||||
"futures",
|
"futures",
|
||||||
|
"headers",
|
||||||
"hyper",
|
"hyper",
|
||||||
"log",
|
"log",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
@@ -412,12 +451,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 +630,12 @@ 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]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.5.1"
|
version = "0.5.1"
|
||||||
@@ -712,6 +792,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 +985,24 @@ 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]]
|
[[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"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.2.0"
|
version = "0.4.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,7 @@ 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"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
|
|||||||
12
README.md
12
README.md
@@ -5,12 +5,13 @@
|
|||||||
|
|
||||||
Duf is a simple file server.
|
Duf is a simple file server.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Serve static files
|
- Serve static files
|
||||||
- Download folder as zip file
|
- Download folder as zip file
|
||||||
|
- Search files
|
||||||
- Upload files
|
- Upload files
|
||||||
- Delete files
|
- Delete files
|
||||||
- Basic authentication
|
- Basic authentication
|
||||||
@@ -36,16 +37,19 @@ You can run this command to start serving your current working directory on 127.
|
|||||||
duf
|
duf
|
||||||
```
|
```
|
||||||
|
|
||||||
...or specify which folder you want to serve:
|
...or specify which folder you want to serve.
|
||||||
|
|
||||||
```
|
```
|
||||||
duf folder_name
|
duf folder_name
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Only serve static files, disable editing operations such as update or delete
|
||||||
|
```
|
||||||
|
duf --no-change
|
||||||
|
```
|
||||||
|
|
||||||
Finally, run this command to see a list of all available option
|
Finally, run this command to see a list of all available option
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Curl
|
### Curl
|
||||||
|
|
||||||
Download a file
|
Download a file
|
||||||
|
|||||||
73
src/args.rs
73
src/args.rs
@@ -10,47 +10,48 @@ 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("no-change")
|
||||||
.help("Only serve static files, not allowed to upload or delete file");
|
.short('C')
|
||||||
|
.long("no-change")
|
||||||
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("Authenticate with user and pass")
|
||||||
.value_name("user:pass");
|
.value_name("user:pass"),
|
||||||
|
)
|
||||||
let arg_no_log = Arg::new("no-log")
|
.arg(
|
||||||
.long("--no-log")
|
Arg::new("cors")
|
||||||
.help("Don't log any request/response information.");
|
.long("cors")
|
||||||
|
.help("Enable CORS, sets `Access-Control-Allow-Origin: *`"),
|
||||||
clap::command!()
|
)
|
||||||
.about(ABOUT)
|
|
||||||
.arg(arg_address)
|
|
||||||
.arg(arg_port)
|
|
||||||
.arg(arg_path)
|
|
||||||
.arg(arg_static)
|
|
||||||
.arg(arg_auth)
|
|
||||||
.arg(arg_no_log)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn matches() -> ArgMatches {
|
pub fn matches() -> ArgMatches {
|
||||||
@@ -64,7 +65,7 @@ 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 cors: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Args {
|
impl Args {
|
||||||
@@ -77,9 +78,9 @@ 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("no-change");
|
||||||
|
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");
|
|
||||||
|
|
||||||
Ok(Args {
|
Ok(Args {
|
||||||
address,
|
address,
|
||||||
@@ -87,7 +88,7 @@ impl Args {
|
|||||||
path,
|
path,
|
||||||
readonly,
|
readonly,
|
||||||
auth,
|
auth,
|
||||||
log,
|
cors,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,14 +4,15 @@ html {
|
|||||||
color: #24292e;
|
color: #24292e;
|
||||||
}
|
}
|
||||||
|
|
||||||
.head {
|
body {
|
||||||
display: flex;
|
width: 700px;
|
||||||
align-items: baseline;
|
|
||||||
padding: 1em 1em 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.head input {
|
.head {
|
||||||
display: none;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1em 1em 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.breadcrumb {
|
.breadcrumb {
|
||||||
@@ -44,11 +45,50 @@ html {
|
|||||||
padding-left: 0.5em;
|
padding-left: 0.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.toolbox {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.searchbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
width: 246px;
|
||||||
|
height: 22px;
|
||||||
|
background-color: #fafafa;
|
||||||
|
transition: all .15s;
|
||||||
|
border: 1px #ddd solid;
|
||||||
|
border-radius: 15px;
|
||||||
|
margin: 0 0 2px 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.searchbar #search {
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 16px;
|
||||||
|
padding: 1px;
|
||||||
|
font-family: helvetica neue,luxi sans,Tahoma,hiragino sans gb,STHeiti,sans-serif;
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.searchbar .icon {
|
||||||
|
color: #9a9a9a;
|
||||||
|
padding: 3px 3px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
.upload-control {
|
.upload-control {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
padding-left: 0.25em;
|
padding-left: 0.25em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.upload-control input {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.main {
|
.main {
|
||||||
padding: 0 1em;
|
padding: 0 1em;
|
||||||
}
|
}
|
||||||
@@ -65,22 +105,22 @@ html {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-name {
|
.main .cell-name {
|
||||||
width: 300px;
|
width: 400px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-mtime {
|
.main .cell-mtime {
|
||||||
width: 150px;
|
width: 120px;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-size {
|
.main .cell-size {
|
||||||
text-align: right;
|
text-align: right;
|
||||||
width: 100px;
|
width: 60px;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-actions {
|
.main .cell-actions {
|
||||||
width: 100px;
|
width: 60px;
|
||||||
display: flex;
|
display: flex;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,21 @@
|
|||||||
<body>
|
<body>
|
||||||
<div class="head">
|
<div class="head">
|
||||||
<div class="breadcrumb"></div>
|
<div class="breadcrumb"></div>
|
||||||
|
<div class="toolbox">
|
||||||
<div>
|
<div>
|
||||||
<a href="?zip" title="Download folder as a .zip file">
|
<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>
|
<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>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</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="main">
|
||||||
<div class="uploaders">
|
<div class="uploaders">
|
||||||
</div>
|
</div>
|
||||||
@@ -34,7 +43,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
|
|
||||||
const $head = document.querySelector(".head");
|
const $toolbox = document.querySelector(".toolbox");
|
||||||
const $tbody = document.querySelector(".main tbody");
|
const $tbody = document.querySelector(".main tbody");
|
||||||
const $breadcrumb = document.querySelector(".breadcrumb");
|
const $breadcrumb = document.querySelector(".breadcrumb");
|
||||||
const $uploaders = document.querySelector(".uploaders");
|
const $uploaders = document.querySelector(".uploaders");
|
||||||
@@ -45,20 +54,19 @@
|
|||||||
class Uploader {
|
class Uploader {
|
||||||
idx = 0;
|
idx = 0;
|
||||||
file;
|
file;
|
||||||
path;
|
|
||||||
$elem;
|
$elem;
|
||||||
constructor(idx, file) {
|
constructor(idx, file) {
|
||||||
this.idx = idx;
|
this.idx = idx;
|
||||||
this.file = file;
|
this.file = file;
|
||||||
this.path = location.pathname + "/" + file.name;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
upload() {
|
upload() {
|
||||||
const { file, idx, path } = this;
|
const { file, idx } = this;
|
||||||
|
const url = getUrl(file.name);
|
||||||
$uploaders.insertAdjacentHTML("beforeend", `
|
$uploaders.insertAdjacentHTML("beforeend", `
|
||||||
<div class="uploader path">
|
<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>
|
<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="${path}" id="file${idx}">${file.name} (0%)</a>
|
<a href="${url}" id="file${idx}">${file.name} (0%)</a>
|
||||||
</div>`);
|
</div>`);
|
||||||
this.$elem = document.getElementById(`file${idx}`);
|
this.$elem = document.getElementById(`file${idx}`);
|
||||||
|
|
||||||
@@ -67,7 +75,7 @@
|
|||||||
ajax.addEventListener("load", e => this.complete(e), false);
|
ajax.addEventListener("load", e => this.complete(e), false);
|
||||||
ajax.addEventListener("error", e => this.fail(e), false);
|
ajax.addEventListener("error", e => this.fail(e), false);
|
||||||
ajax.addEventListener("abort", e => this.fail(e), false);
|
ajax.addEventListener("abort", e => this.fail(e), false);
|
||||||
ajax.open("PUT", path);
|
ajax.open("PUT", url);
|
||||||
ajax.send(file);
|
ajax.send(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,7 +114,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addPath(file, index) {
|
function addPath(file, index) {
|
||||||
const url = encodeURI(file.path);
|
const url = getUrl(file.name)
|
||||||
let actionDelete = "";
|
let actionDelete = "";
|
||||||
let actionDownload = "";
|
let actionDownload = "";
|
||||||
if (file.path_type.endsWith("Dir")) {
|
if (file.path_type.endsWith("Dir")) {
|
||||||
@@ -153,7 +161,7 @@
|
|||||||
if (!file) return;
|
if (!file) return;
|
||||||
|
|
||||||
const ajax = new XMLHttpRequest();
|
const ajax = new XMLHttpRequest();
|
||||||
ajax.open("DELETE", encodeURI(file.path));
|
ajax.open("DELETE", getUrl(file.name));
|
||||||
ajax.addEventListener("readystatechange", function() {
|
ajax.addEventListener("readystatechange", function() {
|
||||||
if(ajax.readyState === 4 && ajax.status === 200) {
|
if(ajax.readyState === 4 && ajax.status === 200) {
|
||||||
document.getElementById(`addPath${index}`).remove();
|
document.getElementById(`addPath${index}`).remove();
|
||||||
@@ -163,7 +171,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addUploadControl() {
|
function addUploadControl() {
|
||||||
$head.insertAdjacentHTML("beforeend", `
|
$toolbox.insertAdjacentHTML("beforeend", `
|
||||||
<div class="upload-control" title="Upload file">
|
<div class="upload-control" title="Upload file">
|
||||||
<label for="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>
|
<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>
|
||||||
@@ -173,6 +181,13 @@
|
|||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getUrl(name) {
|
||||||
|
let url = location.href.split('?')[0];
|
||||||
|
if (!url.endsWith("/")) url += "/";
|
||||||
|
url += encodeURI(name);
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
function getSvg(path_type) {
|
function getSvg(path_type) {
|
||||||
switch (path_type) {
|
switch (path_type) {
|
||||||
case "Dir":
|
case "Dir":
|
||||||
|
|||||||
@@ -25,14 +25,13 @@ async fn main() {
|
|||||||
async fn run() -> BoxResult<()> {
|
async fn run() -> BoxResult<()> {
|
||||||
let args = Args::parse(matches())?;
|
let args = Args::parse(matches())?;
|
||||||
|
|
||||||
let level = if args.log {
|
if std::env::var("RUST_LOG").is_ok() {
|
||||||
LevelFilter::Info
|
simple_logger::init()?;
|
||||||
} else {
|
} 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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
224
src/server.rs
224
src/server.rs
@@ -5,7 +5,8 @@ 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, HeaderMapExt};
|
||||||
|
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;
|
||||||
@@ -18,8 +19,7 @@ use tokio::fs::File;
|
|||||||
use tokio::io::AsyncWrite;
|
use tokio::io::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;
|
use tokio_util::io::{ReaderStream, StreamReader};
|
||||||
use tokio_util::io::StreamReader;
|
|
||||||
|
|
||||||
type Request = hyper::Request<Body>;
|
type Request = hyper::Request<Body>;
|
||||||
type Response = hyper::Response<Body>;
|
type Response = hyper::Response<Body>;
|
||||||
@@ -35,6 +35,7 @@ macro_rules! status_code {
|
|||||||
|
|
||||||
const INDEX_HTML: &str = include_str!("index.html");
|
const INDEX_HTML: &str = include_str!("index.html");
|
||||||
const INDEX_CSS: &str = include_str!("index.css");
|
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()?;
|
||||||
@@ -69,11 +70,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,53 +86,71 @@ 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)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_static(&self, req: Request) -> BoxResult<Response> {
|
async fn handle_static(&self, req: Request) -> BoxResult<Response> {
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
let req_path = req.uri().path();
|
||||||
|
let path = match self.get_file_path(req_path)? {
|
||||||
Some(path) => path,
|
Some(path) => path,
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
||||||
};
|
};
|
||||||
match fs::metadata(&path).await {
|
match fs::metadata(&path).await {
|
||||||
Ok(meta) => {
|
Ok(meta) => {
|
||||||
if meta.is_dir() {
|
if meta.is_dir() {
|
||||||
if req.uri().query().map(|v| v == "zip").unwrap_or_default() {
|
let req_query = req.uri().query().unwrap_or_default();
|
||||||
self.handle_send_dir_zip(path.as_path()).await
|
if req_query == "zip" {
|
||||||
} else {
|
return self.handle_send_dir_zip(path.as_path()).await;
|
||||||
self.handle_send_dir(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 {
|
} else {
|
||||||
self.handle_send_file(path.as_path()).await
|
self.handle_send_file(path.as_path()).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => Ok(status_code!(StatusCode::NOT_FOUND)),
|
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(&self, mut req: Request) -> BoxResult<Response> {
|
||||||
|
let forbidden = status_code!(StatusCode::FORBIDDEN);
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
let path = match self.get_file_path(req.uri().path())? {
|
||||||
Some(path) => path,
|
Some(path) => path,
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
None => return Ok(forbidden),
|
||||||
};
|
};
|
||||||
|
|
||||||
if !fs::metadata(&path.parent().unwrap()).await?.is_dir() {
|
match path.parent() {
|
||||||
return Ok(status_code!(StatusCode::FORBIDDEN));
|
Some(parent) => match fs::metadata(parent).await {
|
||||||
|
Ok(meta) => {
|
||||||
|
if !meta.is_dir() {
|
||||||
|
return Ok(forbidden);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => fs::create_dir_all(parent).await?,
|
||||||
|
},
|
||||||
|
None => return Ok(forbidden),
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut file = fs::File::create(path).await?;
|
let mut file = fs::File::create(path).await?;
|
||||||
@@ -160,35 +183,52 @@ impl InnerService {
|
|||||||
Ok(status_code!(StatusCode::OK))
|
Ok(status_code!(StatusCode::OK))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_dir(&self, path: &Path) -> BoxResult<Response> {
|
async fn handle_ls_dir(&self, path: &Path, exist: bool) -> BoxResult<Response> {
|
||||||
let mut rd = fs::read_dir(path).await?;
|
|
||||||
let mut paths: Vec<PathItem> = vec![];
|
let mut paths: Vec<PathItem> = vec![];
|
||||||
|
if exist {
|
||||||
|
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) = self.get_path_item(entry_path).await {
|
if let Ok(item) = get_path_item(entry_path, path.to_path_buf()).await {
|
||||||
paths.push(item);
|
paths.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
self.send_index(path, paths)
|
||||||
|
}
|
||||||
|
|
||||||
paths.sort_unstable();
|
async fn handle_query_dir(&self, path: &Path, q: &str) -> BoxResult<Response> {
|
||||||
let breadcrumb = self.get_breadcrumb(path);
|
let mut paths: Vec<PathItem> = vec![];
|
||||||
let data = SendDirData {
|
let mut walkdir = WalkDir::new(path);
|
||||||
breadcrumb,
|
while let Some(entry) = walkdir.next().await {
|
||||||
paths,
|
if let Ok(entry) = entry {
|
||||||
readonly: self.args.readonly,
|
if !entry
|
||||||
};
|
.file_name()
|
||||||
let data = serde_json::to_string(&data).unwrap();
|
.to_string_lossy()
|
||||||
|
.to_lowercase()
|
||||||
let mut output =
|
.contains(&q.to_lowercase())
|
||||||
INDEX_HTML.replace("__STYLE__", &format!("<style>\n{}</style>", INDEX_CSS));
|
{
|
||||||
output = output.replace("__DATA__", &data);
|
continue;
|
||||||
|
}
|
||||||
Ok(hyper::Response::builder().body(output.into()).unwrap())
|
if fs::symlink_metadata(entry.path()).await.is_err() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Ok(item) = get_path_item(entry.path(), path.to_path_buf()).await {
|
||||||
|
paths.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.send_index(path, paths)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> {
|
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> {
|
||||||
let (mut writer, reader) = tokio::io::duplex(65536);
|
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
||||||
dir_zip(&mut writer, path).await?;
|
let path = path.to_owned();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = dir_zip(&mut writer, &path).await {
|
||||||
|
error!("Fail to zip {}, {}", path.display(), e.to_string());
|
||||||
|
}
|
||||||
|
});
|
||||||
let stream = ReaderStream::new(reader);
|
let stream = ReaderStream::new(reader);
|
||||||
let body = Body::wrap_stream(stream);
|
let body = Body::wrap_stream(stream);
|
||||||
Ok(Response::new(body))
|
Ok(Response::new(body))
|
||||||
@@ -201,6 +241,22 @@ impl InnerService {
|
|||||||
Ok(Response::new(body))
|
Ok(Response::new(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn send_index(&self, path: &Path, mut paths: Vec<PathItem>) -> BoxResult<Response> {
|
||||||
|
paths.sort_unstable();
|
||||||
|
let breadcrumb = self.get_breadcrumb(path);
|
||||||
|
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> {
|
fn auth_guard(&self, req: &Request) -> BoxResult<bool> {
|
||||||
if let Some(auth) = &self.args.auth {
|
if let Some(auth) = &self.args.auth {
|
||||||
if let Some(value) = req.headers().get("Authorization") {
|
if let Some(value) = req.headers().get("Authorization") {
|
||||||
@@ -220,43 +276,6 @@ impl InnerService {
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_path_item<P: AsRef<Path>>(&self, path: P) -> BoxResult<PathItem> {
|
|
||||||
let path = path.as_ref();
|
|
||||||
let base_path = &self.args.path;
|
|
||||||
let rel_path = path.strip_prefix(base_path).unwrap();
|
|
||||||
let meta = fs::metadata(&path).await?;
|
|
||||||
let s_meta = fs::symlink_metadata(&path).await?;
|
|
||||||
let is_dir = meta.is_dir();
|
|
||||||
let is_symlink = s_meta.file_type().is_symlink();
|
|
||||||
let path_type = match (is_symlink, is_dir) {
|
|
||||||
(true, true) => PathType::SymlinkDir,
|
|
||||||
(false, true) => PathType::Dir,
|
|
||||||
(true, false) => PathType::SymlinkFile,
|
|
||||||
(false, false) => PathType::File,
|
|
||||||
};
|
|
||||||
let mtime = meta
|
|
||||||
.modified()?
|
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
|
||||||
.ok()
|
|
||||||
.map(|v| v.as_millis() as u64);
|
|
||||||
let size = match path_type {
|
|
||||||
PathType::Dir | PathType::SymlinkDir => None,
|
|
||||||
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
|
||||||
};
|
|
||||||
let name = rel_path
|
|
||||||
.file_name()
|
|
||||||
.and_then(|v| v.to_str())
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_owned();
|
|
||||||
Ok(PathItem {
|
|
||||||
path_type,
|
|
||||||
name,
|
|
||||||
path: format!("/{}", normalize_path(rel_path)),
|
|
||||||
mtime,
|
|
||||||
size,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_breadcrumb(&self, path: &Path) -> String {
|
fn get_breadcrumb(&self, path: &Path) -> String {
|
||||||
let path = match self.args.path.parent() {
|
let path = match self.args.path.parent() {
|
||||||
Some(p) => path.strip_prefix(p).unwrap(),
|
Some(p) => path.strip_prefix(p).unwrap(),
|
||||||
@@ -282,7 +301,7 @@ impl InnerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||||
struct SendDirData {
|
struct IndexData {
|
||||||
breadcrumb: String,
|
breadcrumb: String,
|
||||||
paths: Vec<PathItem>,
|
paths: Vec<PathItem>,
|
||||||
readonly: bool,
|
readonly: bool,
|
||||||
@@ -292,7 +311,6 @@ struct SendDirData {
|
|||||||
struct PathItem {
|
struct PathItem {
|
||||||
path_type: PathType,
|
path_type: PathType,
|
||||||
name: String,
|
name: String,
|
||||||
path: String,
|
|
||||||
mtime: Option<u64>,
|
mtime: Option<u64>,
|
||||||
size: Option<u64>,
|
size: Option<u64>,
|
||||||
}
|
}
|
||||||
@@ -305,6 +323,37 @@ enum PathType {
|
|||||||
SymlinkFile,
|
SymlinkFile,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn get_path_item<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathItem> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
let rel_path = path.strip_prefix(base_path).unwrap();
|
||||||
|
let meta = fs::metadata(&path).await?;
|
||||||
|
let s_meta = fs::symlink_metadata(&path).await?;
|
||||||
|
let is_dir = meta.is_dir();
|
||||||
|
let is_symlink = s_meta.file_type().is_symlink();
|
||||||
|
let path_type = match (is_symlink, is_dir) {
|
||||||
|
(true, true) => PathType::SymlinkDir,
|
||||||
|
(false, true) => PathType::Dir,
|
||||||
|
(true, false) => PathType::SymlinkFile,
|
||||||
|
(false, false) => PathType::File,
|
||||||
|
};
|
||||||
|
let mtime = meta
|
||||||
|
.modified()?
|
||||||
|
.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
|
.ok()
|
||||||
|
.map(|v| v.as_millis() as u64);
|
||||||
|
let size = match path_type {
|
||||||
|
PathType::Dir | PathType::SymlinkDir => None,
|
||||||
|
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
||||||
|
};
|
||||||
|
let name = normalize_path(rel_path);
|
||||||
|
Ok(PathItem {
|
||||||
|
path_type,
|
||||||
|
name,
|
||||||
|
mtime,
|
||||||
|
size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
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) {
|
||||||
@@ -314,12 +363,25 @@ 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);
|
||||||
while let Some(entry) = walkdir.next().await {
|
while let Some(entry) = walkdir.next().await {
|
||||||
if let Ok(entry) = entry {
|
if let Ok(entry) = entry {
|
||||||
let meta = fs::symlink_metadata(entry.path()).await?;
|
let meta = match fs::symlink_metadata(entry.path()).await {
|
||||||
|
Ok(meta) => meta,
|
||||||
|
Err(_) => continue,
|
||||||
|
};
|
||||||
if meta.is_file() {
|
if meta.is_file() {
|
||||||
let filepath = entry.path();
|
let filepath = entry.path();
|
||||||
let filename = match filepath.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
|
let filename = match filepath.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
|
||||||
|
|||||||
Reference in New Issue
Block a user