From 9ca3f478be4e4cf0578d1604f65d86dc799faf57 Mon Sep 17 00:00:00 2001 From: feco Date: Thu, 26 Nov 2026 14:31:05 +0000 Subject: [PATCH] Forum: search, muting members, archived topics, the public threads in the sitemap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- ...0043_forum_search_mutes_archive_charts.sql | 52 +++++++ services/forum/src/auth.rs | 19 ++- services/forum/src/mail.rs | 3 + services/forum/src/routes/home.rs | 28 ++-- services/forum/src/routes/members.rs | 1 + services/forum/src/routes/mod.rs | 19 ++- services/forum/src/routes/mutes.rs | 67 +++++++++ services/forum/src/routes/replies.rs | 1 + services/forum/src/routes/search.rs | 139 +++++++++++++++++ services/forum/src/routes/threads.rs | 29 ++-- services/forum/src/routes/topics.rs | 15 +- services/forum/src/tests.rs | 79 ++++++++++ .../frontend/src/app/forum/[tema]/page.tsx | 23 ++- .../src/app/forum/beallitasok/MutedList.tsx | 46 ++++++ .../src/app/forum/beallitasok/ProfileForm.tsx | 4 + services/frontend/src/app/forum/forum.css | 27 ++++ .../frontend/src/app/forum/kereses/page.tsx | 103 +++++++++++++ services/frontend/src/app/forum/layout.tsx | 10 +- .../src/app/forum/moderalas/TopicsAdmin.tsx | 15 ++ services/frontend/src/app/forum/page.tsx | 142 +++++++++++------- .../src/app/forum/tag/[nev]/MuteButton.tsx | 49 ++++++ .../frontend/src/app/forum/tag/[nev]/page.tsx | 2 + services/frontend/src/app/forum/uj/page.tsx | 2 +- services/frontend/src/app/robots.ts | 19 ++- services/frontend/src/app/sitemap.ts | 17 ++- .../src/components/forum/ThreadView.tsx | 40 ++++- services/frontend/src/lib/forum.ts | 10 +- services/frontend/src/lib/forumServer.ts | 15 ++ services/worker/src/forum_digest.rs | 6 +- services/worker/src/forum_sky.rs | 2 +- 30 files changed, 879 insertions(+), 105 deletions(-) create mode 100644 crates/db/migrations/0043_forum_search_mutes_archive_charts.sql create mode 100644 services/forum/src/routes/mutes.rs create mode 100644 services/forum/src/routes/search.rs create mode 100644 services/frontend/src/app/forum/beallitasok/MutedList.tsx create mode 100644 services/frontend/src/app/forum/kereses/page.tsx create mode 100644 services/frontend/src/app/forum/tag/[nev]/MuteButton.tsx 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} + + +
  • + ))} +
+ + 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{" "} + + + {r.snippet && ( + + + + )} + +
  • + ))} +
+ ))} + {(page > 1 || more) && ( + + )} +
+ ); +} 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} +