Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/addon/file_server/directory_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub struct DirectoryEntry {
pub(crate) display_name: String,
pub(crate) is_dir: bool,
pub(crate) size: String,
pub(crate) len: u64,
pub(crate) entry_path: String,
pub(crate) created_at: String,
pub(crate) updated_at: String,
Expand Down Expand Up @@ -67,4 +68,6 @@ pub struct DirectoryIndex {
/// Directory listing entry
pub(crate) entries: Vec<DirectoryEntry>,
pub(crate) breadcrumbs: Vec<BreadcrumbItem>,
pub(crate) sort_by_name: bool,
pub(crate) sort_by_size: bool,
}
64 changes: 53 additions & 11 deletions src/addon/file_server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use crate::utils::url_encode::{decode_uri, encode_uri, PERCENT_ENCODE_SET};

use self::directory_entry::{BreadcrumbItem, DirectoryEntry, DirectoryIndex};
use self::http_utils::{make_http_file_response, CacheControlDirective};
use self::query_params::{QueryParams, SortBy};

/// Explorer's Handlebars template filename
const EXPLORER_TEMPLATE: &str = "explorer";
Expand Down Expand Up @@ -60,22 +61,22 @@ impl<'a> FileServer {
Arc::new(handlebars)
}

fn parse_path(req_uri: &str) -> Result<PathBuf> {
fn parse_path(req_uri: &str) -> Result<(PathBuf, Option<QueryParams>)> {
let uri = Uri::from_str(req_uri)?;
let uri_parts = uri.into_parts();

if let Some(path_and_query) = uri_parts.path_and_query {
let path = path_and_query.path();
let _queries = if let Some(query_str) = path_and_query.query() {
Some(query_params::QueryParams::from_str(query_str)?)
let query_params = if let Some(query_str) = path_and_query.query() {
Some(QueryParams::from_str(query_str)?)
} else {
None
};

return Ok(decode_uri(path));
return Ok((decode_uri(path), query_params));
}

Ok(PathBuf::from_str("/")?)
Ok((PathBuf::from_str("/")?, None))
}

/// Resolves a HTTP Request to a file or directory.
Expand Down Expand Up @@ -105,11 +106,13 @@ impl<'a> FileServer {
pub async fn resolve(&self, req_path: String) -> Result<Response<Body>> {
use std::io::ErrorKind;

let path = FileServer::parse_path(req_path.as_str())?;
let (path, query_params) = FileServer::parse_path(req_path.as_str())?;

match self.scoped_file_system.resolve(path).await {
Ok(entry) => match entry {
Entry::Directory(dir) => self.render_directory_index(dir.path()).await,
Entry::Directory(dir) => {
self.render_directory_index(dir.path(), query_params).await
}
Entry::File(file) => {
make_http_file_response(*file, CacheControlDirective::MaxAge(2500)).await
}
Expand All @@ -134,8 +137,13 @@ impl<'a> FileServer {
/// Indexes the directory by creating a `DirectoryIndex`. Such `DirectoryIndex`
/// is used to build the Handlebars "Explorer" template using the Handlebars
/// engine and builds an HTTP Response containing such file
async fn render_directory_index(&self, path: PathBuf) -> Result<Response<Body>> {
let directory_index = FileServer::index_directory(self.root_dir.clone(), path)?;
async fn render_directory_index(
&self,
path: PathBuf,
query_params: Option<QueryParams>,
) -> Result<Response<Body>> {
let directory_index =
FileServer::index_directory(self.root_dir.clone(), path, query_params)?;
let html = self
.handlebars
.render(EXPLORER_TEMPLATE, &directory_index)
Expand Down Expand Up @@ -204,7 +212,11 @@ impl<'a> FileServer {

/// Creates a `DirectoryIndex` with the provided `root_dir` and `path`
/// (HTTP Request URI)
fn index_directory(root_dir: PathBuf, path: PathBuf) -> Result<DirectoryIndex> {
fn index_directory(
root_dir: PathBuf,
path: PathBuf,
query_params: Option<QueryParams>,
) -> Result<DirectoryIndex> {
let breadcrumbs = FileServer::breadcrumbs_from_path(&root_dir, &path)?;
let entries = read_dir(path).context("Unable to read directory")?;
let mut directory_entries: Vec<DirectoryEntry> = Vec::new();
Expand All @@ -231,17 +243,47 @@ impl<'a> FileServer {
.to_string(),
is_dir: metadata.is_dir(),
size: format_bytes(metadata.len() as f64),
len: metadata.len(),
entry_path: FileServer::make_dir_entry_link(&root_dir, &entry.path()),
created_at,
updated_at,
});
}

if let Some(query_params) = query_params {
if let Some(sort_by) = query_params.sort_by {
match sort_by {
SortBy::Name => {
directory_entries.sort_by_key(|entry| entry.display_name.clone());

return Ok(DirectoryIndex {
entries: directory_entries,
breadcrumbs,
sort_by_name: true,
sort_by_size: false,
});
}
SortBy::Size => {
directory_entries.sort_by_key(|entry| entry.len);

return Ok(DirectoryIndex {
entries: directory_entries,
breadcrumbs,
sort_by_name: false,
sort_by_size: true,
});
}
}
}
}

directory_entries.sort();

Ok(DirectoryIndex {
entries: directory_entries,
breadcrumbs,
sort_by_name: false,
sort_by_size: false,
})
}

Expand Down Expand Up @@ -301,7 +343,7 @@ mod tests {
];

for (idx, req_uri) in have.iter().enumerate() {
let sanitized_path = FileServer::parse_path(req_uri).unwrap();
let sanitized_path = FileServer::parse_path(req_uri).unwrap().0;
let wanted_path = PathBuf::from_str(want[idx]).unwrap();

assert_eq!(sanitized_path, wanted_path);
Expand Down
9 changes: 6 additions & 3 deletions src/addon/file_server/query_params.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use anyhow::Error;
use serde::Serialize;
use std::str::FromStr;

#[derive(Debug, PartialEq, Eq)]
enum SortBy {
#[derive(Debug, Eq, PartialEq, Serialize)]
pub enum SortBy {
Name,
Size,
}

impl FromStr for SortBy {
Expand All @@ -15,14 +17,15 @@ impl FromStr for SortBy {

match lower {
"name" => Ok(SortBy::Name),
"size" => Ok(SortBy::Size),
_ => Err(Error::msg("Value doesnt correspond")),
}
}
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct QueryParams {
sort_by: Option<SortBy>,
pub(crate) sort_by: Option<SortBy>,
}

impl FromStr for QueryParams {
Expand Down
27 changes: 16 additions & 11 deletions src/addon/file_server/template/explorer.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,20 @@
min-width: var(--min-width);
overflow-y: auto;
padding: 0;
padding-bottom: 2rem;
width: 95%;
}

#explorer .hrow {
background-color: #FFFFFF;
border-bottom: 1px solid #DDDDDD;
position: -webkit-sticky;
position: sticky;
top: 0;
}

#explorer .hrow .hcol {
border-right: 1px solid #DDDDDD;
box-sizing: border-box;
padding: .3rem .35rem;
color: #000000;
padding: .3rem;
text-decoration: none;
}

#explorer .brow, .bcol {
Expand All @@ -65,7 +63,6 @@

#explorer .hcol:nth-child(2), #explorer .bcol:nth-child(2) {
/* Name Column */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 300px;
Expand Down Expand Up @@ -188,11 +185,19 @@
<main>
<ul id="explorer">
<li class="hrow">
<span class="hcol icon-col">&nbsp;</span>
<span class="hcol">Name</span>
<span class="hcol">Size</span>
<span class="hcol">Date created</span>
<span class="hcol">Date modified</span>
<span class="hcol icon-col"></span>
{{#if sort_by_name}}
<a class="hcol" href="?sort_by=">Name&nbsp;↓</a>
{{else}}
<a class="hcol" href="?sort_by=name">Name</a>
{{/if}}
{{#if sort_by_size}}
<a class="hcol" href="?sort_by=">Size&nbsp;↓</a>
{{else}}
<a class="hcol" href="?sort_by=size">Size</a>
{{/if}}
<a class="hcol">Date created</a>
<a class="hcol">Date modified</a>
</li>
{{#each entries}}
<li class="brow">
Expand Down