//! 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 { let mut parts = date.split('-').map(|p| p.parse::().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 { 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 { 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 = 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 AND archived_at IS NULL \ 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")); } }