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 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
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
target/
*.stats*
.vscode
./config.json
pages/*
config.json
pages/*
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "busser"
version = "0.0.2"
version = "0.0.3"
authors = ["Jerboa"]

edition="2021"
Expand Down
32 changes: 28 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,43 @@
## Busser

Simple website hosting in Rust with Axum
#### Simple HTTPS website hosting in Rust with [Axum](https://github.com/tokio-rs/axum).

✔️ Host HTML/JS (text) content from a given directory
1. Just create a folder with your ```.html/.css/.js``` and other resources, ```.png, .gif, ...```
2. Point Busser to it with a config.json.
3. Run it, and that's it!*

\* you'll need certificates for https, and open ports if on a server
```json
// config.json
{
"port_https": 443,
"port_http": 80,
"throttle": {"max_requests_per_second": 5.0, "timeout_millis": 5000, "clear_period_seconds": 86400},
"path": "pages",
"notification_endpoint": { "addr": "https://discord.com/api/webhooks/xxx/yyy" },
"cert_path": "certs/cert.pem",
"key_path": "certs/key.pem"
}
```

✔️ Host HTML content from a given directory

✔️ Http redirect to https

✔️ Https certifactes
✔️ Https certificates

✔️ IP throttling

🏗️ Host Image content (png, jpg, gif, webp, ...)
✔️ Host Image content (png, jpg, gif, webp, ...)

✔️ Host js, css content

✔️ Host via **free tier** cloud services!

🏗️ Discord webhook integration for status messages

____

#### GDPR, Cookie Policies, and Privacy Policies

Please be aware the following data is store/processed
Expand Down
9 changes: 0 additions & 9 deletions config.json

This file was deleted.

4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ 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 = r"(\.html)$";
const NO_EXTENSION_REGEX: &str = r"^(?!.*\.).*";

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
18 changes: 18 additions & 0 deletions src/pages/page.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::cmp::min;

use axum::response::{IntoResponse, Response, Html};
use serde::{Serialize, Deserialize};

use crate::util::read_file_utf8;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Page
{
Expand All @@ -15,6 +19,15 @@ impl Page
Page { uri: uri.to_string(), body: body.to_string() }
}

pub fn from_file(path: String) -> Option<Page>
{
match read_file_utf8(&path)
{
Some(data) => Some(Page::new(path.as_str(), data.as_str())),
None => None
}
}

pub fn error(text: &str) -> Page
{
Page::new("/", text)
Expand All @@ -24,6 +37,11 @@ impl Page
{
self.uri.clone()
}

pub fn preview(&self, n: usize) -> String
{
format!("uri: {}, body: {} ...", self.get_uri(), self.body[1..min(n, self.body.len())].to_string())
}
}

impl IntoResponse for Page {
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::{content_type, 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, content_type(resource_path.to_string())));
}

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

}
81 changes: 81 additions & 0 deletions src/resources/resource.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use std::{cmp::min, collections::HashMap};

use axum::response::{Html, IntoResponse, Response};
use regex::Regex;
use serde::{Serialize, Deserialize};

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

pub fn content_type(extension: String) -> &'static str
{
let content_types = HashMap::from
(
[
(r"\.txt$", "text/plain"),
(r"\.css$", "text/css"),
(r"\.csv$", "text/csv"),
(r"\.(javascript|js)$", "text/javascript"),
(r"\.xml$", "text/xml"),
(r"\.gif$", "image/gif"),
(r"\.(jpg|jpeg)$", "image/jpeg"),
(r"\.png$", "image/png"),
(r"\.tiff$", "image/tiff"),
(r"\.ico$", "image/x-icon"),
(r"\.(djvu)|(djv)$", "image/vnd.djvu"),
(r"\.svg$", "image/svg+xml"),
(r"\.(mpeg|mpg|mp2|mpe|mpv|m2v)$", "video/mpeg"),
(r"\.(mp4|m4v)$", "video/mp4"),
(r"\.(qt|mov)$", "video/quicktime"),
(r"\.(wmv)$", "video/x-ms-wmv"),
(r"\.(flv|f4v|f4p|f4a|f4b)$", "video/x-flv"),
(r"\.webm$", "video/webm")
]
);

for (re, content) in content_types
{
if Regex::new(re).unwrap().is_match(&extension)
{
return content
}
}

"application/octet-stream"
}

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

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

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

pub fn preview(&self, n: usize) -> String
{
format!("uri: {}, type: {}, bytes: {:?} ...", self.get_uri(), self.content_type, self.body[1..min(n, self.body.len())].to_vec())
}
}

impl IntoResponse for Resource {
fn into_response(self) -> Response {
let mut response = Html(self.body).into_response();
response.headers_mut().insert("content-type", self.content_type.parse().unwrap());
response
}
}
61 changes: 47 additions & 14 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, page::Page}, 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,27 +93,17 @@ 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();

for page in pages
{
crate::debug(format!("Adding page {:?}", page), None);
crate::debug(format!("Adding page {:?}", page.preview(64)), None);

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,33 @@ impl Server
)
}

for resource in resources
Jerboa-app marked this conversation as resolved.
Show resolved Hide resolved
{
crate::debug(format!("Adding resource {:?}", resource.preview(8)), 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()})
)
}

match Page::from_file(config.get_home())
{
Some(page) =>
{
crate::debug(format!("Serving home page, /, {}", page.preview(64)), None);
router = router.route("/", get(|| async move {page.clone().into_response()}))
},
None => {}
}

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

Server
Expand Down
Loading