diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..35fddc1 --- /dev/null +++ b/.env.example @@ -0,0 +1,66 @@ +# Port to listen on (binds to 127.0.0.1). +BOOK_PORT=8123 + +# Directory for guestbook entry files. +BOOK_DATA_DIR=./data + +# Site title shown in nav and page title. +BOOK_SITE_TITLE=guestbook + +# Telegram bot token. +BOOK_TELEGRAM_BOT_TOKEN=your-bot-token-here + +# Telegram chat ID for moderation messages. +BOOK_TELEGRAM_CHAT_ID=0 + +# Enable honeypot field for spam prevention. +BOOK_HONEYPOT=true + +# Maximum length for names. 0 for unlimited. +BOOK_MAX_NAME_LENGTH=50 + +# Maximum length for messages. 0 for unlimited. +BOOK_MAX_MESSAGE_LENGTH=1000 + +# Maximum length for website URLs. 0 for unlimited. +BOOK_MAX_WEBSITE_LENGTH=100 + +# Allow new guestbook submissions. When false, the form is hidden and submissions are rejected. +BOOK_OPEN_REGISTRATION=true + +# Separator between guestbook entries. +BOOK_SEPARATOR=------------------------------------------------------------ + +# Path to a CSS file. Takes precedence over BOOK_STYLE. +# BOOK_STYLE_FILE=./templates/default.css + +# Custom CSS injected into a style tag. +# Classes: .guestbook-form, .guestbook-prompt, .guestbook-label, .guestbook-input, +# .guestbook-textarea, .guestbook-button, .entry-header, .entry-name, +# .entry-website, .entry-body, .entry-separator +# BOOK_STYLE= + +# Text shown above the form. +BOOK_FORM_PROMPT=If you visited my site, please sign my guestbook! + +# Submit button text. +BOOK_BUTTON_TEXT=sign + +# Label for the name field. +BOOK_LABEL_NAME=Your name: + +# Label for the website field. +BOOK_LABEL_WEBSITE=Your website (optional): + +# Label for the message field. +BOOK_LABEL_MESSAGE=Your message: + +# Number of rows for the message textarea. +BOOK_TEXTAREA_ROWS=8 + +# Number of columns for the message textarea. +BOOK_TEXTAREA_COLS=60 + +# Custom HTML template file with {{title}}, {{form}}, {{entries}}, and {{style}} placeholders. +# Uses built-in default if unset. +# BOOK_TEMPLATE=./templates/default.html diff --git a/LICENSE b/LICENSE index 5e8a6c2..e9c6128 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Llywelwyn +Copyright (c) 2026 Lewis Wynne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/module.nix b/module.nix index 7326c7e..e1defbe 100644 --- a/module.nix +++ b/module.nix @@ -30,11 +30,6 @@ in description = "Site title shown in nav and page title."; }; - siteUrl = mkOption { - type = types.str; - description = "Base URL of the main site (for absolute nav links)."; - }; - telegramChatId = mkOption { type = types.int; description = "Telegram chat ID for moderation messages."; @@ -75,6 +70,72 @@ in description = "Allow new guestbook submissions. When false, the form is hidden and submissions are rejected."; }; + separator = mkOption { + type = types.str; + default = "------------------------------------------------------------"; + description = "Separator between guestbook entries."; + }; + + style = mkOption { + type = types.str; + default = ""; + description = "Custom CSS injected into a style tag. Use class names: .guestbook-form, .guestbook-prompt, .guestbook-label, .guestbook-input, .guestbook-textarea, .guestbook-button, .entry-header, .entry-name, .entry-website, .entry-body, .entry-separator"; + }; + + styleFile = mkOption { + type = types.nullOr types.path; + default = null; + description = "Path to a CSS file. Takes precedence over style."; + }; + + formPrompt = mkOption { + type = types.str; + default = "If you visited my site, please sign my guestbook!"; + description = "Text shown above the form."; + }; + + buttonText = mkOption { + type = types.str; + default = "sign"; + description = "Submit button text."; + }; + + labelName = mkOption { + type = types.str; + default = "Your name:"; + description = "Label for the name field."; + }; + + labelWebsite = mkOption { + type = types.str; + default = "Your website (optional):"; + description = "Label for the website field."; + }; + + labelMessage = mkOption { + type = types.str; + default = "Your message:"; + description = "Label for the message field."; + }; + + textareaRows = mkOption { + type = types.int; + default = 8; + description = "Number of rows for the message textarea."; + }; + + textareaCols = mkOption { + type = types.int; + default = 60; + description = "Number of columns for the message textarea."; + }; + + templateFile = mkOption { + type = types.nullOr types.path; + default = null; + description = "Custom HTML template file with {{title}}, {{form}}, and {{entries}} placeholders. Uses built-in default if null."; + }; + user = mkOption { type = types.str; default = "guestbook"; @@ -108,13 +169,26 @@ in BOOK_PORT = toString cfg.port; BOOK_DATA_DIR = cfg.dataDir; BOOK_SITE_TITLE = cfg.siteTitle; - BOOK_SITE_URL = cfg.siteUrl; + BOOK_TELEGRAM_CHAT_ID = toString cfg.telegramChatId; BOOK_HONEYPOT = if cfg.honeypot then "true" else "false"; BOOK_MAX_NAME_LENGTH = toString cfg.maxNameLength; BOOK_MAX_MESSAGE_LENGTH = toString cfg.maxMessageLength; BOOK_MAX_WEBSITE_LENGTH = toString cfg.maxWebsiteLength; BOOK_OPEN_REGISTRATION = if cfg.openRegistration then "true" else "false"; + BOOK_SEPARATOR = cfg.separator; + BOOK_STYLE = cfg.style; + } // lib.optionalAttrs (cfg.styleFile != null) { + BOOK_STYLE_FILE = cfg.styleFile; + BOOK_FORM_PROMPT = cfg.formPrompt; + BOOK_BUTTON_TEXT = cfg.buttonText; + BOOK_LABEL_NAME = cfg.labelName; + BOOK_LABEL_WEBSITE = cfg.labelWebsite; + BOOK_LABEL_MESSAGE = cfg.labelMessage; + BOOK_TEXTAREA_ROWS = toString cfg.textareaRows; + BOOK_TEXTAREA_COLS = toString cfg.textareaCols; + } // lib.optionalAttrs (cfg.templateFile != null) { + BOOK_TEMPLATE = cfg.templateFile; }; serviceConfig = { Type = "simple"; diff --git a/src/config.rs b/src/config.rs index 84a1128..b86eced 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,7 +6,7 @@ pub struct Config { pub port: u16, pub data_dir: PathBuf, pub site_title: String, - pub site_url: String, + pub telegram_bot_token: String, pub telegram_chat_id: i64, pub honeypot: bool, @@ -14,6 +14,16 @@ pub struct Config { pub max_message_length: usize, pub max_website_length: usize, pub open_registration: bool, + pub template: Option, + pub separator: String, + pub style: String, + pub form_prompt: String, + pub button_text: String, + pub label_name: String, + pub label_website: String, + pub label_message: String, + pub textarea_rows: u32, + pub textarea_cols: u32, } impl Config { @@ -31,7 +41,7 @@ impl Config { .map(PathBuf::from) .unwrap_or_else(|_| PathBuf::from("./data")), site_title: env::var("BOOK_SITE_TITLE").unwrap_or_else(|_| "guestbook".into()), - site_url: env::var("BOOK_SITE_URL").map_err(|_| "BOOK_SITE_URL is required")?, + telegram_bot_token: env::var("BOOK_TELEGRAM_BOT_TOKEN") .map_err(|_| "BOOK_TELEGRAM_BOT_TOKEN is required")?, telegram_chat_id: env::var("BOOK_TELEGRAM_CHAT_ID") @@ -56,6 +66,38 @@ impl Config { open_registration: env::var("BOOK_OPEN_REGISTRATION") .map(|v| v != "false") .unwrap_or(true), + separator: env::var("BOOK_SEPARATOR") + .unwrap_or_else(|_| "------------------------------------------------------------".into()), + template: env::var("BOOK_TEMPLATE").ok().map(|path| { + std::fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("failed to read template {path}: {e}")) + }), + style: env::var("BOOK_STYLE_FILE") + .ok() + .map(|path| { + std::fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("failed to read style file {path}: {e}")) + }) + .or_else(|| env::var("BOOK_STYLE").ok()) + .unwrap_or_default(), + form_prompt: env::var("BOOK_FORM_PROMPT") + .unwrap_or_else(|_| "If you visited my site, please sign my guestbook!".into()), + button_text: env::var("BOOK_BUTTON_TEXT") + .unwrap_or_else(|_| "sign".into()), + label_name: env::var("BOOK_LABEL_NAME") + .unwrap_or_else(|_| "Your name:".into()), + label_website: env::var("BOOK_LABEL_WEBSITE") + .unwrap_or_else(|_| "Your website (optional):".into()), + label_message: env::var("BOOK_LABEL_MESSAGE") + .unwrap_or_else(|_| "Your message:".into()), + textarea_rows: env::var("BOOK_TEXTAREA_ROWS") + .unwrap_or_else(|_| "8".into()) + .parse() + .map_err(|_| "BOOK_TEXTAREA_ROWS must be a number")?, + textarea_cols: env::var("BOOK_TEXTAREA_COLS") + .unwrap_or_else(|_| "60".into()) + .parse() + .map_err(|_| "BOOK_TEXTAREA_COLS must be a number")?, }) } } @@ -73,7 +115,6 @@ mod tests { env::set_var("BOOK_PORT", "9999"); env::set_var("BOOK_DATA_DIR", "/tmp/gb"); env::set_var("BOOK_SITE_TITLE", "test.rs"); - env::set_var("BOOK_SITE_URL", "https://test.rs"); env::set_var("BOOK_TELEGRAM_BOT_TOKEN", "123:ABC"); env::set_var("BOOK_TELEGRAM_CHAT_ID", "12345"); @@ -82,14 +123,12 @@ mod tests { assert_eq!(config.listen_addr(), "127.0.0.1:9999"); assert_eq!(config.data_dir, PathBuf::from("/tmp/gb")); assert_eq!(config.site_title, "test.rs"); - assert_eq!(config.site_url, "https://test.rs"); assert_eq!(config.telegram_chat_id, 12345); // Clean up env::remove_var("BOOK_PORT"); env::remove_var("BOOK_DATA_DIR"); env::remove_var("BOOK_SITE_TITLE"); - env::remove_var("BOOK_SITE_URL"); env::remove_var("BOOK_TELEGRAM_BOT_TOKEN"); env::remove_var("BOOK_TELEGRAM_CHAT_ID"); } @@ -97,7 +136,6 @@ mod tests { #[test] fn test_defaults() { let _lock = ENV_LOCK.lock().unwrap(); - env::set_var("BOOK_SITE_URL", "https://test.rs"); env::set_var("BOOK_TELEGRAM_BOT_TOKEN", "123:ABC"); env::set_var("BOOK_TELEGRAM_CHAT_ID", "12345"); @@ -106,7 +144,6 @@ mod tests { assert_eq!(config.data_dir, PathBuf::from("./data")); assert_eq!(config.site_title, "guestbook"); - env::remove_var("BOOK_SITE_URL"); env::remove_var("BOOK_TELEGRAM_BOT_TOKEN"); env::remove_var("BOOK_TELEGRAM_CHAT_ID"); } @@ -114,7 +151,6 @@ mod tests { #[test] fn test_missing_required() { let _lock = ENV_LOCK.lock().unwrap(); - env::remove_var("BOOK_SITE_URL"); env::remove_var("BOOK_TELEGRAM_BOT_TOKEN"); env::remove_var("BOOK_TELEGRAM_CHAT_ID"); diff --git a/src/render.rs b/src/render.rs index 68f6fab..9fcf179 100644 --- a/src/render.rs +++ b/src/render.rs @@ -1,69 +1,106 @@ +use crate::config::Config; use crate::entries::Entry; -pub fn render_page(site_title: &str, site_url: &str, entries: &[Entry], form_html: &str) -> String { - let nav_url = site_url.trim_end_matches('/'); - let mut html = format!( - r#" - - - - - {site_title} - - - - -

guestbook

-

If you visited my site, please sign my guestbook!

-{form_html} -"# - ); +pub const DEFAULT_TEMPLATE: &str = include_str!("../templates/default.html"); +pub const DEFAULT_STYLE: &str = include_str!("../templates/default.css"); +pub fn render_page(template: &str, config: &Config, entries: &[Entry], form_html: &str) -> String { + let entries_html = render_entries(entries, &config.separator); + let css = if config.style.is_empty() { + DEFAULT_STYLE + } else { + &config.style + }; + let style = format!(""); + template + .replace("{{title}}", &config.site_title) + .replace("{{form}}", form_html) + .replace("{{entries}}", &entries_html) + .replace("{{style}}", &style) +} + +pub fn render_form(config: &Config) -> String { + format!( + r#"{prompt} +
+ + + + + + + + + + +
"#, + prompt = config.form_prompt, + label_name = config.label_name, + label_website = config.label_website, + label_message = config.label_message, + rows = config.textarea_rows, + cols = config.textarea_cols, + button = config.button_text, + ) +} + +fn render_entries(entries: &[Entry], separator: &str) -> String { + let mut html = String::new(); for entry in entries { - html.push_str(&render_entry(entry)); + html.push_str(&render_entry(entry, separator)); } - - html.push_str("\n\n"); html } -fn render_entry(entry: &Entry) -> String { - let mut header = format!("
\n

{} - {}", entry.meta.date, entry.meta.name); +fn render_entry(entry: &Entry, separator: &str) -> String { + let mut header = format!( + "{} - {}", + entry.meta.date, entry.meta.name + ); if !entry.meta.website.is_empty() { header.push_str(&format!( - " ({})", + " ({})", entry.meta.website, entry.meta.website )); } - header.push_str("

\n"); - format!("{header} {}\n
\n", entry.body) + header.push_str(""); + format!( + "\n{header}\n\n{}\n\n{separator}\n", + entry.body + ) } -pub const FORM_HTML: &str = r#"
- - - - - -
"#; - -pub const STYLE_CSS: &str = "body { - max-width: 70ch; - line-height: 1.5; - margin: 0 auto; - padding: 1rem; -} -"; - #[cfg(test)] mod tests { use super::*; use crate::entries::{Entry, EntryMeta, Status}; + use std::path::PathBuf; + + fn test_config() -> Config { + Config { + port: 0, + data_dir: PathBuf::from("./data"), + site_title: "test".into(), + + telegram_bot_token: "fake".into(), + telegram_chat_id: 0, + honeypot: true, + max_name_length: 50, + max_message_length: 1000, + max_website_length: 100, + open_registration: true, + template: None, + separator: "---".into(), + style: String::new(), + form_prompt: "Sign my guestbook!".into(), + button_text: "sign".into(), + label_name: "Your name:".into(), + label_website: "Your website (optional):".into(), + label_message: "Your message:".into(), + textarea_rows: 8, + textarea_cols: 60, + } + } fn make_entry(name: &str, date: &str, body: &str) -> Entry { Entry { @@ -79,41 +116,91 @@ mod tests { } #[test] - fn test_render_page_contains_nav() { - let html = render_page("ily.rs", "https://ily.rs", &[], FORM_HTML); - assert!(html.contains(r#"ily.rs"#)); - assert!(html.contains(r#"links"#)); + fn test_render_default_template() { + let config = test_config(); + let form = render_form(&config); + let html = render_page(DEFAULT_TEMPLATE, &config, &[], &form); + assert!(html.contains("test")); + assert!(html.contains("guestbook-form")); } #[test] - fn test_render_page_contains_form() { - let html = render_page("ily.rs", "https://ily.rs", &[], FORM_HTML); - assert!(html.contains(r#"action="/submit""#)); - assert!(html.contains(r#"style="display:none""#)); // honeypot + fn test_render_custom_template() { + let config = test_config(); + let custom = "{{title}} {{form}} {{entries}} {{style}}"; + let form = render_form(&config); + let html = render_page(custom, &config, &[], &form); + assert!(html.contains("test")); + assert!(html.contains("guestbook-form")); } #[test] - fn test_render_entry_no_website() { + fn test_render_entry_classes() { + let config = test_config(); let entry = make_entry("alice", "2026-04-09", "Hello!"); - let html = render_page("ily.rs", "https://ily.rs", &[entry], FORM_HTML); - assert!(html.contains("alice")); - assert!(html.contains("Hello!")); - assert!(!html.contains(""#)); + let form = render_form(&config); + let html = render_page(DEFAULT_TEMPLATE, &config, &[entry], &form); + assert!(html.contains("entry-website")); + assert!(html.contains(r#"href="https://bob.com">"#)); } #[test] fn test_render_preserves_html_in_body() { - let entry = make_entry("carol", "2026-04-09", "Bold "); - let html = render_page("ily.rs", "https://ily.rs", &[entry], FORM_HTML); + let config = test_config(); + let entry = make_entry("carol", "2026-04-09", "Bold"); + let form = render_form(&config); + let html = render_page(DEFAULT_TEMPLATE, &config, &[entry], &form); assert!(html.contains("Bold")); - assert!(html.contains("")); + } + + #[test] + fn test_render_empty_form_when_closed() { + let config = test_config(); + let html = render_page(DEFAULT_TEMPLATE, &config, &[], ""); + assert!(!html.contains("action=\"/submit\"")); + } + + #[test] + fn test_render_custom_style() { + let mut config = test_config(); + config.style = ".entry-name { color: red; }".into(); + let html = render_page(DEFAULT_TEMPLATE, &config, &[], ""); + assert!(html.contains(".entry-name { color: red; }")); + assert!(html.contains("