Compare commits

..

23 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
sigoden
4841ebb76d docs: update readme demo png 2022-05-29 13:16:58 +08:00
sigoden
586b209c89 feat: support searching 2022-05-29 13:10:41 +08:00
sigoden
2eba975066 styles: optimize css 2022-05-29 11:38:54 +08:00
sigoden
c8a25b54ab feat: Automatically create dir while uploading 2022-05-29 10:53:19 +08:00
sigoden
8900dde7e7 refactor: handler zip 2022-05-29 06:57:16 +08:00
sigoden
06d2b81824 fix: optimize download zip 2022-05-28 22:28:49 +08:00
sigoden
3673a64ec7 feat: aware RUST_LOG 2022-05-28 20:43:20 +08:00
sigoden
d9a917176a fix: cannot upload in root 2022-05-28 20:40:49 +08:00
sigoden
cdb7b5fc87 docs: improve readme 2022-05-28 19:48:54 +08:00
sigoden
76569581dd docs: improve readme 2022-05-28 19:03:50 +08:00
sigoden
ae11a39804 feat: download folder as zip file 2022-05-28 19:00:16 +08:00
sigoden
63e6906393 feat: add logger 2022-05-27 09:21:17 +08:00
sigoden
e6ea7e4f75 chore: update cargo metadata 2022-05-26 21:43:58 +08:00
sigoden
8db039c53b docs: update demo png 2022-05-26 21:36:14 +08:00
10 changed files with 1260 additions and 374 deletions

575
Cargo.lock generated
View File

@@ -2,6 +2,116 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 3
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "async-channel"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2114d64672151c0c5eaa5e131ec84a74f06e1e559830dabba01ca30605d66319"
dependencies = [
"concurrent-queue",
"event-listener",
"futures-core",
]
[[package]]
name = "async-compression"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "345fd392ab01f746c717b1357165b76f0b67a60192007b234058c9045fdcf695"
dependencies = [
"bzip2",
"flate2",
"futures-core",
"memchr",
"pin-project-lite",
"tokio",
"xz2",
"zstd",
"zstd-safe",
]
[[package]]
name = "async-fs"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b3ca4f8ff117c37c278a2f7415ce9be55560b846b5bc4412aaa5d29c1c3dae2"
dependencies = [
"async-lock",
"blocking",
"futures-lite",
]
[[package]]
name = "async-lock"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e97a171d191782fba31bb902b14ad94e24a68145032b7eedf871ab0bc0d077b6"
dependencies = [
"event-listener",
]
[[package]]
name = "async-task"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30696a84d817107fc028e049980e09d5e140e8da8f1caeb17e8e950658a3cea9"
[[package]]
name = "async-walkdir"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "826d88d73e87e7504b635b6e427561faa6a65f4a2f59e75efcbfa51a0876bb90"
dependencies = [
"async-fs",
"futures-lite",
]
[[package]]
name = "async_io_utilities"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0248112abfeab682c97306bc1e180ee957260107a55a437cedf9a3acca92135e"
dependencies = [
"tokio",
]
[[package]]
name = "async_zip"
version = "0.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a5c419dca9559f15d04befbf9ff01c39ca16d4c0abd56f60daaf87a386b929"
dependencies = [
"async-compression",
"async_io_utilities",
"chrono",
"crc32fast",
"thiserror",
"tokio",
]
[[package]]
name = "atomic-waker"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "065374052e7df7ee4047b1160cca5e1467a12351a40b3da123c870ba0b8eda2a"
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.1.0" version = "1.1.0"
@@ -20,18 +130,90 @@ 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]]
name = "blocking"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6ccb65d468978a086b69884437ded69a90faab3bbe6e67f242173ea728acccc"
dependencies = [
"async-channel",
"async-task",
"atomic-waker",
"fastrand",
"futures-lite",
"once_cell",
]
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.1.0" version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8"
[[package]]
name = "bzip2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6afcd980b5f3a45017c57e57a2fcccbb351cc43a356ce117ef760ef8052b89b0"
dependencies = [
"bzip2-sys",
"libc",
]
[[package]]
name = "bzip2-sys"
version = "0.1.11+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "736a955f3fa7875102d57c82b8cac37ec45224a07fd32d58f9f7a186b6cd4cdc"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "cache-padded"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1db59621ec70f09c5e9b597b220c7a2b43611f4710dc03ceb8748637775692c"
[[package]]
name = "cc"
version = "1.0.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11"
dependencies = [
"jobserver",
]
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
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 = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73"
dependencies = [
"libc",
"num-integer",
"num-traits",
"time 0.1.44",
"winapi",
]
[[package]] [[package]]
name = "clap" name = "clap"
version = "3.1.18" version = "3.1.18"
@@ -55,20 +237,111 @@ dependencies = [
] ]
[[package]] [[package]]
name = "duf" name = "colored"
version = "0.1.0" version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
dependencies = [ dependencies = [
"atty",
"lazy_static",
"winapi",
]
[[package]]
name = "concurrent-queue"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30ed07550be01594c6026cff2a1d7fe9c8f683caa798e12b68694ac9e88286a3"
dependencies = [
"cache-padded",
]
[[package]]
name = "cpufeatures"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [
"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]]
name = "duf"
version = "0.5.0"
dependencies = [
"async-walkdir",
"async_zip",
"base64", "base64",
"clap", "clap",
"futures", "futures",
"headers",
"hyper", "hyper",
"log",
"mime_guess",
"percent-encoding", "percent-encoding",
"serde", "serde",
"serde_json", "serde_json",
"simple_logger",
"tokio", "tokio",
"tokio-util", "tokio-util",
] ]
[[package]]
name = "event-listener"
version = "2.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77f3309417938f28bf8228fcff79a4a37103981e3e186d2ccd19c74b38f4eb71"
[[package]]
name = "fastrand"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf"
dependencies = [
"instant",
]
[[package]]
name = "flate2"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39522e96686d38f4bc984b9198e3a0613264abaebaff2c5c918bfa6b6da09af"
dependencies = [
"cfg-if",
"crc32fast",
"libc",
"miniz_oxide",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@@ -123,6 +396,21 @@ version = "0.3.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b"
[[package]]
name = "futures-lite"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694489acd39452c77daa48516b894c153f192c3578d5a839b62c58099fcbf48"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"memchr",
"parking",
"pin-project-lite",
"waker-fn",
]
[[package]] [[package]]
name = "futures-macro" name = "futures-macro"
version = "0.3.21" version = "0.3.21"
@@ -164,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"
@@ -215,9 +538,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
[[package]] [[package]]
name = "hyper" name = "hyper"
version = "0.14.18" version = "0.14.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b26ae0a80afebe130861d90abf98e3814a4f28a4c6ffeb5ab8ebb2be311e0ef2" checksum = "42dc3c131584288d375f2d07f822b0cb012d8c6fb899a5b9fdb3cb7eb9b6004f"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-channel", "futures-channel",
@@ -238,20 +561,38 @@ dependencies = [
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.8.1" version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" checksum = "e6012d540c5baa3589337a98ce73408de9b5a25ec9fc2c6fd6be8f0d39e0ca5a"
dependencies = [ dependencies = [
"autocfg", "autocfg",
"hashbrown", "hashbrown",
] ]
[[package]]
name = "instant"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.2" version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d"
[[package]]
name = "jobserver"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.4.0" version = "1.4.0"
@@ -273,12 +614,48 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "lzma-sys"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdb4b7c3eddad11d3af9e86c487607d2d2442d185d848575365c4856ba96d619"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.5.0" 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]]
name = "miniz_oxide"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2b29bd4bc3f33391105ebee3589c19197c4271e3e5a9ec9bfe8127eeff8f082"
dependencies = [
"adler",
]
[[package]] [[package]]
name = "mio" name = "mio"
version = "0.8.3" version = "0.8.3"
@@ -287,10 +664,29 @@ checksum = "713d550d9b44d89174e066b7a6217ae06234c10cb47819a88290d2b353c31799"
dependencies = [ dependencies = [
"libc", "libc",
"log", "log",
"wasi", "wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys", "windows-sys",
] ]
[[package]]
name = "num-integer"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "num_cpus" name = "num_cpus"
version = "1.13.1" version = "1.13.1"
@@ -301,6 +697,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "num_threads"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.12.0" version = "1.12.0"
@@ -313,6 +718,12 @@ version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21326818e99cfe6ce1e524c2a805c189a99b5ae555a35d19f9a284b427d86afa" checksum = "21326818e99cfe6ce1e524c2a805c189a99b5ae555a35d19f9a284b427d86afa"
[[package]]
name = "parking"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"
[[package]] [[package]]
name = "percent-encoding" name = "percent-encoding"
version = "2.1.0" version = "2.1.0"
@@ -331,6 +742,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkg-config"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.39" version = "1.0.39"
@@ -386,6 +803,30 @@ 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]]
name = "simple_logger"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75a9723083573ace81ad0cdfc50b858aa3c366c48636edb4109d73122a0c0ea"
dependencies = [
"atty",
"colored",
"log",
"time 0.3.9",
"winapi",
]
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.6" version = "0.4.6"
@@ -419,6 +860,55 @@ version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
[[package]]
name = "thiserror"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "time"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi",
]
[[package]]
name = "time"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd"
dependencies = [
"itoa",
"libc",
"num_threads",
"time-macros",
]
[[package]]
name = "time-macros"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42657b1a6f4d817cda8e7a0ace261fe0cc946cf3a80314390b22cc61ae080792"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.18.2" version = "1.18.2"
@@ -506,12 +996,39 @@ 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]]
name = "waker-fn"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
[[package]] [[package]]
name = "want" name = "want"
version = "0.3.0" version = "0.3.0"
@@ -522,6 +1039,12 @@ dependencies = [
"try-lock", "try-lock",
] ]
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.11.0+wasi-snapshot-preview1" version = "0.11.0+wasi-snapshot-preview1"
@@ -592,3 +1115,41 @@ name = "windows_x86_64_msvc"
version = "0.36.1" version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
[[package]]
name = "xz2"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c179869f34fc7c01830d3ce7ea2086bc3a07e0d35289b667d0a8bf910258926c"
dependencies = [
"lzma-sys",
]
[[package]]
name = "zstd"
version = "0.11.2+zstd.1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "5.0.2+zstd.1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db"
dependencies = [
"libc",
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.0.1+zstd.1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fd07cbbc53846d9145dbffdf6dd09a7a0aa52be46741825f5c97bdd4f73f12b"
dependencies = [
"cc",
"libc",
]

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "duf" name = "duf"
version = "0.1.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."
@@ -9,7 +9,7 @@ homepage = "https://github.com/sigoden/duf"
repository = "https://github.com/sigoden/duf" repository = "https://github.com/sigoden/duf"
autotests = false autotests = false
categories = ["command-line-utilities", "web-programming::http-server"] categories = ["command-line-utilities", "web-programming::http-server"]
keywords = ["static", "file", "server", "upload", "http", "cli"] keywords = ["static", "file", "server", "http", "cli"]
[dependencies] [dependencies]
clap = { version = "3", default-features = false, features = ["std", "cargo"] } clap = { version = "3", default-features = false, features = ["std", "cargo"] }
@@ -20,7 +20,13 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
tokio-util = { version = "0.7", features = ["codec", "io-util"] } tokio-util = { version = "0.7", features = ["codec", "io-util"] }
futures = "0.3" futures = "0.3"
base64 = "0.13.0" base64 = "0.13"
log = "0.4"
simple_logger = "2.1.0"
async_zip = "0.0.7"
async-walkdir = "0.2.0"
headers = "0.3.7"
mime_guess = "2.0.4"
[profile.release] [profile.release]
lto = true lto = true

View File

@@ -5,13 +5,17 @@
Duf is a simple file server. Duf is a simple file server.
![demo](https://user-images.githubusercontent.com/4012553/170497689-02aa836d-b49e-4dbb-a98b-37db2d5e9e13.png) ![demo](https://user-images.githubusercontent.com/4012553/170853369-dfcdc4c7-4864-4401-bf49-6e41ffe05df3.png)
## Features ## Features
- Serve static files - Serve static files
- Upload/Delete files - Download folder as zip file
- Support basic auth - Search files
- Upload files
- Delete files
- Basic authentication
- Unzip zip file when upload
- Easy to use with curl - Easy to use with curl
## Install ## Install
@@ -34,23 +38,32 @@ 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 --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
### Curl
## Curl
Download a file Download a file
``` ```
curl http://127.0.0.1:5000/some-file curl http://127.0.0.1:5000/some-file
curl -o some-file.zip http://127.0.0.1:5000/some-file.zip curl -o some-file2 http://127.0.0.1:5000/some-file
```
Download a folder as zip file
```
curl -o some-folder.zip http://127.0.0.1:5000/some-folder?zip
``` ```
Upload a file Upload a file
@@ -59,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,43 +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")
.short('p')
.long("port")
.default_value("5000")
.help("Specify port to listen on")
.value_name("port");
let arg_address = Arg::new("address")
.short('b')
.long("bind")
.default_value("127.0.0.1")
.help("Specify bind address")
.value_name("address");
let arg_path = Arg::new("path")
.default_value(".")
.allow_invalid_utf8(true)
.help("Path to a directory for serving files");
let arg_readonly = Arg::new("readonly")
.short('r')
.long("readonly")
.help("Only serve static files, no operations like upload and delete");
let arg_auth = Arg::new("auth")
.short('a')
.long("auth")
.help("Authenticate with user and pass")
.value_name("user:pass");
clap::command!() clap::command!()
.about(ABOUT) .about(ABOUT)
.arg(arg_address) .arg(
.arg(arg_port) Arg::new("address")
.arg(arg_path) .short('b')
.arg(arg_readonly) .long("bind")
.arg(arg_auth) .default_value("127.0.0.1")
.help("Specify bind address")
.value_name("address"),
)
.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(".")
.allow_invalid_utf8(true)
.help("Path to a directory for serving files"),
)
.arg(
Arg::new("readonly")
.short('r')
.long("readonly")
.help("Disable change operations such as update or delete"),
)
.arg(
Arg::new("auth")
.short('a')
.long("auth")
.help("Use HTTP authentication for all operations")
.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::new("cors")
.long("cors")
.help("Enable CORS, sets `Access-Control-Allow-Origin: *`"),
)
} }
pub fn matches() -> ArgMatches { pub fn matches() -> ArgMatches {
@@ -60,6 +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 no_auth_read: bool,
pub cors: bool,
} }
impl Args { impl Args {
@@ -73,7 +85,9 @@ impl Args {
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("readonly"); 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 no_auth_read = matches.is_present("no-auth-read");
Ok(Args { Ok(Args {
address, address,
@@ -81,6 +95,8 @@ impl Args {
path, path,
readonly, readonly,
auth, auth,
no_auth_read,
cors,
}) })
} }

View File

@@ -4,16 +4,21 @@ html {
color: #24292e; color: #24292e;
} }
.head { body {
display: flex; width: 700px;
align-items: baseline;
padding: 1em 1em 0;
} }
.head input { .hidden {
display: none; display: none;
} }
.head {
display: flex;
flex-wrap: wrap;
align-items: center;
padding: 1em 1em 0;
}
.breadcrumb { .breadcrumb {
font-size: 1.25em; font-size: 1.25em;
} }
@@ -44,8 +49,48 @@ 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;
}
.upload-control input {
display: none;
} }
.main { .main {
@@ -64,22 +109,23 @@ 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: 70px;
padding-left: 0.6em; padding-left: 0.6em;
} }
.main .cell-actions { .main .cell-actions {
width: 100px; width: 60px;
display: flex;
padding-left: 0.6em; padding-left: 0.6em;
} }
@@ -108,6 +154,10 @@ html {
text-decoration: underline; text-decoration: underline;
} }
.action-btn {
padding-left: 0.4em;
}
.uploaders { .uploaders {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;

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,210 +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>
<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>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script>
const $head = document.querySelector(".head");
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;
path;
$elem;
constructor(idx, file) {
this.idx = idx;
this.file = file;
this.path = location.pathname + "/" + file.name;
}
upload() {
const { file, idx, path } = this;
$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="${path}" 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.error(e), false);
ajax.addEventListener("abort", e => this.abort(e), false);
ajax.open("PUT", path);
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}`;
}
error(event) {
this.$elem.innerHTML = `${this.file.name} (x)`;
}
abort(event) {
this.$elem.innerHTML = `${this.file.name} (x)`;
}
}
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 actionTd = readonly ? "" : `
<td class="cell-actions">
<div onclick="deletePath(${index})" class="delete-btn" id="deleteBtn${index}" title="Delete ${file.name}">
<svg width="18" height="18" viewBox="0 0 40 40"><path d="M28,40H11.8c-3.3,0-5.9-2.7-5.9-5.9V16c0-0.6,0.4-1,1-1s1,0.4,1,1v18.1c0,2.2,1.8,3.9,3.9,3.9H28c2.2,0,3.9-1.8,3.9-3.9V16 c0-0.6,0.4-1,1-1s1,0.4,1,1v18.1C33.9,37.3,31.2,40,28,40z"/></g><g><path d="M33.3,4.9h-7.6C25.2,2.1,22.8,0,19.9,0s-5.3,2.1-5.8,4.9H6.5c-2.3,0-4.1,1.8-4.1,4.1S4.2,13,6.5,13h26.9 c2.3,0,4.1-1.8,4.1-4.1S35.6,4.9,33.3,4.9z M19.9,2c1.8,0,3.3,1.2,3.7,2.9h-7.5C16.6,3.2,18.1,2,19.9,2z M33.3,11H6.5 c-1.1,0-2.1-0.9-2.1-2.1c0-1.1,0.9-2.1,2.1-2.1h26.9c1.1,0,2.1,0.9,2.1,2.1C35.4,10.1,34.5,11,33.3,11z"/></g><g><path d="M12.9,35.1c-0.6,0-1-0.4-1-1V17.4c0-0.6,0.4-1,1-1s1,0.4,1,1v16.7C13.9,34.6,13.4,35.1,12.9,35.1z"/></g><g><path d="M26.9,35.1c-0.6,0-1-0.4-1-1V17.4c0-0.6,0.4-1,1-1s1,0.4,1,1v16.7C27.9,34.6,27.4,35.1,26.9,35.1z"/></g><g><path d="M19.9,35.1c-0.6,0-1-0.4-1-1V17.4c0-0.6,0.4-1,1-1s1,0.4,1,1v16.7C20.9,34.6,20.4,35.1,19.9,35.1z"/></svg>
</div>
</td>`
$tbody.insertAdjacentHTML("beforeend", `
<tr id="addPath${index}">
<td class="path cell-name">
<div>${getSvg(file.path_type)}</div>
<a href="${encodeURI(file.path)}" title="${file.name}">${file.name}</a>
</td>
<td class="cell-mtime">${formatMtime(file.mtime)}</td>
<td class="cell-size">${formatSize(file.size)}</td>
${actionTd}
</tr>`)
}
async function deletePath(index) {
const file = paths[index];
if (!file) return;
try {
const res = await fetch(encodeURI(file.path), {
method: "DELETE",
});
if (res.status !== 200) {
const text = await res.text();
throw new Error(text);
}
document.getElementById(`addPath${index}`).remove();
} catch (err) {
alert(`Failed to delete ${file.name}, ${err.message}`);
}
}
function addUploadControl() {
$head.insertAdjacentHTML("beforeend", `
<div class="upload-control" title="Upload file">
<label for="file">
<svg viewBox="0 0 384.97 384.97" width="14" height="14"><path d="M372.939,264.641c-6.641,0-12.03,5.39-12.03,12.03v84.212H24.061v-84.212c0-6.641-5.39-12.03-12.03-12.03 S0,270.031,0,276.671v96.242c0,6.641,5.39,12.03,12.03,12.03h360.909c6.641,0,12.03-5.39,12.03-12.03v-96.242 C384.97,270.019,379.58,264.641,372.939,264.641z"></path><path d="M117.067,103.507l63.46-62.558v235.71c0,6.641,5.438,12.03,12.151,12.03c6.713,0,12.151-5.39,12.151-12.03V40.95 l63.46,62.558c4.74,4.704,12.439,4.704,17.179,0c4.74-4.704,4.752-12.319,0-17.011l-84.2-82.997 c-4.692-4.656-12.584-4.608-17.191,0L99.888,86.496c-4.752,4.704-4.74,12.319,0,17.011 C104.628,108.211,112.327,108.211,117.067,103.507z"></path></svg>
</label>
<input type="file" id="file" name="file" multiple>
</div>
`);
}
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.querySelector(".main thead tr").insertAdjacentHTML("beforeend", `<th class="cell-actions">Actions</th>`);
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

@@ -4,21 +4,35 @@ macro_rules! bail {
} }
} }
#[macro_use]
extern crate log;
mod args; mod args;
mod server; mod server;
pub type BoxResult<T> = Result<T, Box<dyn std::error::Error>>; pub type BoxResult<T> = Result<T, Box<dyn std::error::Error>>;
use log::LevelFilter;
use crate::args::{matches, Args}; use crate::args::{matches, Args};
use crate::server::serve; use crate::server::serve;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
Args::parse(matches()) run().await.unwrap_or_else(handle_err)
.map(serve) }
.unwrap_or_else(handle_err)
.await async fn run() -> BoxResult<()> {
.unwrap_or_else(handle_err); let args = Args::parse(matches())?;
if std::env::var("RUST_LOG").is_ok() {
simple_logger::init()?;
} else {
simple_logger::SimpleLogger::default()
.with_level(LevelFilter::Info)
.init()?;
}
serve(args).await
} }
fn handle_err<T>(err: Box<dyn std::error::Error>) -> T { fn handle_err<T>(err: Box<dyn std::error::Error>) -> T {

View File

@@ -1,7 +1,16 @@
use crate::{Args, BoxResult}; use crate::{Args, BoxResult};
use async_walkdir::WalkDir;
use async_zip::read::seek::ZipFileReader;
use async_zip::write::{EntryOptions, ZipFileWriter};
use async_zip::Compression;
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;
@@ -10,9 +19,11 @@ use std::convert::Infallible;
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::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::StreamReader; 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>;
@@ -26,8 +37,10 @@ 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;
pub async fn serve(args: Args) -> BoxResult<()> { pub async fn serve(args: Args) -> BoxResult<()> {
let address = args.address()?; let address = args.address()?;
@@ -37,7 +50,7 @@ pub async fn serve(args: Args) -> BoxResult<()> {
async { async {
Ok::<_, Infallible>(service_fn(move |req| { Ok::<_, Infallible>(service_fn(move |req| {
let inner = inner.clone(); let inner = inner.clone();
inner.handle(req) inner.call(req)
})) }))
} }
}); });
@@ -59,57 +72,93 @@ impl InnerService {
Self { args } Self { args }
} }
pub async fn handle(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 uri = req.uri().clone();
let cors = self.args.cors;
let mut res = self
.handle(req)
.await
.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR));
info!(r#""{} {}" - {}"#, method, uri, res.status());
if cors {
add_cors(&mut res);
}
Ok(res)
}
pub async fn handle(self: Arc<Self>, req: Request) -> BoxResult<Response> {
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() {
let res = 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 Method::OPTIONS => Ok(status_code!(StatusCode::NO_CONTENT)),
} else if req.method() == Method::DELETE { Method::DELETE => self.handle_delete(req).await,
self.handle_delete(req).await _ => Ok(status_code!(StatusCode::NOT_FOUND)),
} else { }
return Ok(status_code!(StatusCode::NOT_FOUND));
};
Ok(res.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR)))
} }
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() {
self.handle_send_dir(path.as_path()).await 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 { } else {
self.handle_send_file(path.as_path()).await self.handle_send_file(&req, 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))
} }
} }
Err(_) => 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?;
let body_with_io_error = req let body_with_io_error = req
.body_mut() .body_mut()
@@ -121,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));
} }
@@ -139,37 +212,123 @@ 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![];
while let Some(entry) = rd.next_entry().await? { if exist {
let entry_path = entry.path(); let mut rd = fs::read_dir(path).await?;
if let Ok(item) = self.get_path_item(entry_path).await { while let Some(entry) = rd.next_entry().await? {
paths.push(item); let entry_path = entry.path();
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_query_dir(&self, path: &Path, q: &str) -> BoxResult<Response> {
let mut paths: Vec<PathItem> = vec![];
let mut walkdir = WalkDir::new(path);
while let Some(entry) = walkdir.next().await {
if let Ok(entry) = entry {
if !entry
.file_name()
.to_string_lossy()
.to_lowercase()
.contains(&q.to_lowercase())
{
continue;
}
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> {
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
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 body = Body::wrap_stream(stream);
Ok(Response::new(body))
}
async fn handle_send_file(&self, req: &Request, path: &Path) -> BoxResult<Response> {
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 body = Body::wrap_stream(stream);
*res.body_mut() = body;
Ok(res)
}
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() {
let data = SendDirData { Some(p) => path.strip_prefix(p).unwrap(),
breadcrumb, None => path,
};
let data = IndexData {
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 output = INDEX_HTML.replace(
"__SLOB__",
&format!(
r#"
<title>Files in {} - Duf/</title>
<style>{}</style>
<script>var DATA = {}; {}</script>
"#,
rel_path.display(),
INDEX_CSS,
data,
INDEX_JS
),
);
let mut output = Ok(Response::new(output.into()))
INDEX_HTML.replace("__STYLE__", &format!("<style>\n{}</style>", INDEX_CSS));
output = output.replace("__DATA__", &data);
Ok(hyper::Response::builder().body(output.into()).unwrap())
}
async fn handle_send_file(&self, path: &Path) -> BoxResult<Response> {
let file = fs::File::open(path).await?;
let stream = FramedRead::new(file, BytesCodec::new());
let body = Body::wrap_stream(stream);
Ok(Response::new(body))
} }
fn auth_guard(&self, req: &Request) -> BoxResult<bool> { fn auth_guard(&self, req: &Request) -> BoxResult<bool> {
@@ -185,57 +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)
} }
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 {
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) {
@@ -253,7 +370,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,
@@ -263,8 +380,7 @@ struct SendDirData {
struct PathItem { struct PathItem {
path_type: PathType, path_type: PathType,
name: String, name: String,
path: String, mtime: u64,
mtime: Option<u64>,
size: Option<u64>, size: Option<u64>,
} }
@@ -276,6 +392,39 @@ 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, meta2) = tokio::join!(fs::metadata(&path), fs::symlink_metadata(&path));
let (meta, meta2) = (meta?, meta2?);
let is_dir = meta.is_dir();
let is_symlink = meta2.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 = get_timestamp(&meta.modified()?);
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 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) {
@@ -284,3 +433,40 @@ fn normalize_path<P: AsRef<Path>>(path: P) -> String {
path.to_string() path.to_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<()> {
let mut writer = ZipFileWriter::new(writer);
let mut walkdir = WalkDir::new(dir);
while let Some(entry) = walkdir.next().await {
if let Ok(entry) = entry {
let meta = match fs::symlink_metadata(entry.path()).await {
Ok(meta) => meta,
Err(_) => continue,
};
if meta.is_file() {
let filepath = entry.path();
let filename = match filepath.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
Some(v) => v,
None => continue,
};
let entry_options = EntryOptions::new(filename.to_owned(), Compression::Deflate);
let mut file = File::open(&filepath).await?;
let mut file_writer = writer.write_entry_stream(entry_options).await?;
io::copy(&mut file, &mut file_writer).await?;
file_writer.close().await?;
}
}
}
writer.close().await?;
Ok(())
}