Skip to content

Commit

Permalink
commit practice
Browse files Browse the repository at this point in the history
  • Loading branch information
rcrwhyg committed Aug 31, 2024
1 parent 02b4dc3 commit db2d9b0
Show file tree
Hide file tree
Showing 7 changed files with 236 additions and 12 deletions.
103 changes: 103 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ clap = { version = "4.5.16", features = ["derive"] }
csv = "1.3.0"
ed25519-dalek = { version = "2.1.1", features = ["rand_core"] }
enum_dispatch = "0.3.13"
futures = "0.3.30"
rand = "0.8.5"
serde = { version = "1.0.209", features = ["derive"] }
serde_json = "1.0.127"
Expand All @@ -36,4 +37,5 @@ tower-http = { version = "0.5.2", features = [
] }
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.14", features = ["env-filter"] }
url = "2.5.2"
zxcvbn = "3.1.0"
1 change: 1 addition & 0 deletions deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ allow = [
"Unicode-DFS-2016",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
#"Apache-2.0 WITH LLVM-exception",
]
# The confidence threshold for detecting a license from license text.
Expand Down
4 changes: 2 additions & 2 deletions src/cli/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,15 @@ pub struct KeyGenerateOpts {
pub struct TextEncryptOpts {
#[arg(short, long, value_parser = verify_file, default_value = "-")]
pub input: String,
#[arg(short, long, value_parser = verify_file)]
#[arg(short, long)]
pub key: String,
}

#[derive(Debug, Parser)]
pub struct TextDecryptOpts {
#[arg(short, long, value_parser = verify_file, default_value = "-")]
pub input: String,
#[arg(short, long, value_parser = verify_file)]
#[arg(short, long)]
pub key: String,
}

Expand Down
101 changes: 98 additions & 3 deletions src/process/http_serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use axum::{
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use tokio::fs::read_dir;
use tower_http::services::ServeDir;
use tracing::{info, warn};

Expand All @@ -13,6 +16,15 @@ struct HttpServeState {
path: PathBuf,
}

#[derive(Debug, Deserialize, Serialize)]
struct FileInfo {
name: String,
path: String,
is_dir: bool,
size: u64,
sub_files: Vec<FileInfo>,
}

pub async fn process_http_serve(path: PathBuf, port: u16) -> anyhow::Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
info!("Serving {:?} on port {}", path, addr);
Expand All @@ -36,12 +48,53 @@ async fn file_handler(
State(state): State<Arc<HttpServeState>>,
Path(path): Path<String>,
) -> (StatusCode, String) {
let p = std::path::Path::new(&state.path).join(path);
let p: PathBuf = std::path::Path::new(&state.path).join(path);
info!("Reading file {:?}", p);
if !p.exists() {
if !p.ends_with("index.html") {
return (
StatusCode::NOT_FOUND,
format!("File {} not Found", p.display()),
);
}

let dir = p.parent().unwrap();
println!("Directory {:?}", dir);
// std::path::Path::new(&state.path).join("index.html");
let files: Vec<FileInfo> = match process_directory_index(dir).await {
Ok(files) => files,
Err(err) => {
warn!("Error reading directory: {}", err);
return (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Error reading directory: {}", err),
);
}
};

let mut ret = String::new();
ret.push_str("<ul>");
for file in files {
println!("{}", json!(file));
if file.is_dir {
ret.push_str(
format!(
"<li><a href=\"{}/index.html\">{}</a></li>",
file.path, file.name
)
.as_str(),
);
} else {
ret.push_str(
format!("<li><a href=\"{}\">{}</a></li>", file.path, file.name).as_str(),
);
}
}
ret.push_str("</ul>");

(
StatusCode::NOT_FOUND,
format!("File {} not Found", p.display()),
StatusCode::OK,
format!("<html><body> {} </body></html>", ret),
)
} else {
// TODO: test p is a directory
Expand All @@ -61,6 +114,48 @@ async fn file_handler(
}
}

async fn process_directory_index(path: &std::path::Path) -> anyhow::Result<Vec<FileInfo>> {
let mut files = Vec::new();

let mut dir = match read_dir(path).await {
Ok(dir) => dir,
Err(err) => {
warn!("Error reading directory: {}", err);
return Err(err.into());
}
};

while let Some(entry) = dir.next_entry().await? {
let path = entry.path();
let metadata = entry.metadata().await?;
let file_type = metadata.file_type();

// let mut file = FileInfo {
let file = FileInfo {
name: entry.file_name().into_string().unwrap(),
path: path
.iter()
.skip(1)
.map(|p| p.to_string_lossy())
.collect::<Vec<_>>()
.join("/"),
is_dir: file_type.is_dir(),
size: metadata.len(),
sub_files: Vec::new(),
};

// 递归展开所有子目录
// if file_type.is_dir() {
// let sub_files = Box::pin(process_directory_index(&path)).await?;
// file.sub_files.extend(sub_files);
// }

files.push(file);
}

Ok(files)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading

0 comments on commit db2d9b0

Please sign in to comment.