diff --git a/crates/db/migrations/0043_forum_search_mutes_archive_charts.sql b/crates/db/migrations/0043_forum_search_mutes_archive_charts.sql
new file mode 100644
index 0000000..72f382e
--- /dev/null
+++ b/crates/db/migrations/0043_forum_search_mutes_archive_charts.sql
@@ -0,0 +1,52 @@
+-- Forum: archived topics, muted members, search, and charts attached to a
+-- question.
+
+-- An archived topic stays readable at its address, but takes no new threads
+-- or replies, and leaves the front page lists.
+ALTER TABLE forum.topics ADD COLUMN archived_at timestamptz;
+
+-- "Némítás": the muted member's threads leave the lists, their posts fold
+-- up, and their replies and mentions no longer notify. They are not told.
+CREATE TABLE forum.mutes (
+ user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ muted_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (user_id, muted_id),
+ CHECK (user_id <> muted_id)
+);
+
+-- Search: Hungarian stems (szálak → szál), and the words without accents
+-- too, so "alvas" finds "alvás".
+CREATE EXTENSION IF NOT EXISTS unaccent;
+CREATE TEXT SEARCH CONFIGURATION forum.plain (COPY = simple);
+ALTER TEXT SEARCH CONFIGURATION forum.plain ALTER MAPPING FOR hword, hword_part, word WITH unaccent, simple;
+
+ALTER TABLE forum.threads ADD COLUMN search tsvector GENERATED ALWAYS AS (
+ to_tsvector('hungarian'::regconfig, title) || to_tsvector('forum.plain'::regconfig, title)
+) STORED;
+ALTER TABLE forum.posts ADD COLUMN search tsvector GENERATED ALWAYS AS (
+ to_tsvector('hungarian'::regconfig, body) || to_tsvector('forum.plain'::regconfig, body)
+) STORED;
+CREATE INDEX threads_search_idx ON forum.threads USING gin (search);
+CREATE INDEX posts_search_idx ON forum.posts USING gin (search);
+
+-- A question about one's own chart, forecast or synastry: the opening post
+-- carries a share made for the forum (see below), shown to members only.
+ALTER TABLE forum.posts ADD COLUMN share_id uuid REFERENCES shares ON DELETE SET NULL;
+
+-- Shares made for the forum: never birth data, and the public view leaves
+-- out the chart names (they may be real names next to a nickname).
+ALTER TABLE shares ADD COLUMN for_forum boolean NOT NULL DEFAULT false;
+
+-- A yearly forecast can be shared too (its calculation, and the detailed
+-- text if there is one), without the place of the birthday.
+ALTER TABLE shares ADD COLUMN forecast_id uuid REFERENCES forecasts ON DELETE CASCADE;
+ALTER TABLE shares DROP CONSTRAINT shares_kind_check;
+ALTER TABLE shares ADD CONSTRAINT shares_kind_check CHECK (kind IN ('chart', 'synastry', 'analysis', 'forecast'));
+ALTER TABLE shares DROP CONSTRAINT shares_target;
+ALTER TABLE shares ADD CONSTRAINT shares_target CHECK (
+ (kind = 'chart' AND chart_id IS NOT NULL AND synastry_id IS NULL AND analysis_id IS NULL AND forecast_id IS NULL)
+ OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND analysis_id IS NULL AND forecast_id IS NULL)
+ OR (kind = 'analysis' AND analysis_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL)
+ OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND analysis_id IS NULL)
+);
diff --git a/services/forum/src/auth.rs b/services/forum/src/auth.rs
index 645a647..8d34536 100644
--- a/services/forum/src/auth.rs
+++ b/services/forum/src/auth.rs
@@ -66,6 +66,8 @@ pub struct Viewer {
pub member: Option,
/// The restricted topics the member was approved into.
pub topics: Vec,
+ /// The members they muted.
+ pub mutes: Vec,
}
impl Viewer {
@@ -137,15 +139,22 @@ impl FromRequestParts> 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 })
}
}
diff --git a/services/forum/src/mail.rs b/services/forum/src/mail.rs
index d7b6303..fe42318 100644
--- a/services/forum/src/mail.rs
+++ b/services/forum/src/mail.rs
@@ -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() {
diff --git a/services/forum/src/routes/home.rs b/services/forum/src/routes/home.rs
index 140fe11..9f6215b 100644
--- a/services/forum/src/routes/home.rs
+++ b/services/forum/src/routes/home.rs
@@ -27,6 +27,7 @@ struct TopicRow {
description: String,
visibility: String,
listening: bool,
+ archived: bool,
thread_count: i64,
new_count: Option,
last_author: Option,
@@ -39,6 +40,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult> {
let (me, since) = card_params(viewer);
let rows: Vec = 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> {
"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> {
let followed = followed_counts(&state, &viewer).await?;
let unanswered: Vec = 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> {
"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> {
.fetch_all(&state.db)
.await?;
let people = super::authors(&state.db, present.iter().copied()).await?;
- let online: Vec = present.iter().filter_map(|id| people.get(id).cloned()).collect();
+ let online: Vec =
+ 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
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
/// 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 {
let me = viewer.user_id();
@@ -275,12 +280,13 @@ pub async fn topic(
WithRejection(Path(slug), _): WithRejection, ApiError>,
WithRejection(Query(q), _): WithRejection, ApiError>,
) -> ApiResult> {
- 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,
diff --git a/services/forum/src/routes/members.rs b/services/forum/src/routes/members.rs
index 1654892..2cc34a2 100644
--- a/services/forum/src/routes/members.rs
+++ b/services/forum/src/routes/members.rs
@@ -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) }
}),
diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs
index 626011d..d1ebcc4 100644
--- a/services/forum/src/routes/mod.rs
+++ b/services/forum/src/routes/mod.rs
@@ -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) -> 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) -> 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"),
)
}
diff --git a/services/forum/src/routes/mutes.rs b/services/forum/src/routes/mutes.rs
new file mode 100644
index 0000000..901e96c
--- /dev/null
+++ b/services/forum/src/routes/mutes.rs
@@ -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 {
+ 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, ApiError>,
+) -> ApiResult {
+ 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, ApiError>,
+) -> ApiResult {
+ 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> {
+ viewer.require_member()?;
+ let people = authors(&state.db, viewer.mutes.iter().copied()).await?;
+ let mut muted: Vec = 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 })))
+}
diff --git a/services/forum/src/routes/replies.rs b/services/forum/src/routes/replies.rs
index 97466b7..b461830 100644
--- a/services/forum/src/routes/replies.rs
+++ b/services/forum/src/routes/replies.rs
@@ -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))",
diff --git a/services/forum/src/routes/search.rs b/services/forum/src/routes/search.rs
new file mode 100644
index 0000000..db8f283
--- /dev/null
+++ b/services/forum/src/routes/search.rs
@@ -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,
+ #[serde(default)]
+ page: Option,
+}
+
+#[derive(sqlx::FromRow)]
+struct Hit {
+ id: i64,
+ title: String,
+ topic_slug: String,
+ topic_name: String,
+ author_id: Option,
+ last_post_at: OffsetDateTime,
+ reply_count: i32,
+ post_id: Option,
+ snippet: Option,
+}
+
+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, ApiError>,
+) -> ApiResult> {
+ 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 = query
+ .split(|c: char| !c.is_alphanumeric())
+ .filter(|w| w.chars().count() >= 3)
+ .take(8)
+ .map(|w| format!("{w}:*"))
+ .collect();
+ let rows: Vec = 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 = 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> {
+ let topics: Vec<(String, Option)> = 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 = 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::>(),
+ "threads": threads.iter().map(|t| json!({
+ "id": t.id, "slug": text::slug(&t.title), "updated": rfc3339(t.last_post_at),
+ })).collect::>(),
+ })))
+}
diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs
index 81ddb74..3b59831 100644
--- a/services/forum/src/routes/threads.rs
+++ b/services/forum/src/routes/threads.rs
@@ -42,11 +42,13 @@ pub struct ThreadRow {
pub deleted_at: Option,
pub delete_reason: Option,
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 {
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 {
"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,
) -> ApiResult<(StatusCode, Json)> {
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))
diff --git a/services/forum/src/routes/topics.rs b/services/forum/src/routes/topics.rs
index 00ca400..9e9c44f 100644
--- a/services/forum/src/routes/topics.rs
+++ b/services/forum/src/routes/topics.rs
@@ -107,6 +107,9 @@ pub struct TopicChange {
listening: Option,
#[serde(default)]
position: Option,
+ /// Archive (true) or bring back (false).
+ #[serde(default)]
+ archived: Option,
}
/// 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?;
diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs
index eebfe76..4253079 100644
--- a/services/forum/src/tests.rs
+++ b/services/forum/src/tests.rs
@@ -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 {
+ let mut ids: Vec =
+ 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 = 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;
+}
diff --git a/services/frontend/src/app/forum/[tema]/page.tsx b/services/frontend/src/app/forum/[tema]/page.tsx
index 6281daa..e75576e 100644
--- a/services/frontend/src/app/forum/[tema]/page.tsx
+++ b/services/frontend/src/app/forum/[tema]/page.tsx
@@ -60,13 +60,24 @@ export default async function TopicPageView({ params, searchParams }: Props) {
: "Zárt kör: ezt a témát csak a jóváhagyott tagjai látják."}
)}
+ {topic.archived && (
+
+
+
+
+
+ Archivált téma: a szálak olvashatók, de új szál és hozzászólás már nem írható.
+
+ )}
-
- Új szál
-
+ {!topic.archived && (
+
+ Új szál
+
+ )}
{threads.length === 0 ? (
Ebben a témában még nincs szál. Nyisd meg te az elsőt!
diff --git a/services/frontend/src/app/forum/beallitasok/MutedList.tsx b/services/frontend/src/app/forum/beallitasok/MutedList.tsx
new file mode 100644
index 0000000..7e38939
--- /dev/null
+++ b/services/frontend/src/app/forum/beallitasok/MutedList.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import { Avatar } from "@/components/forum/Avatar";
+import { api } from "@/lib/api";
+import type { ForumAuthor } from "@/lib/forum";
+
+/** The members the viewer muted, each with "Feloldás". */
+export function MutedList() {
+ const [muted, setMuted] = useState(null);
+ useEffect(() => {
+ api<{ muted: ForumAuthor[] }>("/forum/me/mutes")
+ .then((res) => setMuted(res.muted))
+ .catch(() => setMuted([]));
+ }, []);
+ if (!muted || muted.length === 0) return null;
+ return (
+
+ Elnémított tagok
+
+ {muted.map((m) => (
+
+
+
+ {m.nickname}
+
+ {
+ await api(`/forum/members/${encodeURIComponent(m.nickname)}/mute`, { method: "DELETE" });
+ setMuted((list) => (list ?? []).filter((x) => x.nickname !== m.nickname));
+ }}
+ >
+ Feloldás
+
+
+ ))}
+
+
+ Az elnémított tagok szálai nem jelennek meg a listáidban, és nem kapsz értesítést tőlük.
+
+
+ );
+}
diff --git a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx
index 60ed1e2..4724d8f 100644
--- a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx
+++ b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx
@@ -9,6 +9,8 @@ import { api, errorText } from "@/lib/api";
import { withEmoji } from "@/lib/emoticons";
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
+import { MutedList } from "./MutedList";
+
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
{ value: "none", label: "Semmit" },
{ value: "sun", label: "Csak a Nap-jegyemet" },
@@ -347,6 +349,8 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
+ {member && }
+
{member && (
Rangod
diff --git a/services/frontend/src/app/forum/forum.css b/services/frontend/src/app/forum/forum.css
index 3be9797..3467027 100644
--- a/services/frontend/src/app/forum/forum.css
+++ b/services/frontend/src/app/forum/forum.css
@@ -86,6 +86,8 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
.forum-theme:hover { color: var(--gold); border-color: var(--f-border-hover); }
.forum-theme svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.forum-theme-label { display: none; }
+.forum-tools { display: flex; align-items: center; gap: 8px; }
+.forum-search { padding: 0; width: 44px; }
/* The forum's menu: a bar at the bottom on phones, tabs in the forum bar on wider screens. */
.forum-nav {
@@ -121,6 +123,7 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
.fn-item[aria-current="page"] { background: var(--f-tint); }
.fn-icon { width: 20px; height: 20px; }
.forum-theme { padding: 0 14px; }
+ .forum-search { padding: 0; }
.forum-theme-label { display: inline; }
}
@@ -660,3 +663,27 @@ a.fh-online-item:hover { color: var(--gold); }
/* The same row at the foot of a card, or framed inside one. */
.fh-link-foot { margin: 14px -18px -18px; border-top: 1px solid var(--line); border-radius: 0 0 16px 16px; }
.fh-link-boxed { min-height: 52px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 12px; }
+
+/* --- search --- */
+.fsearch-form { display: flex; gap: 8px; }
+.fsearch-form .inp { flex: 1; min-width: 0; }
+.fsearch-results { list-style: none; margin: 0; padding: 0; }
+.fsearch-results li + li { border-top: 1px solid var(--line); }
+.fsearch-hit { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; color: var(--ink); text-decoration: none; }
+.fsearch-hit:hover { background: var(--f-hover); }
+.fsearch-title { font-size: 17px; font-weight: 600; }
+.fsearch-meta { font-size: 13px; color: var(--muted); }
+.fsearch-snippet { font-size: 15px; color: var(--ink-2); }
+.fsearch-snippet mark { background: var(--f-tint-strong); color: var(--ink); border-radius: 3px; padding: 0 2px; }
+
+/* --- muted members --- */
+.fp-muted { padding: 4px 0; }
+.fmute { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
+.fmuted { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.fmuted li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
+
+/* --- archived topics --- */
+.fh-archived { margin-top: 10px; }
+.fh-archived summary { min-height: 44px; display: flex; align-items: center; color: var(--ink-2); font-size: 15px; cursor: pointer; }
+.fh-archived .fh-links { list-style: none; margin: 0; padding: 0; }
+.fh-archived li + li .fh-link { border-top: 1px solid var(--line); }
diff --git a/services/frontend/src/app/forum/kereses/page.tsx b/services/frontend/src/app/forum/kereses/page.tsx
new file mode 100644
index 0000000..1949e45
--- /dev/null
+++ b/services/frontend/src/app/forum/kereses/page.tsx
@@ -0,0 +1,103 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+
+import { ago, threadHref } from "@/lib/forum";
+import { forumGet } from "@/lib/forumServer";
+
+export const metadata: Metadata = { title: "Keresés a fórumban", robots: { index: false, follow: true } };
+
+interface SearchResult {
+ thread: { id: number; title: string; slug: string };
+ topic: { slug: string; name: string };
+ author: { nickname: string } | null;
+ last_post_at: string;
+ reply_count: number;
+ post_id: number | null;
+ /** The matching words between ⟦ and ⟧. */
+ snippet: string | null;
+}
+
+/** The words the search found, marked. */
+function Marked({ text }: { text: string }) {
+ return (
+ <>
+ {text
+ .split(/(⟦[^⟧]*⟧)/)
+ .map((part, i) =>
+ part.startsWith("⟦") ?
{part.slice(1, -1)} :
{part} ,
+ )}
+ >
+ );
+}
+
+/** Search in the threads and posts the visitor may read. */
+export default async function SearchPage({ searchParams }: { searchParams: Promise<{ q?: string; oldal?: string }> }) {
+ const params = await searchParams;
+ const q = (params.q ?? "").trim();
+ const page = Math.max(1, Number(params.oldal) || 1);
+ const res =
+ q.length >= 2
+ ? await forumGet<{ results: SearchResult[]; more: boolean }>(
+ `/v1/forum/search?q=${encodeURIComponent(q)}&page=${page}`,
+ )
+ : null;
+ const results = res?.ok ? res.data.results : [];
+ const more = res?.ok ? res.data.more : false;
+ const link = (p: number) => `/forum/kereses?q=${encodeURIComponent(q)}&oldal=${p}`;
+ return (
+
+
Keresés
+
+ {q.length >= 2 &&
+ (results.length === 0 ? (
+
Erre nincs találat. Próbáld más szóval, vagy rövidebben.
+ ) : (
+
+ {results.map((r) => (
+
+
+ {r.thread.title}
+
+ {r.topic.name} · {r.author?.nickname ?? "Törölt tag"} · {r.reply_count} válasz · utoljára{" "}
+
+ {ago(r.last_post_at)}
+
+
+ {r.snippet && (
+
+
+
+ )}
+
+
+ ))}
+
+ ))}
+ {(page > 1 || more) && (
+
+ {page > 1 ? ‹ Előző : }
+ {page}. oldal
+ {more ? Következő › : }
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/forum/layout.tsx b/services/frontend/src/app/forum/layout.tsx
index f5aa56d..3acd01d 100644
--- a/services/frontend/src/app/forum/layout.tsx
+++ b/services/frontend/src/app/forum/layout.tsx
@@ -48,7 +48,15 @@ export default async function ForumLayout({ children }: { children: React.ReactN
}}
wsUrl={process.env.FORUM_WS_URL || "/api/v1/forum/ws"}
/>
-
+
{children}
diff --git a/services/frontend/src/app/forum/moderalas/TopicsAdmin.tsx b/services/frontend/src/app/forum/moderalas/TopicsAdmin.tsx
index 687167e..e95d537 100644
--- a/services/frontend/src/app/forum/moderalas/TopicsAdmin.tsx
+++ b/services/frontend/src/app/forum/moderalas/TopicsAdmin.tsx
@@ -145,7 +145,22 @@ export function TopicsAdmin({
{t.name} · {VISIBILITY[t.visibility] ?? t.visibility}
+ {t.archived && · archivált }
+
+ (t.archived ||
+ window.confirm(
+ `Archiválod a(z) „${t.name}” témát? A szálai olvashatók maradnak, de új szál és hozzászólás nem írható bele, és lekerül a főoldalról.`,
+ )) &&
+ act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { archived: !t.archived } }))
+ }
+ >
+ {t.archived ? "Visszaállítás" : "Archiválás"}
+
Témák
- {topics.map((t) =>
- t.visibility === "restricted" && !t.readable ? (
-
-
-
-
-
-
-
- {t.name}
-
-
-
-
+ {topics
+ .filter((t) => !t.archived)
+ .map((t) =>
+ t.visibility === "restricted" && !t.readable ? (
+
+
+
+
- {t.description}
- Zárt kör: jóváhagyás után olvasható
-
- {viewer.member && }
-
-
- ) : (
-
-
-
-
-
-
-
- {t.name}
- {t.visibility !== "public" && (
-
+
+
+ {t.name}
+
- )}
+
+ {t.description}
+ Zárt kör: jóváhagyás után olvasható
- {t.description}
- {t.readable && t.last && (
-
- {t.last.author && (
-
+ {viewer.member && }
+
+
+ ) : (
+
+
+
+
+
+
+
+ {t.name}
+ {t.visibility !== "public" && (
+
+
+
+
)}
- {t.last.author?.nickname ?? "Törölt tag"},{" "}
-
- {ago(t.last.at)}
-
+
+ {t.description}
+ {t.readable && t.last && (
+
+ {t.last.author && (
+
+ )}
+ {t.last.author?.nickname ?? "Törölt tag"},{" "}
+
+ {ago(t.last.at)}
+
+
+ )}
+ {!t.readable && Belépés után olvasható }
+
+ {t.readable && (
+
+ {t.thread_count ?? 0} szál
)}
- {!t.readable && Belépés után olvasható }
-
- {t.readable && (
-
- {t.thread_count ?? 0} szál
-
- )}
- {t.readable && t.new_count ? (
- {t.new_count > 99 ? "99+" : t.new_count} új
- ) : null}
-
-
- ),
- )}
+ {t.readable && t.new_count ? (
+ {t.new_count > 99 ? "99+" : t.new_count} új
+ ) : null}
+
+
+ ),
+ )}
+ {topics.some((t) => t.archived) && (
+
+ Archivált témák ({topics.filter((t) => t.archived).length})
+
+ {topics
+ .filter((t) => t.archived && t.readable)
+ .map((t) => (
+
+
+
+ {t.name}
+
+ {t.description} · {t.thread_count ?? 0} szál
+
+
+
+ ›
+
+
+
+ ))}
+
+
+ )}
diff --git a/services/frontend/src/app/forum/tag/[nev]/MuteButton.tsx b/services/frontend/src/app/forum/tag/[nev]/MuteButton.tsx
new file mode 100644
index 0000000..ba04539
--- /dev/null
+++ b/services/frontend/src/app/forum/tag/[nev]/MuteButton.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+
+/** "Némítás" on a member's profile: their threads, posts and notices step out of the viewer's way. */
+export function MuteButton({ nickname, muted }: { nickname: string; muted: boolean }) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ return (
+
+
{
+ if (
+ !muted &&
+ !window.confirm(
+ `Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud.`,
+ )
+ )
+ return;
+ setBusy(true);
+ setError(null);
+ try {
+ await api(`/forum/members/${encodeURIComponent(nickname)}/mute`, { method: muted ? "DELETE" : "PUT" });
+ router.refresh();
+ } catch (e) {
+ setError(errorText(e));
+ } finally {
+ setBusy(false);
+ }
+ }}
+ >
+ {muted ? "Némítás feloldása" : "Némítás"}
+
+ {muted &&
Elnémítottad: a szálai és az értesítései nem jelennek meg nálad. }
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/forum/tag/[nev]/page.tsx b/services/frontend/src/app/forum/tag/[nev]/page.tsx
index aa69462..6fe2055 100644
--- a/services/frontend/src/app/forum/tag/[nev]/page.tsx
+++ b/services/frontend/src/app/forum/tag/[nev]/page.tsx
@@ -10,6 +10,7 @@ import { type MemberProfile, ago, banText, threadHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
import { BanPanel } from "./BanPanel";
+import { MuteButton } from "./MuteButton";
import { RequestPanel } from "./RequestPanel";
type Props = { params: Promise<{ nev: string }> };
@@ -70,6 +71,7 @@ export default async function MemberPage({ params }: Props) {
Profil szerkesztése
)}
+ {viewer.member && !member.own && }
{viewer.moderator && !member.own && !a.moderator && (
t.readable) : [];
+ const topics = res.ok ? res.data.topics.filter((t) => t.readable && !t.archived) : [];
const initial = topics.find((t) => t.slug === tema)?.slug ?? topics[0]?.slug ?? "";
return (
diff --git a/services/frontend/src/app/robots.ts b/services/frontend/src/app/robots.ts
index 17be8cc..2b4779e 100644
--- a/services/frontend/src/app/robots.ts
+++ b/services/frontend/src/app/robots.ts
@@ -54,7 +54,24 @@ const AI_SEARCH = [
];
// Logged-in pages redirect anyway; shared links carry noindex.
-const PRIVATE = ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek", "/szamlak"];
+const PRIVATE = [
+ "/api/",
+ "/admin",
+ "/profil",
+ "/kepletek",
+ "/osszevetesek",
+ "/szemelyek",
+ "/szamlak",
+ // The forum's own pages (the topics and threads are open).
+ "/forum/beallitasok",
+ "/forum/uzenetek",
+ "/forum/valaszok",
+ "/forum/kovetett",
+ "/forum/moderalas",
+ "/forum/uj",
+ "/forum/kereses",
+ "/forum/leiratkozas",
+];
export default async function robots(): Promise
{
return {
diff --git a/services/frontend/src/app/sitemap.ts b/services/frontend/src/app/sitemap.ts
index 99ecbce..598d18b 100644
--- a/services/frontend/src/app/sitemap.ts
+++ b/services/frontend/src/app/sitemap.ts
@@ -2,6 +2,7 @@ import type { MetadataRoute } from "next";
import { ZODIAC } from "@/content/zodiac";
import { loadCelebrities } from "@/lib/celebrities";
+import { forumEnabled, forumSitemap } from "@/lib/forumServer";
import { currentYear } from "@/lib/sky";
import { siteUrl } from "@/lib/share";
@@ -10,7 +11,7 @@ export default async function sitemap(): Promise {
const base = await siteUrl();
const privacy = { languages: { hu: `${base}/adatvedelem`, en: `${base}/privacy` } };
// The sitemap still works when the backend does not answer.
- const people = await loadCelebrities().catch(() => []);
+ const [people, forum] = await Promise.all([loadCelebrities().catch(() => []), forumSitemap()]);
const next = currentYear() + 1;
return [
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
@@ -30,6 +31,20 @@ export default async function sitemap(): Promise {
changeFrequency: "monthly" as const,
priority: 0.6,
})),
+ // The forum's public topics and threads (the members-only ones are not listed).
+ ...(forumEnabled() ? [{ url: `${base}/forum`, changeFrequency: "hourly" as const, priority: 0.8 }] : []),
+ ...forum.topics.map((t) => ({
+ url: `${base}/forum/${t.slug}`,
+ lastModified: t.updated ?? undefined,
+ changeFrequency: "daily" as const,
+ priority: 0.6,
+ })),
+ ...forum.threads.map((t) => ({
+ url: `${base}/forum/szal/${t.id}-${t.slug}`,
+ lastModified: t.updated,
+ changeFrequency: "weekly" as const,
+ priority: 0.5,
+ })),
{ url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 },
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
diff --git a/services/frontend/src/components/forum/ThreadView.tsx b/services/frontend/src/components/forum/ThreadView.tsx
index a691ab4..d833103 100644
--- a/services/frontend/src/components/forum/ThreadView.tsx
+++ b/services/frontend/src/components/forum/ThreadView.tsx
@@ -27,6 +27,8 @@ type Actions = {
remove: (post: ForumPost) => void;
restore: (post: ForumPost) => void;
helped: (post: ForumPost) => void;
+ /** Mute or unmute the post's author. */
+ mute: (post: ForumPost) => void;
};
function ReactionRow({
@@ -187,6 +189,7 @@ function PostCard({
const [reporting, setReporting] = useState(false);
const [menu, setMenu] = useState(false);
const [showCollapsed, setShowCollapsed] = useState(false);
+ const [showMuted, setShowMuted] = useState(false);
const { viewer, thread, access } = page;
const writer = viewer.member !== null && !viewer.member.banned;
const starter = post.author !== null && post.author.nickname === thread.author?.nickname;
@@ -208,6 +211,17 @@ function PostCard({
);
}
+ // A muted member's post folds up; one click shows it.
+ if (post.muted && !showMuted) {
+ return (
+
+ setShowMuted(true)}>
+ {author?.nickname ?? "Egy tag"} hozzászólása · elnémítottad · Megjelenítés
+
+
+ );
+ }
+
const menuItems: { label: string; run: () => void; danger?: boolean }[] = [];
if (!post.deleted) {
if (access?.is_thread_author && !post.is_opening && !post.own && writer) {
@@ -216,6 +230,11 @@ function PostCard({
if (post.own && writer && !thread.locked) menuItems.push({ label: "Szerkesztés", run: () => setEditing(true) });
if (post.own) menuItems.push({ label: "Törlés", run: () => actions.remove(post), danger: true });
if (viewer.logged_in && !post.own) menuItems.push({ label: "Jelentés", run: () => setReporting(true) });
+ if (viewer.member && !post.own && author && !post.system)
+ menuItems.push({
+ label: post.muted ? `${author.nickname} némításának feloldása` : `${author.nickname} némítása`,
+ run: () => actions.mute(post),
+ });
if (viewer.moderator && !post.own)
menuItems.push({ label: "Eltávolítás", run: () => actions.remove(post), danger: true });
} else if (viewer.moderator) {
@@ -515,6 +534,21 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
await reload();
}),
+ mute: (post) => {
+ const nickname = post.author?.nickname;
+ if (!nickname) return;
+ if (
+ !post.muted &&
+ !window.confirm(
+ `Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud. A beállításoknál bármikor feloldhatod.`,
+ )
+ )
+ return;
+ void run(async () => {
+ await api(`/forum/members/${encodeURIComponent(nickname)}/mute`, { method: post.muted ? "DELETE" : "PUT" });
+ await reload();
+ });
+ },
helped: (post) =>
void run(async () => {
const updated = await api(`/forum/posts/${post.id}/helped`, {
@@ -738,7 +772,11 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
) : viewer.member?.banned ? (
Most nem írhatsz a fórumba.
) : !access?.can_reply ? (
- Ez a szál le van zárva, új hozzászólás nem írható.
+
+ {thread.topic.archived
+ ? "Ez a téma archivált: olvasható, de új hozzászólás nem írható."
+ : "Ez a szál le van zárva, új hozzászólás nem írható."}
+
) : (
<>
(path: string): Promise> {
if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`);
return { ok: true, data: (await res.json()) as T };
}
+
+/** The public forum pages for the sitemap (nothing when the forum is off or does not answer). */
+export async function forumSitemap(): Promise<{
+ topics: { slug: string; updated: string | null }[];
+ threads: { id: number; slug: string; updated: string }[];
+}> {
+ const empty = { topics: [], threads: [] };
+ if (!forumEnabled()) return empty;
+ try {
+ const res = await fetch(`${FORUM_URL}/v1/forum/sitemap`, { next: { revalidate: 3600 } });
+ return res.ok ? await res.json() : empty;
+ } catch {
+ return empty;
+ }
+}
diff --git a/services/worker/src/forum_digest.rs b/services/worker/src/forum_digest.rs
index ea29fda..719d820 100644
--- a/services/worker/src/forum_digest.rs
+++ b/services/worker/src/forum_digest.rs
@@ -130,7 +130,7 @@ pub async fn listeners_once(db: &PgPool, base_url: &str) -> Result)> = sqlx::query_as(&format!(
"SELECT th.id, th.title, th.author_id FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \
- AND th.listeners_notified_at IS NULL AND tp.visibility <> 'restricted' \
+ AND th.listeners_notified_at IS NULL AND tp.visibility <> 'restricted' AND tp.archived_at IS NULL \
AND (th.intent = 'listen' OR tp.listening) \
AND th.created_at < now() - interval '{LISTENER_AFTER}' AND th.created_at > now() - interval '3 days' \
ORDER BY th.created_at LIMIT 20 FOR UPDATE OF th SKIP LOCKED"
@@ -190,7 +190,7 @@ pub async fn weekly_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<
let busy: Vec<(i64, String, i64)> = sqlx::query_as(
"SELECT th.id, th.title, count(p.id) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
JOIN forum.posts p ON p.thread_id = th.id AND p.deleted_at IS NULL AND p.created_at > now() - interval '7 days' \
- WHERE th.deleted_at IS NULL AND tp.visibility <> 'restricted' \
+ WHERE th.deleted_at IS NULL AND tp.visibility <> 'restricted' AND tp.archived_at IS NULL \
GROUP BY th.id, th.title ORDER BY count(p.id) DESC, max(p.id) DESC LIMIT 5",
)
.fetch_all(db)
@@ -198,7 +198,7 @@ pub async fn weekly_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<
let waiting: Vec = sqlx::query_scalar(
"SELECT th.title FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.reply_count = 0 AND th.deleted_at IS NULL AND NOT th.locked AND NOT th.system \
- AND tp.visibility <> 'restricted' AND th.created_at > now() - interval '7 days' \
+ AND tp.visibility <> 'restricted' AND tp.archived_at IS NULL AND th.created_at > now() - interval '7 days' \
ORDER BY th.created_at LIMIT 3",
)
.fetch_all(db)
diff --git a/services/worker/src/forum_sky.rs b/services/worker/src/forum_sky.rs
index 9c26747..5e8944e 100644
--- a/services/worker/src/forum_sky.rs
+++ b/services/worker/src/forum_sky.rs
@@ -224,7 +224,7 @@ pub async fn run_once(db: &PgPool, http: &reqwest::Client, backend_url: &str, an
let mut tx = db.begin().await?;
let thread: Option = sqlx::query_scalar(
"INSERT INTO forum.threads (topic_id, author_id, title, system, pinned, daily_date) \
- SELECT id, NULL, $2, true, true, (now() AT TIME ZONE 'Europe/Budapest')::date FROM forum.topics WHERE slug = $1 \
+ SELECT id, NULL, $2, true, true, (now() AT TIME ZONE 'Europe/Budapest')::date FROM forum.topics WHERE slug = $1 AND archived_at IS NULL \
ON CONFLICT (daily_date) DO NOTHING RETURNING id",
)
.bind(TOPIC)