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:
feco
2026-11-26 12:37:52 +00:00
co-authored by Claude Opus 5.5
parent 0a2308c491
commit 564c22176f
31 changed files with 2226 additions and 320 deletions
+18 -2
View File
@@ -38,10 +38,16 @@ pub struct Member {
pub email_replies: String,
pub email_followed: String,
pub email_messages: String,
pub email_mentions: String,
pub email_listener: String,
pub email_weekly: bool,
pub listener: bool,
pub supporter_badge: bool,
}
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
created_at, nickname_changed_at, banned_until, ban_reason, email_replies, email_followed, email_messages";
created_at, nickname_changed_at, banned_until, ban_reason, email_replies, email_followed, email_messages, \
email_mentions, email_listener, email_weekly, listener, supporter_badge";
impl Member {
pub fn rank(&self, now: OffsetDateTime) -> Rank {
@@ -58,6 +64,8 @@ impl Member {
pub struct Viewer {
pub user: Option<User>,
pub member: Option<Member>,
/// The restricted topics the member was approved into.
pub topics: Vec<i16>,
}
impl Viewer {
@@ -129,7 +137,15 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
.execute(&state.db)
.await?;
}
Ok(Viewer { user: Some(user), member })
let topics = if member.is_some() {
sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'approved'")
.bind(user.id)
.fetch_all(&state.db)
.await?
} else {
Vec::new()
};
Ok(Viewer { user: Some(user), member, topics })
}
}
+45
View File
@@ -217,3 +217,48 @@ pub async fn notify_reporters(state: &AppState, reporters: &[Option<Uuid>], outc
notify_user(state, reporter, "forum_report_result", payload).await;
}
}
/// Members named in a post ("@Holdfény") who asked for an e-mail about it
/// (not while online, one per thread an hour).
pub async fn after_mention(state: &AppState, thread_id: i64, post_id: i64, author: Uuid, users: &[Uuid], body: &str) {
let result: Result<(), sqlx::Error> = async {
let recipients: Vec<Recipient> = sqlx::query_as(&format!(
"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.user_id = ANY($1) AND m.email_mentions = 'instant' AND {OFFLINE} \
AND NOT EXISTS (SELECT 1 FROM email_outbox e WHERE e.user_id = m.user_id \
AND e.template IN ('forum_mention', 'forum_reply') \
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
))
.bind(users)
.bind(thread_id)
.fetch_all(&state.db)
.await?;
if recipients.is_empty() {
return Ok(());
}
let (title, who): (String, Option<String>) = sqlx::query_as(
"SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) FROM forum.threads th WHERE th.id = $1",
)
.bind(thread_id)
.bind(author)
.fetch_one(&state.db)
.await?;
let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title));
for to in &recipients {
let payload = json!({
"url": url,
"author": who,
"thread_title": title,
"thread_id": thread_id.to_string(),
"excerpt": body.chars().take(300).collect::<String>(),
});
queue(&state.db, &state.base_url, to, "forum_mention", payload).await?;
}
Ok(())
}
.await;
if let Err(e) = result {
tracing::error!(error = %e, thread = thread_id, "queueing the mention e-mails");
}
}
+18 -4
View File
@@ -6,7 +6,8 @@
//! or `Authorization: Bearer`) is valid here too.
//!
//! Configuration: `DATABASE_URL`, `PUBLIC_BASE_URL` (the site, for e-mail
//! links; default `http://localhost:3001`); `BIND_ADDR` (default `0.0.0.0:8083`),
//! links; default `http://localhost:3001`), `S3_*` (avatar uploads, as the
//! backend's); `BIND_ADDR` (default `0.0.0.0:8083`),
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
//!
//! `forum healthcheck` performs a local health check (for Docker).
@@ -37,11 +38,19 @@ pub struct AppState {
pub base_url: String,
/// The live events of this instance (`live::listen` fills it).
pub hub: live::Hub,
/// Where uploaded avatars are kept (`S3_*`); `None`: no uploads.
pub storage: Option<object_storage::Storage>,
}
impl AppState {
pub fn new(db: PgPool, base_url: String) -> Self {
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string(), hub: live::Hub::default() }
pub fn new(db: PgPool, base_url: String, storage: Option<object_storage::Storage>) -> Self {
Self {
db,
flood_secs: 5,
base_url: base_url.trim_end_matches('/').to_string(),
hub: live::Hub::default(),
storage,
}
}
}
@@ -56,7 +65,12 @@ async fn main() -> anyhow::Result<()> {
let pool = db::connect(&url).await.context("connecting to the database")?;
db::migrate(&pool).await.context("running database migrations")?;
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
let state = Arc::new(AppState::new(pool, base_url));
let storage =
object_storage::StorageConfig::from_env().map_err(anyhow::Error::msg)?.map(object_storage::Storage::new);
if storage.is_none() {
tracing::info!("S3_ENDPOINT is not set: no avatar uploads");
}
let state = Arc::new(AppState::new(pool, base_url, storage));
tokio::spawn(live::listen(state.db.clone(), state.hub.clone()));
let app = routes::router(state);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
+204
View File
@@ -0,0 +1,204 @@
//! Own avatars: a member from the Kereső rank may upload a picture instead of
//! a starter avatar. It is cut to a square, made small (256 pixels), stripped
//! of its metadata (EXIF: camera, place) and kept in the object storage; the
//! forum serves it. A moderator can put the starter avatar back.
use std::io::Cursor;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum_extra::extract::WithRejection;
use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use image::metadata::Orientation;
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use uuid::Uuid;
use super::St;
use super::moderation::{self, Action};
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
/// The largest upload accepted, in bytes.
pub const MAX_UPLOAD: usize = 8 * 1024 * 1024;
/// The stored picture's side, in pixels.
const SIDE: u32 = 256;
const MIN_SIDE: u32 = 64;
/// The objects' folder in the bucket.
const FOLDER: &str = "forum-avatars";
pub const PREFIX: &str = "upload:";
/// A JPEG, PNG or WebP picture as an upright square JPEG of [`SIDE`] pixels.
/// The error is a message for the member.
pub fn normalize(bytes: &[u8]) -> Result<Vec<u8>, String> {
let unreadable = || "A képet nem sikerült beolvasni. JPEG, PNG vagy WebP képet tölts fel.".to_string();
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?;
if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP)) {
return Err(unreadable());
}
let mut limits = Limits::default();
limits.max_image_width = Some(12_000);
limits.max_image_height = Some(12_000);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(|_| unreadable())?;
let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
let mut img = DynamicImage::from_decoder(decoder).map_err(|_| unreadable())?;
img.apply_orientation(orientation);
let side = img.width().min(img.height());
if side < MIN_SIDE {
return Err(format!("A kép túl kicsi: legalább {MIN_SIDE}×{MIN_SIDE} pixeles legyen."));
}
// The middle square, then small.
let square = img.crop_imm((img.width() - side) / 2, (img.height() - side) / 2, side, side);
let small = square.resize_exact(SIDE, SIDE, FilterType::Lanczos3);
let rgb = if small.color().has_alpha() {
// JPEG has no transparency: a transparent part turns white.
let rgba = small.to_rgba8();
image::RgbImage::from_fn(SIDE, SIDE, |x, y| {
let [r, g, b, a] = rgba.get_pixel(x, y).0;
let mix = |c: u8| ((u16::from(c) * u16::from(a) + 255 * (255 - u16::from(a))) / 255) as u8;
image::Rgb([mix(r), mix(g), mix(b)])
})
} else {
small.to_rgb8()
};
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, 85).encode_image(&rgb).map_err(|e| e.to_string())?;
Ok(jpeg)
}
/// The stored file of an `upload:` avatar, if it is one.
pub fn uploaded_file(avatar: &str) -> Option<&str> {
avatar.strip_prefix(PREFIX)
}
fn valid_file(file: &str) -> bool {
file.len() <= 80
&& file.ends_with(".jpg")
&& file.trim_end_matches(".jpg").chars().all(|c| c.is_ascii_hexdigit() || c == '-')
}
/// Removes a stored avatar (best effort: a leftover file is only storage).
pub async fn forget(state: &crate::AppState, avatar: &str) {
if let (Some(file), Some(storage)) = (uploaded_file(avatar), &state.storage)
&& let Err(e) = storage.delete(&format!("{FOLDER}/{file}")).await
{
tracing::warn!(error = %e, "removing an old avatar");
}
}
/// `PUT /v1/forum/me/avatar`: the picture's bytes as the body.
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<Json<Value>> {
let member = viewer.require_writer()?.clone();
if member.rank(OffsetDateTime::now_utc()).is_newcomer() && !viewer.is_moderator() {
return Err(ApiError::Forbidden("Saját képet a Kereső rangtól tölthetsz fel.".into()));
}
let Some(storage) = &state.storage else {
return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into()));
};
if body.len() > MAX_UPLOAD {
return Err(ApiError::bad("A kép legfeljebb 8 MB lehet."));
}
let bytes = body.to_vec();
let jpeg = tokio::task::spawn_blocking(move || normalize(&bytes))
.await
.map_err(|e| ApiError::Internal(e.to_string()))?
.map_err(ApiError::BadRequest)?;
let hash: String = Sha256::digest(&jpeg).iter().take(6).map(|b| format!("{b:02x}")).collect();
let file = format!("{}-{hash}.jpg", member.user_id.simple());
storage
.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg")
.await
.map_err(|e| ApiError::Internal(format!("storing an avatar: {e}")))?;
let avatar = format!("{PREFIX}{file}");
sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1")
.bind(member.user_id)
.bind(&avatar)
.execute(&state.db)
.await?;
if member.avatar != avatar {
forget(&state, &member.avatar).await;
}
Ok(Json(json!({ "avatar": avatar })))
}
/// `GET /v1/forum/avatars/{file}`: a stored avatar (its name changes with
/// its content, so it is cached for good).
pub async fn serve(
State(state): St,
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Response> {
if !valid_file(&file) {
return Err(ApiError::NotFound("avatar"));
}
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("avatar"))?;
let object = storage
.get(&format!("{FOLDER}/{file}"))
.await
.map_err(|e| ApiError::Internal(format!("reading an avatar: {e}")))?
.ok_or(ApiError::NotFound("avatar"))?;
Ok((
[(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")],
object.bytes,
)
.into_response())
}
/// A moderator puts back the starter avatar (an unfit picture).
pub async fn reset(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let key = text::nickname_key(&nickname);
let found: Option<(Uuid, String)> =
sqlx::query_as("SELECT user_id, avatar FROM forum.members WHERE nickname_key = $1")
.bind(&key)
.fetch_optional(&state.db)
.await?;
let (user, avatar) = found.ok_or(ApiError::NotFound("member"))?;
if uploaded_file(&avatar).is_none() {
return Ok(StatusCode::NO_CONTENT);
}
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1")
.bind(user)
.bind(text::default_avatar(&key))
.execute(&mut *tx)
.await?;
moderation::record(&mut *tx, moderator.id, Action::ResetAvatar, Some(user), None, None, None, None).await?;
tx.commit().await?;
forget(&state, &avatar).await;
Ok(StatusCode::NO_CONTENT)
}
#[cfg(test)]
mod tests {
use super::*;
fn png(width: u32, height: u32) -> Vec<u8> {
let img =
DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, image::Rgba([200, 100, 50, 255])));
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap();
out
}
#[test]
fn makes_a_small_square_jpeg() {
let jpeg = normalize(&png(900, 400)).unwrap();
let back = image::load_from_memory(&jpeg).unwrap();
assert_eq!((back.width(), back.height()), (SIDE, SIDE));
assert!(normalize(&png(40, 40)).unwrap_err().contains("túl kicsi"));
assert!(normalize(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;").is_err());
assert!(valid_file("0190aa-3f2a1b.jpg") && !valid_file("../x.jpg") && !valid_file("a.png"));
}
}
+67 -4
View File
@@ -58,15 +58,34 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
.bind(since)
.fetch_all(&state.db)
.await?;
let readable: Vec<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility)).collect();
let readable: Vec<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility, r.id)).collect();
let people =
super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author))
.await?;
// A restricted topic shows by name to members, who may ask to join.
let pending: Vec<i16> = match viewer.user_id() {
Some(me) => {
sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'pending'")
.bind(me)
.fetch_all(&state.db)
.await?
}
None => Vec::new(),
};
Ok(rows
.into_iter()
.zip(readable)
.filter(|(r, _)| r.visibility != "restricted" || viewer.is_moderator())
.filter(|(r, _)| r.visibility != "restricted" || viewer.member.is_some() || viewer.is_moderator())
.map(|(r, readable)| {
let membership = (r.visibility == "restricted").then(|| {
if viewer.topics.contains(&r.id) {
"approved"
} else if pending.contains(&r.id) {
"pending"
} else {
"none"
}
});
let mut topic = json!({
"id": r.id,
"slug": r.slug,
@@ -75,6 +94,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
"visibility": r.visibility,
"listening": r.listening,
"readable": readable,
"membership": membership,
});
if readable {
topic["thread_count"] = json!(r.thread_count);
@@ -143,9 +163,21 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
.fetch_all(&state.db)
.await?;
// "Most itt vannak": members seen in the last few minutes (not the invisible ones).
let present: Vec<Uuid> = sqlx::query_scalar(
"SELECT user_id FROM forum.members WHERE NOT invisible \
AND last_seen_at > now() - make_interval(mins => $1) ORDER BY last_seen_at DESC LIMIT 24",
)
.bind(crate::auth::ONLINE_MINUTES as i32)
.fetch_all(&state.db)
.await?;
let people = super::authors(&state.db, present.iter().copied()).await?;
let online: Vec<Value> = present.iter().filter_map(|id| people.get(id).cloned()).collect();
Ok(Json(json!({
"viewer": viewer_json(&viewer),
"followed": followed,
"online": online,
"topics": topics,
"unanswered": cards_json(&state.db, unanswered).await?,
"hot": cards_json(&state.db, hot).await?,
@@ -170,18 +202,49 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
Ok(Some(json!({ "new_replies": replies, "threads": threads })))
}
/// Threads asking to be heard (or in a listening topic) that have waited an
/// hour without a reply (two weeks at most), not the listener's own.
pub const WAITING_SQL: &str = "th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \
AND th.created_at < now() - interval '1 hour' AND th.created_at > now() - interval '14 days' \
AND (th.intent = 'listen' OR tp.listening)";
async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult<i64> {
let me = viewer.user_id();
Ok(sqlx::query_scalar(&format!(
"SELECT count(*) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE {WAITING_SQL} AND th.author_id IS DISTINCT FROM $1 AND ({})",
super::visible_topics(viewer)
))
.bind(me)
.fetch_one(&state.db)
.await?)
}
/// For the forum's menu on every page: who the viewer is, and the badge.
pub async fn nav(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
let messages = match &viewer.member {
Some(m) => Some(super::messages::unread_count(&state.db, m.user_id).await?),
None => None,
};
let reports = if viewer.is_moderator() { Some(super::reports::open_count(&state.db).await?) } else { None };
let reports = if viewer.is_moderator() {
let requests: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.topic_members WHERE status = 'pending'")
.fetch_one(&state.db)
.await?;
Some(super::reports::open_count(&state.db).await? + requests)
} else {
None
};
// Volunteer listeners: threads asking to be heard, still without a reply.
let waiting = match &viewer.member {
Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?),
_ => None,
};
Ok(Json(json!({
"viewer": viewer_json(&viewer),
"followed": followed_counts(&state, &viewer).await?,
"messages": messages,
"reports": reports,
"waiting": waiting,
})))
}
@@ -208,7 +271,7 @@ pub async fn topic(
.fetch_optional(&state.db)
.await?;
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?;
if !may_read(&viewer, &visibility) {
if !may_read(&viewer, &visibility, id) {
// A members-only topic asks for a login; a restricted one stays hidden.
return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") });
}
+56 -4
View File
@@ -52,12 +52,21 @@ pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
"replies": m.email_replies,
"followed": m.email_followed,
"messages": m.email_messages,
"mentions": m.email_mentions,
"listener": m.email_listener,
"weekly": m.email_weekly,
},
"listener": m.listener,
"supporter_badge": m.supporter_badge,
// From the Kereső rank: volunteering as a listener, an own picture.
"can_listen": viewer.is_moderator() || !rank.is_newcomer(),
"can_upload_avatar": viewer.is_moderator() || !rank.is_newcomer(),
})
});
let buyer = super::has_purchase(&state.db, user.id).await?;
let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id);
let chart = signs.map(|s| json!({ "sun": s.share("sun"), "big3": s.share("big3"), "planets": s.share("planets") }));
Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart })))
Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart, "can_supporter": buyer })))
}
#[derive(Deserialize)]
@@ -74,6 +83,12 @@ pub struct SaveMe {
/// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`.
#[serde(default)]
email: Option<EmailSettings>,
/// Volunteering as a listener (from the Kereső rank).
#[serde(default)]
listener: Option<bool>,
/// Showing the "Támogató" badge (buyers only).
#[serde(default)]
supporter_badge: Option<bool>,
}
#[derive(Deserialize)]
@@ -84,6 +99,12 @@ pub struct EmailSettings {
followed: Option<String>,
#[serde(default)]
messages: Option<String>,
#[serde(default)]
mentions: Option<String>,
#[serde(default)]
listener: Option<String>,
#[serde(default)]
weekly: Option<bool>,
}
fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult<Option<String>> {
@@ -120,7 +141,13 @@ pub async fn save_me(
let user = viewer.require_user()?;
let nickname = text::nickname(&req.nickname)?;
let key = text::nickname_key(&nickname);
let avatar = req.avatar.as_deref().map(text::avatar).transpose()?;
// The current avatar sent back unchanged (an own picture too) is no change.
let current = viewer.member.as_ref().map(|m| m.avatar.as_str());
let avatar = match req.avatar.as_deref() {
Some(a) if Some(a) == current => None,
other => other.map(text::avatar).transpose()?,
};
let avatar_changed = avatar.is_some();
let bio = req.bio.as_deref().map(text::bio).transpose()?;
let chart_share = match req.chart_share.as_deref() {
None => None,
@@ -131,6 +158,18 @@ pub async fn save_me(
let email_replies = one_of(email.and_then(|e| e.replies.as_deref()), &["off", "daily", "instant"])?;
let email_followed = one_of(email.and_then(|e| e.followed.as_deref()), &["off", "daily"])?;
let email_messages = one_of(email.and_then(|e| e.messages.as_deref()), &["off", "instant"])?;
let email_mentions = one_of(email.and_then(|e| e.mentions.as_deref()), &["off", "instant"])?;
let email_listener = one_of(email.and_then(|e| e.listener.as_deref()), &["off", "instant"])?;
let email_weekly = email.and_then(|e| e.weekly);
if req.listener == Some(true) {
let newcomer = viewer.member.as_ref().is_none_or(|m| m.rank(OffsetDateTime::now_utc()).is_newcomer());
if newcomer && !viewer.is_moderator() {
return Err(ApiError::Forbidden("Meghallgatónak a Kereső rangtól jelentkezhetsz.".into()));
}
}
if req.supporter_badge == Some(true) && !super::has_purchase(&state.db, user.id).await? {
return Err(ApiError::Forbidden("A Támogató jelvény a csomagot vásárlóké.".into()));
}
if nickname_taken(&state.db, &key, user.id).await? {
return Err(taken());
}
@@ -207,16 +246,28 @@ pub async fn save_me(
}
sqlx::query(
"UPDATE forum.members SET email_replies = COALESCE($2, email_replies), \
email_followed = COALESCE($3, email_followed), email_messages = COALESCE($4, email_messages) \
email_followed = COALESCE($3, email_followed), email_messages = COALESCE($4, email_messages), \
email_mentions = COALESCE($5, email_mentions), email_listener = COALESCE($6, email_listener), \
email_weekly = COALESCE($7, email_weekly), listener = COALESCE($8, listener), \
supporter_badge = COALESCE($9, supporter_badge) \
WHERE user_id = $1",
)
.bind(user.id)
.bind(email_replies)
.bind(email_followed)
.bind(email_messages)
.bind(email_mentions)
.bind(email_listener)
.bind(email_weekly)
.bind(req.listener)
.bind(req.supporter_badge)
.execute(&mut *tx)
.await?;
tx.commit().await?;
// A starter avatar chosen instead of an own picture: the picture goes.
if let (Some(old), true) = (viewer.member.as_ref().map(|m| m.avatar.clone()), avatar_changed) {
super::avatars::forget(&state, &old).await;
}
let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer };
me(State(state), viewer).await
}
@@ -255,7 +306,8 @@ pub async fn unsubscribe(
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let done = sqlx::query(
"UPDATE forum.members SET email_replies = 'off', email_followed = 'off', email_messages = 'off' \
"UPDATE forum.members SET email_replies = 'off', email_followed = 'off', email_messages = 'off', \
email_mentions = 'off', email_listener = 'off', email_weekly = false \
WHERE email_token = $1",
)
.bind(q.token.trim())
+179
View File
@@ -0,0 +1,179 @@
//! "@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");
}
}
+41 -12
View File
@@ -5,13 +5,16 @@
//! role. A thread in a topic the viewer may not read answers 404, so its
//! existence is not revealed.
mod avatars;
mod home;
mod members;
mod mentions;
mod messages;
mod moderation;
mod posts;
mod reports;
mod threads;
mod topics;
use std::collections::HashMap;
use std::sync::Arc;
@@ -40,8 +43,10 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/healthz", get(health))
.route("/v1/forum/home", get(home::home))
.route("/v1/forum/nav", get(home::nav))
.route("/v1/forum/topics", get(home::topics))
.route("/v1/forum/topics/{slug}", get(home::topic))
.route("/v1/forum/topics", get(home::topics).post(topics::create))
.route("/v1/forum/topics/{slug}", get(home::topic).patch(topics::update))
.route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave))
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
.route("/v1/forum/followed", get(home::followed))
.route("/v1/forum/threads", post(threads::create))
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
@@ -63,10 +68,17 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/conversations/{id}/messages", post(messages::send))
.route("/v1/forum/conversations/{id}/read", post(messages::read))
.route("/v1/forum/me", get(members::me).put(members::save_me))
.route(
"/v1/forum/me/avatar",
put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)),
)
.route("/v1/forum/avatars/{file}", get(avatars::serve))
.route("/v1/forum/members/{nickname}/avatar-reset", post(avatars::reset))
.route("/v1/forum/nickname-check", get(members::nickname_check))
.route("/v1/forum/presence", post(members::presence))
.route("/v1/forum/unsubscribe", post(members::unsubscribe))
.route("/v1/forum/ws", get(crate::live::connect))
.route("/v1/forum/members/search", get(mentions::search))
.route("/v1/forum/members/{nickname}", get(members::profile))
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log))
@@ -83,23 +95,30 @@ async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
}
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
/// Built from the viewer's flags only, never from input.
pub fn visible_topics(viewer: &Viewer) -> &'static str {
/// Built from the viewer's flags and their approved topic ids only, never
/// from input.
pub fn visible_topics(viewer: &Viewer) -> String {
if viewer.is_moderator() {
"TRUE"
"TRUE".into()
} else if viewer.logged_in() {
"tp.visibility IN ('public', 'members')"
let mut sql = "tp.visibility IN ('public', 'members')".to_string();
if !viewer.topics.is_empty() {
let ids: Vec<String> = viewer.topics.iter().map(|id| id.to_string()).collect();
sql.push_str(&format!(" OR tp.id IN ({})", ids.join(", ")));
}
sql
} else {
"tp.visibility = 'public'"
"tp.visibility = 'public'".into()
}
}
/// Whether the viewer may read a topic of this visibility.
pub fn may_read(viewer: &Viewer, visibility: &str) -> bool {
/// Whether the viewer may read a topic of this visibility (restricted: only
/// moderators and the approved members).
pub fn may_read(viewer: &Viewer, visibility: &str, topic: i16) -> bool {
match visibility {
"public" => true,
"members" => viewer.logged_in(),
_ => viewer.is_moderator(),
_ => viewer.is_moderator() || viewer.topics.contains(&topic),
}
}
@@ -120,6 +139,8 @@ pub struct CardRow {
pub participants: i64,
/// Posts by others the member has not read; `None` for visitors.
pub unread: Option<i64>,
/// The site's own thread (the daily sky).
pub system: bool,
}
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
@@ -136,7 +157,8 @@ pub fn card_sql(viewer: &Viewer) -> String {
WHERE p.thread_id = th.id AND p.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
AND p.created_at > $2::timestamptz \
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread \
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread, \
th.system \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.deleted_at IS NULL AND ({})",
visible_topics(viewer)
@@ -170,6 +192,7 @@ pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, s
"pinned": r.pinned,
"locked": r.locked,
"unread": r.unread,
"system": r.system,
})
})
.collect())
@@ -186,6 +209,8 @@ struct AuthorRow {
last_seen_at: Option<OffsetDateTime>,
chart_share: String,
roles: Vec<String>,
listener: bool,
supporter: bool,
}
/// How members appear next to what they wrote: nickname, avatar, rank,
@@ -199,7 +224,9 @@ pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result
}
let rows: Vec<AuthorRow> = sqlx::query_as(
"SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \
m.chart_share, u.roles \
m.chart_share, u.roles, m.listener, \
m.supporter_badge AND EXISTS (SELECT 1 FROM package_orders o \
WHERE o.user_id = m.user_id AND o.source = 'stripe') AS supporter \
FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.user_id = ANY($1)",
)
.bind(&ids)
@@ -222,6 +249,8 @@ pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result
"moderator": moderator,
"online": online(r.invisible, r.last_seen_at, now),
"signs": shown,
"listener": r.listener,
"supporter": r.supporter,
});
(r.user_id, value)
})
+10
View File
@@ -29,6 +29,11 @@ pub enum Action {
Unpin,
ResolveReport,
DismissReport,
ApproveMember,
RejectMember,
RemoveMember,
ResetAvatar,
Topic,
}
impl Action {
@@ -46,6 +51,11 @@ impl Action {
Action::Unpin => "unpin",
Action::ResolveReport => "resolve_report",
Action::DismissReport => "dismiss_report",
Action::ApproveMember => "approve_member",
Action::RejectMember => "reject_member",
Action::RemoveMember => "remove_member",
Action::ResetAvatar => "reset_avatar",
Action::Topic => "topic",
}
}
}
+1
View File
@@ -61,6 +61,7 @@ pub async fn edit(
.fetch_one(&state.db)
.await?;
announce(&state, post.thread_id).await;
super::mentions::after_post(&state, post.thread_id, post.id, member.user_id, &body).await;
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
}
+22 -5
View File
@@ -28,6 +28,7 @@ pub const REACTIONS: [&str; 4] = ["with_you", "thanks", "me_too", "insight"];
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct ThreadRow {
pub id: i64,
pub topic_id: i16,
pub topic_slug: String,
pub topic_name: String,
pub visibility: String,
@@ -40,11 +41,12 @@ pub struct ThreadRow {
pub pinned: bool,
pub deleted_at: Option<OffsetDateTime>,
pub delete_reason: Option<String>,
pub system: bool,
}
const THREAD_SELECT: &str = "SELECT th.id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
const THREAD_SELECT: &str = "SELECT th.id, th.topic_id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
tp.listening, th.author_id, th.title, th.intent, th.created_at, th.locked, th.pinned, th.deleted_at, \
th.delete_reason \
th.delete_reason, th.system \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id";
/// A thread the viewer may read (deleted ones too): 404 when it does not
@@ -55,7 +57,7 @@ pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult
.fetch_optional(db)
.await?
.ok_or(ApiError::NotFound("thread"))?;
if !may_read(viewer, &thread.visibility) {
if !may_read(viewer, &thread.visibility, thread.topic_id) {
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
}
Ok(thread)
@@ -88,10 +90,12 @@ pub struct PostRow {
pub deleted_at: Option<OffsetDateTime>,
pub deleted_by: Option<Uuid>,
pub delete_reason: Option<String>,
/// Written by the site itself (the daily sky thread).
pub system: bool,
}
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
delete_reason";
delete_reason, system";
/// Posts as the thread page shows them: authors, reactions, the viewer's own
/// reaction. A removed post keeps its place with the reason; only
@@ -120,10 +124,18 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
}
None => HashMap::new(),
};
let named: Vec<(i64, String)> = sqlx::query_as(
"SELECT mn.post_id, m.nickname FROM forum.mentions mn JOIN forum.members m ON m.user_id = mn.user_id \
WHERE mn.post_id = ANY($1)",
)
.bind(&ids)
.fetch_all(db)
.await?;
let moderator = viewer.is_moderator();
Ok(posts
.iter()
.map(|p| {
let mentions: Vec<&String> = named.iter().filter(|(id, _)| *id == p.id).map(|(_, n)| n).collect();
let counts = by_post.remove(&p.id).unwrap_or_default();
let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum();
let down = counts.get("down").copied().unwrap_or(0);
@@ -150,6 +162,8 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
"score": score,
"collapsed": score <= COLLAPSE_SCORE,
"mine": mine.get(&p.id),
"mentions": mentions,
"system": p.system,
});
if moderator {
post["down"] = json!(down);
@@ -225,6 +239,7 @@ fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
"locked": thread.locked,
"pinned": thread.pinned,
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
"system": thread.system,
})
}
@@ -292,7 +307,7 @@ pub async fn create(
.fetch_optional(&state.db)
.await?;
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
if !may_read(&viewer, &visibility) {
if !may_read(&viewer, &visibility, topic_id) {
return Err(ApiError::bad("Ismeretlen téma."));
}
let title = text::title(&req.title)?;
@@ -325,6 +340,7 @@ pub async fn create(
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
tx.commit().await?;
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
super::mentions::after_post(&state, thread_id, post_id, member.user_id, &body).await;
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
}
@@ -421,6 +437,7 @@ pub async fn reply(
after_post(&mut tx, member.user_id, id, post.id).await?;
tx.commit().await?;
crate::mail::after_reply(&state, id, post.id, member.user_id, post.parent_id, &body).await;
super::mentions::after_post(&state, id, post.id, member.user_id, &body).await;
let followers = crate::live::followers(&state.db, id, member.user_id).await;
crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers))
.await;
+296
View File
@@ -0,0 +1,296 @@
//! Topics: the admin creates and edits them; a restricted topic is read and
//! written only by its approved members (and moderators): members ask to
//! join, moderators approve or turn them down.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use uuid::Uuid;
use super::moderation::{self, Action};
use super::{Body, St, authors, rfc3339};
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
const NAME_MAX: usize = 60;
const DESCRIPTION_MAX: usize = 160;
const NOTE_MAX: usize = 300;
fn require_admin(viewer: &Viewer) -> ApiResult<Uuid> {
let user = viewer.require_user()?;
if viewer.is_admin() { Ok(user.id) } else { Err(ApiError::Forbidden("Témát csak az admin kezelhet.".into())) }
}
fn visibility(raw: &str) -> ApiResult<String> {
match raw {
"public" | "members" | "restricted" => Ok(raw.to_string()),
_ => Err(ApiError::bad("Ismeretlen láthatóság.")),
}
}
fn one_line(raw: &str, max: usize, what: &str) -> ApiResult<String> {
let text: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
let len = text.chars().count();
if len < 2 || len > max {
return Err(ApiError::bad(format!("A {what} 2–{max} karakter legyen.")));
}
Ok(text)
}
#[derive(Deserialize)]
pub struct NewTopic {
name: String,
description: String,
#[serde(default = "public")]
visibility: String,
#[serde(default)]
listening: bool,
}
fn public() -> String {
"public".into()
}
/// The admin opens a topic (last in the list); its address comes from the name.
pub async fn create(
State(state): St,
viewer: Viewer,
WithRejection(Json(req), _): Body<NewTopic>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let admin = require_admin(&viewer)?;
let name = one_line(&req.name, NAME_MAX, "név")?;
let description = one_line(&req.description, DESCRIPTION_MAX, "leírás")?;
let visibility = visibility(&req.visibility)?;
let slug = text::slug(&name);
if slug.is_empty() {
return Err(ApiError::bad("A névből nem lesz cím: írj bele betűket."));
}
let mut tx = state.db.begin().await?;
let created: Result<i16, sqlx::Error> = sqlx::query_scalar(
"INSERT INTO forum.topics (id, slug, name, description, visibility, listening, position) \
SELECT COALESCE(max(id), 0) + 1, $1, $2, $3, $4, $5, COALESCE(max(position), 0) + 1 FROM forum.topics \
RETURNING id",
)
.bind(&slug)
.bind(&name)
.bind(&description)
.bind(&visibility)
.bind(req.listening)
.fetch_one(&mut *tx)
.await;
let id = match created {
Ok(id) => id,
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
return Err(ApiError::conflict("topic_exists", "Ilyen nevű téma már van."));
}
Err(e) => return Err(e.into()),
};
moderation::record(&mut *tx, admin, Action::Topic, None, None, None, Some(&format!("új téma: {name}")), None)
.await?;
tx.commit().await?;
Ok((StatusCode::CREATED, Json(json!({ "id": id, "slug": slug }))))
}
#[derive(Deserialize)]
pub struct TopicChange {
#[serde(default)]
name: Option<String>,
#[serde(default)]
description: Option<String>,
#[serde(default)]
visibility: Option<String>,
#[serde(default)]
listening: Option<bool>,
#[serde(default)]
position: Option<i16>,
}
/// The admin renames, describes, moves or changes the visibility of a topic
/// (its address stays, so links keep working).
pub async fn update(
State(state): St,
viewer: Viewer,
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
WithRejection(Json(req), _): Body<TopicChange>,
) -> ApiResult<StatusCode> {
let admin = require_admin(&viewer)?;
let name = req.name.as_deref().map(|n| one_line(n, NAME_MAX, "név")).transpose()?;
let description = req.description.as_deref().map(|d| one_line(d, DESCRIPTION_MAX, "leírás")).transpose()?;
let visibility = req.visibility.as_deref().map(visibility).transpose()?;
let mut tx = state.db.begin().await?;
let changed = sqlx::query(
"UPDATE forum.topics SET name = COALESCE($2, name), description = COALESCE($3, description), \
visibility = COALESCE($4, visibility), listening = COALESCE($5, listening), \
position = COALESCE($6, position) WHERE slug = $1",
)
.bind(&slug)
.bind(&name)
.bind(&description)
.bind(&visibility)
.bind(req.listening)
.bind(req.position)
.execute(&mut *tx)
.await?;
if changed.rows_affected() == 0 {
return Err(ApiError::NotFound("topic"));
}
moderation::record(
&mut *tx,
admin,
Action::Topic,
None,
None,
None,
Some(&format!("téma módosítva: {slug}")),
None,
)
.await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
pub struct JoinRequest {
#[serde(default)]
note: Option<String>,
}
/// A member asks to join a restricted topic (with a few words, if they like).
pub async fn join(
State(state): St,
viewer: Viewer,
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
WithRejection(Json(req), _): Body<JoinRequest>,
) -> ApiResult<StatusCode> {
let member = viewer.require_writer()?;
let topic: Option<(i16, String)> = sqlx::query_as("SELECT id, visibility FROM forum.topics WHERE slug = $1")
.bind(&slug)
.fetch_optional(&state.db)
.await?;
let (id, visibility) = topic.ok_or(ApiError::NotFound("topic"))?;
if visibility != "restricted" {
return Err(ApiError::bad("Ebbe a témába nem kell jelentkezni."));
}
let note: String = req.note.as_deref().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");
if note.chars().count() > NOTE_MAX {
return Err(ApiError::bad(format!("Legfeljebb {NOTE_MAX} karakter.")));
}
sqlx::query("INSERT INTO forum.topic_members (topic_id, user_id, note) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING")
.bind(id)
.bind(member.user_id)
.bind(&note)
.execute(&state.db)
.await?;
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
Ok(StatusCode::NO_CONTENT)
}
/// Leaving a restricted topic, or taking back the request.
pub async fn leave(
State(state): St,
viewer: Viewer,
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
sqlx::query(
"DELETE FROM forum.topic_members WHERE user_id = $1 AND topic_id = (SELECT id FROM forum.topics WHERE slug = $2)",
)
.bind(member.user_id)
.bind(&slug)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(sqlx::FromRow)]
struct RequestRow {
topic_slug: String,
topic_name: String,
user_id: Uuid,
status: String,
note: String,
requested_at: time::OffsetDateTime,
}
/// For moderators: who waits to join a restricted topic, and who is in.
pub async fn requests(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<RequestRow> = sqlx::query_as(
"SELECT tp.slug AS topic_slug, tp.name AS topic_name, tm.user_id, tm.status, tm.note, tm.requested_at \
FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id \
ORDER BY tm.status <> 'pending', tp.position, tm.requested_at",
)
.fetch_all(&state.db)
.await?;
let people = authors(&state.db, rows.iter().map(|r| r.user_id)).await?;
Ok(Json(json!({
"requests": rows.iter().map(|r| json!({
"topic": { "slug": r.topic_slug, "name": r.topic_name },
"member": people.get(&r.user_id),
"status": r.status,
"note": r.note,
"requested_at": rfc3339(r.requested_at),
})).collect::<Vec<_>>(),
})))
}
#[derive(Deserialize)]
pub struct Decision {
topic: String,
nickname: String,
/// `approve`, `reject` (a request) or `remove` (a member).
action: String,
}
/// A moderator approves or turns down a request, or removes a member.
pub async fn decide(
State(state): St,
viewer: Viewer,
WithRejection(Json(req), _): Body<Decision>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let found: Option<(i16, Uuid)> = sqlx::query_as(
"SELECT tp.id, m.user_id FROM forum.topics tp, forum.members m WHERE tp.slug = $1 AND m.nickname_key = $2",
)
.bind(&req.topic)
.bind(text::nickname_key(&req.nickname))
.fetch_optional(&state.db)
.await?;
let (topic, user) = found.ok_or(ApiError::NotFound("request"))?;
let mut tx = state.db.begin().await?;
let (done, action) = match req.action.as_str() {
"approve" => (
sqlx::query(
"UPDATE forum.topic_members SET status = 'approved', decided_at = now(), decided_by = $3 \
WHERE topic_id = $1 AND user_id = $2",
)
.bind(topic)
.bind(user)
.bind(moderator.id)
.execute(&mut *tx)
.await?,
Action::ApproveMember,
),
"reject" | "remove" => (
sqlx::query("DELETE FROM forum.topic_members WHERE topic_id = $1 AND user_id = $2")
.bind(topic)
.bind(user)
.execute(&mut *tx)
.await?,
if req.action == "reject" { Action::RejectMember } else { Action::RemoveMember },
),
_ => return Err(ApiError::bad("Ismeretlen döntés.")),
};
if done.rows_affected() == 0 {
return Err(ApiError::NotFound("request"));
}
moderation::record(&mut *tx, moderator.id, action, Some(user), None, None, Some(&req.topic), None).await?;
tx.commit().await?;
let event = crate::live::Event { moderators: true, ..Default::default() }.for_users(vec![user]);
crate::live::emit(&state.db, event).await;
Ok(StatusCode::NO_CONTENT)
}
+156 -2
View File
@@ -35,6 +35,7 @@ impl TestApp {
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: None,
};
Self { router: routes::router(Arc::new(state)), pool }
}
@@ -744,7 +745,11 @@ async fn instant_mails_and_unsubscribe(pool: PgPool) {
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
let me = app.get("/v1/forum/me", Some(&anna)).await;
assert_eq!(me["member"]["email"], json!({"replies": "daily", "followed": "off", "messages": "instant"}));
assert_eq!(
me["member"]["email"],
json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant",
"listener": "off", "weekly": false})
);
let (status, _) = app
.call(
"PUT",
@@ -845,7 +850,11 @@ async fn instant_mails_and_unsubscribe(pool: PgPool) {
let (status, _) = app.call("POST", &format!("/v1/forum/unsubscribe?token={token}"), None, Value::Null).await;
assert_eq!(status, StatusCode::OK);
let me = app.get("/v1/forum/me", Some(&anna)).await;
assert_eq!(me["member"]["email"], json!({"replies": "off", "followed": "off", "messages": "off"}));
assert_eq!(
me["member"]["email"],
json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off",
"listener": "off", "weekly": false})
);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -857,6 +866,7 @@ async fn live_doorbell_over_websocket(pool: PgPool) {
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: None,
});
tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone()));
let router = routes::router(state.clone());
@@ -924,3 +934,147 @@ async fn futures_next(
}
}
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn restricted_topics_by_approval(pool: PgPool) {
let app = TestApp::new(pool);
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
let moderator = app.member("mod@example.com", "Őrangyal", &["moderator"]).await;
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
// Only the admin opens topics.
let body =
json!({ "name": "Gyászolók köre", "description": "Akik elveszítettek valakit", "visibility": "restricted" });
assert_eq!(app.call("POST", "/v1/forum/topics", Some(&moderator), body.clone()).await.0, StatusCode::FORBIDDEN);
let (status, created) = app.call("POST", "/v1/forum/topics", Some(&admin), body).await;
assert_eq!(status, StatusCode::CREATED, "{created}");
assert_eq!(created["slug"], "gyaszolok-kore");
// Members see it by name and may ask to join; visitors do not see it.
let home = app.get("/v1/forum/home", Some(&anna)).await;
let topic = home["topics"].as_array().unwrap().iter().find(|t| t["slug"] == "gyaszolok-kore").unwrap().clone();
assert_eq!((topic["readable"].as_bool(), topic["membership"].as_str()), (Some(false), Some("none")));
assert!(
app.get("/v1/forum/home", None).await["topics"]
.as_array()
.unwrap()
.iter()
.all(|t| t["slug"] != "gyaszolok-kore")
);
let (status, _) = app.call("GET", "/v1/forum/topics/gyaszolok-kore", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::NOT_FOUND);
let (status, _) = app
.call(
"POST",
"/v1/forum/threads",
Some(&anna),
json!({ "topic": "gyaszolok-kore", "title": "Apukám", "body": "x" }),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let (status, _) = app
.call(
"POST",
"/v1/forum/topics/gyaszolok-kore/join",
Some(&anna),
json!({ "note": "Tavaly vesztettem el anyukámat." }),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 1, "the request shows for moderators");
// A moderator approves: now Anna reads and writes there, Bea still not.
let requests = app.get("/v1/forum/mod/topic-requests", Some(&moderator)).await;
assert_eq!(requests["requests"][0]["member"]["nickname"], "Csendesvíz");
assert_eq!(requests["requests"][0]["note"], "Tavaly vesztettem el anyukámat.");
let (status, _) = app
.call(
"POST",
"/v1/forum/mod/topic-requests",
Some(&moderator),
json!({ "topic": "gyaszolok-kore", "nickname": "Csendesvíz", "action": "approve" }),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
let thread = app.thread(&anna, "gyaszolok-kore", "Apukám emléke").await;
app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
let (status, _) = app.call("GET", &format!("/v1/forum/threads/{thread}"), Some(&bea), Value::Null).await;
assert_eq!(status, StatusCode::NOT_FOUND);
app.get(&format!("/v1/forum/threads/{thread}"), Some(&moderator)).await;
assert_eq!(app.get("/v1/forum/mod/log", Some(&moderator)).await["entries"][0]["action"], "approve_member");
// The admin renames it; the address stays.
let (status, _) = app
.call("PATCH", "/v1/forum/topics/gyaszolok-kore", Some(&admin), json!({ "name": "Gyász és emlékezés" }))
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(app.get("/v1/forum/topics/gyaszolok-kore", Some(&anna)).await["topic"]["name"], "Gyász és emlékezés");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn mentions_listeners_supporters_and_who_is_here(pool: PgPool) {
let app = TestApp::new(pool);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Hold fény", &["user"]).await;
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
// "@Hold fény" (with its space) names Bea: she follows the thread, it is new for her.
let thread = app.thread(&anna, "torzsasztal", "Téli levesek").await;
let post = app.reply(&cili, thread, "Szerinted, @Hold fény, mi a legjobb? És @Senki?", None).await;
assert_eq!(post["mentions"], json!(["Hold fény"]));
let followed = app.get("/v1/forum/followed", Some(&bea)).await;
assert_eq!(followed["threads"][0]["id"], thread);
let found = app.get("/v1/forum/members/search?q=hold", Some(&anna)).await;
assert_eq!(found["members"][0]["nickname"], "Hold fény");
// Listening volunteers: from the Kereső rank; they see what waits for a reply.
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Hold fény", "listener": true })).await;
assert_eq!(status, StatusCode::FORBIDDEN);
app.season(&bea, 5, 10).await;
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Hold fény", "listener": true })).await;
assert_eq!(status, StatusCode::OK);
let waiting = app.thread(&anna, "ami-a-szivemen-van", "Nehéz napok").await;
sqlx::query("UPDATE forum.threads SET created_at = now() - interval '2 hours' WHERE id = $1")
.bind(waiting)
.execute(&app.pool)
.await
.unwrap();
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["waiting"], 1);
assert!(app.get("/v1/forum/nav", Some(&cili)).await["waiting"].is_null());
let shown = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
assert!(shown["posts"].as_array().unwrap().iter().all(|p| p["author"]["supporter"] == false));
// The supporter badge: buyers only, and only when they switch it on.
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&cili), json!({ "nickname": "Zöldág", "supporter_badge": true })).await;
assert_eq!(status, StatusCode::FORBIDDEN);
sqlx::query("INSERT INTO package_orders (id, user_id, package, source, price_huf) VALUES ($1, $2, 'egyeni', 'stripe', 4900)")
.bind(Uuid::now_v7())
.bind(cili.id)
.execute(&app.pool)
.await
.unwrap();
assert_eq!(app.get("/v1/forum/me", Some(&cili)).await["can_supporter"], true);
let (status, _) =
app.call("PUT", "/v1/forum/me", Some(&cili), json!({ "nickname": "Zöldág", "supporter_badge": true })).await;
assert_eq!(status, StatusCode::OK);
let profile = app.get("/v1/forum/members/Zöldág", None).await;
assert_eq!(
(profile["member"]["author"]["supporter"].as_bool(), profile["member"]["author"]["listener"].as_bool()),
(Some(true), Some(false))
);
assert_eq!(app.get("/v1/forum/members/hold%20f%C3%A9ny", None).await["member"]["author"]["listener"], true);
// Who is here: the members seen in the last minutes, not the invisible.
app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "invisible": true })).await;
let here: Vec<String> = app.get("/v1/forum/home", None).await["online"]
.as_array()
.unwrap()
.iter()
.map(|m| m["nickname"].as_str().unwrap().to_string())
.collect();
assert!(here.contains(&"Zöldág".to_string()) && !here.contains(&"Csendesvíz".to_string()));
}