//! E-mail texts (Hungarian and English), as plain text and HTML. //! //! The payloads are written by the backend; the validity periods in the //! texts match the token lifetimes there. The worker sends the result, the //! backend renders it for the admin preview. //! //! The layout is deliberately plain for spam filters: one column, inline //! styles, no images, no tracking, every link on the site's own domain, and //! a plain-text part with the same content. use serde_json::Value; #[derive(Debug, Clone, PartialEq)] pub struct Rendered { pub subject: String, pub text: String, pub html: String, /// One-click unsubscribe address for the `List-Unsubscribe` header (RFC 8058). pub unsubscribe_post_url: Option, } #[derive(Debug, PartialEq)] pub enum TemplateError { UnknownTemplate(String), MissingField(&'static str), } impl std::fmt::Display for TemplateError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TemplateError::UnknownTemplate(t) => write!(f, "unknown e-mail template '{t}'"), TemplateError::MissingField(field) => write!(f, "e-mail payload has no '{field}'"), } } } #[derive(Clone, Copy, PartialEq)] enum Lang { Hu, En, } /// One e-mail: greeting, paragraphs, a button and a closing note. struct Content { subject: String, /// The line mail clients show after the subject in the inbox. preheader: Option, greeting: String, intro: String, /// A personal message, shown as a quote. quote: Option, /// A short list after the intro, with its heading. points: Option<(&'static str, Vec<&'static str>)>, button: &'static str, url: String, note: String, /// Why the recipient got this e-mail (for mails they did not ask for). reason: Option, /// Label and page of the unsubscribe link in the footer. unsubscribe: Option<(&'static str, String)>, unsubscribe_post_url: Option, } impl Content { fn simple(subject: String, greeting: String, intro: String, button: &'static str, url: String, note: &str) -> Self { Self { subject, preheader: None, greeting, intro, quote: None, points: None, button, url, note: note.to_owned(), reason: None, unsubscribe: None, unsubscribe_post_url: None, } } } pub fn render(template: &str, locale: &str, payload: &Value) -> Result { let lang = if locale.eq_ignore_ascii_case("hu") { Lang::Hu } else { Lang::En }; let url = field(payload, "url")?; let greeting = |name: Option| match (lang, name) { (Lang::Hu, Some(n)) => format!("Szia {n}!"), (Lang::Hu, None) => "Szia!".to_owned(), (Lang::En, Some(n)) => format!("Hi {n},"), (Lang::En, None) => "Hi,".to_owned(), }; let content = match (template, lang) { ("verify_email", Lang::Hu) => Content::simple( "Erősítsd meg az e-mail-címed".into(), greeting(name(payload, "display_name")), "Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal erősítsd meg az e-mail-címed.".into(), "E-mail-cím megerősítése", url, "A link 3 napig érvényes. Ha nem te regisztráltál, nyugodtan hagyd figyelmen kívül ezt a levelet.", ), ("verify_email", Lang::En) => Content::simple( "Confirm your e-mail address".into(), greeting(name(payload, "display_name")), "Thanks for signing up for Sorsfonalak! Please confirm your e-mail address with the button below.".into(), "Confirm e-mail address", url, "The link is valid for 3 days. If you did not sign up, you can safely ignore this e-mail.", ), ("reset_password", Lang::Hu) => Content::simple( "Új jelszó megadása".into(), greeting(name(payload, "display_name")), "Jelszó-visszaállítást kértél a Sorsfonalak-fiókodhoz. Az alábbi gombbal adhatsz meg új jelszót.".into(), "Új jelszó megadása", url, "A link 1 óráig érvényes, és csak egyszer használható. Ha nem te kérted, hagyd figyelmen kívül ezt a levelet: a jelszavad nem változik.", ), ("reset_password", Lang::En) => Content::simple( "Set a new password".into(), greeting(name(payload, "display_name")), "You asked to reset the password of your Sorsfonalak account. Use the button below to set a new one." .into(), "Set a new password", url, "The link is valid for 1 hour and can be used once. If you did not ask for this, ignore this e-mail: your password stays the same.", ), ("invite_accepted", Lang::Hu) => { let who = name(payload, "invitee_name"); Content::simple( match &who { Some(n) => format!("{n} elfogadta a meghívásod"), None => "Elfogadták a meghívásod".into(), }, greeting(None), format!( "{} elfogadta a „Mennyire illünk össze?” meghívásod, és elkészült a szinasztriátok.", who.as_deref().unwrap_or("A meghívott") ), "Szinasztria megnyitása", url, "A szinasztriát mindketten látjátok, de egymás születési adatait nem.", ) } ("invite_accepted", Lang::En) => { let who = name(payload, "invitee_name"); Content::simple( match &who { Some(n) => format!("{n} accepted your invitation"), None => "Your invitation was accepted".into(), }, greeting(None), format!( "{} accepted your “How compatible are we?” invitation, and your synastry is ready.", who.as_deref().unwrap_or("Your invitee") ), "Open synastry", url, "You both see the synastry, but not each other's birth data.", ) } ("invitation", _) => invitation(lang, payload, url)?, _ => return Err(TemplateError::UnknownTemplate(template.to_owned())), }; Ok(content.render(lang)) } /// An invitation to the closed site (sent by an administrator). fn invitation(lang: Lang, payload: &Value, url: String) -> Result { let inviter = name(payload, "inviter_name"); let message = message(payload); let until = payload["expires_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("expires_on"))?; // "2026. december 17." + "-ig" = "2026. december 17-ig" let until_hu = until.trim_end_matches('.'); let unsubscribe_url = field(payload, "unsubscribe_url")?; let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?; Ok(match lang { Lang::Hu => Content { subject: match &inviter { Some(n) => format!("{n} meghívott a Sorsfonalakra"), None => "Meghívót kaptál a Sorsfonalakra".into(), }, preheader: Some(format!("Születési képlet és rövid elemzés ingyen. A meghívó {until_hu}-ig érvényes.")), greeting: "Szia!".into(), intro: match &inviter { Some(n) => { format!("{n} meghívott a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.") } None => { "Meghívót kaptál a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.".into() } }, quote: message, points: Some(( "Mit találsz ott?", vec![ "a születési képleted kiszámolva és megrajzolva, ingyen,", "egy rövid, személyre szóló elemzést róla,", "összevetést a szeretteiddel: mennyire illetek össze.", ], )), button: "Meghívás elfogadása", url, note: format!( "A meghívó {until_hu}-ig érvényes. Elfogadáskor Google-fiókkal lépsz be, és ezzel a linkkel bármelyik Google-fiókodat használhatod." ), reason: Some(match &inviter { Some(n) => { format!("Ezt a levelet azért kaptad, mert {n} megadta az e-mail-címed a Sorsfonalak meghívójában.") } None => { "Ezt a levelet azért kaptad, mert valaki megadta az e-mail-címed a Sorsfonalak meghívójában.".into() } }), unsubscribe: Some(("Nem kérek több meghívót", unsubscribe_url)), unsubscribe_post_url: Some(unsubscribe_post_url), }, Lang::En => Content { subject: match &inviter { Some(n) => format!("{n} invited you to Sorsfonalak"), None => "You are invited to Sorsfonalak".into(), }, preheader: Some(format!( "Your birth chart and a short reading, free. The invitation is valid until {until}." )), greeting: "Hi,".into(), intro: match &inviter { Some(n) => format!("{n} invited you to Sorsfonalak. The site is invitation-only for now."), None => "You are invited to Sorsfonalak. The site is invitation-only for now.".into(), }, quote: message, points: Some(( "What you will find there:", vec![ "your birth chart, calculated and drawn, for free,", "a short, personal reading of it,", "comparisons with your loved ones: how well you match.", ], )), button: "Accept the invitation", url, note: format!( "The invitation is valid until {until}. You sign in with Google, and with this link any of your Google accounts will do." ), reason: Some(match &inviter { Some(n) => format!("You got this e-mail because {n} entered your address in a Sorsfonalak invitation."), None => "You got this e-mail because someone entered your address in a Sorsfonalak invitation.".into(), }), unsubscribe: Some(("No more invitations, please", unsubscribe_url)), unsubscribe_post_url: Some(unsubscribe_post_url), }, }) } fn field(payload: &Value, name: &'static str) -> Result { payload[name].as_str().filter(|u| !u.is_empty()).map(str::to_owned).ok_or(TemplateError::MissingField(name)) } /// A user-supplied name, safe for a subject line. fn name(payload: &Value, field: &str) -> Option { let name: String = payload[field].as_str()?.chars().filter(|c| !c.is_control()).take(60).collect(); let name = name.trim(); (!name.is_empty()).then(|| name.to_owned()) } /// The personal message of an invitation: line breaks kept, other control characters dropped. fn message(payload: &Value) -> Option { let text: String = payload["message"].as_str()?.chars().filter(|c| *c == '\n' || !c.is_control()).take(500).collect(); let text = text.trim(); (!text.is_empty()).then(|| text.to_owned()) } /// `2026-12-17` as "2026. december 17." or "17 December 2026". fn date(lang: Lang, iso: &str) -> Option { const HU: [&str; 12] = [ "január", "február", "március", "április", "május", "június", "július", "augusztus", "szeptember", "október", "november", "december", ]; const EN: [&str; 12] = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; let mut parts = iso.splitn(3, '-'); let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?); let (y, m, d): (u32, usize, u32) = (y.parse().ok()?, m.parse().ok()?, d.get(..2)?.parse().ok()?); let month = m.checked_sub(1).filter(|&i| i < 12)?; Some(match lang { Lang::Hu => format!("{y}. {} {d}.", HU[month]), Lang::En => format!("{d} {} {y}", EN[month]), }) } fn escape(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), _ => out.push(c), } } out } const TEXT: &str = "#2a2620"; const MUTED: &str = "#6b645a"; const FAINT: &str = "#9b948a"; const GOLD: &str = "#9a7b3c"; impl Content { fn render(self, lang: Lang) -> Rendered { let footer = match lang { Lang::Hu => "Ezt a levelet a Sorsfonalak küldte.", Lang::En => "This e-mail was sent by Sorsfonalak.", }; let mut text = format!("{}\n\n{}\n\n", self.greeting, self.intro); if let Some(q) = &self.quote { for line in q.lines() { text.push_str(&format!("> {line}\n")); } text.push('\n'); } if let Some((heading, items)) = &self.points { text.push_str(heading); text.push('\n'); for item in items { text.push_str(&format!("- {item}\n")); } text.push('\n'); } text.push_str(&format!("{}:\n{}\n\n{}\n\n-- \nSorsfonalak\n", self.button, self.url, self.note)); if let Some(reason) = &self.reason { text.push_str(&format!("\n{reason}\n")); } if let Some((label, url)) = &self.unsubscribe { text.push_str(&format!("{label}: {url}\n")); } let preheader = self.preheader.as_deref().map_or(String::new(), |p| { format!( r#"
{}
"#, escape(p) ) }); let quote = self.quote.as_deref().map_or(String::new(), |q| { format!( r#"
{}
"#, escape(q).replace('\n', "
") ) }); let points = self.points.as_ref().map_or(String::new(), |(heading, items)| { let items: String = items .iter() .map(|i| format!(r#"
  • {}
  • "#, escape(i))) .collect(); format!( r#"{}
      {items}
    "#, escape(heading) ) }); let mut small = Vec::new(); if let Some(reason) = &self.reason { small.push(escape(reason)); } if let Some((label, url)) = &self.unsubscribe { small.push(format!(r#"{}"#, escape(url), escape(label))); } small.push(escape(footer)); let small = small.join("
    "); let html = format!( r#" {subject} {preheader}
    {quote}{points}
    SORSFONALAK
    {greeting}
    {intro}
    {button}
    {note}
    {url_text}

    {small}

    "#, lang = if lang == Lang::Hu { "hu" } else { "en" }, subject = escape(&self.subject), greeting = escape(&self.greeting), intro = escape(&self.intro), url = escape(&self.url), button = escape(self.button), note = escape(&self.note), url_text = escape(&self.url), ); Rendered { subject: self.subject, text, html, unsubscribe_post_url: self.unsubscribe_post_url } } } #[cfg(test)] mod tests { use serde_json::json; use super::*; fn invitation_payload() -> Value { json!({ "url": "https://sorsfonalak.test/meghivo/abc", "inviter_name": "Kata", "message": "Gyere, nézd meg!\nSzia", "expires_on": "2026-12-17", "unsubscribe_url": "https://sorsfonalak.test/leiratkozas?token=abc", "unsubscribe_post_url": "https://sorsfonalak.test/api/v1/public/invitations/unsubscribe?token=abc", }) } #[test] fn invitation_has_both_parts() { let hu = render("invitation", "hu", &invitation_payload()).unwrap(); assert_eq!(hu.subject, "Kata meghívott a Sorsfonalakra"); assert!(hu.text.contains("> Gyere, nézd meg!\n> Szia")); assert!(hu.text.contains("A meghívó 2026. december 17-ig érvényes.")); assert!(hu.text.contains("Nem kérek több meghívót: https://sorsfonalak.test/leiratkozas?token=abc")); assert!(hu.html.contains("Gyere, nézd meg!
    <b>Szia</b>")); assert!(hu.html.contains(r#"href="https://sorsfonalak.test/meghivo/abc""#)); assert!(hu.html.contains("display:none")); assert_eq!( hu.unsubscribe_post_url.as_deref(), Some("https://sorsfonalak.test/api/v1/public/invitations/unsubscribe?token=abc") ); let mut anonymous = invitation_payload(); anonymous["inviter_name"] = Value::Null; anonymous["message"] = Value::Null; let en = render("invitation", "en", &anonymous).unwrap(); assert_eq!(en.subject, "You are invited to Sorsfonalak"); assert!(en.text.contains("valid until 17 December 2026") && !en.text.contains("> ")); assert!(!en.html.contains("border-left")); let mut broken = invitation_payload(); broken["unsubscribe_url"] = Value::Null; assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url"))); } #[test] fn dates() { assert_eq!(date(Lang::Hu, "2027-01-05").as_deref(), Some("2027. január 5.")); assert_eq!(date(Lang::En, "2027-01-05T10:00:00Z").as_deref(), Some("5 January 2027")); assert_eq!(date(Lang::Hu, "2027-13-05"), None); } }