mirror of
https://github.com/sigoden/dufs.git
synced 2026-04-09 00:59:02 +03:00
init commit
This commit is contained in:
102
src/args.rs
Normal file
102
src/args.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
use clap::crate_description;
|
||||
use clap::{Arg, ArgMatches};
|
||||
use std::env;
|
||||
use std::fs::canonicalize;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::BoxResult;
|
||||
|
||||
const ABOUT: &str = concat!("\n", crate_description!()); // Add extra newline.
|
||||
|
||||
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");
|
||||
|
||||
clap::command!()
|
||||
.about(ABOUT)
|
||||
.arg(arg_address)
|
||||
.arg(arg_port)
|
||||
.arg(arg_path)
|
||||
}
|
||||
|
||||
pub fn matches() -> ArgMatches {
|
||||
app().get_matches()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct Args {
|
||||
pub address: String,
|
||||
pub port: u16,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
/// Parse command-line arguments.
|
||||
///
|
||||
/// If a parsing error ocurred, exit the process and print out informative
|
||||
/// error message to user.
|
||||
pub fn parse(matches: ArgMatches) -> BoxResult<Args> {
|
||||
let address = matches.value_of("address").unwrap_or_default().to_owned();
|
||||
let port = matches.value_of_t::<u16>("port")?;
|
||||
let path = matches.value_of_os("path").unwrap_or_default();
|
||||
let path = Args::parse_path(path)?;
|
||||
|
||||
Ok(Args {
|
||||
address,
|
||||
port,
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse path.
|
||||
fn parse_path<P: AsRef<Path>>(path: P) -> BoxResult<PathBuf> {
|
||||
let path = path.as_ref();
|
||||
if !path.exists() {
|
||||
bail!("error: path \"{}\" doesn't exist", path.display());
|
||||
}
|
||||
|
||||
env::current_dir()
|
||||
.and_then(|mut p| {
|
||||
p.push(path); // If path is absolute, it replaces the current path.
|
||||
canonicalize(p)
|
||||
})
|
||||
.or_else(|err| {
|
||||
bail!(
|
||||
"error: failed to access path \"{}\": {}",
|
||||
path.display(),
|
||||
err,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct socket address from arguments.
|
||||
pub fn address(&self) -> BoxResult<SocketAddr> {
|
||||
format!("{}:{}", self.address, self.port)
|
||||
.parse()
|
||||
.or_else(|err| {
|
||||
bail!(
|
||||
"error: invalid address {}:{} : {}",
|
||||
self.address,
|
||||
self.port,
|
||||
err,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
102
src/index.css
Normal file
102
src/index.css
Normal file
@@ -0,0 +1,102 @@
|
||||
html {
|
||||
font-family: -apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif;
|
||||
line-height: 1.5;
|
||||
color: #24292e;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
padding: 2.5em 2.5em 0;
|
||||
}
|
||||
|
||||
.head input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.breadcrumb {
|
||||
font-size: 1.25em;
|
||||
}
|
||||
|
||||
.breadcrumb > a {
|
||||
color: #0366d6;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.breadcrumb > a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* final breadcrumb */
|
||||
.breadcrumb > b {
|
||||
color: #24292e;
|
||||
}
|
||||
|
||||
.breadcrumb > .separator {
|
||||
color: #586069;
|
||||
padding: 0 0.25em;
|
||||
}
|
||||
|
||||
.breadcrumb svg {
|
||||
height: 100%;
|
||||
fill: rgba(3,47,98,0.5);
|
||||
padding-right: 0.5em;
|
||||
padding-left: 0.5em;
|
||||
}
|
||||
|
||||
.action {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.main {
|
||||
padding: 0 2.5em;
|
||||
}
|
||||
|
||||
.main th {
|
||||
text-align: left;
|
||||
font-weight: unset;
|
||||
color: #5c5c5c;
|
||||
}
|
||||
|
||||
.main .cell-name {
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
.main .cell-size {
|
||||
text-align: right;
|
||||
width: 80px;
|
||||
}
|
||||
|
||||
.path svg {
|
||||
height: 100%;
|
||||
fill: rgba(3,47,98,0.5);
|
||||
padding-right: 0.5em;
|
||||
}
|
||||
|
||||
.path {
|
||||
display: flex;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.path a {
|
||||
color: #0366d6;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
display: block;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.path a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.uploaders {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
padding: 0.5em 0;
|
||||
}
|
||||
|
||||
.uploader {
|
||||
padding-right: 2em;
|
||||
}
|
||||
175
src/index.html
Normal file
175
src/index.html
Normal file
@@ -0,0 +1,175 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
<title>Duf</title>
|
||||
__STYLE__
|
||||
</head>
|
||||
<body>
|
||||
<div class="head">
|
||||
<div class="breadcrumb"></div>
|
||||
<div class="action" 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>
|
||||
</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 $tbody = document.querySelector(".main tbody");
|
||||
const $breadcrumb = document.querySelector(".breadcrumb");
|
||||
const $fileInput = document.getElementById("file");
|
||||
const $uploaders = document.querySelector(".uploaders");
|
||||
const { breadcrumb, paths } = __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 addFile(file) {
|
||||
$tbody.insertAdjacentHTML("beforeend", `
|
||||
<tr>
|
||||
<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>
|
||||
</tr>
|
||||
`)
|
||||
}
|
||||
|
||||
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 => addFile(file));
|
||||
$fileInput.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>
|
||||
27
src/main.rs
Normal file
27
src/main.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
macro_rules! bail {
|
||||
($($tt:tt)*) => {
|
||||
return Err(From::from(format!($($tt)*)))
|
||||
}
|
||||
}
|
||||
|
||||
mod args;
|
||||
mod server;
|
||||
|
||||
pub type BoxResult<T> = Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
use crate::args::{matches, Args};
|
||||
use crate::server::serve;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
Args::parse(matches())
|
||||
.map(serve)
|
||||
.unwrap_or_else(handle_err)
|
||||
.await
|
||||
.unwrap_or_else(handle_err);
|
||||
}
|
||||
|
||||
fn handle_err<T>(err: Box<dyn std::error::Error>) -> T {
|
||||
eprintln!("Server error: {}", err);
|
||||
std::process::exit(1);
|
||||
}
|
||||
239
src/server.rs
Normal file
239
src/server.rs
Normal file
@@ -0,0 +1,239 @@
|
||||
use crate::{Args, BoxResult};
|
||||
|
||||
use futures::TryStreamExt;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Method, StatusCode};
|
||||
use percent_encoding::percent_decode;
|
||||
use serde::Serialize;
|
||||
use std::convert::Infallible;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
use tokio::{fs, io};
|
||||
use tokio_util::codec::{BytesCodec, FramedRead};
|
||||
use tokio_util::io::StreamReader;
|
||||
|
||||
type Request = hyper::Request<Body>;
|
||||
type Response = hyper::Response<Body>;
|
||||
|
||||
macro_rules! status_code {
|
||||
($status:expr) => {
|
||||
hyper::Response::builder()
|
||||
.status($status)
|
||||
.body($status.canonical_reason().unwrap_or_default().into())
|
||||
.unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
const INDEX_HTML: &str = include_str!("index.html");
|
||||
const INDEX_CSS: &str = include_str!("index.css");
|
||||
|
||||
pub async fn serve(args: Args) -> BoxResult<()> {
|
||||
let address = args.address()?;
|
||||
let inner = Arc::new(InnerService::new(args));
|
||||
let make_svc = make_service_fn(move |_| {
|
||||
let inner = inner.clone();
|
||||
async {
|
||||
Ok::<_, Infallible>(service_fn(move |req| {
|
||||
let inner = inner.clone();
|
||||
inner.handle(req)
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let server = hyper::Server::try_bind(&address)?.serve(make_svc);
|
||||
let address = server.local_addr();
|
||||
eprintln!("Files served on http://{}", address);
|
||||
server.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct InnerService {
|
||||
args: Args,
|
||||
}
|
||||
|
||||
impl InnerService {
|
||||
pub fn new(args: Args) -> Self {
|
||||
Self { args }
|
||||
}
|
||||
|
||||
pub async fn handle(self: Arc<Self>, req: Request) -> Result<Response, hyper::Error> {
|
||||
let res = if req.method() == Method::GET {
|
||||
self.handle_static(req).await
|
||||
} else if req.method() == Method::PUT {
|
||||
self.handle_upload(req).await
|
||||
} 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> {
|
||||
let path = match self.get_file_path(req.uri().path())? {
|
||||
Some(path) => path,
|
||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
||||
};
|
||||
match fs::metadata(&path).await {
|
||||
Ok(meta) => {
|
||||
if meta.is_dir() {
|
||||
self.handle_send_dir(path.as_path()).await
|
||||
} else {
|
||||
self.handle_send_file(path.as_path()).await
|
||||
}
|
||||
}
|
||||
Err(_) => return Ok(status_code!(StatusCode::NOT_FOUND)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_upload(&self, mut req: Request) -> BoxResult<Response> {
|
||||
let path = match self.get_file_path(req.uri().path())? {
|
||||
Some(path) => path,
|
||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
||||
};
|
||||
|
||||
if !fs::metadata(&path.parent().unwrap()).await?.is_dir() {
|
||||
return Ok(status_code!(StatusCode::FORBIDDEN));
|
||||
}
|
||||
|
||||
let mut file = fs::File::create(path).await?;
|
||||
|
||||
let body_with_io_error = req
|
||||
.body_mut()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::Other, err));
|
||||
|
||||
let body_reader = StreamReader::new(body_with_io_error);
|
||||
|
||||
futures::pin_mut!(body_reader);
|
||||
|
||||
io::copy(&mut body_reader, &mut file).await?;
|
||||
|
||||
return Ok(status_code!(StatusCode::OK));
|
||||
}
|
||||
|
||||
async fn handle_send_dir(&self, path: &Path) -> BoxResult<Response> {
|
||||
let base_path = &self.args.path;
|
||||
let mut rd = fs::read_dir(path).await?;
|
||||
let mut paths: Vec<PathItem> = vec![];
|
||||
if self.args.path != path {
|
||||
paths.push(PathItem {
|
||||
path_type: PathType::Dir,
|
||||
name: "..".to_owned(),
|
||||
path: format!(
|
||||
"/{}",
|
||||
normalize_path(path.parent().unwrap().strip_prefix(base_path).unwrap())
|
||||
),
|
||||
mtime: None,
|
||||
size: None,
|
||||
})
|
||||
}
|
||||
while let Some(entry) = rd.next_entry().await? {
|
||||
let entry_path = entry.path();
|
||||
let rel_path = entry_path.strip_prefix(base_path).unwrap();
|
||||
let meta = fs::metadata(&entry_path).await?;
|
||||
let s_meta = fs::symlink_metadata(&entry_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();
|
||||
paths.push(PathItem {
|
||||
path_type,
|
||||
name,
|
||||
path: format!("/{}", normalize_path(rel_path)),
|
||||
mtime,
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
paths.sort_unstable();
|
||||
let breadcrumb = self.get_breadcrumb(path);
|
||||
let data = SendDirData { breadcrumb, paths };
|
||||
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())
|
||||
}
|
||||
|
||||
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 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>> {
|
||||
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?;
|
||||
let slashes_switched = if cfg!(windows) {
|
||||
decoded_path.replace('/', "\\")
|
||||
} else {
|
||||
decoded_path.into_owned()
|
||||
};
|
||||
let path = self.args.path.join(&slashes_switched);
|
||||
if path.starts_with(&self.args.path) {
|
||||
Ok(Some(path))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct SendDirData {
|
||||
breadcrumb: String,
|
||||
paths: Vec<PathItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct PathItem {
|
||||
path_type: PathType,
|
||||
name: String,
|
||||
path: String,
|
||||
mtime: Option<u64>,
|
||||
size: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||
enum PathType {
|
||||
Dir,
|
||||
SymlinkDir,
|
||||
File,
|
||||
SymlinkFile,
|
||||
}
|
||||
|
||||
fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
||||
let path = path.as_ref().to_str().unwrap_or_default();
|
||||
if cfg!(windows) {
|
||||
path.replace('\\', "/")
|
||||
} else {
|
||||
path.to_string()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user