//! The forum's front page, the topics, a topic's threads, followed threads. use axum::Json; use axum::extract::{Path, Query, State}; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use time::OffsetDateTime; use uuid::Uuid; use super::{CardRow, St, card_params, card_sql, cards_json, may_read, rfc3339}; use crate::auth::Viewer; use crate::error::{ApiError, ApiResult}; /// Threads on one page of a topic. const PAGE_SIZE: i64 = 30; /// "Pörgős most": at least this many replies in the last 24 hours. const HOT_MIN_REPLIES: i64 = 3; /// "Várják a válaszod": threads without a reply from the last two weeks. const UNANSWERED_DAYS: i32 = 14; #[derive(sqlx::FromRow)] struct TopicRow { id: i16, slug: String, name: String, description: String, visibility: String, listening: bool, thread_count: i64, new_count: Option, last_author: Option, last_at: Option, } /// The topics in order: counts and the latest post for those the viewer may /// read, the others (a members-only topic for a visitor) only by name. 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, \ (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 \ WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \ AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2::timestamptz \ AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS new_count, \ last.author_id AS last_author, last.created_at AS last_at \ FROM forum.topics tp \ LEFT JOIN LATERAL (SELECT p.author_id, p.created_at FROM forum.posts p \ JOIN forum.threads th ON th.id = p.thread_id \ WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \ ORDER BY p.id DESC LIMIT 1) last ON true \ ORDER BY tp.position", ) .bind(me) .bind(since) .fetch_all(&state.db) .await?; let readable: Vec = rows.iter().map(|r| may_read(viewer, &r.visibility, r.id)).collect(); let people = super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author)) .await?; // A restricted topic shows by name to members, who may ask to join. let pending: Vec = match viewer.user_id() { Some(me) => { sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'pending'") .bind(me) .fetch_all(&state.db) .await? } None => Vec::new(), }; Ok(rows .into_iter() .zip(readable) .filter(|(r, _)| r.visibility != "restricted" || viewer.member.is_some() || viewer.is_moderator()) .map(|(r, readable)| { let membership = (r.visibility == "restricted").then(|| { if viewer.topics.contains(&r.id) { "approved" } else if pending.contains(&r.id) { "pending" } else { "none" } }); let mut topic = json!({ "id": r.id, "slug": r.slug, "name": r.name, "description": r.description, "visibility": r.visibility, "listening": r.listening, "readable": readable, "membership": membership, }); if readable { topic["thread_count"] = json!(r.thread_count); topic["new_count"] = json!(r.new_count); topic["last"] = json!(r.last_at.map(|at| json!({ "author": r.last_author.and_then(|id| people.get(&id).cloned()), "at": rfc3339(at), }))); } topic }) .collect()) } /// What the header and the front page show about the viewer. pub fn viewer_json(viewer: &Viewer) -> Value { let now = OffsetDateTime::now_utc(); json!({ "logged_in": viewer.logged_in(), "needs_nickname": viewer.logged_in() && viewer.member.is_none(), "moderator": viewer.is_moderator(), "member": viewer.member.as_ref().map(|m| { let rank = m.rank(now); json!({ "nickname": m.nickname, "avatar": m.avatar, "rank": rank, "rank_name": rank.name(), "banned": m.banned(now), }) }), }) } /// The front page: the viewer, new replies in followed threads, the topics, /// threads waiting for a first reply, and the busiest threads of the day. pub async fn home(state: St, viewer: Viewer) -> ApiResult> { let (me, since) = card_params(&viewer); let topics = topic_list(&state, &viewer).await?; 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.created_at > now() - make_interval(days => $3) \ ORDER BY th.created_at LIMIT 3", card_sql(&viewer) )) .bind(me) .bind(since) .bind(UNANSWERED_DAYS) .fetch_all(&state.db) .await?; let hot: Vec = sqlx::query_as(&format!( "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) \ ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5", card_sql(&viewer) )) .bind(me) .bind(since) .bind(HOT_MIN_REPLIES) .fetch_all(&state.db) .await?; // "Most itt vannak": members seen in the last few minutes (not the invisible ones). let present: Vec = sqlx::query_scalar( "SELECT user_id FROM forum.members WHERE NOT invisible \ AND last_seen_at > now() - make_interval(mins => $1) ORDER BY last_seen_at DESC LIMIT 24", ) .bind(crate::auth::ONLINE_MINUTES as i32) .fetch_all(&state.db) .await?; let people = super::authors(&state.db, present.iter().copied()).await?; let online: Vec = present.iter().filter_map(|id| people.get(id).cloned()).collect(); // Volunteer listeners: threads asking to be heard, still without a reply. let waiting = match &viewer.member { Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?), _ => None, }; let replies = match &viewer.member { Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?), None => None, }; Ok(Json(json!({ "viewer": viewer_json(&viewer), "followed": followed, "replies": replies, "waiting": waiting, "online": online, "topics": topics, "unanswered": cards_json(&state.db, unanswered).await?, "hot": cards_json(&state.db, hot).await?, }))) } /// New replies (by others, unread) in the member's followed threads. async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult> { let (Some(me), Some(since)) = card_params(viewer) else { return Ok(None) }; let (replies, threads): (i64, i64) = sqlx::query_as( "SELECT count(*), count(DISTINCT p.thread_id) FROM forum.follows f \ 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 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)", ) .bind(me) .bind(since) .fetch_one(&state.db) .await?; Ok(Some(json!({ "new_replies": replies, "threads": threads }))) } /// Threads asking to be heard (or in a listening topic) that have waited an /// hour without a reply (two weeks at most), not the listener's own. pub const WAITING_SQL: &str = "th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \ AND th.created_at < now() - interval '1 hour' AND th.created_at > now() - interval '14 days' \ AND (th.intent = 'listen' OR tp.listening)"; async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult { let me = viewer.user_id(); Ok(sqlx::query_scalar(&format!( "SELECT count(*) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ WHERE {WAITING_SQL} AND th.author_id IS DISTINCT FROM $1 AND ({})", super::visible_topics(viewer) )) .bind(me) .fetch_one(&state.db) .await?) } /// For the forum's menu on every page: who the viewer is, and the badge. pub async fn nav(state: St, viewer: Viewer) -> ApiResult> { let messages = match &viewer.member { Some(m) => Some(super::messages::unread_count(&state.db, m.user_id).await?), None => None, }; let reports = if viewer.is_moderator() { let requests: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.topic_members WHERE status = 'pending'") .fetch_one(&state.db) .await?; Some(super::reports::open_count(&state.db).await? + requests) } else { None }; // The only count on the forum tab: unread answers to the member. let replies = match &viewer.member { Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?), None => None, }; Ok(Json(json!({ "viewer": viewer_json(&viewer), "replies": replies, "messages": messages, "reports": reports, }))) } pub async fn topics(state: St, viewer: Viewer) -> ApiResult> { Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? }))) } #[derive(Deserialize)] pub struct PageQuery { #[serde(default)] page: Option, } /// A topic's threads: pinned ones first, then by the latest post. pub async fn topic( State(state): St, viewer: Viewer, 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"))?; 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") }); } let page = q.page.unwrap_or(1).clamp(1, 10_000); let (me, since) = card_params(&viewer); let rows: Vec = sqlx::query_as(&format!( "{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5", card_sql(&viewer) )) .bind(me) .bind(since) .bind(id) .bind(PAGE_SIZE + 1) .bind((page - 1) * PAGE_SIZE) .fetch_all(&state.db) .await?; let has_more = rows.len() as i64 > PAGE_SIZE; let rows = rows.into_iter().take(PAGE_SIZE as usize).collect(); Ok(Json(json!({ "viewer": viewer_json(&viewer), "topic": { "slug": slug, "name": name, "description": description, "visibility": visibility, "listening": listening, }, "threads": cards_json(&state.db, rows).await?, "page": page, "has_more": has_more, }))) } /// The threads the member follows, the latest activity first, with what is unread. pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult> { viewer.require_member()?; let (me, since) = card_params(&viewer); let rows: Vec = sqlx::query_as(&format!( "{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \ ORDER BY th.last_post_at DESC LIMIT 50", card_sql(&viewer) )) .bind(me) .bind(since) .fetch_all(&state.db) .await?; Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? }))) }