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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 14:31:05 +00:00
co-authored by Claude Opus 5.5
parent 4800a30e6d
commit 9ca3f478be
30 changed files with 879 additions and 105 deletions
@@ -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)
);
+14 -5
View File
@@ -66,6 +66,8 @@ pub struct Viewer {
pub member: Option<Member>, pub member: Option<Member>,
/// The restricted topics the member was approved into. /// The restricted topics the member was approved into.
pub topics: Vec<i16>, pub topics: Vec<i16>,
/// The members they muted.
pub mutes: Vec<Uuid>,
} }
impl Viewer { impl Viewer {
@@ -137,15 +139,22 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
.execute(&state.db) .execute(&state.db)
.await?; .await?;
} }
let topics = if member.is_some() { let (topics, mutes) = if member.is_some() {
sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'approved'") let topics = sqlx::query_scalar(
"SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'approved'",
)
.bind(user.id) .bind(user.id)
.fetch_all(&state.db) .fetch_all(&state.db)
.await? .await?;
let mutes = sqlx::query_scalar("SELECT muted_id FROM forum.mutes WHERE user_id = $1")
.bind(user.id)
.fetch_all(&state.db)
.await?;
(topics, mutes)
} else { } else {
Vec::new() (Vec::new(), Vec::new())
}; };
Ok(Viewer { user: Some(user), member, topics }) Ok(Viewer { user: Some(user), member, topics, mutes })
} }
} }
+3
View File
@@ -78,6 +78,7 @@ async fn reply_mails(
WHERE m.email_replies = 'instant' AND m.user_id <> $1 AND {OFFLINE} \ 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 \ AND m.user_id IN (SELECT author_id FROM forum.threads WHERE id = $2 \
UNION SELECT author_id FROM forum.posts WHERE id = $3) \ 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 \ AND NOT EXISTS (SELECT 1 FROM email_outbox e \
WHERE e.user_id = m.user_id AND e.template = 'forum_reply' \ 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')" 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 \ "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 \ 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} \ 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 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.template IN ('forum_mention', 'forum_reply') \
AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')" AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')"
)) ))
.bind(users) .bind(users)
.bind(thread_id) .bind(thread_id)
.bind(author)
.fetch_all(&state.db) .fetch_all(&state.db)
.await?; .await?;
if recipients.is_empty() { if recipients.is_empty() {
+14 -8
View File
@@ -27,6 +27,7 @@ struct TopicRow {
description: String, description: String,
visibility: String, visibility: String,
listening: bool, listening: bool,
archived: bool,
thread_count: i64, thread_count: i64,
new_count: Option<i64>, new_count: Option<i64>,
last_author: Option<Uuid>, last_author: Option<Uuid>,
@@ -39,6 +40,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
let (me, since) = card_params(viewer); let (me, since) = card_params(viewer);
let rows: Vec<TopicRow> = sqlx::query_as( let rows: Vec<TopicRow> = sqlx::query_as(
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \ "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, \ (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 \ 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 \ (SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
@@ -93,6 +95,7 @@ async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
"description": r.description, "description": r.description,
"visibility": r.visibility, "visibility": r.visibility,
"listening": r.listening, "listening": r.listening,
"archived": r.archived,
"readable": readable, "readable": readable,
"membership": membership, "membership": membership,
}); });
@@ -138,7 +141,7 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
let followed = followed_counts(&state, &viewer).await?; let followed = followed_counts(&state, &viewer).await?;
let unanswered: Vec<CardRow> = sqlx::query_as(&format!( let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 \ "{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 AND tp.archived_at IS NULL \
AND th.created_at > now() - make_interval(days => $3) \ AND th.created_at > now() - make_interval(days => $3) \
ORDER BY th.created_at LIMIT 3", ORDER BY th.created_at LIMIT 3",
card_sql(&viewer) card_sql(&viewer)
@@ -153,7 +156,7 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \ "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 \ WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
GROUP BY thread_id HAVING count(*) >= $3) \ 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", ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5",
card_sql(&viewer) card_sql(&viewer)
)) ))
@@ -172,7 +175,8 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
.fetch_all(&state.db) .fetch_all(&state.db)
.await?; .await?;
let people = super::authors(&state.db, present.iter().copied()).await?; let people = super::authors(&state.db, present.iter().copied()).await?;
let online: Vec<Value> = present.iter().filter_map(|id| people.get(id).cloned()).collect(); let online: Vec<Value> =
present.iter().filter(|id| !viewer.mutes.contains(id)).filter_map(|id| people.get(id).cloned()).collect();
// Volunteer listeners: threads asking to be heard, still without a reply. // Volunteer listeners: threads asking to be heard, still without a reply.
let waiting = match &viewer.member { let waiting = match &viewer.member {
@@ -203,6 +207,7 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \ JOIN forum.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 \ 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 \ 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 \ 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)", WHERE r.user_id = $1 AND r.thread_id = f.thread_id), 0)",
) )
@@ -217,7 +222,7 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
/// hour without a reply (two weeks at most), not the listener's own. /// 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 \ 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.created_at < now() - interval '1 hour' AND th.created_at > now() - interval '14 days' \
AND (th.intent = 'listen' OR tp.listening)"; AND (th.intent = 'listen' OR tp.listening) AND tp.archived_at IS NULL";
async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult<i64> { async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult<i64> {
let me = viewer.user_id(); let me = viewer.user_id();
@@ -275,12 +280,13 @@ pub async fn topic(
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>, WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>, WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
) -> ApiResult<Json<Value>> { ) -> ApiResult<Json<Value>> {
let topic: Option<(i16, String, String, String, bool)> = let topic: Option<(i16, String, String, String, bool, bool)> = sqlx::query_as(
sqlx::query_as("SELECT id, name, description, visibility, listening FROM forum.topics WHERE slug = $1") "SELECT id, name, description, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1",
)
.bind(&slug) .bind(&slug)
.fetch_optional(&state.db) .fetch_optional(&state.db)
.await?; .await?;
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?; let (id, name, description, visibility, listening, archived) = topic.ok_or(ApiError::NotFound("topic"))?;
if !may_read(&viewer, &visibility, id) { if !may_read(&viewer, &visibility, id) {
// A members-only topic asks for a login; a restricted one stays hidden. // A members-only topic asks for a login; a restricted one stays hidden.
return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") }); return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") });
@@ -304,7 +310,7 @@ pub async fn topic(
"viewer": viewer_json(&viewer), "viewer": viewer_json(&viewer),
"topic": { "topic": {
"slug": slug, "name": name, "description": description, "slug": slug, "name": name, "description": description,
"visibility": visibility, "listening": listening, "visibility": visibility, "listening": listening, "archived": archived,
}, },
"threads": cards_json(&state.db, rows).await?, "threads": cards_json(&state.db, rows).await?,
"page": page, "page": page,
+1
View File
@@ -405,6 +405,7 @@ pub async fn profile(
"thread_count": thread_count, "thread_count": thread_count,
"last_seen": last_seen, "last_seen": last_seen,
"own": own, "own": own,
"muted": viewer.mutes.contains(&row.user_id),
"banned_until": banned.filter(|_| show_ban).map(|u| { "banned_until": banned.filter(|_| show_ban).map(|u| {
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) } if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
}), }),
+16 -3
View File
@@ -11,9 +11,11 @@ mod members;
mod mentions; mod mentions;
mod messages; mod messages;
mod moderation; mod moderation;
mod mutes;
mod posts; mod posts;
mod replies; mod replies;
mod reports; mod reports;
mod search;
mod threads; mod threads;
mod topics; mod topics;
@@ -50,6 +52,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide)) .route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
.route("/v1/forum/followed", get(home::followed)) .route("/v1/forum/followed", get(home::followed))
.route("/v1/forum/replies", get(replies::list)) .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/replies/read", post(replies::read_all))
.route("/v1/forum/threads", post(threads::create)) .route("/v1/forum/threads", post(threads::create))
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove)) .route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
@@ -83,6 +87,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/ws", get(crate::live::connect)) .route("/v1/forum/ws", get(crate::live::connect))
.route("/v1/forum/members/search", get(mentions::search)) .route("/v1/forum/members/search", get(mentions::search))
.route("/v1/forum/members/{nickname}", get(members::profile)) .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/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log)) .route("/v1/forum/mod/log", get(moderation::log))
.route("/v1/forum/mod/reports", get(reports::list)) .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 /// `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), /// 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`. /// 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 { pub fn card_sql(viewer: &Viewer) -> String {
format!( format!(
"SELECT th.id, th.title, th.intent, th.author_id, th.created_at, th.last_post_at, th.reply_count, \ "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 \ CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
(SELECT count(*) FROM forum.posts p \ (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 \ 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 \ AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread, \ WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread, \
th.system \ th.system \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.deleted_at IS NULL AND ({})", WHERE th.deleted_at IS NULL AND ({}) AND {}",
visible_topics(viewer) not_muted("p.author_id"),
visible_topics(viewer),
not_muted("th.author_id"),
) )
} }
+67
View File
@@ -0,0 +1,67 @@
//! "Némítás": a member mutes another. The muted member's threads leave the
//! muter's lists, their posts fold up (one click shows them), their replies
//! and mentions no longer notify, and they drop out of "Most itt vannak".
//! The muted member is not told, and can still be reported.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use serde_json::{Value, json};
use uuid::Uuid;
use super::{St, authors};
use crate::AppState;
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
async fn member_id(state: &AppState, nickname: &str) -> ApiResult<Uuid> {
sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
.bind(text::nickname_key(nickname))
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("member"))
}
pub async fn mute(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
let target = member_id(&state, &nickname).await?;
if target == member.user_id {
return Err(ApiError::bad("Saját magadat nem némíthatod el."));
}
sqlx::query("INSERT INTO forum.mutes (user_id, muted_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(member.user_id)
.bind(target)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn unmute(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
let target = member_id(&state, &nickname).await?;
sqlx::query("DELETE FROM forum.mutes WHERE user_id = $1 AND muted_id = $2")
.bind(member.user_id)
.bind(target)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
/// The members the viewer muted (for the settings page).
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_member()?;
let people = authors(&state.db, viewer.mutes.iter().copied()).await?;
let mut muted: Vec<Value> = viewer.mutes.iter().filter_map(|id| people.get(id).cloned()).collect();
muted.sort_by(|a, b| a["nickname"].as_str().cmp(&b["nickname"].as_str()));
Ok(Json(json!({ "muted": muted })))
}
+1
View File
@@ -28,6 +28,7 @@ fn answers(viewer: &Viewer) -> String {
LEFT JOIN forum.reads r ON r.user_id = $1 AND r.thread_id = p.thread_id \ 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 \ 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 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 \ AND (target.author_id = $1 \
OR (p.parent_id IS NULL AND th.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))", OR EXISTS (SELECT 1 FROM forum.mentions mn WHERE mn.post_id = p.id AND mn.user_id = $1))",
+139
View File
@@ -0,0 +1,139 @@
//! Search in what the viewer may read: thread titles and posts, with
//! Hungarian stems ("szálak" finds "szál") and without accents ("alvas"
//! finds "alvás"). One result per thread, with the best matching post's
//! words marked; muted members are left out.
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::{St, authors, not_muted, rfc3339, visible_topics};
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
#[derive(Deserialize)]
pub struct SearchQuery {
#[serde(default)]
q: Option<String>,
#[serde(default)]
page: Option<i64>,
}
#[derive(sqlx::FromRow)]
struct Hit {
id: i64,
title: String,
topic_slug: String,
topic_name: String,
author_id: Option<Uuid>,
last_post_at: OffsetDateTime,
reply_count: i32,
post_id: Option<i64>,
snippet: Option<String>,
}
const PAGE: i64 = 20;
/// Around the matching words in `snippet` (the page marks them).
pub const MARK_START: &str = "⟦";
pub const MARK_END: &str = "⟧";
pub async fn search(
State(state): St,
viewer: Viewer,
WithRejection(Query(q), _): WithRejection<Query<SearchQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let query: String = q.q.unwrap_or_default().trim().chars().take(100).collect();
let page = q.page.unwrap_or(1).clamp(1, 50);
if query.chars().count() < 2 {
return Ok(Json(json!({ "query": query, "results": [], "more": false, "page": page })));
}
// Word beginnings without accents too: "alvas" finds "alvásban".
let prefixes: Vec<String> = query
.split(|c: char| !c.is_alphanumeric())
.filter(|w| w.chars().count() >= 3)
.take(8)
.map(|w| format!("{w}:*"))
.collect();
let rows: Vec<Hit> = sqlx::query_as(&format!(
"WITH q AS (SELECT websearch_to_tsquery('hungarian', $2) || to_tsquery('forum.plain', $6) AS q), \
hits AS (SELECT p.thread_id, p.id, p.body, ts_rank(p.search, q.q) AS rank FROM forum.posts p, q \
WHERE p.search @@ q.q AND p.deleted_at IS NULL AND {posts_ok}) \
SELECT th.id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, th.author_id, th.last_post_at, \
th.reply_count, best.id AS post_id, \
CASE WHEN best.id IS NULL THEN NULL ELSE ts_headline('hungarian', best.body, q.q, $5) END AS snippet \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id CROSS JOIN q \
LEFT JOIN LATERAL (SELECT h.id, h.body, h.rank FROM hits h WHERE h.thread_id = th.id \
ORDER BY h.rank DESC, h.id LIMIT 1) best ON true \
WHERE th.deleted_at IS NULL AND ({visible}) AND {threads_ok} \
AND (th.search @@ q.q OR th.id IN (SELECT thread_id FROM hits)) \
ORDER BY (CASE WHEN th.search @@ q.q THEN 2 * ts_rank(th.search, q.q) ELSE 0 END + COALESCE(best.rank, 0)) DESC, \
th.last_post_at DESC \
LIMIT $3 OFFSET $4",
posts_ok = not_muted("p.author_id"),
visible = visible_topics(&viewer),
threads_ok = not_muted("th.author_id"),
))
.bind(viewer.user_id())
.bind(&query)
.bind(PAGE + 1)
.bind((page - 1) * PAGE)
.bind(format!(
"StartSel={MARK_START}, StopSel={MARK_END}, MaxWords=30, MinWords=12, ShortWord=2, MaxFragments=1"
))
.bind(prefixes.join(" & "))
.fetch_all(&state.db)
.await?;
let more = rows.len() as i64 > PAGE;
let rows = &rows[..rows.len().min(PAGE as usize)];
let people = authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?;
let results: Vec<Value> = rows
.iter()
.map(|r| {
json!({
"thread": { "id": r.id, "title": r.title, "slug": text::slug(&r.title) },
"topic": { "slug": r.topic_slug, "name": r.topic_name },
"author": r.author_id.and_then(|a| people.get(&a).cloned()),
"last_post_at": rfc3339(r.last_post_at),
"reply_count": r.reply_count,
"post_id": r.post_id,
"snippet": r.snippet,
})
})
.collect();
Ok(Json(json!({ "query": query, "results": results, "more": more, "page": page })))
}
#[derive(sqlx::FromRow)]
struct MapThread {
id: i64,
title: String,
last_post_at: OffsetDateTime,
}
/// For the sitemap: the public topics and their threads (newest activity first).
pub async fn sitemap(State(state): St) -> ApiResult<Json<Value>> {
let topics: Vec<(String, Option<OffsetDateTime>)> = sqlx::query_as(
"SELECT tp.slug, (SELECT max(th.last_post_at) FROM forum.threads th \
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) \
FROM forum.topics tp WHERE tp.visibility = 'public' ORDER BY tp.position",
)
.fetch_all(&state.db)
.await?;
let threads: Vec<MapThread> = sqlx::query_as(
"SELECT th.id, th.title, th.last_post_at FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE tp.visibility = 'public' AND th.deleted_at IS NULL ORDER BY th.last_post_at DESC LIMIT 5000",
)
.fetch_all(&state.db)
.await?;
Ok(Json(json!({
"topics": topics.iter().map(|(slug, at)| json!({ "slug": slug, "updated": at.map(rfc3339) })).collect::<Vec<_>>(),
"threads": threads.iter().map(|t| json!({
"id": t.id, "slug": text::slug(&t.title), "updated": rfc3339(t.last_post_at),
})).collect::<Vec<_>>(),
})))
}
+20 -9
View File
@@ -42,11 +42,13 @@ pub struct ThreadRow {
pub deleted_at: Option<OffsetDateTime>, pub deleted_at: Option<OffsetDateTime>,
pub delete_reason: Option<String>, pub delete_reason: Option<String>,
pub system: bool, 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, \ 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, \ 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"; 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 /// 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) Ok(thread)
} }
/// A thread that can take new posts and reactions: not removed, and not /// A thread that can take new posts and reactions: not removed, not in an
/// locked (moderators may still write in a locked one). /// archived topic, and not locked (moderators may still write in a locked one).
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> { pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
let thread = readable_thread(db, viewer, id).await?; let thread = readable_thread(db, viewer, id).await?;
if thread.deleted_at.is_some() { if thread.deleted_at.is_some() {
return Err(ApiError::NotFound("thread")); 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() { if thread.locked && !viewer.is_moderator() {
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into())); 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, "mentions": mentions,
"system": p.system, "system": p.system,
"reply_to": reply_to, "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 { if moderator {
post["down"] = json!(down); post["down"] = json!(down);
@@ -229,7 +236,7 @@ pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _):
None => (false, None), None => (false, None),
}; };
let writer = viewer.member.as_ref().filter(|m| !m.banned(now)); 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!({ out["access"] = json!({
"can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()), "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()), "can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()),
@@ -248,7 +255,7 @@ fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
"intent": thread.intent, "intent": thread.intent,
"topic": { "topic": {
"slug": thread.topic_slug, "name": thread.topic_name, "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, "author": author,
"created_at": rfc3339(thread.created_at), "created_at": rfc3339(thread.created_at),
@@ -317,12 +324,15 @@ pub async fn create(
WithRejection(Json(req), _): Body<CreateThread>, WithRejection(Json(req), _): Body<CreateThread>,
) -> ApiResult<(StatusCode, Json<Value>)> { ) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?; let member = viewer.require_writer()?;
let topic: Option<(i16, String, bool)> = let topic: Option<(i16, String, bool, bool)> =
sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1") sqlx::query_as("SELECT id, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1")
.bind(&req.topic) .bind(&req.topic)
.fetch_optional(&state.db) .fetch_optional(&state.db)
.await?; .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) { if !may_read(&viewer, &visibility, topic_id) {
return Err(ApiError::bad("Ismeretlen téma.")); return Err(ApiError::bad("Ismeretlen téma."));
} }
@@ -458,7 +468,8 @@ pub async fn reply(
.await?; .await?;
after_post(&mut tx, member.user_id, id, post.id).await?; after_post(&mut tx, member.user_id, id, post.id).await?;
tx.commit().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; 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; 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)) crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers))
+13 -2
View File
@@ -107,6 +107,9 @@ pub struct TopicChange {
listening: Option<bool>, listening: Option<bool>,
#[serde(default)] #[serde(default)]
position: Option<i16>, position: Option<i16>,
/// Archive (true) or bring back (false).
#[serde(default)]
archived: Option<bool>,
} }
/// The admin renames, describes, moves or changes the visibility of a topic /// The admin renames, describes, moves or changes the visibility of a topic
@@ -125,7 +128,10 @@ pub async fn update(
let changed = sqlx::query( let changed = sqlx::query(
"UPDATE forum.topics SET name = COALESCE($2, name), description = COALESCE($3, description), \ "UPDATE forum.topics SET name = COALESCE($2, name), description = COALESCE($3, description), \
visibility = COALESCE($4, visibility), listening = COALESCE($5, listening), \ 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(&slug)
.bind(&name) .bind(&name)
@@ -133,6 +139,7 @@ pub async fn update(
.bind(&visibility) .bind(&visibility)
.bind(req.listening) .bind(req.listening)
.bind(req.position) .bind(req.position)
.bind(req.archived)
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
if changed.rows_affected() == 0 { if changed.rows_affected() == 0 {
@@ -145,7 +152,11 @@ pub async fn update(
None, None,
None, 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, None,
) )
.await?; .await?;
+79
View File
@@ -1130,3 +1130,82 @@ async fn answers_to_the_member(pool: PgPool) {
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["replies"], 0); assert_eq!(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"); assert_eq!(answers(app.get("/v1/forum/replies", Some(&bea)).await).len(), 2, "the list stays");
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn search_mutes_and_archived_topics(pool: PgPool) {
let app = TestApp::new(pool);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
let admin = app.member("admin@example.com", "Gazda", &["user", "admin"]).await;
let found = |v: Value| -> Vec<i64> {
let mut ids: Vec<i64> =
v["results"].as_array().unwrap().iter().map(|r| r["thread"]["id"].as_i64().unwrap()).collect();
ids.sort();
ids
};
// Search: word beginnings without accents, titles, and only what one may read.
let sleep = app.thread(&anna, "torzsasztal", "Nehezen alszom").await;
app.reply(&bea, sleep, "Nekem az esti séták segítettek az alvásban.", None).await;
let hidden = app.thread(&anna, "ami-a-szivemen-van", "Alvászavar titokban").await;
assert_eq!(found(app.get("/v1/forum/search?q=alvas", None).await), vec![sleep], "a visitor: public topics");
assert_eq!(found(app.get("/v1/forum/search?q=alv%C3%A1s", Some(&anna)).await), vec![sleep, hidden]);
let hit = app.get("/v1/forum/search?q=s%C3%A9t%C3%A1k", None).await;
assert!(hit["results"][0]["snippet"].as_str().unwrap().contains("⟦séták⟧"), "{hit}");
assert!(found(app.get("/v1/forum/search?q=a", None).await).is_empty(), "too short");
let map = app.get("/v1/forum/sitemap", None).await;
let mapped: Vec<i64> = map["threads"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect();
assert_eq!(mapped, vec![sleep], "public threads only");
// Muting Bea: her threads leave Anna's lists, her posts fold up, her
// answers stop counting, and search leaves her out. She is not told.
let soups = app.thread(&bea, "torzsasztal", "Téli levesek").await;
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 1);
let (status, _) = app.call("PUT", "/v1/forum/members/Holdf%C3%A9ny/mute", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::NO_CONTENT);
let listed = app.get("/v1/forum/topics/torzsasztal", Some(&anna)).await;
assert!(listed["threads"].as_array().unwrap().iter().all(|t| t["id"] != soups));
let thread = app.get(&format!("/v1/forum/threads/{sleep}"), Some(&anna)).await;
assert_eq!(thread["posts"][1]["muted"], true);
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 0);
assert!(found(app.get("/v1/forum/search?q=s%C3%A9t%C3%A1k", Some(&anna)).await).is_empty());
assert_eq!(app.get("/v1/forum/me/mutes", Some(&anna)).await["muted"][0]["nickname"], "Holdfény");
assert_eq!(app.get("/v1/forum/members/Holdf%C3%A9ny", Some(&anna)).await["member"]["muted"], true);
assert_eq!(app.get(&format!("/v1/forum/threads/{sleep}"), Some(&bea)).await["posts"][0]["muted"], false);
let (status, _) = app.call("PUT", "/v1/forum/members/Csendesv%C3%ADz/mute", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "not oneself");
let (status, _) = app.call("DELETE", "/v1/forum/members/Holdf%C3%A9ny/mute", Some(&anna), Value::Null).await;
assert_eq!(status, StatusCode::NO_CONTENT);
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 1);
// Archiving the topic: readable, but nothing new; brought back, it works again.
let (status, _) =
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": true })).await;
assert_eq!(status, StatusCode::NO_CONTENT);
let topic = app.get("/v1/forum/topics/torzsasztal", Some(&anna)).await;
assert_eq!(topic["topic"]["archived"], true);
let thread = app.get(&format!("/v1/forum/threads/{sleep}"), Some(&anna)).await;
assert_eq!(thread["access"]["can_reply"], false);
assert_eq!(thread["thread"]["topic"]["archived"], true);
let (status, _) = app
.call("POST", &format!("/v1/forum/threads/{sleep}/posts"), Some(&bea), json!({ "body": "Még egy szó." }))
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let (status, _) = app
.call(
"POST",
"/v1/forum/threads",
Some(&anna),
json!({ "topic": "torzsasztal", "title": "Új", "body": "Szia" }),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let home = app.get("/v1/forum/home", Some(&anna)).await;
let archived = home["topics"].as_array().unwrap().iter().find(|t| t["slug"] == "torzsasztal").unwrap();
assert_eq!(archived["archived"], true);
let (status, _) =
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&anna), json!({ "archived": false })).await;
assert_eq!(status, StatusCode::FORBIDDEN, "admins only");
app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": false })).await;
app.reply(&bea, sleep, "Még egy szó.", None).await;
}
@@ -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."} : "Zárt kör: ezt a témát csak a jóváhagyott tagjai látják."}
</p> </p>
)} )}
{topic.archived && (
<p className="ftopic-private">
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="3.5" y="4.5" width="17" height="4.5" rx="1" />
<path d="M5 9v9.5a1.5 1.5 0 0 0 1.5 1.5h11a1.5 1.5 0 0 0 1.5-1.5V9M10 13h4" />
</svg>
Archivált téma: a szálak olvashatók, de új szál és hozzászólás már nem írható.
</p>
)}
</div> </div>
{!topic.archived && (
<Link <Link
href={viewer.logged_in ? `/forum/uj?tema=${topic.slug}` : `/belepes?vissza=/forum/uj?tema=${topic.slug}`} href={viewer.logged_in ? `/forum/uj?tema=${topic.slug}` : `/belepes?vissza=/forum/uj?tema=${topic.slug}`}
className="btn btn-primary" className="btn btn-primary"
> >
Új szál Új szál
</Link> </Link>
)}
</header> </header>
{threads.length === 0 ? ( {threads.length === 0 ? (
<p className="fh-card fh-empty">Ebben a témában még nincs szál. Nyisd meg te az elsőt!</p> <p className="fh-card fh-empty">Ebben a témában még nincs szál. Nyisd meg te az elsőt!</p>
@@ -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<ForumAuthor[] | null>(null);
useEffect(() => {
api<{ muted: ForumAuthor[] }>("/forum/me/mutes")
.then((res) => setMuted(res.muted))
.catch(() => setMuted([]));
}, []);
if (!muted || muted.length === 0) return null;
return (
<fieldset className="fnew-set">
<legend>Elnémított tagok</legend>
<ul className="fmuted">
{muted.map((m) => (
<li key={m.nickname}>
<span className="fh-online-item">
<Avatar avatar={m.avatar} size={28} />
{m.nickname}
</span>
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={async () => {
await api(`/forum/members/${encodeURIComponent(m.nickname)}/mute`, { method: "DELETE" });
setMuted((list) => (list ?? []).filter((x) => x.nickname !== m.nickname));
}}
>
Feloldás
</button>
</li>
))}
</ul>
<span className="hint">
Az elnémított tagok szálai nem jelennek meg a listáidban, és nem kapsz értesítést tőlük.
</span>
</fieldset>
);
}
@@ -9,6 +9,8 @@ import { api, errorText } from "@/lib/api";
import { withEmoji } from "@/lib/emoticons"; import { withEmoji } from "@/lib/emoticons";
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum"; import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
import { MutedList } from "./MutedList";
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [ const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
{ value: "none", label: "Semmit" }, { value: "none", label: "Semmit" },
{ value: "sun", label: "Csak a Nap-jegyemet" }, { value: "sun", label: "Csak a Nap-jegyemet" },
@@ -347,6 +349,8 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
</span> </span>
</fieldset> </fieldset>
{member && <MutedList />}
{member && ( {member && (
<div className="fprof-rank"> <div className="fprof-rank">
<span className="eyebrow">Rangod</span> <span className="eyebrow">Rangod</span>
+27
View File
@@ -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: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 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-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. */ /* The forum's menu: a bar at the bottom on phones, tabs in the forum bar on wider screens. */
.forum-nav { .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-item[aria-current="page"] { background: var(--f-tint); }
.fn-icon { width: 20px; height: 20px; } .fn-icon { width: 20px; height: 20px; }
.forum-theme { padding: 0 14px; } .forum-theme { padding: 0 14px; }
.forum-search { padding: 0; }
.forum-theme-label { display: inline; } .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. */ /* 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-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; } .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); }
@@ -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("⟦") ? <mark key={i}>{part.slice(1, -1)}</mark> : <span key={i}>{part}</span>,
)}
</>
);
}
/** 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 (
<div className="fh">
<h1 className="fpage-title">Keresés</h1>
<form className="fsearch-form" action="/forum/kereses" role="search">
<label htmlFor="fsearch-q" className="sr-only">
Mit keresel?
</label>
<input
id="fsearch-q"
name="q"
type="search"
className="inp"
defaultValue={q}
placeholder="Mit keresel? Például: alvás, telihold, gyász"
minLength={2}
maxLength={100}
autoFocus={!q}
/>
<button type="submit" className="btn btn-primary">
Keresés
</button>
</form>
{q.length >= 2 &&
(results.length === 0 ? (
<p className="fh-card fh-empty">Erre nincs találat. Próbáld más szóval, vagy rövidebben.</p>
) : (
<ul className="fh-card fh-flush fsearch-results">
{results.map((r) => (
<li key={r.thread.id}>
<Link href={threadHref(r.thread, r.post_id ?? undefined)} className="fsearch-hit">
<span className="fsearch-title">{r.thread.title}</span>
<span className="fsearch-meta">
{r.topic.name} · {r.author?.nickname ?? "Törölt tag"} · {r.reply_count} válasz · utoljára{" "}
<time suppressHydrationWarning dateTime={r.last_post_at}>
{ago(r.last_post_at)}
</time>
</span>
{r.snippet && (
<span className="fsearch-snippet">
<Marked text={r.snippet} />
</span>
)}
</Link>
</li>
))}
</ul>
))}
{(page > 1 || more) && (
<nav className="forum-pager" aria-label="Lapozás">
{page > 1 ? <Link href={link(page - 1)}>‹ Előző</Link> : <span />}
<span className="hint">{page}. oldal</span>
{more ? <Link href={link(page + 1)}>Következő ›</Link> : <span />}
</nav>
)}
</div>
);
}
@@ -48,8 +48,16 @@ export default async function ForumLayout({ children }: { children: React.ReactN
}} }}
wsUrl={process.env.FORUM_WS_URL || "/api/v1/forum/ws"} wsUrl={process.env.FORUM_WS_URL || "/api/v1/forum/ws"}
/> />
<div className="forum-tools">
<Link href="/forum/kereses" className="forum-theme forum-search" aria-label="Keresés a fórumban">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="11" cy="11" r="6.5" />
<path d="M16 16l4.5 4.5" />
</svg>
</Link>
<ThemeToggle initial={theme} /> <ThemeToggle initial={theme} />
</div> </div>
</div>
<main className="forum-main">{children}</main> <main className="forum-main">{children}</main>
</div> </div>
</div> </div>
@@ -145,7 +145,22 @@ export function TopicsAdmin({
<li key={t.slug} className="ftop-member"> <li key={t.slug} className="ftop-member">
<span> <span>
<strong>{t.name}</strong> <span className="hint">· {VISIBILITY[t.visibility] ?? t.visibility}</span> <strong>{t.name}</strong> <span className="hint">· {VISIBILITY[t.visibility] ?? t.visibility}</span>
{t.archived && <span className="hint"> · archivált</span>}
</span> </span>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy}
onClick={() =>
(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"}
</button>
<select <select
className="inp ftop-vis" className="inp ftop-vis"
aria-label={`${t.name} láthatósága`} aria-label={`${t.name} láthatósága`}
+27 -1
View File
@@ -173,7 +173,9 @@ export default async function ForumHomePage() {
<h2 id="fh-topics">Témák</h2> <h2 id="fh-topics">Témák</h2>
</div> </div>
<ul className="fh-card fh-flush fh-topics"> <ul className="fh-card fh-flush fh-topics">
{topics.map((t) => {topics
.filter((t) => !t.archived)
.map((t) =>
t.visibility === "restricted" && !t.readable ? ( t.visibility === "restricted" && !t.readable ? (
<li key={t.slug}> <li key={t.slug}>
<div className="fh-topic fh-topic-closed"> <div className="fh-topic fh-topic-closed">
@@ -240,6 +242,30 @@ export default async function ForumHomePage() {
), ),
)} )}
</ul> </ul>
{topics.some((t) => t.archived) && (
<details className="fh-archived">
<summary>Archivált témák ({topics.filter((t) => t.archived).length})</summary>
<ul className="fh-card fh-flush fh-links">
{topics
.filter((t) => t.archived && t.readable)
.map((t) => (
<li key={t.slug}>
<Link href={`/forum/${t.slug}`} className="fh-link">
<span className="fh-link-text">
{t.name}
<span className="hint">
{t.description} · {t.thread_count ?? 0} szál
</span>
</span>
<span className="fh-link-arrow" aria-hidden="true">
›
</span>
</Link>
</li>
))}
</ul>
</details>
)}
</section> </section>
</div> </div>
@@ -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<string | null>(null);
return (
<div className="fmute">
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy}
onClick={async () => {
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"}
</button>
{muted && <span className="hint">Elnémítottad: a szálai és az értesítései nem jelennek meg nálad.</span>}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
@@ -10,6 +10,7 @@ import { type MemberProfile, ago, banText, threadHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer"; import { forumGet } from "@/lib/forumServer";
import { BanPanel } from "./BanPanel"; import { BanPanel } from "./BanPanel";
import { MuteButton } from "./MuteButton";
import { RequestPanel } from "./RequestPanel"; import { RequestPanel } from "./RequestPanel";
type Props = { params: Promise<{ nev: string }> }; type Props = { params: Promise<{ nev: string }> };
@@ -70,6 +71,7 @@ export default async function MemberPage({ params }: Props) {
Profil szerkesztése Profil szerkesztése
</Link> </Link>
)} )}
{viewer.member && !member.own && <MuteButton nickname={a.nickname} muted={member.muted} />}
{viewer.moderator && !member.own && !a.moderator && ( {viewer.moderator && !member.own && !a.moderator && (
<BanPanel <BanPanel
nickname={a.nickname} nickname={a.nickname}
+1 -1
View File
@@ -18,7 +18,7 @@ export default async function NewThreadPage({ searchParams }: Props) {
const viewer = nav.ok ? nav.data.viewer : null; const viewer = nav.ok ? nav.data.viewer : null;
if (!viewer?.logged_in) redirect(`/belepes?vissza=${encodeURIComponent(back)}`); if (!viewer?.logged_in) redirect(`/belepes?vissza=${encodeURIComponent(back)}`);
if (viewer.needs_nickname) redirect(`/forum/beallitasok?vissza=${encodeURIComponent(back)}`); if (viewer.needs_nickname) redirect(`/forum/beallitasok?vissza=${encodeURIComponent(back)}`);
const topics = res.ok ? res.data.topics.filter((t) => 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 ?? ""; const initial = topics.find((t) => t.slug === tema)?.slug ?? topics[0]?.slug ?? "";
return ( return (
<div className="fh"> <div className="fh">
+18 -1
View File
@@ -54,7 +54,24 @@ const AI_SEARCH = [
]; ];
// Logged-in pages redirect anyway; shared links carry noindex. // 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<MetadataRoute.Robots> { export default async function robots(): Promise<MetadataRoute.Robots> {
return { return {
+16 -1
View File
@@ -2,6 +2,7 @@ import type { MetadataRoute } from "next";
import { ZODIAC } from "@/content/zodiac"; import { ZODIAC } from "@/content/zodiac";
import { loadCelebrities } from "@/lib/celebrities"; import { loadCelebrities } from "@/lib/celebrities";
import { forumEnabled, forumSitemap } from "@/lib/forumServer";
import { currentYear } from "@/lib/sky"; import { currentYear } from "@/lib/sky";
import { siteUrl } from "@/lib/share"; import { siteUrl } from "@/lib/share";
@@ -10,7 +11,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const base = await siteUrl(); const base = await siteUrl();
const privacy = { languages: { hu: `${base}/adatvedelem`, en: `${base}/privacy` } }; const privacy = { languages: { hu: `${base}/adatvedelem`, en: `${base}/privacy` } };
// The sitemap still works when the backend does not answer. // 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; const next = currentYear() + 1;
return [ return [
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 }, { url: `${base}/`, changeFrequency: "weekly", priority: 1 },
@@ -30,6 +31,20 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
changeFrequency: "monthly" as const, changeFrequency: "monthly" as const,
priority: 0.6, 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}/aszf`, changeFrequency: "yearly", priority: 0.2 },
{ url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 }, { url: `${base}/kapcsolat`, changeFrequency: "yearly", priority: 0.2 },
@@ -27,6 +27,8 @@ type Actions = {
remove: (post: ForumPost) => void; remove: (post: ForumPost) => void;
restore: (post: ForumPost) => void; restore: (post: ForumPost) => void;
helped: (post: ForumPost) => void; helped: (post: ForumPost) => void;
/** Mute or unmute the post's author. */
mute: (post: ForumPost) => void;
}; };
function ReactionRow({ function ReactionRow({
@@ -187,6 +189,7 @@ function PostCard({
const [reporting, setReporting] = useState(false); const [reporting, setReporting] = useState(false);
const [menu, setMenu] = useState(false); const [menu, setMenu] = useState(false);
const [showCollapsed, setShowCollapsed] = useState(false); const [showCollapsed, setShowCollapsed] = useState(false);
const [showMuted, setShowMuted] = useState(false);
const { viewer, thread, access } = page; const { viewer, thread, access } = page;
const writer = viewer.member !== null && !viewer.member.banned; const writer = viewer.member !== null && !viewer.member.banned;
const starter = post.author !== null && post.author.nickname === thread.author?.nickname; 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 (
<article className={nested ? "fp fp-muted fp-nested" : "fp fp-muted"} id={`h${post.id}`}>
<button type="button" className="fp-collapsed" onClick={() => setShowMuted(true)}>
{author?.nickname ?? "Egy tag"} hozzászólása · elnémítottad · Megjelenítés
</button>
</article>
);
}
const menuItems: { label: string; run: () => void; danger?: boolean }[] = []; const menuItems: { label: string; run: () => void; danger?: boolean }[] = [];
if (!post.deleted) { if (!post.deleted) {
if (access?.is_thread_author && !post.is_opening && !post.own && writer) { 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 && 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 (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.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) if (viewer.moderator && !post.own)
menuItems.push({ label: "Eltávolítás", run: () => actions.remove(post), danger: true }); menuItems.push({ label: "Eltávolítás", run: () => actions.remove(post), danger: true });
} else if (viewer.moderator) { } else if (viewer.moderator) {
@@ -515,6 +534,21 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
await api(`/forum/posts/${post.id}/restore`, { method: "POST" }); await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
await reload(); 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) => helped: (post) =>
void run(async () => { void run(async () => {
const updated = await api<ForumPost>(`/forum/posts/${post.id}/helped`, { const updated = await api<ForumPost>(`/forum/posts/${post.id}/helped`, {
@@ -738,7 +772,11 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
) : viewer.member?.banned ? ( ) : viewer.member?.banned ? (
<p className="ftv-gate">Most nem írhatsz a fórumba.</p> <p className="ftv-gate">Most nem írhatsz a fórumba.</p>
) : !access?.can_reply ? ( ) : !access?.can_reply ? (
<p className="ftv-gate">Ez a szál le van zárva, új hozzászólás nem írható.</p> <p className="ftv-gate">
{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ó."}
</p>
) : ( ) : (
<> <>
<Composer <Composer
+8 -2
View File
@@ -42,6 +42,8 @@ export interface ForumTopic extends TopicRef {
description: string; description: string;
visibility: "public" | "members" | "restricted"; visibility: "public" | "members" | "restricted";
listening: boolean; listening: boolean;
/** Archived: readable, but takes nothing new. */
archived?: boolean;
readable: boolean; readable: boolean;
/** A restricted topic: the viewer's place in it. */ /** A restricted topic: the viewer's place in it. */
membership?: "none" | "pending" | "approved" | null; membership?: "none" | "pending" | "approved" | null;
@@ -84,7 +86,7 @@ export interface ForumHome {
export interface TopicPage { export interface TopicPage {
viewer: ForumViewer; viewer: ForumViewer;
topic: TopicRef & { description: string; visibility: string; listening: boolean }; topic: TopicRef & { description: string; visibility: string; listening: boolean; archived?: boolean };
threads: ThreadCard[]; threads: ThreadCard[];
page: number; page: number;
has_more: boolean; has_more: boolean;
@@ -113,6 +115,8 @@ export interface ForumPost {
system?: boolean; system?: boolean;
/** The post this reply answered (it may sit on the same level). */ /** The post this reply answered (it may sit on the same level). */
reply_to?: { id: number; nickname: string | null } | null; reply_to?: { id: number; nickname: string | null } | null;
/** The viewer muted the author: shown folded up. */
muted?: boolean;
} }
export interface ThreadPage { export interface ThreadPage {
@@ -122,7 +126,7 @@ export interface ThreadPage {
slug: string; slug: string;
title: string; title: string;
intent: "listen" | "advice" | null; intent: "listen" | "advice" | null;
topic: TopicRef & { visibility: string; listening: boolean }; topic: TopicRef & { visibility: string; listening: boolean; archived?: boolean };
author: ForumAuthor | null; author: ForumAuthor | null;
created_at: string; created_at: string;
locked: boolean; locked: boolean;
@@ -188,6 +192,8 @@ export interface MemberProfile {
thread_count: number; thread_count: number;
last_seen: "online" | "day" | "week" | "earlier" | null; last_seen: "online" | "day" | "week" | "earlier" | null;
own: boolean; own: boolean;
/** The viewer muted them. */
muted: boolean;
banned_until: string | null; banned_until: string | null;
ban_reason: string | null; ban_reason: string | null;
}; };
+15
View File
@@ -27,3 +27,18 @@ export async function forumGet<T>(path: string): Promise<ForumResult<T>> {
if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`); if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`);
return { ok: true, data: (await res.json()) as T }; 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;
}
}
+3 -3
View File
@@ -130,7 +130,7 @@ pub async fn listeners_once(db: &PgPool, base_url: &str) -> Result<usize, sqlx::
let threads: Vec<(i64, String, Option<Uuid>)> = sqlx::query_as(&format!( let threads: Vec<(i64, String, Option<Uuid>)> = 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 \ "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 \ 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.intent = 'listen' OR tp.listening) \
AND th.created_at < now() - interval '{LISTENER_AFTER}' AND th.created_at > now() - interval '3 days' \ 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" 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( 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 \ "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' \ 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", GROUP BY th.id, th.title ORDER BY count(p.id) DESC, max(p.id) DESC LIMIT 5",
) )
.fetch_all(db) .fetch_all(db)
@@ -198,7 +198,7 @@ pub async fn weekly_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<
let waiting: Vec<String> = sqlx::query_scalar( let waiting: Vec<String> = sqlx::query_scalar(
"SELECT th.title FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ "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 \ 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", ORDER BY th.created_at LIMIT 3",
) )
.fetch_all(db) .fetch_all(db)
+1 -1
View File
@@ -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 mut tx = db.begin().await?;
let thread: Option<i64> = sqlx::query_scalar( let thread: Option<i64> = sqlx::query_scalar(
"INSERT INTO forum.threads (topic_id, author_id, title, system, pinned, daily_date) \ "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", ON CONFLICT (daily_date) DO NOTHING RETURNING id",
) )
.bind(TOPIC) .bind(TOPIC)