Files
sorsfonalak/services/forum/src/routes/mentions.rs
T
fecoandClaude Opus 5.5 564c22176f 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
2026-11-26 12:37:52 +00:00

180 lines
6.2 KiB
Rust

//! "@Holdfény" in a post: the members it names follow the thread (so it shows
//! as new for them), hear of it live, and by e-mail if they asked. Nicknames
//! may hold spaces, so after an "@" the longest text that folds into a
//! member's nickname wins ("@Hold fény" too).
use std::collections::HashSet;
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use uuid::Uuid;
use super::{St, authors};
use crate::AppState;
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
/// Members named in one post, at most.
const MAX_MENTIONS: usize = 10;
/// Characters looked at after an "@".
const LOOK_AHEAD: usize = 30;
/// For each "@" (at the start of a word), the folded forms of the text after
/// it, longest last.
fn candidates(body: &str) -> Vec<Vec<String>> {
let chars: Vec<char> = body.chars().collect();
let mut out = Vec::new();
for (i, c) in chars.iter().enumerate() {
if *c != '@' || (i > 0 && chars[i - 1].is_alphanumeric()) {
continue;
}
let mut keys = Vec::new();
let mut taken = String::new();
for &next in chars.iter().skip(i + 1).take(LOOK_AHEAD) {
if next == '\n' || next == '@' {
break;
}
taken.push(next);
let key = text::nickname_key(&taken);
if key.len() >= text::NICKNAME_MIN && keys.last() != Some(&key) {
keys.push(key);
}
}
if !keys.is_empty() {
out.push(keys);
}
}
out
}
/// The members a text names (not its author), longest match per "@".
pub async fn named(db: &PgPool, body: &str, author: Uuid) -> Result<Vec<Uuid>, sqlx::Error> {
let per_at = candidates(body);
let all: Vec<String> = per_at.iter().flatten().cloned().collect::<HashSet<_>>().into_iter().collect();
if all.is_empty() {
return Ok(Vec::new());
}
let found: Vec<(Uuid, String)> =
sqlx::query_as("SELECT user_id, nickname_key FROM forum.members WHERE nickname_key = ANY($1)")
.bind(&all)
.fetch_all(db)
.await?;
let mut users = Vec::new();
for keys in per_at {
if let Some((user, _)) = keys.iter().rev().find_map(|k| found.iter().find(|(_, key)| key == k))
&& *user != author
&& !users.contains(user)
{
users.push(*user);
}
if users.len() >= MAX_MENTIONS {
break;
}
}
Ok(users)
}
/// Records the mentions of a post; returns the members named for the first
/// time, who may read the thread (a restricted topic: its members only).
pub async fn record(state: &AppState, thread: i64, post: i64, author: Uuid, body: &str) -> Vec<Uuid> {
let result: Result<Vec<Uuid>, sqlx::Error> = async {
let users = named(&state.db, body, author).await?;
if users.is_empty() {
return Ok(Vec::new());
}
let readers: Vec<Uuid> = sqlx::query_scalar(
"SELECT u.id FROM users u JOIN forum.threads th ON th.id = $2 JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE u.id = ANY($1) AND (tp.visibility <> 'restricted' \
OR 'moderator' = ANY(u.roles) OR 'admin' = ANY(u.roles) \
OR EXISTS (SELECT 1 FROM forum.topic_members tm \
WHERE tm.topic_id = tp.id AND tm.user_id = u.id AND tm.status = 'approved'))",
)
.bind(&users)
.bind(thread)
.fetch_all(&state.db)
.await?;
let mut fresh = Vec::new();
for user in readers {
let inserted =
sqlx::query("INSERT INTO forum.mentions (post_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(post)
.bind(user)
.execute(&state.db)
.await?;
if inserted.rows_affected() == 1 {
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(user)
.bind(thread)
.execute(&state.db)
.await?;
fresh.push(user);
}
}
Ok(fresh)
}
.await;
match result {
Ok(fresh) => fresh,
Err(e) => {
tracing::error!(error = %e, post, "recording mentions");
Vec::new()
}
}
}
/// After a post is saved: mentions recorded, the named told live and by e-mail.
pub async fn after_post(state: &AppState, thread: i64, post: i64, author: Uuid, body: &str) {
let fresh = record(state, thread, post, author, body).await;
if fresh.is_empty() {
return;
}
crate::mail::after_mention(state, thread, post, author, &fresh, body).await;
crate::live::emit(&state.db, crate::live::Event::default().for_users(fresh)).await;
}
#[derive(Deserialize)]
pub struct SearchQuery {
q: String,
}
/// While typing "@Ho…": members whose nickname starts so (the recently seen first).
pub async fn search(
State(state): St,
viewer: Viewer,
WithRejection(Query(q), _): WithRejection<Query<SearchQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
viewer.require_member()?;
let key = text::nickname_key(&q.q);
if key.is_empty() {
return Ok(Json(json!({ "members": [] })));
}
let ids: Vec<Uuid> = sqlx::query_scalar(
"SELECT user_id FROM forum.members WHERE nickname_key LIKE $1 || '%' \
ORDER BY last_seen_at DESC NULLS LAST LIMIT 6",
)
.bind(&key)
.fetch_all(&state.db)
.await?;
let people = authors(&state.db, ids.iter().copied()).await?;
Ok(Json(json!({ "members": ids.iter().filter_map(|id| people.get(id)).collect::<Vec<_>>() })))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_text_after_each_at() {
let found = candidates("Szia @Hold fény, és @zöldág! e-mail: a@b.hu");
assert_eq!(found.len(), 2, "not inside an e-mail address");
assert!(found[0].contains(&"holdfeny".to_string()));
assert!(found[1].contains(&"zoldag".to_string()));
assert!(candidates("@ab").is_empty(), "too short to be a nickname");
}
}