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
+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"}));
}