Forum: a service of its own and the /forum pages
services/forum (axum, port 8083) on the same database and login, in the forum schema (migration 0038, which also adds the moderator role): nicknames, profiles with shared signs, topics, threads with listening or advice intent, two-level replies, read marks and followed threads, reactions as ratings with points and ranks, newcomer limits (lifted by a purchase), moderation with reasons, bans and a log. Integration tests run in CI. The frontend's /forum pages (light by default, dark on request, phone first with a desktop layout) are switched on by FORUM_URL; the /api/v1 proxy sends /api/v1/forum/* to the forum service. Concept and status: docs/kozosseg.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "forum"
|
||||
description = "Sorsfonalak forum: pseudonymous members, topics, threads, posts, reactions, moderation"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
db.workspace = true
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
axum.workspace = true
|
||||
axum-extra.workspace = true
|
||||
deunicode.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sqlx.workspace = true
|
||||
thiserror.workspace = true
|
||||
time.workspace = true
|
||||
tokio.workspace = true
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
http-body-util = "0.1"
|
||||
@@ -0,0 +1,33 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Build from the repository root:
|
||||
# docker build -f services/forum/Dockerfile -t sorsfonalak/forum .
|
||||
|
||||
ARG RUST_VERSION=1.99
|
||||
|
||||
# --- 1. static (musl) build ----------------------------------------------------
|
||||
FROM rust:${RUST_VERSION}-alpine AS build
|
||||
RUN apk add --no-cache musl-dev
|
||||
WORKDIR /app
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates crates
|
||||
COPY services services
|
||||
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,target=/app/target,sharing=locked \
|
||||
cargo build --release --locked -p forum \
|
||||
&& cp target/release/forum /forum
|
||||
# The log directory (LOG_DIR); a volume mounted here takes over its owner.
|
||||
RUN mkdir /logs
|
||||
|
||||
# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) ---
|
||||
FROM scratch
|
||||
COPY --from=build /forum /forum
|
||||
COPY --from=build --chown=65532:65532 /logs /logs
|
||||
ENV BIND_ADDR=0.0.0.0:8083 \
|
||||
LOG_FORMAT=json \
|
||||
RUST_LOG=info
|
||||
USER 65532:65532
|
||||
EXPOSE 8083
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
|
||||
CMD ["/forum", "healthcheck"]
|
||||
ENTRYPOINT ["/forum"]
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Who is asking: the backend's session (cookie or Bearer token) and the
|
||||
//! member behind it. Reading needs no login; writing needs a nickname.
|
||||
//! Every request of a member also keeps the online dot fresh.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use db::{Role, User};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::rank::Rank;
|
||||
|
||||
pub const SESSION_COOKIE: &str = "sf_session";
|
||||
|
||||
/// How long a member counts as online after the last request.
|
||||
pub const ONLINE_MINUTES: i64 = 5;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct Member {
|
||||
pub user_id: Uuid,
|
||||
pub nickname: String,
|
||||
pub avatar: String,
|
||||
pub bio: String,
|
||||
pub chart_share: String,
|
||||
pub invisible: bool,
|
||||
pub points: i32,
|
||||
pub post_count: i32,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub nickname_changed_at: OffsetDateTime,
|
||||
pub banned_until: Option<OffsetDateTime>,
|
||||
pub ban_reason: Option<String>,
|
||||
}
|
||||
|
||||
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
|
||||
created_at, nickname_changed_at, banned_until, ban_reason";
|
||||
|
||||
impl Member {
|
||||
pub fn rank(&self, now: OffsetDateTime) -> Rank {
|
||||
Rank::of(self.points, self.created_at, now)
|
||||
}
|
||||
|
||||
pub fn banned(&self, now: OffsetDateTime) -> bool {
|
||||
self.banned_until.is_some_and(|until| until > now)
|
||||
}
|
||||
}
|
||||
|
||||
/// The visitor: maybe logged in, maybe a member (has chosen a nickname).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Viewer {
|
||||
pub user: Option<User>,
|
||||
pub member: Option<Member>,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
pub fn user_id(&self) -> Option<Uuid> {
|
||||
self.user.as_ref().map(|u| u.id)
|
||||
}
|
||||
|
||||
pub fn logged_in(&self) -> bool {
|
||||
self.user.is_some()
|
||||
}
|
||||
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.user.as_ref().is_some_and(|u| u.has_role(Role::Admin))
|
||||
}
|
||||
|
||||
/// A moderator or an admin.
|
||||
pub fn is_moderator(&self) -> bool {
|
||||
self.user.as_ref().is_some_and(|u| u.has_role(Role::Moderator) || u.has_role(Role::Admin))
|
||||
}
|
||||
|
||||
pub fn require_user(&self) -> Result<&User, ApiError> {
|
||||
self.user.as_ref().ok_or(ApiError::Unauthorized)
|
||||
}
|
||||
|
||||
pub fn require_member(&self) -> Result<&Member, ApiError> {
|
||||
self.require_user()?;
|
||||
self.member.as_ref().ok_or(ApiError::NicknameRequired)
|
||||
}
|
||||
|
||||
/// A member who may write (not banned).
|
||||
pub fn require_writer(&self) -> Result<&Member, ApiError> {
|
||||
let member = self.require_member()?;
|
||||
if member.banned(OffsetDateTime::now_utc()) {
|
||||
let reason = member.ban_reason.as_deref().map(|r| format!(" Indok: {r}")).unwrap_or_default();
|
||||
return Err(ApiError::Banned(format!("Most nem írhatsz a fórumba.{reason}")));
|
||||
}
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub fn require_moderator(&self) -> Result<&User, ApiError> {
|
||||
let user = self.require_user()?;
|
||||
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
|
||||
}
|
||||
}
|
||||
|
||||
fn session_token(parts: &Parts) -> Option<String> {
|
||||
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
|
||||
&& let Some(token) = value.strip_prefix("Bearer ")
|
||||
{
|
||||
return Some(token.trim().to_string());
|
||||
}
|
||||
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
|
||||
}
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
|
||||
let member = load_member(&state.db, user.id).await?;
|
||||
if member.is_some() {
|
||||
// At most once a minute per member: the online dot.
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET last_seen_at = now() \
|
||||
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
|
||||
)
|
||||
.bind(user.id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
}
|
||||
Ok(Viewer { user: Some(user), member })
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_member(db: &sqlx::PgPool, user_id: Uuid) -> Result<Option<Member>, sqlx::Error> {
|
||||
sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1"))
|
||||
.bind(user_id)
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
use axum::Json;
|
||||
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde_json::json;
|
||||
|
||||
/// API error, rendered as `{"error": {"code", "message"}}` like the backend's.
|
||||
/// Messages meant for the user are Hungarian.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ApiError {
|
||||
#[error("{0}")]
|
||||
BadRequest(String),
|
||||
#[error("authentication required")]
|
||||
Unauthorized,
|
||||
/// Logged in, but no nickname yet: the frontend sends the user to choose one.
|
||||
#[error("Előbb válassz álnevet.")]
|
||||
NicknameRequired,
|
||||
#[error("{0}")]
|
||||
Forbidden(String),
|
||||
/// Banned from writing; the message tells until when.
|
||||
#[error("{0}")]
|
||||
Banned(String),
|
||||
#[error("{0} not found")]
|
||||
NotFound(&'static str),
|
||||
#[error("{message}")]
|
||||
Conflict { code: &'static str, message: String },
|
||||
/// A usage limit; the message is shown to the user as is.
|
||||
#[error("{0}")]
|
||||
Limited(String),
|
||||
#[error("internal error")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
|
||||
ApiError::Conflict { code, message: message.into() }
|
||||
}
|
||||
|
||||
pub fn bad(message: impl Into<String>) -> Self {
|
||||
ApiError::BadRequest(message.into())
|
||||
}
|
||||
|
||||
fn status_and_code(&self) -> (StatusCode, &'static str) {
|
||||
match self {
|
||||
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
|
||||
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
|
||||
ApiError::NicknameRequired => (StatusCode::FORBIDDEN, "nickname_required"),
|
||||
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
|
||||
ApiError::Banned(_) => (StatusCode::FORBIDDEN, "banned"),
|
||||
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
|
||||
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
|
||||
ApiError::Limited(_) => (StatusCode::TOO_MANY_REQUESTS, "limited"),
|
||||
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, code) = self.status_and_code();
|
||||
if let ApiError::Internal(detail) = &self {
|
||||
tracing::error!(error = %detail, code, "request failed");
|
||||
}
|
||||
(status, Json(json!({ "error": { "code": code, "message": self.to_string() } }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for ApiError {
|
||||
fn from(e: sqlx::Error) -> Self {
|
||||
ApiError::Internal(format!("database: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for ApiError {
|
||||
fn from(rejection: JsonRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<QueryRejection> for ApiError {
|
||||
fn from(rejection: QueryRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathRejection> for ApiError {
|
||||
fn from(rejection: PathRejection) -> Self {
|
||||
ApiError::BadRequest(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
pub type ApiResult<T> = Result<T, ApiError>;
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Sorsfonalak forum: pseudonymous members, topics, threads, posts,
|
||||
//! reactions, read marks, followed threads and moderation (docs/kozosseg.md).
|
||||
//!
|
||||
//! A service of its own, so it can be scaled apart from the backend. It shares
|
||||
//! the database and the login: a session of the backend (`sf_session` cookie
|
||||
//! or `Authorization: Bearer`) is valid here too.
|
||||
//!
|
||||
//! Configuration: `DATABASE_URL`; `BIND_ADDR` (default `0.0.0.0:8083`),
|
||||
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
|
||||
//!
|
||||
//! `forum healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod auth;
|
||||
mod error;
|
||||
mod rank;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod text;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use sqlx::PgPool;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8083";
|
||||
|
||||
pub struct AppState {
|
||||
pub db: PgPool,
|
||||
/// Seconds a member waits between two posts (0 in the tests).
|
||||
pub flood_secs: i32,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(db: PgPool) -> Self {
|
||||
Self { db, flood_secs: 5 }
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
|
||||
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||
return service_kit::healthcheck(addr);
|
||||
}
|
||||
let _log = service_kit::init_logging("forum");
|
||||
let url = std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?;
|
||||
let pool = db::connect(&url).await.context("connecting to the database")?;
|
||||
db::migrate(&pool).await.context("running database migrations")?;
|
||||
let app = routes::router(Arc::new(AppState::new(pool)));
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "listening");
|
||||
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Ranks: earned from points (reactions and "Ez segített" marks received)
|
||||
//! and time spent as a member, so nobody climbs in a few days. A rank is
|
||||
//! also a permission level. Buying a package gives no rank: it only lifts the
|
||||
//! newcomer's daily limits (docs/kozosseg.md).
|
||||
|
||||
use serde::Serialize;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Rank {
|
||||
Vandor,
|
||||
Kereso,
|
||||
Fono,
|
||||
Csillagfono,
|
||||
Sorsfono,
|
||||
}
|
||||
|
||||
/// (rank, points needed, days of membership needed), lowest first.
|
||||
const LADDER: [(Rank, i32, i64); 5] = [
|
||||
(Rank::Vandor, i32::MIN, 0),
|
||||
(Rank::Kereso, 5, 3),
|
||||
(Rank::Fono, 30, 14),
|
||||
(Rank::Csillagfono, 100, 45),
|
||||
(Rank::Sorsfono, 300, 120),
|
||||
];
|
||||
|
||||
/// What an "Ez segített" mark is worth.
|
||||
pub const HELPED_POINTS: i32 = 5;
|
||||
/// Newcomer limits (lifted by a purchase): new threads and posts in 24 hours.
|
||||
pub const NEWCOMER_THREADS_PER_DAY: i64 = 3;
|
||||
pub const NEWCOMER_POSTS_PER_DAY: i64 = 20;
|
||||
/// A post whose reactions add up to this or less is shown collapsed.
|
||||
pub const COLLAPSE_SCORE: i64 = -3;
|
||||
|
||||
impl Rank {
|
||||
pub fn of(points: i32, member_since: OffsetDateTime, now: OffsetDateTime) -> Rank {
|
||||
let days = (now - member_since).whole_days();
|
||||
LADDER.iter().rev().find(|(_, p, d)| points >= *p && days >= *d).map(|(r, _, _)| *r).unwrap_or(Rank::Vandor)
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Rank::Vandor => "Vándor",
|
||||
Rank::Kereso => "Kereső",
|
||||
Rank::Fono => "Fonó",
|
||||
Rank::Csillagfono => "Csillagfonó",
|
||||
Rank::Sorsfono => "Sorsfonó",
|
||||
}
|
||||
}
|
||||
|
||||
/// A newcomer: daily limits, reactions that do not count yet, no ⌄.
|
||||
pub fn is_newcomer(self) -> bool {
|
||||
self == Rank::Vandor
|
||||
}
|
||||
|
||||
/// May use the ⌄ (never in a listening topic).
|
||||
pub fn may_downvote(self) -> bool {
|
||||
self >= Rank::Kereso
|
||||
}
|
||||
|
||||
/// The next rank and what it needs, for the member's own profile.
|
||||
pub fn next(self) -> Option<(Rank, i32, i64)> {
|
||||
LADDER.iter().find(|(r, _, _)| *r > self).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ranks_need_points_and_time() {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let days = |d: i64| now - time::Duration::days(d);
|
||||
assert_eq!(Rank::of(0, days(400), now), Rank::Vandor);
|
||||
assert_eq!(Rank::of(500, days(1), now), Rank::Vandor, "points alone are not enough");
|
||||
assert_eq!(Rank::of(5, days(3), now), Rank::Kereso);
|
||||
assert_eq!(Rank::of(40, days(20), now), Rank::Fono);
|
||||
assert_eq!(Rank::of(40, days(400), now), Rank::Fono);
|
||||
assert_eq!(Rank::of(300, days(120), now), Rank::Sorsfono);
|
||||
assert_eq!(Rank::Vandor.next().map(|n| n.0), Some(Rank::Kereso));
|
||||
assert_eq!(Rank::Sorsfono.next(), None);
|
||||
assert!(!Rank::Vandor.may_downvote() && Rank::Kereso.may_downvote());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! 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<i64>,
|
||||
last_author: Option<Uuid>,
|
||||
last_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// 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<Vec<Value>> {
|
||||
let (me, since) = card_params(viewer);
|
||||
let rows: Vec<TopicRow> = sqlx::query_as(
|
||||
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \
|
||||
(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<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility)).collect();
|
||||
let people =
|
||||
super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author))
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.zip(readable)
|
||||
.filter(|(r, _)| r.visibility != "restricted" || viewer.is_moderator())
|
||||
.map(|(r, readable)| {
|
||||
let mut topic = json!({
|
||||
"id": r.id,
|
||||
"slug": r.slug,
|
||||
"name": r.name,
|
||||
"description": r.description,
|
||||
"visibility": r.visibility,
|
||||
"listening": r.listening,
|
||||
"readable": readable,
|
||||
});
|
||||
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<Json<Value>> {
|
||||
let (me, since) = card_params(&viewer);
|
||||
let topics = topic_list(&state, &viewer).await?;
|
||||
|
||||
let followed = followed_counts(&state, &viewer).await?;
|
||||
|
||||
let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 \
|
||||
AND th.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<CardRow> = 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?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"followed": followed,
|
||||
"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<Option<Value>> {
|
||||
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 })))
|
||||
}
|
||||
|
||||
/// For the forum's menu on every page: who the viewer is, and the badge.
|
||||
pub async fn nav(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(json!({ "viewer": viewer_json(&viewer), "followed": followed_counts(&state, &viewer).await? })))
|
||||
}
|
||||
|
||||
pub async fn topics(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PageQuery {
|
||||
#[serde(default)]
|
||||
page: Option<i64>,
|
||||
}
|
||||
|
||||
/// 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<Path<String>, ApiError>,
|
||||
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let topic: Option<(i16, String, String, String, bool)> =
|
||||
sqlx::query_as("SELECT id, name, description, visibility, listening FROM forum.topics WHERE slug = $1")
|
||||
.bind(&slug)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?;
|
||||
if !may_read(&viewer, &visibility) {
|
||||
// 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<CardRow> = 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<Json<Value>> {
|
||||
viewer.require_member()?;
|
||||
let (me, since) = card_params(&viewer);
|
||||
let rows: Vec<CardRow> = 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? })))
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Members: one's own forum profile (nickname first), the nickname check
|
||||
//! while typing, the online heartbeat, and a member's public profile.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::home::viewer_json;
|
||||
use super::{Body, St, authors, online, rfc3339, shared_signs, visible_topics};
|
||||
use crate::auth::{self, Viewer};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
/// A nickname may change once in this many days (spelling fixes that keep the
|
||||
/// same folded form any time).
|
||||
const NICKNAME_CHANGE_DAYS: i64 = 30;
|
||||
/// A nickname given up stays reserved this long.
|
||||
const NICKNAME_RESERVED_DAYS: i64 = 90;
|
||||
|
||||
/// The viewer's own forum profile, and what each chart sharing level would show.
|
||||
pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
let user = viewer.require_user()?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let member = viewer.member.as_ref().map(|m| {
|
||||
let rank = m.rank(now);
|
||||
let change_after = m.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
|
||||
json!({
|
||||
"nickname": m.nickname,
|
||||
"avatar": m.avatar,
|
||||
"bio": m.bio,
|
||||
"chart_share": m.chart_share,
|
||||
"invisible": m.invisible,
|
||||
"points": m.points,
|
||||
"post_count": m.post_count,
|
||||
"created_at": rfc3339(m.created_at),
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"next_rank": rank.next().map(|(r, points, days)| json!({
|
||||
"rank": r, "name": r.name(), "points": points, "days": days,
|
||||
})),
|
||||
"nickname_change_after": (change_after > now).then(|| rfc3339(change_after)),
|
||||
"banned_until": m.banned_until.filter(|u| *u > now).map(|u| {
|
||||
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||
}),
|
||||
"ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)),
|
||||
})
|
||||
});
|
||||
let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id);
|
||||
let chart = signs.map(|s| json!({ "sun": s.share("sun"), "big3": s.share("big3"), "planets": s.share("planets") }));
|
||||
Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SaveMe {
|
||||
nickname: String,
|
||||
#[serde(default)]
|
||||
avatar: Option<String>,
|
||||
#[serde(default)]
|
||||
bio: Option<String>,
|
||||
#[serde(default)]
|
||||
chart_share: Option<String>,
|
||||
#[serde(default)]
|
||||
invisible: Option<bool>,
|
||||
}
|
||||
|
||||
/// Whether someone else has (or recently had) this folded nickname.
|
||||
async fn nickname_taken(db: &sqlx::PgPool, key: &str, me: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT EXISTS (SELECT 1 FROM forum.members WHERE nickname_key = $1 AND user_id <> $2) \
|
||||
OR EXISTS (SELECT 1 FROM forum.retired_nicknames \
|
||||
WHERE nickname_key = $1 AND user_id <> $2 AND until > now())",
|
||||
)
|
||||
.bind(key)
|
||||
.bind(me)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
|
||||
fn taken() -> ApiError {
|
||||
ApiError::conflict("nickname_taken", "Ezt az álnevet már más használja. Válassz másikat.")
|
||||
}
|
||||
|
||||
/// Creates the forum profile (choosing a nickname is the first step) or changes it.
|
||||
pub async fn save_me(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<SaveMe>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let user = viewer.require_user()?;
|
||||
let nickname = text::nickname(&req.nickname)?;
|
||||
let key = text::nickname_key(&nickname);
|
||||
let avatar = req.avatar.as_deref().map(text::avatar).transpose()?;
|
||||
let bio = req.bio.as_deref().map(text::bio).transpose()?;
|
||||
let chart_share = match req.chart_share.as_deref() {
|
||||
None => None,
|
||||
Some(level @ ("none" | "sun" | "big3" | "planets")) => Some(level.to_string()),
|
||||
Some(_) => return Err(ApiError::bad("Ismeretlen megosztási szint.")),
|
||||
};
|
||||
if nickname_taken(&state.db, &key, user.id).await? {
|
||||
return Err(taken());
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut tx = state.db.begin().await?;
|
||||
let result = match &viewer.member {
|
||||
None => {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, bio, chart_share, invisible) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(&nickname)
|
||||
.bind(&key)
|
||||
.bind(avatar.unwrap_or_else(|| text::default_avatar(&key)))
|
||||
.bind(bio.unwrap_or_default())
|
||||
.bind(chart_share.unwrap_or_else(|| "none".into()))
|
||||
.bind(req.invisible.unwrap_or(false))
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
}
|
||||
Some(member) => {
|
||||
let old_key = text::nickname_key(&member.nickname);
|
||||
let renamed = old_key != key;
|
||||
if renamed {
|
||||
let allowed = member.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
|
||||
if allowed > now {
|
||||
return Err(ApiError::conflict(
|
||||
"nickname_too_soon",
|
||||
format!("Az álneved {NICKNAME_CHANGE_DAYS} naponta egyszer változtathatod meg."),
|
||||
));
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.retired_nicknames (nickname_key, user_id, until) \
|
||||
VALUES ($1, $2, now() + make_interval(days => $3)) \
|
||||
ON CONFLICT (nickname_key) DO UPDATE SET user_id = EXCLUDED.user_id, until = EXCLUDED.until",
|
||||
)
|
||||
.bind(&old_key)
|
||||
.bind(user.id)
|
||||
.bind(NICKNAME_RESERVED_DAYS as i32)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Taking back one's own earlier name.
|
||||
sqlx::query("DELETE FROM forum.retired_nicknames WHERE nickname_key = $1 AND user_id = $2")
|
||||
.bind(&key)
|
||||
.bind(user.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET nickname = $2, nickname_key = $3, \
|
||||
avatar = COALESCE($4, avatar), bio = COALESCE($5, bio), \
|
||||
chart_share = COALESCE($6, chart_share), invisible = COALESCE($7, invisible), \
|
||||
nickname_changed_at = CASE WHEN $8 THEN now() ELSE nickname_changed_at END \
|
||||
WHERE user_id = $1",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(&nickname)
|
||||
.bind(&key)
|
||||
.bind(avatar)
|
||||
.bind(bio)
|
||||
.bind(chart_share)
|
||||
.bind(req.invisible)
|
||||
.bind(renamed)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(_) => {}
|
||||
// Someone took it in the same moment.
|
||||
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => return Err(taken()),
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
tx.commit().await?;
|
||||
let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer };
|
||||
me(State(state), viewer).await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NameQuery {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// While typing: is this nickname valid and free?
|
||||
pub async fn nickname_check(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Query(q), _): WithRejection<Query<NameQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let user = viewer.require_user()?;
|
||||
let nickname = match text::nickname(&q.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return Ok(Json(json!({ "ok": false, "message": e.to_string() }))),
|
||||
};
|
||||
if nickname_taken(&state.db, &text::nickname_key(&nickname), user.id).await? {
|
||||
return Ok(Json(json!({ "ok": false, "message": taken().to_string() })));
|
||||
}
|
||||
Ok(Json(json!({ "ok": true, "nickname": nickname })))
|
||||
}
|
||||
|
||||
/// The page is open: keeps the online dot (the viewer extractor does the work).
|
||||
pub async fn presence(_viewer: Viewer) -> StatusCode {
|
||||
StatusCode::NO_CONTENT
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ProfileRow {
|
||||
user_id: Uuid,
|
||||
bio: String,
|
||||
created_at: OffsetDateTime,
|
||||
post_count: i32,
|
||||
invisible: bool,
|
||||
last_seen_at: Option<OffsetDateTime>,
|
||||
banned_until: Option<OffsetDateTime>,
|
||||
ban_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct RecentRow {
|
||||
id: i64,
|
||||
thread_id: i64,
|
||||
title: String,
|
||||
topic_slug: String,
|
||||
topic_name: String,
|
||||
created_at: OffsetDateTime,
|
||||
excerpt: String,
|
||||
is_opening: bool,
|
||||
}
|
||||
|
||||
/// A member's public profile: nickname, avatar, rank, shared signs, bio,
|
||||
/// activity (coarsely), and recent posts from the topics the viewer may read.
|
||||
pub async fn profile(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row: ProfileRow = sqlx::query_as(
|
||||
"SELECT user_id, bio, created_at, post_count, invisible, last_seen_at, banned_until, ban_reason \
|
||||
FROM forum.members WHERE nickname_key = $1",
|
||||
)
|
||||
.bind(text::nickname_key(&nickname))
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("member"))?;
|
||||
let brief = authors(&state.db, [row.user_id]).await?.remove(&row.user_id).ok_or(ApiError::NotFound("member"))?;
|
||||
let recent: Vec<RecentRow> = sqlx::query_as(&format!(
|
||||
"SELECT p.id, p.thread_id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, p.created_at, \
|
||||
left(p.body, 200) AS excerpt, p.is_opening \
|
||||
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE p.author_id = $1 AND p.deleted_at IS NULL AND th.deleted_at IS NULL AND ({}) \
|
||||
ORDER BY p.id DESC LIMIT 10",
|
||||
visible_topics(&viewer)
|
||||
))
|
||||
.bind(row.user_id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let thread_count: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM forum.threads WHERE author_id = $1 AND deleted_at IS NULL")
|
||||
.bind(row.user_id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let own = viewer.user_id() == Some(row.user_id);
|
||||
let last_seen = if row.invisible && !own {
|
||||
None
|
||||
} else if online(false, row.last_seen_at, now) {
|
||||
Some("online")
|
||||
} else {
|
||||
row.last_seen_at.map(|t| match now - t {
|
||||
d if d < time::Duration::days(1) => "day",
|
||||
d if d < time::Duration::days(7) => "week",
|
||||
_ => "earlier",
|
||||
})
|
||||
};
|
||||
let banned = row.banned_until.filter(|u| *u > now);
|
||||
let show_ban = own || viewer.is_moderator();
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"member": {
|
||||
"author": brief,
|
||||
"bio": row.bio,
|
||||
"created_at": rfc3339(row.created_at),
|
||||
"post_count": row.post_count,
|
||||
"thread_count": thread_count,
|
||||
"last_seen": last_seen,
|
||||
"own": own,
|
||||
"banned_until": banned.filter(|_| show_ban).map(|u| {
|
||||
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||
}),
|
||||
"ban_reason": row.ban_reason.filter(|_| show_ban && banned.is_some()),
|
||||
},
|
||||
"recent": recent.into_iter().map(|r| json!({
|
||||
"id": r.id,
|
||||
"thread_id": r.thread_id,
|
||||
"thread_slug": text::slug(&r.title),
|
||||
"thread_title": r.title,
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"excerpt": r.excerpt,
|
||||
"is_opening": r.is_opening,
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! HTTP routes, all under `/v1/forum`.
|
||||
//!
|
||||
//! Reading is open (members-only topics need a login); writing needs a
|
||||
//! nickname ([`Viewer::require_writer`]); moderation the moderator or admin
|
||||
//! role. A thread in a topic the viewer may not read answers 404, so its
|
||||
//! existence is not revealed.
|
||||
|
||||
mod home;
|
||||
mod members;
|
||||
mod moderation;
|
||||
mod posts;
|
||||
mod threads;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::routing::{get, post, put};
|
||||
use axum::{Json, Router};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::auth::{ONLINE_MINUTES, Viewer};
|
||||
use crate::error::ApiError;
|
||||
use crate::rank::Rank;
|
||||
|
||||
pub type Body<T> = WithRejection<Json<T>, ApiError>;
|
||||
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
||||
pub type St = State<Arc<AppState>>;
|
||||
|
||||
pub fn router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/healthz", get(health))
|
||||
.route("/v1/forum/home", get(home::home))
|
||||
.route("/v1/forum/nav", get(home::nav))
|
||||
.route("/v1/forum/topics", get(home::topics))
|
||||
.route("/v1/forum/topics/{slug}", get(home::topic))
|
||||
.route("/v1/forum/followed", get(home::followed))
|
||||
.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}/restore", post(threads::restore))
|
||||
.route("/v1/forum/threads/{id}/posts", post(threads::reply))
|
||||
.route("/v1/forum/threads/{id}/read", post(threads::mark_read))
|
||||
.route("/v1/forum/threads/{id}/follow", put(threads::follow).delete(threads::unfollow))
|
||||
.route("/v1/forum/posts/{id}", axum::routing::patch(posts::edit).delete(posts::remove))
|
||||
.route("/v1/forum/posts/{id}/restore", post(posts::restore))
|
||||
.route("/v1/forum/posts/{id}/reaction", put(posts::react).delete(posts::unreact))
|
||||
.route("/v1/forum/posts/{id}/helped", put(posts::mark_helped).delete(posts::unmark_helped))
|
||||
.route("/v1/forum/me", get(members::me).put(members::save_me))
|
||||
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
||||
.route("/v1/forum/presence", post(members::presence))
|
||||
.route("/v1/forum/members/{nickname}", get(members::profile))
|
||||
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
|
||||
.route("/v1/forum/mod/log", get(moderation::log))
|
||||
// The request log: masked paths, health checks only when they fail.
|
||||
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
|
||||
sqlx::query("SELECT 1").execute(&state.db).await?;
|
||||
Ok(Json(json!({ "status": "ok" })))
|
||||
}
|
||||
|
||||
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
|
||||
/// Built from the viewer's flags only, never from input.
|
||||
pub fn visible_topics(viewer: &Viewer) -> &'static str {
|
||||
if viewer.is_moderator() {
|
||||
"TRUE"
|
||||
} else if viewer.logged_in() {
|
||||
"tp.visibility IN ('public', 'members')"
|
||||
} else {
|
||||
"tp.visibility = 'public'"
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the viewer may read a topic of this visibility.
|
||||
pub fn may_read(viewer: &Viewer, visibility: &str) -> bool {
|
||||
match visibility {
|
||||
"public" => true,
|
||||
"members" => viewer.logged_in(),
|
||||
_ => viewer.is_moderator(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread in a list: what the cards on the forum pages show.
|
||||
#[derive(sqlx::FromRow)]
|
||||
pub struct CardRow {
|
||||
pub id: i64,
|
||||
pub title: String,
|
||||
pub intent: Option<String>,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub last_post_at: OffsetDateTime,
|
||||
pub reply_count: i32,
|
||||
pub pinned: bool,
|
||||
pub locked: bool,
|
||||
pub topic_slug: String,
|
||||
pub topic_name: String,
|
||||
pub participants: i64,
|
||||
/// Posts by others the member has not read; `None` for visitors.
|
||||
pub unread: Option<i64>,
|
||||
}
|
||||
|
||||
/// `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`.
|
||||
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, \
|
||||
th.pinned, th.locked, tp.slug AS topic_slug, tp.name AS topic_name, \
|
||||
(SELECT count(DISTINCT p.author_id) FROM forum.posts p \
|
||||
WHERE p.thread_id = th.id AND p.deleted_at IS NULL) AS participants, \
|
||||
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.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 \
|
||||
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE th.deleted_at IS NULL AND ({})",
|
||||
visible_topics(viewer)
|
||||
)
|
||||
}
|
||||
|
||||
/// `$1` and `$2` of [`card_sql`].
|
||||
pub fn card_params(viewer: &Viewer) -> (Option<Uuid>, Option<OffsetDateTime>) {
|
||||
match &viewer.member {
|
||||
Some(m) => (Some(m.user_id), Some(m.created_at)),
|
||||
None => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, sqlx::Error> {
|
||||
let people = authors(db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
json!({
|
||||
"id": r.id,
|
||||
"slug": crate::text::slug(&r.title),
|
||||
"title": r.title,
|
||||
"intent": r.intent,
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"last_post_at": rfc3339(r.last_post_at),
|
||||
"reply_count": r.reply_count,
|
||||
"participants": r.participants,
|
||||
"pinned": r.pinned,
|
||||
"locked": r.locked,
|
||||
"unread": r.unread,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct AuthorRow {
|
||||
user_id: Uuid,
|
||||
nickname: String,
|
||||
avatar: String,
|
||||
points: i32,
|
||||
created_at: OffsetDateTime,
|
||||
invisible: bool,
|
||||
last_seen_at: Option<OffsetDateTime>,
|
||||
chart_share: String,
|
||||
roles: Vec<String>,
|
||||
}
|
||||
|
||||
/// How members appear next to what they wrote: nickname, avatar, rank,
|
||||
/// moderator badge, online dot, and the signs they chose to share.
|
||||
pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
|
||||
let mut ids: Vec<Uuid> = ids.into_iter().collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
let rows: Vec<AuthorRow> = sqlx::query_as(
|
||||
"SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \
|
||||
m.chart_share, u.roles \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.user_id = ANY($1)",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let sharing: Vec<Uuid> = rows.iter().filter(|r| r.chart_share != "none").map(|r| r.user_id).collect();
|
||||
let signs = shared_signs(db, &sharing).await?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let rank = Rank::of(r.points, r.created_at, now);
|
||||
let moderator = r.roles.iter().any(|role| role == "moderator" || role == "admin");
|
||||
let shown = signs.get(&r.user_id).map(|chart| chart.share(&r.chart_share));
|
||||
let value = json!({
|
||||
"nickname": r.nickname,
|
||||
"avatar": r.avatar,
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"moderator": moderator,
|
||||
"online": online(r.invisible, r.last_seen_at, now),
|
||||
"signs": shown,
|
||||
});
|
||||
(r.user_id, value)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn online(invisible: bool, last_seen_at: Option<OffsetDateTime>, now: OffsetDateTime) -> bool {
|
||||
!invisible && last_seen_at.is_some_and(|t| now - t < time::Duration::minutes(ONLINE_MINUTES))
|
||||
}
|
||||
|
||||
/// The signs of a member's own chart (never degrees: they would give away the
|
||||
/// birth date and time).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ChartSigns {
|
||||
/// Planet id → sign id, in the chart's order.
|
||||
pub planets: Vec<(String, String)>,
|
||||
/// Only when the birth time is known.
|
||||
pub ascendant: Option<String>,
|
||||
}
|
||||
|
||||
const PLANETS: [&str; 10] =
|
||||
["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||
|
||||
impl ChartSigns {
|
||||
fn sign(&self, id: &str) -> Option<&str> {
|
||||
self.planets.iter().find(|(p, _)| p == id).map(|(_, s)| s.as_str())
|
||||
}
|
||||
|
||||
/// What a sharing level shows; `None` for "none".
|
||||
pub fn share(&self, level: &str) -> Option<Value> {
|
||||
let mut out = serde_json::Map::new();
|
||||
let mut put = |key: &str, sign: Option<&str>| {
|
||||
if let Some(sign) = sign {
|
||||
out.insert(key.to_string(), json!(sign));
|
||||
}
|
||||
};
|
||||
match level {
|
||||
"sun" => put("sun", self.sign("sun")),
|
||||
"big3" => {
|
||||
put("sun", self.sign("sun"));
|
||||
put("moon", self.sign("moon"));
|
||||
put("ascendant", self.ascendant.as_deref());
|
||||
}
|
||||
"planets" => {
|
||||
for planet in PLANETS {
|
||||
put(planet, self.sign(planet));
|
||||
}
|
||||
put("ascendant", self.ascendant.as_deref());
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
if out.is_empty() { None } else { Some(Value::Object(out)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The signs of each user's own chart (the current one first).
|
||||
pub async fn shared_signs(db: &PgPool, users: &[Uuid]) -> Result<HashMap<Uuid, ChartSigns>, sqlx::Error> {
|
||||
if users.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
type Row = (Uuid, Option<Value>, Option<String>, Option<bool>);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT DISTINCT ON (owner_id) owner_id, result->'points', result->'angles'->'ascendant'->>'sign', \
|
||||
(result->'time'->>'time_known')::boolean \
|
||||
FROM charts WHERE owner_id = ANY($1) AND kind = 'own' ORDER BY owner_id, is_primary DESC, created_at",
|
||||
)
|
||||
.bind(users)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(owner, points, ascendant, time_known)| {
|
||||
let planets = points
|
||||
.as_ref()
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| Some((p["id"].as_str()?.to_string(), p["sign"].as_str()?.to_string())))
|
||||
.filter(|(id, _)| PLANETS.contains(&id.as_str()))
|
||||
.collect();
|
||||
let ascendant = ascendant.filter(|_| time_known.unwrap_or(false));
|
||||
(owner, ChartSigns { planets, ascendant })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn rfc3339(t: OffsetDateTime) -> String {
|
||||
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the user bought a package (lifts the newcomer limits).
|
||||
pub async fn has_purchase(db: &PgPool, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')")
|
||||
.bind(user)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Moderation: bans and the log of every moderation step (who, what, why;
|
||||
//! a person or, later, the AI). Removing posts and threads is in their modules.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Action {
|
||||
DeletePost,
|
||||
RestorePost,
|
||||
DeleteThread,
|
||||
RestoreThread,
|
||||
Ban,
|
||||
Unban,
|
||||
Lock,
|
||||
Unlock,
|
||||
Pin,
|
||||
Unpin,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Action::DeletePost => "delete_post",
|
||||
Action::RestorePost => "restore_post",
|
||||
Action::DeleteThread => "delete_thread",
|
||||
Action::RestoreThread => "restore_thread",
|
||||
Action::Ban => "ban",
|
||||
Action::Unban => "unban",
|
||||
Action::Lock => "lock",
|
||||
Action::Unlock => "unlock",
|
||||
Action::Pin => "pin",
|
||||
Action::Unpin => "unpin",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one line of the moderation log (a person's step).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn record(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
actor: Uuid,
|
||||
action: Action,
|
||||
target_user: Option<Uuid>,
|
||||
thread_id: Option<i64>,
|
||||
post_id: Option<i64>,
|
||||
reason: Option<&str>,
|
||||
until: Option<OffsetDateTime>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \
|
||||
VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(actor)
|
||||
.bind(action.as_str())
|
||||
.bind(target_user)
|
||||
.bind(thread_id)
|
||||
.bind(post_id)
|
||||
.bind(reason)
|
||||
.bind(until)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A ban for good: the last day of year 9999.
|
||||
fn forever() -> OffsetDateTime {
|
||||
let day = time::Date::from_calendar_date(9999, time::Month::December, 31).expect("valid date");
|
||||
time::PrimitiveDateTime::new(day, time::Time::MIDNIGHT).assume_utc()
|
||||
}
|
||||
|
||||
/// The longest temporary ban, in hours (a year); longer is a ban for good.
|
||||
const MAX_BAN_HOURS: i64 = 24 * 365;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct BanRequest {
|
||||
/// Hours; missing or `null`: for good.
|
||||
#[serde(default)]
|
||||
hours: Option<i64>,
|
||||
#[serde(default)]
|
||||
reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The member behind a nickname, and whether they are a moderator or admin.
|
||||
async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> {
|
||||
let row: Option<(Uuid, Vec<String>)> = sqlx::query_as(
|
||||
"SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1",
|
||||
)
|
||||
.bind(text::nickname_key(nickname))
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
let (id, roles) = row.ok_or(ApiError::NotFound("member"))?;
|
||||
Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin")))
|
||||
}
|
||||
|
||||
/// A moderator bans a member for some hours or for good: they may still
|
||||
/// read, not write. Moderators and admins cannot be banned this way.
|
||||
pub async fn ban(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Json(req), _): Body<BanRequest>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (user, protected) = target(&state.db, &nickname).await?;
|
||||
if protected {
|
||||
return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into()));
|
||||
}
|
||||
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||
let until = match req.hours {
|
||||
Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h),
|
||||
Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))),
|
||||
None => forever(),
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.bind(until)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned");
|
||||
Ok(Json(json!({ "banned_until": if req.hours.is_none() { "infinity".to_string() } else { rfc3339(until) } })))
|
||||
}
|
||||
|
||||
pub async fn unban(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (user, _) = target(&state.db, &nickname).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LogRow {
|
||||
id: i64,
|
||||
actor: Option<String>,
|
||||
actor_kind: String,
|
||||
action: String,
|
||||
target: Option<String>,
|
||||
thread_id: Option<i64>,
|
||||
thread_title: Option<String>,
|
||||
post_id: Option<i64>,
|
||||
reason: Option<String>,
|
||||
until: Option<OffsetDateTime>,
|
||||
created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// The latest moderation steps, for moderators.
|
||||
pub async fn log(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_moderator()?;
|
||||
let rows: Vec<LogRow> = sqlx::query_as(
|
||||
"SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \
|
||||
tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.reason, l.until, l.created_at \
|
||||
FROM forum.mod_log l \
|
||||
LEFT JOIN forum.members am ON am.user_id = l.actor_id \
|
||||
LEFT JOIN users au ON au.id = l.actor_id \
|
||||
LEFT JOIN forum.members tm ON tm.user_id = l.target_user \
|
||||
LEFT JOIN forum.threads th ON th.id = l.thread_id \
|
||||
ORDER BY l.id DESC LIMIT 200",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"entries": rows.into_iter().map(|r| json!({
|
||||
"id": r.id,
|
||||
"actor": r.actor,
|
||||
"actor_kind": r.actor_kind,
|
||||
"action": r.action,
|
||||
"target": r.target,
|
||||
"thread": r.thread_id.map(|id| json!({ "id": id, "title": r.thread_title })),
|
||||
"post_id": r.post_id,
|
||||
"reason": r.reason,
|
||||
"until": r.until.map(|u| if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! A post: editing one's own, removal (one's own, or a moderator's with a
|
||||
//! reason), the admin's restore, reactions and the "Ez segített" mark.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::moderation::{self, Action};
|
||||
use super::threads::{POST_COLUMNS, PostRow, REACTIONS, Reason, ThreadRow, open_thread, posts_json, readable_thread};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::HELPED_POINTS;
|
||||
use crate::text;
|
||||
|
||||
/// A post and its thread, both readable by the viewer.
|
||||
async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> {
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("post"))?;
|
||||
let thread = readable_thread(db, viewer, post.thread_id).await?;
|
||||
Ok((post, thread))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Edit {
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// The author changes their post (while the thread is open).
|
||||
pub async fn edit(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Edit>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.author_id != Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into()));
|
||||
}
|
||||
open_thread(&state.db, &viewer, post.thread_id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(&body)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The author takes back their post, or a moderator removes it with a reason.
|
||||
/// Hidden, not erased: the admin can restore it.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let user = viewer.require_user()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let own = post.author_id == Some(user.id);
|
||||
let reason = if own {
|
||||
None
|
||||
} else if viewer.is_moderator() {
|
||||
Some(text::reason(req.reason.as_deref().unwrap_or(""))?)
|
||||
} else {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat törölheted.".into()));
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = greatest(reply_count - 1, 0) WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
if !own {
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
user.id,
|
||||
Action::DeletePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
reason.as_deref(),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a removal.
|
||||
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let admin = viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||
}
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
admin.id,
|
||||
Action::RestorePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct React {
|
||||
kind: String,
|
||||
}
|
||||
|
||||
fn points_of(kind: &str) -> i32 {
|
||||
if kind == "down" { -1 } else { 1 }
|
||||
}
|
||||
|
||||
/// Gives (or changes) the viewer's one reaction to a post. A newcomer's
|
||||
/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is
|
||||
/// not offered in listening topics.
|
||||
pub async fn react(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<React>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("post"));
|
||||
}
|
||||
open_thread(&state.db, &viewer, thread.id).await?;
|
||||
if post.author_id == Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into()));
|
||||
}
|
||||
let kind = req.kind.as_str();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let rank = member.rank(now);
|
||||
if kind == "down" {
|
||||
if thread.listening {
|
||||
return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into()));
|
||||
}
|
||||
if !rank.may_downvote() {
|
||||
return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into()));
|
||||
}
|
||||
} else if !REACTIONS.contains(&kind) {
|
||||
return Err(ApiError::bad("Ismeretlen reakció."));
|
||||
}
|
||||
let counted = !rank.is_newcomer();
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let previous: Option<(String, bool)> =
|
||||
sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let mut delta = if counted { points_of(kind) } else { 0 };
|
||||
if let Some((old, true)) = &previous {
|
||||
delta -= points_of(old);
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \
|
||||
ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(kind)
|
||||
.bind(counted)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
add_points(&mut tx, post.author_id, delta).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let removed: Option<(String, bool)> =
|
||||
sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some((kind, true)) = removed {
|
||||
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
async fn add_points(tx: &mut sqlx::PgConnection, author: Option<uuid::Uuid>, delta: i32) -> Result<(), sqlx::Error> {
|
||||
if let (Some(author), true) = (author, delta != 0) {
|
||||
sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.bind(delta)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The thread's author marks a reply that helped (worth more than a reaction).
|
||||
pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, true).await
|
||||
}
|
||||
|
||||
pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, false).await
|
||||
}
|
||||
|
||||
async fn set_helped(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
on: bool,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if thread.author_id != Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into()));
|
||||
}
|
||||
if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted."));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
let changed: Option<i64> = if on {
|
||||
sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id")
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id",
|
||||
)
|
||||
}
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if changed.is_some() {
|
||||
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Threads: reading one, starting one, replying, read marks, following, and
|
||||
//! the moderators' lock, pin, removal and the admin's restore.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::home::viewer_json;
|
||||
use super::moderation::{self, Action};
|
||||
use super::{Body, IdPath, St, authors, has_purchase, may_read, rfc3339};
|
||||
use crate::AppState;
|
||||
use crate::auth::{Member, Viewer};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::{self, COLLAPSE_SCORE};
|
||||
use crate::text;
|
||||
|
||||
/// The positive reactions; each is +1, the ⌄ (`down`) is -1.
|
||||
pub const REACTIONS: [&str; 4] = ["with_you", "thanks", "me_too", "insight"];
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct ThreadRow {
|
||||
pub id: i64,
|
||||
pub topic_slug: String,
|
||||
pub topic_name: String,
|
||||
pub visibility: String,
|
||||
pub listening: bool,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub title: String,
|
||||
pub intent: Option<String>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub locked: bool,
|
||||
pub pinned: bool,
|
||||
pub deleted_at: Option<OffsetDateTime>,
|
||||
pub delete_reason: Option<String>,
|
||||
}
|
||||
|
||||
const THREAD_SELECT: &str = "SELECT th.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 \
|
||||
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
|
||||
/// exist or sits in a hidden topic, 401 in a members-only topic for a visitor.
|
||||
pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||
let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("thread"))?;
|
||||
if !may_read(viewer, &thread.visibility) {
|
||||
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
/// A thread that can take new posts and reactions: not removed, and not
|
||||
/// locked (moderators may still write in a locked one).
|
||||
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||
let thread = readable_thread(db, viewer, id).await?;
|
||||
if thread.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("thread"));
|
||||
}
|
||||
if thread.locked && !viewer.is_moderator() {
|
||||
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into()));
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct PostRow {
|
||||
pub id: i64,
|
||||
pub thread_id: i64,
|
||||
pub parent_id: Option<i64>,
|
||||
pub is_opening: bool,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub body: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub edited_at: Option<OffsetDateTime>,
|
||||
pub helped_at: Option<OffsetDateTime>,
|
||||
pub deleted_at: Option<OffsetDateTime>,
|
||||
pub deleted_by: Option<Uuid>,
|
||||
pub delete_reason: Option<String>,
|
||||
}
|
||||
|
||||
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
|
||||
delete_reason";
|
||||
|
||||
/// Posts as the thread page shows them: authors, reactions, the viewer's own
|
||||
/// reaction. A removed post keeps its place with the reason; only
|
||||
/// moderators still see its text.
|
||||
pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult<Vec<Value>> {
|
||||
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
|
||||
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
|
||||
let counts: Vec<(i64, String, i64)> =
|
||||
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let mut by_post: HashMap<i64, HashMap<String, i64>> = HashMap::new();
|
||||
for (post, kind, n) in counts {
|
||||
by_post.entry(post).or_default().insert(kind, n);
|
||||
}
|
||||
let mine: HashMap<i64, String> = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2")
|
||||
.bind(&ids)
|
||||
.bind(me)
|
||||
.fetch_all(db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let moderator = viewer.is_moderator();
|
||||
Ok(posts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let counts = by_post.remove(&p.id).unwrap_or_default();
|
||||
let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum();
|
||||
let down = counts.get("down").copied().unwrap_or(0);
|
||||
let score = positive - down;
|
||||
let deleted = p.deleted_at.map(|_| {
|
||||
json!({
|
||||
"by_moderator": p.deleted_by.is_some() && p.deleted_by != p.author_id,
|
||||
"reason": p.delete_reason,
|
||||
})
|
||||
});
|
||||
let mut post = json!({
|
||||
"id": p.id,
|
||||
"parent_id": p.parent_id,
|
||||
"is_opening": p.is_opening,
|
||||
"author": p.author_id.and_then(|id| people.get(&id).cloned()),
|
||||
"own": p.author_id.is_some() && p.author_id == viewer.user_id(),
|
||||
"body": if p.deleted_at.is_none() || moderator { Some(&p.body) } else { None },
|
||||
"deleted": deleted,
|
||||
"created_at": rfc3339(p.created_at),
|
||||
"edited_at": p.edited_at.map(rfc3339),
|
||||
"helped": p.helped_at.is_some(),
|
||||
"reactions": REACTIONS.iter().map(|k| (k.to_string(), json!(counts.get(*k).copied().unwrap_or(0))))
|
||||
.collect::<serde_json::Map<_, _>>(),
|
||||
"score": score,
|
||||
"collapsed": score <= COLLAPSE_SCORE,
|
||||
"mine": mine.get(&p.id),
|
||||
});
|
||||
if moderator {
|
||||
post["down"] = json!(down);
|
||||
}
|
||||
post
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// A thread with all its posts, oldest first.
|
||||
pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
let people = authors(&state.db, thread.author_id).await?;
|
||||
let moderator = viewer.is_moderator();
|
||||
let mut out = json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())),
|
||||
});
|
||||
if thread.deleted_at.is_some() && !moderator {
|
||||
out["posts"] = json!([]);
|
||||
return Ok(Json(out));
|
||||
}
|
||||
let posts: Vec<PostRow> =
|
||||
sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id"))
|
||||
.bind(id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?);
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let (following, last_read) = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
let following: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)")
|
||||
.bind(me)
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let last_read: Option<i64> =
|
||||
sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2")
|
||||
.bind(me)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
(following, last_read)
|
||||
}
|
||||
None => (false, None),
|
||||
};
|
||||
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
|
||||
let open = thread.deleted_at.is_none() && (!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()),
|
||||
"is_thread_author": thread.author_id.is_some() && thread.author_id == viewer.user_id(),
|
||||
"following": following,
|
||||
"last_read_post_id": last_read,
|
||||
});
|
||||
Ok(Json(out))
|
||||
}
|
||||
|
||||
fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
|
||||
json!({
|
||||
"id": thread.id,
|
||||
"slug": text::slug(&thread.title),
|
||||
"title": thread.title,
|
||||
"intent": thread.intent,
|
||||
"topic": {
|
||||
"slug": thread.topic_slug, "name": thread.topic_name,
|
||||
"visibility": thread.visibility, "listening": thread.listening,
|
||||
},
|
||||
"author": author,
|
||||
"created_at": rfc3339(thread.created_at),
|
||||
"locked": thread.locked,
|
||||
"pinned": thread.pinned,
|
||||
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
|
||||
})
|
||||
}
|
||||
|
||||
/// Too fast, or past a newcomer's daily limit (lifted by a purchase and for moderators).
|
||||
async fn check_limits(state: &AppState, viewer: &Viewer, member: &Member, new_thread: bool) -> ApiResult<()> {
|
||||
let db = &state.db;
|
||||
let recent: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS (SELECT 1 FROM forum.posts \
|
||||
WHERE author_id = $1 AND created_at > now() - make_interval(secs => $2))",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.bind(f64::from(state.flood_secs))
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if recent {
|
||||
return Err(ApiError::Limited("Várj pár másodpercet a következő hozzászólással.".into()));
|
||||
}
|
||||
if viewer.is_moderator() || !member.rank(OffsetDateTime::now_utc()).is_newcomer() {
|
||||
return Ok(());
|
||||
}
|
||||
let (threads, posts): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*) FILTER (WHERE is_opening), count(*) FROM forum.posts \
|
||||
WHERE author_id = $1 AND created_at > now() - interval '24 hours'",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
let over =
|
||||
if new_thread { threads >= rank::NEWCOMER_THREADS_PER_DAY } else { posts >= rank::NEWCOMER_POSTS_PER_DAY };
|
||||
if over && !has_purchase(db, member.user_id).await? {
|
||||
return Err(ApiError::Limited(if new_thread {
|
||||
format!(
|
||||
"Új tagként naponta legfeljebb {} szálat nyithatsz. Holnap újra lehet.",
|
||||
rank::NEWCOMER_THREADS_PER_DAY
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Új tagként naponta legfeljebb {} hozzászólást írhatsz. Holnap újra lehet.",
|
||||
rank::NEWCOMER_POSTS_PER_DAY
|
||||
)
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateThread {
|
||||
topic: String,
|
||||
title: String,
|
||||
body: String,
|
||||
#[serde(default)]
|
||||
intent: Option<String>,
|
||||
}
|
||||
|
||||
/// Starts a thread with its opening post; the author follows it.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<CreateThread>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let member = viewer.require_writer()?;
|
||||
let topic: Option<(i16, String, bool)> =
|
||||
sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1")
|
||||
.bind(&req.topic)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
|
||||
if !may_read(&viewer, &visibility) {
|
||||
return Err(ApiError::bad("Ismeretlen téma."));
|
||||
}
|
||||
let title = text::title(&req.title)?;
|
||||
let body = text::body(&req.body)?;
|
||||
let intent = match req.intent.as_deref() {
|
||||
Some(i @ ("listen" | "advice")) => Some(i.to_string()),
|
||||
None | Some("") => listening.then(|| "listen".to_string()),
|
||||
Some(_) => return Err(ApiError::bad("Ismeretlen szándék.")),
|
||||
};
|
||||
check_limits(&state, &viewer, member, true).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let thread_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title, intent) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(topic_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&title)
|
||||
.bind(&intent)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let post_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, $3) RETURNING id",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&body)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
|
||||
}
|
||||
|
||||
/// After a post: the author's count, following the thread, and the read mark
|
||||
/// up to their own post.
|
||||
async fn after_post(
|
||||
tx: &mut sqlx::PgConnection,
|
||||
author: Uuid,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE forum.members SET post_count = post_count + 1 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(author)
|
||||
.bind(thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
upsert_read(&mut *tx, author, thread_id, post_id).await
|
||||
}
|
||||
|
||||
async fn upsert_read(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
user: Uuid,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT (user_id, thread_id) DO UPDATE \
|
||||
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(thread_id)
|
||||
.bind(post_id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Reply {
|
||||
body: String,
|
||||
/// The post answered; a reply to a reply goes under the same first-level
|
||||
/// post (two levels at most), a reply to the opening post is first-level.
|
||||
#[serde(default)]
|
||||
parent_id: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn reply(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reply>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let member = viewer.require_writer()?;
|
||||
open_thread(&state.db, &viewer, id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
let parent = match req.parent_id {
|
||||
None => None,
|
||||
Some(parent_id) => {
|
||||
let parent: Option<(Option<i64>, bool, bool)> = sqlx::query_as(
|
||||
"SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2",
|
||||
)
|
||||
.bind(parent_id)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?;
|
||||
if deleted {
|
||||
return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni."));
|
||||
}
|
||||
if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) }
|
||||
}
|
||||
};
|
||||
check_limits(&state, &viewer, member, false).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, $4) RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(parent)
|
||||
.bind(&body)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE forum.threads SET last_post_at = now(), reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||
tx.commit().await?;
|
||||
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
|
||||
Ok((StatusCode::CREATED, Json(post)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReadMark {
|
||||
post_id: i64,
|
||||
}
|
||||
|
||||
/// Read up to that post (never backwards).
|
||||
pub async fn mark_read(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ReadMark>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
readable_thread(&state.db, &viewer, id).await?;
|
||||
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) };
|
||||
upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
readable_thread(&state.db, &viewer, id).await?;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(member.user_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2")
|
||||
.bind(member.user_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ThreadChange {
|
||||
#[serde(default)]
|
||||
locked: Option<bool>,
|
||||
#[serde(default)]
|
||||
pinned: Option<bool>,
|
||||
}
|
||||
|
||||
/// Moderators lock (no more replies) or pin (first in its topic) a thread.
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ThreadChange>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
if let Some(locked) = req.locked.filter(|l| *l != thread.locked) {
|
||||
sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(locked)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let action = if locked { Action::Lock } else { Action::Unlock };
|
||||
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||
}
|
||||
if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) {
|
||||
sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(pinned)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let action = if pinned { Action::Pin } else { Action::Unpin };
|
||||
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Reason {
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// A moderator removes a whole thread; its place keeps the reason.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
if thread.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(moderator.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
moderator.id,
|
||||
Action::DeleteThread,
|
||||
thread.author_id,
|
||||
Some(id),
|
||||
None,
|
||||
Some(&reason),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = id, moderator = %moderator.id, "thread removed");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a thread's removal.
|
||||
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let admin = viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||
}
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
if thread.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
//! End-to-end tests against a real PostgreSQL database.
|
||||
//!
|
||||
//! `DATABASE_URL` must point to a server where the user may create databases
|
||||
//! (e.g. the `postgres` service of docker-compose); every test gets a fresh,
|
||||
//! migrated database. Users and sessions are made directly in the database,
|
||||
//! as the backend would.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{AppState, routes};
|
||||
|
||||
struct TestApp {
|
||||
router: Router,
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
struct User {
|
||||
id: Uuid,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl TestApp {
|
||||
fn new(pool: PgPool) -> Self {
|
||||
let state = AppState { db: pool.clone(), flood_secs: 0 };
|
||||
Self { router: routes::router(Arc::new(state)), pool }
|
||||
}
|
||||
|
||||
/// A user with a session, as after a login in the backend.
|
||||
async fn user(&self, email: &str, roles: &[&str]) -> User {
|
||||
let id = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO users (id, email, display_name, roles) VALUES ($1, $2, 'Valódi Név', $3)")
|
||||
.bind(id)
|
||||
.bind(email)
|
||||
.bind(roles.iter().map(|r| r.to_string()).collect::<Vec<_>>())
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let token = db::new_token();
|
||||
sqlx::query(
|
||||
"INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES ($1, $2, $3, now() + interval '1 day')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(id)
|
||||
.bind(db::token_hash(&token))
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
User { id, token }
|
||||
}
|
||||
|
||||
/// A user who already chose a nickname.
|
||||
async fn member(&self, email: &str, nickname: &str, roles: &[&str]) -> User {
|
||||
let user = self.user(email, roles).await;
|
||||
let (status, body) = self.call("PUT", "/v1/forum/me", Some(&user), json!({ "nickname": nickname })).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
user
|
||||
}
|
||||
|
||||
/// Makes a member older and gives them points (rank Kereső and up).
|
||||
async fn season(&self, user: &User, days: i32, points: i32) {
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET created_at = now() - make_interval(days => $2), points = $3, \
|
||||
nickname_changed_at = now() - make_interval(days => $2) WHERE user_id = $1",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(days)
|
||||
.bind(points)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn points(&self, user: &User) -> i32 {
|
||||
sqlx::query_scalar("SELECT points FROM forum.members WHERE user_id = $1")
|
||||
.bind(user.id)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn call(&self, method: &str, uri: &str, user: Option<&User>, body: Value) -> (StatusCode, Value) {
|
||||
let mut req = Request::builder().method(method).uri(uri);
|
||||
if let Some(u) = user {
|
||||
req = req.header("authorization", format!("Bearer {}", u.token));
|
||||
}
|
||||
let req = if body.is_null() {
|
||||
req.body(Body::empty()).unwrap()
|
||||
} else {
|
||||
req.header("content-type", "application/json").body(Body::from(body.to_string())).unwrap()
|
||||
};
|
||||
let resp = self.router.clone().oneshot(req).await.unwrap();
|
||||
let status = resp.status();
|
||||
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||
let value = if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap() };
|
||||
(status, value)
|
||||
}
|
||||
|
||||
async fn get(&self, uri: &str, user: Option<&User>) -> Value {
|
||||
let (status, body) = self.call("GET", uri, user, Value::Null).await;
|
||||
assert_eq!(status, StatusCode::OK, "GET {uri}: {body}");
|
||||
body
|
||||
}
|
||||
|
||||
/// Starts a thread; returns its id.
|
||||
async fn thread(&self, user: &User, topic: &str, title: &str) -> i64 {
|
||||
let (status, body) = self
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(user),
|
||||
json!({ "topic": topic, "title": title, "body": "Az első gondolat." }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{body}");
|
||||
body["id"].as_i64().unwrap()
|
||||
}
|
||||
|
||||
/// Replies; returns the new post.
|
||||
async fn reply(&self, user: &User, thread: i64, body: &str, parent: Option<i64>) -> Value {
|
||||
let (status, post) = self
|
||||
.call(
|
||||
"POST",
|
||||
&format!("/v1/forum/threads/{thread}/posts"),
|
||||
Some(user),
|
||||
json!({ "body": body, "parent_id": parent }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{post}");
|
||||
post
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_nickname_comes_first_and_stays_unique(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let visitor_try = app
|
||||
.call("POST", "/v1/forum/threads", None, json!({ "topic": "torzsasztal", "title": "Szia", "body": "x" }))
|
||||
.await;
|
||||
assert_eq!(visitor_try.0, StatusCode::UNAUTHORIZED);
|
||||
|
||||
let anna = app.user("anna@example.com", &["user"]).await;
|
||||
let (status, body) = app
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(&anna),
|
||||
json!({ "topic": "torzsasztal", "title": "Szia mindenki", "body": "x" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("nickname_required")));
|
||||
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
||||
assert!(me["member"].is_null());
|
||||
assert_eq!(me["viewer"]["needs_nickname"], true);
|
||||
|
||||
// The real name is never offered or shown.
|
||||
let (status, me) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": " Hold fény " })).await;
|
||||
assert_eq!(status, StatusCode::OK, "{me}");
|
||||
assert_eq!(me["member"]["nickname"], "Hold fény");
|
||||
assert_eq!(me["member"]["rank"], "vandor");
|
||||
assert!(!me.to_string().contains("Valódi"));
|
||||
|
||||
// Folded the same: taken.
|
||||
let bea = app.user("bea@example.com", &["user"]).await;
|
||||
let check = app.get("/v1/forum/nickname-check?name=holdfeny", Some(&bea)).await;
|
||||
assert_eq!(check["ok"], false);
|
||||
let (status, body) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Ho1dfény" })).await;
|
||||
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_taken")));
|
||||
assert_eq!(app.get("/v1/forum/nickname-check?name=Napraforgó", Some(&bea)).await["ok"], true);
|
||||
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Napraforgó" })).await;
|
||||
|
||||
// A spelling fix any time; a new name once in 30 days.
|
||||
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Holdfény" })).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let (status, body) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await;
|
||||
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_too_soon")));
|
||||
app.season(&anna, 31, 0).await;
|
||||
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
// The old name stays reserved for others…
|
||||
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Holdfény" })).await;
|
||||
assert_eq!(status, StatusCode::CONFLICT);
|
||||
// …and the profile is found by the new one, in any spelling.
|
||||
let profile = app.get("/v1/forum/members/csillagpor", None).await;
|
||||
assert_eq!(profile["member"]["author"]["nickname"], "Csillagpor");
|
||||
|
||||
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Admin Bea" })).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let (status, _) =
|
||||
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Bea", "avatar": "hold-piros" })).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn threads_replies_and_what_is_new(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;
|
||||
|
||||
// A listening topic: members only, threads ask for listening by default.
|
||||
let heart = app.thread(&anna, "ami-a-szivemen-van", "Nem tudom elengedni anyukám házát").await;
|
||||
let (status, _) = app.call("GET", &format!("/v1/forum/threads/{heart}"), None, Value::Null).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED, "visitors may not read a members-only topic");
|
||||
let (status, _) = app.call("GET", "/v1/forum/topics/ami-a-szivemen-van", None, Value::Null).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&bea)).await;
|
||||
assert_eq!(shown["thread"]["intent"], "listen");
|
||||
assert_eq!(shown["thread"]["slug"], "nem-tudom-elengedni-anyukam-hazat");
|
||||
assert_eq!(shown["access"]["can_downvote"], false);
|
||||
|
||||
// A visitor sees the public topics and that the members-only one exists.
|
||||
let public = app.thread(&anna, "torzsasztal", "Téli levesek").await;
|
||||
let home = app.get("/v1/forum/home", None).await;
|
||||
let topics = home["topics"].as_array().unwrap();
|
||||
assert_eq!(topics[0]["readable"], false);
|
||||
assert!(topics[0].get("thread_count").is_none());
|
||||
assert_eq!(topics[3]["thread_count"], 1);
|
||||
let waiting: Vec<i64> = home["unanswered"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect();
|
||||
assert_eq!(waiting, vec![public], "the visitor sees only the public thread waiting");
|
||||
|
||||
// Bea sees both waiting and both as new; Anna does not see her own.
|
||||
let home = app.get("/v1/forum/home", Some(&bea)).await;
|
||||
assert_eq!(home["unanswered"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(home["topics"][0]["new_count"], 1);
|
||||
assert!(app.get("/v1/forum/home", Some(&anna)).await["unanswered"].as_array().unwrap().is_empty());
|
||||
|
||||
// Replies: a reply to a reply stays on the second level.
|
||||
let first = app.reply(&bea, heart, "Nem vagy egyedül :)", None).await;
|
||||
assert_eq!(first["body"], "Nem vagy egyedül 🙂");
|
||||
assert_eq!(first["author"]["nickname"], "Holdfény");
|
||||
let second = app.reply(&anna, heart, "Köszönöm.", first["id"].as_i64()).await;
|
||||
let third = app.reply(&bea, heart, "Szívesen.", second["id"].as_i64()).await;
|
||||
assert_eq!(third["parent_id"], first["id"]);
|
||||
|
||||
// Anna follows her thread: one new reply from Bea since she last read.
|
||||
let home = app.get("/v1/forum/home", Some(&anna)).await;
|
||||
assert_eq!(home["followed"]["new_replies"], 1);
|
||||
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await;
|
||||
assert_eq!(shown["posts"].as_array().unwrap().len(), 4);
|
||||
assert_eq!(shown["access"]["last_read_post_id"], second["id"]);
|
||||
let (status, _) = app
|
||||
.call("POST", &format!("/v1/forum/threads/{heart}/read"), Some(&anna), json!({ "post_id": third["id"] }))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/forum/home", Some(&anna)).await["followed"]["new_replies"], 0);
|
||||
let followed = app.get("/v1/forum/followed", Some(&anna)).await;
|
||||
assert_eq!(followed["threads"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(followed["threads"][0]["reply_count"], 3);
|
||||
|
||||
// Busy today: three replies make it "pörgős".
|
||||
assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["hot"][0]["id"], heart);
|
||||
|
||||
// Editing one's own post only.
|
||||
let (status, _) =
|
||||
app.call("PATCH", &format!("/v1/forum/posts/{}", first["id"]), Some(&anna), json!({ "body": "Átírva" })).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, edited) = app
|
||||
.call("PATCH", &format!("/v1/forum/posts/{}", first["id"]), Some(&bea), json!({ "body": "Nem vagy egyedül." }))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(edited["edited_at"].is_string());
|
||||
|
||||
// Taking back one's own post: its place stays, the text goes.
|
||||
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{}", third["id"]), Some(&bea), json!({})).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await;
|
||||
let gone = shown["posts"].as_array().unwrap().iter().find(|p| p["id"] == third["id"]).unwrap().clone();
|
||||
assert!(gone["body"].is_null());
|
||||
assert_eq!(gone["deleted"]["by_moderator"], false);
|
||||
assert_eq!(app.get("/v1/forum/followed", Some(&anna)).await["threads"][0]["reply_count"], 2);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn reactions_give_points_and_ranks(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 cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
|
||||
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
|
||||
let post = app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
|
||||
let post_id = post["id"].as_i64().unwrap();
|
||||
let react = |user: &User, kind: &str| {
|
||||
let uri = format!("/v1/forum/posts/{post_id}/reaction");
|
||||
let body = json!({ "kind": kind });
|
||||
let user = User { id: user.id, token: user.token.clone() };
|
||||
let app = &app;
|
||||
async move { app.call("PUT", &uri, Some(&user), body).await }
|
||||
};
|
||||
|
||||
// A newcomer's reaction shows but gives no points; no ⌄ for newcomers.
|
||||
let (status, shown) = react(&cili, "with_you").await;
|
||||
assert_eq!(status, StatusCode::OK, "{shown}");
|
||||
assert_eq!(shown["reactions"]["with_you"], 1);
|
||||
assert_eq!(app.points(&bea).await, 0);
|
||||
assert_eq!(react(&cili, "down").await.0, StatusCode::FORBIDDEN);
|
||||
assert_eq!(react(&bea, "thanks").await.0, StatusCode::FORBIDDEN, "not on one's own post");
|
||||
assert_eq!(react(&cili, "hug").await.0, StatusCode::BAD_REQUEST);
|
||||
|
||||
// A seasoned member's reaction counts; changing it to ⌄ swings by two.
|
||||
app.season(&anna, 10, 5).await;
|
||||
let (_, shown) = react(&anna, "insight").await;
|
||||
assert_eq!(shown["mine"], "insight");
|
||||
assert_eq!(app.points(&bea).await, 1);
|
||||
let (_, shown) = react(&anna, "down").await;
|
||||
assert_eq!(app.points(&bea).await, -1);
|
||||
assert!(shown.get("down").is_none(), "only moderators see the ⌄ count");
|
||||
assert_eq!(shown["score"], 0);
|
||||
let (status, _) =
|
||||
app.call("DELETE", &format!("/v1/forum/posts/{post_id}/reaction"), Some(&anna), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(app.points(&bea).await, 0);
|
||||
|
||||
// "Ez segített": only the thread's author, worth five.
|
||||
let (status, _) = app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&cili), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, shown) = app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&anna), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(shown["helped"], true);
|
||||
app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&anna), Value::Null).await;
|
||||
assert_eq!(app.points(&bea).await, 5, "marking twice counts once");
|
||||
|
||||
// Points alone do not make a rank: time does too.
|
||||
let me = app.get("/v1/forum/me", Some(&bea)).await;
|
||||
assert_eq!(me["member"]["rank"], "vandor");
|
||||
assert_eq!(me["member"]["next_rank"]["name"], "Kereső");
|
||||
app.season(&bea, 3, 5).await;
|
||||
assert_eq!(app.get("/v1/forum/me", Some(&bea)).await["member"]["rank"], "kereso");
|
||||
|
||||
// No ⌄ in a listening topic, whatever the rank.
|
||||
let heart = app.thread(&cili, "ami-a-szivemen-van", "Nehéz napok").await;
|
||||
let opening = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await["posts"][0]["id"].as_i64().unwrap();
|
||||
let (status, _) =
|
||||
app.call("PUT", &format!("/v1/forum/posts/{opening}/reaction"), Some(&anna), json!({ "kind": "down" })).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn moderators_remove_and_ban(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let spam = app.member("spam@example.com", "Gyógyító", &["user"]).await;
|
||||
let moderator = app.member("mod@example.com", "Őrangyal", &["user", "moderator"]).await;
|
||||
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
|
||||
let thread = app.thread(&anna, "belso-utak", "Energiák").await;
|
||||
let ad = app.reply(&spam, thread, "Energetikai gyógyítás, írj privátban!", None).await;
|
||||
let ad_id = ad["id"].as_i64().unwrap();
|
||||
|
||||
// Members may not remove others' posts; a moderator needs a reason.
|
||||
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{ad_id}"), Some(&anna), json!({})).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{ad_id}"), Some(&moderator), json!({})).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let (status, _) = app
|
||||
.call(
|
||||
"DELETE",
|
||||
&format!("/v1/forum/posts/{ad_id}"),
|
||||
Some(&moderator),
|
||||
json!({ "reason": "szolgáltatás hirdetése" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
||||
assert!(seen["posts"][1]["body"].is_null());
|
||||
assert_eq!(seen["posts"][1]["deleted"]["reason"], "szolgáltatás hirdetése");
|
||||
assert_eq!(seen["posts"][1]["deleted"]["by_moderator"], true);
|
||||
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&moderator)).await;
|
||||
assert!(seen["posts"][1]["body"].is_string(), "moderators still see the text");
|
||||
|
||||
// Only the admin restores.
|
||||
let (status, _) =
|
||||
app.call("POST", &format!("/v1/forum/posts/{ad_id}/restore"), Some(&moderator), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) = app.call("POST", &format!("/v1/forum/posts/{ad_id}/restore"), Some(&admin), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
|
||||
// A ban: reading yes, writing no; moderators cannot be banned.
|
||||
let (status, body) = app
|
||||
.call("POST", "/v1/forum/members/gyogyito/ban", Some(&moderator), json!({ "hours": 48, "reason": "hirdetés" }))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
let (status, body) = app
|
||||
.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&spam), json!({ "body": "Még egyszer" }))
|
||||
.await;
|
||||
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("banned")));
|
||||
app.get(&format!("/v1/forum/threads/{thread}"), Some(&spam)).await;
|
||||
assert!(app.get("/v1/forum/me", Some(&spam)).await["member"]["banned_until"].is_string());
|
||||
let (status, _) =
|
||||
app.call("POST", "/v1/forum/members/orangyal/ban", Some(&moderator), json!({ "reason": "teszt" })).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) =
|
||||
app.call("POST", "/v1/forum/members/csendesviz/ban", Some(&anna), json!({ "reason": "teszt" })).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
// For good, then lifted.
|
||||
let (_, body) = app
|
||||
.call("POST", "/v1/forum/members/gyogyito/ban", Some(&moderator), json!({ "reason": "ismételt hirdetés" }))
|
||||
.await;
|
||||
assert_eq!(body["banned_until"], "infinity");
|
||||
let (status, _) = app.call("DELETE", "/v1/forum/members/gyogyito/ban", Some(&moderator), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
app.reply(&spam, thread, "Bocsánat.", None).await;
|
||||
|
||||
// Lock and remove a thread; others see only the reason.
|
||||
let (status, _) =
|
||||
app.call("PATCH", &format!("/v1/forum/threads/{thread}"), Some(&moderator), json!({ "locked": true })).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
let (status, _) = app
|
||||
.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&anna), json!({ "body": "Lezárva?" }))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) = app
|
||||
.call("DELETE", &format!("/v1/forum/threads/{thread}"), Some(&moderator), json!({ "reason": "vita elfajult" }))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
||||
assert_eq!(seen["thread"]["deleted"]["reason"], "vita elfajult");
|
||||
assert!(seen["posts"].as_array().unwrap().is_empty());
|
||||
assert!(app.get("/v1/forum/topics/belso-utak", Some(&anna)).await["threads"].as_array().unwrap().is_empty());
|
||||
|
||||
// Every step is in the log, which only moderators read.
|
||||
let (status, _) = app.call("GET", "/v1/forum/mod/log", Some(&anna), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let log = app.get("/v1/forum/mod/log", Some(&moderator)).await;
|
||||
let actions: Vec<&str> = log["entries"].as_array().unwrap().iter().map(|e| e["action"].as_str().unwrap()).collect();
|
||||
assert_eq!(actions, vec!["delete_thread", "lock", "unban", "ban", "ban", "restore_post", "delete_post"]);
|
||||
assert_eq!(log["entries"][6]["actor"], "Őrangyal");
|
||||
assert_eq!(log["entries"][6]["target"], "Gyógyító");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn newcomer_limits_and_a_purchase(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
for i in 0..3 {
|
||||
app.thread(&anna, "torzsasztal", &format!("Kérdés {i}")).await;
|
||||
}
|
||||
let (status, body) = app
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(&anna),
|
||||
json!({ "topic": "torzsasztal", "title": "Negyedik", "body": "x" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::TOO_MANY_REQUESTS, Some("limited")));
|
||||
// A purchase lifts the newcomer limits (but gives no rank).
|
||||
sqlx::query("INSERT INTO package_orders (id, user_id, package, source, price_huf) VALUES ($1, $2, 'egyeni', 'stripe', 4900)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(anna.id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.thread(&anna, "torzsasztal", "Negyedik").await;
|
||||
assert_eq!(app.get("/v1/forum/me", Some(&anna)).await["member"]["rank"], "vandor");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn profiles_share_signs_never_degrees(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let result = json!({
|
||||
"points": [
|
||||
{"id": "sun", "sign": "pisces", "longitude": 345.2},
|
||||
{"id": "moon", "sign": "cancer", "longitude": 101.7},
|
||||
{"id": "venus", "sign": "aries", "longitude": 12.0},
|
||||
{"id": "mean_node", "sign": "leo", "longitude": 130.0}
|
||||
],
|
||||
"angles": {"ascendant": {"sign": "virgo", "longitude": 160.4}},
|
||||
"time": {"time_known": true}
|
||||
});
|
||||
sqlx::query(
|
||||
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
|
||||
VALUES ($1, $2, 'Én', true, 'own', '{}', $3, 'x')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(anna.id)
|
||||
.bind(&result)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
||||
assert!(profile["member"]["author"]["signs"].is_null(), "nothing shared by default");
|
||||
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
||||
assert_eq!(me["chart"]["big3"], json!({"sun": "pisces", "moon": "cancer", "ascendant": "virgo"}));
|
||||
|
||||
let (status, _) = app
|
||||
.call(
|
||||
"PUT",
|
||||
"/v1/forum/me",
|
||||
Some(&anna),
|
||||
json!({ "nickname": "Csendesvíz", "chart_share": "planets", "bio": "Szia <3" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
||||
assert_eq!(
|
||||
profile["member"]["author"]["signs"],
|
||||
json!({"sun": "pisces", "moon": "cancer", "venus": "aries", "ascendant": "virgo"})
|
||||
);
|
||||
assert_eq!(profile["member"]["bio"], "Szia 🤍");
|
||||
assert!(!profile.to_string().contains("longitude") && !profile.to_string().contains("345"));
|
||||
let (status, _) = app
|
||||
.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "bio": "www.gyogyitas.hu" }))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// Online now, unless invisible.
|
||||
assert_eq!(profile["member"]["author"]["online"], true);
|
||||
app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "invisible": true })).await;
|
||||
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
||||
assert_eq!(profile["member"]["author"]["online"], false);
|
||||
assert!(profile["member"]["last_seen"].is_null());
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! Rules for what members type: nicknames, titles, posts, the bio, avatars.
|
||||
|
||||
use crate::error::ApiError;
|
||||
|
||||
pub const NICKNAME_MIN: usize = 3;
|
||||
pub const NICKNAME_MAX: usize = 24;
|
||||
pub const TITLE_MIN: usize = 4;
|
||||
pub const TITLE_MAX: usize = 120;
|
||||
pub const BODY_MAX: usize = 10_000;
|
||||
pub const BIO_MAX: usize = 500;
|
||||
pub const REASON_MIN: usize = 3;
|
||||
pub const REASON_MAX: usize = 300;
|
||||
|
||||
/// The starter avatars: a glyph on a background colour, `<glyph>-<colour>`.
|
||||
/// The frontend draws them (`src/components/forum/Avatar.tsx`).
|
||||
pub const AVATAR_GLYPHS: [&str; 8] = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"];
|
||||
pub const AVATAR_COLOURS: [&str; 6] = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"];
|
||||
|
||||
/// Words a nickname may not contain (compared folded, see [`nickname_key`]).
|
||||
const RESERVED: [&str; 7] = ["admin", "moderator", "sorsfonalak", "rendszer", "ugyfelszolgalat", "torolttag", "forum"];
|
||||
|
||||
const SEPARATORS: [char; 4] = [' ', '-', '_', '.'];
|
||||
|
||||
/// A nickname as it will be shown: trimmed, inner spaces collapsed, checked.
|
||||
/// Letters (accented ones too), digits, and single spaces, `-`, `_` or `.`
|
||||
/// between them; it starts with a letter.
|
||||
pub fn nickname(raw: &str) -> Result<String, ApiError> {
|
||||
let name = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = name.chars().count();
|
||||
if !(NICKNAME_MIN..=NICKNAME_MAX).contains(&len) {
|
||||
return Err(ApiError::bad(format!("Az álnév {NICKNAME_MIN}–{NICKNAME_MAX} karakter legyen.")));
|
||||
}
|
||||
if !name.chars().next().is_some_and(latin_letter) {
|
||||
return Err(ApiError::bad("Az álnév betűvel kezdődjön."));
|
||||
}
|
||||
let mut previous_separator = false;
|
||||
for c in name.chars() {
|
||||
let separator = SEPARATORS.contains(&c);
|
||||
if !(separator || latin_letter(c) || c.is_ascii_digit()) {
|
||||
return Err(ApiError::bad("Az álnévben betűk, számok, szóköz, kötőjel, aláhúzás és pont lehet."));
|
||||
}
|
||||
if separator && previous_separator {
|
||||
return Err(ApiError::bad("Az álnévben ne legyen két elválasztó jel egymás után."));
|
||||
}
|
||||
previous_separator = separator;
|
||||
}
|
||||
if previous_separator {
|
||||
return Err(ApiError::bad("Az álnév ne végződjön elválasztó jellel."));
|
||||
}
|
||||
let key = nickname_key(&name);
|
||||
if RESERVED.iter().any(|word| key.contains(&nickname_key(word))) {
|
||||
return Err(ApiError::bad("Ezt az álnevet nem választhatod."));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// A letter of the Latin script (accented ones included), so look-alike
|
||||
/// letters of other scripts cannot imitate a nickname.
|
||||
fn latin_letter(c: char) -> bool {
|
||||
c.is_alphabetic()
|
||||
&& matches!(c as u32,
|
||||
0x41..=0x5A | 0x61..=0x7A // ASCII
|
||||
| 0xC0..=0x24F // Latin-1 Supplement, Latin Extended-A and -B
|
||||
| 0x1E00..=0x1EFF) // Latin Extended Additional
|
||||
}
|
||||
|
||||
/// The nickname folded for uniqueness: no accents, case or separators, and
|
||||
/// characters that look alike made the same (`I`, `l`, `1` → `l`; `0` → `o`),
|
||||
/// so "Holdfény", "holdfeny" and "Ho1d-feny" are one name.
|
||||
pub fn nickname_key(name: &str) -> String {
|
||||
deunicode::deunicode(name)
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric())
|
||||
.map(|c| match c {
|
||||
'i' | '1' => 'l',
|
||||
'0' => 'o',
|
||||
other => other,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A thread title: one line, spaces collapsed.
|
||||
pub fn title(raw: &str) -> Result<String, ApiError> {
|
||||
let title: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = title.chars().count();
|
||||
if len < TITLE_MIN {
|
||||
return Err(ApiError::bad(format!("A cím legalább {TITLE_MIN} karakter legyen.")));
|
||||
}
|
||||
if len > TITLE_MAX {
|
||||
return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet.")));
|
||||
}
|
||||
Ok(title)
|
||||
}
|
||||
|
||||
/// A post: control characters removed, at most one empty line in a row,
|
||||
/// trailing spaces dropped, the old smileys turned into emoji.
|
||||
pub fn body(raw: &str) -> Result<String, ApiError> {
|
||||
let text = clean_multiline(raw, 2);
|
||||
if text.is_empty() {
|
||||
return Err(ApiError::bad("A hozzászólás nem lehet üres."));
|
||||
}
|
||||
if text.chars().count() > BODY_MAX {
|
||||
return Err(ApiError::bad(format!("A hozzászólás legfeljebb {BODY_MAX} karakter lehet.")));
|
||||
}
|
||||
Ok(smileys(&text))
|
||||
}
|
||||
|
||||
/// The profile's short introduction: no links (old-school profile spam).
|
||||
pub fn bio(raw: &str) -> Result<String, ApiError> {
|
||||
let text = clean_multiline(raw, 1);
|
||||
if text.chars().count() > BIO_MAX {
|
||||
return Err(ApiError::bad(format!("A bemutatkozás legfeljebb {BIO_MAX} karakter lehet.")));
|
||||
}
|
||||
let lower = text.to_lowercase();
|
||||
if lower.contains("http") || lower.contains("www.") {
|
||||
return Err(ApiError::bad("A bemutatkozásba nem tehetsz linket."));
|
||||
}
|
||||
Ok(smileys(&text))
|
||||
}
|
||||
|
||||
/// A moderator's reason, shown in place of what was removed.
|
||||
pub fn reason(raw: &str) -> Result<String, ApiError> {
|
||||
let text: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let len = text.chars().count();
|
||||
if !(REASON_MIN..=REASON_MAX).contains(&len) {
|
||||
return Err(ApiError::bad(format!("Az indoklás {REASON_MIN}–{REASON_MAX} karakter legyen.")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn avatar(raw: &str) -> Result<String, ApiError> {
|
||||
let valid = raw
|
||||
.split_once('-')
|
||||
.is_some_and(|(glyph, colour)| AVATAR_GLYPHS.contains(&glyph) && AVATAR_COLOURS.contains(&colour));
|
||||
if valid { Ok(raw.to_string()) } else { Err(ApiError::bad("Ismeretlen avatar.")) }
|
||||
}
|
||||
|
||||
/// A default avatar for a new member, picked from the nickname.
|
||||
pub fn default_avatar(key: &str) -> String {
|
||||
let n: usize = key.bytes().map(usize::from).sum();
|
||||
format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()])
|
||||
}
|
||||
|
||||
/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`.
|
||||
pub fn slug(title: &str) -> String {
|
||||
let ascii = deunicode::deunicode(title).to_lowercase();
|
||||
let mut slug = String::new();
|
||||
for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) {
|
||||
if !slug.is_empty() && slug.len() + 1 + word.len() > 60 {
|
||||
break;
|
||||
}
|
||||
if !slug.is_empty() {
|
||||
slug.push('-');
|
||||
}
|
||||
slug.push_str(word);
|
||||
}
|
||||
slug
|
||||
}
|
||||
|
||||
/// Lines with control characters removed and trailing spaces dropped; at most
|
||||
/// `max_breaks` line breaks in a row; trimmed.
|
||||
fn clean_multiline(raw: &str, max_breaks: usize) -> String {
|
||||
let normalized = raw.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let mut out = String::with_capacity(normalized.len());
|
||||
let mut breaks = 0;
|
||||
for line in normalized.split('\n') {
|
||||
let line: String = line.chars().map(|c| if c == '\t' { ' ' } else { c }).filter(|c| !c.is_control()).collect();
|
||||
let line = line.trim_end();
|
||||
if line.trim().is_empty() {
|
||||
breaks += 1;
|
||||
continue;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push_str(&"\n".repeat(breaks.clamp(1, max_breaks)));
|
||||
}
|
||||
breaks = 1;
|
||||
out.push_str(line);
|
||||
}
|
||||
out.trim().to_string()
|
||||
}
|
||||
|
||||
/// `:)`, `:D`, `;)`, `:(`, `:P` and `<3` standing alone become emoji, as on the
|
||||
/// old forums.
|
||||
fn smileys(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut word = String::new();
|
||||
let flush = |word: &mut String, out: &mut String| {
|
||||
let emoji = match word.as_str() {
|
||||
":)" | ":-)" => Some("🙂"),
|
||||
":D" | ":-D" => Some("😄"),
|
||||
";)" | ";-)" => Some("😉"),
|
||||
":(" | ":-(" => Some("🙁"),
|
||||
":P" | ":-P" | ":p" => Some("😛"),
|
||||
"<3" => Some("🤍"),
|
||||
_ => None,
|
||||
};
|
||||
out.push_str(emoji.unwrap_or(word));
|
||||
word.clear();
|
||||
};
|
||||
for c in text.chars() {
|
||||
if c.is_whitespace() {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
} else {
|
||||
word.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nicknames() {
|
||||
assert_eq!(nickname(" Hold fény ").unwrap(), "Hold fény");
|
||||
assert_eq!(nickname("Csendesvíz").unwrap(), "Csendesvíz");
|
||||
assert!(nickname("ab").is_err());
|
||||
assert!(nickname("1abc").is_err());
|
||||
assert!(nickname("abc--def").is_err());
|
||||
assert!(nickname("abc-").is_err());
|
||||
assert!(nickname("Admin Anna").is_err());
|
||||
assert!(nickname("Sorsfona1ak").is_err());
|
||||
assert!(nickname("Мария").is_err(), "Cyrillic look-alikes are refused");
|
||||
assert!(nickname("név😀").is_err());
|
||||
assert_eq!(nickname_key("Holdfény"), nickname_key("ho1d-feny"));
|
||||
assert_eq!(nickname_key("Ilona"), nickname_key("1lona"));
|
||||
assert_eq!(nickname_key("Olga"), nickname_key("0lga"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bodies() {
|
||||
assert_eq!(body(" Szia :)\r\n\r\n\r\n\r\nMi újság? <3 ").unwrap(), "Szia 🙂\n\nMi újság? 🤍");
|
||||
assert_eq!(body("http://x.hu/:)").unwrap(), "http://x.hu/:)", "only smileys standing alone");
|
||||
assert!(body(" \n\t ").is_err());
|
||||
assert_eq!(body("a\u{0007}b").unwrap(), "ab");
|
||||
assert!(bio("Látogass meg: www.pelda.hu").is_err());
|
||||
assert_eq!(bio("Első sor\n\n\nMásodik").unwrap(), "Első sor\nMásodik");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn titles_slugs_avatars() {
|
||||
assert_eq!(title(" Nem tudom elengedni ").unwrap(), "Nem tudom elengedni");
|
||||
assert!(title("abc").is_err());
|
||||
assert_eq!(slug("Nem tudom elengedni anyukám házát!"), "nem-tudom-elengedni-anyukam-hazat");
|
||||
assert!(slug(&"hosszú ".repeat(30)).len() <= 60);
|
||||
assert!(avatar("hold-ejkek").is_ok());
|
||||
assert!(avatar("hold-piros").is_err());
|
||||
assert!(avatar(&default_avatar("csendesvlz")).is_ok());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user