Forum: e-mail notifications with a daily digest
Members choose per kind: replies to them (daily digest, instant or off), new posts in followed threads (daily or off), private messages and requests (instant or off). The forum service queues the instant e-mails (none while online, at most one per thread an hour); the worker's new forum task makes the evening digest of what is unread. Every forum e-mail greets by the nickname and has a one-click unsubscribe (RFC 8058). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -50,7 +50,7 @@ struct Content {
|
||||
/// A personal message, shown as a quote.
|
||||
quote: Option<String>,
|
||||
/// A short list after the intro, with its heading.
|
||||
points: Option<(&'static str, Vec<&'static str>)>,
|
||||
points: Option<(&'static str, Vec<String>)>,
|
||||
/// A code to type in, shown large in a box, with its label.
|
||||
code: Option<(&'static str, String)>,
|
||||
button: &'static str,
|
||||
@@ -182,6 +182,10 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
||||
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
||||
("gift", _) => gift(lang, payload, url)?,
|
||||
("gift_package", _) => gift_package(lang, payload, url)?,
|
||||
// The forum is Hungarian only.
|
||||
("forum_reply", _) => forum_reply(payload, url)?,
|
||||
("forum_digest", _) => forum_digest(payload, url)?,
|
||||
("forum_message", _) => forum_message(payload, url)?,
|
||||
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
|
||||
};
|
||||
Ok(content.render(lang))
|
||||
@@ -240,7 +244,10 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
|
||||
"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.",
|
||||
],
|
||||
]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
)),
|
||||
button: "Meghívás elfogadása",
|
||||
url,
|
||||
@@ -279,7 +286,10 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
|
||||
"your birth chart, calculated and drawn, for free,",
|
||||
"a short, personal reading of it,",
|
||||
"comparisons with your loved ones: how well you match.",
|
||||
],
|
||||
]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
)),
|
||||
button: "Accept the invitation",
|
||||
url,
|
||||
@@ -297,6 +307,124 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
|
||||
})
|
||||
}
|
||||
|
||||
/// The forum e-mails' common footer: why it came, where to change it, and the
|
||||
/// one-click unsubscribe of every forum e-mail.
|
||||
fn forum_footer(payload: &Value, mut content: Content, why: &str) -> Result<Content, TemplateError> {
|
||||
content.reason =
|
||||
Some(format!("Azért kapod ezt a levelet, mert {why}. Az értesítéseket a fórumprofilodnál állíthatod be."));
|
||||
content.unsubscribe = Some(("Leiratkozás a fórum összes leveléről", field(payload, "unsubscribe_url")?));
|
||||
content.unsubscribe_post_url = Some(field(payload, "unsubscribe_post_url")?);
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// "Szia Csendesvíz!": the forum greets by the nickname, never the real name.
|
||||
fn hello(payload: &Value) -> String {
|
||||
name(payload, "nickname").map_or_else(|| "Szia!".to_owned(), |n| format!("Szia {n}!"))
|
||||
}
|
||||
|
||||
/// A short excerpt of a member's text for a quote (never the whole post).
|
||||
fn excerpt(payload: &Value, key: &str, max: usize) -> Option<String> {
|
||||
let text: String = payload[key].as_str()?.chars().filter(|c| !c.is_control() || *c == '\n').collect();
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(if text.chars().count() > max {
|
||||
format!("{}…", text.chars().take(max).collect::<String>().trim_end())
|
||||
} else {
|
||||
text.to_owned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Someone answered the member: in their thread or to their post.
|
||||
fn forum_reply(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let author = name(payload, "author").unwrap_or_else(|| "Valaki".into());
|
||||
let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?;
|
||||
let content = Content {
|
||||
subject: format!("{author} válaszolt: „{title}”"),
|
||||
preheader: excerpt(payload, "excerpt", 90),
|
||||
greeting: hello(payload),
|
||||
intro: format!("{author} válaszolt neked a Sorsfonalak fórumán, a(z) „{title}” szálban:"),
|
||||
quote: excerpt(payload, "excerpt", 300),
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Megnézem",
|
||||
url,
|
||||
note: "Ha nem kérsz azonnali levelet, a fórumprofilodnál napi összesítőre válthatsz, vagy kikapcsolhatod."
|
||||
.into(),
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
};
|
||||
forum_footer(payload, content, "a fórumon azonnali értesítést kértél a válaszokról")
|
||||
}
|
||||
|
||||
/// The daily digest: the threads with new posts for the member.
|
||||
fn forum_digest(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let lines: Vec<String> = payload["lines"]
|
||||
.as_array()
|
||||
.ok_or(TemplateError::MissingField("lines"))?
|
||||
.iter()
|
||||
.filter_map(|l| l.as_str())
|
||||
.map(|l| l.chars().filter(|c| !c.is_control()).take(160).collect())
|
||||
.collect();
|
||||
if lines.is_empty() {
|
||||
return Err(TemplateError::MissingField("lines"));
|
||||
}
|
||||
let total = payload["total"].as_i64().unwrap_or(lines.len() as i64);
|
||||
let content = Content {
|
||||
subject: format!("{total} új hozzászólás vár a fórumon"),
|
||||
preheader: lines.first().cloned(),
|
||||
greeting: hello(payload),
|
||||
intro: "Mióta utoljára írtunk, ezekben a szálakban jött új hozzászólás:".into(),
|
||||
quote: None,
|
||||
points: Some(("Szálak:", lines)),
|
||||
code: None,
|
||||
button: "Megnézem a fórumon",
|
||||
url,
|
||||
note: "Naponta legfeljebb egy ilyen levelet küldünk, és csak akkor, ha van újdonság.".into(),
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
};
|
||||
forum_footer(payload, content, "a fórumon napi összesítőt kértél")
|
||||
}
|
||||
|
||||
/// A private message, or a request to talk. The message itself is not in
|
||||
/// the e-mail; a request's short introduction is.
|
||||
fn forum_message(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let from = name(payload, "from").unwrap_or_else(|| "Valaki".into());
|
||||
let request = payload["kind"].as_str() == Some("request");
|
||||
let content = Content {
|
||||
subject: if request {
|
||||
format!("{from} beszélgetni szeretne veled")
|
||||
} else {
|
||||
format!("Új üzeneted jött: {from}")
|
||||
},
|
||||
preheader: None,
|
||||
greeting: hello(payload),
|
||||
intro: if request {
|
||||
format!("{from} beszélgetést kezdeményezett veled a Sorsfonalak fórumán. Ezt írta magáról:")
|
||||
} else {
|
||||
format!("{from} privát üzenetet küldött neked a Sorsfonalak fórumán.")
|
||||
},
|
||||
quote: if request { excerpt(payload, "excerpt", 200) } else { None },
|
||||
points: None,
|
||||
code: None,
|
||||
button: if request { "Megnézem a kérést" } else { "Elolvasom" },
|
||||
url,
|
||||
note: if request {
|
||||
"Elfogadhatod, csendben elutasíthatod (erről nem kap értesítést), vagy letilthatod.".into()
|
||||
} else {
|
||||
"Az üzenet szövegét nem tesszük bele a levélbe: a fórumon olvashatod.".into()
|
||||
},
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
};
|
||||
forum_footer(payload, content, "a fórumon értesítést kértél a privát üzenetekről")
|
||||
}
|
||||
|
||||
fn field(payload: &Value, name: &'static str) -> Result<String, TemplateError> {
|
||||
payload[name].as_str().filter(|u| !u.is_empty()).map(str::to_owned).ok_or(TemplateError::MissingField(name))
|
||||
}
|
||||
@@ -501,7 +629,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
|
||||
"kattints a gombra, és lépj be, vagy regisztrálj, ha még nincs fiókod;",
|
||||
"a kód már ki lesz töltve, csak a beváltásra kell kattintanod;",
|
||||
"utána a csomag a tiéd: elkészítheted a képleted és az elemzéseidet.",
|
||||
],
|
||||
].into_iter().map(String::from).collect(),
|
||||
)),
|
||||
button: "Ajándék beváltása",
|
||||
url,
|
||||
@@ -537,7 +665,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
|
||||
"click the button and log in, or sign up if you have no account yet;",
|
||||
"the code is filled in for you: just click Redeem;",
|
||||
"the package is yours: make your chart and your readings.",
|
||||
],
|
||||
].into_iter().map(String::from).collect(),
|
||||
)),
|
||||
button: "Redeem the gift",
|
||||
url,
|
||||
@@ -623,7 +751,7 @@ fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content,
|
||||
vec![
|
||||
"a születési képleted percre pontosan kiszámolva és megrajzolva, egy rövid elemzéssel,",
|
||||
"részletes elemzés, éves előrejelzés és kapcsolati összevetés azokkal, akiket szeretsz.",
|
||||
],
|
||||
].into_iter().map(String::from).collect(),
|
||||
)),
|
||||
button: "Körülnézek",
|
||||
url,
|
||||
@@ -645,7 +773,7 @@ fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content,
|
||||
vec![
|
||||
"your birth chart, calculated to the minute and drawn, with a short reading,",
|
||||
"detailed readings, a yearly forecast and comparisons with the people you love.",
|
||||
],
|
||||
].into_iter().map(String::from).collect(),
|
||||
)),
|
||||
button: "Take a look",
|
||||
url,
|
||||
@@ -685,7 +813,10 @@ fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result<Content,
|
||||
vec![
|
||||
"a saját születési képleted kiszámolva és megrajzolva, egy rövid elemzéssel, ingyen,",
|
||||
"a kettőtök összevetését: hol erős és hol kényes a kapcsolatotok.",
|
||||
],
|
||||
]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
)),
|
||||
button: "Megnézem",
|
||||
url,
|
||||
@@ -717,7 +848,10 @@ fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result<Content,
|
||||
vec![
|
||||
"your own birth chart, calculated and drawn, with a short reading, for free,",
|
||||
"the comparison of the two of you: where your relationship is strong and where it is delicate.",
|
||||
],
|
||||
]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
)),
|
||||
button: "Take a look",
|
||||
url,
|
||||
@@ -1000,7 +1134,11 @@ mod tests {
|
||||
assert!(hu.text.contains("Tartalma: 2 részletes képletelemzés, 3 kérdés."), "{}", hu.text);
|
||||
let units = json!({"url": "https://sorsfonalak.hu/csomagok", "gift": "2 kérdést"});
|
||||
let hu = render("gift", "hu", &units).unwrap();
|
||||
assert!(hu.text.contains("Szia!") && hu.text.contains("Ajándékba kaptad 2 kérdést,") && !hu.text.contains("Tartalma"));
|
||||
assert!(
|
||||
hu.text.contains("Szia!")
|
||||
&& hu.text.contains("Ajándékba kaptad 2 kérdést,")
|
||||
&& !hu.text.contains("Tartalma")
|
||||
);
|
||||
assert!(render("gift", "en", &payload).unwrap().subject.starts_with("A gift"));
|
||||
assert_eq!(render("gift", "hu", &json!({"url": "x"})), Err(TemplateError::MissingField("gift")));
|
||||
}
|
||||
@@ -1086,4 +1224,48 @@ mod tests {
|
||||
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);
|
||||
}
|
||||
|
||||
fn forum_links() -> serde_json::Value {
|
||||
json!({
|
||||
"url": "https://sorsfonalak.hu/forum/szal/12-szia",
|
||||
"nickname": "Csendesvíz",
|
||||
"unsubscribe_url": "https://sorsfonalak.hu/forum/leiratkozas?token=t",
|
||||
"unsubscribe_post_url": "https://sorsfonalak.hu/api/v1/forum/unsubscribe?token=t",
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forum_mails() {
|
||||
let mut p = forum_links();
|
||||
p["author"] = json!("Holdfény");
|
||||
p["thread_title"] = json!("Nem tudom elengedni");
|
||||
p["excerpt"] = json!("Nem vagy egyedül. ".repeat(40));
|
||||
let m = render("forum_reply", "hu", &p).unwrap();
|
||||
assert_eq!(m.subject, "Holdfény válaszolt: „Nem tudom elengedni”");
|
||||
assert!(m.text.starts_with("Szia Csendesvíz!"));
|
||||
assert!(m.text.contains("…"), "only an excerpt");
|
||||
assert!(m.html.contains("Leiratkozás a fórum összes leveléről"));
|
||||
assert_eq!(m.unsubscribe_post_url.as_deref(), Some("https://sorsfonalak.hu/api/v1/forum/unsubscribe?token=t"));
|
||||
|
||||
let mut p = forum_links();
|
||||
p["lines"] = json!(["„Téli levesek” – 2 új", "„Reggeli csend” – 1 új"]);
|
||||
p["total"] = json!(3);
|
||||
let m = render("forum_digest", "hu", &p).unwrap();
|
||||
assert_eq!(m.subject, "3 új hozzászólás vár a fórumon");
|
||||
assert!(m.text.contains("- „Téli levesek” – 2 új"));
|
||||
p["lines"] = json!([]);
|
||||
assert!(render("forum_digest", "hu", &p).is_err());
|
||||
|
||||
let mut p = forum_links();
|
||||
p["from"] = json!("Zöldág");
|
||||
p["kind"] = json!("message");
|
||||
p["excerpt"] = json!("titkos szöveg");
|
||||
let m = render("forum_message", "hu", &p).unwrap();
|
||||
assert_eq!(m.subject, "Új üzeneted jött: Zöldág");
|
||||
assert!(!m.text.contains("titkos"), "a message's text stays out of the e-mail");
|
||||
p["kind"] = json!("request");
|
||||
let m = render("forum_message", "hu", &p).unwrap();
|
||||
assert_eq!(m.subject, "Zöldág beszélgetni szeretne veled");
|
||||
assert!(m.text.contains("titkos"), "a request's introduction is shown");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user