Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Resources to handle e.g. .pngs #3

Merged
merged 2 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const MAJOR: &str = env!("CARGO_PKG_VERSION_MAJOR");
const MINOR: &str = env!("CARGO_PKG_VERSION_MINOR");
const PATCH: &str = env!("CARGO_PKG_VERSION_PATCH");

const RESOURCE_REGEX: &str = r"(\.\S+)";
const HTML_REGEX: &str = ".html";

const DEBUG: bool = true;

pub fn debug(msg: String, context: Option<String>)
Expand Down
6 changes: 2 additions & 4 deletions src/pages/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::path::Path;

use regex::Regex;

use crate::{server::model::{Config, CONFIG_PATH}, util::{list_dir, list_dir_by, list_sub_dirs, read_file_utf8}};
use crate::{util::{list_dir_by, list_sub_dirs, read_file_utf8}, HTML_REGEX};

use self::page::Page;

Expand All @@ -16,7 +14,7 @@ pub fn get_pages(path: Option<&str>) -> Vec<Page>
None => ""
};

let html_regex = Regex::new(".html").unwrap();
let html_regex = Regex::new(HTML_REGEX).unwrap();
let page_paths = list_dir_by(html_regex, scan_path.to_string());
let mut pages: Vec<Page> = vec![];

Expand Down
56 changes: 55 additions & 1 deletion src/resources/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,55 @@
pub mod resource;
pub mod resource;

use regex::Regex;

use crate::{util::{list_dir_by, list_sub_dirs, read_file_bytes}, HTML_REGEX, RESOURCE_REGEX};

use self::resource::Resource;

pub fn get_resources(path: Option<&str>) -> Vec<Resource>
{
let scan_path = match path
{
Some(s) => s,
None => ""
};

let resource_regex = Regex::new(RESOURCE_REGEX).unwrap();
let html_regex = Regex::new(HTML_REGEX).unwrap();

let resource_paths = list_dir_by(resource_regex, scan_path.to_string());
let mut resources: Vec<Resource> = vec![];

for resource_path in resource_paths
{
match html_regex.find_iter(resource_path.as_str()).count()
{
0 => {},
_ => {continue}
}

let data = match read_file_bytes(&resource_path)
{
Some(data) => data,
None => continue
};

resources.push(Resource::new(resource_path.as_str(), data));
}

let dirs = list_sub_dirs(scan_path.to_string());

if !dirs.is_empty()
{
for dir in dirs
{
for resource in get_resources(Some(&dir))
{
resources.push(resource);
}
}
}

resources

}
33 changes: 33 additions & 0 deletions src/resources/resource.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use axum::response::{Html, IntoResponse, Response};
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Resource
{
uri: String,
body: Vec<u8>
}

impl Resource
{
pub fn new(uri: &str, body: Vec<u8>) -> Resource
{
Resource { uri: uri.to_string(), body }
}

pub fn get_uri(&self) -> String
{
self.uri.clone()
}

pub fn get_bytes(&self) -> Vec<u8>
{
self.body.clone()
}
}

impl IntoResponse for Resource {
fn into_response(self) -> Response {
Html(self.body).into_response()
}
}
49 changes: 36 additions & 13 deletions src/server/https.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::
{
pages::get_pages, util::read_file_utf8, web::throttle::{handle_throttle, IpThrottler}
pages::get_pages, resources::get_resources, util::read_file_utf8, web::throttle::{handle_throttle, IpThrottler}
};

use std::{net::{IpAddr, Ipv4Addr, SocketAddr}, path::Path};
Expand All @@ -23,6 +23,22 @@ pub struct Server
config: Config
}

pub fn parse_uri(uri: String, path: String) -> String
{
if uri.starts_with(&path)
{
uri.replace(&path, "/")
}
else if uri.starts_with("/")
{
uri
}
else
{
"/".to_string()+&uri
}
}

impl Server
{
pub fn new
Expand Down Expand Up @@ -77,6 +93,7 @@ impl Server
let app = Arc::new(Mutex::new(AppState::new()));

let pages = get_pages(Some(&config.get_path()));
let resources = get_resources(Some(&config.get_path()));

let mut router: Router<(), axum::body::Body> = Router::new();

Expand All @@ -86,18 +103,7 @@ impl Server

let path = config.get_path()+"/";

let uri = if page.get_uri().starts_with(&path)
{
page.get_uri().replace(&path, "/")
}
else if page.get_uri().starts_with("/")
{
page.get_uri()
}
else
{
"/".to_string()+&page.get_uri()
};
let uri = parse_uri(page.get_uri(), path);

crate::debug(format!("Serving: {}", uri), None);

Expand All @@ -108,6 +114,23 @@ impl Server
)
}

for resource in resources
Jerboa-app marked this conversation as resolved.
Show resolved Hide resolved
{
crate::debug(format!("Adding resource {:?}", resource.get_uri()), None);

let path = config.get_path()+"/";

let uri = parse_uri(resource.get_uri(), path);

crate::debug(format!("Serving: {}", uri), None);

router = router.route
(
&uri,
get(|| async move {resource.clone().into_response()})
)
}

router = router.layer(middleware::from_fn_with_state(throttle_state.clone(), handle_throttle));

Server
Expand Down
22 changes: 22 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,33 @@ pub fn read_file_utf8(path: &str) -> Option<String>

let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) =>
{
crate::debug(format!("error reading file to utf8, {}", why), None);
None
},
Ok(_) => Some(s)
}
}

pub fn read_file_bytes(path: &str) -> Option<Vec<u8>>
{
let mut file = match File::open(path) {
Err(why) =>
{
crate::debug(format!("error reading file to utf8, {}", why), None);
return None
},
Ok(file) => file,
};

let mut s: Vec<u8> = vec![];
match file.read_to_end(&mut s) {
Err(why) =>
{
crate::debug(format!("error reading file to utf8, {}", why), None);
None
},
Ok(_) => Some(s)
}
}
Expand Down