//! "@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> { let chars: Vec = 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, sqlx::Error> { let per_at = candidates(body); let all: Vec = per_at.iter().flatten().cloned().collect::>().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 { let result: Result, sqlx::Error> = async { let users = named(&state.db, body, author).await?; if users.is_empty() { return Ok(Vec::new()); } let readers: Vec = 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, ApiError>, ) -> ApiResult> { viewer.require_member()?; let key = text::nickname_key(&q.q); if key.is_empty() { return Ok(Json(json!({ "members": [] }))); } let ids: Vec = 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::>() }))) } #[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"); } }