Files
sorsfonalak/services/forum/src/mail.rs
T
fecoandClaude Opus 5.5 da42c92e71 ÁSZF: the forum chapter, and the moderation e-mails it promises
A new point 8 (the old 8–11 become 9–12): reading, writing and the
nickname, the house rules, posts (they stay as "Törölt tag" after an
account is deleted), private messages, ranks and limits, reports and
moderation under the DSA (receipt, decision notice, statement of reasons,
objection, point of contact; every decision is made by a person),
notifications. In force from 2026-11-26 (TERMS_UPDATED, TERMS_VERSION).

So that it holds: the member gets an e-mail with the reason when a
moderator removes their post or thread or bans them, and every reporter
gets the decision on their report, whatever their notification settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:08:13 +00:00

220 lines
7.9 KiB
Rust

//! 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
}
#[derive(sqlx::FromRow)]
struct Person {
email: String,
locale: String,
nickname: Option<String>,
}
/// A notice that has to reach the user whatever their notification settings
/// (a moderation step concerning them, the decision on their report).
pub async fn notify_user(state: &AppState, user: Uuid, template: &str, mut payload: Value) {
let person: Result<Option<Person>, sqlx::Error> = sqlx::query_as(
"SELECT u.email, u.locale, m.nickname FROM users u LEFT JOIN forum.members m ON m.user_id = u.id WHERE u.id = $1",
)
.bind(user)
.fetch_optional(&state.db)
.await;
let result = match person {
Ok(Some(p)) => {
payload["nickname"] = json!(p.nickname);
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(user)
.bind(&p.email)
.bind(template)
.bind(&p.locale)
.bind(payload)
.execute(&state.db)
.await
.map(|_| ())
}
Ok(None) => Ok(()),
Err(e) => Err(e),
};
if let Err(e) = result {
tracing::error!(error = %e, template, "queueing a moderation e-mail");
}
}
/// The forum rules, where the moderation e-mails point.
pub fn rules_url(state: &AppState) -> String {
format!("{}/aszf#forum", state.base_url)
}
/// "3 napos" or "12 órás": a ban's length for the e-mail.
pub fn ban_duration(hours: i64) -> String {
if hours % 24 == 0 { format!("{} napos", hours / 24) } else { format!("{hours} órás") }
}
/// Tells each reporter (once) how their report was decided.
pub async fn notify_reporters(state: &AppState, reporters: &[Option<Uuid>], outcome: &str) {
let mut seen: Vec<Uuid> = reporters.iter().flatten().copied().collect();
seen.sort_unstable();
seen.dedup();
for reporter in seen {
let payload = json!({ "url": format!("{}/forum", state.base_url), "outcome": outcome });
notify_user(state, reporter, "forum_report_result", payload).await;
}
}