From 36b38525c393134ec31c3edf93331217548c1580 Mon Sep 17 00:00:00 2001 From: feco Date: Thu, 26 Nov 2026 10:29:49 +0000 Subject: [PATCH 01/19] 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 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- .gitea/workflows/ci.yml | 7 +- Cargo.lock | 23 + Cargo.toml | 1 + crates/db/migrations/0038_forum.sql | 151 +++++ crates/db/src/lib.rs | 5 +- deploy/.env.example | 3 + deploy/docker-compose.yml | 20 +- docker-compose.yml | 18 + docs/kozosseg.md | 317 +++++++++ services/forum/Cargo.toml | 28 + services/forum/Dockerfile | 33 + services/forum/src/auth.rs | 138 ++++ services/forum/src/error.rs | 92 +++ services/forum/src/main.rs | 55 ++ services/forum/src/rank.rs | 86 +++ services/forum/src/routes/home.rs | 246 +++++++ services/forum/src/routes/members.rs | 307 +++++++++ services/forum/src/routes/mod.rs | 306 +++++++++ services/forum/src/routes/moderation.rs | 200 ++++++ services/forum/src/routes/posts.rs | 287 ++++++++ services/forum/src/routes/threads.rs | 571 ++++++++++++++++ services/forum/src/tests.rs | 521 +++++++++++++++ services/forum/src/text.rs | 254 +++++++ .../frontend/src/app/admin/AdminUsers.tsx | 2 +- .../src/app/api/v1/[...path]/route.ts | 14 +- .../frontend/src/app/forum/[tema]/page.tsx | 81 +++ .../src/app/forum/beallitasok/ProfileForm.tsx | 205 ++++++ .../src/app/forum/beallitasok/page.tsx | 32 + services/frontend/src/app/forum/forum.css | 447 +++++++++++++ .../frontend/src/app/forum/kovetett/page.tsx | 27 + services/frontend/src/app/forum/layout.tsx | 53 ++ .../frontend/src/app/forum/moderalas/page.tsx | 64 ++ services/frontend/src/app/forum/page.tsx | 244 +++++++ .../frontend/src/app/forum/szal/[id]/page.tsx | 49 ++ .../src/app/forum/tag/[nev]/BanPanel.tsx | 89 +++ .../frontend/src/app/forum/tag/[nev]/page.tsx | 104 +++ .../src/app/forum/uj/NewThreadForm.tsx | 166 +++++ services/frontend/src/app/forum/uj/page.tsx | 33 + services/frontend/src/components/NavIcon.tsx | 7 + .../frontend/src/components/SiteHeader.tsx | 11 +- .../src/components/forum/AuthorLine.tsx | 103 +++ .../frontend/src/components/forum/Avatar.tsx | 100 +++ .../src/components/forum/Composer.tsx | 114 ++++ .../src/components/forum/ForumNav.tsx | 111 +++ .../src/components/forum/PostBody.tsx | 17 + .../src/components/forum/ThemeToggle.tsx | 42 ++ .../src/components/forum/ThreadList.tsx | 86 +++ .../src/components/forum/ThreadView.tsx | 632 ++++++++++++++++++ services/frontend/src/lib/astro.ts | 1 + services/frontend/src/lib/forum.ts | 259 +++++++ services/frontend/src/lib/forumServer.ts | 29 + services/frontend/src/lib/types.ts | 2 +- 52 files changed, 6782 insertions(+), 11 deletions(-) create mode 100644 crates/db/migrations/0038_forum.sql create mode 100644 docs/kozosseg.md create mode 100644 services/forum/Cargo.toml create mode 100644 services/forum/Dockerfile create mode 100644 services/forum/src/auth.rs create mode 100644 services/forum/src/error.rs create mode 100644 services/forum/src/main.rs create mode 100644 services/forum/src/rank.rs create mode 100644 services/forum/src/routes/home.rs create mode 100644 services/forum/src/routes/members.rs create mode 100644 services/forum/src/routes/mod.rs create mode 100644 services/forum/src/routes/moderation.rs create mode 100644 services/forum/src/routes/posts.rs create mode 100644 services/forum/src/routes/threads.rs create mode 100644 services/forum/src/tests.rs create mode 100644 services/forum/src/text.rs create mode 100644 services/frontend/src/app/forum/[tema]/page.tsx create mode 100644 services/frontend/src/app/forum/beallitasok/ProfileForm.tsx create mode 100644 services/frontend/src/app/forum/beallitasok/page.tsx create mode 100644 services/frontend/src/app/forum/forum.css create mode 100644 services/frontend/src/app/forum/kovetett/page.tsx create mode 100644 services/frontend/src/app/forum/layout.tsx create mode 100644 services/frontend/src/app/forum/moderalas/page.tsx create mode 100644 services/frontend/src/app/forum/page.tsx create mode 100644 services/frontend/src/app/forum/szal/[id]/page.tsx create mode 100644 services/frontend/src/app/forum/tag/[nev]/BanPanel.tsx create mode 100644 services/frontend/src/app/forum/tag/[nev]/page.tsx create mode 100644 services/frontend/src/app/forum/uj/NewThreadForm.tsx create mode 100644 services/frontend/src/app/forum/uj/page.tsx create mode 100644 services/frontend/src/components/forum/AuthorLine.tsx create mode 100644 services/frontend/src/components/forum/Avatar.tsx create mode 100644 services/frontend/src/components/forum/Composer.tsx create mode 100644 services/frontend/src/components/forum/ForumNav.tsx create mode 100644 services/frontend/src/components/forum/PostBody.tsx create mode 100644 services/frontend/src/components/forum/ThemeToggle.tsx create mode 100644 services/frontend/src/components/forum/ThreadList.tsx create mode 100644 services/frontend/src/components/forum/ThreadView.tsx create mode 100644 services/frontend/src/lib/forum.ts create mode 100644 services/frontend/src/lib/forumServer.ts diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index f0c3030..e700330 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -60,7 +60,7 @@ jobs: # astro-engine and horoscope-api need the Swiss Ephemeris sources and # data (scripts/fetch-deps.sh); their tests run locally. - name: Test - run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates + run: cargo test --locked -p backend -p worker -p forum -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates build: needs: test @@ -95,6 +95,7 @@ jobs: build horoscope-api -f services/horoscope-api/Dockerfile . build backend -f services/backend/Dockerfile . build worker -f services/worker/Dockerfile . + build forum -f services/forum/Dockerfile . build frontend services/frontend # Only the last 5 commit images of each service stay in the registry, # plus `main`, `prod`, `latest` and the commit running in production @@ -107,7 +108,7 @@ jobs: set -eu apk add --no-cache -q curl jq prod=$(git ls-remote origin refs/heads/prod | cut -c1-12) - for svc in horoscope-api backend worker frontend; do + for svc in horoscope-api backend worker forum frontend; do name="sorsfonalak-$svc" page=1 : > versions.tsv @@ -132,7 +133,7 @@ jobs: if: always() run: | docker logout "$REGISTRY" || true - for svc in horoscope-api backend worker frontend; do + for svc in horoscope-api backend worker forum frontend; do docker images "$IMAGE_PREFIX-$svc" --format '{{.Repository}}:{{.Tag}}' | xargs -r docker rmi >/dev/null 2>&1 || true done docker image prune -f >/dev/null diff --git a/Cargo.lock b/Cargo.lock index 7e4d77f..808755b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -693,6 +693,29 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "forum" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "axum-extra", + "db", + "deunicode", + "http-body-util", + "serde", + "serde_json", + "service-kit", + "sqlx", + "thiserror", + "time", + "tokio", + "tower", + "tower-http", + "tracing", + "uuid", +] + [[package]] name = "futures-channel" version = "0.3.34" diff --git a/Cargo.toml b/Cargo.toml index 22a3aae..4e91895 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "services/horoscope-api", "services/backend", "services/worker", + "services/forum", ] [workspace.package] diff --git a/crates/db/migrations/0038_forum.sql b/crates/db/migrations/0038_forum.sql new file mode 100644 index 0000000..c3b5947 --- /dev/null +++ b/crates/db/migrations/0038_forum.sql @@ -0,0 +1,151 @@ +-- The forum (services/forum, docs/kozosseg.md): pseudonymous members, topics, +-- threads, posts, reactions, read marks, followed threads and the moderation +-- log, in a schema of its own. +CREATE SCHEMA forum; + +-- 'moderator': appointed by an admin; may delete posts and threads and ban members. +ALTER TABLE users DROP CONSTRAINT users_roles_valid; +ALTER TABLE users ADD CONSTRAINT users_roles_valid + CHECK (cardinality(roles) > 0 + AND roles <@ ARRAY['admin', 'creator', 'moderator', 'premium', 'vip', 'user']::text[]); + +-- A user who chose a nickname. Nothing here is the real name: the nickname is +-- typed by the user, never taken from the Google or Apple account. +CREATE TABLE forum.members ( + user_id uuid PRIMARY KEY REFERENCES users ON DELETE CASCADE, + nickname text NOT NULL, + -- The nickname folded (no accents, case, spaces or look-alike digits): unique. + nickname_key text NOT NULL UNIQUE, + -- A starter avatar, '-' (the frontend draws it). + avatar text NOT NULL, + bio text NOT NULL DEFAULT '', + -- What the profile shows of the user's own chart: nothing, the Sun sign, + -- Sun, Moon and Ascendant, or every planet's sign. Never degrees. + chart_share text NOT NULL DEFAULT 'none' CHECK (chart_share IN ('none', 'sun', 'big3', 'planets')), + -- Not shown as online. + invisible boolean NOT NULL DEFAULT false, + -- Reactions received (counted ones), "Ez segített" marks; the rank comes from these. + points integer NOT NULL DEFAULT 0, + post_count integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now(), + nickname_changed_at timestamptz NOT NULL DEFAULT now(), + last_seen_at timestamptz, + -- Banned until then (year 9999: for good): may read, not write. + banned_until timestamptz, + ban_reason text +); + +-- A nickname given up stays reserved for a while, so nobody can take over a +-- known member's name. +CREATE TABLE forum.retired_nicknames ( + nickname_key text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + until timestamptz NOT NULL +); + +CREATE TABLE forum.topics ( + id smallint PRIMARY KEY, + slug text NOT NULL UNIQUE, + name text NOT NULL, + description text NOT NULL, + -- public: anyone reads (search engines too); members: logged-in users; + -- restricted: approved members only (not used yet: moderators only). + visibility text NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'members', 'restricted')), + -- A listening topic: no ⌄ there, and new threads ask for listening by default. + listening boolean NOT NULL DEFAULT false, + position smallint NOT NULL +); + +INSERT INTO forum.topics (id, slug, name, description, visibility, listening, position) VALUES + (1, 'ami-a-szivemen-van', 'Ami a szívemen van', 'Meghallgatás, élethelyzetek', 'members', true, 1), + (2, 'belso-utak', 'Belső utak', 'Spiritualitás, meditáció, álmok', 'public', false, 2), + (3, 'egbolt-es-kepletek', 'Égbolt és képletek', 'Asztrológia, megosztott elemzések', 'public', false, 3), + (4, 'torzsasztal', 'Törzsasztal', 'Bármi, ami eszedbe jut', 'public', false, 4); + +CREATE TABLE forum.threads ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + topic_id smallint NOT NULL REFERENCES forum.topics, + -- NULL once the account is deleted (the thread stays, "törölt tag"). + author_id uuid REFERENCES users ON DELETE SET NULL, + title text NOT NULL, + -- What the author asks for: only listening, or advice and opinions. + intent text CHECK (intent IN ('listen', 'advice')), + created_at timestamptz NOT NULL DEFAULT now(), + last_post_at timestamptz NOT NULL DEFAULT now(), + -- Visible replies (the opening post not counted). + reply_count integer NOT NULL DEFAULT 0, + pinned boolean NOT NULL DEFAULT false, + locked boolean NOT NULL DEFAULT false, + deleted_at timestamptz, + deleted_by uuid REFERENCES users ON DELETE SET NULL, + delete_reason text +); +CREATE INDEX threads_topic_idx ON forum.threads (topic_id, pinned DESC, last_post_at DESC) WHERE deleted_at IS NULL; +CREATE INDEX threads_author_idx ON forum.threads (author_id, created_at DESC); + +CREATE TABLE forum.posts ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE, + author_id uuid REFERENCES users ON DELETE SET NULL, + -- A reply to a reply (two levels at most: the parent is never itself a reply). + parent_id bigint REFERENCES forum.posts ON DELETE SET NULL, + is_opening boolean NOT NULL DEFAULT false, + body text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + edited_at timestamptz, + -- The thread's author marked it "Ez segített". + helped_at timestamptz, + -- Hidden, not erased: a moderator's reason shows in its place, an admin can restore it. + deleted_at timestamptz, + deleted_by uuid REFERENCES users ON DELETE SET NULL, + delete_reason text +); +CREATE INDEX posts_thread_idx ON forum.posts (thread_id, id); +CREATE INDEX posts_author_idx ON forum.posts (author_id, created_at DESC); +CREATE INDEX posts_recent_idx ON forum.posts (created_at DESC); +CREATE UNIQUE INDEX posts_opening_key ON forum.posts (thread_id) WHERE is_opening; + +-- One reaction per member and post; each is +1 to the author's points, 'down' (⌄) is -1. +CREATE TABLE forum.reactions ( + post_id bigint NOT NULL REFERENCES forum.posts ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('with_you', 'thanks', 'me_too', 'insight', 'down')), + -- Whether it moved the author's points (a new member's reaction does not). + counted boolean NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (post_id, user_id) +); + +-- How far a member has read a thread ("Itt hagytad abba"). +CREATE TABLE forum.reads ( + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE, + last_post_id bigint NOT NULL, + read_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, thread_id) +); + +-- Followed threads: one's own and the ones replied to, or followed by hand. +CREATE TABLE forum.follows ( + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, thread_id) +); +CREATE INDEX follows_thread_idx ON forum.follows (thread_id); + +-- Every moderation step: who (a person or, later, the AI), what, why. +CREATE TABLE forum.mod_log ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + actor_id uuid REFERENCES users ON DELETE SET NULL, + actor_kind text NOT NULL DEFAULT 'human' CHECK (actor_kind IN ('human', 'ai')), + action text NOT NULL CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', + 'ban', 'unban', 'lock', 'unlock', 'pin', 'unpin')), + target_user uuid REFERENCES users ON DELETE SET NULL, + thread_id bigint, + post_id bigint, + reason text, + until timestamptz, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX mod_log_created_idx ON forum.mod_log (created_at DESC); diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index f34e6ac..8cca945 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -36,6 +36,8 @@ pub enum Role { Admin, /// May write articles (phase 2). Creator, + /// Forum moderator, appointed by an admin. + Moderator, /// Paid tier: may use the models marked `@premium`. Premium, /// Top tier: may use the `@vip` and `@premium` models. @@ -44,12 +46,13 @@ pub enum Role { } impl Role { - pub const ALL: [Role; 5] = [Role::Admin, Role::Creator, Role::Premium, Role::Vip, Role::User]; + pub const ALL: [Role; 6] = [Role::Admin, Role::Creator, Role::Moderator, Role::Premium, Role::Vip, Role::User]; pub fn as_str(self) -> &'static str { match self { Role::Admin => "admin", Role::Creator => "creator", + Role::Moderator => "moderator", Role::Premium => "premium", Role::Vip => "vip", Role::User => "user", diff --git a/deploy/.env.example b/deploy/.env.example index 9391397..847e945 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -18,6 +18,9 @@ MAIL_FROM=Sorsfonalak # invite: new accounts need an invitation (default); open: anyone can sign up SIGNUP_MODE=invite +# The forum (docs/kozosseg.md): it always runs, visitors see it once this is set +# FORUM_URL=http://forum:8083 + # Image version; every deployment rewrites it TAG=latest diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index f16caca..21a67de 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -186,6 +186,22 @@ services: logging: *logging restart: unless-stopped + # The forum (docs/kozosseg.md): its own service on the same database and + # login; switched on for the visitors by FORUM_URL in the frontend below. + forum: + image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-forum:${TAG:-latest} + environment: + DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak + LOG_DIR: /logs + depends_on: + postgres: + condition: service_healthy + read_only: true + volumes: + - logs:/logs + logging: *logging + restart: unless-stopped + frontend: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest} environment: @@ -193,6 +209,8 @@ services: HOROSCOPE_API_URL: http://horoscope-api:8080 # Absolute links of the share previews (og:image). PUBLIC_BASE_URL: https://${DOMAIN} + # The forum: off until FORUM_URL=http://forum:8083 is in .env (no menu item, its pages 404). + FORUM_URL: ${FORUM_URL:-} depends_on: backend: condition: service_healthy @@ -222,7 +240,7 @@ services: volumes: pgdata: - # Backend and worker logs (backend.YYYY-MM-DD.log, worker…, worker-ai…). + # Backend, worker and forum logs (backend.YYYY-MM-DD.log, worker…, worker-ai…, forum…). logs: caddy-data: caddy-config: diff --git a/docker-compose.yml b/docker-compose.yml index 13c2108..c42ae4a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -108,6 +108,22 @@ services: read_only: true restart: unless-stopped + # The forum (services/forum): its own service on the same database and login. + forum: + build: + context: . + dockerfile: services/forum/Dockerfile + image: sorsfonalak/forum:latest + ports: + - "8083:8083" + environment: + DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD:-sorsfonalak-dev}@postgres:5432/sorsfonalak + depends_on: + postgres: + condition: service_healthy + read_only: true + restart: unless-stopped + frontend: build: context: services/frontend @@ -118,6 +134,8 @@ services: environment: BACKEND_URL: http://backend:8081 HOROSCOPE_API_URL: http://horoscope-api:8080 + # Empty: the forum is switched off (no menu item, its pages 404). + FORUM_URL: ${FORUM_URL:-http://forum:8083} depends_on: backend: condition: service_healthy diff --git a/docs/kozosseg.md b/docs/kozosseg.md new file mode 100644 index 0000000..cc53d34 --- /dev/null +++ b/docs/kozosseg.md @@ -0,0 +1,317 @@ +# Közösség (fórum) – koncepció + +**Állapot:** az első fejlesztési kör kész a `forum` branchen (2026-11-26). A link: **`/forum`**. A kiinduló jegyzet: `docs/texts/input.txt`. + +Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a többi eldöntött irány. Az első körben a javaslatok egy része is elkészült (lásd lent), ezek a használat alapján még változhatnak. + +## Megvalósítás + +### Ami elkészült (1. kör) + +- **Külön szolgáltatás:** `services/forum` (Rust, axum, 8083-as port). A backend adatbázisát és belépését használja: a backend munkamenete itt is érvényes. Az adatok a `forum` sémában vannak (`crates/db/migrations/0038_forum.sql`). +- **Bekapcsolás:** + - A frontend `FORUM_URL` változója kapcsolja be. Üresen nincs menüpont, és a `/forum` oldalai 404-et adnak. + - Élesben a `.env`-be kell: `FORUM_URL=http://forum:8083`. + - A böngésző a meglévő `/api/v1` proxyn éri el (`/api/v1/forum/...`). +- **Álnév és profil:** + - Az első hozzászólás előtt kötelező álnevet választani; az egyezést ékezet, kis- és nagybetű és a hasonló kinézetű betűk nélkül vizsgálja; vannak foglalt nevek; csak latin betű lehet. + - Álnevet 30 naponta lehet váltani, a régit 90 napig más nem kaphatja meg. + - 48 kezdő avatar (8 jel × 6 szín), bemutatkozás link nélkül. + - Képletmegosztás négy szinten, fokok nélkül, és láthatatlan mód. +- **Témák:** a négy javasolt téma. Az „Ami a szívemen van” csak tagoknak szól, meghallgatós, és a keresők nem indexelik. +- **Szálak:** + - A szál indítója jelöli, mit kér: meghallgatást vagy tanácsot. + - Válaszok két szint mélységig; a válaszra adott válasz az első szintű alá kerül. + - A saját hozzászólás szerkeszthető és törölhető. + - A régi smiley-k emojivá alakulnak. + - A linkek sima szövegként jelennek meg. +- **Olvasottság:** + - „Itt hagytad abba” vonal a szálban. + - Szálanként és témánként látszik, mennyi az új hozzászólás. + - A saját és a megválaszolt szálakat a tag automatikusan követi, a többit kézzel kezdheti követni. A „Követett” oldalon és a menü jelvényén látszik, ha új válasz jött. +- **Reakciók („B” változat), pontok, rangok:** + - A négy reakció mindegyike +1, a ⌄ −1. + - A ⌄ a Kereső rangtól használható, meghallgatós témában nincs. + - Az „Ez segített” +5. + - Az új tag reakciója látszik, de pontot nem ad. + - Rangok pontból és tagsági időből: Vándor 0 → Kereső 5 pont és 3 nap → Fonó 30 és 14 → Csillagfonó 100 és 45 → Sorsfonó 300 és 120. +- **Új tag korlátai:** naponta 3 szál és 20 hozzászólás, 5 másodperc két hozzászólás között. A vásárlás (Stripe-csomag) feloldja a napi korlátokat, rangot nem ad. +- **Főoldal:** „Mióta nem jártál itt” sáv, Mai égbolt (a Hold aznap), Várják a válaszod, Pörgős most (legalább 3 válasz 24 órán belül), Témák. +- **Online pötty:** + - Zöld, ha a tag 5 percen belül járt itt. + - A megnyitott oldal percenként jelez. + - Láthatatlan módban nem látszik. + - A profilon az utolsó látogatás csak durván látszik. +- **A szál oldalán az új válaszok** 30 másodpercenként frissülnek („1 új válasz érkezett” gomb). Ez a WebSocket helyett az első kör megoldása. +- **Moderálás:** + - Az admin a meglévő admin oldalon adja ki a `moderator` szerepkört. + - A moderátor hozzászólást és szálat távolíthat el kötelező indoklással, amely a helyén látszik. Lezárhat és kitűzhet szálat, és eltilthat néhány órára, napra vagy végleg; az eltiltott tag olvashat, de nem írhat. + - Moderátort és admint nem lehet eltiltani. + - Visszaállítani csak az admin tud. + - Minden lépés bekerül a moderálási naplóba (`/forum/moderalas`), és jelölve van, hogy ember vagy AI tette. +- **Színek:** a fórum alapból világos (meleg, papírszerű háttér, sötétarany kiemelés), a fórum sávján lévő gombbal sötétre váltható. A választást süti őrzi (`sf_forum_theme`), így a szerver már a választott témával küldi az oldalt. A fejléc és a lábléc mindkét témában sötét marad. +- **Mobil:** alul rögzített menüsáv (Fórum, Követett, Új szál, Profilom), nagy gombok, 17 px-es szöveg. +- **Asztali nézet:** + - A menü a fórum sávjába kerül, fülekként. + - A főoldal két hasábos (jobb oldalt a Mai égbolt és a saját kártya). + - A szálak listája oszlopos (válaszok, utolsó hozzászólás). + - A hozzászólások mellett a régi fórumok szerzőoszlopa látszik (avatar, név, rang, jegyek). + - A profiloldal két hasábos. +- **Tesztek:** `cargo test -p forum` (integrációs tesztek valódi Postgresszel), a CI-ban is fut. + +### Ami még hátravan + +- **Jelentés gomb** hozzászóláshoz (a DSA miatt kell), és az ÁSZF kiegészítése. +- **Privát üzenetek** kéréssel. +- **E-mail értesítések:** a napi összesítő, az értesítési beállítások oldala és a hírlevél-kapcsoló. +- **WebSocket-csengő** a 30 másodperces lekérdezés helyett. +- **Napi „Mai égbolt” szál:** a worker nyitná meg automatikusan. +- **AI-funkciók:** előszűrés, lelki krízis jelzése, az AI-összefoglaló kártya a főoldalon. +- **Saját avatar feltöltése** (Spaces), és a „Támogató” jelvény. +- **Zárt témák** jóváhagyással (a séma tudja, a felület még nem). +- **Fiók törlése és adatexport:** + - Törléskor a szálak és a hozzászólások most „Törölt tag” néven maradnak. Erről dönteni kell: maradjanak így, vagy törlődjenek. + - A backend adatexportja még nem tartalmazza a fórumot. + +## Cél + +A régi fórumok hangulata: mély beszélgetések, törzsgárda, valódi párbeszéd. Az emberek **beszélgessenek egymással**, főleg azok, akik meghallgatásra vágynak. A téma a spiritualitás, de nem csak asztrológia, és nem csak a horoszkópokból indul ki. Ha a közösség működik, a fizetős horoszkóp a háttérbe kerülhet. + +Ne videónézegető közösség legyen: **elsősorban szöveg**, a média visszaszorítva. + +## Alapelvek + +- **Tartós álnév:** mindenki álnéven ír, ami nem változik naponta, így felépül a bizalom. +- **Időrend, algoritmus nélkül.** +- **Kevés téma az elején,** hogy a fórum ne tűnjön üresnek. +- **Az AI soha nem szól hozzá tagként.** Lehet moderátor vagy háttérsegéd, de aki meghallgatást kér, annak ember válaszol. (javaslat) + +## Témák és láthatóság + +Témák (javaslat): +- **Ami a szívemen van** – meghallgatás, élethelyzetek +- **Belső utak** – spiritualitás, meditáció, megélések (az elején az **Álomnapló** is ide tartozhat) +- **Égbolt és képletek** – asztrológia, megosztott elemzésrészletek +- **Törzsasztal** – bármi más + +A fórum **nyilvános**. A Reddit mintájára lehetnek zárt terek is, ahová jelentkezni kell. A láthatóság a téma tulajdonsága, három szinttel (javaslat): + +| Szint | Olvasás | Írás | Kereső | +|---|---|---|---| +| Nyilvános | bárki | belépett tag | indexeli | +| Csak tagoknak | belépett tag | belépett tag | nem indexeli | +| Zárt | jóváhagyott tag | jóváhagyott tag | nem indexeli | + +Az **Ami a szívemen van** csak tagoknak szól, mert egy álnév kevésbé véd, mint gondolnánk: a részletekből az ismerősök felismerik az írót, és a Google évekig őrzi a szöveget. (javaslat) + +## Szálak és hozzászólások (javaslat) + +- Szálazott válaszok, két szint mélységig, idézéssel. +- **„Az utolsó látogatásod óta”** jelölés szálanként, és egy link, ami az első olvasatlan hozzászólásra ugrik. +- A szál indítója jelöli, mit kér: **csak meghallgatást** vagy **tanácsot / véleményt**. +- Megosztott AI-elemzésrészlet mellé kötelező legalább néhány mondat saját gondolat. +- Naponta automatikus **„Mai égbolt”** szál, újhold- és teliholdszál, ami utána archiválódik. + +## Meghallgatás (javaslat) + +- **„Még senki nem válaszolt”** lista, a legrégebbi felül. +- **Önkéntes meghallgatók:** szerepkör jelvénnyel, értesítést kapnak, ha egy szál néhány órája válasz nélkül áll. + +## Értékelés és reakciók + +A **„B” változat**: a reakció maga az értékelés. + +- Négy rögzített reakció, mindegyik +1 pont: 🤍 *Veled vagyok*, 🙏 *Köszönöm*, ✨ *Rám is igaz*, 💡 *Érdekes gondolat*. A készlet később bővíthető, de tetszőleges emojival nem lehet reagálni. +- Mellette egy diszkrét **⌄** („nem visz előre”), ami −1. A meghallgató témákban nem jelenik meg, és csak egy bizonyos rangtól használható. (javaslat) +- A sok mínuszt kapott hozzászólás nem tűnik el, csak összecsukódik („kattints a megjelenítéshez”). (javaslat) +- A szál indítója hozzászólásonként egyszer adhat **„Ez segített”** jelölést, ami többet ér, pl. +5. (javaslat) + +## Rangok és szerepkörök + +A rang az értékelésekhez kötődik, de nem csak azokból jön (javaslat): +- pontok az értékelésekből és az „Ez segített” jelölésekből; +- tagság ideje és aktív napok száma, ami lassítja a felkapaszkodást; +- moderálási figyelmeztetések, amik visszavetnek. + +Csalás ellen (javaslat): saját magára senki nem szavazhat, a friss tagok szavazata eleinte nem számít a rangba, és figyelni kell a folyton egymást értékelő fiókokra. + +Rangnevek (javaslat): *Vándor → Kereső → Fonó → Csillagfonó → Sorsfonó*. A rang neve nyilvános, a pontszámot csak a tag látja. + +A rang egyben **jogosultsági szint** is: ettől függ, ki küldhet privát üzenetkérést, ki tölthet fel saját avatart, ki tehet be linket, és ki használhatja a ⌄ jelet. + +**A kezdő (Vándor) is nyithat szálat és hozzászólhat**, mert lehet, hogy épp segítségre van szüksége. A hozzászólásai nem várnak moderátori jóváhagyásra. **Privát üzenetet viszont nem kezdeményezhet.** Ha valaki más kérést küld neki, azt elfogadhatja. (az elfogadás javaslat) + +A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderátor, meghallgató, támogató. + +### Vásárlás és rang + +**A csomagvásárlás nem ad rangot.** A rang bizalmat jelent, ezért pénzért nem járhat, és a csalóknak is megérné egy olcsó csomagért hamarabb privát üzenetet írni. Helyette: +- **Feloldja a kezdő korlátokat** (napi hozzászólásszám, a szavazat beszámítása), mert aki fizetett, az szinte biztosan valódi ember. Privát üzenetkéréshez továbbra is rang kell. +- **„Támogató” jelvény,** amit a tag maga dönt el, hogy kiteszi-e. Alapból rejtve. + +## Profil és álnév + +- **Álnevet kötelező választani** az első hozzászólás, reakció vagy szálindítás előtt. Olvasni álnév nélkül is lehet. +- Az álnév soha nem a Google- vagy Apple-fiók nevéből jön, és az oldal fel sem ajánlja. Egy rövid figyelmeztetés: „Ne a valódi neved legyen, ha nem szeretnéd, hogy felismerjenek.” +- Az álnév szabályai (javaslat): + - **egyedi**, kis- és nagybetűtől, ékezettől és hasonló kinézetű betűktől függetlenül; + - **foglalt nevek** (admin, moderátor, sorsfonalak stb.) nem választhatók; + - **30 naponta** egyszer módosítható, és a régi nevet egy ideig más nem kaphatja meg. +- **Bemutatkozás:** rövid szöveg, kb. 500 karakter, emojival, link nélkül. (a hossz és a link javaslat) +- **A horoszkópjából a tag választja ki, mit oszt meg.** Lépcsők (javaslat): semmi / Nap-jegy / Nap, Hold, Aszcendens (ez a név mellett is látszik) / az összes bolygó jegyekben / a rövid AI-összefoglaló. + - **Pontos fokokat nem mutatunk,** mert azokból visszaszámolható a születési dátum, az idő és nagyjából a hely. (javaslat) +- Magától látszik a profilon (javaslat): rang, szerepkörök, csatlakozás ideje, hozzászólások száma, utolsó aktivitás durván, legutóbbi hozzászólások (a csak tagoknak szóló témákból kívülállónak nem), „Beszélgetést kezdeményezek” gomb. + +## Avatar + +- Egyelőre **egy** avatarja van mindenkinek. +- **Kezdő készlet:** néhány tucat generált kép. SVG-ben, a márka színeivel (holdfázisok, csillagképek, növények, szimbólumok), így tárolni sem kell őket. (az SVG javaslat) +- **Saját kép:** a DO Spacesbe kerül, a meglévő `services/backend/src/storage.rs` mintájára (privát tároló, a szolgáltatás adja ki, a Cloudflare tartja gyorsítótárban). Csak egy rang fölött tölthető fel, a moderátor egy kattintással visszaállíthatja. Feltöltéskor csak az első képkocka marad meg, animált avatar nincs. (javaslat) + +## Média + +- **GIF nincs.** +- **Emoji van,** a hozzászólásokban is. Emojiválasztó, kiemelve a csillagjegyekkel (♈–♓) és a holdfázisokkal (🌑–🌕), és a régi fórumos `:)` → 🙂 és `<3` → 🤍 átalakítás. (a részletek javaslatok) +- **Videó** nem játszódik le helyben, a link sima szöveges linkként jelenik meg, előnézet nélkül. (javaslat) +- **Kép:** az elején nincs, később hozzászólásonként legfeljebb egy, rang fölött, kis méretben. (javaslat) +- Az aláírás csak szöveg lehet. (javaslat) + +## Privát üzenetek + +Kellenek, de az első verzió egyszerű legyen. **Előbb kérést kell küldeni,** nem lehet csak úgy ráírni valakire. + +Javasolt első verzió: +1. **Kérés:** a profilon egy „Beszélgetést kezdeményezek” gomb, hozzá legfeljebb 200 karakteres bemutatkozás, link és kép nélkül. +2. **A címzett dönt:** elfogad, elutasít vagy letilt. +3. **Az elutasítás csendes:** a küldő nem kap róla értesítést, a kérés 14 nap után lejár. +4. **Elfogadás után** kettes beszélgetés: szöveg és emoji, kép nincs, a link nem kattintható. + +Visszaélés ellen: +- kérést csak az küldhet, aki elért egy rangot és írt már nyilvánosan; +- naponta legfeljebb 3 nyitott kérés; +- a letiltott tag nem küldhet újabb kérést. + +A moderátor csak jelentés után látja a beszélgetést, és ezt az adatvédelmi tájékoztatónak is tartalmaznia kell. + +Később: csoportos beszélgetés, „gépel…” jelzés, olvasási visszaigazolás. + +## Értesítések + +- **Beállítási oldal,** ahol típusonként ki-be kapcsolható, ki miről kér értesítést, és a hírlevél is. +- **Az oldalon belül WebSocketen** jelez, ha egy másik szálban válasz érkezett. +- **Web push egyelőre nem kell.** + +Típusok és alapértékek (javaslat): + +| Esemény | Az oldalon | E-mail | +|---|---|---| +| Válasz a hozzászólásomra | be | napi összesítő | +| Új hozzászólás egy követett szálban | be | ki | +| Megemlítettek (@álnév) | be | azonnal | +| Válasz nélküli szál (meghallgatóknak) | be | ki | +| Heti összefoglaló | – | ki | +| Hírlevél | – | ki | + +A hírlevélhez a reklámtörvény szerint kifejezett, előzetes hozzájárulás kell, ezért alapból kikapcsolt, külön kapcsolóval. + +## Online jelenlét + +- **Zöld pötty** az avatar mellett, ha a tag az elmúlt 5 percben aktív volt. +- **„Most itt vannak” lista** csak később, ha nagyobb lesz a forgalom. +- **Láthatatlan mód** a beállításokban, és az „utoljára itt” csak durván látszik („ma”, „ezen a héten”). (javaslat) + +## Moderáció + +- **A moderátorokat az admin jelöli ki.** +- **Szerepkörök:** admin, moderátor (az egész fórum), témamoderátor (csak a saját témája). (a témamoderátor javaslat) +- **A moderátor jogai:** hozzászólást és szálat törölhet, néhány órára vagy napra eltilthat, és véglegesen is kitilthat. +- Kiegészítő eszközök (javaslat): áthelyezés, szál lezárása, kitűzés, figyelmeztetés, tag jóváhagyása zárt témába. +- **A törlés valójában elrejtés** (javaslat): + - A helyén egy sor marad: „A moderátor eltávolította (ok: …)”, így a szál olvasható marad. + - Az admin visszaállíthatja, és a tartalom egy ideig megmarad bizonyítéknak. + - A szerző értesítést kap az okkal, mert ezt a DSA előírja. Fellebbezni a meglévő visszajelzés-oldalon lehet. +- **Eltiltás:** az eltiltott tag olvashat, de nem írhat, nem reagálhat és nem küldhet privát üzenetet. Látja, meddig tart az eltiltás. (javaslat) +- **Kitiltás:** csak a fórumra vonatkozik, a megvásárolt horoszkópszolgáltatásokat nem érinti, hiszen azokért fizetett. (javaslat) +- **A moderátor határai:** nem tilthat ki másik moderátort vagy admint, és minden lépését az admin visszacsinálhatja. (javaslat) +- **Moderálási napló:** ki, mit, miért, és hogy **ember vagy AI** tette. Ez a DSA miatt is kell, mert eltávolításkor meg kell adni az okot. (javaslat) +- **AI később:** először csak jelöl és sorba állít, ember dönt. Ha bevált, egyértelmű esetekben (spam, hirdetés) önállóan is dönthet. A DSA szerint az érintettnek tudnia kell, ha automatikus eszköz döntött. (az ütemezés javaslat) +- **Lelki krízis** (javaslat): ha egy hozzászólás komoly bajra utal, az AI jelöli, a szerző mellett megjelenik a lelki elsősegély száma (116-123), és az admin értesítést kap. +- **Szolgáltatást hirdetni tilos:** jóslást, energetikai gyógyítást, tanfolyamot nem lehet árulni. (javaslat) +- **DSA-követelmények:** bejelentési lehetőség, kapcsolattartási pont, indoklás az eltávolításhoz, és ezekhez az ÁSZF bővítése. + +## Főoldal + +Kell hozzá dizájn. Ami biztos: a **legpörgősebb szálak**, és ha van valami **napi aktuális**, az. A többi javaslat. + +Mobilon, fentről lefelé (javaslat): +1. **„Mióta nem jártál itt” sáv:** csak visszatérőknek, pl. „5 új válasz a követett szálaidban”. +2. **Mai égbolt kártya:** + - holdfázis, a nap fő égi eseménye egy mondatban, és link a napi szálra a hozzászólások számával; + - **mindig van tartalma**, mert az AI generálja, így a főoldal az induláskor sem üres; + - később a belépett tagnak egy személyes sor is: „Nálad most…”. +3. **AI-összefoglaló és ajánló** (felmerült ötlet, még nincs kidolgozva): + - **„Tegnap a fórumon”:** két-három mondat a nyilvános témák beszélgetéseiről; + - **„Neked ajánljuk”:** két szál, mellettük az ok, pl. „mert ezt a témát követed”, később „a te Napodat is érinti”; + - **adatvédelem:** csak a nyilvános témákból készül, az „Ami a szívemen van” témát nem olvassa, tagot nem idéz és nem nevez meg; + - **AI-címke:** jól láthatóan AI-összefoglalóként van jelölve. Nem tagként szól, így nem ütközik azzal az elvvel, hogy az AI nem szól hozzá a beszélgetésekhez. +4. **Várják a válaszod:** 1–3 válasz nélküli szál, finoman kiemelve. A meghallgatás elve miatt ez közel van a tetejéhez. +5. **Pörgős most:** + - az utóbbi 24 óra legélénkebb szálai, a válaszok és a résztvevők száma szerint; + - átlátható, felcímkézett sorrend, nem rejtett algoritmus; + - amíg kevés a forgalom, nem jelenik meg. +6. **Témák:** + - témánként az új hozzászólások száma és a legutóbbi hozzászóló avatarja online pöttyel; + - a témán belül a sorrend időrendi. +7. **Alsó navigációs sáv.** + +Aki nincs belépve, annak az oldal tetején egy rövid bemutatkozás jelenik meg: miről szól ez a hely, és egy belépés gomb. + +Az a szakasz, amihez nincs elég tartalom, nem jelenik meg. Az üres doboz kihaltnak mutatja a fórumot. + +## Mobil + +**A legtöbben telefonról írnak, ezért a modulnak elsősorban mobilon kell jól működnie.** A tervezés is a telefonnal kezdődjön. (a részletek javaslatok) + +- **Alsó navigációs sáv:** Témák · Értesítések · Üzenetek · Profil. +- **Nagy gombok és betűk az 50+ korosztálynak:** legalább 44 px-es koppintási felület, legalább 17 px-es szöveg. A reakciógombok mindig látszanak, nem kell hozzájuk hosszan nyomni. +- **Szálak:** a két szint mélység mobilon még olvasható. Mélyebb válaszlánc helyett idézés, és az ágak összecsukhatók. +- **Szövegdoboz** a képernyő alján, ami a billentyűzettel együtt mozog. Emojinak a telefon billentyűzete elég, a külön emojiválasztó főleg asztali gépre kell. +- **WebSocket a telefonon:** a háttérbe tett lapot a telefon felfüggeszti. Amikor a lap újra előtérbe kerül, újracsatlakozik, és lekéri, mi történt közben. A csengős felépítés ezt külön munka nélkül kezeli. +- **Később PWA:** a fórum ikonként a kezdőképernyőre tehető, push nélkül. + +## Architektúra + +A fórummotor **külön szolgáltatás**, hogy később, például Kubernetesen, külön lehessen skálázni. Ez a WebSocketet nem nehezíti meg, ha a WebSocket csak csengőként működik. (a részletek javaslatok) + +- **`services/forum`:** külön program, axum. Ugyanabban a Postgresben fut, de saját sémában (`forum.*`), saját adatbázis-felhasználóval, korlátozott jogokkal. +- **Belépés:** ugyanabból a `sessions` táblából ellenőrzi, mint a backend. Ezt a kódot közös crate-be kell kiemelni, így egy belépés elég mindkettőhöz. +- **A WebSocket csak jelez:** pl. „új válasz a 123-as szálban”. A tartalmat a böngésző REST-en kéri le. Újracsatlakozáskor megkérdezi: „mi történt X óta?”. Így egy pod bármikor újraindítható, és semmi nem vész el. +- **Több példány esetén** minden példány egy Postgres LISTEN/NOTIFY csatornát hallgat (`forum_events`), és a saját kapcsolatainak továbbítja az eseményeket. A worker már most is így kapja az e-maileket. Redis nem kell, és ha egyszer szükséges, a csatorna kicserélhető NATS-ra vagy Redisre. +- **Online pötty:** a kapcsolat legfeljebb percenként frissíti a `last_seen` mezőt, így minden példány ugyanazt látja. +- **Buktatók:** + - A Next.js `/api/v1` proxy WebSocketet nem tud továbbítani, ezért a `/ws` útvonalat a frontend előtti proxyban kell közvetlenül a fórumszolgáltatásra irányítani. + - A Cloudflare kb. 100 másodperc tétlenség után bontja a kapcsolatot, ezért 30 másodpercenként szívverés-üzenet kell. + +## Később + +- **„Nálad is most van”:** tagok, akiknél most ugyanaz a tranzit zajlik, és amit megéléseikről írtak. Ehhez tranzitszámítás és a tagok összepárosítása kell. +- **Képlettestvérek:** szálak azonos Hold-jegyűektől vagy Aszcendensűektől. +- **Csillagszülinap:** az oldal felköszönti a tagot a Nap-visszatérésén. **Csak kifejezett engedéllyel,** mert elárulja a születésnapot. +- **Élő Tranzit-szoba:** időhöz kötött élő beszélgetés újholdkor és teliholdkor, ha már elég ember van hozzá. +- **Támogató tagság** jelvénnyel. + +## AI-szereplők? (bizonytalan) + +Felmerült, hogy „cuki” AI-robotok néha beszóljanak a beszélgetésekbe. Még nincs eldöntve. Ha lesz, ezek a keretek (javaslat): +- **Egy kabalafigura,** nem több robot. Jól láthatóan **AI**-ként jelölve: az EU AI Act 2026 augusztusa óta előírja, hogy az ember tudja, ha géppel beszél. +- **Soha nem az „Ami a szívemen van” témában,** és soha nem válaszol elsőként egy meghallgatást kérő szálra. +- **Bejelentésekkel és köszöntésekkel kezdene:** megnyitja a napi égbolt-szálat, köszönti az újholdat, gratulál a századik hozzászóláshoz, üdvözli az új tagokat egy külön üdvözlő szálban. +- **Korlátok:** ritkán szólal meg, nem szavaz, és nem kap rangot. +- **Bővítés csak bizonyítás után:** csak ha ez bevált, szólhat hozzá beszélgetésekhez is, és akkor is csak könnyed témákban (Törzsasztal, Égbolt). + +## Nyitott kérdések + +- **AI-kabala:** legyen-e, és mit csináljon. +- **A főoldal dizájnja** (a szerkezet fent, javaslatként). +- **A rangok határai** és a pontértékek. +- **A kezdő korlátok** pontos számai (napi hozzászólás, a szavazat mikortól számít). diff --git a/services/forum/Cargo.toml b/services/forum/Cargo.toml new file mode 100644 index 0000000..7acaedd --- /dev/null +++ b/services/forum/Cargo.toml @@ -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" diff --git a/services/forum/Dockerfile b/services/forum/Dockerfile new file mode 100644 index 0000000..5167053 --- /dev/null +++ b/services/forum/Dockerfile @@ -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"] diff --git a/services/forum/src/auth.rs b/services/forum/src/auth.rs new file mode 100644 index 0000000..471a4ed --- /dev/null +++ b/services/forum/src/auth.rs @@ -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, + pub ban_reason: Option, +} + +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, + pub member: Option, +} + +impl Viewer { + pub fn user_id(&self) -> Option { + 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 { + 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> for Viewer { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { + 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, sqlx::Error> { + sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1")) + .bind(user_id) + .fetch_optional(db) + .await +} diff --git a/services/forum/src/error.rs b/services/forum/src/error.rs new file mode 100644 index 0000000..96a848c --- /dev/null +++ b/services/forum/src/error.rs @@ -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) -> Self { + ApiError::Conflict { code, message: message.into() } + } + + pub fn bad(message: impl Into) -> 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 for ApiError { + fn from(e: sqlx::Error) -> Self { + ApiError::Internal(format!("database: {e}")) + } +} + +impl From for ApiError { + fn from(rejection: JsonRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} + +impl From for ApiError { + fn from(rejection: QueryRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} + +impl From for ApiError { + fn from(rejection: PathRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} + +pub type ApiResult = Result; diff --git a/services/forum/src/main.rs b/services/forum/src/main.rs new file mode 100644 index 0000000..c1f611c --- /dev/null +++ b/services/forum/src/main.rs @@ -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(()) +} diff --git a/services/forum/src/rank.rs b/services/forum/src/rank.rs new file mode 100644 index 0000000..08d9796 --- /dev/null +++ b/services/forum/src/rank.rs @@ -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()); + } +} diff --git a/services/forum/src/routes/home.rs b/services/forum/src/routes/home.rs new file mode 100644 index 0000000..2ca7b72 --- /dev/null +++ b/services/forum/src/routes/home.rs @@ -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, + last_author: Option, + last_at: Option, +} + +/// The topics in order: counts and the latest post for those the viewer may +/// read, the others (a members-only topic for a visitor) only by name. +async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult> { + let (me, since) = card_params(viewer); + let rows: Vec = sqlx::query_as( + "SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \ + (SELECT count(*) FROM forum.threads th WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) AS thread_count, \ + CASE WHEN $1::uuid IS NULL THEN NULL ELSE \ + (SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \ + WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \ + AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2::timestamptz \ + AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ + WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS new_count, \ + last.author_id AS last_author, last.created_at AS last_at \ + FROM forum.topics tp \ + LEFT JOIN LATERAL (SELECT p.author_id, p.created_at FROM forum.posts p \ + JOIN forum.threads th ON th.id = p.thread_id \ + WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \ + ORDER BY p.id DESC LIMIT 1) last ON true \ + ORDER BY tp.position", + ) + .bind(me) + .bind(since) + .fetch_all(&state.db) + .await?; + let readable: Vec = rows.iter().map(|r| may_read(viewer, &r.visibility)).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> { + let (me, since) = card_params(&viewer); + let topics = topic_list(&state, &viewer).await?; + + let followed = followed_counts(&state, &viewer).await?; + + let unanswered: Vec = sqlx::query_as(&format!( + "{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 \ + AND th.created_at > now() - make_interval(days => $3) \ + ORDER BY th.created_at LIMIT 3", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .bind(UNANSWERED_DAYS) + .fetch_all(&state.db) + .await?; + + let hot: Vec = sqlx::query_as(&format!( + "WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \ + WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \ + GROUP BY thread_id HAVING count(*) >= $3) \ + {} AND th.id IN (SELECT thread_id FROM recent) \ + ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .bind(HOT_MIN_REPLIES) + .fetch_all(&state.db) + .await?; + + 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> { + 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> { + Ok(Json(json!({ "viewer": viewer_json(&viewer), "followed": followed_counts(&state, &viewer).await? }))) +} + +pub async fn topics(state: St, viewer: Viewer) -> ApiResult> { + Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? }))) +} + +#[derive(Deserialize)] +pub struct PageQuery { + #[serde(default)] + page: Option, +} + +/// A topic's threads: pinned ones first, then by the latest post. +pub async fn topic( + State(state): St, + viewer: Viewer, + WithRejection(Path(slug), _): WithRejection, ApiError>, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let topic: Option<(i16, String, String, String, bool)> = + sqlx::query_as("SELECT id, name, description, visibility, listening FROM forum.topics WHERE slug = $1") + .bind(&slug) + .fetch_optional(&state.db) + .await?; + let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?; + if !may_read(&viewer, &visibility) { + // A members-only topic asks for a login; a restricted one stays hidden. + return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") }); + } + let page = q.page.unwrap_or(1).clamp(1, 10_000); + let (me, since) = card_params(&viewer); + let rows: Vec = sqlx::query_as(&format!( + "{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .bind(id) + .bind(PAGE_SIZE + 1) + .bind((page - 1) * PAGE_SIZE) + .fetch_all(&state.db) + .await?; + let has_more = rows.len() as i64 > PAGE_SIZE; + let rows = rows.into_iter().take(PAGE_SIZE as usize).collect(); + Ok(Json(json!({ + "viewer": viewer_json(&viewer), + "topic": { + "slug": slug, "name": name, "description": description, + "visibility": visibility, "listening": listening, + }, + "threads": cards_json(&state.db, rows).await?, + "page": page, + "has_more": has_more, + }))) +} + +/// The threads the member follows, the latest activity first, with what is unread. +pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_member()?; + let (me, since) = card_params(&viewer); + let rows: Vec = sqlx::query_as(&format!( + "{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \ + ORDER BY th.last_post_at DESC LIMIT 50", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .fetch_all(&state.db) + .await?; + Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? }))) +} diff --git a/services/forum/src/routes/members.rs b/services/forum/src/routes/members.rs new file mode 100644 index 0000000..b3ab7bc --- /dev/null +++ b/services/forum/src/routes/members.rs @@ -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> { + 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, + #[serde(default)] + bio: Option, + #[serde(default)] + chart_share: Option, + #[serde(default)] + invisible: Option, +} + +/// Whether someone else has (or recently had) this folded nickname. +async fn nickname_taken(db: &sqlx::PgPool, key: &str, me: Uuid) -> Result { + 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, +) -> ApiResult> { + 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, ApiError>, +) -> ApiResult> { + 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, + banned_until: Option, + ban_reason: Option, +} + +#[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, ApiError>, +) -> ApiResult> { + 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 = 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::>(), + }))) +} diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs new file mode 100644 index 0000000..97a3c4e --- /dev/null +++ b/services/forum/src/routes/mod.rs @@ -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 = WithRejection, ApiError>; +pub type IdPath = WithRejection, ApiError>; +pub type St = State>; + +pub fn router(state: Arc) -> 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, 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, + pub author_id: Option, + 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, +} + +/// `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, Option) { + 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) -> Result, 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, + chart_share: String, + roles: Vec, +} + +/// 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) -> Result, sqlx::Error> { + let mut ids: Vec = ids.into_iter().collect(); + ids.sort_unstable(); + ids.dedup(); + if ids.is_empty() { + return Ok(HashMap::new()); + } + let rows: Vec = 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 = 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, 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, +} + +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 { + 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, sqlx::Error> { + if users.is_empty() { + return Ok(HashMap::new()); + } + type Row = (Uuid, Option, Option, Option); + let rows: Vec = 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 { + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')") + .bind(user) + .fetch_one(db) + .await +} diff --git a/services/forum/src/routes/moderation.rs b/services/forum/src/routes/moderation.rs new file mode 100644 index 0000000..ab556b0 --- /dev/null +++ b/services/forum/src/routes/moderation.rs @@ -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, + thread_id: Option, + post_id: Option, + reason: Option<&str>, + until: Option, +) -> 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, + #[serde(default)] + reason: Option, +} + +/// 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)> = 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, ApiError>, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + 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, ApiError>, +) -> ApiResult { + 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, + actor_kind: String, + action: String, + target: Option, + thread_id: Option, + thread_title: Option, + post_id: Option, + reason: Option, + until: Option, + created_at: OffsetDateTime, +} + +/// The latest moderation steps, for moderators. +pub async fn log(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_moderator()?; + let rows: Vec = 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::>(), + }))) +} diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs new file mode 100644 index 0000000..2b2cec8 --- /dev/null +++ b/services/forum/src/routes/posts.rs @@ -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, +) -> ApiResult> { + 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, +) -> ApiResult { + 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 { + 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, +) -> ApiResult> { + 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> { + 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, 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> { + set_helped(state, viewer, path, true).await +} + +pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult> { + set_helped(state, viewer, path, false).await +} + +async fn set_helped( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + on: bool, +) -> ApiResult> { + 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 = 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))) +} diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs new file mode 100644 index 0000000..ce0dd90 --- /dev/null +++ b/services/forum/src/routes/threads.rs @@ -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, + pub title: String, + pub intent: Option, + pub created_at: OffsetDateTime, + pub locked: bool, + pub pinned: bool, + pub deleted_at: Option, + pub delete_reason: Option, +} + +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 { + 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 { + 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, + pub is_opening: bool, + pub author_id: Option, + pub body: String, + pub created_at: OffsetDateTime, + pub edited_at: Option, + pub helped_at: Option, + pub deleted_at: Option, + pub deleted_by: Option, + pub delete_reason: Option, +} + +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> { + let ids: Vec = 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> = HashMap::new(); + for (post, kind, n) in counts { + by_post.entry(post).or_default().insert(kind, n); + } + let mine: HashMap = 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::>(), + "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> { + 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 = + 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 = + 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 { + 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, +} + +/// Starts a thread with its opening post; the author follows it. +pub async fn create( + State(state): St, + viewer: Viewer, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let member = viewer.require_writer()?; + let topic: Option<(i16, String, bool)> = + sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1") + .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, +} + +pub async fn reply( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + 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, 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, +) -> ApiResult { + let member = viewer.require_member()?; + readable_thread(&state.db, &viewer, id).await?; + let last: Option = 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 { + 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 { + 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, + #[serde(default)] + pinned: Option, +} + +/// 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, +) -> ApiResult { + 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, +} + +/// 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, +) -> ApiResult { + 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 { + 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) +} diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs new file mode 100644 index 0000000..57deefc --- /dev/null +++ b/services/forum/src/tests.rs @@ -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::>()) + .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) -> 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 = 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()); +} diff --git a/services/forum/src/text.rs b/services/forum/src/text.rs new file mode 100644 index 0000000..1943006 --- /dev/null +++ b/services/forum/src/text.rs @@ -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, `-`. +/// 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 { + let name = raw.split_whitespace().collect::>().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 { + let title: String = raw.split_whitespace().collect::>().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 { + 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 { + 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 { + let text: String = raw.split_whitespace().collect::>().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 { + 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()); + } +} diff --git a/services/frontend/src/app/admin/AdminUsers.tsx b/services/frontend/src/app/admin/AdminUsers.tsx index 877d292..f3825f0 100644 --- a/services/frontend/src/app/admin/AdminUsers.tsx +++ b/services/frontend/src/app/admin/AdminUsers.tsx @@ -9,7 +9,7 @@ import { ROLE_LABELS, formatDate } from "@/lib/astro"; import type { AdminUser, Package, Role } from "@/lib/types"; const PAGE_SIZE = 25; -const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"]; +const EDITABLE_ROLES: Role[] = ["user", "creator", "moderator", "admin"]; type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot"; /** `short`: the mark in the list, where the names do not fit (explained under it). */ diff --git a/services/frontend/src/app/api/v1/[...path]/route.ts b/services/frontend/src/app/api/v1/[...path]/route.ts index 4a380af..7c9b8ac 100644 --- a/services/frontend/src/app/api/v1/[...path]/route.ts +++ b/services/frontend/src/app/api/v1/[...path]/route.ts @@ -1,9 +1,11 @@ -// Forwards /api/v1/* to the backend, so the browser talks to one origin and -// the session cookie belongs to the frontend's host (no CORS needed). +// Forwards /api/v1/* to the backend (and /api/v1/forum/* to the forum +// service), so the browser talks to one origin and the session cookie belongs +// to the frontend's host (no CORS needed). import { revalidateTag } from "next/cache"; import type { NextRequest } from "next/server"; import { CELEBRITIES_TAG } from "@/lib/celebrities"; +import { FORUM_URL } from "@/lib/forumServer"; import { BACKEND_URL } from "@/lib/server"; import { SHARES_TAG } from "@/lib/share"; @@ -22,7 +24,13 @@ const SKIP_RESPONSE_HEADERS = new Set(["connection", "content-encoding", "conten async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { const { path } = await ctx.params; - const target = `${BACKEND_URL}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`; + // The forum is a service of its own; without FORUM_URL it is switched off. + const forum = path[0] === "forum"; + if (forum && !FORUM_URL) { + return Response.json({ error: { code: "not_found", message: "A fórum nincs bekapcsolva." } }, { status: 404 }); + } + const base = forum ? FORUM_URL : BACKEND_URL; + const target = `${base}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`; const headers = new Headers(); for (const name of REQUEST_HEADERS) { diff --git a/services/frontend/src/app/forum/[tema]/page.tsx b/services/frontend/src/app/forum/[tema]/page.tsx new file mode 100644 index 0000000..003af12 --- /dev/null +++ b/services/frontend/src/app/forum/[tema]/page.tsx @@ -0,0 +1,81 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; + +import { ThreadList } from "@/components/forum/ThreadList"; +import type { TopicPage } from "@/lib/forum"; +import { forumGet } from "@/lib/forumServer"; + +type Props = { params: Promise<{ tema: string }>; searchParams: Promise<{ oldal?: string }> }; + +async function load(slug: string, page: number) { + return forumGet(`/v1/forum/topics/${encodeURIComponent(slug)}?page=${page}`); +} + +function pageOf(raw: string | undefined): number { + const n = Number(raw ?? 1); + return Number.isInteger(n) && n > 0 ? n : 1; +} + +export async function generateMetadata({ params }: Props): Promise { + const { tema } = await params; + const res = await load(tema, 1); + if (!res.ok) return { title: "Fórum" }; + const { topic } = res.data; + // Members-only topics stay out of search engines. + return { + title: topic.name, + description: topic.description, + robots: topic.visibility === "public" ? undefined : { index: false, follow: false }, + }; +} + +/** A topic's threads: pinned ones first, then by the latest post. */ +export default async function TopicPageView({ params, searchParams }: Props) { + const { tema } = await params; + const page = pageOf((await searchParams).oldal); + const res = await load(tema, page); + if (!res.ok) { + if (res.status === 401) redirect(`/belepes?vissza=/forum/${tema}`); + notFound(); + } + const { topic, threads, has_more, viewer } = res.data; + return ( +
+ +
+
+

{topic.name}

+

{topic.description}

+ {topic.listening && ( +

+ Meghallgatós téma: itt nincs ⌄, és a szálak alapból meghallgatást kérnek, nem tanácsot. +

+ )} +
+ + Új szál + +
+ {threads.length === 0 ? ( +

Ebben a témában még nincs szál. Nyisd meg te az elsőt!

+ ) : ( +
+ +
+ )} + {(page > 1 || has_more) && ( + + )} +
+ ); +} diff --git a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx new file mode 100644 index 0000000..95c67a1 --- /dev/null +++ b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx @@ -0,0 +1,205 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; + +import { AVATAR_COLOURS, AVATAR_GLYPHS, Avatar, GLYPH_NAMES } from "@/components/forum/Avatar"; +import { signsText } from "@/components/forum/AuthorLine"; +import { api, errorText } from "@/lib/api"; +import { type ChartShare, type ForumMe, banText, memberHref } from "@/lib/forum"; + +const SHARE_LEVELS: { value: ChartShare; label: string }[] = [ + { value: "none", label: "Semmit" }, + { value: "sun", label: "Csak a Nap-jegyemet" }, + { value: "big3", label: "Nap, Hold és Aszcendens" }, + { value: "planets", label: "Minden bolygó jegyét" }, +]; + +export function ProfileForm({ me, back }: { me: ForumMe; back: string | null }) { + const router = useRouter(); + const member = me.member; + const [nickname, setNickname] = useState(member?.nickname ?? ""); + const [check, setCheck] = useState<{ ok: boolean; message?: string } | null>(null); + const [avatar, setAvatar] = useState(member?.avatar ?? ""); + const [bio, setBio] = useState(member?.bio ?? ""); + const [share, setShare] = useState(member?.chart_share ?? "none"); + const [invisible, setInvisible] = useState(member?.invisible ?? false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + + // While typing: valid and free? (Not for the member's own current name.) + useEffect(() => { + const name = nickname.trim(); + if (!name || name === member?.nickname) { + setCheck(null); + return; + } + const timer = window.setTimeout(() => { + api<{ ok: boolean; message?: string }>(`/forum/nickname-check?name=${encodeURIComponent(name)}`) + .then(setCheck) + .catch(() => setCheck(null)); + }, 400); + return () => window.clearTimeout(timer); + }, [nickname, member?.nickname]); + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + setSaved(false); + try { + const res = await api("/forum/me", { + method: "PUT", + body: { nickname, avatar: avatar || null, bio, chart_share: share, invisible }, + }); + if (back) { + router.push(back); + } else if (!member && res.member) { + router.push(memberHref(res.member.nickname)); + } else { + setSaved(true); + } + router.refresh(); + } catch (err) { + setError(errorText(err)); + } finally { + setBusy(false); + } + } + + const preview = share === "none" ? null : me.chart?.[share]; + + return ( +
+ {member?.banned_until && ( +

+ Most nem írhatsz a fórumba ({banText(member.banned_until)}). + {member.ban_reason && ` Indok: ${member.ban_reason}`} +

+ )} + +
+ + setNickname(e.target.value)} + maxLength={24} + required + autoComplete="off" + aria-describedby="fprof-nick-hint" + /> + + {check && !check.ok + ? check.message + : check?.ok + ? "Szabad, választhatod." + : "Ne a valódi neved legyen, ha nem szeretnéd, hogy felismerjenek. 3–24 karakter: betűk, számok, szóköz, kötőjel."} + + {member?.nickname_change_after && ( + + Új álnevet{" "} + {new Date(member.nickname_change_after).toLocaleDateString("hu-HU", { month: "long", day: "numeric" })} után + választhatsz (az ékezet és a kis- és nagybetű javítható addig is). + + )} +
+ +
+ Avatar +
+ {AVATAR_COLOURS.flatMap((colour) => + AVATAR_GLYPHS.map((glyph) => { + const value = `${glyph}-${colour}`; + return ( + + ); + }), + )} +
+ {!avatar && Ha nem választasz, az álneved alapján kapsz egyet.} +
+ +
+ +