Forum: daily sky thread, listeners, mentions, own avatars, restricted topics
- The worker opens a "Mai égbolt" thread every morning from the day's sky (no AI), pinned for the day. - Volunteer listeners (from the Kereső rank) get a badge, a count of the threads asking to be heard that still wait for a reply, and, if they ask, an e-mail after two hours of waiting. - "@Holdfény" names a member (nicknames with spaces too): they follow the thread, hear of it live and, if they asked, by e-mail; a search helps typing it. - From the Kereső rank a member may upload an own avatar: a small square JPEG without metadata in the object storage (now a shared crate with the backend), served by the forum; moderators can put the starter back. - The "Támogató" badge for buyers who switch it on. - The admin creates and edits topics; restricted ones are read by their approved members, who ask to join and moderators decide. - "Most itt vannak" on the front page; the weekly summary e-mail on Sunday evening for those who ask (off by default). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
//! 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.
|
||||
//! The `forum` task: the forum's scheduled work.
|
||||
//!
|
||||
//! * The 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.
|
||||
//! * The daily "Mai égbolt" thread (`forum_sky`).
|
||||
//! * Volunteer listeners: a thread asking to be heard that waited two hours
|
||||
//! without a reply is sent to those who asked for such e-mails.
|
||||
//! * The weekly summary, on Sunday evening, for those who asked for it.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -113,11 +118,179 @@ pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usi
|
||||
Ok(queued)
|
||||
}
|
||||
|
||||
pub async fn run(db: PgPool, base_url: String, stop: watch::Receiver<bool>) {
|
||||
/// A waiting thread is sent to the listeners after this long without a reply.
|
||||
const LISTENER_AFTER: &str = "2 hours";
|
||||
|
||||
/// Sends the listeners the threads that wait for a first reply; returns how
|
||||
/// many e-mails were queued. Each thread once; a listener at most one such
|
||||
/// e-mail in six hours.
|
||||
pub async fn listeners_once(db: &PgPool, base_url: &str) -> Result<usize, sqlx::Error> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let mut tx = db.begin().await?;
|
||||
let threads: Vec<(i64, String, Option<Uuid>)> = sqlx::query_as(&format!(
|
||||
"SELECT th.id, th.title, th.author_id FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \
|
||||
AND th.listeners_notified_at IS NULL AND tp.visibility <> 'restricted' \
|
||||
AND (th.intent = 'listen' OR tp.listening) \
|
||||
AND th.created_at < now() - interval '{LISTENER_AFTER}' AND th.created_at > now() - interval '3 days' \
|
||||
ORDER BY th.created_at LIMIT 20 FOR UPDATE OF th SKIP LOCKED"
|
||||
))
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let mut queued = 0;
|
||||
for (id, title, author) in threads {
|
||||
let listeners: Vec<(Uuid, String, String, String, String)> = sqlx::query_as(
|
||||
"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.listener AND m.email_listener = 'instant' AND m.user_id IS DISTINCT FROM $1 \
|
||||
AND (m.banned_until IS NULL OR m.banned_until < now()) \
|
||||
AND (m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes') \
|
||||
AND NOT EXISTS (SELECT 1 FROM email_outbox e WHERE e.user_id = m.user_id \
|
||||
AND e.template = 'forum_listener' AND e.created_at > now() - interval '6 hours')",
|
||||
)
|
||||
.bind(author)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let slug = thread_slug(&title);
|
||||
for (user, email, locale, nickname, token) in listeners {
|
||||
let payload = json!({
|
||||
"url": format!("{base}/forum/szal/{id}-{slug}#valasz"),
|
||||
"nickname": nickname,
|
||||
"thread_title": title,
|
||||
"unsubscribe_url": format!("{base}/forum/leiratkozas?token={token}"),
|
||||
"unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={token}"),
|
||||
});
|
||||
queue(&mut tx, user, &email, &locale, "forum_listener", payload).await?;
|
||||
queued += 1;
|
||||
}
|
||||
sqlx::query("UPDATE forum.threads SET listeners_notified_at = now() WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(queued)
|
||||
}
|
||||
|
||||
/// Sunday evening: the week's busiest threads and those still waiting, to the
|
||||
/// members who asked for it; returns how many e-mails were queued.
|
||||
pub async fn weekly_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usize, sqlx::Error> {
|
||||
if !any_time {
|
||||
let (dow, hour): (i32, i32) = sqlx::query_as(
|
||||
"SELECT extract(dow FROM now() AT TIME ZONE 'Europe/Budapest')::int, \
|
||||
extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int",
|
||||
)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if dow != 0 || !(18..22).contains(&hour) {
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let busy: Vec<(i64, String, i64)> = sqlx::query_as(
|
||||
"SELECT th.id, th.title, count(p.id) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
JOIN forum.posts p ON p.thread_id = th.id AND p.deleted_at IS NULL AND p.created_at > now() - interval '7 days' \
|
||||
WHERE th.deleted_at IS NULL AND tp.visibility <> 'restricted' \
|
||||
GROUP BY th.id, th.title ORDER BY count(p.id) DESC, max(p.id) DESC LIMIT 5",
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let waiting: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT th.title FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE th.reply_count = 0 AND th.deleted_at IS NULL AND NOT th.locked AND NOT th.system \
|
||||
AND tp.visibility <> 'restricted' AND th.created_at > now() - interval '7 days' \
|
||||
ORDER BY th.created_at LIMIT 3",
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let busy: Vec<String> = busy.iter().map(|(_, title, n)| format!("„{title}” – {n} hozzászólás")).collect();
|
||||
let waiting: Vec<String> = waiting.iter().map(|t| format!("„{t}”")).collect();
|
||||
let mut tx = db.begin().await?;
|
||||
let due: Vec<(Uuid, String, String, String, String)> = sqlx::query_as(
|
||||
"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_weekly AND (m.weekly_sent_at IS NULL OR m.weekly_sent_at < now() - interval '6 days') \
|
||||
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 (user, email, locale, nickname, token) in due {
|
||||
if !busy.is_empty() || !waiting.is_empty() {
|
||||
let payload = json!({
|
||||
"url": format!("{base}/forum"),
|
||||
"nickname": nickname,
|
||||
"busy": busy,
|
||||
"waiting": waiting,
|
||||
"unsubscribe_url": format!("{base}/forum/leiratkozas?token={token}"),
|
||||
"unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={token}"),
|
||||
});
|
||||
queue(&mut tx, user, &email, &locale, "forum_weekly", payload).await?;
|
||||
queued += 1;
|
||||
}
|
||||
sqlx::query("UPDATE forum.members SET weekly_sent_at = now() WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(queued)
|
||||
}
|
||||
|
||||
async fn queue(
|
||||
tx: &mut sqlx::PgConnection,
|
||||
user: Uuid,
|
||||
email: &str,
|
||||
locale: &str,
|
||||
template: &str,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
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(email)
|
||||
.bind(template)
|
||||
.bind(locale)
|
||||
.bind(payload)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The readable part of a thread's address (the forum service's `text::slug`).
|
||||
fn thread_slug(title: &str) -> String {
|
||||
let ascii = deunicode::deunicode(title).to_lowercase();
|
||||
let mut slug = String::new();
|
||||
for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) {
|
||||
if !slug.is_empty() && slug.len() + 1 + word.len() > 60 {
|
||||
break;
|
||||
}
|
||||
if !slug.is_empty() {
|
||||
slug.push('-');
|
||||
}
|
||||
slug.push_str(word);
|
||||
}
|
||||
slug
|
||||
}
|
||||
|
||||
pub async fn run(db: PgPool, base_url: String, backend_url: String, stop: watch::Receiver<bool>) {
|
||||
let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build().expect("static configuration");
|
||||
loop {
|
||||
if let Err(e) = run_once(&db, &base_url, false).await {
|
||||
tracing::error!(error = %e, "forum digests");
|
||||
}
|
||||
if let Err(e) = crate::forum_sky::run_once(&db, &http, &backend_url, false).await {
|
||||
tracing::error!(error = %e, "daily sky thread");
|
||||
}
|
||||
if let Err(e) = listeners_once(&db, &base_url).await {
|
||||
tracing::error!(error = %e, "forum listener e-mails");
|
||||
}
|
||||
if let Err(e) = weekly_once(&db, &base_url, false).await {
|
||||
tracing::error!(error = %e, "forum weekly summary");
|
||||
}
|
||||
tokio::select! {
|
||||
() = tokio::time::sleep(Duration::from_secs(10 * 60)) => {}
|
||||
() = crate::stopped(stop.clone()) => break,
|
||||
@@ -210,3 +383,115 @@ mod tests {
|
||||
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod more_tests {
|
||||
use axum::Json;
|
||||
use axum::routing::get;
|
||||
|
||||
use super::*;
|
||||
|
||||
async fn user(db: &PgPool, email: &str, nickname: &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) VALUES ($1, $2, lower($2), 'hold-ejkek')")
|
||||
.bind(id)
|
||||
.bind(nickname)
|
||||
.execute(db)
|
||||
.await
|
||||
.unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn listeners_hear_of_a_waiting_thread_once(pool: PgPool) {
|
||||
let anna = user(&pool, "anna@example.com", "Anna").await;
|
||||
let bea = user(&pool, "bea@example.com", "Bea").await;
|
||||
let cili = user(&pool, "cili@example.com", "Cili").await;
|
||||
sqlx::query("UPDATE forum.members SET listener = true, email_listener = 'instant' WHERE user_id IN ($1, $2)")
|
||||
.bind(bea)
|
||||
.bind(cili)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
// Anna asks to be heard; three hours, no reply. Another thread is fresh.
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title, intent, created_at) VALUES \
|
||||
(2, $1, 'Nehéz napok', 'listen', now() - interval '3 hours'), (2, $1, 'Friss', 'listen', now())",
|
||||
)
|
||||
.bind(anna)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(listeners_once(&pool, "https://sorsfonalak.hu").await.unwrap(), 2);
|
||||
assert_eq!(listeners_once(&pool, "https://sorsfonalak.hu").await.unwrap(), 0, "once per thread");
|
||||
let to: Vec<String> =
|
||||
sqlx::query_scalar("SELECT to_email FROM email_outbox WHERE template = 'forum_listener' ORDER BY to_email")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(to, vec!["bea@example.com", "cili@example.com"]);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn the_weekly_summary_only_for_those_who_asked(pool: PgPool) {
|
||||
let anna = user(&pool, "anna@example.com", "Anna").await;
|
||||
user(&pool, "bea@example.com", "Bea").await;
|
||||
sqlx::query("UPDATE forum.members SET email_weekly = true WHERE user_id = $1")
|
||||
.bind(anna)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let thread: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES (4, $1, 'Téli levesek') RETURNING id",
|
||||
)
|
||||
.bind(anna)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'x')")
|
||||
.bind(thread)
|
||||
.bind(anna)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(weekly_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 1);
|
||||
assert_eq!(weekly_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0, "once a week");
|
||||
let payload: serde_json::Value =
|
||||
sqlx::query_scalar("SELECT payload FROM email_outbox WHERE template = 'forum_weekly'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(payload["busy"][0], "„Téli levesek” – 1 hozzászólás");
|
||||
assert!(email_templates::render("forum_weekly", "hu", &payload).is_ok());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn the_daily_sky_thread_is_opened_once(pool: PgPool) {
|
||||
async fn sky() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({
|
||||
"local_time": "2026-11-27T06:10",
|
||||
"moon": {"position": {"sign": "cancer"}, "phase": "waning_gibbous", "illumination": 0.9,
|
||||
"sign_change": null, "next_phases": []},
|
||||
"planets": []
|
||||
}))
|
||||
}
|
||||
let app = axum::Router::new().route("/v1/public/sky", get(sky));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let http = reqwest::Client::new();
|
||||
let url = format!("http://{addr}");
|
||||
assert!(crate::forum_sky::run_once(&pool, &http, &url, true).await.unwrap());
|
||||
assert!(!crate::forum_sky::run_once(&pool, &http, &url, true).await.unwrap(), "one a day");
|
||||
let (title, system, pinned, body): (String, bool, bool, String) = sqlx::query_as(
|
||||
"SELECT th.title, th.system, th.pinned, p.body FROM forum.threads th \
|
||||
JOIN forum.posts p ON p.thread_id = th.id AND p.is_opening",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(title.starts_with("Mai égbolt · ") && system && pinned);
|
||||
assert!(body.starts_with("A Hold ma a Rákban jár."));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user