diff options
| author | gyoder <70408179+gyoder@users.noreply.github.com> | 2025-07-05 16:13:17 -0600 |
|---|---|---|
| committer | gyoder <70408179+gyoder@users.noreply.github.com> | 2025-07-05 16:16:51 -0600 |
| commit | 7e896c1397a6d2ccbac31a63852b6ed0fbd32a8d (patch) | |
| tree | d3a1592241654265be123f1ee32999eda30e2e06 | |
| parent | 93cee588074981d33bd0da54aaa2e9c0311c3d87 (diff) | |
added apache2 cgi script
| -rw-r--r-- | Cargo.lock | 8 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | htmlua-apache-cgi/Cargo.toml | 8 | ||||
| -rw-r--r-- | htmlua-apache-cgi/src/main.rs | 32 | ||||
| -rw-r--r-- | htmlua-parser/src/lib.rs | 239 | ||||
| -rw-r--r-- | htmlua-parser/src/render.rs | 239 | ||||
| -rw-r--r-- | htmlua-parser/src/serve.rs | 39 |
7 files changed, 329 insertions, 238 deletions
@@ -212,6 +212,14 @@ dependencies = [ ] [[package]] +name = "htmlua-apache-cgi" +version = "0.1.0" +dependencies = [ + "htmlua-parser", + "kuchikiki", +] + +[[package]] name = "htmlua-parser" version = "0.1.0" dependencies = [ @@ -1,5 +1,5 @@ [workspace] -members = ["htmlua-parser", "htmlua-server"] +members = [ "htmlua-apache-cgi","htmlua-parser", "htmlua-server"] resolver = "2" diff --git a/htmlua-apache-cgi/Cargo.toml b/htmlua-apache-cgi/Cargo.toml new file mode 100644 index 0000000..7a8052d --- /dev/null +++ b/htmlua-apache-cgi/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "htmlua-apache-cgi" +version = "0.1.0" +edition = "2024" + +[dependencies] +htmlua-parser = { path = "../htmlua-parser" } +kuchikiki = "0.8.2" diff --git a/htmlua-apache-cgi/src/main.rs b/htmlua-apache-cgi/src/main.rs new file mode 100644 index 0000000..ce86dc6 --- /dev/null +++ b/htmlua-apache-cgi/src/main.rs @@ -0,0 +1,32 @@ +use std::env; +use std::fs; +use std::fs::read_to_string; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use htmlua_parser::serve::serve_content; +use kuchikiki::{ + NodeRef, + traits::TendrilSink, +}; + +fn main() { + println!("Content-Type: text/html\n"); + + let request_uri = env::var("PATH_INFO").unwrap_or_else(|_| "".to_string()); + + let page = serve_content(request_uri.as_str()).unwrap(); + + + // Output the final expanded HTML + println!("{page}"); +} + +// Simple HTML escape function +fn html_escape(input: &str) -> String { + input + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} diff --git a/htmlua-parser/src/lib.rs b/htmlua-parser/src/lib.rs index d5b291f..75aac9c 100644 --- a/htmlua-parser/src/lib.rs +++ b/htmlua-parser/src/lib.rs @@ -1,239 +1,4 @@ -use std::cell::RefCell; -use std::fmt::Write; -use std::fs::read_to_string; -use std::path::PathBuf; -use std::rc::Rc; -use anyhow::Result; -use anyhow::anyhow; -use kuchikiki::{ - NodeRef, - traits::TendrilSink, -}; -use mlua::{Lua, Table}; +pub mod render; +pub mod serve; -fn create_luahtml_stdlib(l: &Lua, stdout: &Rc<RefCell<String>>) -> mlua::Result<Table> { - let t = l.create_table()?; - - // This cannot be the best way to do this - - let stdout_println = stdout.clone(); - t.set( - "println", - l.create_function(move |_, text: String| { - let mut stdout_ref = stdout_println.borrow_mut(); - writeln!(stdout_ref, "{text}").map_err(mlua::Error::external) - })?, - )?; - - let stdout_print = stdout.clone(); - t.set( - "print", - l.create_function(move |_, text: String| { - let mut stdout_ref = stdout_print.borrow_mut(); - write!(stdout_ref, "{text}").map_err(mlua::Error::external) - })?, - )?; - Ok(t) -} - -pub fn execute_lua(document: NodeRef) -> Result<NodeRef> { - let lua = Lua::new(); - let globals = lua.globals(); - - let stdout: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new())); - - let htmlua_table = create_luahtml_stdlib(&lua, &stdout) - .map_err(|e| anyhow!("Failed to create Lua stdlib: {}", e))?; - - globals - .set("htmlua", htmlua_table) - .map_err(|e| anyhow!("Failed to set global: {}", e))?; - - let lua_elements: Vec<_> = match document.select("lua") { - Ok(e) => e.collect(), - Err(()) => return Err(anyhow!("Unable to find Lua")), - }; - - for node in lua_elements { - if let Some(text_node) = node.as_node().first_child() { - if let Some(lua_code) = text_node.as_text() { - stdout.borrow_mut().clear(); - lua.load(lua_code.borrow().as_str()) - .exec() - .map_err(|e| anyhow!("Failed to execute Lua: {}", e))?; - node.as_node() - .insert_before(NodeRef::new_text(stdout.borrow().as_str())); - node.as_node().detach(); - } - } - } - - Ok(document) -} - -pub fn expand_template(document: NodeRef, component_path: &PathBuf, include_from: Option<&NodeRef>) -> Result<NodeRef> { - if let Some(from_node) = include_from { - - - for i in document.select("includeelement").map_err(|()| anyhow!("Error finding includeelement"))? { - if let Some(name) = i.attributes.borrow().get("name") { - let exported = from_node.select_first(format!("exportelement.{name}").as_str()).map_err(|()| anyhow!("Error finding exportelement"))?; - exported.as_node().children().for_each(|c| i.as_node().insert_after(c)); - } - } - while let Ok(i) = document.select_first("includeelement") { - i.as_node().detach(); - } - - } - for i in document.select("include").map_err(|()| anyhow!("Error finding include"))? { - let attrs = match i.as_node().as_element() { - Some(e) => e.attributes.borrow(), - None => continue, - }; - if let Some(include_path) = attrs.get("path") { - let mut item_path = component_path.clone(); - item_path.push(include_path); - let component_text = read_to_string(item_path)?; - let new_node = kuchikiki::parse_html().one(component_text); - let replaced_node = expand_template(new_node, component_path, Some(i.as_node()))?; - i.as_node().insert_before(replaced_node); - i.as_node().detach(); - } - } - Ok(document) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn basic_lua() { - let page = r#" - <!DOCTYPE html> - <html> - <head> - <title>Basic HTML Page</title> - </head> - <body> - <h1>Hello World</h1> - <p>This is a paragraph.</p> - <span><lua> - htmlua.println("Test from Lua!") - </lua></span> - </body> - </html>"#; - let document = kuchikiki::parse_html().one(page); - let d = execute_lua(document).unwrap(); - let text = d.select_first("span").unwrap().as_node().text_contents(); - assert_eq!(text, "Test from Lua!\n"); - assert!(d.select_first("lua").is_err()); - } - - #[test] - fn multiple_lua() { - let page = r#" - <!DOCTYPE html> - <html> - <head> - <title>Basic HTML Page</title> - </head> - <body> - <h1>Hello World</h1> - <p>This is a paragraph.</p> - <span id="ta"><lua> - htmlua.println("Test from Lua!") - </lua></span> - <div> - <span id="tb"><lua>htmlua.println("test 2")</lua></span> - </div> - </body> - </html>"#; - let document = kuchikiki::parse_html().one(page); - let d = execute_lua(document).unwrap(); - let text = d.select_first("#ta").unwrap().as_node().text_contents(); - assert_eq!(text, "Test from Lua!\n"); - let text = d.select_first("#tb").unwrap().as_node().text_contents(); - assert_eq!(text, "test 2\n"); - assert!(d.select_first("lua").is_err()); - } - - #[test] - fn basic_include() { - let page = r#" - <!DOCTYPE html> - <html> - <head> - <title>Basic HTML Page</title> - </head> - <body> - <h1>Hello World</h1> - <p>This is a paragraph.</p> - <include path="comp1.html" /> - <span><lua> - htmlua.println("Test from Lua!") - </lua></span> - </body> - </html>"#; - let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - p.push("tests/components"); - let document = kuchikiki::parse_html().one(page); - let d = expand_template(document, &p, None).unwrap(); - let text = d.select_first("span").unwrap().as_node().text_contents(); - assert_eq!(text, "included1"); - assert!(d.select_first("include").is_err()); - } - - #[test] - fn recursive_include() { - let page = r#" - <!DOCTYPE html> - <html> - <head> - <title>Basic HTML Page</title> - </head> - <body> - <h1>Hello World</h1> - <include path="comp2_level1.html" /> - </body> - </html>"#; - let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - p.push("tests/components"); - let document = kuchikiki::parse_html().one(page); - let d = expand_template(document, &p, None).unwrap(); - let text = d.select_first("span").unwrap().as_node().text_contents(); - assert_eq!(text, "included_twice"); - assert!(d.select_first("include").is_err()); - } - - #[test] - fn export_element_include() { - let page = r#" - <!DOCTYPE html> - <html> - <head> - <title>Basic HTML Page</title> - </head> - <body> - <h1>Hello World</h1> - <include path="with_include1.html"> - <exportelement class="el1"><span id="ta">element 1</span></exportelement> - <exportelement class="el2"><span id="tb">element 2</span></exportelement> - </include> - </body> - </html>"#; - let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - p.push("tests/components"); - let document = kuchikiki::parse_html().one(page); - let d = expand_template(document, &p, None).unwrap(); - let text = d.select_first("#ta").unwrap().as_node().text_contents(); - assert_eq!(text, "element 1"); - let text = d.select_first("#tb").unwrap().as_node().text_contents(); - assert_eq!(text, "element 2"); - assert!(d.select_first("exportelement").is_err()); - assert!(d.select_first("includeelement").is_err()); - } - -} diff --git a/htmlua-parser/src/render.rs b/htmlua-parser/src/render.rs new file mode 100644 index 0000000..d5b291f --- /dev/null +++ b/htmlua-parser/src/render.rs @@ -0,0 +1,239 @@ +use std::cell::RefCell; +use std::fmt::Write; +use std::fs::read_to_string; +use std::path::PathBuf; +use std::rc::Rc; + +use anyhow::Result; +use anyhow::anyhow; +use kuchikiki::{ + NodeRef, + traits::TendrilSink, +}; +use mlua::{Lua, Table}; + +fn create_luahtml_stdlib(l: &Lua, stdout: &Rc<RefCell<String>>) -> mlua::Result<Table> { + let t = l.create_table()?; + + // This cannot be the best way to do this + + let stdout_println = stdout.clone(); + t.set( + "println", + l.create_function(move |_, text: String| { + let mut stdout_ref = stdout_println.borrow_mut(); + writeln!(stdout_ref, "{text}").map_err(mlua::Error::external) + })?, + )?; + + let stdout_print = stdout.clone(); + t.set( + "print", + l.create_function(move |_, text: String| { + let mut stdout_ref = stdout_print.borrow_mut(); + write!(stdout_ref, "{text}").map_err(mlua::Error::external) + })?, + )?; + Ok(t) +} + +pub fn execute_lua(document: NodeRef) -> Result<NodeRef> { + let lua = Lua::new(); + let globals = lua.globals(); + + let stdout: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new())); + + let htmlua_table = create_luahtml_stdlib(&lua, &stdout) + .map_err(|e| anyhow!("Failed to create Lua stdlib: {}", e))?; + + globals + .set("htmlua", htmlua_table) + .map_err(|e| anyhow!("Failed to set global: {}", e))?; + + let lua_elements: Vec<_> = match document.select("lua") { + Ok(e) => e.collect(), + Err(()) => return Err(anyhow!("Unable to find Lua")), + }; + + for node in lua_elements { + if let Some(text_node) = node.as_node().first_child() { + if let Some(lua_code) = text_node.as_text() { + stdout.borrow_mut().clear(); + lua.load(lua_code.borrow().as_str()) + .exec() + .map_err(|e| anyhow!("Failed to execute Lua: {}", e))?; + node.as_node() + .insert_before(NodeRef::new_text(stdout.borrow().as_str())); + node.as_node().detach(); + } + } + } + + Ok(document) +} + +pub fn expand_template(document: NodeRef, component_path: &PathBuf, include_from: Option<&NodeRef>) -> Result<NodeRef> { + if let Some(from_node) = include_from { + + + for i in document.select("includeelement").map_err(|()| anyhow!("Error finding includeelement"))? { + if let Some(name) = i.attributes.borrow().get("name") { + let exported = from_node.select_first(format!("exportelement.{name}").as_str()).map_err(|()| anyhow!("Error finding exportelement"))?; + exported.as_node().children().for_each(|c| i.as_node().insert_after(c)); + } + } + while let Ok(i) = document.select_first("includeelement") { + i.as_node().detach(); + } + + } + for i in document.select("include").map_err(|()| anyhow!("Error finding include"))? { + let attrs = match i.as_node().as_element() { + Some(e) => e.attributes.borrow(), + None => continue, + }; + if let Some(include_path) = attrs.get("path") { + let mut item_path = component_path.clone(); + item_path.push(include_path); + let component_text = read_to_string(item_path)?; + let new_node = kuchikiki::parse_html().one(component_text); + let replaced_node = expand_template(new_node, component_path, Some(i.as_node()))?; + i.as_node().insert_before(replaced_node); + i.as_node().detach(); + } + } + Ok(document) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn basic_lua() { + let page = r#" + <!DOCTYPE html> + <html> + <head> + <title>Basic HTML Page</title> + </head> + <body> + <h1>Hello World</h1> + <p>This is a paragraph.</p> + <span><lua> + htmlua.println("Test from Lua!") + </lua></span> + </body> + </html>"#; + let document = kuchikiki::parse_html().one(page); + let d = execute_lua(document).unwrap(); + let text = d.select_first("span").unwrap().as_node().text_contents(); + assert_eq!(text, "Test from Lua!\n"); + assert!(d.select_first("lua").is_err()); + } + + #[test] + fn multiple_lua() { + let page = r#" + <!DOCTYPE html> + <html> + <head> + <title>Basic HTML Page</title> + </head> + <body> + <h1>Hello World</h1> + <p>This is a paragraph.</p> + <span id="ta"><lua> + htmlua.println("Test from Lua!") + </lua></span> + <div> + <span id="tb"><lua>htmlua.println("test 2")</lua></span> + </div> + </body> + </html>"#; + let document = kuchikiki::parse_html().one(page); + let d = execute_lua(document).unwrap(); + let text = d.select_first("#ta").unwrap().as_node().text_contents(); + assert_eq!(text, "Test from Lua!\n"); + let text = d.select_first("#tb").unwrap().as_node().text_contents(); + assert_eq!(text, "test 2\n"); + assert!(d.select_first("lua").is_err()); + } + + #[test] + fn basic_include() { + let page = r#" + <!DOCTYPE html> + <html> + <head> + <title>Basic HTML Page</title> + </head> + <body> + <h1>Hello World</h1> + <p>This is a paragraph.</p> + <include path="comp1.html" /> + <span><lua> + htmlua.println("Test from Lua!") + </lua></span> + </body> + </html>"#; + let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.push("tests/components"); + let document = kuchikiki::parse_html().one(page); + let d = expand_template(document, &p, None).unwrap(); + let text = d.select_first("span").unwrap().as_node().text_contents(); + assert_eq!(text, "included1"); + assert!(d.select_first("include").is_err()); + } + + #[test] + fn recursive_include() { + let page = r#" + <!DOCTYPE html> + <html> + <head> + <title>Basic HTML Page</title> + </head> + <body> + <h1>Hello World</h1> + <include path="comp2_level1.html" /> + </body> + </html>"#; + let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.push("tests/components"); + let document = kuchikiki::parse_html().one(page); + let d = expand_template(document, &p, None).unwrap(); + let text = d.select_first("span").unwrap().as_node().text_contents(); + assert_eq!(text, "included_twice"); + assert!(d.select_first("include").is_err()); + } + + #[test] + fn export_element_include() { + let page = r#" + <!DOCTYPE html> + <html> + <head> + <title>Basic HTML Page</title> + </head> + <body> + <h1>Hello World</h1> + <include path="with_include1.html"> + <exportelement class="el1"><span id="ta">element 1</span></exportelement> + <exportelement class="el2"><span id="tb">element 2</span></exportelement> + </include> + </body> + </html>"#; + let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.push("tests/components"); + let document = kuchikiki::parse_html().one(page); + let d = expand_template(document, &p, None).unwrap(); + let text = d.select_first("#ta").unwrap().as_node().text_contents(); + assert_eq!(text, "element 1"); + let text = d.select_first("#tb").unwrap().as_node().text_contents(); + assert_eq!(text, "element 2"); + assert!(d.select_first("exportelement").is_err()); + assert!(d.select_first("includeelement").is_err()); + } + +} diff --git a/htmlua-parser/src/serve.rs b/htmlua-parser/src/serve.rs new file mode 100644 index 0000000..6bbf73a --- /dev/null +++ b/htmlua-parser/src/serve.rs @@ -0,0 +1,39 @@ +use std::env; +use std::fs; +use std::fs::read_to_string; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use super::render::execute_lua; +use super::render::expand_template; +use anyhow::Result; +use kuchikiki::{ + NodeRef, + traits::TendrilSink, +}; + +pub fn serve_content(request_uri: &str) -> Result<String>{ + // TODO: read from config + let pages = PathBuf::from("/var/www/htmlua/pages"); + let components = PathBuf::from("/var/www/htmlua/components"); + + let safe_path = Path::new(request_uri).strip_prefix("/")?; + let page_path = pages.join(safe_path); + + let page_string = read_to_string(&page_path)?; + + let doc = kuchikiki::parse_html().one(page_string); + let full_doc = expand_template(doc, &components, None)?; + + let executed_doc = execute_lua(full_doc)?; + + Ok(executed_doc.to_string()) +} + +fn html_escape(input: &str) -> String { + input + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} |
