Forum: search, muting members, archived topics, the public threads in the sitemap

- Search (/forum/kereses, the magnifier in the forum bar): thread titles
  and posts the viewer may read, Hungarian stems and word beginnings
  without accents ("alvas" finds "alvásban"), one result per thread with
  the matching words marked.
- Muting a member (post menu, profile; the list in the settings): their
  threads leave the lists, their posts fold up, their replies and mentions
  no longer count or send e-mails. They are not told.
- The admin archives a topic (Moderálás → Témák): it stays readable but
  takes no new threads or replies, and folds away on the front page.
- The public topics and threads are in the sitemap; the forum's own pages
  are kept from robots.
- A reply e-mail goes to the one answered, also on the second level.
- Migration 0043 also prepares charts attached to a forum question.

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 14:31:05 +00:00
co-authored by Claude Opus 5.5
parent 4800a30e6d
commit 9ca3f478be
30 changed files with 879 additions and 105 deletions
+14 -5
View File
@@ -66,6 +66,8 @@ pub struct Viewer {
pub member: Option<Member>,
/// The restricted topics the member was approved into.
pub topics: Vec<i16>,
/// The members they muted.
pub mutes: Vec<Uuid>,
}
impl Viewer {
@@ -137,15 +139,22 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
.execute(&state.db)
.await?;
}
let topics = if member.is_some() {
sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'approved'")
let (topics, mutes) = if member.is_some() {
let topics = 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?;
let mutes = sqlx::query_scalar("SELECT muted_id FROM forum.mutes WHERE user_id = $1")
.bind(user.id)
.fetch_all(&state.db)
.await?
.await?;
(topics, mutes)
} else {
Vec::new()
(Vec::new(), Vec::new())
};
Ok(Viewer { user: Some(user), member, topics })
Ok(Viewer { user: Some(user), member, topics, mutes })
}
}
+3
View File
@@ -78,6 +78,7 @@ async fn reply_mails(
WHERE m.email_replies = 'instant' AND m.user_id <> $1 AND {OFFLINE} \
AND m.user_id IN (SELECT author_id FROM forum.threads WHERE id = $2 \
UNION SELECT author_id FROM forum.posts WHERE id = $3) \
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = m.user_id AND mu.muted_id = $1) \
AND NOT EXISTS (SELECT 1 FROM email_outbox e \
WHERE e.user_id = m.user_id AND e.template = 'forum_reply' \
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
@@ -226,12 +227,14 @@ pub async fn after_mention(state: &AppState, thread_id: i64, post_id: i64, autho
"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 forum.mutes mu WHERE mu.user_id = m.user_id AND mu.muted_id = $3) \
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)
.bind(author)
.fetch_all(&state.db)
.await?;
if recipients.is_empty() {
+17 -11
View File
@@ -27,6 +27,7 @@ struct TopicRow {
description: String,
visibility: String,
listening: bool,
archived: bool,
thread_count: i64,
new_count: Option<i64>,
last_author: Option<Uuid>,
@@ -39,6 +40,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
let (me, since) = card_params(viewer);
let rows: Vec<TopicRow> = sqlx::query_as(
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \
tp.archived_at IS NOT NULL AS archived, \
(SELECT count(*) FROM forum.threads th WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) AS thread_count, \
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
(SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
@@ -93,6 +95,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
"description": r.description,
"visibility": r.visibility,
"listening": r.listening,
"archived": r.archived,
"readable": readable,
"membership": membership,
});
@@ -138,7 +141,7 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
let followed = followed_counts(&state, &viewer).await?;
let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 \
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 AND tp.archived_at IS NULL \
AND th.created_at > now() - make_interval(days => $3) \
ORDER BY th.created_at LIMIT 3",
card_sql(&viewer)
@@ -153,7 +156,7 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
GROUP BY thread_id HAVING count(*) >= $3) \
{} AND th.id IN (SELECT thread_id FROM recent) \
{} AND th.id IN (SELECT thread_id FROM recent) AND tp.archived_at IS NULL \
ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5",
card_sql(&viewer)
))
@@ -172,7 +175,8 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
.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();
let online: Vec<Value> =
present.iter().filter(|id| !viewer.mutes.contains(id)).filter_map(|id| people.get(id).cloned()).collect();
// Volunteer listeners: threads asking to be heard, still without a reply.
let waiting = match &viewer.member {
@@ -203,6 +207,7 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \
JOIN forum.posts p ON p.thread_id = f.thread_id AND p.deleted_at IS NULL \
WHERE f.user_id = $1 AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2 \
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = p.author_id) \
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
WHERE r.user_id = $1 AND r.thread_id = f.thread_id), 0)",
)
@@ -217,7 +222,7 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
/// 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)";
AND (th.intent = 'listen' OR tp.listening) AND tp.archived_at IS NULL";
async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult<i64> {
let me = viewer.user_id();
@@ -275,12 +280,13 @@ pub async fn topic(
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let topic: Option<(i16, String, String, String, bool)> =
sqlx::query_as("SELECT id, name, description, visibility, listening FROM forum.topics WHERE slug = $1")
.bind(&slug)
.fetch_optional(&state.db)
.await?;
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?;
let topic: Option<(i16, String, String, String, bool, bool)> = sqlx::query_as(
"SELECT id, name, description, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1",
)
.bind(&slug)
.fetch_optional(&state.db)
.await?;
let (id, name, description, visibility, listening, archived) = topic.ok_or(ApiError::NotFound("topic"))?;
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") });
@@ -304,7 +310,7 @@ pub async fn topic(
"viewer": viewer_json(&viewer),
"topic": {
"slug": slug, "name": name, "description": description,
"visibility": visibility, "listening": listening,
"visibility": visibility, "listening": listening, "archived": archived,
},
"threads": cards_json(&state.db, rows).await?,
"page": page,
+1
View File
@@ -405,6 +405,7 @@ pub async fn profile(
"thread_count": thread_count,
"last_seen": last_seen,
"own": own,
"muted": viewer.mutes.contains(&row.user_id),
"banned_until": banned.filter(|_| show_ban).map(|u| {
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
}),
+16 -3
View File
@@ -11,9 +11,11 @@ mod members;
mod mentions;
mod messages;
mod moderation;
mod mutes;
mod posts;
mod replies;
mod reports;
mod search;
mod threads;
mod topics;
@@ -50,6 +52,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
.route("/v1/forum/followed", get(home::followed))
.route("/v1/forum/replies", get(replies::list))
.route("/v1/forum/search", get(search::search))
.route("/v1/forum/sitemap", get(search::sitemap))
.route("/v1/forum/replies/read", post(replies::read_all))
.route("/v1/forum/threads", post(threads::create))
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
@@ -83,6 +87,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.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}/mute", put(mutes::mute).delete(mutes::unmute))
.route("/v1/forum/me/mutes", get(mutes::list))
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log))
.route("/v1/forum/mod/reports", get(reports::list))
@@ -149,6 +155,11 @@ pub struct CardRow {
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
/// the member's user id and `$2` when they joined (both NULL for a visitor),
/// so the caller's own parameters start at `$3`. Append `AND …`, `ORDER BY`, `LIMIT`.
/// `col` (an author) is not muted by the viewer, `$1` (true for visitors).
pub fn not_muted(col: &str) -> String {
format!("NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = {col})")
}
pub fn card_sql(viewer: &Viewer) -> String {
format!(
"SELECT th.id, th.title, th.intent, th.author_id, th.created_at, th.last_post_at, th.reply_count, \
@@ -158,13 +169,15 @@ pub fn card_sql(viewer: &Viewer) -> String {
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
(SELECT count(*) FROM forum.posts p \
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.created_at > $2::timestamptz AND {} \
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, \
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)
WHERE th.deleted_at IS NULL AND ({}) AND {}",
not_muted("p.author_id"),
visible_topics(viewer),
not_muted("th.author_id"),
)
}
+67
View File
@@ -0,0 +1,67 @@
//! "Némítás": a member mutes another. The muted member's threads leave the
//! muter's lists, their posts fold up (one click shows them), their replies
//! and mentions no longer notify, and they drop out of "Most itt vannak".
//! The muted member is not told, and can still be reported.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use serde_json::{Value, json};
use uuid::Uuid;
use super::{St, authors};
use crate::AppState;
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
async fn member_id(state: &AppState, nickname: &str) -> ApiResult<Uuid> {
sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
.bind(text::nickname_key(nickname))
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("member"))
}
pub async fn mute(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
let target = member_id(&state, &nickname).await?;
if target == member.user_id {
return Err(ApiError::bad("Saját magadat nem némíthatod el."));
}
sqlx::query("INSERT INTO forum.mutes (user_id, muted_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(member.user_id)
.bind(target)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn unmute(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
let target = member_id(&state, &nickname).await?;
sqlx::query("DELETE FROM forum.mutes WHERE user_id = $1 AND muted_id = $2")
.bind(member.user_id)
.bind(target)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
/// The members the viewer muted (for the settings page).
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_member()?;
let people = authors(&state.db, viewer.mutes.iter().copied()).await?;
let mut muted: Vec<Value> = viewer.mutes.iter().filter_map(|id| people.get(id).cloned()).collect();
muted.sort_by(|a, b| a["nickname"].as_str().cmp(&b["nickname"].as_str()));
Ok(Json(json!({ "muted": muted })))
}
+1
View File
@@ -28,6 +28,7 @@ fn answers(viewer: &Viewer) -> String {
LEFT JOIN forum.reads r ON r.user_id = $1 AND r.thread_id = p.thread_id \
WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND NOT p.is_opening AND NOT p.system \
AND p.author_id IS DISTINCT FROM $1 AND ({}) \
AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = p.author_id) \
AND (target.author_id = $1 \
OR (p.parent_id IS NULL AND th.author_id = $1) \
OR EXISTS (SELECT 1 FROM forum.mentions mn WHERE mn.post_id = p.id AND mn.user_id = $1))",
+139
View File
@@ -0,0 +1,139 @@
//! Search in what the viewer may read: thread titles and posts, with
//! Hungarian stems ("szálak" finds "szál") and without accents ("alvas"
//! finds "alvás"). One result per thread, with the best matching post's
//! words marked; muted members are left out.
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::{St, authors, not_muted, rfc3339, visible_topics};
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
#[derive(Deserialize)]
pub struct SearchQuery {
#[serde(default)]
q: Option<String>,
#[serde(default)]
page: Option<i64>,
}
#[derive(sqlx::FromRow)]
struct Hit {
id: i64,
title: String,
topic_slug: String,
topic_name: String,
author_id: Option<Uuid>,
last_post_at: OffsetDateTime,
reply_count: i32,
post_id: Option<i64>,
snippet: Option<String>,
}
const PAGE: i64 = 20;
/// Around the matching words in `snippet` (the page marks them).
pub const MARK_START: &str = "⟦";
pub const MARK_END: &str = "⟧";
pub async fn search(
State(state): St,
viewer: Viewer,
WithRejection(Query(q), _): WithRejection<Query<SearchQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let query: String = q.q.unwrap_or_default().trim().chars().take(100).collect();
let page = q.page.unwrap_or(1).clamp(1, 50);
if query.chars().count() < 2 {
return Ok(Json(json!({ "query": query, "results": [], "more": false, "page": page })));
}
// Word beginnings without accents too: "alvas" finds "alvásban".
let prefixes: Vec<String> = query
.split(|c: char| !c.is_alphanumeric())
.filter(|w| w.chars().count() >= 3)
.take(8)
.map(|w| format!("{w}:*"))
.collect();
let rows: Vec<Hit> = sqlx::query_as(&format!(
"WITH q AS (SELECT websearch_to_tsquery('hungarian', $2) || to_tsquery('forum.plain', $6) AS q), \
hits AS (SELECT p.thread_id, p.id, p.body, ts_rank(p.search, q.q) AS rank FROM forum.posts p, q \
WHERE p.search @@ q.q AND p.deleted_at IS NULL AND {posts_ok}) \
SELECT th.id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, th.author_id, th.last_post_at, \
th.reply_count, best.id AS post_id, \
CASE WHEN best.id IS NULL THEN NULL ELSE ts_headline('hungarian', best.body, q.q, $5) END AS snippet \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id CROSS JOIN q \
LEFT JOIN LATERAL (SELECT h.id, h.body, h.rank FROM hits h WHERE h.thread_id = th.id \
ORDER BY h.rank DESC, h.id LIMIT 1) best ON true \
WHERE th.deleted_at IS NULL AND ({visible}) AND {threads_ok} \
AND (th.search @@ q.q OR th.id IN (SELECT thread_id FROM hits)) \
ORDER BY (CASE WHEN th.search @@ q.q THEN 2 * ts_rank(th.search, q.q) ELSE 0 END + COALESCE(best.rank, 0)) DESC, \
th.last_post_at DESC \
LIMIT $3 OFFSET $4",
posts_ok = not_muted("p.author_id"),
visible = visible_topics(&viewer),
threads_ok = not_muted("th.author_id"),
))
.bind(viewer.user_id())
.bind(&query)
.bind(PAGE + 1)
.bind((page - 1) * PAGE)
.bind(format!(
"StartSel={MARK_START}, StopSel={MARK_END}, MaxWords=30, MinWords=12, ShortWord=2, MaxFragments=1"
))
.bind(prefixes.join(" & "))
.fetch_all(&state.db)
.await?;
let more = rows.len() as i64 > PAGE;
let rows = &rows[..rows.len().min(PAGE as usize)];
let people = authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?;
let results: Vec<Value> = rows
.iter()
.map(|r| {
json!({
"thread": { "id": r.id, "title": r.title, "slug": text::slug(&r.title) },
"topic": { "slug": r.topic_slug, "name": r.topic_name },
"author": r.author_id.and_then(|a| people.get(&a).cloned()),
"last_post_at": rfc3339(r.last_post_at),
"reply_count": r.reply_count,
"post_id": r.post_id,
"snippet": r.snippet,
})
})
.collect();
Ok(Json(json!({ "query": query, "results": results, "more": more, "page": page })))
}
#[derive(sqlx::FromRow)]
struct MapThread {
id: i64,
title: String,
last_post_at: OffsetDateTime,
}
/// For the sitemap: the public topics and their threads (newest activity first).
pub async fn sitemap(State(state): St) -> ApiResult<Json<Value>> {
let topics: Vec<(String, Option<OffsetDateTime>)> = sqlx::query_as(
"SELECT tp.slug, (SELECT max(th.last_post_at) FROM forum.threads th \
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) \
FROM forum.topics tp WHERE tp.visibility = 'public' ORDER BY tp.position",
)
.fetch_all(&state.db)
.await?;
let threads: Vec<MapThread> = sqlx::query_as(
"SELECT th.id, th.title, th.last_post_at FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE tp.visibility = 'public' AND th.deleted_at IS NULL ORDER BY th.last_post_at DESC LIMIT 5000",
)
.fetch_all(&state.db)
.await?;
Ok(Json(json!({
"topics": topics.iter().map(|(slug, at)| json!({ "slug": slug, "updated": at.map(rfc3339) })).collect::<Vec<_>>(),
"threads": threads.iter().map(|t| json!({
"id": t.id, "slug": text::slug(&t.title), "updated": rfc3339(t.last_post_at),
})).collect::<Vec<_>>(),
})))
}
+20 -9
View File
@@ -42,11 +42,13 @@ pub struct ThreadRow {
pub deleted_at: Option<OffsetDateTime>,
pub delete_reason: Option<String>,
pub system: bool,
/// Its topic is archived: readable, but takes nothing new.
pub archived: bool,
}
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.system \
th.delete_reason, th.system, tp.archived_at IS NOT NULL AS archived \
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
@@ -63,13 +65,16 @@ pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult
Ok(thread)
}
/// A thread that can take new posts and reactions: not removed, and not
/// locked (moderators may still write in a locked one).
/// A thread that can take new posts and reactions: not removed, not in an
/// archived topic, and not locked (moderators may still write in a locked one).
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
let thread = readable_thread(db, viewer, id).await?;
if thread.deleted_at.is_some() {
return Err(ApiError::NotFound("thread"));
}
if thread.archived {
return Err(ApiError::Forbidden("Ez a téma archivált: olvasható, de új hozzászólás nem írható.".into()));
}
if thread.locked && !viewer.is_moderator() {
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into()));
}
@@ -180,6 +185,8 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
"mentions": mentions,
"system": p.system,
"reply_to": reply_to,
// The viewer muted the author: the page folds it up.
"muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)),
});
if moderator {
post["down"] = json!(down);
@@ -229,7 +236,7 @@ pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _):
None => (false, None),
};
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
let open = thread.deleted_at.is_none() && (!thread.locked || moderator);
let open = thread.deleted_at.is_none() && !thread.archived && (!thread.locked || moderator);
out["access"] = json!({
"can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()),
"can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()),
@@ -248,7 +255,7 @@ fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
"intent": thread.intent,
"topic": {
"slug": thread.topic_slug, "name": thread.topic_name,
"visibility": thread.visibility, "listening": thread.listening,
"visibility": thread.visibility, "listening": thread.listening, "archived": thread.archived,
},
"author": author,
"created_at": rfc3339(thread.created_at),
@@ -317,12 +324,15 @@ pub async fn create(
WithRejection(Json(req), _): Body<CreateThread>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?;
let topic: Option<(i16, String, bool)> =
sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1")
let topic: Option<(i16, String, bool, bool)> =
sqlx::query_as("SELECT id, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1")
.bind(&req.topic)
.fetch_optional(&state.db)
.await?;
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
let (topic_id, visibility, listening, archived) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
if archived {
return Err(ApiError::bad("Ez a téma archivált, új szál nem nyitható benne."));
}
if !may_read(&viewer, &visibility, topic_id) {
return Err(ApiError::bad("Ismeretlen téma."));
}
@@ -458,7 +468,8 @@ pub async fn reply(
.await?;
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;
// The one answered hears of it (on the second level, not the branch's first post).
crate::mail::after_reply(&state, id, post.id, member.user_id, post.reply_to_id.or(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))
+13 -2
View File
@@ -107,6 +107,9 @@ pub struct TopicChange {
listening: Option<bool>,
#[serde(default)]
position: Option<i16>,
/// Archive (true) or bring back (false).
#[serde(default)]
archived: Option<bool>,
}
/// The admin renames, describes, moves or changes the visibility of a topic
@@ -125,7 +128,10 @@ pub async fn update(
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",
position = COALESCE($6, position), \
archived_at = CASE WHEN $7::boolean IS NULL THEN archived_at \
WHEN $7 THEN COALESCE(archived_at, now()) ELSE NULL END \
WHERE slug = $1",
)
.bind(&slug)
.bind(&name)
@@ -133,6 +139,7 @@ pub async fn update(
.bind(&visibility)
.bind(req.listening)
.bind(req.position)
.bind(req.archived)
.execute(&mut *tx)
.await?;
if changed.rows_affected() == 0 {
@@ -145,7 +152,11 @@ pub async fn update(
None,
None,
None,
Some(&format!("téma módosítva: {slug}")),
Some(&match req.archived {
Some(true) => format!("téma archiválva: {slug}"),
Some(false) => format!("téma visszaállítva: {slug}"),
None => format!("téma módosítva: {slug}"),
}),
None,
)
.await?;
+79
View File
@@ -1130,3 +1130,82 @@ async fn answers_to_the_member(pool: PgPool) {
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["replies"], 0);
assert_eq!(answers(app.get("/v1/forum/replies", Some(&bea)).await).len(), 2, "the list stays");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn search_mutes_and_archived_topics(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", "Holdfény", &["user"]).await;
let admin = app.member("admin@example.com", "Gazda", &["user", "admin"]).await;
let found = |v: Value| -> Vec<i64> {
let mut ids: Vec<i64> =
v["results"].as_array().unwrap().iter().map(|r| r["thread"]["id"].as_i64().unwrap()).collect();
ids.sort();
ids
};
// Search: word beginnings without accents, titles, and only what one may read.
let sleep = app.thread(&anna, "torzsasztal", "Nehezen alszom").await;
app.reply(&bea, sleep, "Nekem az esti séták segítettek az alvásban.", None).await;
let hidden = app.thread(&anna, "ami-a-szivemen-van", "Alvászavar titokban").await;
assert_eq!(found(app.get("/v1/forum/search?q=alvas", None).await), vec![sleep], "a visitor: public topics");
assert_eq!(found(app.get("/v1/forum/search?q=alv%C3%A1s", Some(&anna)).await), vec![sleep, hidden]);
let hit = app.get("/v1/forum/search?q=s%C3%A9t%C3%A1k", None).await;
assert!(hit["results"][0]["snippet"].as_str().unwrap().contains("⟦séták⟧"), "{hit}");
assert!(found(app.get("/v1/forum/search?q=a", None).await).is_empty(), "too short");
let map = app.get("/v1/forum/sitemap", None).await;
let mapped: Vec<i64> = map["threads"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect();
assert_eq!(mapped, vec![sleep], "public threads only");
// Muting Bea: her threads leave Anna's lists, her posts fold up, her
// answers stop counting, and search leaves her out. She is not told.
let soups = app.thread(&bea, "torzsasztal", "Téli levesek").await;
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 1);
let (status, _) = app.call("PUT", "/v1/forum/members/Holdf%C3%A9ny/mute", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::NO_CONTENT);
let listed = app.get("/v1/forum/topics/torzsasztal", Some(&anna)).await;
assert!(listed["threads"].as_array().unwrap().iter().all(|t| t["id"] != soups));
let thread = app.get(&format!("/v1/forum/threads/{sleep}"), Some(&anna)).await;
assert_eq!(thread["posts"][1]["muted"], true);
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 0);
assert!(found(app.get("/v1/forum/search?q=s%C3%A9t%C3%A1k", Some(&anna)).await).is_empty());
assert_eq!(app.get("/v1/forum/me/mutes", Some(&anna)).await["muted"][0]["nickname"], "Holdfény");
assert_eq!(app.get("/v1/forum/members/Holdf%C3%A9ny", Some(&anna)).await["member"]["muted"], true);
assert_eq!(app.get(&format!("/v1/forum/threads/{sleep}"), Some(&bea)).await["posts"][0]["muted"], false);
let (status, _) = app.call("PUT", "/v1/forum/members/Csendesv%C3%ADz/mute", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "not oneself");
let (status, _) = app.call("DELETE", "/v1/forum/members/Holdf%C3%A9ny/mute", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 1);
// Archiving the topic: readable, but nothing new; brought back, it works again.
let (status, _) =
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": true })).await;
assert_eq!(status, StatusCode::NO_CONTENT);
let topic = app.get("/v1/forum/topics/torzsasztal", Some(&anna)).await;
assert_eq!(topic["topic"]["archived"], true);
let thread = app.get(&format!("/v1/forum/threads/{sleep}"), Some(&anna)).await;
assert_eq!(thread["access"]["can_reply"], false);
assert_eq!(thread["thread"]["topic"]["archived"], true);
let (status, _) = app
.call("POST", &format!("/v1/forum/threads/{sleep}/posts"), Some(&bea), json!({ "body": "Még egy szó." }))
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let (status, _) = app
.call(
"POST",
"/v1/forum/threads",
Some(&anna),
json!({ "topic": "torzsasztal", "title": "Új", "body": "Szia" }),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let home = app.get("/v1/forum/home", Some(&anna)).await;
let archived = home["topics"].as_array().unwrap().iter().find(|t| t["slug"] == "torzsasztal").unwrap();
assert_eq!(archived["archived"], true);
let (status, _) =
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&anna), json!({ "archived": false })).await;
assert_eq!(status, StatusCode::FORBIDDEN, "admins only");
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": false })).await;
app.reply(&bea, sleep, "Még egy szó.", None).await;
}