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:
@@ -13,6 +13,7 @@ email-templates.workspace = true
|
||||
gift-card.workspace = true
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
deunicode.workspace = true
|
||||
axum.workspace = true
|
||||
base64.workspace = true
|
||||
hmac.workspace = true
|
||||
|
||||
@@ -76,6 +76,9 @@ pub struct Config {
|
||||
pub openrouter_base_url: String,
|
||||
/// Frontend address, sent to OpenRouter as `HTTP-Referer`.
|
||||
pub public_base_url: Option<String>,
|
||||
/// The backend (`BACKEND_URL`, default `http://backend:8081`): the sky of
|
||||
/// the forum's daily thread.
|
||||
pub backend_url: String,
|
||||
/// Detailed analyses and forecasts written at the same time (0: none).
|
||||
pub analysis_concurrency: usize,
|
||||
/// Summaries and answers written at the same time (0: none).
|
||||
@@ -137,6 +140,7 @@ impl Config {
|
||||
openrouter_base_url: var("OPENROUTER_BASE_URL")
|
||||
.unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()),
|
||||
public_base_url: var("PUBLIC_BASE_URL"),
|
||||
backend_url: var("BACKEND_URL").unwrap_or_else(|| "http://backend:8081".into()),
|
||||
analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?,
|
||||
quick_concurrency: parsed("QUICK_CONCURRENCY", 2)?,
|
||||
max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?,
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! The forum's daily "Mai égbolt" thread: every morning the worker opens it
|
||||
//! in the "Égbolt és képletek" topic from the sky of the day (the backend's
|
||||
//! public sky: the Moon's sign and phase, a sign change, the retrograde
|
||||
//! planets, the next lunation). No AI: fixed Hungarian sentences. The new
|
||||
//! thread is pinned for the day; yesterday's is unpinned.
|
||||
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// The topic it goes to.
|
||||
const TOPIC: &str = "egbolt-es-kepletek";
|
||||
/// From this hour (Hungarian time) it is made, once a day.
|
||||
const FROM_HOUR: i32 = 5;
|
||||
|
||||
/// "a Rákban": the sign with the inessive ending.
|
||||
fn sign_in(sign: &str) -> &'static str {
|
||||
match sign {
|
||||
"aries" => "Kosban",
|
||||
"taurus" => "Bikában",
|
||||
"gemini" => "Ikrekben",
|
||||
"cancer" => "Rákban",
|
||||
"leo" => "Oroszlánban",
|
||||
"virgo" => "Szűzben",
|
||||
"libra" => "Mérlegben",
|
||||
"scorpio" => "Skorpióban",
|
||||
"sagittarius" => "Nyilasban",
|
||||
"capricorn" => "Bakban",
|
||||
"aquarius" => "Vízöntőben",
|
||||
_ => "Halakban",
|
||||
}
|
||||
}
|
||||
|
||||
/// "a Rákba": the sign with the illative ending.
|
||||
fn sign_into(sign: &str) -> &'static str {
|
||||
match sign {
|
||||
"aries" => "Kosba",
|
||||
"taurus" => "Bikába",
|
||||
"gemini" => "Ikrekbe",
|
||||
"cancer" => "Rákba",
|
||||
"leo" => "Oroszlánba",
|
||||
"virgo" => "Szűzbe",
|
||||
"libra" => "Mérlegbe",
|
||||
"scorpio" => "Skorpióba",
|
||||
"sagittarius" => "Nyilasba",
|
||||
"capricorn" => "Bakba",
|
||||
"aquarius" => "Vízöntőbe",
|
||||
_ => "Halakba",
|
||||
}
|
||||
}
|
||||
|
||||
/// The Moon in a sign, as the frontend's sky card says it.
|
||||
fn moon_mood(sign: &str) -> &'static str {
|
||||
match sign {
|
||||
"aries" => "Lendület és türelmetlenség. Jó nap elkezdeni valamit.",
|
||||
"taurus" => "Nyugalom, kényelem, érzéki örömök. Ráérősebb tempó.",
|
||||
"gemini" => "Kíváncsiság, beszélgetések, sok apró ügy egyszerre.",
|
||||
"cancer" => "Otthon, család, érzékenység. Jólesik a biztonság.",
|
||||
"leo" => "Önkifejezés, játékosság, a figyelem öröme.",
|
||||
"virgo" => "Rendrakás, részletek, a test és a napi rutin.",
|
||||
"libra" => "Kapcsolatok, harmónia, kompromisszumok.",
|
||||
"scorpio" => "Mélység és intenzitás: erősebb érzések, kevesebb felszínesség.",
|
||||
"sagittarius" => "Derűlátás, tanulás, kalandvágy.",
|
||||
"capricorn" => "Kötelességek, tervezés, kitartó munka.",
|
||||
"aquarius" => "Szabadság, barátok, szokatlan ötletek.",
|
||||
_ => "Álmodozás, együttérzés, megérzések.",
|
||||
}
|
||||
}
|
||||
|
||||
fn phase_name(phase: &str) -> &'static str {
|
||||
match phase {
|
||||
"new_moon" => "Újhold",
|
||||
"waxing_crescent" => "Növő holdsarló",
|
||||
"first_quarter" => "Első negyed",
|
||||
"waxing_gibbous" => "Növő hold",
|
||||
"full_moon" => "Telihold",
|
||||
"waning_gibbous" => "Fogyó hold",
|
||||
"last_quarter" => "Utolsó negyed",
|
||||
_ => "Fogyó holdsarló",
|
||||
}
|
||||
}
|
||||
|
||||
fn lunation_name(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"new_moon" => "újhold",
|
||||
"first_quarter" => "első negyed",
|
||||
"full_moon" => "telihold",
|
||||
_ => "utolsó negyed",
|
||||
}
|
||||
}
|
||||
|
||||
fn planet_name(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"mercury" => "Merkúr",
|
||||
"venus" => "Vénusz",
|
||||
"mars" => "Mars",
|
||||
"jupiter" => "Jupiter",
|
||||
"saturn" => "Szaturnusz",
|
||||
"uranus" => "Uránusz",
|
||||
"neptune" => "Neptunusz",
|
||||
"pluto" => "Plútó",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// "a" or "az" before a word.
|
||||
fn article(word: &str) -> &'static str {
|
||||
if word.starts_with(['A', 'Á', 'E', 'É', 'I', 'Í', 'O', 'Ó', 'Ö', 'Ő', 'U', 'Ú', 'Ü', 'Ű']) {
|
||||
"az"
|
||||
} else {
|
||||
"a"
|
||||
}
|
||||
}
|
||||
|
||||
const MONTHS: [&str; 12] = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
const WEEKDAYS: [&str; 7] = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"];
|
||||
|
||||
/// "november 27., csütörtök" from "2026-11-27".
|
||||
fn day_title(date: &str) -> Option<String> {
|
||||
let mut parts = date.split('-').map(|p| p.parse::<i32>().ok());
|
||||
let (year, month, day) = (parts.next()??, parts.next()??, parts.next()??);
|
||||
let month_enum = time::Month::try_from(u8::try_from(month).ok()?).ok()?;
|
||||
let d = time::Date::from_calendar_date(year, month_enum, u8::try_from(day).ok()?).ok()?;
|
||||
let weekday = WEEKDAYS[d.weekday().number_days_from_monday() as usize];
|
||||
Some(format!("{} {day}., {weekday}", MONTHS[(month - 1) as usize]))
|
||||
}
|
||||
|
||||
/// "december 1." from "2026-12-01T07:09".
|
||||
fn short_date(local: &str) -> Option<String> {
|
||||
let month: usize = local.get(5..7)?.parse().ok()?;
|
||||
let day: u32 = local.get(8..10)?.parse().ok()?;
|
||||
Some(format!("{} {day}.", MONTHS.get(month.checked_sub(1)?)?))
|
||||
}
|
||||
|
||||
/// The title and the opening post of the day's thread, from the sky now.
|
||||
pub fn compose(sky: &Value) -> Option<(String, String)> {
|
||||
let local = sky["local_time"].as_str()?;
|
||||
let today = local.get(..10)?;
|
||||
let moon = &sky["moon"];
|
||||
let sign = moon["position"]["sign"].as_str()?;
|
||||
let phase = moon["phase"].as_str().unwrap_or("");
|
||||
let lit = (moon["illumination"].as_f64().unwrap_or(0.0) * 100.0).round() as i64;
|
||||
let title = format!("Mai égbolt · {}", day_title(today)?);
|
||||
|
||||
let place = sign_in(sign);
|
||||
let mut first = format!(
|
||||
"A Hold ma {} {place} jár. {}, {lit}%-os megvilágítással. {}",
|
||||
article(place),
|
||||
phase_name(phase),
|
||||
moon_mood(sign)
|
||||
);
|
||||
if let (Some(at), Some(next)) = (moon["sign_change"]["local_time"].as_str(), moon["sign_change"]["sign"].as_str())
|
||||
&& at.starts_with(today)
|
||||
&& let Some(time) = at.get(11..16)
|
||||
{
|
||||
let into = sign_into(next);
|
||||
first.push_str(&format!(" {time}-kor átlép {} {into}.", article(into)));
|
||||
}
|
||||
|
||||
let mut lines = vec![first];
|
||||
let retro: Vec<&str> = sky["planets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|p| p["retrograde"].as_bool() == Some(true))
|
||||
.filter_map(|p| planet_name(p["id"].as_str()?))
|
||||
.collect();
|
||||
if !retro.is_empty() {
|
||||
lines.push(format!("Retrográd most: {}.", retro.join(", ")));
|
||||
}
|
||||
if let Some(next) = moon["next_phases"].as_array().and_then(|p| p.first()) {
|
||||
let kind = next["kind"].as_str().unwrap_or("");
|
||||
let at = next["local_time"].as_str().and_then(short_date);
|
||||
let place = next["position"]["sign"].as_str().map(sign_in);
|
||||
if let (Some(at), Some(place)) = (at, place) {
|
||||
let name = lunation_name(kind);
|
||||
lines.push(format!(
|
||||
"{}{}: {at}, {} {place}.",
|
||||
name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default(),
|
||||
&name[name.chars().next().map(char::len_utf8).unwrap_or(0)..],
|
||||
article(place)
|
||||
));
|
||||
}
|
||||
}
|
||||
lines.push(
|
||||
"Hogy telik a napotok? Írjátok meg, mit hozott a mai égbolt, vagy egyszerűen csak azt, hogy vagytok.".into(),
|
||||
);
|
||||
Some((title, lines.join("\n\n")))
|
||||
}
|
||||
|
||||
/// Opens today's thread if it is morning and there is none yet; true when made.
|
||||
pub async fn run_once(db: &PgPool, http: &reqwest::Client, backend_url: &str, any_time: bool) -> anyhow::Result<bool> {
|
||||
let (hour, exists): (i32, bool) = sqlx::query_as(
|
||||
"SELECT extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int, \
|
||||
EXISTS (SELECT 1 FROM forum.threads WHERE daily_date = (now() AT TIME ZONE 'Europe/Budapest')::date)",
|
||||
)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if exists || (!any_time && hour < FROM_HOUR) {
|
||||
return Ok(false);
|
||||
}
|
||||
let sky: Value = http
|
||||
.get(format!("{}/v1/public/sky", backend_url.trim_end_matches('/')))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await?;
|
||||
let Some((title, body)) = compose(&sky) else {
|
||||
anyhow::bail!("the sky answer has no Moon");
|
||||
};
|
||||
let mut tx = db.begin().await?;
|
||||
let thread: Option<i64> = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title, system, pinned, daily_date) \
|
||||
SELECT id, NULL, $2, true, true, (now() AT TIME ZONE 'Europe/Budapest')::date FROM forum.topics WHERE slug = $1 \
|
||||
ON CONFLICT (daily_date) DO NOTHING RETURNING id",
|
||||
)
|
||||
.bind(TOPIC)
|
||||
.bind(&title)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(thread) = thread else { return Ok(false) };
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body, system) VALUES ($1, NULL, true, $2, true)",
|
||||
)
|
||||
.bind(thread)
|
||||
.bind(&body)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE forum.threads SET pinned = false WHERE daily_date IS NOT NULL AND id <> $1 AND pinned")
|
||||
.bind(thread)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread, "daily sky thread opened");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn sky() -> Value {
|
||||
json!({
|
||||
"local_time": "2026-11-27T06:10",
|
||||
"moon": {
|
||||
"position": {"sign": "cancer"}, "phase": "waning_gibbous", "illumination": 0.887,
|
||||
"sign_change": {"local_time": "2026-11-27T12:21", "sign": "leo"},
|
||||
"next_phases": [{"kind": "last_quarter", "local_time": "2026-12-01T07:09", "position": {"sign": "virgo"}}]
|
||||
},
|
||||
"planets": [
|
||||
{"id": "sun", "retrograde": false},
|
||||
{"id": "saturn", "retrograde": true},
|
||||
{"id": "neptune", "retrograde": true}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_the_day_in_hungarian() {
|
||||
let (title, body) = compose(&sky()).unwrap();
|
||||
assert_eq!(title, "Mai égbolt · november 27., péntek");
|
||||
assert!(body.starts_with("A Hold ma a Rákban jár. Fogyó hold, 89%-os megvilágítással. Otthon, család"));
|
||||
assert!(body.contains("12:21-kor átlép az Oroszlánba."), "{body}");
|
||||
assert!(body.contains("Retrográd most: Szaturnusz, Neptunusz."));
|
||||
assert!(body.contains("Utolsó negyed: december 1., a Szűzben."), "{body}");
|
||||
assert!(body.ends_with("hogy vagytok."));
|
||||
// A sign change on another day is left out.
|
||||
let mut other = sky();
|
||||
other["moon"]["sign_change"]["local_time"] = json!("2026-11-28T09:00");
|
||||
assert!(!compose(&other).unwrap().1.contains("átlép"));
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ mod compare;
|
||||
mod config;
|
||||
mod email;
|
||||
mod forum_digest;
|
||||
mod forum_sky;
|
||||
mod invoices;
|
||||
mod notify;
|
||||
mod ses;
|
||||
@@ -172,10 +173,10 @@ async fn main() -> anyhow::Result<()> {
|
||||
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()));
|
||||
tracing::info!("forum task enabled (digests, daily sky thread, listeners, weekly summary)");
|
||||
jobs.spawn(forum_digest::run(pool.clone(), base.clone(), config.backend_url.clone(), stop.clone()));
|
||||
}
|
||||
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum digests (their links need it)"),
|
||||
None => tracing::warn!("PUBLIC_BASE_URL is not set: no forum task (its e-mail links need it)"),
|
||||
}
|
||||
|
||||
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
|
||||
|
||||
Reference in New Issue
Block a user