Forum: reports for moderators and private messages by request

Any logged-in user can report a post, or a private message received; a
possible crisis shows the helplines at once. Moderators get the open
reports (crisis first) with what was reported, remove or close them, and
every step goes to the log; the operator gets a Telegram notice of each
new report (kind and link only). Private conversations start with a
request and a short introduction (from the Kereső rank, a few a day); the
recipient accepts, declines silently or blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 10:48:28 +00:00
co-authored by Claude Opus 5.5
parent 36b38525c3
commit 4def9569b1
28 changed files with 2322 additions and 58 deletions
+3 -2
View File
@@ -159,9 +159,10 @@ async fn main() -> anyhow::Result<()> {
match (&config.telegram_bot_token, &config.telegram_chat_id) {
_ if !tasks.notify => {}
(Some(token), Some(chat)) => {
tracing::info!("purchase notices enabled (Telegram)");
tracing::info!("purchase and forum report notices enabled (Telegram)");
let telegram = telegram::Telegram::new(&config.telegram_api_url, token, chat);
jobs.spawn(notify::run(pool.clone(), telegram, config.poll_interval, stop.clone()));
let base = config.public_base_url.clone();
jobs.spawn(notify::run(pool.clone(), telegram, base, config.poll_interval, stop.clone()));
}
_ => tracing::info!("TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is not set: no purchase notices"),
}
+105 -2
View File
@@ -1,6 +1,7 @@
//! The `notify` task: a Telegram notice to the operator about every paid
//! checkout ("Páros csomag, 6 000 Ft"), once. It runs on its own, apart from
//! invoicing, and carries no personal data of the buyer.
//! invoicing, and carries no personal data of the buyer. Also every new forum
//! report (what kind, and the moderators' page), a possible crisis first.
//!
//! A purchase counts as notified when Telegram took the message, or refused
//! it for good (a wrong token or chat: logged as an error); after an outage
@@ -65,11 +66,63 @@ pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result<usize, sqlx::E
Ok(sent)
}
pub async fn run(db: PgPool, telegram: Telegram, interval: Duration, stop: watch::Receiver<bool>) {
/// The notice of a forum report: its kind only (nothing of the post or the
/// people), and where moderators handle it.
fn report_text(kind: &str, base_url: Option<&str>) -> String {
let what = match kind {
"crisis" => "⚠️ LELKI KRÍZIS lehet: valaki aggódik egy tagért",
"illegal" => "🚩 Jogsértő tartalom",
"rude" => "🚩 Bántó, sértő hozzászólás",
"ad" => "🚩 Szolgáltatás hirdetése",
"spam" => "🚩 Spam",
_ => "🚩 Egyéb",
};
let link = base_url.map(|b| format!("\n{}/forum/moderalas", b.trim_end_matches('/'))).unwrap_or_default();
format!("Fórumjelentés: {what}{link}")
}
/// Sends the notices of the forum reports not notified yet (crisis ones first).
pub async fn reports_once(db: &PgPool, telegram: &Telegram, base_url: Option<&str>) -> Result<usize, sqlx::Error> {
let mut tx = db.begin().await?;
let due: Vec<(i64, String)> = sqlx::query_as(
"SELECT id, kind FROM forum.reports WHERE notified_at IS NULL \
ORDER BY kind <> 'crisis', created_at LIMIT $1 FOR UPDATE SKIP LOCKED",
)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
let mut sent = 0;
for (id, kind) in due {
match telegram.send(&report_text(&kind, base_url)).await {
Ok(()) => sent += 1,
Err(e) if e.permanent => {
tracing::error!(report = id, error = %e.message, "telegram refused the report notice; check TELEGRAM_*");
}
Err(e) => {
tracing::warn!(report = id, error = %e.message, "report notice not sent yet");
break;
}
}
sqlx::query("UPDATE forum.reports SET notified_at = now() WHERE id = $1").bind(id).execute(&mut *tx).await?;
}
tx.commit().await?;
Ok(sent)
}
pub async fn run(
db: PgPool,
telegram: Telegram,
base_url: Option<String>,
interval: Duration,
stop: watch::Receiver<bool>,
) {
loop {
if let Err(e) = run_once(&db, &telegram).await {
tracing::error!(error = %e, "purchase notices");
}
if let Err(e) = reports_once(&db, &telegram, base_url.as_deref()).await {
tracing::error!(error = %e, "forum report notices");
}
tokio::select! {
() = tokio::time::sleep(interval) => {}
() = crate::stopped(stop.clone()) => break,
@@ -128,6 +181,56 @@ mod tests {
id
}
#[test]
fn report_texts() {
assert_eq!(
report_text("crisis", Some("https://sorsfonalak.hu/")),
"Fórumjelentés: ⚠️ LELKI KRÍZIS lehet: valaki aggódik egy tagért\nhttps://sorsfonalak.hu/forum/moderalas"
);
assert_eq!(report_text("ad", None), "Fórumjelentés: 🚩 Szolgáltatás hirdetése");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn report_notices_go_out_once(pool: PgPool) {
let fake = Arc::new(Fake::default());
let url = fake_telegram(fake.clone()).await;
let telegram = Telegram::new(&url, "TOKEN", "42");
let user = uuid::Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email) VALUES ($1, 'a@example.com')")
.bind(user)
.execute(&pool)
.await
.unwrap();
let thread: i64 = sqlx::query_scalar(
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES (2, $1, 'Teszt') RETURNING id",
)
.bind(user)
.fetch_one(&pool)
.await
.unwrap();
let post: i64 = sqlx::query_scalar(
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'x') RETURNING id",
)
.bind(thread)
.bind(user)
.fetch_one(&pool)
.await
.unwrap();
for kind in ["spam", "crisis"] {
sqlx::query("INSERT INTO forum.reports (post_id, kind) VALUES ($1, $2)")
.bind(post)
.bind(kind)
.execute(&pool)
.await
.unwrap();
}
assert_eq!(reports_once(&pool, &telegram, None).await.unwrap(), 2);
assert_eq!(reports_once(&pool, &telegram, None).await.unwrap(), 0);
let messages = fake.messages.lock().unwrap();
assert!(messages[0]["text"].as_str().unwrap().contains("KRÍZIS"), "the crisis one first");
assert!(messages[1]["text"].as_str().unwrap().contains("Spam"));
}
#[test]
fn notice_texts() {
assert_eq!(
+4 -1
View File
@@ -829,7 +829,10 @@ mod analyses {
assert_eq!(body["response_format"]["json_schema"]["name"], "question_answer");
let user = body["messages"][1]["content"].as_str().unwrap();
assert!(user.contains("- Sun: Pisces") && user.contains("# Csendes erő"), "chart data and analysis");
assert!(user.contains("Kérdés:\n<kerdes>\nMi az erősségem?\n</kerdes>\nVálasz: A kitartásod."), "earlier answers");
assert!(
user.contains("Kérdés:\n<kerdes>\nMi az erősségem?\n</kerdes>\nVálasz: A kitartásod."),
"earlier answers"
);
assert!(user.contains("<kerdes>\nÉs a munkában?\n</kerdes>") && user.contains("legfeljebb 250 szóban"));
for secret in ["1990", "14:30", "Szeged"] {
assert!(!user.contains(secret), "{secret} leaked");