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:
feco
2026-11-26 10:59:29 +00:00
co-authored by Claude Opus 5.5
parent 4def9569b1
commit 7c768fccff
22 changed files with 938 additions and 27 deletions
@@ -0,0 +1,12 @@
-- Forum e-mail notifications (docs/kozosseg.md), each switched by the member:
-- replies to them (instant, a daily digest, or off), new posts in followed
-- threads (daily or off), private messages and requests (instant or off).
-- The token is the one-click unsubscribe link of these e-mails.
ALTER TABLE forum.members
ADD COLUMN email_replies text NOT NULL DEFAULT 'daily' CHECK (email_replies IN ('off', 'daily', 'instant')),
ADD COLUMN email_followed text NOT NULL DEFAULT 'off' CHECK (email_followed IN ('off', 'daily')),
ADD COLUMN email_messages text NOT NULL DEFAULT 'instant' CHECK (email_messages IN ('off', 'instant')),
-- When the last daily digest was made (the worker's forum task).
ADD COLUMN digest_sent_at timestamptz,
ADD COLUMN email_token text NOT NULL DEFAULT replace(gen_random_uuid()::text, '-', '');
CREATE UNIQUE INDEX members_email_token_key ON forum.members (email_token);
+192 -10
View File
@@ -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");
}
}
+4 -1
View File
@@ -134,7 +134,8 @@ services:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
WORKER_TASKS: email,cleanup,invoices,notify
# forum: the forum's daily e-mail digest.
WORKER_TASKS: email,cleanup,invoices,notify,forum
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-}
# SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md);
@@ -192,6 +193,8 @@ services:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-forum:${TAG:-latest}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
# The links in the forum's e-mails.
PUBLIC_BASE_URL: https://${DOMAIN}
LOG_DIR: /logs
depends_on:
postgres:
+2
View File
@@ -118,6 +118,8 @@ services:
- "8083:8083"
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD:-sorsfonalak-dev}@postgres:5432/sorsfonalak
# The links in the forum's e-mails.
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001}
depends_on:
postgres:
condition: service_healthy
+11 -2
View File
@@ -80,11 +80,20 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több
- A beszélgetésben szöveg és emoji mehet, olvasási visszaigazolás nincs. Az új üzeneteket 15 másodpercenként kérdezi le.
- Bármelyik fél letilthatja a másikat, és csak a letiltó oldhatja fel a tiltást.
- Az „Üzenetek” menüpont jelvénye mutatja az olvasatlan üzeneteket és a megválaszolatlan kéréseket. A profilon jelenik meg a „Beszélgetést kezdeményezek” gomb.
- **Adatbázis:** `crates/db/migrations/0039_forum_reports_messages.sql`.
- **E-mail értesítések:**
- A fórumprofilban három beállítás van:
- válasz neked (a száladban vagy a hozzászólásodra): napi összesítő (alapértelmezett), azonnal vagy kikapcsolva;
- új hozzászólás a követett szálakban: napi összesítő vagy kikapcsolva (alapértelmezett);
- privát üzenet és kérés: azonnal (alapértelmezett) vagy kikapcsolva.
- **Azonnali levél:** a fórumszolgáltatás teszi az `email_outbox`-ba. Nem megy levél annak, aki épp online, szálanként óránként legfeljebb egy, beszélgetésenként fél óránként legfeljebb egy. Az üzenet szövege nem kerül bele, a kérés bemutatkozása igen.
- **Napi összesítő:** a worker új `forum` feladata (élesben a `WORKER_TASKS`-ban). Este 18 és 22 óra között, magyar idő szerint, tagonként naponta legfeljebb egy levél, és csak az olvasatlanokról, ha van ilyen.
- **Megszólítás:** a levelek az álnéven szólítanak meg.
- **Leiratkozás:** minden levél alján egy kattintással lehet leiratkozni (a levélprogram leiratkozás gombjával is, RFC 8058), ez a fórum összes levelét kikapcsolja. Oldala: `/forum/leiratkozas`.
- **Adatbázis:** `0039_forum_reports_messages.sql` és `0040_forum_notifications.sql`.
### Ami még hátravan
- **E-mail értesítések:** a napi összesítő, az értesítési beállítások oldala és a hírlevél-kapcsoló.
- **Hírlevél:** az oldalnak még nincs hírlevele. Ha lesz, külön, kifejezett hozzájárulással, nem a fórum beállításai között.
- **ÁSZF kiegészítése a fórummal:** a DSA szerinti bejelentés, a kapcsolattartási pont és az indoklás rendje, plusz egy mondat az adatvédelmi tájékoztatóba, hogy a moderátor csak jelentett privát üzenetet lát.
- **WebSocket-csengő** a lekérdezés helyett.
- **Napi „Mai égbolt” szál:** a worker nyitná meg automatikusan.
+4 -1
View File
@@ -35,10 +35,13 @@ pub struct Member {
pub nickname_changed_at: OffsetDateTime,
pub banned_until: Option<OffsetDateTime>,
pub ban_reason: Option<String>,
pub email_replies: String,
pub email_followed: String,
pub email_messages: String,
}
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
created_at, nickname_changed_at, banned_until, ban_reason";
created_at, nickname_changed_at, banned_until, ban_reason, email_replies, email_followed, email_messages";
impl Member {
pub fn rank(&self, now: OffsetDateTime) -> Rank {
+157
View File
@@ -0,0 +1,157 @@
//! Instant forum e-mails (a reply to the member, a private message or a
//! request), queued in `email_outbox` for the worker to send. The daily
//! digest is the worker's own job (its `forum` task).
//!
//! Nobody gets an instant e-mail while online (they see the badge), and at
//! most one per thread an hour, one per conversation in half an hour. A
//! failure here is logged and never fails the post itself.
use serde_json::{Value, json};
use sqlx::PgPool;
use uuid::Uuid;
use crate::AppState;
use crate::text;
/// The one-click unsubscribe links of a member's forum e-mails.
fn unsubscribe_links(base: &str, token: &str) -> (String, String) {
(format!("{base}/forum/leiratkozas?token={token}"), format!("{base}/api/v1/forum/unsubscribe?token={token}"))
}
#[derive(sqlx::FromRow)]
struct Recipient {
user_id: Uuid,
email: String,
locale: String,
nickname: String,
email_token: String,
}
async fn queue(db: &PgPool, base: &str, to: &Recipient, template: &str, mut payload: Value) -> Result<(), sqlx::Error> {
let (unsubscribe_url, unsubscribe_post_url) = unsubscribe_links(base, &to.email_token);
payload["nickname"] = json!(to.nickname);
payload["unsubscribe_url"] = json!(unsubscribe_url);
payload["unsubscribe_post_url"] = json!(unsubscribe_post_url);
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
)
.bind(Uuid::now_v7())
.bind(to.user_id)
.bind(&to.email)
.bind(template)
.bind(&to.locale)
.bind(payload)
.execute(db)
.await?;
Ok(())
}
/// Not online now (the last request more than five minutes ago).
const OFFLINE: &str = "(m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes')";
/// A reply: to the thread's author and to the author of the post answered,
/// if they asked for instant e-mails.
pub async fn after_reply(
state: &AppState,
thread_id: i64,
post_id: i64,
replier: Uuid,
parent: Option<i64>,
body: &str,
) {
if let Err(e) = reply_mails(state, thread_id, post_id, replier, parent, body).await {
tracing::error!(error = %e, thread = thread_id, "queueing the reply e-mails");
}
}
async fn reply_mails(
state: &AppState,
thread_id: i64,
post_id: i64,
replier: Uuid,
parent: Option<i64>,
body: &str,
) -> Result<(), sqlx::Error> {
let recipients: Vec<Recipient> = sqlx::query_as(&format!(
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
FROM forum.members m JOIN users u ON u.id = m.user_id \
WHERE m.email_replies = 'instant' AND m.user_id <> $1 AND {OFFLINE} \
AND m.user_id IN (SELECT author_id FROM forum.threads WHERE id = $2 \
UNION SELECT author_id FROM forum.posts WHERE id = $3) \
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
WHERE e.user_id = m.user_id AND e.template = 'forum_reply' \
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
))
.bind(replier)
.bind(thread_id)
.bind(parent)
.fetch_all(&state.db)
.await?;
if recipients.is_empty() {
return Ok(());
}
let (title, author): (String, Option<String>) = sqlx::query_as(
"SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) \
FROM forum.threads th WHERE th.id = $1",
)
.bind(thread_id)
.bind(replier)
.fetch_one(&state.db)
.await?;
let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title));
for to in &recipients {
let payload = json!({
"url": url,
"author": author,
"thread_title": title,
"thread_id": thread_id.to_string(),
"excerpt": body.chars().take(300).collect::<String>(),
});
queue(&state.db, &state.base_url, to, "forum_reply", payload).await?;
}
Ok(())
}
/// A private message or a request: to the other member, if they asked for it.
pub async fn after_message(state: &AppState, conversation: i64, sender: Uuid, request: bool, intro: Option<&str>) {
if let Err(e) = message_mail(state, conversation, sender, request, intro).await {
tracing::error!(error = %e, conversation, "queueing the message e-mail");
}
}
async fn message_mail(
state: &AppState,
conversation: i64,
sender: Uuid,
request: bool,
intro: Option<&str>,
) -> Result<(), sqlx::Error> {
let to: Option<Recipient> = sqlx::query_as(&format!(
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \
FROM forum.conversations c \
JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $2 THEN c.user_b ELSE c.user_a END \
JOIN users u ON u.id = m.user_id \
WHERE c.id = $1 AND m.email_messages = 'instant' AND {OFFLINE} \
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
WHERE e.user_id = m.user_id AND e.template = 'forum_message' \
AND e.payload->>'conversation_id' = $1::text \
AND e.created_at > now() - interval '30 minutes')"
))
.bind(conversation)
.bind(sender)
.fetch_optional(&state.db)
.await?;
let Some(to) = to else { return Ok(()) };
let from: Option<String> = sqlx::query_scalar("SELECT nickname FROM forum.members WHERE user_id = $1")
.bind(sender)
.fetch_optional(&state.db)
.await?;
let payload = json!({
"url": format!("{}/forum/uzenetek/{conversation}", state.base_url),
"from": from,
"kind": if request { "request" } else { "message" },
"excerpt": intro,
"conversation_id": conversation.to_string(),
});
queue(&state.db, &state.base_url, &to, "forum_message", payload).await
}
+9 -4
View File
@@ -5,13 +5,15 @@
//! the database and the login: a session of the backend (`sf_session` cookie
//! or `Authorization: Bearer`) is valid here too.
//!
//! Configuration: `DATABASE_URL`; `BIND_ADDR` (default `0.0.0.0:8083`),
//! Configuration: `DATABASE_URL`, `PUBLIC_BASE_URL` (the site, for e-mail
//! links; default `http://localhost:3001`); `BIND_ADDR` (default `0.0.0.0:8083`),
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
//!
//! `forum healthcheck` performs a local health check (for Docker).
mod auth;
mod error;
mod mail;
mod rank;
mod routes;
#[cfg(test)]
@@ -29,11 +31,13 @@ pub struct AppState {
pub db: PgPool,
/// Seconds a member waits between two posts (0 in the tests).
pub flood_secs: i32,
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`).
pub base_url: String,
}
impl AppState {
pub fn new(db: PgPool) -> Self {
Self { db, flood_secs: 5 }
pub fn new(db: PgPool, base_url: String) -> Self {
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string() }
}
}
@@ -47,7 +51,8 @@ async fn main() -> anyhow::Result<()> {
let url = std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?;
let pool = db::connect(&url).await.context("connecting to the database")?;
db::migrate(&pool).await.context("running database migrations")?;
let app = routes::router(Arc::new(AppState::new(pool)));
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
let app = routes::router(Arc::new(AppState::new(pool, base_url)));
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "listening");
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
+65
View File
@@ -48,6 +48,11 @@ pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
}),
"ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)),
"email": {
"replies": m.email_replies,
"followed": m.email_followed,
"messages": m.email_messages,
},
})
});
let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id);
@@ -66,6 +71,27 @@ pub struct SaveMe {
chart_share: Option<String>,
#[serde(default)]
invisible: Option<bool>,
/// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`.
#[serde(default)]
email: Option<EmailSettings>,
}
#[derive(Deserialize)]
pub struct EmailSettings {
#[serde(default)]
replies: Option<String>,
#[serde(default)]
followed: Option<String>,
#[serde(default)]
messages: Option<String>,
}
fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult<Option<String>> {
match value {
None => Ok(None),
Some(v) if allowed.contains(&v) => Ok(Some(v.to_string())),
Some(_) => Err(ApiError::bad("Ismeretlen értesítési beállítás.")),
}
}
/// Whether someone else has (or recently had) this folded nickname.
@@ -101,6 +127,10 @@ pub async fn save_me(
Some(level @ ("none" | "sun" | "big3" | "planets")) => Some(level.to_string()),
Some(_) => return Err(ApiError::bad("Ismeretlen megosztási szint.")),
};
let email = req.email.as_ref();
let email_replies = one_of(email.and_then(|e| e.replies.as_deref()), &["off", "daily", "instant"])?;
let email_followed = one_of(email.and_then(|e| e.followed.as_deref()), &["off", "daily"])?;
let email_messages = one_of(email.and_then(|e| e.messages.as_deref()), &["off", "instant"])?;
if nickname_taken(&state.db, &key, user.id).await? {
return Err(taken());
}
@@ -175,6 +205,17 @@ pub async fn save_me(
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => return Err(taken()),
Err(e) => return Err(e.into()),
}
sqlx::query(
"UPDATE forum.members SET email_replies = COALESCE($2, email_replies), \
email_followed = COALESCE($3, email_followed), email_messages = COALESCE($4, email_messages) \
WHERE user_id = $1",
)
.bind(user.id)
.bind(email_replies)
.bind(email_followed)
.bind(email_messages)
.execute(&mut *tx)
.await?;
tx.commit().await?;
let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer };
me(State(state), viewer).await
@@ -202,6 +243,30 @@ pub async fn nickname_check(
Ok(Json(json!({ "ok": true, "nickname": nickname })))
}
#[derive(Deserialize)]
pub struct TokenQuery {
token: String,
}
/// One click from a forum e-mail (its footer link, or the mail client's
/// unsubscribe button, RFC 8058): every forum e-mail off, no login needed.
pub async fn unsubscribe(
State(state): St,
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let done = sqlx::query(
"UPDATE forum.members SET email_replies = 'off', email_followed = 'off', email_messages = 'off' \
WHERE email_token = $1",
)
.bind(q.token.trim())
.execute(&state.db)
.await?;
if done.rows_affected() == 0 {
return Err(ApiError::NotFound("token"));
}
Ok(Json(json!({ "unsubscribed": true })))
}
/// The page is open: keeps the online dot (the viewer extractor does the work).
pub async fn presence(_viewer: Viewer) -> StatusCode {
StatusCode::NO_CONTENT
+2
View File
@@ -224,6 +224,7 @@ pub async fn request(
}
};
tx.commit().await?;
crate::mail::after_message(&state, id, me.user_id, true, Some(&intro)).await;
Ok((StatusCode::CREATED, Json(json!({ "id": id }))))
}
@@ -461,6 +462,7 @@ pub async fn send(
.await?;
mark(&mut *tx, id, me, message_id).await?;
tx.commit().await?;
crate::mail::after_message(&state, id, me, false, None).await;
Ok((
StatusCode::CREATED,
Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })),
+1
View File
@@ -65,6 +65,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/me", get(members::me).put(members::save_me))
.route("/v1/forum/nickname-check", get(members::nickname_check))
.route("/v1/forum/presence", post(members::presence))
.route("/v1/forum/unsubscribe", post(members::unsubscribe))
.route("/v1/forum/members/{nickname}", get(members::profile))
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log))
+1
View File
@@ -420,6 +420,7 @@ pub async fn reply(
.await?;
after_post(&mut tx, member.user_id, id, post.id).await?;
tx.commit().await?;
crate::mail::after_reply(&state, id, post.id, member.user_id, post.parent_id, &body).await;
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
Ok((StatusCode::CREATED, Json(post)))
}
+112 -1
View File
@@ -30,7 +30,7 @@ struct User {
impl TestApp {
fn new(pool: PgPool) -> Self {
let state = AppState { db: pool.clone(), flood_secs: 0 };
let state = AppState { db: pool.clone(), flood_secs: 0, base_url: "https://sorsfonalak.test".into() };
Self { router: routes::router(Arc::new(state)), pool }
}
@@ -704,3 +704,114 @@ async fn private_messages_start_with_a_request(pool: PgPool) {
let (status, _) = app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await;
assert_eq!(status, StatusCode::NO_CONTENT);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn instant_mails_and_unsubscribe(pool: PgPool) {
let app = TestApp::new(pool);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
let me = app.get("/v1/forum/me", Some(&anna)).await;
assert_eq!(me["member"]["email"], json!({"replies": "daily", "followed": "off", "messages": "instant"}));
let (status, _) = app
.call(
"PUT",
"/v1/forum/me",
Some(&anna),
json!({ "nickname": "Csendesvíz", "email": { "replies": "instant" } }),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _) = app
.call(
"PUT",
"/v1/forum/me",
Some(&anna),
json!({ "nickname": "Csendesvíz", "email": { "followed": "instant" } }),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
let offline = |who: &str| {
let pool = app.pool.clone();
let who = who.to_string();
async move {
sqlx::query(
"UPDATE forum.members m SET last_seen_at = now() - interval '10 minutes' \
FROM users u WHERE u.id = m.user_id AND u.email = $1",
)
.bind(who)
.execute(&pool)
.await
.unwrap();
}
};
let mails = |template: &str| {
let pool = app.pool.clone();
let template = template.to_string();
async move {
sqlx::query_as::<_, (String, Value)>(
"SELECT to_email, payload FROM email_outbox WHERE template = $1 ORDER BY created_at",
)
.bind(template)
.fetch_all(&pool)
.await
.unwrap()
}
};
// Online: no e-mail (the badge is enough).
app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
assert!(mails("forum_reply").await.is_empty());
// Away: one e-mail, then no more for this thread within the hour.
offline("anna@example.com").await;
let post = app.reply(&bea, thread, "Négyig be, hatig ki :)", None).await;
app.reply(&cili, thread, "Gyertyát gyújtok.", None).await;
let sent = mails("forum_reply").await;
assert_eq!(sent.len(), 1);
assert_eq!(sent[0].0, "anna@example.com");
assert_eq!(sent[0].1["author"], "Holdfény");
assert_eq!(sent[0].1["nickname"], "Csendesvíz");
assert_eq!(sent[0].1["excerpt"], "Négyig be, hatig ki 🙂");
assert_eq!(sent[0].1["url"], format!("https://sorsfonalak.test/forum/szal/{thread}-reggeli-csend#h{}", post["id"]));
// Bea answered under her own post too, but asked only for the daily digest.
offline("bea@example.com").await;
app.reply(&cili, thread, "Szép gondolat.", post["id"].as_i64()).await;
assert!(mails("forum_reply").await.iter().all(|(to, _)| to != "bea@example.com"));
// A request to Bea (instant messages by default), while she is away.
app.season(&anna, 5, 10).await;
offline("bea@example.com").await;
let (status, _) = app
.call(
"POST",
"/v1/forum/conversations",
Some(&anna),
json!({ "to": "Holdfény", "intro": "Szia, beszélgetnénk?" }),
)
.await;
assert_eq!(status, StatusCode::CREATED);
let sent = mails("forum_message").await;
assert_eq!((sent.len(), sent[0].0.as_str()), (1, "bea@example.com"));
assert_eq!(sent[0].1["kind"], "request");
assert_eq!(sent[0].1["excerpt"], "Szia, beszélgetnénk?");
// One click turns every forum e-mail off.
let token: String = sqlx::query_scalar("SELECT email_token FROM forum.members WHERE user_id = $1")
.bind(anna.id)
.fetch_one(&app.pool)
.await
.unwrap();
assert!(
sent[0].1["unsubscribe_post_url"]
.as_str()
.unwrap()
.starts_with("https://sorsfonalak.test/api/v1/forum/unsubscribe?token=")
);
let (status, _) = app.call("POST", "/v1/forum/unsubscribe?token=nope", None, Value::Null).await;
assert_eq!(status, StatusCode::NOT_FOUND);
let (status, _) = app.call("POST", &format!("/v1/forum/unsubscribe?token={token}"), None, Value::Null).await;
assert_eq!(status, StatusCode::OK);
let me = app.get("/v1/forum/me", Some(&anna)).await;
assert_eq!(me["member"]["email"], json!({"replies": "off", "followed": "off", "messages": "off"}));
}
@@ -6,7 +6,7 @@ import { useEffect, useState } from "react";
import { AVATAR_COLOURS, AVATAR_GLYPHS, Avatar, GLYPH_NAMES } from "@/components/forum/Avatar";
import { signsText } from "@/components/forum/AuthorLine";
import { api, errorText } from "@/lib/api";
import { type ChartShare, type ForumMe, banText, memberHref } from "@/lib/forum";
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
{ value: "none", label: "Semmit" },
@@ -24,6 +24,9 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
const [bio, setBio] = useState(member?.bio ?? "");
const [share, setShare] = useState<ChartShare>(member?.chart_share ?? "none");
const [invisible, setInvisible] = useState(member?.invisible ?? false);
const [email, setEmail] = useState<EmailSettings>(
member?.email ?? { replies: "daily", followed: "off", messages: "instant" },
);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
@@ -51,7 +54,7 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
try {
const res = await api<ForumMe>("/forum/me", {
method: "PUT",
body: { nickname, avatar: avatar || null, bio, chart_share: share, invisible },
body: { nickname, avatar: avatar || null, bio, chart_share: share, invisible, email },
});
if (back) {
router.push(back);
@@ -179,6 +182,47 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
</span>
</label>
<fieldset className="fnew-set">
<legend>Értesítések e-mailben</legend>
<div className="fprof-mail">
<label htmlFor="fprof-mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
<select
id="fprof-mail-replies"
className="inp"
value={email.replies}
onChange={(e) => setEmail({ ...email, replies: e.target.value as EmailSettings["replies"] })}
>
<option value="daily">Napi összesítőben, este</option>
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
<option value="off">Ne küldjetek</option>
</select>
<label htmlFor="fprof-mail-followed">Új hozzászólás a követett szálaimban</label>
<select
id="fprof-mail-followed"
className="inp"
value={email.followed}
onChange={(e) => setEmail({ ...email, followed: e.target.value as EmailSettings["followed"] })}
>
<option value="off">Ne küldjetek</option>
<option value="daily">Napi összesítőben, este</option>
</select>
<label htmlFor="fprof-mail-messages">Privát üzenet vagy beszélgetési kérés</label>
<select
id="fprof-mail-messages"
className="inp"
value={email.messages}
onChange={(e) => setEmail({ ...email, messages: e.target.value as EmailSettings["messages"] })}
>
<option value="instant">Azonnal</option>
<option value="off">Ne küldjetek</option>
</select>
</div>
<span className="hint">
Ha éppen itt vagy a fórumon, nem küldünk levelet: a menü jelzi az újdonságot. A privát üzenetek szövege nem
kerül bele a levélbe.
</span>
</fieldset>
{member && (
<div className="fprof-rank">
<span className="eyebrow">Rangod</span>
@@ -498,3 +498,8 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
.fchat-msg .frep { width: min(420px, 86vw); }
.fchat-compose { display: flex; flex-direction: column; gap: 6px; padding-top: 12px; border-top: 1px solid var(--line); }
@media (min-width: 760px) { .forum-nav .fn-item { padding: 0 12px; } }
/* --- e-mail settings --- */
.fprof-mail { display: grid; gap: 6px; }
.fprof-mail label { font-size: 14px; font-weight: 500; margin-top: 8px; }
.fprof-mail label:first-child { margin-top: 0; }
@@ -0,0 +1,48 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
export function ForumUnsubscribe({ token }: { token: string | null }) {
const [state, setState] = useState<"idle" | "busy" | "done">("idle");
const [error, setError] = useState<string | null>(null);
if (!token)
return <p className="msg msg-error">Hiányzik a leiratkozó link vége. Nyisd meg újra a levélben lévő linket.</p>;
async function unsubscribe() {
setState("busy");
setError(null);
try {
await api(`/forum/unsubscribe?token=${encodeURIComponent(token ?? "")}`, { method: "POST" });
setState("done");
} catch (e) {
setError(errorText(e));
setState("idle");
}
}
if (state === "done") {
return (
<p className="fh-banner">
<span>
Kész, a fórum nem küld több levelet. Ha meggondolod magad, a{" "}
<Link href="/forum/beallitasok">fórumprofilodnál</Link> újra bekapcsolhatod.
</span>
</p>
);
}
return (
<>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<button type="button" className="btn btn-primary" disabled={state === "busy"} onClick={unsubscribe}>
{state === "busy" ? "Leiratkozás…" : "Leiratkozom a fórum leveleiről"}
</button>
</>
);
}
@@ -0,0 +1,20 @@
import { ForumUnsubscribe } from "./ForumUnsubscribe";
export const metadata = { title: "Leiratkozás a fórum leveleiről", robots: { index: false } };
type Props = { searchParams: Promise<{ token?: string | string[] }> };
/** From the footer of a forum e-mail: every forum e-mail off, no login needed. */
export default async function ForumUnsubscribePage({ searchParams }: Props) {
const raw = (await searchParams).token;
const token = Array.isArray(raw) ? raw[0] : raw;
return (
<div className="fh fprof">
<h1 className="fpage-title">Leiratkozás</h1>
<p className="muted">
Nem kérsz több levelet a fórumról: se válaszértesítést, se napi összesítőt, se üzenetértesítést.
</p>
<ForumUnsubscribe token={token ?? null} />
</div>
);
}
+7
View File
@@ -119,6 +119,12 @@ export interface ThreadPage {
};
}
export interface EmailSettings {
replies: "off" | "daily" | "instant";
followed: "off" | "daily";
messages: "off" | "instant";
}
export interface ForumMe {
viewer: ForumViewer;
member: {
@@ -136,6 +142,7 @@ export interface ForumMe {
nickname_change_after: string | null;
banned_until: string | null;
ban_reason: string | null;
email: EmailSettings;
} | null;
chart: Record<Exclude<ChartShare, "none">, Record<string, string> | null> | null;
}
+11 -4
View File
@@ -16,13 +16,17 @@ pub struct Tasks {
pub analyses: bool,
/// Issuing the invoices of the payments in Billingo.
pub invoices: bool,
/// Telegram notices about purchases.
/// Telegram notices about purchases and forum reports.
pub notify: bool,
/// The forum's daily e-mail digest.
pub forum: bool,
}
impl Tasks {
pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true };
const NONE: Tasks = Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false };
pub const ALL: Tasks =
Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true, forum: true };
const NONE: Tasks =
Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false, forum: false };
pub fn parse(raw: &str) -> anyhow::Result<Self> {
let mut tasks = Self::NONE;
@@ -33,8 +37,11 @@ impl Tasks {
"analyses" => tasks.analyses = true,
"invoices" => tasks.invoices = true,
"notify" => tasks.notify = true,
"forum" => tasks.forum = true,
other => {
anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify)")
anyhow::bail!(
"unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify, forum)"
)
}
}
}
+212
View File
@@ -0,0 +1,212 @@
//! The `forum` task: the forum's daily e-mail digest. In the evening
//! (18–22 h, Hungarian time) every member who asked for it gets one e-mail
//! listing the threads with posts they have not read yet: replies to them
//! (`email_replies = 'daily'`) and new posts in followed threads
//! (`email_followed = 'daily'`). Nothing new, no e-mail. The instant e-mails
//! are queued by the forum service itself.
use std::time::Duration;
use serde_json::json;
use sqlx::PgPool;
use tokio::sync::watch;
use uuid::Uuid;
/// Members handled in one round.
const BATCH: i64 = 200;
/// Threads listed in one digest.
const MAX_THREADS: i64 = 10;
#[derive(sqlx::FromRow)]
struct Due {
user_id: Uuid,
email: String,
locale: String,
nickname: String,
email_token: String,
replies: bool,
followed: bool,
since: time::OffsetDateTime,
}
/// The evening window, by Hungarian time.
async fn evening(db: &PgPool) -> Result<bool, sqlx::Error> {
let hour: i32 =
sqlx::query_scalar("SELECT extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int").fetch_one(db).await?;
Ok((18..22).contains(&hour))
}
/// Makes the digests that are due; returns how many e-mails were queued.
/// `any_time`: also outside the evening window (tests).
pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usize, sqlx::Error> {
if !any_time && !evening(db).await? {
return Ok(0);
}
let base = base_url.trim_end_matches('/');
let mut tx = db.begin().await?;
let due: Vec<Due> = sqlx::query_as(
"SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token, \
m.email_replies = 'daily' AS replies, m.email_followed = 'daily' AS followed, \
greatest(COALESCE(m.digest_sent_at, m.created_at), now() - interval '2 days') AS since \
FROM forum.members m JOIN users u ON u.id = m.user_id \
WHERE (m.email_replies = 'daily' OR m.email_followed = 'daily') \
AND (m.digest_sent_at IS NULL OR m.digest_sent_at < now() - interval '20 hours') \
ORDER BY m.user_id LIMIT $1 FOR UPDATE OF m SKIP LOCKED",
)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
let mut queued = 0;
for m in due {
let threads: Vec<(String, i64)> = sqlx::query_as(
"SELECT th.title, count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
AND p.created_at > $2 \
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
WHERE r.user_id = $1 AND r.thread_id = th.id), 0) \
AND (($3 AND (th.author_id = $1 \
OR p.parent_id IN (SELECT id FROM forum.posts WHERE author_id = $1))) \
OR ($4 AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1))) \
GROUP BY th.id, th.title ORDER BY max(p.id) DESC LIMIT $5",
)
.bind(m.user_id)
.bind(m.since)
.bind(m.replies)
.bind(m.followed)
.bind(MAX_THREADS)
.fetch_all(&mut *tx)
.await?;
if !threads.is_empty() {
let total: i64 = threads.iter().map(|(_, n)| n).sum();
let lines: Vec<String> =
threads.iter().map(|(title, n)| format!("„{title}” – {n} új hozzászólás")).collect();
let payload = json!({
"url": format!("{base}/forum/kovetett"),
"nickname": m.nickname,
"lines": lines,
"total": total,
"unsubscribe_url": format!("{base}/forum/leiratkozas?token={}", m.email_token),
"unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={}", m.email_token),
});
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \
VALUES ($1, $2, $3, 'forum_digest', $4, $5)",
)
.bind(Uuid::now_v7())
.bind(m.user_id)
.bind(&m.email)
.bind(&m.locale)
.bind(payload)
.execute(&mut *tx)
.await?;
queued += 1;
}
sqlx::query("UPDATE forum.members SET digest_sent_at = now() WHERE user_id = $1")
.bind(m.user_id)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
if queued > 0 {
tracing::info!(queued, "forum digests queued");
}
Ok(queued)
}
pub async fn run(db: PgPool, base_url: String, stop: watch::Receiver<bool>) {
loop {
if let Err(e) = run_once(&db, &base_url, false).await {
tracing::error!(error = %e, "forum digests");
}
tokio::select! {
() = tokio::time::sleep(Duration::from_secs(10 * 60)) => {}
() = crate::stopped(stop.clone()) => break,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn member(db: &PgPool, email: &str, nickname: &str, replies: &str, followed: &str) -> Uuid {
let id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email) VALUES ($1, $2)").bind(id).bind(email).execute(db).await.unwrap();
sqlx::query(
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, email_replies, email_followed, created_at) \
VALUES ($1, $2, lower($2), 'hold-ejkek', $3, $4, now() - interval '3 days')",
)
.bind(id)
.bind(nickname)
.bind(replies)
.bind(followed)
.execute(db)
.await
.unwrap();
id
}
async fn post(db: &PgPool, thread: i64, author: Uuid, parent: Option<i64>) -> i64 {
sqlx::query_scalar(
"INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, 'x') RETURNING id",
)
.bind(thread)
.bind(author)
.bind(parent)
.fetch_one(db)
.await
.unwrap()
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn one_digest_a_day_with_what_is_unread(pool: PgPool) {
let anna = member(&pool, "anna@example.com", "Anna", "daily", "off").await;
let bea = member(&pool, "bea@example.com", "Bea", "off", "daily").await;
let cili = member(&pool, "cili@example.com", "Cili", "instant", "off").await;
let thread: i64 = sqlx::query_scalar(
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES (2, $1, 'Reggeli csend') RETURNING id",
)
.bind(anna)
.fetch_one(&pool)
.await
.unwrap();
post(&pool, thread, anna, None).await;
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2), ($3, $2)")
.bind(anna)
.bind(thread)
.bind(bea)
.execute(&pool)
.await
.unwrap();
post(&pool, thread, cili, None).await;
post(&pool, thread, cili, None).await;
assert_eq!(run_once(&pool, "https://sorsfonalak.hu/", true).await.unwrap(), 2);
let mails: Vec<(String, serde_json::Value)> = sqlx::query_as(
"SELECT to_email, payload FROM email_outbox WHERE template = 'forum_digest' ORDER BY to_email",
)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(mails.len(), 2, "Cili asked for instant e-mails, not the digest");
assert_eq!(mails[0].0, "anna@example.com");
assert_eq!(mails[0].1["lines"][0], "„Reggeli csend” – 2 új hozzászólás");
assert_eq!(mails[0].1["url"], "https://sorsfonalak.hu/forum/kovetett");
assert!(email_templates::render("forum_digest", "hu", &mails[0].1).is_ok());
// Once a day only; and nothing unread, nothing sent.
post(&pool, thread, cili, None).await;
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
sqlx::query("UPDATE forum.members SET digest_sent_at = now() - interval '1 day'").execute(&pool).await.unwrap();
let last: i64 = sqlx::query_scalar("SELECT max(id) FROM forum.posts").fetch_one(&pool).await.unwrap();
sqlx::query("INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3), ($4, $2, $3)")
.bind(anna)
.bind(thread)
.bind(last)
.bind(bea)
.execute(&pool)
.await
.unwrap();
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
}
}
+11
View File
@@ -19,6 +19,7 @@ mod cleanup;
mod compare;
mod config;
mod email;
mod forum_digest;
mod invoices;
mod notify;
mod ses;
@@ -105,6 +106,7 @@ async fn main() -> anyhow::Result<()> {
analyses = tasks.analyses,
invoices = tasks.invoices,
notify = tasks.notify,
forum = tasks.forum,
"worker tasks"
);
match &config.smtp_url {
@@ -167,6 +169,15 @@ async fn main() -> anyhow::Result<()> {
_ => tracing::info!("TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is not set: no purchase notices"),
}
match &config.public_base_url {
_ if !tasks.forum => {}
Some(base) => {
tracing::info!("forum digests enabled");
jobs.spawn(forum_digest::run(pool.clone(), base.clone(), stop.clone()));
}
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum digests (their links need it)"),
}
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "worker running");
+6 -2
View File
@@ -288,11 +288,15 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
fn worker_tasks_are_chosen_by_name() {
use crate::config::Tasks;
let mail = Tasks::parse("email, cleanup").unwrap();
assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false });
assert_eq!(
mail,
Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false, forum: false }
);
assert_eq!(
Tasks::parse("analyses").unwrap(),
Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false }
Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false, forum: false }
);
assert!(Tasks::parse("email,forum").unwrap().forum);
assert!(Tasks::parse("email,invoices").unwrap().invoices);
assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify);
assert!(Tasks::parse("emails").is_err());