1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use super::Directory;
use crate::files::pages::render_server_page;
use actix_web::{dev::ServiceResponse, HttpRequest, HttpResponse};
use handlebars::Handlebars;
use indoc::indoc;
use percent_encoding::{utf8_percent_encode, CONTROLS};
use serde_json::json;
use std::{io, path::Path};
pub type ListingRenderer =
dyn Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error> + Sync + Send;
const LIST_TEMPLATE: &str = indoc! {"
<ul>
{{#each entries}}
<li><a href={{url}}>{{name}}</a></li>
{{/each}}
</ul>
"};
pub fn default_listing_renderer(
dir: &Directory,
req: &HttpRequest,
) -> Result<ServiceResponse, io::Error> {
let index_of = format!("Index of {}", req.path());
let base = Path::new(req.path());
let title = match base.file_name() {
Some(filename) => filename.to_string_lossy().into_owned(),
None => String::from("/"),
};
let mut entries = vec![];
for entry in dir.path.read_dir()? {
if dir.is_visible(&entry) {
let entry = entry.unwrap();
let p = match entry.path().strip_prefix(&dir.path) {
Ok(p) if cfg!(windows) => base.join(p).to_string_lossy().replace('\\', "/"),
Ok(p) => base.join(p).to_string_lossy().into_owned(),
Err(_) => continue,
};
if let Ok(metadata) = entry.metadata() {
if metadata.is_dir() {
entries.push(json!({
"url": utf8_percent_encode(&p, CONTROLS).to_string(),
"name": format!("{}/", entry.file_name().to_string_lossy()),
}));
} else {
entries.push(json!({
"url": utf8_percent_encode(&p, CONTROLS).to_string(),
"name": entry.file_name().to_string_lossy(),
}));
}
} else {
continue;
}
}
}
let reg = Handlebars::new();
let body = reg
.render_template(
LIST_TEMPLATE,
&json!({
"entries": entries,
}),
)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let html = render_server_page(&title, &index_of, &body)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(ServiceResponse::new(
req.clone(),
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html),
))
}