Add asset_root option

main
_ 2020-11-18 23:24:47 +00:00
parent 3293b3e7f9
commit b32990a6bb
12 changed files with 40 additions and 17 deletions

View File

@ -108,7 +108,7 @@ async fn main () -> Result <(), Box <dyn Error>> {
let addr = SocketAddr::from(([0, 0, 0, 0], 4000)); let addr = SocketAddr::from(([0, 0, 0, 0], 4000));
let handlebars = file_server::load_templates ()?; let handlebars = file_server::load_templates (&PathBuf::new ())?;
let state = Arc::new (ServerState { let state = Arc::new (ServerState {
config: Config { config: Config {

View File

@ -14,13 +14,16 @@ struct Opt {
#[structopt (long)] #[structopt (long)]
config_path: Option <PathBuf>, config_path: Option <PathBuf>,
#[structopt (long)]
asset_root: Option <PathBuf>,
} }
fn main () -> Result <(), Box <dyn Error>> { fn main () -> Result <(), Box <dyn Error>> {
let opt = Opt::from_args (); let opt = Opt::from_args ();
tracing_subscriber::fmt::init (); tracing_subscriber::fmt::init ();
let path = opt.config_path.unwrap_or_else (|| PathBuf::from ("./config/ptth_server.toml")); let path = opt.config_path.clone ().unwrap_or_else (|| PathBuf::from ("./config/ptth_server.toml"));
let config_file: ptth::server::ConfigFile = ptth::load_toml::load (&path); let config_file: ptth::server::ConfigFile = ptth::load_toml::load (&path);
let mut rt = if false { let mut rt = if false {
@ -37,11 +40,12 @@ fn main () -> Result <(), Box <dyn Error>> {
runtime::Runtime::new ()? runtime::Runtime::new ()?
}; };
rt.block_on (async { rt.block_on (async move {
ptth::server::run_server ( ptth::server::run_server (
config_file, config_file,
ptth::graceful_shutdown::init (), ptth::graceful_shutdown::init (),
Some (path) Some (path),
opt.asset_root
).await ).await
})?; })?;

View File

@ -133,7 +133,7 @@ mod tests {
let (stop_server_tx, stop_server_rx) = oneshot::channel (); let (stop_server_tx, stop_server_rx) = oneshot::channel ();
let task_server = { let task_server = {
spawn (async move { spawn (async move {
server::run_server (config_file, stop_server_rx, None).await.unwrap (); server::run_server (config_file, stop_server_rx, None, None).await.unwrap ();
}) })
}; };

View File

@ -147,7 +147,7 @@ impl From <&ConfigFile> for RelayState {
Self { Self {
config: Config::from (config_file), config: Config::from (config_file),
handlebars: Arc::new (load_templates ().unwrap ()), handlebars: Arc::new (load_templates (&PathBuf::new ()).unwrap ()),
request_rendezvous: Default::default (), request_rendezvous: Default::default (),
response_rendezvous: Default::default (), response_rendezvous: Default::default (),
shutdown_watch_tx, shutdown_watch_tx,
@ -539,17 +539,21 @@ async fn handle_all (req: Request <Body>, state: Arc <RelayState>)
}) })
} }
pub fn load_templates () use std::path::{Path, PathBuf};
pub fn load_templates (asset_root: &Path)
-> Result <Handlebars <'static>, Box <dyn Error>> -> Result <Handlebars <'static>, Box <dyn Error>>
{ {
let mut handlebars = Handlebars::new (); let mut handlebars = Handlebars::new ();
handlebars.set_strict_mode (true); handlebars.set_strict_mode (true);
let asset_root = asset_root.join ("handlebars/relay");
for (k, v) in vec! [ for (k, v) in vec! [
("relay_server_list", "relay_server_list.html"), ("relay_server_list", "relay_server_list.html"),
("relay_root", "relay_root.html"), ("relay_root", "relay_root.html"),
].into_iter () { ].into_iter () {
handlebars.register_template_file (k, format! ("ptth_handlebars/{}", v))?; handlebars.register_template_file (k, &asset_root.join (v))?;
} }
Ok (handlebars) Ok (handlebars)

View File

@ -381,7 +381,7 @@ fn serve_307 (location: String) -> Response {
resp resp
} }
fn render_markdown (bytes: &[u8]) -> Result <String, MarkdownError> { fn render_markdown (bytes: &[u8], out: &mut String) -> Result <(), MarkdownError> {
use pulldown_cmark::{Parser, Options, html}; use pulldown_cmark::{Parser, Options, html};
let markdown_input = match std::str::from_utf8 (bytes) { let markdown_input = match std::str::from_utf8 (bytes) {
@ -393,11 +393,17 @@ fn render_markdown (bytes: &[u8]) -> Result <String, MarkdownError> {
options.insert (Options::ENABLE_STRIKETHROUGH); options.insert (Options::ENABLE_STRIKETHROUGH);
let parser = Parser::new_ext (markdown_input, options); let parser = Parser::new_ext (markdown_input, options);
html::push_html (out, parser);
Ok (())
}
fn render_markdown_styled (bytes: &[u8]) -> Result <String, MarkdownError> {
// Write to String buffer. // Write to String buffer.
let mut out = String::new (); let mut out = String::new ();
out.push_str ("<body style=\"font-family: sans-serif;\">"); out.push_str ("<body style=\"font-family: sans-serif;\">");
html::push_html (&mut out, parser); render_markdown (bytes, &mut out)?;
out.push_str ("</body>"); out.push_str ("</body>");
Ok (out) Ok (out)
@ -543,7 +549,7 @@ async fn internal_serve_all (
let bytes_read = file.read (&mut buffer).await.unwrap (); let bytes_read = file.read (&mut buffer).await.unwrap ();
buffer.truncate (bytes_read); buffer.truncate (bytes_read);
MarkdownPreview (render_markdown (&buffer).unwrap ()) MarkdownPreview (render_markdown_styled (&buffer).unwrap ())
} }
} }
else { else {
@ -628,17 +634,21 @@ pub async fn serve_all (
} }
} }
pub fn load_templates () pub fn load_templates (
asset_root: &Path
)
-> Result <Handlebars <'static>, Box <dyn Error>> -> Result <Handlebars <'static>, Box <dyn Error>>
{ {
let mut handlebars = Handlebars::new (); let mut handlebars = Handlebars::new ();
handlebars.set_strict_mode (true); handlebars.set_strict_mode (true);
let asset_root = asset_root.join ("handlebars/server");
for (k, v) in vec! [ for (k, v) in vec! [
("file_server_dir", "file_server_dir.html"), ("file_server_dir", "file_server_dir.html"),
("file_server_root", "file_server_root.html"), ("file_server_root", "file_server_root.html"),
].into_iter () { ].into_iter () {
handlebars.register_template_file (k, format! ("ptth_handlebars/{}", v))?; handlebars.register_template_file (k, asset_root.join (v))?;
} }
Ok (handlebars) Ok (handlebars)
@ -770,7 +780,7 @@ mod tests {
let mut rt = Runtime::new ().unwrap (); let mut rt = Runtime::new ().unwrap ();
rt.block_on (async { rt.block_on (async {
let handlebars = load_templates ().unwrap (); let handlebars = load_templates (&PathBuf::new ()).unwrap ();
let server_info = ServerInfo { let server_info = ServerInfo {
server_name: "PTTH File Server".to_string (), server_name: "PTTH File Server".to_string (),
}; };
@ -879,7 +889,9 @@ mod tests {
"<p>Hello world, this is a <del>complicated</del> <em>very simple</em> example.</p>\n" "<p>Hello world, this is a <del>complicated</del> <em>very simple</em> example.</p>\n"
), ),
].into_iter () { ].into_iter () {
assert_eq! (expected, &render_markdown (input.as_bytes ()).unwrap ()); let mut out = String::default ();
render_markdown (input.as_bytes (), &mut out).unwrap ();
assert_eq! (expected, &out);
} }
} }
} }

View File

@ -128,10 +128,13 @@ pub struct Config {
pub async fn run_server ( pub async fn run_server (
config_file: ConfigFile, config_file: ConfigFile,
shutdown_oneshot: oneshot::Receiver <()>, shutdown_oneshot: oneshot::Receiver <()>,
hidden_path: Option <PathBuf> hidden_path: Option <PathBuf>,
asset_root: Option <PathBuf>
) )
-> Result <(), Box <dyn Error>> -> Result <(), Box <dyn Error>>
{ {
let asset_root = asset_root.unwrap_or_else (|| PathBuf::new ());
use std::convert::TryInto; use std::convert::TryInto;
if crate::password_is_bad (config_file.api_key.clone ()) { if crate::password_is_bad (config_file.api_key.clone ()) {
@ -154,7 +157,7 @@ pub async fn run_server (
.default_headers (headers) .default_headers (headers)
.timeout (Duration::from_secs (40)) .timeout (Duration::from_secs (40))
.build ().unwrap (); .build ().unwrap ();
let handlebars = file_server::load_templates ()?; let handlebars = file_server::load_templates (&asset_root).expect ("Can't load Handlebars templates");
let state = Arc::new (ServerState { let state = Arc::new (ServerState {
config: Config { config: Config {