diff --git a/crates/db/migrations/0040_forum_notifications.sql b/crates/db/migrations/0040_forum_notifications.sql new file mode 100644 index 0000000..1ecf8dd --- /dev/null +++ b/crates/db/migrations/0040_forum_notifications.sql @@ -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); diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index a5547b2..06f9500 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -50,7 +50,7 @@ struct Content { /// 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>)>, + points: Option<(&'static str, Vec)>, /// 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 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 Result Result Result { + 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 { + 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::().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 { + 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 { + let lines: Vec = 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 { + 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 { 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 Result Result Result Result Result 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"); + } } diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 21a67de..09679cd 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -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: diff --git a/docker-compose.yml b/docker-compose.yml index c42ae4a..ab302ff 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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 diff --git a/docs/kozosseg.md b/docs/kozosseg.md index e2d11cf..fa9a549 100644 --- a/docs/kozosseg.md +++ b/docs/kozosseg.md @@ -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. diff --git a/services/forum/src/auth.rs b/services/forum/src/auth.rs index 471a4ed..41917cb 100644 --- a/services/forum/src/auth.rs +++ b/services/forum/src/auth.rs @@ -35,10 +35,13 @@ pub struct Member { pub nickname_changed_at: OffsetDateTime, pub banned_until: Option, pub ban_reason: Option, + 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 { diff --git a/services/forum/src/mail.rs b/services/forum/src/mail.rs new file mode 100644 index 0000000..4e8e203 --- /dev/null +++ b/services/forum/src/mail.rs @@ -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, + 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, + body: &str, +) -> Result<(), sqlx::Error> { + let recipients: Vec = 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) = 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::(), + }); + 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 = 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 = 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 +} diff --git a/services/forum/src/main.rs b/services/forum/src/main.rs index c1f611c..cc7f083 100644 --- a/services/forum/src/main.rs +++ b/services/forum/src/main.rs @@ -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?; diff --git a/services/forum/src/routes/members.rs b/services/forum/src/routes/members.rs index 4797cdd..9111cad 100644 --- a/services/forum/src/routes/members.rs +++ b/services/forum/src/routes/members.rs @@ -48,6 +48,11 @@ pub async fn me(State(state): St, viewer: Viewer) -> ApiResult> { 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, #[serde(default)] invisible: Option, + /// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`. + #[serde(default)] + email: Option, +} + +#[derive(Deserialize)] +pub struct EmailSettings { + #[serde(default)] + replies: Option, + #[serde(default)] + followed: Option, + #[serde(default)] + messages: Option, +} + +fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult> { + 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, ApiError>, +) -> ApiResult> { + 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 diff --git a/services/forum/src/routes/messages.rs b/services/forum/src/routes/messages.rs index 86f5519..045ba38 100644 --- a/services/forum/src/routes/messages.rs +++ b/services/forum/src/routes/messages.rs @@ -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) })), diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs index d0c00d2..5a6a979 100644 --- a/services/forum/src/routes/mod.rs +++ b/services/forum/src/routes/mod.rs @@ -65,6 +65,7 @@ pub fn router(state: Arc) -> 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)) diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs index ce0dd90..19bfacd 100644 --- a/services/forum/src/routes/threads.rs +++ b/services/forum/src/routes/threads.rs @@ -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))) } diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index febc3b1..9f73b8d 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -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"})); +} diff --git a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx index 95c67a1..14bf173 100644 --- a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx +++ b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx @@ -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(member?.chart_share ?? "none"); const [invisible, setInvisible] = useState(member?.invisible ?? false); + const [email, setEmail] = useState( + member?.email ?? { replies: "daily", followed: "off", messages: "instant" }, + ); const [busy, setBusy] = useState(false); const [error, setError] = useState(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("/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 }) +
+ Értesítések e-mailben +
+ + + + + + +
+ + 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. + +
+ {member && (
Rangod diff --git a/services/frontend/src/app/forum/forum.css b/services/frontend/src/app/forum/forum.css index 24659a2..4b7f3c1 100644 --- a/services/frontend/src/app/forum/forum.css +++ b/services/frontend/src/app/forum/forum.css @@ -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; } diff --git a/services/frontend/src/app/forum/leiratkozas/ForumUnsubscribe.tsx b/services/frontend/src/app/forum/leiratkozas/ForumUnsubscribe.tsx new file mode 100644 index 0000000..d537d47 --- /dev/null +++ b/services/frontend/src/app/forum/leiratkozas/ForumUnsubscribe.tsx @@ -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(null); + if (!token) + return

Hiányzik a leiratkozó link vége. Nyisd meg újra a levélben lévő linket.

; + + 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 ( +

+ + Kész, a fórum nem küld több levelet. Ha meggondolod magad, a{" "} + fórumprofilodnál újra bekapcsolhatod. + +

+ ); + } + return ( + <> + {error && ( +

+ {error} +

+ )} + + + ); +} diff --git a/services/frontend/src/app/forum/leiratkozas/page.tsx b/services/frontend/src/app/forum/leiratkozas/page.tsx new file mode 100644 index 0000000..8b773d4 --- /dev/null +++ b/services/frontend/src/app/forum/leiratkozas/page.tsx @@ -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 ( +
+

Leiratkozás

+

+ 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. +

+ +
+ ); +} diff --git a/services/frontend/src/lib/forum.ts b/services/frontend/src/lib/forum.ts index 35296b5..a826845 100644 --- a/services/frontend/src/lib/forum.ts +++ b/services/frontend/src/lib/forum.ts @@ -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, Record | null> | null; } diff --git a/services/worker/src/config.rs b/services/worker/src/config.rs index 2dacdb1..0878384 100644 --- a/services/worker/src/config.rs +++ b/services/worker/src/config.rs @@ -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 { 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)" + ) } } } diff --git a/services/worker/src/forum_digest.rs b/services/worker/src/forum_digest.rs new file mode 100644 index 0000000..f77d180 --- /dev/null +++ b/services/worker/src/forum_digest.rs @@ -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 { + 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 { + 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 = 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 = + 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) { + 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 { + 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); + } +} diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 41e7082..6ba1e81 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -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"); diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs index 3583c32..f0bdf21 100644 --- a/services/worker/src/tests.rs +++ b/services/worker/src/tests.rs @@ -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());