Forum: a service of its own and the /forum pages
services/forum (axum, port 8083) on the same database and login, in the forum schema (migration 0038, which also adds the moderator role): nicknames, profiles with shared signs, topics, threads with listening or advice intent, two-level replies, read marks and followed threads, reactions as ratings with points and ranks, newcomer limits (lifted by a purchase), moderation with reasons, bans and a log. Integration tests run in CI. The frontend's /forum pages (light by default, dark on request, phone first with a desktop layout) are switched on by FORUM_URL; the /api/v1 proxy sends /api/v1/forum/* to the forum service. Concept and status: docs/kozosseg.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -60,7 +60,7 @@ jobs:
|
|||||||
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
|
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
|
||||||
# data (scripts/fetch-deps.sh); their tests run locally.
|
# data (scripts/fetch-deps.sh); their tests run locally.
|
||||||
- name: Test
|
- 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:
|
build:
|
||||||
needs: test
|
needs: test
|
||||||
@@ -95,6 +95,7 @@ jobs:
|
|||||||
build horoscope-api -f services/horoscope-api/Dockerfile .
|
build horoscope-api -f services/horoscope-api/Dockerfile .
|
||||||
build backend -f services/backend/Dockerfile .
|
build backend -f services/backend/Dockerfile .
|
||||||
build worker -f services/worker/Dockerfile .
|
build worker -f services/worker/Dockerfile .
|
||||||
|
build forum -f services/forum/Dockerfile .
|
||||||
build frontend services/frontend
|
build frontend services/frontend
|
||||||
# Only the last 5 commit images of each service stay in the registry,
|
# Only the last 5 commit images of each service stay in the registry,
|
||||||
# plus `main`, `prod`, `latest` and the commit running in production
|
# plus `main`, `prod`, `latest` and the commit running in production
|
||||||
@@ -107,7 +108,7 @@ jobs:
|
|||||||
set -eu
|
set -eu
|
||||||
apk add --no-cache -q curl jq
|
apk add --no-cache -q curl jq
|
||||||
prod=$(git ls-remote origin refs/heads/prod | cut -c1-12)
|
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"
|
name="sorsfonalak-$svc"
|
||||||
page=1
|
page=1
|
||||||
: > versions.tsv
|
: > versions.tsv
|
||||||
@@ -132,7 +133,7 @@ jobs:
|
|||||||
if: always()
|
if: always()
|
||||||
run: |
|
run: |
|
||||||
docker logout "$REGISTRY" || true
|
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
|
docker images "$IMAGE_PREFIX-$svc" --format '{{.Repository}}:{{.Tag}}' | xargs -r docker rmi >/dev/null 2>&1 || true
|
||||||
done
|
done
|
||||||
docker image prune -f >/dev/null
|
docker image prune -f >/dev/null
|
||||||
|
|||||||
Generated
+23
@@ -693,6 +693,29 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"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]]
|
[[package]]
|
||||||
name = "futures-channel"
|
name = "futures-channel"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ members = [
|
|||||||
"services/horoscope-api",
|
"services/horoscope-api",
|
||||||
"services/backend",
|
"services/backend",
|
||||||
"services/worker",
|
"services/worker",
|
||||||
|
"services/forum",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
|
|||||||
@@ -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, '<glyph>-<colour>' (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);
|
||||||
@@ -36,6 +36,8 @@ pub enum Role {
|
|||||||
Admin,
|
Admin,
|
||||||
/// May write articles (phase 2).
|
/// May write articles (phase 2).
|
||||||
Creator,
|
Creator,
|
||||||
|
/// Forum moderator, appointed by an admin.
|
||||||
|
Moderator,
|
||||||
/// Paid tier: may use the models marked `@premium`.
|
/// Paid tier: may use the models marked `@premium`.
|
||||||
Premium,
|
Premium,
|
||||||
/// Top tier: may use the `@vip` and `@premium` models.
|
/// Top tier: may use the `@vip` and `@premium` models.
|
||||||
@@ -44,12 +46,13 @@ pub enum Role {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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 {
|
pub fn as_str(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Role::Admin => "admin",
|
Role::Admin => "admin",
|
||||||
Role::Creator => "creator",
|
Role::Creator => "creator",
|
||||||
|
Role::Moderator => "moderator",
|
||||||
Role::Premium => "premium",
|
Role::Premium => "premium",
|
||||||
Role::Vip => "vip",
|
Role::Vip => "vip",
|
||||||
Role::User => "user",
|
Role::User => "user",
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>
|
|||||||
# invite: new accounts need an invitation (default); open: anyone can sign up
|
# invite: new accounts need an invitation (default); open: anyone can sign up
|
||||||
SIGNUP_MODE=invite
|
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
|
# Image version; every deployment rewrites it
|
||||||
TAG=latest
|
TAG=latest
|
||||||
|
|
||||||
|
|||||||
@@ -186,6 +186,22 @@ services:
|
|||||||
logging: *logging
|
logging: *logging
|
||||||
restart: unless-stopped
|
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:
|
frontend:
|
||||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
|
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
|
||||||
environment:
|
environment:
|
||||||
@@ -193,6 +209,8 @@ services:
|
|||||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||||
# Absolute links of the share previews (og:image).
|
# Absolute links of the share previews (og:image).
|
||||||
PUBLIC_BASE_URL: https://${DOMAIN}
|
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:
|
depends_on:
|
||||||
backend:
|
backend:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -222,7 +240,7 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
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:
|
logs:
|
||||||
caddy-data:
|
caddy-data:
|
||||||
caddy-config:
|
caddy-config:
|
||||||
|
|||||||
@@ -108,6 +108,22 @@ services:
|
|||||||
read_only: true
|
read_only: true
|
||||||
restart: unless-stopped
|
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:
|
frontend:
|
||||||
build:
|
build:
|
||||||
context: services/frontend
|
context: services/frontend
|
||||||
@@ -118,6 +134,8 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
BACKEND_URL: http://backend:8081
|
BACKEND_URL: http://backend:8081
|
||||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
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:
|
depends_on:
|
||||||
backend:
|
backend:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -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).
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
[package]
|
||||||
|
name = "forum"
|
||||||
|
description = "Sorsfonalak forum: pseudonymous members, topics, threads, posts, reactions, moderation"
|
||||||
|
edition.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
db.workspace = true
|
||||||
|
service-kit.workspace = true
|
||||||
|
anyhow.workspace = true
|
||||||
|
axum.workspace = true
|
||||||
|
axum-extra.workspace = true
|
||||||
|
deunicode.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
sqlx.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
time.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
tower-http.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
|
http-body-util = "0.1"
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
#
|
||||||
|
# Build from the repository root:
|
||||||
|
# docker build -f services/forum/Dockerfile -t sorsfonalak/forum .
|
||||||
|
|
||||||
|
ARG RUST_VERSION=1.99
|
||||||
|
|
||||||
|
# --- 1. static (musl) build ----------------------------------------------------
|
||||||
|
FROM rust:${RUST_VERSION}-alpine AS build
|
||||||
|
RUN apk add --no-cache musl-dev
|
||||||
|
WORKDIR /app
|
||||||
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY crates crates
|
||||||
|
COPY services services
|
||||||
|
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
|
||||||
|
--mount=type=cache,target=/app/target,sharing=locked \
|
||||||
|
cargo build --release --locked -p forum \
|
||||||
|
&& cp target/release/forum /forum
|
||||||
|
# The log directory (LOG_DIR); a volume mounted here takes over its owner.
|
||||||
|
RUN mkdir /logs
|
||||||
|
|
||||||
|
# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) ---
|
||||||
|
FROM scratch
|
||||||
|
COPY --from=build /forum /forum
|
||||||
|
COPY --from=build --chown=65532:65532 /logs /logs
|
||||||
|
ENV BIND_ADDR=0.0.0.0:8083 \
|
||||||
|
LOG_FORMAT=json \
|
||||||
|
RUST_LOG=info
|
||||||
|
USER 65532:65532
|
||||||
|
EXPOSE 8083
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
|
||||||
|
CMD ["/forum", "healthcheck"]
|
||||||
|
ENTRYPOINT ["/forum"]
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
//! Who is asking: the backend's session (cookie or Bearer token) and the
|
||||||
|
//! member behind it. Reading needs no login; writing needs a nickname.
|
||||||
|
//! Every request of a member also keeps the online dot fresh.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
|
use axum::http::header::AUTHORIZATION;
|
||||||
|
use axum::http::request::Parts;
|
||||||
|
use axum_extra::extract::cookie::CookieJar;
|
||||||
|
use db::{Role, User};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::error::ApiError;
|
||||||
|
use crate::rank::Rank;
|
||||||
|
|
||||||
|
pub const SESSION_COOKIE: &str = "sf_session";
|
||||||
|
|
||||||
|
/// How long a member counts as online after the last request.
|
||||||
|
pub const ONLINE_MINUTES: i64 = 5;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||||
|
pub struct Member {
|
||||||
|
pub user_id: Uuid,
|
||||||
|
pub nickname: String,
|
||||||
|
pub avatar: String,
|
||||||
|
pub bio: String,
|
||||||
|
pub chart_share: String,
|
||||||
|
pub invisible: bool,
|
||||||
|
pub points: i32,
|
||||||
|
pub post_count: i32,
|
||||||
|
pub created_at: OffsetDateTime,
|
||||||
|
pub nickname_changed_at: OffsetDateTime,
|
||||||
|
pub banned_until: Option<OffsetDateTime>,
|
||||||
|
pub ban_reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
|
||||||
|
created_at, nickname_changed_at, banned_until, ban_reason";
|
||||||
|
|
||||||
|
impl Member {
|
||||||
|
pub fn rank(&self, now: OffsetDateTime) -> Rank {
|
||||||
|
Rank::of(self.points, self.created_at, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn banned(&self, now: OffsetDateTime) -> bool {
|
||||||
|
self.banned_until.is_some_and(|until| until > now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The visitor: maybe logged in, maybe a member (has chosen a nickname).
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct Viewer {
|
||||||
|
pub user: Option<User>,
|
||||||
|
pub member: Option<Member>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Viewer {
|
||||||
|
pub fn user_id(&self) -> Option<Uuid> {
|
||||||
|
self.user.as_ref().map(|u| u.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logged_in(&self) -> bool {
|
||||||
|
self.user.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_admin(&self) -> bool {
|
||||||
|
self.user.as_ref().is_some_and(|u| u.has_role(Role::Admin))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A moderator or an admin.
|
||||||
|
pub fn is_moderator(&self) -> bool {
|
||||||
|
self.user.as_ref().is_some_and(|u| u.has_role(Role::Moderator) || u.has_role(Role::Admin))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require_user(&self) -> Result<&User, ApiError> {
|
||||||
|
self.user.as_ref().ok_or(ApiError::Unauthorized)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require_member(&self) -> Result<&Member, ApiError> {
|
||||||
|
self.require_user()?;
|
||||||
|
self.member.as_ref().ok_or(ApiError::NicknameRequired)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A member who may write (not banned).
|
||||||
|
pub fn require_writer(&self) -> Result<&Member, ApiError> {
|
||||||
|
let member = self.require_member()?;
|
||||||
|
if member.banned(OffsetDateTime::now_utc()) {
|
||||||
|
let reason = member.ban_reason.as_deref().map(|r| format!(" Indok: {r}")).unwrap_or_default();
|
||||||
|
return Err(ApiError::Banned(format!("Most nem írhatsz a fórumba.{reason}")));
|
||||||
|
}
|
||||||
|
Ok(member)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require_moderator(&self) -> Result<&User, ApiError> {
|
||||||
|
let user = self.require_user()?;
|
||||||
|
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_token(parts: &Parts) -> Option<String> {
|
||||||
|
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
|
||||||
|
&& let Some(token) = value.strip_prefix("Bearer ")
|
||||||
|
{
|
||||||
|
return Some(token.trim().to_string());
|
||||||
|
}
|
||||||
|
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||||
|
type Rejection = ApiError;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||||
|
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
|
||||||
|
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
|
||||||
|
let member = load_member(&state.db, user.id).await?;
|
||||||
|
if member.is_some() {
|
||||||
|
// At most once a minute per member: the online dot.
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE forum.members SET last_seen_at = now() \
|
||||||
|
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
|
||||||
|
)
|
||||||
|
.bind(user.id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(Viewer { user: Some(user), member })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn load_member(db: &sqlx::PgPool, user_id: Uuid) -> Result<Option<Member>, sqlx::Error> {
|
||||||
|
sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1"))
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
use axum::Json;
|
||||||
|
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// API error, rendered as `{"error": {"code", "message"}}` like the backend's.
|
||||||
|
/// Messages meant for the user are Hungarian.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ApiError {
|
||||||
|
#[error("{0}")]
|
||||||
|
BadRequest(String),
|
||||||
|
#[error("authentication required")]
|
||||||
|
Unauthorized,
|
||||||
|
/// Logged in, but no nickname yet: the frontend sends the user to choose one.
|
||||||
|
#[error("Előbb válassz álnevet.")]
|
||||||
|
NicknameRequired,
|
||||||
|
#[error("{0}")]
|
||||||
|
Forbidden(String),
|
||||||
|
/// Banned from writing; the message tells until when.
|
||||||
|
#[error("{0}")]
|
||||||
|
Banned(String),
|
||||||
|
#[error("{0} not found")]
|
||||||
|
NotFound(&'static str),
|
||||||
|
#[error("{message}")]
|
||||||
|
Conflict { code: &'static str, message: String },
|
||||||
|
/// A usage limit; the message is shown to the user as is.
|
||||||
|
#[error("{0}")]
|
||||||
|
Limited(String),
|
||||||
|
#[error("internal error")]
|
||||||
|
Internal(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiError {
|
||||||
|
pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
|
||||||
|
ApiError::Conflict { code, message: message.into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad(message: impl Into<String>) -> Self {
|
||||||
|
ApiError::BadRequest(message.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_and_code(&self) -> (StatusCode, &'static str) {
|
||||||
|
match self {
|
||||||
|
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
|
||||||
|
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
|
||||||
|
ApiError::NicknameRequired => (StatusCode::FORBIDDEN, "nickname_required"),
|
||||||
|
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
|
||||||
|
ApiError::Banned(_) => (StatusCode::FORBIDDEN, "banned"),
|
||||||
|
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
|
||||||
|
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
|
||||||
|
ApiError::Limited(_) => (StatusCode::TOO_MANY_REQUESTS, "limited"),
|
||||||
|
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for ApiError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
let (status, code) = self.status_and_code();
|
||||||
|
if let ApiError::Internal(detail) = &self {
|
||||||
|
tracing::error!(error = %detail, code, "request failed");
|
||||||
|
}
|
||||||
|
(status, Json(json!({ "error": { "code": code, "message": self.to_string() } }))).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<sqlx::Error> for ApiError {
|
||||||
|
fn from(e: sqlx::Error) -> Self {
|
||||||
|
ApiError::Internal(format!("database: {e}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<JsonRejection> for ApiError {
|
||||||
|
fn from(rejection: JsonRejection) -> Self {
|
||||||
|
ApiError::BadRequest(rejection.body_text())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<QueryRejection> for ApiError {
|
||||||
|
fn from(rejection: QueryRejection) -> Self {
|
||||||
|
ApiError::BadRequest(rejection.body_text())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<PathRejection> for ApiError {
|
||||||
|
fn from(rejection: PathRejection) -> Self {
|
||||||
|
ApiError::BadRequest(rejection.body_text())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type ApiResult<T> = Result<T, ApiError>;
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
//! Sorsfonalak forum: pseudonymous members, topics, threads, posts,
|
||||||
|
//! reactions, read marks, followed threads and moderation (docs/kozosseg.md).
|
||||||
|
//!
|
||||||
|
//! A service of its own, so it can be scaled apart from the backend. It shares
|
||||||
|
//! the database and the login: a session of the backend (`sf_session` cookie
|
||||||
|
//! or `Authorization: Bearer`) is valid here too.
|
||||||
|
//!
|
||||||
|
//! Configuration: `DATABASE_URL`; `BIND_ADDR` (default `0.0.0.0:8083`),
|
||||||
|
//! `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. Database migrations run at startup.
|
||||||
|
//!
|
||||||
|
//! `forum healthcheck` performs a local health check (for Docker).
|
||||||
|
|
||||||
|
mod auth;
|
||||||
|
mod error;
|
||||||
|
mod rank;
|
||||||
|
mod routes;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
mod text;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8083";
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub db: PgPool,
|
||||||
|
/// Seconds a member waits between two posts (0 in the tests).
|
||||||
|
pub flood_secs: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(db: PgPool) -> Self {
|
||||||
|
Self { db, flood_secs: 5 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
|
||||||
|
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||||
|
return service_kit::healthcheck(addr);
|
||||||
|
}
|
||||||
|
let _log = service_kit::init_logging("forum");
|
||||||
|
let url = std::env::var("DATABASE_URL").context("DATABASE_URL is not set")?;
|
||||||
|
let pool = db::connect(&url).await.context("connecting to the database")?;
|
||||||
|
db::migrate(&pool).await.context("running database migrations")?;
|
||||||
|
let app = routes::router(Arc::new(AppState::new(pool)));
|
||||||
|
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||||
|
tracing::info!(%addr, "listening");
|
||||||
|
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
//! Ranks: earned from points (reactions and "Ez segített" marks received)
|
||||||
|
//! and time spent as a member, so nobody climbs in a few days. A rank is
|
||||||
|
//! also a permission level. Buying a package gives no rank: it only lifts the
|
||||||
|
//! newcomer's daily limits (docs/kozosseg.md).
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Rank {
|
||||||
|
Vandor,
|
||||||
|
Kereso,
|
||||||
|
Fono,
|
||||||
|
Csillagfono,
|
||||||
|
Sorsfono,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (rank, points needed, days of membership needed), lowest first.
|
||||||
|
const LADDER: [(Rank, i32, i64); 5] = [
|
||||||
|
(Rank::Vandor, i32::MIN, 0),
|
||||||
|
(Rank::Kereso, 5, 3),
|
||||||
|
(Rank::Fono, 30, 14),
|
||||||
|
(Rank::Csillagfono, 100, 45),
|
||||||
|
(Rank::Sorsfono, 300, 120),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// What an "Ez segített" mark is worth.
|
||||||
|
pub const HELPED_POINTS: i32 = 5;
|
||||||
|
/// Newcomer limits (lifted by a purchase): new threads and posts in 24 hours.
|
||||||
|
pub const NEWCOMER_THREADS_PER_DAY: i64 = 3;
|
||||||
|
pub const NEWCOMER_POSTS_PER_DAY: i64 = 20;
|
||||||
|
/// A post whose reactions add up to this or less is shown collapsed.
|
||||||
|
pub const COLLAPSE_SCORE: i64 = -3;
|
||||||
|
|
||||||
|
impl Rank {
|
||||||
|
pub fn of(points: i32, member_since: OffsetDateTime, now: OffsetDateTime) -> Rank {
|
||||||
|
let days = (now - member_since).whole_days();
|
||||||
|
LADDER.iter().rev().find(|(_, p, d)| points >= *p && days >= *d).map(|(r, _, _)| *r).unwrap_or(Rank::Vandor)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Rank::Vandor => "Vándor",
|
||||||
|
Rank::Kereso => "Kereső",
|
||||||
|
Rank::Fono => "Fonó",
|
||||||
|
Rank::Csillagfono => "Csillagfonó",
|
||||||
|
Rank::Sorsfono => "Sorsfonó",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A newcomer: daily limits, reactions that do not count yet, no ⌄.
|
||||||
|
pub fn is_newcomer(self) -> bool {
|
||||||
|
self == Rank::Vandor
|
||||||
|
}
|
||||||
|
|
||||||
|
/// May use the ⌄ (never in a listening topic).
|
||||||
|
pub fn may_downvote(self) -> bool {
|
||||||
|
self >= Rank::Kereso
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next rank and what it needs, for the member's own profile.
|
||||||
|
pub fn next(self) -> Option<(Rank, i32, i64)> {
|
||||||
|
LADDER.iter().find(|(r, _, _)| *r > self).copied()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ranks_need_points_and_time() {
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let days = |d: i64| now - time::Duration::days(d);
|
||||||
|
assert_eq!(Rank::of(0, days(400), now), Rank::Vandor);
|
||||||
|
assert_eq!(Rank::of(500, days(1), now), Rank::Vandor, "points alone are not enough");
|
||||||
|
assert_eq!(Rank::of(5, days(3), now), Rank::Kereso);
|
||||||
|
assert_eq!(Rank::of(40, days(20), now), Rank::Fono);
|
||||||
|
assert_eq!(Rank::of(40, days(400), now), Rank::Fono);
|
||||||
|
assert_eq!(Rank::of(300, days(120), now), Rank::Sorsfono);
|
||||||
|
assert_eq!(Rank::Vandor.next().map(|n| n.0), Some(Rank::Kereso));
|
||||||
|
assert_eq!(Rank::Sorsfono.next(), None);
|
||||||
|
assert!(!Rank::Vandor.may_downvote() && Rank::Kereso.may_downvote());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
//! The forum's front page, the topics, a topic's threads, followed threads.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Path, Query, State};
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::{CardRow, St, card_params, card_sql, cards_json, may_read, rfc3339};
|
||||||
|
use crate::auth::Viewer;
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
|
||||||
|
/// Threads on one page of a topic.
|
||||||
|
const PAGE_SIZE: i64 = 30;
|
||||||
|
/// "Pörgős most": at least this many replies in the last 24 hours.
|
||||||
|
const HOT_MIN_REPLIES: i64 = 3;
|
||||||
|
/// "Várják a válaszod": threads without a reply from the last two weeks.
|
||||||
|
const UNANSWERED_DAYS: i32 = 14;
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct TopicRow {
|
||||||
|
id: i16,
|
||||||
|
slug: String,
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
visibility: String,
|
||||||
|
listening: bool,
|
||||||
|
thread_count: i64,
|
||||||
|
new_count: Option<i64>,
|
||||||
|
last_author: Option<Uuid>,
|
||||||
|
last_at: Option<OffsetDateTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The topics in order: counts and the latest post for those the viewer may
|
||||||
|
/// read, the others (a members-only topic for a visitor) only by name.
|
||||||
|
async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
|
||||||
|
let (me, since) = card_params(viewer);
|
||||||
|
let rows: Vec<TopicRow> = sqlx::query_as(
|
||||||
|
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \
|
||||||
|
(SELECT count(*) FROM forum.threads th WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) AS thread_count, \
|
||||||
|
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
|
||||||
|
(SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
|
||||||
|
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \
|
||||||
|
AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2::timestamptz \
|
||||||
|
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||||
|
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS new_count, \
|
||||||
|
last.author_id AS last_author, last.created_at AS last_at \
|
||||||
|
FROM forum.topics tp \
|
||||||
|
LEFT JOIN LATERAL (SELECT p.author_id, p.created_at FROM forum.posts p \
|
||||||
|
JOIN forum.threads th ON th.id = p.thread_id \
|
||||||
|
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \
|
||||||
|
ORDER BY p.id DESC LIMIT 1) last ON true \
|
||||||
|
ORDER BY tp.position",
|
||||||
|
)
|
||||||
|
.bind(me)
|
||||||
|
.bind(since)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
let readable: Vec<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility)).collect();
|
||||||
|
let people =
|
||||||
|
super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author))
|
||||||
|
.await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.zip(readable)
|
||||||
|
.filter(|(r, _)| r.visibility != "restricted" || viewer.is_moderator())
|
||||||
|
.map(|(r, readable)| {
|
||||||
|
let mut topic = json!({
|
||||||
|
"id": r.id,
|
||||||
|
"slug": r.slug,
|
||||||
|
"name": r.name,
|
||||||
|
"description": r.description,
|
||||||
|
"visibility": r.visibility,
|
||||||
|
"listening": r.listening,
|
||||||
|
"readable": readable,
|
||||||
|
});
|
||||||
|
if readable {
|
||||||
|
topic["thread_count"] = json!(r.thread_count);
|
||||||
|
topic["new_count"] = json!(r.new_count);
|
||||||
|
topic["last"] = json!(r.last_at.map(|at| json!({
|
||||||
|
"author": r.last_author.and_then(|id| people.get(&id).cloned()),
|
||||||
|
"at": rfc3339(at),
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
topic
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the header and the front page show about the viewer.
|
||||||
|
pub fn viewer_json(viewer: &Viewer) -> Value {
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
json!({
|
||||||
|
"logged_in": viewer.logged_in(),
|
||||||
|
"needs_nickname": viewer.logged_in() && viewer.member.is_none(),
|
||||||
|
"moderator": viewer.is_moderator(),
|
||||||
|
"member": viewer.member.as_ref().map(|m| {
|
||||||
|
let rank = m.rank(now);
|
||||||
|
json!({
|
||||||
|
"nickname": m.nickname,
|
||||||
|
"avatar": m.avatar,
|
||||||
|
"rank": rank,
|
||||||
|
"rank_name": rank.name(),
|
||||||
|
"banned": m.banned(now),
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The front page: the viewer, new replies in followed threads, the topics,
|
||||||
|
/// threads waiting for a first reply, and the busiest threads of the day.
|
||||||
|
pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
|
let (me, since) = card_params(&viewer);
|
||||||
|
let topics = topic_list(&state, &viewer).await?;
|
||||||
|
|
||||||
|
let followed = followed_counts(&state, &viewer).await?;
|
||||||
|
|
||||||
|
let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
|
||||||
|
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 \
|
||||||
|
AND th.created_at > now() - make_interval(days => $3) \
|
||||||
|
ORDER BY th.created_at LIMIT 3",
|
||||||
|
card_sql(&viewer)
|
||||||
|
))
|
||||||
|
.bind(me)
|
||||||
|
.bind(since)
|
||||||
|
.bind(UNANSWERED_DAYS)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let hot: Vec<CardRow> = sqlx::query_as(&format!(
|
||||||
|
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
|
||||||
|
WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
|
||||||
|
GROUP BY thread_id HAVING count(*) >= $3) \
|
||||||
|
{} AND th.id IN (SELECT thread_id FROM recent) \
|
||||||
|
ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5",
|
||||||
|
card_sql(&viewer)
|
||||||
|
))
|
||||||
|
.bind(me)
|
||||||
|
.bind(since)
|
||||||
|
.bind(HOT_MIN_REPLIES)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(Json(json!({
|
||||||
|
"viewer": viewer_json(&viewer),
|
||||||
|
"followed": followed,
|
||||||
|
"topics": topics,
|
||||||
|
"unanswered": cards_json(&state.db, unanswered).await?,
|
||||||
|
"hot": cards_json(&state.db, hot).await?,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// New replies (by others, unread) in the member's followed threads.
|
||||||
|
async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>> {
|
||||||
|
let (Some(me), Some(since)) = card_params(viewer) else { return Ok(None) };
|
||||||
|
let (replies, threads): (i64, i64) = sqlx::query_as(
|
||||||
|
"SELECT count(*), count(DISTINCT p.thread_id) FROM forum.follows f \
|
||||||
|
JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \
|
||||||
|
JOIN forum.posts p ON p.thread_id = f.thread_id AND p.deleted_at IS NULL \
|
||||||
|
WHERE f.user_id = $1 AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2 \
|
||||||
|
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||||
|
WHERE r.user_id = $1 AND r.thread_id = f.thread_id), 0)",
|
||||||
|
)
|
||||||
|
.bind(me)
|
||||||
|
.bind(since)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(Some(json!({ "new_replies": replies, "threads": threads })))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For the forum's menu on every page: who the viewer is, and the badge.
|
||||||
|
pub async fn nav(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
|
Ok(Json(json!({ "viewer": viewer_json(&viewer), "followed": followed_counts(&state, &viewer).await? })))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn topics(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
|
Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? })))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct PageQuery {
|
||||||
|
#[serde(default)]
|
||||||
|
page: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A topic's threads: pinned ones first, then by the latest post.
|
||||||
|
pub async fn topic(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||||
|
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let topic: Option<(i16, String, String, String, bool)> =
|
||||||
|
sqlx::query_as("SELECT id, name, description, visibility, listening FROM forum.topics WHERE slug = $1")
|
||||||
|
.bind(&slug)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?;
|
||||||
|
if !may_read(&viewer, &visibility) {
|
||||||
|
// A members-only topic asks for a login; a restricted one stays hidden.
|
||||||
|
return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") });
|
||||||
|
}
|
||||||
|
let page = q.page.unwrap_or(1).clamp(1, 10_000);
|
||||||
|
let (me, since) = card_params(&viewer);
|
||||||
|
let rows: Vec<CardRow> = sqlx::query_as(&format!(
|
||||||
|
"{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5",
|
||||||
|
card_sql(&viewer)
|
||||||
|
))
|
||||||
|
.bind(me)
|
||||||
|
.bind(since)
|
||||||
|
.bind(id)
|
||||||
|
.bind(PAGE_SIZE + 1)
|
||||||
|
.bind((page - 1) * PAGE_SIZE)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
let has_more = rows.len() as i64 > PAGE_SIZE;
|
||||||
|
let rows = rows.into_iter().take(PAGE_SIZE as usize).collect();
|
||||||
|
Ok(Json(json!({
|
||||||
|
"viewer": viewer_json(&viewer),
|
||||||
|
"topic": {
|
||||||
|
"slug": slug, "name": name, "description": description,
|
||||||
|
"visibility": visibility, "listening": listening,
|
||||||
|
},
|
||||||
|
"threads": cards_json(&state.db, rows).await?,
|
||||||
|
"page": page,
|
||||||
|
"has_more": has_more,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The threads the member follows, the latest activity first, with what is unread.
|
||||||
|
pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
|
viewer.require_member()?;
|
||||||
|
let (me, since) = card_params(&viewer);
|
||||||
|
let rows: Vec<CardRow> = sqlx::query_as(&format!(
|
||||||
|
"{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \
|
||||||
|
ORDER BY th.last_post_at DESC LIMIT 50",
|
||||||
|
card_sql(&viewer)
|
||||||
|
))
|
||||||
|
.bind(me)
|
||||||
|
.bind(since)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? })))
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
//! Members: one's own forum profile (nickname first), the nickname check
|
||||||
|
//! while typing, the online heartbeat, and a member's public profile.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Path, Query, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::home::viewer_json;
|
||||||
|
use super::{Body, St, authors, online, rfc3339, shared_signs, visible_topics};
|
||||||
|
use crate::auth::{self, Viewer};
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
use crate::text;
|
||||||
|
|
||||||
|
/// A nickname may change once in this many days (spelling fixes that keep the
|
||||||
|
/// same folded form any time).
|
||||||
|
const NICKNAME_CHANGE_DAYS: i64 = 30;
|
||||||
|
/// A nickname given up stays reserved this long.
|
||||||
|
const NICKNAME_RESERVED_DAYS: i64 = 90;
|
||||||
|
|
||||||
|
/// The viewer's own forum profile, and what each chart sharing level would show.
|
||||||
|
pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
|
let user = viewer.require_user()?;
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let member = viewer.member.as_ref().map(|m| {
|
||||||
|
let rank = m.rank(now);
|
||||||
|
let change_after = m.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
|
||||||
|
json!({
|
||||||
|
"nickname": m.nickname,
|
||||||
|
"avatar": m.avatar,
|
||||||
|
"bio": m.bio,
|
||||||
|
"chart_share": m.chart_share,
|
||||||
|
"invisible": m.invisible,
|
||||||
|
"points": m.points,
|
||||||
|
"post_count": m.post_count,
|
||||||
|
"created_at": rfc3339(m.created_at),
|
||||||
|
"rank": rank,
|
||||||
|
"rank_name": rank.name(),
|
||||||
|
"next_rank": rank.next().map(|(r, points, days)| json!({
|
||||||
|
"rank": r, "name": r.name(), "points": points, "days": days,
|
||||||
|
})),
|
||||||
|
"nickname_change_after": (change_after > now).then(|| rfc3339(change_after)),
|
||||||
|
"banned_until": m.banned_until.filter(|u| *u > now).map(|u| {
|
||||||
|
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||||
|
}),
|
||||||
|
"ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)),
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id);
|
||||||
|
let chart = signs.map(|s| json!({ "sun": s.share("sun"), "big3": s.share("big3"), "planets": s.share("planets") }));
|
||||||
|
Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart })))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct SaveMe {
|
||||||
|
nickname: String,
|
||||||
|
#[serde(default)]
|
||||||
|
avatar: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
bio: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
chart_share: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
invisible: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether someone else has (or recently had) this folded nickname.
|
||||||
|
async fn nickname_taken(db: &sqlx::PgPool, key: &str, me: Uuid) -> Result<bool, sqlx::Error> {
|
||||||
|
sqlx::query_scalar(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM forum.members WHERE nickname_key = $1 AND user_id <> $2) \
|
||||||
|
OR EXISTS (SELECT 1 FROM forum.retired_nicknames \
|
||||||
|
WHERE nickname_key = $1 AND user_id <> $2 AND until > now())",
|
||||||
|
)
|
||||||
|
.bind(key)
|
||||||
|
.bind(me)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn taken() -> ApiError {
|
||||||
|
ApiError::conflict("nickname_taken", "Ezt az álnevet már más használja. Válassz másikat.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates the forum profile (choosing a nickname is the first step) or changes it.
|
||||||
|
pub async fn save_me(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Json(req), _): Body<SaveMe>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let user = viewer.require_user()?;
|
||||||
|
let nickname = text::nickname(&req.nickname)?;
|
||||||
|
let key = text::nickname_key(&nickname);
|
||||||
|
let avatar = req.avatar.as_deref().map(text::avatar).transpose()?;
|
||||||
|
let bio = req.bio.as_deref().map(text::bio).transpose()?;
|
||||||
|
let chart_share = match req.chart_share.as_deref() {
|
||||||
|
None => None,
|
||||||
|
Some(level @ ("none" | "sun" | "big3" | "planets")) => Some(level.to_string()),
|
||||||
|
Some(_) => return Err(ApiError::bad("Ismeretlen megosztási szint.")),
|
||||||
|
};
|
||||||
|
if nickname_taken(&state.db, &key, user.id).await? {
|
||||||
|
return Err(taken());
|
||||||
|
}
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let result = match &viewer.member {
|
||||||
|
None => {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, bio, chart_share, invisible) \
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||||
|
)
|
||||||
|
.bind(user.id)
|
||||||
|
.bind(&nickname)
|
||||||
|
.bind(&key)
|
||||||
|
.bind(avatar.unwrap_or_else(|| text::default_avatar(&key)))
|
||||||
|
.bind(bio.unwrap_or_default())
|
||||||
|
.bind(chart_share.unwrap_or_else(|| "none".into()))
|
||||||
|
.bind(req.invisible.unwrap_or(false))
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
Some(member) => {
|
||||||
|
let old_key = text::nickname_key(&member.nickname);
|
||||||
|
let renamed = old_key != key;
|
||||||
|
if renamed {
|
||||||
|
let allowed = member.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
|
||||||
|
if allowed > now {
|
||||||
|
return Err(ApiError::conflict(
|
||||||
|
"nickname_too_soon",
|
||||||
|
format!("Az álneved {NICKNAME_CHANGE_DAYS} naponta egyszer változtathatod meg."),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO forum.retired_nicknames (nickname_key, user_id, until) \
|
||||||
|
VALUES ($1, $2, now() + make_interval(days => $3)) \
|
||||||
|
ON CONFLICT (nickname_key) DO UPDATE SET user_id = EXCLUDED.user_id, until = EXCLUDED.until",
|
||||||
|
)
|
||||||
|
.bind(&old_key)
|
||||||
|
.bind(user.id)
|
||||||
|
.bind(NICKNAME_RESERVED_DAYS as i32)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
// Taking back one's own earlier name.
|
||||||
|
sqlx::query("DELETE FROM forum.retired_nicknames WHERE nickname_key = $1 AND user_id = $2")
|
||||||
|
.bind(&key)
|
||||||
|
.bind(user.id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE forum.members SET nickname = $2, nickname_key = $3, \
|
||||||
|
avatar = COALESCE($4, avatar), bio = COALESCE($5, bio), \
|
||||||
|
chart_share = COALESCE($6, chart_share), invisible = COALESCE($7, invisible), \
|
||||||
|
nickname_changed_at = CASE WHEN $8 THEN now() ELSE nickname_changed_at END \
|
||||||
|
WHERE user_id = $1",
|
||||||
|
)
|
||||||
|
.bind(user.id)
|
||||||
|
.bind(&nickname)
|
||||||
|
.bind(&key)
|
||||||
|
.bind(avatar)
|
||||||
|
.bind(bio)
|
||||||
|
.bind(chart_share)
|
||||||
|
.bind(req.invisible)
|
||||||
|
.bind(renamed)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(_) => {}
|
||||||
|
// Someone took it in the same moment.
|
||||||
|
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => return Err(taken()),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer };
|
||||||
|
me(State(state), viewer).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct NameQuery {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// While typing: is this nickname valid and free?
|
||||||
|
pub async fn nickname_check(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Query(q), _): WithRejection<Query<NameQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let user = viewer.require_user()?;
|
||||||
|
let nickname = match text::nickname(&q.name) {
|
||||||
|
Ok(n) => n,
|
||||||
|
Err(e) => return Ok(Json(json!({ "ok": false, "message": e.to_string() }))),
|
||||||
|
};
|
||||||
|
if nickname_taken(&state.db, &text::nickname_key(&nickname), user.id).await? {
|
||||||
|
return Ok(Json(json!({ "ok": false, "message": taken().to_string() })));
|
||||||
|
}
|
||||||
|
Ok(Json(json!({ "ok": true, "nickname": nickname })))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The page is open: keeps the online dot (the viewer extractor does the work).
|
||||||
|
pub async fn presence(_viewer: Viewer) -> StatusCode {
|
||||||
|
StatusCode::NO_CONTENT
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct ProfileRow {
|
||||||
|
user_id: Uuid,
|
||||||
|
bio: String,
|
||||||
|
created_at: OffsetDateTime,
|
||||||
|
post_count: i32,
|
||||||
|
invisible: bool,
|
||||||
|
last_seen_at: Option<OffsetDateTime>,
|
||||||
|
banned_until: Option<OffsetDateTime>,
|
||||||
|
ban_reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct RecentRow {
|
||||||
|
id: i64,
|
||||||
|
thread_id: i64,
|
||||||
|
title: String,
|
||||||
|
topic_slug: String,
|
||||||
|
topic_name: String,
|
||||||
|
created_at: OffsetDateTime,
|
||||||
|
excerpt: String,
|
||||||
|
is_opening: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A member's public profile: nickname, avatar, rank, shared signs, bio,
|
||||||
|
/// activity (coarsely), and recent posts from the topics the viewer may read.
|
||||||
|
pub async fn profile(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let row: ProfileRow = sqlx::query_as(
|
||||||
|
"SELECT user_id, bio, created_at, post_count, invisible, last_seen_at, banned_until, ban_reason \
|
||||||
|
FROM forum.members WHERE nickname_key = $1",
|
||||||
|
)
|
||||||
|
.bind(text::nickname_key(&nickname))
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?
|
||||||
|
.ok_or(ApiError::NotFound("member"))?;
|
||||||
|
let brief = authors(&state.db, [row.user_id]).await?.remove(&row.user_id).ok_or(ApiError::NotFound("member"))?;
|
||||||
|
let recent: Vec<RecentRow> = sqlx::query_as(&format!(
|
||||||
|
"SELECT p.id, p.thread_id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, p.created_at, \
|
||||||
|
left(p.body, 200) AS excerpt, p.is_opening \
|
||||||
|
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||||
|
WHERE p.author_id = $1 AND p.deleted_at IS NULL AND th.deleted_at IS NULL AND ({}) \
|
||||||
|
ORDER BY p.id DESC LIMIT 10",
|
||||||
|
visible_topics(&viewer)
|
||||||
|
))
|
||||||
|
.bind(row.user_id)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
let thread_count: i64 =
|
||||||
|
sqlx::query_scalar("SELECT count(*) FROM forum.threads WHERE author_id = $1 AND deleted_at IS NULL")
|
||||||
|
.bind(row.user_id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let own = viewer.user_id() == Some(row.user_id);
|
||||||
|
let last_seen = if row.invisible && !own {
|
||||||
|
None
|
||||||
|
} else if online(false, row.last_seen_at, now) {
|
||||||
|
Some("online")
|
||||||
|
} else {
|
||||||
|
row.last_seen_at.map(|t| match now - t {
|
||||||
|
d if d < time::Duration::days(1) => "day",
|
||||||
|
d if d < time::Duration::days(7) => "week",
|
||||||
|
_ => "earlier",
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let banned = row.banned_until.filter(|u| *u > now);
|
||||||
|
let show_ban = own || viewer.is_moderator();
|
||||||
|
Ok(Json(json!({
|
||||||
|
"viewer": viewer_json(&viewer),
|
||||||
|
"member": {
|
||||||
|
"author": brief,
|
||||||
|
"bio": row.bio,
|
||||||
|
"created_at": rfc3339(row.created_at),
|
||||||
|
"post_count": row.post_count,
|
||||||
|
"thread_count": thread_count,
|
||||||
|
"last_seen": last_seen,
|
||||||
|
"own": own,
|
||||||
|
"banned_until": banned.filter(|_| show_ban).map(|u| {
|
||||||
|
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||||
|
}),
|
||||||
|
"ban_reason": row.ban_reason.filter(|_| show_ban && banned.is_some()),
|
||||||
|
},
|
||||||
|
"recent": recent.into_iter().map(|r| json!({
|
||||||
|
"id": r.id,
|
||||||
|
"thread_id": r.thread_id,
|
||||||
|
"thread_slug": text::slug(&r.title),
|
||||||
|
"thread_title": r.title,
|
||||||
|
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||||
|
"created_at": rfc3339(r.created_at),
|
||||||
|
"excerpt": r.excerpt,
|
||||||
|
"is_opening": r.is_opening,
|
||||||
|
})).collect::<Vec<_>>(),
|
||||||
|
})))
|
||||||
|
}
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
//! HTTP routes, all under `/v1/forum`.
|
||||||
|
//!
|
||||||
|
//! Reading is open (members-only topics need a login); writing needs a
|
||||||
|
//! nickname ([`Viewer::require_writer`]); moderation the moderator or admin
|
||||||
|
//! role. A thread in a topic the viewer may not read answers 404, so its
|
||||||
|
//! existence is not revealed.
|
||||||
|
|
||||||
|
mod home;
|
||||||
|
mod members;
|
||||||
|
mod moderation;
|
||||||
|
mod posts;
|
||||||
|
mod threads;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::routing::{get, post, put};
|
||||||
|
use axum::{Json, Router};
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use tower_http::trace::TraceLayer;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::auth::{ONLINE_MINUTES, Viewer};
|
||||||
|
use crate::error::ApiError;
|
||||||
|
use crate::rank::Rank;
|
||||||
|
|
||||||
|
pub type Body<T> = WithRejection<Json<T>, ApiError>;
|
||||||
|
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
||||||
|
pub type St = State<Arc<AppState>>;
|
||||||
|
|
||||||
|
pub fn router(state: Arc<AppState>) -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/healthz", get(health))
|
||||||
|
.route("/v1/forum/home", get(home::home))
|
||||||
|
.route("/v1/forum/nav", get(home::nav))
|
||||||
|
.route("/v1/forum/topics", get(home::topics))
|
||||||
|
.route("/v1/forum/topics/{slug}", get(home::topic))
|
||||||
|
.route("/v1/forum/followed", get(home::followed))
|
||||||
|
.route("/v1/forum/threads", post(threads::create))
|
||||||
|
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
|
||||||
|
.route("/v1/forum/threads/{id}/restore", post(threads::restore))
|
||||||
|
.route("/v1/forum/threads/{id}/posts", post(threads::reply))
|
||||||
|
.route("/v1/forum/threads/{id}/read", post(threads::mark_read))
|
||||||
|
.route("/v1/forum/threads/{id}/follow", put(threads::follow).delete(threads::unfollow))
|
||||||
|
.route("/v1/forum/posts/{id}", axum::routing::patch(posts::edit).delete(posts::remove))
|
||||||
|
.route("/v1/forum/posts/{id}/restore", post(posts::restore))
|
||||||
|
.route("/v1/forum/posts/{id}/reaction", put(posts::react).delete(posts::unreact))
|
||||||
|
.route("/v1/forum/posts/{id}/helped", put(posts::mark_helped).delete(posts::unmark_helped))
|
||||||
|
.route("/v1/forum/me", get(members::me).put(members::save_me))
|
||||||
|
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
||||||
|
.route("/v1/forum/presence", post(members::presence))
|
||||||
|
.route("/v1/forum/members/{nickname}", get(members::profile))
|
||||||
|
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
|
||||||
|
.route("/v1/forum/mod/log", get(moderation::log))
|
||||||
|
// The request log: masked paths, health checks only when they fail.
|
||||||
|
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
|
||||||
|
.with_state(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
|
||||||
|
sqlx::query("SELECT 1").execute(&state.db).await?;
|
||||||
|
Ok(Json(json!({ "status": "ok" })))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
|
||||||
|
/// Built from the viewer's flags only, never from input.
|
||||||
|
pub fn visible_topics(viewer: &Viewer) -> &'static str {
|
||||||
|
if viewer.is_moderator() {
|
||||||
|
"TRUE"
|
||||||
|
} else if viewer.logged_in() {
|
||||||
|
"tp.visibility IN ('public', 'members')"
|
||||||
|
} else {
|
||||||
|
"tp.visibility = 'public'"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the viewer may read a topic of this visibility.
|
||||||
|
pub fn may_read(viewer: &Viewer, visibility: &str) -> bool {
|
||||||
|
match visibility {
|
||||||
|
"public" => true,
|
||||||
|
"members" => viewer.logged_in(),
|
||||||
|
_ => viewer.is_moderator(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A thread in a list: what the cards on the forum pages show.
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
pub struct CardRow {
|
||||||
|
pub id: i64,
|
||||||
|
pub title: String,
|
||||||
|
pub intent: Option<String>,
|
||||||
|
pub author_id: Option<Uuid>,
|
||||||
|
pub created_at: OffsetDateTime,
|
||||||
|
pub last_post_at: OffsetDateTime,
|
||||||
|
pub reply_count: i32,
|
||||||
|
pub pinned: bool,
|
||||||
|
pub locked: bool,
|
||||||
|
pub topic_slug: String,
|
||||||
|
pub topic_name: String,
|
||||||
|
pub participants: i64,
|
||||||
|
/// Posts by others the member has not read; `None` for visitors.
|
||||||
|
pub unread: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
|
||||||
|
/// the member's user id and `$2` when they joined (both NULL for a visitor),
|
||||||
|
/// so the caller's own parameters start at `$3`. Append `AND …`, `ORDER BY`, `LIMIT`.
|
||||||
|
pub fn card_sql(viewer: &Viewer) -> String {
|
||||||
|
format!(
|
||||||
|
"SELECT th.id, th.title, th.intent, th.author_id, th.created_at, th.last_post_at, th.reply_count, \
|
||||||
|
th.pinned, th.locked, tp.slug AS topic_slug, tp.name AS topic_name, \
|
||||||
|
(SELECT count(DISTINCT p.author_id) FROM forum.posts p \
|
||||||
|
WHERE p.thread_id = th.id AND p.deleted_at IS NULL) AS participants, \
|
||||||
|
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
|
||||||
|
(SELECT count(*) FROM forum.posts p \
|
||||||
|
WHERE p.thread_id = th.id AND p.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
|
||||||
|
AND p.created_at > $2::timestamptz \
|
||||||
|
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||||
|
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread \
|
||||||
|
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||||
|
WHERE th.deleted_at IS NULL AND ({})",
|
||||||
|
visible_topics(viewer)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `$1` and `$2` of [`card_sql`].
|
||||||
|
pub fn card_params(viewer: &Viewer) -> (Option<Uuid>, Option<OffsetDateTime>) {
|
||||||
|
match &viewer.member {
|
||||||
|
Some(m) => (Some(m.user_id), Some(m.created_at)),
|
||||||
|
None => (None, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, sqlx::Error> {
|
||||||
|
let people = authors(db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
json!({
|
||||||
|
"id": r.id,
|
||||||
|
"slug": crate::text::slug(&r.title),
|
||||||
|
"title": r.title,
|
||||||
|
"intent": r.intent,
|
||||||
|
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||||
|
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
|
||||||
|
"created_at": rfc3339(r.created_at),
|
||||||
|
"last_post_at": rfc3339(r.last_post_at),
|
||||||
|
"reply_count": r.reply_count,
|
||||||
|
"participants": r.participants,
|
||||||
|
"pinned": r.pinned,
|
||||||
|
"locked": r.locked,
|
||||||
|
"unread": r.unread,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct AuthorRow {
|
||||||
|
user_id: Uuid,
|
||||||
|
nickname: String,
|
||||||
|
avatar: String,
|
||||||
|
points: i32,
|
||||||
|
created_at: OffsetDateTime,
|
||||||
|
invisible: bool,
|
||||||
|
last_seen_at: Option<OffsetDateTime>,
|
||||||
|
chart_share: String,
|
||||||
|
roles: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How members appear next to what they wrote: nickname, avatar, rank,
|
||||||
|
/// moderator badge, online dot, and the signs they chose to share.
|
||||||
|
pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
|
||||||
|
let mut ids: Vec<Uuid> = ids.into_iter().collect();
|
||||||
|
ids.sort_unstable();
|
||||||
|
ids.dedup();
|
||||||
|
if ids.is_empty() {
|
||||||
|
return Ok(HashMap::new());
|
||||||
|
}
|
||||||
|
let rows: Vec<AuthorRow> = sqlx::query_as(
|
||||||
|
"SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \
|
||||||
|
m.chart_share, u.roles \
|
||||||
|
FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.user_id = ANY($1)",
|
||||||
|
)
|
||||||
|
.bind(&ids)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let sharing: Vec<Uuid> = rows.iter().filter(|r| r.chart_share != "none").map(|r| r.user_id).collect();
|
||||||
|
let signs = shared_signs(db, &sharing).await?;
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
let rank = Rank::of(r.points, r.created_at, now);
|
||||||
|
let moderator = r.roles.iter().any(|role| role == "moderator" || role == "admin");
|
||||||
|
let shown = signs.get(&r.user_id).map(|chart| chart.share(&r.chart_share));
|
||||||
|
let value = json!({
|
||||||
|
"nickname": r.nickname,
|
||||||
|
"avatar": r.avatar,
|
||||||
|
"rank": rank,
|
||||||
|
"rank_name": rank.name(),
|
||||||
|
"moderator": moderator,
|
||||||
|
"online": online(r.invisible, r.last_seen_at, now),
|
||||||
|
"signs": shown,
|
||||||
|
});
|
||||||
|
(r.user_id, value)
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn online(invisible: bool, last_seen_at: Option<OffsetDateTime>, now: OffsetDateTime) -> bool {
|
||||||
|
!invisible && last_seen_at.is_some_and(|t| now - t < time::Duration::minutes(ONLINE_MINUTES))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The signs of a member's own chart (never degrees: they would give away the
|
||||||
|
/// birth date and time).
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct ChartSigns {
|
||||||
|
/// Planet id → sign id, in the chart's order.
|
||||||
|
pub planets: Vec<(String, String)>,
|
||||||
|
/// Only when the birth time is known.
|
||||||
|
pub ascendant: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const PLANETS: [&str; 10] =
|
||||||
|
["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||||
|
|
||||||
|
impl ChartSigns {
|
||||||
|
fn sign(&self, id: &str) -> Option<&str> {
|
||||||
|
self.planets.iter().find(|(p, _)| p == id).map(|(_, s)| s.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a sharing level shows; `None` for "none".
|
||||||
|
pub fn share(&self, level: &str) -> Option<Value> {
|
||||||
|
let mut out = serde_json::Map::new();
|
||||||
|
let mut put = |key: &str, sign: Option<&str>| {
|
||||||
|
if let Some(sign) = sign {
|
||||||
|
out.insert(key.to_string(), json!(sign));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match level {
|
||||||
|
"sun" => put("sun", self.sign("sun")),
|
||||||
|
"big3" => {
|
||||||
|
put("sun", self.sign("sun"));
|
||||||
|
put("moon", self.sign("moon"));
|
||||||
|
put("ascendant", self.ascendant.as_deref());
|
||||||
|
}
|
||||||
|
"planets" => {
|
||||||
|
for planet in PLANETS {
|
||||||
|
put(planet, self.sign(planet));
|
||||||
|
}
|
||||||
|
put("ascendant", self.ascendant.as_deref());
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
}
|
||||||
|
if out.is_empty() { None } else { Some(Value::Object(out)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The signs of each user's own chart (the current one first).
|
||||||
|
pub async fn shared_signs(db: &PgPool, users: &[Uuid]) -> Result<HashMap<Uuid, ChartSigns>, sqlx::Error> {
|
||||||
|
if users.is_empty() {
|
||||||
|
return Ok(HashMap::new());
|
||||||
|
}
|
||||||
|
type Row = (Uuid, Option<Value>, Option<String>, Option<bool>);
|
||||||
|
let rows: Vec<Row> = sqlx::query_as(
|
||||||
|
"SELECT DISTINCT ON (owner_id) owner_id, result->'points', result->'angles'->'ascendant'->>'sign', \
|
||||||
|
(result->'time'->>'time_known')::boolean \
|
||||||
|
FROM charts WHERE owner_id = ANY($1) AND kind = 'own' ORDER BY owner_id, is_primary DESC, created_at",
|
||||||
|
)
|
||||||
|
.bind(users)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|(owner, points, ascendant, time_known)| {
|
||||||
|
let planets = points
|
||||||
|
.as_ref()
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|p| Some((p["id"].as_str()?.to_string(), p["sign"].as_str()?.to_string())))
|
||||||
|
.filter(|(id, _)| PLANETS.contains(&id.as_str()))
|
||||||
|
.collect();
|
||||||
|
let ascendant = ascendant.filter(|_| time_known.unwrap_or(false));
|
||||||
|
(owner, ChartSigns { planets, ascendant })
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rfc3339(t: OffsetDateTime) -> String {
|
||||||
|
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the user bought a package (lifts the newcomer limits).
|
||||||
|
pub async fn has_purchase(db: &PgPool, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||||
|
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')")
|
||||||
|
.bind(user)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
//! Moderation: bans and the log of every moderation step (who, what, why;
|
||||||
|
//! a person or, later, the AI). Removing posts and threads is in their modules.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::{Body, St, rfc3339};
|
||||||
|
use crate::auth::Viewer;
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
use crate::text;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum Action {
|
||||||
|
DeletePost,
|
||||||
|
RestorePost,
|
||||||
|
DeleteThread,
|
||||||
|
RestoreThread,
|
||||||
|
Ban,
|
||||||
|
Unban,
|
||||||
|
Lock,
|
||||||
|
Unlock,
|
||||||
|
Pin,
|
||||||
|
Unpin,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Action {
|
||||||
|
fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::DeletePost => "delete_post",
|
||||||
|
Action::RestorePost => "restore_post",
|
||||||
|
Action::DeleteThread => "delete_thread",
|
||||||
|
Action::RestoreThread => "restore_thread",
|
||||||
|
Action::Ban => "ban",
|
||||||
|
Action::Unban => "unban",
|
||||||
|
Action::Lock => "lock",
|
||||||
|
Action::Unlock => "unlock",
|
||||||
|
Action::Pin => "pin",
|
||||||
|
Action::Unpin => "unpin",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes one line of the moderation log (a person's step).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub async fn record(
|
||||||
|
db: impl sqlx::PgExecutor<'_>,
|
||||||
|
actor: Uuid,
|
||||||
|
action: Action,
|
||||||
|
target_user: Option<Uuid>,
|
||||||
|
thread_id: Option<i64>,
|
||||||
|
post_id: Option<i64>,
|
||||||
|
reason: Option<&str>,
|
||||||
|
until: Option<OffsetDateTime>,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \
|
||||||
|
VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)",
|
||||||
|
)
|
||||||
|
.bind(actor)
|
||||||
|
.bind(action.as_str())
|
||||||
|
.bind(target_user)
|
||||||
|
.bind(thread_id)
|
||||||
|
.bind(post_id)
|
||||||
|
.bind(reason)
|
||||||
|
.bind(until)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A ban for good: the last day of year 9999.
|
||||||
|
fn forever() -> OffsetDateTime {
|
||||||
|
let day = time::Date::from_calendar_date(9999, time::Month::December, 31).expect("valid date");
|
||||||
|
time::PrimitiveDateTime::new(day, time::Time::MIDNIGHT).assume_utc()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The longest temporary ban, in hours (a year); longer is a ban for good.
|
||||||
|
const MAX_BAN_HOURS: i64 = 24 * 365;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct BanRequest {
|
||||||
|
/// Hours; missing or `null`: for good.
|
||||||
|
#[serde(default)]
|
||||||
|
hours: Option<i64>,
|
||||||
|
#[serde(default)]
|
||||||
|
reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The member behind a nickname, and whether they are a moderator or admin.
|
||||||
|
async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> {
|
||||||
|
let row: Option<(Uuid, Vec<String>)> = sqlx::query_as(
|
||||||
|
"SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1",
|
||||||
|
)
|
||||||
|
.bind(text::nickname_key(nickname))
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
let (id, roles) = row.ok_or(ApiError::NotFound("member"))?;
|
||||||
|
Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A moderator bans a member for some hours or for good: they may still
|
||||||
|
/// read, not write. Moderators and admins cannot be banned this way.
|
||||||
|
pub async fn ban(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||||
|
WithRejection(Json(req), _): Body<BanRequest>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let moderator = viewer.require_moderator()?;
|
||||||
|
let (user, protected) = target(&state.db, &nickname).await?;
|
||||||
|
if protected {
|
||||||
|
return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into()));
|
||||||
|
}
|
||||||
|
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||||
|
let until = match req.hours {
|
||||||
|
Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h),
|
||||||
|
Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))),
|
||||||
|
None => forever(),
|
||||||
|
};
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1")
|
||||||
|
.bind(user)
|
||||||
|
.bind(until)
|
||||||
|
.bind(&reason)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned");
|
||||||
|
Ok(Json(json!({ "banned_until": if req.hours.is_none() { "infinity".to_string() } else { rfc3339(until) } })))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unban(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||||
|
) -> ApiResult<StatusCode> {
|
||||||
|
let moderator = viewer.require_moderator()?;
|
||||||
|
let (user, _) = target(&state.db, &nickname).await?;
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1")
|
||||||
|
.bind(user)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct LogRow {
|
||||||
|
id: i64,
|
||||||
|
actor: Option<String>,
|
||||||
|
actor_kind: String,
|
||||||
|
action: String,
|
||||||
|
target: Option<String>,
|
||||||
|
thread_id: Option<i64>,
|
||||||
|
thread_title: Option<String>,
|
||||||
|
post_id: Option<i64>,
|
||||||
|
reason: Option<String>,
|
||||||
|
until: Option<OffsetDateTime>,
|
||||||
|
created_at: OffsetDateTime,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The latest moderation steps, for moderators.
|
||||||
|
pub async fn log(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
|
viewer.require_moderator()?;
|
||||||
|
let rows: Vec<LogRow> = sqlx::query_as(
|
||||||
|
"SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \
|
||||||
|
tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.reason, l.until, l.created_at \
|
||||||
|
FROM forum.mod_log l \
|
||||||
|
LEFT JOIN forum.members am ON am.user_id = l.actor_id \
|
||||||
|
LEFT JOIN users au ON au.id = l.actor_id \
|
||||||
|
LEFT JOIN forum.members tm ON tm.user_id = l.target_user \
|
||||||
|
LEFT JOIN forum.threads th ON th.id = l.thread_id \
|
||||||
|
ORDER BY l.id DESC LIMIT 200",
|
||||||
|
)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(Json(json!({
|
||||||
|
"entries": rows.into_iter().map(|r| json!({
|
||||||
|
"id": r.id,
|
||||||
|
"actor": r.actor,
|
||||||
|
"actor_kind": r.actor_kind,
|
||||||
|
"action": r.action,
|
||||||
|
"target": r.target,
|
||||||
|
"thread": r.thread_id.map(|id| json!({ "id": id, "title": r.thread_title })),
|
||||||
|
"post_id": r.post_id,
|
||||||
|
"reason": r.reason,
|
||||||
|
"until": r.until.map(|u| if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }),
|
||||||
|
"created_at": rfc3339(r.created_at),
|
||||||
|
})).collect::<Vec<_>>(),
|
||||||
|
})))
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
//! A post: editing one's own, removal (one's own, or a moderator's with a
|
||||||
|
//! reason), the admin's restore, reactions and the "Ez segített" mark.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
use super::moderation::{self, Action};
|
||||||
|
use super::threads::{POST_COLUMNS, PostRow, REACTIONS, Reason, ThreadRow, open_thread, posts_json, readable_thread};
|
||||||
|
use super::{Body, IdPath, St};
|
||||||
|
use crate::auth::Viewer;
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
use crate::rank::HELPED_POINTS;
|
||||||
|
use crate::text;
|
||||||
|
|
||||||
|
/// A post and its thread, both readable by the viewer.
|
||||||
|
async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> {
|
||||||
|
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?
|
||||||
|
.ok_or(ApiError::NotFound("post"))?;
|
||||||
|
let thread = readable_thread(db, viewer, post.thread_id).await?;
|
||||||
|
Ok((post, thread))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct Edit {
|
||||||
|
body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The author changes their post (while the thread is open).
|
||||||
|
pub async fn edit(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<Edit>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let member = viewer.require_writer()?;
|
||||||
|
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||||
|
if post.author_id != Some(member.user_id) || post.deleted_at.is_some() {
|
||||||
|
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into()));
|
||||||
|
}
|
||||||
|
open_thread(&state.db, &viewer, post.thread_id).await?;
|
||||||
|
let body = text::body(&req.body)?;
|
||||||
|
let post: PostRow = sqlx::query_as(&format!(
|
||||||
|
"UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}"
|
||||||
|
))
|
||||||
|
.bind(id)
|
||||||
|
.bind(&body)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The author takes back their post, or a moderator removes it with a reason.
|
||||||
|
/// Hidden, not erased: the admin can restore it.
|
||||||
|
pub async fn remove(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<Reason>,
|
||||||
|
) -> ApiResult<StatusCode> {
|
||||||
|
let user = viewer.require_user()?;
|
||||||
|
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||||
|
if post.deleted_at.is_some() {
|
||||||
|
return Ok(StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
let own = post.author_id == Some(user.id);
|
||||||
|
let reason = if own {
|
||||||
|
None
|
||||||
|
} else if viewer.is_moderator() {
|
||||||
|
Some(text::reason(req.reason.as_deref().unwrap_or(""))?)
|
||||||
|
} else {
|
||||||
|
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat törölheted.".into()));
|
||||||
|
};
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
sqlx::query("UPDATE forum.posts SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.bind(user.id)
|
||||||
|
.bind(&reason)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if !post.is_opening {
|
||||||
|
sqlx::query("UPDATE forum.threads SET reply_count = greatest(reply_count - 1, 0) WHERE id = $1")
|
||||||
|
.bind(post.thread_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
if !own {
|
||||||
|
moderation::record(
|
||||||
|
&mut *tx,
|
||||||
|
user.id,
|
||||||
|
Action::DeletePost,
|
||||||
|
post.author_id,
|
||||||
|
Some(post.thread_id),
|
||||||
|
Some(id),
|
||||||
|
reason.as_deref(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The admin undoes a removal.
|
||||||
|
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||||
|
let admin = viewer.require_user()?;
|
||||||
|
if !viewer.is_admin() {
|
||||||
|
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||||
|
}
|
||||||
|
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||||
|
if post.deleted_at.is_none() {
|
||||||
|
return Ok(StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if !post.is_opening {
|
||||||
|
sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1")
|
||||||
|
.bind(post.thread_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
moderation::record(
|
||||||
|
&mut *tx,
|
||||||
|
admin.id,
|
||||||
|
Action::RestorePost,
|
||||||
|
post.author_id,
|
||||||
|
Some(post.thread_id),
|
||||||
|
Some(id),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct React {
|
||||||
|
kind: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn points_of(kind: &str) -> i32 {
|
||||||
|
if kind == "down" { -1 } else { 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gives (or changes) the viewer's one reaction to a post. A newcomer's
|
||||||
|
/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is
|
||||||
|
/// not offered in listening topics.
|
||||||
|
pub async fn react(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<React>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let member = viewer.require_writer()?;
|
||||||
|
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||||
|
if post.deleted_at.is_some() {
|
||||||
|
return Err(ApiError::NotFound("post"));
|
||||||
|
}
|
||||||
|
open_thread(&state.db, &viewer, thread.id).await?;
|
||||||
|
if post.author_id == Some(member.user_id) {
|
||||||
|
return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into()));
|
||||||
|
}
|
||||||
|
let kind = req.kind.as_str();
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let rank = member.rank(now);
|
||||||
|
if kind == "down" {
|
||||||
|
if thread.listening {
|
||||||
|
return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into()));
|
||||||
|
}
|
||||||
|
if !rank.may_downvote() {
|
||||||
|
return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into()));
|
||||||
|
}
|
||||||
|
} else if !REACTIONS.contains(&kind) {
|
||||||
|
return Err(ApiError::bad("Ismeretlen reakció."));
|
||||||
|
}
|
||||||
|
let counted = !rank.is_newcomer();
|
||||||
|
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let previous: Option<(String, bool)> =
|
||||||
|
sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE")
|
||||||
|
.bind(id)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let mut delta = if counted { points_of(kind) } else { 0 };
|
||||||
|
if let Some((old, true)) = &previous {
|
||||||
|
delta -= points_of(old);
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \
|
||||||
|
ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(kind)
|
||||||
|
.bind(counted)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
add_points(&mut tx, post.author_id, delta).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||||
|
let member = viewer.require_writer()?;
|
||||||
|
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let removed: Option<(String, bool)> =
|
||||||
|
sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted")
|
||||||
|
.bind(id)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if let Some((kind, true)) = removed {
|
||||||
|
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn add_points(tx: &mut sqlx::PgConnection, author: Option<uuid::Uuid>, delta: i32) -> Result<(), sqlx::Error> {
|
||||||
|
if let (Some(author), true) = (author, delta != 0) {
|
||||||
|
sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1")
|
||||||
|
.bind(author)
|
||||||
|
.bind(delta)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The thread's author marks a reply that helped (worth more than a reaction).
|
||||||
|
pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||||
|
set_helped(state, viewer, path, true).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||||
|
set_helped(state, viewer, path, false).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_helped(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
on: bool,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let member = viewer.require_writer()?;
|
||||||
|
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||||
|
if thread.author_id != Some(member.user_id) {
|
||||||
|
return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into()));
|
||||||
|
}
|
||||||
|
if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() {
|
||||||
|
return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted."));
|
||||||
|
}
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let changed: Option<i64> = if on {
|
||||||
|
sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id")
|
||||||
|
} else {
|
||||||
|
sqlx::query_scalar(
|
||||||
|
"UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if changed.is_some() {
|
||||||
|
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,571 @@
|
|||||||
|
//! Threads: reading one, starting one, replying, read marks, following, and
|
||||||
|
//! the moderators' lock, pin, removal and the admin's restore.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::home::viewer_json;
|
||||||
|
use super::moderation::{self, Action};
|
||||||
|
use super::{Body, IdPath, St, authors, has_purchase, may_read, rfc3339};
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::auth::{Member, Viewer};
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
use crate::rank::{self, COLLAPSE_SCORE};
|
||||||
|
use crate::text;
|
||||||
|
|
||||||
|
/// The positive reactions; each is +1, the ⌄ (`down`) is -1.
|
||||||
|
pub const REACTIONS: [&str; 4] = ["with_you", "thanks", "me_too", "insight"];
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||||
|
pub struct ThreadRow {
|
||||||
|
pub id: i64,
|
||||||
|
pub topic_slug: String,
|
||||||
|
pub topic_name: String,
|
||||||
|
pub visibility: String,
|
||||||
|
pub listening: bool,
|
||||||
|
pub author_id: Option<Uuid>,
|
||||||
|
pub title: String,
|
||||||
|
pub intent: Option<String>,
|
||||||
|
pub created_at: OffsetDateTime,
|
||||||
|
pub locked: bool,
|
||||||
|
pub pinned: bool,
|
||||||
|
pub deleted_at: Option<OffsetDateTime>,
|
||||||
|
pub delete_reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const THREAD_SELECT: &str = "SELECT th.id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
|
||||||
|
tp.listening, th.author_id, th.title, th.intent, th.created_at, th.locked, th.pinned, th.deleted_at, \
|
||||||
|
th.delete_reason \
|
||||||
|
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id";
|
||||||
|
|
||||||
|
/// A thread the viewer may read (deleted ones too): 404 when it does not
|
||||||
|
/// exist or sits in a hidden topic, 401 in a members-only topic for a visitor.
|
||||||
|
pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||||
|
let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1"))
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?
|
||||||
|
.ok_or(ApiError::NotFound("thread"))?;
|
||||||
|
if !may_read(viewer, &thread.visibility) {
|
||||||
|
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
|
||||||
|
}
|
||||||
|
Ok(thread)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A thread that can take new posts and reactions: not removed, and not
|
||||||
|
/// locked (moderators may still write in a locked one).
|
||||||
|
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||||
|
let thread = readable_thread(db, viewer, id).await?;
|
||||||
|
if thread.deleted_at.is_some() {
|
||||||
|
return Err(ApiError::NotFound("thread"));
|
||||||
|
}
|
||||||
|
if thread.locked && !viewer.is_moderator() {
|
||||||
|
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into()));
|
||||||
|
}
|
||||||
|
Ok(thread)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||||
|
pub struct PostRow {
|
||||||
|
pub id: i64,
|
||||||
|
pub thread_id: i64,
|
||||||
|
pub parent_id: Option<i64>,
|
||||||
|
pub is_opening: bool,
|
||||||
|
pub author_id: Option<Uuid>,
|
||||||
|
pub body: String,
|
||||||
|
pub created_at: OffsetDateTime,
|
||||||
|
pub edited_at: Option<OffsetDateTime>,
|
||||||
|
pub helped_at: Option<OffsetDateTime>,
|
||||||
|
pub deleted_at: Option<OffsetDateTime>,
|
||||||
|
pub deleted_by: Option<Uuid>,
|
||||||
|
pub delete_reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
|
||||||
|
delete_reason";
|
||||||
|
|
||||||
|
/// Posts as the thread page shows them: authors, reactions, the viewer's own
|
||||||
|
/// reaction. A removed post keeps its place with the reason; only
|
||||||
|
/// moderators still see its text.
|
||||||
|
pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult<Vec<Value>> {
|
||||||
|
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
|
||||||
|
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
|
||||||
|
let counts: Vec<(i64, String, i64)> =
|
||||||
|
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||||
|
.bind(&ids)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut by_post: HashMap<i64, HashMap<String, i64>> = HashMap::new();
|
||||||
|
for (post, kind, n) in counts {
|
||||||
|
by_post.entry(post).or_default().insert(kind, n);
|
||||||
|
}
|
||||||
|
let mine: HashMap<i64, String> = match viewer.user_id() {
|
||||||
|
Some(me) => {
|
||||||
|
sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2")
|
||||||
|
.bind(&ids)
|
||||||
|
.bind(me)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
None => HashMap::new(),
|
||||||
|
};
|
||||||
|
let moderator = viewer.is_moderator();
|
||||||
|
Ok(posts
|
||||||
|
.iter()
|
||||||
|
.map(|p| {
|
||||||
|
let counts = by_post.remove(&p.id).unwrap_or_default();
|
||||||
|
let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum();
|
||||||
|
let down = counts.get("down").copied().unwrap_or(0);
|
||||||
|
let score = positive - down;
|
||||||
|
let deleted = p.deleted_at.map(|_| {
|
||||||
|
json!({
|
||||||
|
"by_moderator": p.deleted_by.is_some() && p.deleted_by != p.author_id,
|
||||||
|
"reason": p.delete_reason,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let mut post = json!({
|
||||||
|
"id": p.id,
|
||||||
|
"parent_id": p.parent_id,
|
||||||
|
"is_opening": p.is_opening,
|
||||||
|
"author": p.author_id.and_then(|id| people.get(&id).cloned()),
|
||||||
|
"own": p.author_id.is_some() && p.author_id == viewer.user_id(),
|
||||||
|
"body": if p.deleted_at.is_none() || moderator { Some(&p.body) } else { None },
|
||||||
|
"deleted": deleted,
|
||||||
|
"created_at": rfc3339(p.created_at),
|
||||||
|
"edited_at": p.edited_at.map(rfc3339),
|
||||||
|
"helped": p.helped_at.is_some(),
|
||||||
|
"reactions": REACTIONS.iter().map(|k| (k.to_string(), json!(counts.get(*k).copied().unwrap_or(0))))
|
||||||
|
.collect::<serde_json::Map<_, _>>(),
|
||||||
|
"score": score,
|
||||||
|
"collapsed": score <= COLLAPSE_SCORE,
|
||||||
|
"mine": mine.get(&p.id),
|
||||||
|
});
|
||||||
|
if moderator {
|
||||||
|
post["down"] = json!(down);
|
||||||
|
}
|
||||||
|
post
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A thread with all its posts, oldest first.
|
||||||
|
pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||||
|
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||||
|
let people = authors(&state.db, thread.author_id).await?;
|
||||||
|
let moderator = viewer.is_moderator();
|
||||||
|
let mut out = json!({
|
||||||
|
"viewer": viewer_json(&viewer),
|
||||||
|
"thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())),
|
||||||
|
});
|
||||||
|
if thread.deleted_at.is_some() && !moderator {
|
||||||
|
out["posts"] = json!([]);
|
||||||
|
return Ok(Json(out));
|
||||||
|
}
|
||||||
|
let posts: Vec<PostRow> =
|
||||||
|
sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id"))
|
||||||
|
.bind(id)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?);
|
||||||
|
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let (following, last_read) = match viewer.user_id() {
|
||||||
|
Some(me) => {
|
||||||
|
let following: bool =
|
||||||
|
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)")
|
||||||
|
.bind(me)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
let last_read: Option<i64> =
|
||||||
|
sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2")
|
||||||
|
.bind(me)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
(following, last_read)
|
||||||
|
}
|
||||||
|
None => (false, None),
|
||||||
|
};
|
||||||
|
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
|
||||||
|
let open = thread.deleted_at.is_none() && (!thread.locked || moderator);
|
||||||
|
out["access"] = json!({
|
||||||
|
"can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()),
|
||||||
|
"can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()),
|
||||||
|
"is_thread_author": thread.author_id.is_some() && thread.author_id == viewer.user_id(),
|
||||||
|
"following": following,
|
||||||
|
"last_read_post_id": last_read,
|
||||||
|
});
|
||||||
|
Ok(Json(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
|
||||||
|
json!({
|
||||||
|
"id": thread.id,
|
||||||
|
"slug": text::slug(&thread.title),
|
||||||
|
"title": thread.title,
|
||||||
|
"intent": thread.intent,
|
||||||
|
"topic": {
|
||||||
|
"slug": thread.topic_slug, "name": thread.topic_name,
|
||||||
|
"visibility": thread.visibility, "listening": thread.listening,
|
||||||
|
},
|
||||||
|
"author": author,
|
||||||
|
"created_at": rfc3339(thread.created_at),
|
||||||
|
"locked": thread.locked,
|
||||||
|
"pinned": thread.pinned,
|
||||||
|
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Too fast, or past a newcomer's daily limit (lifted by a purchase and for moderators).
|
||||||
|
async fn check_limits(state: &AppState, viewer: &Viewer, member: &Member, new_thread: bool) -> ApiResult<()> {
|
||||||
|
let db = &state.db;
|
||||||
|
let recent: bool = sqlx::query_scalar(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM forum.posts \
|
||||||
|
WHERE author_id = $1 AND created_at > now() - make_interval(secs => $2))",
|
||||||
|
)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(f64::from(state.flood_secs))
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
if recent {
|
||||||
|
return Err(ApiError::Limited("Várj pár másodpercet a következő hozzászólással.".into()));
|
||||||
|
}
|
||||||
|
if viewer.is_moderator() || !member.rank(OffsetDateTime::now_utc()).is_newcomer() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let (threads, posts): (i64, i64) = sqlx::query_as(
|
||||||
|
"SELECT count(*) FILTER (WHERE is_opening), count(*) FROM forum.posts \
|
||||||
|
WHERE author_id = $1 AND created_at > now() - interval '24 hours'",
|
||||||
|
)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
let over =
|
||||||
|
if new_thread { threads >= rank::NEWCOMER_THREADS_PER_DAY } else { posts >= rank::NEWCOMER_POSTS_PER_DAY };
|
||||||
|
if over && !has_purchase(db, member.user_id).await? {
|
||||||
|
return Err(ApiError::Limited(if new_thread {
|
||||||
|
format!(
|
||||||
|
"Új tagként naponta legfeljebb {} szálat nyithatsz. Holnap újra lehet.",
|
||||||
|
rank::NEWCOMER_THREADS_PER_DAY
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"Új tagként naponta legfeljebb {} hozzászólást írhatsz. Holnap újra lehet.",
|
||||||
|
rank::NEWCOMER_POSTS_PER_DAY
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CreateThread {
|
||||||
|
topic: String,
|
||||||
|
title: String,
|
||||||
|
body: String,
|
||||||
|
#[serde(default)]
|
||||||
|
intent: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a thread with its opening post; the author follows it.
|
||||||
|
pub async fn create(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Json(req), _): Body<CreateThread>,
|
||||||
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||||
|
let member = viewer.require_writer()?;
|
||||||
|
let topic: Option<(i16, String, bool)> =
|
||||||
|
sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1")
|
||||||
|
.bind(&req.topic)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
|
||||||
|
if !may_read(&viewer, &visibility) {
|
||||||
|
return Err(ApiError::bad("Ismeretlen téma."));
|
||||||
|
}
|
||||||
|
let title = text::title(&req.title)?;
|
||||||
|
let body = text::body(&req.body)?;
|
||||||
|
let intent = match req.intent.as_deref() {
|
||||||
|
Some(i @ ("listen" | "advice")) => Some(i.to_string()),
|
||||||
|
None | Some("") => listening.then(|| "listen".to_string()),
|
||||||
|
Some(_) => return Err(ApiError::bad("Ismeretlen szándék.")),
|
||||||
|
};
|
||||||
|
check_limits(&state, &viewer, member, true).await?;
|
||||||
|
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let thread_id: i64 = sqlx::query_scalar(
|
||||||
|
"INSERT INTO forum.threads (topic_id, author_id, title, intent) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||||
|
)
|
||||||
|
.bind(topic_id)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(&title)
|
||||||
|
.bind(&intent)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let post_id: i64 = sqlx::query_scalar(
|
||||||
|
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, $3) RETURNING id",
|
||||||
|
)
|
||||||
|
.bind(thread_id)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(&body)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
||||||
|
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a post: the author's count, following the thread, and the read mark
|
||||||
|
/// up to their own post.
|
||||||
|
async fn after_post(
|
||||||
|
tx: &mut sqlx::PgConnection,
|
||||||
|
author: Uuid,
|
||||||
|
thread_id: i64,
|
||||||
|
post_id: i64,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("UPDATE forum.members SET post_count = post_count + 1 WHERE user_id = $1")
|
||||||
|
.bind(author)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||||
|
.bind(author)
|
||||||
|
.bind(thread_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
upsert_read(&mut *tx, author, thread_id, post_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upsert_read(
|
||||||
|
db: impl sqlx::PgExecutor<'_>,
|
||||||
|
user: Uuid,
|
||||||
|
thread_id: i64,
|
||||||
|
post_id: i64,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3) \
|
||||||
|
ON CONFLICT (user_id, thread_id) DO UPDATE \
|
||||||
|
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
|
||||||
|
)
|
||||||
|
.bind(user)
|
||||||
|
.bind(thread_id)
|
||||||
|
.bind(post_id)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct Reply {
|
||||||
|
body: String,
|
||||||
|
/// The post answered; a reply to a reply goes under the same first-level
|
||||||
|
/// post (two levels at most), a reply to the opening post is first-level.
|
||||||
|
#[serde(default)]
|
||||||
|
parent_id: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reply(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<Reply>,
|
||||||
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||||
|
let member = viewer.require_writer()?;
|
||||||
|
open_thread(&state.db, &viewer, id).await?;
|
||||||
|
let body = text::body(&req.body)?;
|
||||||
|
let parent = match req.parent_id {
|
||||||
|
None => None,
|
||||||
|
Some(parent_id) => {
|
||||||
|
let parent: Option<(Option<i64>, bool, bool)> = sqlx::query_as(
|
||||||
|
"SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2",
|
||||||
|
)
|
||||||
|
.bind(parent_id)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?;
|
||||||
|
if deleted {
|
||||||
|
return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni."));
|
||||||
|
}
|
||||||
|
if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
check_limits(&state, &viewer, member, false).await?;
|
||||||
|
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let post: PostRow = sqlx::query_as(&format!(
|
||||||
|
"INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, $4) RETURNING {POST_COLUMNS}"
|
||||||
|
))
|
||||||
|
.bind(id)
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(parent)
|
||||||
|
.bind(&body)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("UPDATE forum.threads SET last_post_at = now(), reply_count = reply_count + 1 WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
|
||||||
|
Ok((StatusCode::CREATED, Json(post)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ReadMark {
|
||||||
|
post_id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read up to that post (never backwards).
|
||||||
|
pub async fn mark_read(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<ReadMark>,
|
||||||
|
) -> ApiResult<StatusCode> {
|
||||||
|
let member = viewer.require_member()?;
|
||||||
|
readable_thread(&state.db, &viewer, id).await?;
|
||||||
|
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) };
|
||||||
|
upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||||
|
let member = viewer.require_member()?;
|
||||||
|
readable_thread(&state.db, &viewer, id).await?;
|
||||||
|
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||||
|
let member = viewer.require_member()?;
|
||||||
|
sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2")
|
||||||
|
.bind(member.user_id)
|
||||||
|
.bind(id)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ThreadChange {
|
||||||
|
#[serde(default)]
|
||||||
|
locked: Option<bool>,
|
||||||
|
#[serde(default)]
|
||||||
|
pinned: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moderators lock (no more replies) or pin (first in its topic) a thread.
|
||||||
|
pub async fn update(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<ThreadChange>,
|
||||||
|
) -> ApiResult<StatusCode> {
|
||||||
|
let moderator = viewer.require_moderator()?;
|
||||||
|
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
if let Some(locked) = req.locked.filter(|l| *l != thread.locked) {
|
||||||
|
sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.bind(locked)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let action = if locked { Action::Lock } else { Action::Unlock };
|
||||||
|
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||||
|
}
|
||||||
|
if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) {
|
||||||
|
sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.bind(pinned)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let action = if pinned { Action::Pin } else { Action::Unpin };
|
||||||
|
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct Reason {
|
||||||
|
#[serde(default)]
|
||||||
|
pub reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A moderator removes a whole thread; its place keeps the reason.
|
||||||
|
pub async fn remove(
|
||||||
|
State(state): St,
|
||||||
|
viewer: Viewer,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
WithRejection(Json(req), _): Body<Reason>,
|
||||||
|
) -> ApiResult<StatusCode> {
|
||||||
|
let moderator = viewer.require_moderator()?;
|
||||||
|
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||||
|
if thread.deleted_at.is_some() {
|
||||||
|
return Ok(StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.bind(moderator.id)
|
||||||
|
.bind(&reason)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
moderation::record(
|
||||||
|
&mut *tx,
|
||||||
|
moderator.id,
|
||||||
|
Action::DeleteThread,
|
||||||
|
thread.author_id,
|
||||||
|
Some(id),
|
||||||
|
None,
|
||||||
|
Some(&reason),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
tracing::info!(thread = id, moderator = %moderator.id, "thread removed");
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The admin undoes a thread's removal.
|
||||||
|
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||||
|
let admin = viewer.require_user()?;
|
||||||
|
if !viewer.is_admin() {
|
||||||
|
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||||
|
}
|
||||||
|
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||||
|
if thread.deleted_at.is_none() {
|
||||||
|
return Ok(StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
@@ -0,0 +1,521 @@
|
|||||||
|
//! End-to-end tests against a real PostgreSQL database.
|
||||||
|
//!
|
||||||
|
//! `DATABASE_URL` must point to a server where the user may create databases
|
||||||
|
//! (e.g. the `postgres` service of docker-compose); every test gets a fresh,
|
||||||
|
//! migrated database. Users and sessions are made directly in the database,
|
||||||
|
//! as the backend would.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::http::{Request, StatusCode};
|
||||||
|
use http_body_util::BodyExt;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use tower::ServiceExt;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::{AppState, routes};
|
||||||
|
|
||||||
|
struct TestApp {
|
||||||
|
router: Router,
|
||||||
|
pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct User {
|
||||||
|
id: Uuid,
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestApp {
|
||||||
|
fn new(pool: PgPool) -> Self {
|
||||||
|
let state = AppState { db: pool.clone(), flood_secs: 0 };
|
||||||
|
Self { router: routes::router(Arc::new(state)), pool }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A user with a session, as after a login in the backend.
|
||||||
|
async fn user(&self, email: &str, roles: &[&str]) -> User {
|
||||||
|
let id = Uuid::now_v7();
|
||||||
|
sqlx::query("INSERT INTO users (id, email, display_name, roles) VALUES ($1, $2, 'Valódi Név', $3)")
|
||||||
|
.bind(id)
|
||||||
|
.bind(email)
|
||||||
|
.bind(roles.iter().map(|r| r.to_string()).collect::<Vec<_>>())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let token = db::new_token();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES ($1, $2, $3, now() + interval '1 day')",
|
||||||
|
)
|
||||||
|
.bind(Uuid::now_v7())
|
||||||
|
.bind(id)
|
||||||
|
.bind(db::token_hash(&token))
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
User { id, token }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A user who already chose a nickname.
|
||||||
|
async fn member(&self, email: &str, nickname: &str, roles: &[&str]) -> User {
|
||||||
|
let user = self.user(email, roles).await;
|
||||||
|
let (status, body) = self.call("PUT", "/v1/forum/me", Some(&user), json!({ "nickname": nickname })).await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
user
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes a member older and gives them points (rank Kereső and up).
|
||||||
|
async fn season(&self, user: &User, days: i32, points: i32) {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE forum.members SET created_at = now() - make_interval(days => $2), points = $3, \
|
||||||
|
nickname_changed_at = now() - make_interval(days => $2) WHERE user_id = $1",
|
||||||
|
)
|
||||||
|
.bind(user.id)
|
||||||
|
.bind(days)
|
||||||
|
.bind(points)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn points(&self, user: &User) -> i32 {
|
||||||
|
sqlx::query_scalar("SELECT points FROM forum.members WHERE user_id = $1")
|
||||||
|
.bind(user.id)
|
||||||
|
.fetch_one(&self.pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(&self, method: &str, uri: &str, user: Option<&User>, body: Value) -> (StatusCode, Value) {
|
||||||
|
let mut req = Request::builder().method(method).uri(uri);
|
||||||
|
if let Some(u) = user {
|
||||||
|
req = req.header("authorization", format!("Bearer {}", u.token));
|
||||||
|
}
|
||||||
|
let req = if body.is_null() {
|
||||||
|
req.body(Body::empty()).unwrap()
|
||||||
|
} else {
|
||||||
|
req.header("content-type", "application/json").body(Body::from(body.to_string())).unwrap()
|
||||||
|
};
|
||||||
|
let resp = self.router.clone().oneshot(req).await.unwrap();
|
||||||
|
let status = resp.status();
|
||||||
|
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||||
|
let value = if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap() };
|
||||||
|
(status, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get(&self, uri: &str, user: Option<&User>) -> Value {
|
||||||
|
let (status, body) = self.call("GET", uri, user, Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "GET {uri}: {body}");
|
||||||
|
body
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a thread; returns its id.
|
||||||
|
async fn thread(&self, user: &User, topic: &str, title: &str) -> i64 {
|
||||||
|
let (status, body) = self
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/v1/forum/threads",
|
||||||
|
Some(user),
|
||||||
|
json!({ "topic": topic, "title": title, "body": "Az első gondolat." }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED, "{body}");
|
||||||
|
body["id"].as_i64().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replies; returns the new post.
|
||||||
|
async fn reply(&self, user: &User, thread: i64, body: &str, parent: Option<i64>) -> Value {
|
||||||
|
let (status, post) = self
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
&format!("/v1/forum/threads/{thread}/posts"),
|
||||||
|
Some(user),
|
||||||
|
json!({ "body": body, "parent_id": parent }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED, "{post}");
|
||||||
|
post
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn a_nickname_comes_first_and_stays_unique(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let visitor_try = app
|
||||||
|
.call("POST", "/v1/forum/threads", None, json!({ "topic": "torzsasztal", "title": "Szia", "body": "x" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(visitor_try.0, StatusCode::UNAUTHORIZED);
|
||||||
|
|
||||||
|
let anna = app.user("anna@example.com", &["user"]).await;
|
||||||
|
let (status, body) = app
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/v1/forum/threads",
|
||||||
|
Some(&anna),
|
||||||
|
json!({ "topic": "torzsasztal", "title": "Szia mindenki", "body": "x" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("nickname_required")));
|
||||||
|
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
||||||
|
assert!(me["member"].is_null());
|
||||||
|
assert_eq!(me["viewer"]["needs_nickname"], true);
|
||||||
|
|
||||||
|
// The real name is never offered or shown.
|
||||||
|
let (status, me) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": " Hold fény " })).await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{me}");
|
||||||
|
assert_eq!(me["member"]["nickname"], "Hold fény");
|
||||||
|
assert_eq!(me["member"]["rank"], "vandor");
|
||||||
|
assert!(!me.to_string().contains("Valódi"));
|
||||||
|
|
||||||
|
// Folded the same: taken.
|
||||||
|
let bea = app.user("bea@example.com", &["user"]).await;
|
||||||
|
let check = app.get("/v1/forum/nickname-check?name=holdfeny", Some(&bea)).await;
|
||||||
|
assert_eq!(check["ok"], false);
|
||||||
|
let (status, body) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Ho1dfény" })).await;
|
||||||
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_taken")));
|
||||||
|
assert_eq!(app.get("/v1/forum/nickname-check?name=Napraforgó", Some(&bea)).await["ok"], true);
|
||||||
|
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Napraforgó" })).await;
|
||||||
|
|
||||||
|
// A spelling fix any time; a new name once in 30 days.
|
||||||
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Holdfény" })).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let (status, body) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await;
|
||||||
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_too_soon")));
|
||||||
|
app.season(&anna, 31, 0).await;
|
||||||
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
// The old name stays reserved for others…
|
||||||
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Holdfény" })).await;
|
||||||
|
assert_eq!(status, StatusCode::CONFLICT);
|
||||||
|
// …and the profile is found by the new one, in any spelling.
|
||||||
|
let profile = app.get("/v1/forum/members/csillagpor", None).await;
|
||||||
|
assert_eq!(profile["member"]["author"]["nickname"], "Csillagpor");
|
||||||
|
|
||||||
|
let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Admin Bea" })).await;
|
||||||
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||||
|
let (status, _) =
|
||||||
|
app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Bea", "avatar": "hold-piros" })).await;
|
||||||
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn threads_replies_and_what_is_new(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||||
|
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||||
|
|
||||||
|
// A listening topic: members only, threads ask for listening by default.
|
||||||
|
let heart = app.thread(&anna, "ami-a-szivemen-van", "Nem tudom elengedni anyukám házát").await;
|
||||||
|
let (status, _) = app.call("GET", &format!("/v1/forum/threads/{heart}"), None, Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::UNAUTHORIZED, "visitors may not read a members-only topic");
|
||||||
|
let (status, _) = app.call("GET", "/v1/forum/topics/ami-a-szivemen-van", None, Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||||
|
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&bea)).await;
|
||||||
|
assert_eq!(shown["thread"]["intent"], "listen");
|
||||||
|
assert_eq!(shown["thread"]["slug"], "nem-tudom-elengedni-anyukam-hazat");
|
||||||
|
assert_eq!(shown["access"]["can_downvote"], false);
|
||||||
|
|
||||||
|
// A visitor sees the public topics and that the members-only one exists.
|
||||||
|
let public = app.thread(&anna, "torzsasztal", "Téli levesek").await;
|
||||||
|
let home = app.get("/v1/forum/home", None).await;
|
||||||
|
let topics = home["topics"].as_array().unwrap();
|
||||||
|
assert_eq!(topics[0]["readable"], false);
|
||||||
|
assert!(topics[0].get("thread_count").is_none());
|
||||||
|
assert_eq!(topics[3]["thread_count"], 1);
|
||||||
|
let waiting: Vec<i64> = home["unanswered"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect();
|
||||||
|
assert_eq!(waiting, vec![public], "the visitor sees only the public thread waiting");
|
||||||
|
|
||||||
|
// Bea sees both waiting and both as new; Anna does not see her own.
|
||||||
|
let home = app.get("/v1/forum/home", Some(&bea)).await;
|
||||||
|
assert_eq!(home["unanswered"].as_array().unwrap().len(), 2);
|
||||||
|
assert_eq!(home["topics"][0]["new_count"], 1);
|
||||||
|
assert!(app.get("/v1/forum/home", Some(&anna)).await["unanswered"].as_array().unwrap().is_empty());
|
||||||
|
|
||||||
|
// Replies: a reply to a reply stays on the second level.
|
||||||
|
let first = app.reply(&bea, heart, "Nem vagy egyedül :)", None).await;
|
||||||
|
assert_eq!(first["body"], "Nem vagy egyedül 🙂");
|
||||||
|
assert_eq!(first["author"]["nickname"], "Holdfény");
|
||||||
|
let second = app.reply(&anna, heart, "Köszönöm.", first["id"].as_i64()).await;
|
||||||
|
let third = app.reply(&bea, heart, "Szívesen.", second["id"].as_i64()).await;
|
||||||
|
assert_eq!(third["parent_id"], first["id"]);
|
||||||
|
|
||||||
|
// Anna follows her thread: one new reply from Bea since she last read.
|
||||||
|
let home = app.get("/v1/forum/home", Some(&anna)).await;
|
||||||
|
assert_eq!(home["followed"]["new_replies"], 1);
|
||||||
|
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await;
|
||||||
|
assert_eq!(shown["posts"].as_array().unwrap().len(), 4);
|
||||||
|
assert_eq!(shown["access"]["last_read_post_id"], second["id"]);
|
||||||
|
let (status, _) = app
|
||||||
|
.call("POST", &format!("/v1/forum/threads/{heart}/read"), Some(&anna), json!({ "post_id": third["id"] }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
assert_eq!(app.get("/v1/forum/home", Some(&anna)).await["followed"]["new_replies"], 0);
|
||||||
|
let followed = app.get("/v1/forum/followed", Some(&anna)).await;
|
||||||
|
assert_eq!(followed["threads"].as_array().unwrap().len(), 2);
|
||||||
|
assert_eq!(followed["threads"][0]["reply_count"], 3);
|
||||||
|
|
||||||
|
// Busy today: three replies make it "pörgős".
|
||||||
|
assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["hot"][0]["id"], heart);
|
||||||
|
|
||||||
|
// Editing one's own post only.
|
||||||
|
let (status, _) =
|
||||||
|
app.call("PATCH", &format!("/v1/forum/posts/{}", first["id"]), Some(&anna), json!({ "body": "Átírva" })).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let (status, edited) = app
|
||||||
|
.call("PATCH", &format!("/v1/forum/posts/{}", first["id"]), Some(&bea), json!({ "body": "Nem vagy egyedül." }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert!(edited["edited_at"].is_string());
|
||||||
|
|
||||||
|
// Taking back one's own post: its place stays, the text goes.
|
||||||
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{}", third["id"]), Some(&bea), json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await;
|
||||||
|
let gone = shown["posts"].as_array().unwrap().iter().find(|p| p["id"] == third["id"]).unwrap().clone();
|
||||||
|
assert!(gone["body"].is_null());
|
||||||
|
assert_eq!(gone["deleted"]["by_moderator"], false);
|
||||||
|
assert_eq!(app.get("/v1/forum/followed", Some(&anna)).await["threads"][0]["reply_count"], 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn reactions_give_points_and_ranks(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||||
|
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||||
|
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
|
||||||
|
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
|
||||||
|
let post = app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
|
||||||
|
let post_id = post["id"].as_i64().unwrap();
|
||||||
|
let react = |user: &User, kind: &str| {
|
||||||
|
let uri = format!("/v1/forum/posts/{post_id}/reaction");
|
||||||
|
let body = json!({ "kind": kind });
|
||||||
|
let user = User { id: user.id, token: user.token.clone() };
|
||||||
|
let app = &app;
|
||||||
|
async move { app.call("PUT", &uri, Some(&user), body).await }
|
||||||
|
};
|
||||||
|
|
||||||
|
// A newcomer's reaction shows but gives no points; no ⌄ for newcomers.
|
||||||
|
let (status, shown) = react(&cili, "with_you").await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{shown}");
|
||||||
|
assert_eq!(shown["reactions"]["with_you"], 1);
|
||||||
|
assert_eq!(app.points(&bea).await, 0);
|
||||||
|
assert_eq!(react(&cili, "down").await.0, StatusCode::FORBIDDEN);
|
||||||
|
assert_eq!(react(&bea, "thanks").await.0, StatusCode::FORBIDDEN, "not on one's own post");
|
||||||
|
assert_eq!(react(&cili, "hug").await.0, StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
// A seasoned member's reaction counts; changing it to ⌄ swings by two.
|
||||||
|
app.season(&anna, 10, 5).await;
|
||||||
|
let (_, shown) = react(&anna, "insight").await;
|
||||||
|
assert_eq!(shown["mine"], "insight");
|
||||||
|
assert_eq!(app.points(&bea).await, 1);
|
||||||
|
let (_, shown) = react(&anna, "down").await;
|
||||||
|
assert_eq!(app.points(&bea).await, -1);
|
||||||
|
assert!(shown.get("down").is_none(), "only moderators see the ⌄ count");
|
||||||
|
assert_eq!(shown["score"], 0);
|
||||||
|
let (status, _) =
|
||||||
|
app.call("DELETE", &format!("/v1/forum/posts/{post_id}/reaction"), Some(&anna), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(app.points(&bea).await, 0);
|
||||||
|
|
||||||
|
// "Ez segített": only the thread's author, worth five.
|
||||||
|
let (status, _) = app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&cili), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let (status, shown) = app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&anna), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(shown["helped"], true);
|
||||||
|
app.call("PUT", &format!("/v1/forum/posts/{post_id}/helped"), Some(&anna), Value::Null).await;
|
||||||
|
assert_eq!(app.points(&bea).await, 5, "marking twice counts once");
|
||||||
|
|
||||||
|
// Points alone do not make a rank: time does too.
|
||||||
|
let me = app.get("/v1/forum/me", Some(&bea)).await;
|
||||||
|
assert_eq!(me["member"]["rank"], "vandor");
|
||||||
|
assert_eq!(me["member"]["next_rank"]["name"], "Kereső");
|
||||||
|
app.season(&bea, 3, 5).await;
|
||||||
|
assert_eq!(app.get("/v1/forum/me", Some(&bea)).await["member"]["rank"], "kereso");
|
||||||
|
|
||||||
|
// No ⌄ in a listening topic, whatever the rank.
|
||||||
|
let heart = app.thread(&cili, "ami-a-szivemen-van", "Nehéz napok").await;
|
||||||
|
let opening = app.get(&format!("/v1/forum/threads/{heart}"), Some(&anna)).await["posts"][0]["id"].as_i64().unwrap();
|
||||||
|
let (status, _) =
|
||||||
|
app.call("PUT", &format!("/v1/forum/posts/{opening}/reaction"), Some(&anna), json!({ "kind": "down" })).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn moderators_remove_and_ban(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||||
|
let spam = app.member("spam@example.com", "Gyógyító", &["user"]).await;
|
||||||
|
let moderator = app.member("mod@example.com", "Őrangyal", &["user", "moderator"]).await;
|
||||||
|
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
|
||||||
|
let thread = app.thread(&anna, "belso-utak", "Energiák").await;
|
||||||
|
let ad = app.reply(&spam, thread, "Energetikai gyógyítás, írj privátban!", None).await;
|
||||||
|
let ad_id = ad["id"].as_i64().unwrap();
|
||||||
|
|
||||||
|
// Members may not remove others' posts; a moderator needs a reason.
|
||||||
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{ad_id}"), Some(&anna), json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{ad_id}"), Some(&moderator), json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||||
|
let (status, _) = app
|
||||||
|
.call(
|
||||||
|
"DELETE",
|
||||||
|
&format!("/v1/forum/posts/{ad_id}"),
|
||||||
|
Some(&moderator),
|
||||||
|
json!({ "reason": "szolgáltatás hirdetése" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
||||||
|
assert!(seen["posts"][1]["body"].is_null());
|
||||||
|
assert_eq!(seen["posts"][1]["deleted"]["reason"], "szolgáltatás hirdetése");
|
||||||
|
assert_eq!(seen["posts"][1]["deleted"]["by_moderator"], true);
|
||||||
|
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&moderator)).await;
|
||||||
|
assert!(seen["posts"][1]["body"].is_string(), "moderators still see the text");
|
||||||
|
|
||||||
|
// Only the admin restores.
|
||||||
|
let (status, _) =
|
||||||
|
app.call("POST", &format!("/v1/forum/posts/{ad_id}/restore"), Some(&moderator), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let (status, _) = app.call("POST", &format!("/v1/forum/posts/{ad_id}/restore"), Some(&admin), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
|
||||||
|
// A ban: reading yes, writing no; moderators cannot be banned.
|
||||||
|
let (status, body) = app
|
||||||
|
.call("POST", "/v1/forum/members/gyogyito/ban", Some(&moderator), json!({ "hours": 48, "reason": "hirdetés" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
let (status, body) = app
|
||||||
|
.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&spam), json!({ "body": "Még egyszer" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("banned")));
|
||||||
|
app.get(&format!("/v1/forum/threads/{thread}"), Some(&spam)).await;
|
||||||
|
assert!(app.get("/v1/forum/me", Some(&spam)).await["member"]["banned_until"].is_string());
|
||||||
|
let (status, _) =
|
||||||
|
app.call("POST", "/v1/forum/members/orangyal/ban", Some(&moderator), json!({ "reason": "teszt" })).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let (status, _) =
|
||||||
|
app.call("POST", "/v1/forum/members/csendesviz/ban", Some(&anna), json!({ "reason": "teszt" })).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
// For good, then lifted.
|
||||||
|
let (_, body) = app
|
||||||
|
.call("POST", "/v1/forum/members/gyogyito/ban", Some(&moderator), json!({ "reason": "ismételt hirdetés" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(body["banned_until"], "infinity");
|
||||||
|
let (status, _) = app.call("DELETE", "/v1/forum/members/gyogyito/ban", Some(&moderator), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
app.reply(&spam, thread, "Bocsánat.", None).await;
|
||||||
|
|
||||||
|
// Lock and remove a thread; others see only the reason.
|
||||||
|
let (status, _) =
|
||||||
|
app.call("PATCH", &format!("/v1/forum/threads/{thread}"), Some(&moderator), json!({ "locked": true })).await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
let (status, _) = app
|
||||||
|
.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&anna), json!({ "body": "Lezárva?" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let (status, _) = app
|
||||||
|
.call("DELETE", &format!("/v1/forum/threads/{thread}"), Some(&moderator), json!({ "reason": "vita elfajult" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
let seen = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
||||||
|
assert_eq!(seen["thread"]["deleted"]["reason"], "vita elfajult");
|
||||||
|
assert!(seen["posts"].as_array().unwrap().is_empty());
|
||||||
|
assert!(app.get("/v1/forum/topics/belso-utak", Some(&anna)).await["threads"].as_array().unwrap().is_empty());
|
||||||
|
|
||||||
|
// Every step is in the log, which only moderators read.
|
||||||
|
let (status, _) = app.call("GET", "/v1/forum/mod/log", Some(&anna), Value::Null).await;
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||||
|
let log = app.get("/v1/forum/mod/log", Some(&moderator)).await;
|
||||||
|
let actions: Vec<&str> = log["entries"].as_array().unwrap().iter().map(|e| e["action"].as_str().unwrap()).collect();
|
||||||
|
assert_eq!(actions, vec!["delete_thread", "lock", "unban", "ban", "ban", "restore_post", "delete_post"]);
|
||||||
|
assert_eq!(log["entries"][6]["actor"], "Őrangyal");
|
||||||
|
assert_eq!(log["entries"][6]["target"], "Gyógyító");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn newcomer_limits_and_a_purchase(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||||
|
for i in 0..3 {
|
||||||
|
app.thread(&anna, "torzsasztal", &format!("Kérdés {i}")).await;
|
||||||
|
}
|
||||||
|
let (status, body) = app
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/v1/forum/threads",
|
||||||
|
Some(&anna),
|
||||||
|
json!({ "topic": "torzsasztal", "title": "Negyedik", "body": "x" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::TOO_MANY_REQUESTS, Some("limited")));
|
||||||
|
// A purchase lifts the newcomer limits (but gives no rank).
|
||||||
|
sqlx::query("INSERT INTO package_orders (id, user_id, package, source, price_huf) VALUES ($1, $2, 'egyeni', 'stripe', 4900)")
|
||||||
|
.bind(Uuid::now_v7())
|
||||||
|
.bind(anna.id)
|
||||||
|
.execute(&app.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
app.thread(&anna, "torzsasztal", "Negyedik").await;
|
||||||
|
assert_eq!(app.get("/v1/forum/me", Some(&anna)).await["member"]["rank"], "vandor");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn profiles_share_signs_never_degrees(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||||
|
let result = json!({
|
||||||
|
"points": [
|
||||||
|
{"id": "sun", "sign": "pisces", "longitude": 345.2},
|
||||||
|
{"id": "moon", "sign": "cancer", "longitude": 101.7},
|
||||||
|
{"id": "venus", "sign": "aries", "longitude": 12.0},
|
||||||
|
{"id": "mean_node", "sign": "leo", "longitude": 130.0}
|
||||||
|
],
|
||||||
|
"angles": {"ascendant": {"sign": "virgo", "longitude": 160.4}},
|
||||||
|
"time": {"time_known": true}
|
||||||
|
});
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
|
||||||
|
VALUES ($1, $2, 'Én', true, 'own', '{}', $3, 'x')",
|
||||||
|
)
|
||||||
|
.bind(Uuid::now_v7())
|
||||||
|
.bind(anna.id)
|
||||||
|
.bind(&result)
|
||||||
|
.execute(&app.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
||||||
|
assert!(profile["member"]["author"]["signs"].is_null(), "nothing shared by default");
|
||||||
|
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
||||||
|
assert_eq!(me["chart"]["big3"], json!({"sun": "pisces", "moon": "cancer", "ascendant": "virgo"}));
|
||||||
|
|
||||||
|
let (status, _) = app
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
"/v1/forum/me",
|
||||||
|
Some(&anna),
|
||||||
|
json!({ "nickname": "Csendesvíz", "chart_share": "planets", "bio": "Szia <3" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
||||||
|
assert_eq!(
|
||||||
|
profile["member"]["author"]["signs"],
|
||||||
|
json!({"sun": "pisces", "moon": "cancer", "venus": "aries", "ascendant": "virgo"})
|
||||||
|
);
|
||||||
|
assert_eq!(profile["member"]["bio"], "Szia 🤍");
|
||||||
|
assert!(!profile.to_string().contains("longitude") && !profile.to_string().contains("345"));
|
||||||
|
let (status, _) = app
|
||||||
|
.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "bio": "www.gyogyitas.hu" }))
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
// Online now, unless invisible.
|
||||||
|
assert_eq!(profile["member"]["author"]["online"], true);
|
||||||
|
app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "invisible": true })).await;
|
||||||
|
let profile = app.get("/v1/forum/members/Csendesvíz", None).await;
|
||||||
|
assert_eq!(profile["member"]["author"]["online"], false);
|
||||||
|
assert!(profile["member"]["last_seen"].is_null());
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
//! Rules for what members type: nicknames, titles, posts, the bio, avatars.
|
||||||
|
|
||||||
|
use crate::error::ApiError;
|
||||||
|
|
||||||
|
pub const NICKNAME_MIN: usize = 3;
|
||||||
|
pub const NICKNAME_MAX: usize = 24;
|
||||||
|
pub const TITLE_MIN: usize = 4;
|
||||||
|
pub const TITLE_MAX: usize = 120;
|
||||||
|
pub const BODY_MAX: usize = 10_000;
|
||||||
|
pub const BIO_MAX: usize = 500;
|
||||||
|
pub const REASON_MIN: usize = 3;
|
||||||
|
pub const REASON_MAX: usize = 300;
|
||||||
|
|
||||||
|
/// The starter avatars: a glyph on a background colour, `<glyph>-<colour>`.
|
||||||
|
/// The frontend draws them (`src/components/forum/Avatar.tsx`).
|
||||||
|
pub const AVATAR_GLYPHS: [&str; 8] = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"];
|
||||||
|
pub const AVATAR_COLOURS: [&str; 6] = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"];
|
||||||
|
|
||||||
|
/// Words a nickname may not contain (compared folded, see [`nickname_key`]).
|
||||||
|
const RESERVED: [&str; 7] = ["admin", "moderator", "sorsfonalak", "rendszer", "ugyfelszolgalat", "torolttag", "forum"];
|
||||||
|
|
||||||
|
const SEPARATORS: [char; 4] = [' ', '-', '_', '.'];
|
||||||
|
|
||||||
|
/// A nickname as it will be shown: trimmed, inner spaces collapsed, checked.
|
||||||
|
/// Letters (accented ones too), digits, and single spaces, `-`, `_` or `.`
|
||||||
|
/// between them; it starts with a letter.
|
||||||
|
pub fn nickname(raw: &str) -> Result<String, ApiError> {
|
||||||
|
let name = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
let len = name.chars().count();
|
||||||
|
if !(NICKNAME_MIN..=NICKNAME_MAX).contains(&len) {
|
||||||
|
return Err(ApiError::bad(format!("Az álnév {NICKNAME_MIN}–{NICKNAME_MAX} karakter legyen.")));
|
||||||
|
}
|
||||||
|
if !name.chars().next().is_some_and(latin_letter) {
|
||||||
|
return Err(ApiError::bad("Az álnév betűvel kezdődjön."));
|
||||||
|
}
|
||||||
|
let mut previous_separator = false;
|
||||||
|
for c in name.chars() {
|
||||||
|
let separator = SEPARATORS.contains(&c);
|
||||||
|
if !(separator || latin_letter(c) || c.is_ascii_digit()) {
|
||||||
|
return Err(ApiError::bad("Az álnévben betűk, számok, szóköz, kötőjel, aláhúzás és pont lehet."));
|
||||||
|
}
|
||||||
|
if separator && previous_separator {
|
||||||
|
return Err(ApiError::bad("Az álnévben ne legyen két elválasztó jel egymás után."));
|
||||||
|
}
|
||||||
|
previous_separator = separator;
|
||||||
|
}
|
||||||
|
if previous_separator {
|
||||||
|
return Err(ApiError::bad("Az álnév ne végződjön elválasztó jellel."));
|
||||||
|
}
|
||||||
|
let key = nickname_key(&name);
|
||||||
|
if RESERVED.iter().any(|word| key.contains(&nickname_key(word))) {
|
||||||
|
return Err(ApiError::bad("Ezt az álnevet nem választhatod."));
|
||||||
|
}
|
||||||
|
Ok(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A letter of the Latin script (accented ones included), so look-alike
|
||||||
|
/// letters of other scripts cannot imitate a nickname.
|
||||||
|
fn latin_letter(c: char) -> bool {
|
||||||
|
c.is_alphabetic()
|
||||||
|
&& matches!(c as u32,
|
||||||
|
0x41..=0x5A | 0x61..=0x7A // ASCII
|
||||||
|
| 0xC0..=0x24F // Latin-1 Supplement, Latin Extended-A and -B
|
||||||
|
| 0x1E00..=0x1EFF) // Latin Extended Additional
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The nickname folded for uniqueness: no accents, case or separators, and
|
||||||
|
/// characters that look alike made the same (`I`, `l`, `1` → `l`; `0` → `o`),
|
||||||
|
/// so "Holdfény", "holdfeny" and "Ho1d-feny" are one name.
|
||||||
|
pub fn nickname_key(name: &str) -> String {
|
||||||
|
deunicode::deunicode(name)
|
||||||
|
.to_lowercase()
|
||||||
|
.chars()
|
||||||
|
.filter(|c| c.is_ascii_alphanumeric())
|
||||||
|
.map(|c| match c {
|
||||||
|
'i' | '1' => 'l',
|
||||||
|
'0' => 'o',
|
||||||
|
other => other,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A thread title: one line, spaces collapsed.
|
||||||
|
pub fn title(raw: &str) -> Result<String, ApiError> {
|
||||||
|
let title: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
let len = title.chars().count();
|
||||||
|
if len < TITLE_MIN {
|
||||||
|
return Err(ApiError::bad(format!("A cím legalább {TITLE_MIN} karakter legyen.")));
|
||||||
|
}
|
||||||
|
if len > TITLE_MAX {
|
||||||
|
return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet.")));
|
||||||
|
}
|
||||||
|
Ok(title)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A post: control characters removed, at most one empty line in a row,
|
||||||
|
/// trailing spaces dropped, the old smileys turned into emoji.
|
||||||
|
pub fn body(raw: &str) -> Result<String, ApiError> {
|
||||||
|
let text = clean_multiline(raw, 2);
|
||||||
|
if text.is_empty() {
|
||||||
|
return Err(ApiError::bad("A hozzászólás nem lehet üres."));
|
||||||
|
}
|
||||||
|
if text.chars().count() > BODY_MAX {
|
||||||
|
return Err(ApiError::bad(format!("A hozzászólás legfeljebb {BODY_MAX} karakter lehet.")));
|
||||||
|
}
|
||||||
|
Ok(smileys(&text))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The profile's short introduction: no links (old-school profile spam).
|
||||||
|
pub fn bio(raw: &str) -> Result<String, ApiError> {
|
||||||
|
let text = clean_multiline(raw, 1);
|
||||||
|
if text.chars().count() > BIO_MAX {
|
||||||
|
return Err(ApiError::bad(format!("A bemutatkozás legfeljebb {BIO_MAX} karakter lehet.")));
|
||||||
|
}
|
||||||
|
let lower = text.to_lowercase();
|
||||||
|
if lower.contains("http") || lower.contains("www.") {
|
||||||
|
return Err(ApiError::bad("A bemutatkozásba nem tehetsz linket."));
|
||||||
|
}
|
||||||
|
Ok(smileys(&text))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A moderator's reason, shown in place of what was removed.
|
||||||
|
pub fn reason(raw: &str) -> Result<String, ApiError> {
|
||||||
|
let text: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
let len = text.chars().count();
|
||||||
|
if !(REASON_MIN..=REASON_MAX).contains(&len) {
|
||||||
|
return Err(ApiError::bad(format!("Az indoklás {REASON_MIN}–{REASON_MAX} karakter legyen.")));
|
||||||
|
}
|
||||||
|
Ok(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn avatar(raw: &str) -> Result<String, ApiError> {
|
||||||
|
let valid = raw
|
||||||
|
.split_once('-')
|
||||||
|
.is_some_and(|(glyph, colour)| AVATAR_GLYPHS.contains(&glyph) && AVATAR_COLOURS.contains(&colour));
|
||||||
|
if valid { Ok(raw.to_string()) } else { Err(ApiError::bad("Ismeretlen avatar.")) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A default avatar for a new member, picked from the nickname.
|
||||||
|
pub fn default_avatar(key: &str) -> String {
|
||||||
|
let n: usize = key.bytes().map(usize::from).sum();
|
||||||
|
format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`.
|
||||||
|
pub fn slug(title: &str) -> String {
|
||||||
|
let ascii = deunicode::deunicode(title).to_lowercase();
|
||||||
|
let mut slug = String::new();
|
||||||
|
for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) {
|
||||||
|
if !slug.is_empty() && slug.len() + 1 + word.len() > 60 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if !slug.is_empty() {
|
||||||
|
slug.push('-');
|
||||||
|
}
|
||||||
|
slug.push_str(word);
|
||||||
|
}
|
||||||
|
slug
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lines with control characters removed and trailing spaces dropped; at most
|
||||||
|
/// `max_breaks` line breaks in a row; trimmed.
|
||||||
|
fn clean_multiline(raw: &str, max_breaks: usize) -> String {
|
||||||
|
let normalized = raw.replace("\r\n", "\n").replace('\r', "\n");
|
||||||
|
let mut out = String::with_capacity(normalized.len());
|
||||||
|
let mut breaks = 0;
|
||||||
|
for line in normalized.split('\n') {
|
||||||
|
let line: String = line.chars().map(|c| if c == '\t' { ' ' } else { c }).filter(|c| !c.is_control()).collect();
|
||||||
|
let line = line.trim_end();
|
||||||
|
if line.trim().is_empty() {
|
||||||
|
breaks += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !out.is_empty() {
|
||||||
|
out.push_str(&"\n".repeat(breaks.clamp(1, max_breaks)));
|
||||||
|
}
|
||||||
|
breaks = 1;
|
||||||
|
out.push_str(line);
|
||||||
|
}
|
||||||
|
out.trim().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `:)`, `:D`, `;)`, `:(`, `:P` and `<3` standing alone become emoji, as on the
|
||||||
|
/// old forums.
|
||||||
|
fn smileys(text: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(text.len());
|
||||||
|
let mut word = String::new();
|
||||||
|
let flush = |word: &mut String, out: &mut String| {
|
||||||
|
let emoji = match word.as_str() {
|
||||||
|
":)" | ":-)" => Some("🙂"),
|
||||||
|
":D" | ":-D" => Some("😄"),
|
||||||
|
";)" | ";-)" => Some("😉"),
|
||||||
|
":(" | ":-(" => Some("🙁"),
|
||||||
|
":P" | ":-P" | ":p" => Some("😛"),
|
||||||
|
"<3" => Some("🤍"),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
out.push_str(emoji.unwrap_or(word));
|
||||||
|
word.clear();
|
||||||
|
};
|
||||||
|
for c in text.chars() {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
flush(&mut word, &mut out);
|
||||||
|
out.push(c);
|
||||||
|
} else {
|
||||||
|
word.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush(&mut word, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nicknames() {
|
||||||
|
assert_eq!(nickname(" Hold fény ").unwrap(), "Hold fény");
|
||||||
|
assert_eq!(nickname("Csendesvíz").unwrap(), "Csendesvíz");
|
||||||
|
assert!(nickname("ab").is_err());
|
||||||
|
assert!(nickname("1abc").is_err());
|
||||||
|
assert!(nickname("abc--def").is_err());
|
||||||
|
assert!(nickname("abc-").is_err());
|
||||||
|
assert!(nickname("Admin Anna").is_err());
|
||||||
|
assert!(nickname("Sorsfona1ak").is_err());
|
||||||
|
assert!(nickname("Мария").is_err(), "Cyrillic look-alikes are refused");
|
||||||
|
assert!(nickname("név😀").is_err());
|
||||||
|
assert_eq!(nickname_key("Holdfény"), nickname_key("ho1d-feny"));
|
||||||
|
assert_eq!(nickname_key("Ilona"), nickname_key("1lona"));
|
||||||
|
assert_eq!(nickname_key("Olga"), nickname_key("0lga"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bodies() {
|
||||||
|
assert_eq!(body(" Szia :)\r\n\r\n\r\n\r\nMi újság? <3 ").unwrap(), "Szia 🙂\n\nMi újság? 🤍");
|
||||||
|
assert_eq!(body("http://x.hu/:)").unwrap(), "http://x.hu/:)", "only smileys standing alone");
|
||||||
|
assert!(body(" \n\t ").is_err());
|
||||||
|
assert_eq!(body("a\u{0007}b").unwrap(), "ab");
|
||||||
|
assert!(bio("Látogass meg: www.pelda.hu").is_err());
|
||||||
|
assert_eq!(bio("Első sor\n\n\nMásodik").unwrap(), "Első sor\nMásodik");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn titles_slugs_avatars() {
|
||||||
|
assert_eq!(title(" Nem tudom elengedni ").unwrap(), "Nem tudom elengedni");
|
||||||
|
assert!(title("abc").is_err());
|
||||||
|
assert_eq!(slug("Nem tudom elengedni anyukám házát!"), "nem-tudom-elengedni-anyukam-hazat");
|
||||||
|
assert!(slug(&"hosszú ".repeat(30)).len() <= 60);
|
||||||
|
assert!(avatar("hold-ejkek").is_ok());
|
||||||
|
assert!(avatar("hold-piros").is_err());
|
||||||
|
assert!(avatar(&default_avatar("csendesvlz")).is_ok());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
|||||||
import type { AdminUser, Package, Role } from "@/lib/types";
|
import type { AdminUser, Package, Role } from "@/lib/types";
|
||||||
|
|
||||||
const PAGE_SIZE = 25;
|
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";
|
type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot";
|
||||||
|
|
||||||
/** `short`: the mark in the list, where the names do not fit (explained under it). */
|
/** `short`: the mark in the list, where the names do not fit (explained under it). */
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
// Forwards /api/v1/* to the backend, so the browser talks to one origin and
|
// Forwards /api/v1/* to the backend (and /api/v1/forum/* to the forum
|
||||||
// the session cookie belongs to the frontend's host (no CORS needed).
|
// 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 { revalidateTag } from "next/cache";
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
import { CELEBRITIES_TAG } from "@/lib/celebrities";
|
import { CELEBRITIES_TAG } from "@/lib/celebrities";
|
||||||
|
import { FORUM_URL } from "@/lib/forumServer";
|
||||||
import { BACKEND_URL } from "@/lib/server";
|
import { BACKEND_URL } from "@/lib/server";
|
||||||
import { SHARES_TAG } from "@/lib/share";
|
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[] }> }) {
|
async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
|
||||||
const { path } = await ctx.params;
|
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();
|
const headers = new Headers();
|
||||||
for (const name of REQUEST_HEADERS) {
|
for (const name of REQUEST_HEADERS) {
|
||||||
|
|||||||
@@ -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<TopicPage>(`/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<Metadata> {
|
||||||
|
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 (
|
||||||
|
<div className="fh">
|
||||||
|
<nav className="forum-crumbs" aria-label="Morzsamenü">
|
||||||
|
<Link href="/forum">Fórum</Link>
|
||||||
|
</nav>
|
||||||
|
<header className="ftopic-head">
|
||||||
|
<div>
|
||||||
|
<h1>{topic.name}</h1>
|
||||||
|
<p className="muted">{topic.description}</p>
|
||||||
|
{topic.listening && (
|
||||||
|
<p className="hint">
|
||||||
|
Meghallgatós téma: itt nincs ⌄, és a szálak alapból meghallgatást kérnek, nem tanácsot.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
href={viewer.logged_in ? `/forum/uj?tema=${topic.slug}` : `/belepes?vissza=/forum/uj?tema=${topic.slug}`}
|
||||||
|
className="btn btn-primary"
|
||||||
|
>
|
||||||
|
Új szál
|
||||||
|
</Link>
|
||||||
|
</header>
|
||||||
|
{threads.length === 0 ? (
|
||||||
|
<p className="fh-card fh-empty">Ebben a témában még nincs szál. Nyisd meg te az elsőt!</p>
|
||||||
|
) : (
|
||||||
|
<div className="fh-card fh-flush">
|
||||||
|
<ThreadList threads={threads} showTopic={false} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{(page > 1 || has_more) && (
|
||||||
|
<nav className="forum-pager" aria-label="Lapozás">
|
||||||
|
{page > 1 ? <Link href={`/forum/${topic.slug}?oldal=${page - 1}`}>‹ Újabbak</Link> : <span />}
|
||||||
|
<span className="hint">{page}. oldal</span>
|
||||||
|
{has_more ? <Link href={`/forum/${topic.slug}?oldal=${page + 1}`}>Régebbiek ›</Link> : <span />}
|
||||||
|
</nav>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<ChartShare>(member?.chart_share ?? "none");
|
||||||
|
const [invisible, setInvisible] = useState(member?.invisible ?? false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(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<ForumMe>("/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 (
|
||||||
|
<form className="fprof" onSubmit={submit}>
|
||||||
|
{member?.banned_until && (
|
||||||
|
<p className="fh-banner fh-banner-warn">
|
||||||
|
Most nem írhatsz a fórumba ({banText(member.banned_until)}).
|
||||||
|
{member.ban_reason && ` Indok: ${member.ban_reason}`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="fprof-nick">Álnév</label>
|
||||||
|
<input
|
||||||
|
id="fprof-nick"
|
||||||
|
className="inp"
|
||||||
|
value={nickname}
|
||||||
|
onChange={(e) => setNickname(e.target.value)}
|
||||||
|
maxLength={24}
|
||||||
|
required
|
||||||
|
autoComplete="off"
|
||||||
|
aria-describedby="fprof-nick-hint"
|
||||||
|
/>
|
||||||
|
<span id="fprof-nick-hint" className={check && !check.ok ? "hint warn" : "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."}
|
||||||
|
</span>
|
||||||
|
{member?.nickname_change_after && (
|
||||||
|
<span className="hint">
|
||||||
|
Ú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).
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset className="fnew-set">
|
||||||
|
<legend>Avatar</legend>
|
||||||
|
<div className="fprof-avatars">
|
||||||
|
{AVATAR_COLOURS.flatMap((colour) =>
|
||||||
|
AVATAR_GLYPHS.map((glyph) => {
|
||||||
|
const value = `${glyph}-${colour}`;
|
||||||
|
return (
|
||||||
|
<label key={value} className="fprof-avatar" title={GLYPH_NAMES[glyph]}>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="avatar"
|
||||||
|
value={value}
|
||||||
|
checked={avatar === value}
|
||||||
|
onChange={() => setAvatar(value)}
|
||||||
|
className="sr-only"
|
||||||
|
/>
|
||||||
|
<Avatar avatar={value} size={44} />
|
||||||
|
<span className="sr-only">{GLYPH_NAMES[glyph]}</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{!avatar && <span className="hint">Ha nem választasz, az álneved alapján kapsz egyet.</span>}
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="fprof-bio">Bemutatkozás</label>
|
||||||
|
<textarea
|
||||||
|
id="fprof-bio"
|
||||||
|
className="fc-text"
|
||||||
|
rows={4}
|
||||||
|
maxLength={500}
|
||||||
|
value={bio}
|
||||||
|
onChange={(e) => setBio(e.target.value)}
|
||||||
|
placeholder="Pár mondat magadról, ha szeretnéd."
|
||||||
|
/>
|
||||||
|
<span className="hint">{bio.length}/500 · link nem tehető bele</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset className="fnew-set">
|
||||||
|
<legend>Mit mutatsz meg a képletedből?</legend>
|
||||||
|
<div className="fnew-intents">
|
||||||
|
{SHARE_LEVELS.map((level) => (
|
||||||
|
<label key={level.value} className="fnew-intent">
|
||||||
|
<input type="radio" name="share" checked={share === level.value} onChange={() => setShare(level.value)} />
|
||||||
|
<span>
|
||||||
|
<strong>{level.label}</strong>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<span className="hint">
|
||||||
|
{me.chart === null
|
||||||
|
? "Még nincs saját képleted, így most semmi nem látszana."
|
||||||
|
: preview
|
||||||
|
? `Így látszik a neved mellett: ${signsText(preview)}`
|
||||||
|
: share === "none"
|
||||||
|
? "Semmi nem látszik a képletedből."
|
||||||
|
: "Ehhez a szinthez nincs adat a képletedben."}{" "}
|
||||||
|
Fokokat soha nem mutatunk, mert azokból kiszámolható a születési időd.
|
||||||
|
</span>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<label className="fprof-check">
|
||||||
|
<input type="checkbox" checked={invisible} onChange={(e) => setInvisible(e.target.checked)} />
|
||||||
|
<span>
|
||||||
|
<strong>Láthatatlan mód</strong>
|
||||||
|
<span className="hint">Nem jelenik meg mellettem a zöld pötty, és az sem, mikor jártam itt utoljára.</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{member && (
|
||||||
|
<div className="fprof-rank">
|
||||||
|
<span className="eyebrow">Rangod</span>
|
||||||
|
<strong>{member.rank_name}</strong>
|
||||||
|
<span className="hint">
|
||||||
|
{member.points} pont · {member.post_count} hozzászólás
|
||||||
|
{member.next_rank &&
|
||||||
|
` · a ${member.next_rank.name} ranghoz ${member.next_rank.points} pont és ${member.next_rank.days} nap tagság kell`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{saved && <p className="msg">Elmentve.</p>}
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={busy || !nickname.trim() || check?.ok === false}>
|
||||||
|
{busy ? "Mentés…" : member ? "Mentés" : "Álnév mentése"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import type { ForumMe } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
import { ProfileForm } from "./ProfileForm";
|
||||||
|
|
||||||
|
export const metadata = { title: "Fórumprofil", robots: { index: false } };
|
||||||
|
|
||||||
|
type Props = { searchParams: Promise<{ vissza?: string }> };
|
||||||
|
|
||||||
|
/** The member's forum profile: the nickname first, then avatar, bio, signs, visibility. */
|
||||||
|
export default async function ForumSettingsPage({ searchParams }: Props) {
|
||||||
|
const { vissza } = await searchParams;
|
||||||
|
const res = await forumGet<ForumMe>("/v1/forum/me");
|
||||||
|
if (!res.ok) redirect(`/belepes?vissza=${encodeURIComponent("/forum/beallitasok")}`);
|
||||||
|
// Only back into the forum.
|
||||||
|
const back = vissza?.startsWith("/forum") ? vissza : null;
|
||||||
|
const me = res.data;
|
||||||
|
return (
|
||||||
|
<div className="fh">
|
||||||
|
<h1 className="fpage-title">{me.member ? "Fórumprofil" : "Válassz álnevet"}</h1>
|
||||||
|
{!me.member && (
|
||||||
|
<p className="muted">
|
||||||
|
A fórumon mindenki álnéven ír. A valódi neved, az e-mail-címed és a születési adataid soha nem jelennek meg
|
||||||
|
itt.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<ProfileForm me={me} back={back} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,447 @@
|
|||||||
|
/* The forum: phones first (most members write from a phone), big touch
|
||||||
|
targets and text for the 50+ readers. Light by default, dark on request
|
||||||
|
(data-theme on .forum, from a cookie): both redefine the site's colour
|
||||||
|
tokens for the forum's part of the page, so the shared .btn, .inp, .hint
|
||||||
|
and links follow. */
|
||||||
|
|
||||||
|
/* --- themes --- */
|
||||||
|
.forum {
|
||||||
|
--f-hover: rgba(255, 255, 255, 0.04);
|
||||||
|
--f-tint: rgba(217, 180, 106, 0.1);
|
||||||
|
--f-tint-strong: rgba(217, 180, 106, 0.14);
|
||||||
|
--f-nav-bg: rgba(13, 18, 32, 0.97);
|
||||||
|
--f-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);
|
||||||
|
--f-border-hover: #5a6790;
|
||||||
|
--f-online: #9fd8b0;
|
||||||
|
--f-blue-tint: rgba(127, 176, 224, 0.12);
|
||||||
|
--f-orange-tint: rgba(240, 163, 94, 0.12);
|
||||||
|
--f-red-tint: rgba(242, 160, 160, 0.08);
|
||||||
|
--f-green-tint: rgba(159, 216, 176, 0.12);
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.forum[data-theme="light"] {
|
||||||
|
--bg: #f6f3ed;
|
||||||
|
--panel: #ffffff;
|
||||||
|
--panel-2: #faf8f4;
|
||||||
|
--line: #e6dfd2;
|
||||||
|
--line-2: #d3c9b6;
|
||||||
|
--ink: #1b2236;
|
||||||
|
--ink-2: #3a4259;
|
||||||
|
--muted: #5c6376;
|
||||||
|
--gold: #8a6a24;
|
||||||
|
--gold-hover: #6e5419;
|
||||||
|
--gold-ink: #ffffff;
|
||||||
|
--danger: #b03a3a;
|
||||||
|
--ok: #2d7a4c;
|
||||||
|
--harmonic: #2c66a0;
|
||||||
|
--square: #9c520e;
|
||||||
|
--f-hover: rgba(27, 34, 54, 0.04);
|
||||||
|
--f-tint: rgba(167, 128, 47, 0.09);
|
||||||
|
--f-tint-strong: rgba(167, 128, 47, 0.14);
|
||||||
|
--f-nav-bg: rgba(255, 255, 255, 0.97);
|
||||||
|
--f-shadow: 0 12px 32px rgba(27, 34, 54, 0.14);
|
||||||
|
--f-border-hover: #a99d86;
|
||||||
|
--f-online: #2fa865;
|
||||||
|
--f-blue-tint: rgba(44, 102, 160, 0.09);
|
||||||
|
--f-orange-tint: rgba(156, 82, 14, 0.09);
|
||||||
|
--f-red-tint: rgba(176, 58, 58, 0.07);
|
||||||
|
--f-green-tint: rgba(45, 122, 76, 0.1);
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
/* The light forum takes the whole page between the (dark) header and footer
|
||||||
|
(the body rule; the background here is for browsers without :has). */
|
||||||
|
.forum[data-theme="light"] { background: var(--bg); min-height: 70vh; }
|
||||||
|
body:has(.forum[data-theme="light"]) { background: #f6f3ed; }
|
||||||
|
body:has(.forum[data-theme="light"]) .night-sky { display: none; }
|
||||||
|
body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
|
||||||
|
.forum[data-theme="light"] .inp:focus { background-color: var(--panel); box-shadow: 0 0 0 3px rgba(167, 128, 47, 0.22); }
|
||||||
|
.forum[data-theme="light"] .inp::placeholder { color: #8b8f9c; }
|
||||||
|
.forum[data-theme="light"] .btn:hover { border-color: var(--f-border-hover); background: var(--f-hover); }
|
||||||
|
.forum[data-theme="light"] .moon-phase-icon .moon-dark { fill: #ebe5d8; stroke: #b99550; }
|
||||||
|
.forum[data-theme="light"] .moon-phase-icon .moon-lit { fill: #d9b46a; }
|
||||||
|
|
||||||
|
/* --- frame --- */
|
||||||
|
.forum-inner { max-width: 1180px; margin: 0 auto; padding: 8px 16px 104px; }
|
||||||
|
.forum-main { display: flex; flex-direction: column; }
|
||||||
|
.forum h1, .forum h2 { font-family: var(--font-display); font-weight: 600; color: var(--ink); }
|
||||||
|
.forum-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 52px; margin-bottom: 8px; }
|
||||||
|
.forum-mark { font-family: var(--font-display); font-size: 26px; font-weight: 600; color: var(--ink); text-decoration: none; }
|
||||||
|
.forum-mark:hover { color: var(--gold); }
|
||||||
|
.forum-theme {
|
||||||
|
display: inline-flex; align-items: center; gap: 8px; min-width: 44px; min-height: 44px; padding: 0 10px; justify-content: center;
|
||||||
|
border: 1px solid var(--line-2); border-radius: 999px; background: var(--panel); color: var(--ink-2);
|
||||||
|
font: 500 14px var(--font-body); cursor: pointer;
|
||||||
|
}
|
||||||
|
.forum-theme:hover { color: var(--gold); border-color: var(--f-border-hover); }
|
||||||
|
.forum-theme svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
|
.forum-theme-label { display: none; }
|
||||||
|
|
||||||
|
/* The forum's menu: a bar at the bottom on phones, tabs in the forum bar on wider screens. */
|
||||||
|
.forum-nav {
|
||||||
|
position: fixed; left: 0; right: 0; bottom: 0; z-index: 25;
|
||||||
|
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
background: var(--f-nav-bg); border-top: 1px solid var(--line);
|
||||||
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
|
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
.fn-item {
|
||||||
|
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
|
||||||
|
min-height: 62px; color: var(--ink-2); text-decoration: none; font-size: 12px;
|
||||||
|
}
|
||||||
|
.fn-item[aria-current="page"] { color: var(--gold); font-weight: 600; }
|
||||||
|
.fn-item:hover { color: var(--gold); }
|
||||||
|
.fn-icon-wrap { position: relative; display: inline-flex; }
|
||||||
|
.fn-icon { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
|
.fn-badge {
|
||||||
|
position: absolute; top: -6px; right: -11px; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box;
|
||||||
|
border-radius: 999px; background: var(--gold); color: var(--gold-ink); font-size: 11px; font-weight: 600; line-height: 18px; text-align: center;
|
||||||
|
}
|
||||||
|
@media (min-width: 760px) {
|
||||||
|
.forum-inner { padding: 20px 24px 64px; }
|
||||||
|
.forum-bar {
|
||||||
|
gap: 16px; margin-bottom: 24px; padding: 6px 6px 6px 18px;
|
||||||
|
background: var(--panel); border: 1px solid var(--line); border-radius: 16px;
|
||||||
|
}
|
||||||
|
.forum-nav {
|
||||||
|
position: static; flex: 1; display: flex; gap: 4px; padding: 0;
|
||||||
|
background: none; border: 0; box-shadow: none;
|
||||||
|
}
|
||||||
|
.fn-item { flex-direction: row; gap: 8px; min-height: 44px; padding: 0 14px; border-radius: 10px; font-size: 15px; }
|
||||||
|
.fn-item[aria-current="page"] { background: var(--f-tint); }
|
||||||
|
.fn-icon { width: 20px; height: 20px; }
|
||||||
|
.forum-theme { padding: 0 14px; }
|
||||||
|
.forum-theme-label { display: inline; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- avatars and the author line --- */
|
||||||
|
.av { position: relative; display: inline-flex; flex: none; }
|
||||||
|
.av svg { display: block; }
|
||||||
|
/* The night-coloured avatars keep the bright gold in both themes. */
|
||||||
|
.av-glyph { fill: none; stroke: #d9b46a; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
|
.av-glyph .av-fill { fill: #d9b46a; stroke: none; }
|
||||||
|
.av-online {
|
||||||
|
position: absolute; right: -1px; bottom: -1px; width: 28%; height: 28%; min-width: 9px; min-height: 9px;
|
||||||
|
border-radius: 50%; background: var(--f-online); border: 2px solid var(--panel); box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.fa-line { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||||
|
.fa-avatar { display: inline-flex; }
|
||||||
|
.fa-meta { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
|
||||||
|
.fa-names { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.fa-name { font-size: 16px; font-weight: 600; color: var(--ink); text-decoration: none; }
|
||||||
|
.fa-name:hover { color: var(--gold); }
|
||||||
|
.fa-rank { font-size: 12px; color: var(--ink-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 0 6px; }
|
||||||
|
.fa-badge { font-size: 12px; border-radius: 6px; padding: 0 6px; }
|
||||||
|
.fa-badge-mod { color: var(--ok); background: var(--f-green-tint); }
|
||||||
|
.fa-badge-starter { color: var(--gold); border: 1px solid var(--line-2); }
|
||||||
|
.fa-badge-new { color: var(--gold-ink); background: var(--gold); font-weight: 600; }
|
||||||
|
.fa-sub { font-size: 13px; color: var(--muted); }
|
||||||
|
|
||||||
|
/* --- cards, banners, sections --- */
|
||||||
|
.fh { display: flex; flex-direction: column; gap: 22px; }
|
||||||
|
.fh-card { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 18px; }
|
||||||
|
.forum[data-theme="light"] .fh-card { box-shadow: 0 1px 2px rgba(27, 34, 54, 0.04); }
|
||||||
|
.fh-flush { padding: 0; overflow: hidden; }
|
||||||
|
.fh-empty { color: var(--muted); }
|
||||||
|
.fh-card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; margin-bottom: 12px; }
|
||||||
|
.fh-intro { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
|
||||||
|
.fh-intro h1 { font-size: 36px; }
|
||||||
|
.fh-banner {
|
||||||
|
display: flex; align-items: center; gap: 12px; justify-content: space-between;
|
||||||
|
min-height: 52px; padding: 12px 14px; border-radius: 12px;
|
||||||
|
background: var(--f-tint); border: 1px solid var(--line-2); color: var(--ink); text-decoration: none;
|
||||||
|
}
|
||||||
|
.fh-banner strong { color: var(--gold); font-weight: 600; }
|
||||||
|
.fh-banner:hover { color: var(--ink); background: var(--f-tint-strong); }
|
||||||
|
.fh-banner-warn { background: var(--f-red-tint); border-color: var(--danger); }
|
||||||
|
.fh-section { display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.fh-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
|
||||||
|
.fh-section-head h2 { font-size: 24px; }
|
||||||
|
.fh-sky-body { display: flex; gap: 16px; align-items: flex-start; }
|
||||||
|
.fh-moon .moon-phase-icon { width: 56px; height: 56px; }
|
||||||
|
.fh-sky-text { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||||
|
.fh-sky-text h2 { font-size: 24px; line-height: 1.15; }
|
||||||
|
.fh-sky-text p { color: var(--ink-2); font-size: 16px; }
|
||||||
|
.fh-sky-link, .fh-side-link { display: inline-flex; align-items: center; min-height: 44px; margin-top: 8px; font-size: 15px; }
|
||||||
|
.fh-waiting-grid { display: grid; gap: 12px; }
|
||||||
|
@media (min-width: 760px) { .fh-waiting-grid { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } }
|
||||||
|
.fh-me { display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
.fh-me-head { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.fh-me-names { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; }
|
||||||
|
.fh-me-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
|
||||||
|
/* Front page: one column on phones in reading order (the two columns'
|
||||||
|
blocks interleave), main column and sidebar from 1024 px. */
|
||||||
|
.fh-home .fh-col { display: contents; }
|
||||||
|
.o-1 { order: 1; } .o-2 { order: 2; } .o-3 { order: 3; } .o-4 { order: 4; }
|
||||||
|
.o-5 { order: 5; } .o-6 { order: 6; } .o-7 { order: 7; } .o-8 { order: 8; }
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
.fh-home { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 28px; align-items: start; }
|
||||||
|
.fh-home .fh-col { display: flex; flex-direction: column; gap: 22px; }
|
||||||
|
.fh-home .fh-col-side { position: sticky; top: 88px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- topics --- */
|
||||||
|
.fh-topics { list-style: none; margin: 0; }
|
||||||
|
.fh-topics li + li { border-top: 1px solid var(--line); }
|
||||||
|
.fh-topic { display: flex; align-items: center; gap: 14px; padding: 14px 16px; min-height: 76px; color: var(--ink); text-decoration: none; }
|
||||||
|
.fh-topic:hover { color: var(--ink); background: var(--f-hover); }
|
||||||
|
.fh-topic-icon {
|
||||||
|
flex: none; width: 44px; height: 44px; border-radius: 12px; background: var(--f-tint);
|
||||||
|
display: inline-flex; align-items: center; justify-content: center;
|
||||||
|
}
|
||||||
|
.topic-icon { width: 24px; height: 24px; fill: none; stroke: var(--gold); stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
|
.fh-topic-text { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }
|
||||||
|
.fh-topic-name { display: flex; align-items: center; gap: 8px; font-size: 17px; font-weight: 600; }
|
||||||
|
.fh-lock { width: 14px; height: 14px; fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; }
|
||||||
|
.fh-topic-desc { font-size: 14px; color: var(--muted); }
|
||||||
|
.fh-topic-last { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--muted); }
|
||||||
|
.fh-topic-count { display: none; flex: none; font-size: 14px; color: var(--muted); text-align: right; min-width: 64px; }
|
||||||
|
.fh-topic-count strong { color: var(--ink); font-weight: 600; }
|
||||||
|
@media (min-width: 640px) { .fh-topic-count { display: block; } }
|
||||||
|
|
||||||
|
/* --- thread lists: a meta line on phones, columns on wider screens --- */
|
||||||
|
.ft-list { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.ft-list li + li { border-top: 1px solid var(--line); }
|
||||||
|
.ft-row { display: flex; align-items: center; gap: 12px; padding: 14px 16px; min-height: 64px; color: var(--ink); text-decoration: none; }
|
||||||
|
.ft-row:hover { color: var(--ink); background: var(--f-hover); }
|
||||||
|
.ft-main { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
|
||||||
|
.ft-title { font-size: 17px; font-weight: 600; line-height: 1.35; }
|
||||||
|
.ft-row:hover .ft-title { color: var(--gold); }
|
||||||
|
.ft-excerpt { font-size: 14px; color: var(--ink-2); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||||
|
.ft-meta { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--muted); }
|
||||||
|
.ft-col { display: none; }
|
||||||
|
.ft-new {
|
||||||
|
flex: none; font-size: 13px; font-weight: 600; color: var(--gold-ink); background: var(--gold);
|
||||||
|
border-radius: 999px; padding: 2px 9px; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.ft-read { flex: none; font-size: 13px; color: var(--muted); }
|
||||||
|
@media (min-width: 760px) {
|
||||||
|
.ft-row { display: grid; grid-template-columns: minmax(0, 1fr) 110px 100px 72px; gap: 16px; padding: 14px 20px; }
|
||||||
|
.ft-m-narrow { display: none; }
|
||||||
|
.ft-col { display: flex; flex-direction: column; align-items: flex-end; font-size: 14px; color: var(--muted); }
|
||||||
|
.ft-col strong { color: var(--ink); font-weight: 600; font-size: 16px; }
|
||||||
|
.ft-col-replies { flex-direction: row; gap: 4px; align-items: baseline; justify-content: flex-end; flex-wrap: wrap; }
|
||||||
|
.ft-col-replies .hint { flex-basis: 100%; text-align: right; }
|
||||||
|
.ft-new, .ft-read { justify-self: end; }
|
||||||
|
}
|
||||||
|
.ft-pin {
|
||||||
|
display: inline-block; margin-right: 8px; vertical-align: 2px; font-size: 12px; font-weight: 500;
|
||||||
|
color: var(--ink-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 0 6px;
|
||||||
|
}
|
||||||
|
.ft-intent { align-self: flex-start; font-size: 13px; font-weight: 500; border-radius: 999px; padding: 3px 10px; }
|
||||||
|
.ft-intent-listen { color: var(--harmonic); background: var(--f-blue-tint); }
|
||||||
|
.ft-intent-advice { color: var(--square); background: var(--f-orange-tint); }
|
||||||
|
.ft-waiting {
|
||||||
|
display: flex; flex-direction: column; gap: 10px; padding: 16px; border-radius: 14px;
|
||||||
|
background: var(--panel); border: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.ft-waiting-title { font-size: 18px; font-weight: 600; line-height: 1.35; color: var(--ink); text-decoration: none; }
|
||||||
|
.ft-waiting-title:hover { color: var(--gold); }
|
||||||
|
.ft-answer { align-self: flex-start; min-height: 44px; border-color: var(--gold); color: var(--gold); margin-top: auto; }
|
||||||
|
|
||||||
|
/* --- topic page and the other headings --- */
|
||||||
|
.forum-crumbs { display: flex; gap: 8px; align-items: center; font-size: 14px; color: var(--muted); }
|
||||||
|
.forum-crumbs a { color: var(--ink-2); text-decoration: none; min-height: 32px; display: inline-flex; align-items: center; }
|
||||||
|
.forum-crumbs a:hover { color: var(--gold); }
|
||||||
|
.ftopic-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 16px; }
|
||||||
|
.ftopic-head h1, .fpage-title { font-size: 34px; line-height: 1.1; }
|
||||||
|
.ftopic-head > div { display: flex; flex-direction: column; gap: 6px; max-width: 620px; }
|
||||||
|
.forum-pager { display: flex; justify-content: space-between; align-items: center; min-height: 44px; }
|
||||||
|
|
||||||
|
/* --- thread view --- */
|
||||||
|
.ftv { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 980px; margin: 0 auto; }
|
||||||
|
.ftv-toolbar { display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.ftv-toolbar:empty { display: none; }
|
||||||
|
.ftv-mod { position: relative; }
|
||||||
|
.ftv-mod summary { list-style: none; cursor: pointer; }
|
||||||
|
.ftv-mod summary::-webkit-details-marker { display: none; }
|
||||||
|
.ftv-mod-menu {
|
||||||
|
position: absolute; right: 0; top: calc(100% + 6px); z-index: 10; min-width: 200px; padding: 6px;
|
||||||
|
display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px;
|
||||||
|
box-shadow: var(--f-shadow);
|
||||||
|
}
|
||||||
|
.ftv-mod-menu button {
|
||||||
|
min-height: 44px; padding: 0 12px; border: 0; border-radius: 8px; background: none; color: var(--ink);
|
||||||
|
font: inherit; font-size: 15px; text-align: left; cursor: pointer;
|
||||||
|
}
|
||||||
|
.ftv-mod-menu button:hover { background: var(--f-hover); color: var(--gold); }
|
||||||
|
.ftv-mod-menu button.danger { color: var(--danger); }
|
||||||
|
.ftv-intent {
|
||||||
|
display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border-radius: 12px;
|
||||||
|
background: var(--f-blue-tint); font-size: 14px; line-height: 1.45; color: var(--ink-2);
|
||||||
|
}
|
||||||
|
.ftv-intent strong { color: var(--harmonic); font-weight: 600; }
|
||||||
|
.ftv-intent-advice { background: var(--f-orange-tint); }
|
||||||
|
.ftv-intent-advice strong { color: var(--square); }
|
||||||
|
.ftv-title { font-size: 30px; line-height: 1.12; }
|
||||||
|
.ftv-count { display: flex; justify-content: space-between; align-items: baseline; padding-top: 6px; }
|
||||||
|
.ftv .ftv-count h2 { font-family: var(--font-body); font-size: 15px; color: var(--ink-2); }
|
||||||
|
.ftv-branch { display: flex; flex-direction: column; }
|
||||||
|
.ftv-children { margin-left: 17px; padding-left: 14px; border-left: 2px solid var(--line); display: flex; flex-direction: column; }
|
||||||
|
.ftv-marker { display: flex; align-items: center; gap: 10px; margin: 8px 0 0; color: var(--gold); font-size: 13px; font-weight: 600; }
|
||||||
|
.ftv-marker::before, .ftv-marker::after { content: ""; flex: 1; height: 1px; background: var(--gold); opacity: 0.5; }
|
||||||
|
.ftv-incoming {
|
||||||
|
position: sticky; bottom: 84px; align-self: center; z-index: 5;
|
||||||
|
display: inline-flex; align-items: center; min-height: 44px; padding: 0 18px; border: 0; border-radius: 999px;
|
||||||
|
background: var(--gold); color: var(--gold-ink); font: 600 15px var(--font-body); cursor: pointer;
|
||||||
|
box-shadow: var(--f-shadow);
|
||||||
|
}
|
||||||
|
.ftv-compose { display: flex; flex-direction: column; gap: 8px; padding-top: 14px; border-top: 1px solid var(--line); scroll-margin-top: 90px; }
|
||||||
|
.ftv-hint { font-size: 14px; color: var(--harmonic); }
|
||||||
|
.ftv-replyto { display: flex; align-items: center; gap: 6px; font-size: 14px; color: var(--ink-2); }
|
||||||
|
.ftv-gate { padding: 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); }
|
||||||
|
|
||||||
|
/* --- posts: author on top on phones, the old forums' author column on wide screens --- */
|
||||||
|
.fp { display: flex; flex-direction: column; padding: 16px 0; border-bottom: 1px solid var(--line); scroll-margin-top: 90px; }
|
||||||
|
.fp-content { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
||||||
|
.fp-author, .fp-when { display: none; }
|
||||||
|
.ftv-children .fp:last-child { border-bottom: 0; }
|
||||||
|
.fp-opening { padding-top: 6px; padding-bottom: 20px; }
|
||||||
|
.fp-body { font-size: 17px; line-height: 1.6; overflow-wrap: anywhere; color: var(--ink); }
|
||||||
|
.fp-body p + p { margin-top: 10px; }
|
||||||
|
.fp-removed {
|
||||||
|
gap: 4px; margin: 12px 0; padding: 12px 14px; border: 1px dashed var(--line-2);
|
||||||
|
border-radius: 12px; color: var(--ink-2); font-size: 15px;
|
||||||
|
}
|
||||||
|
.fp-mod-note { font-size: 13px; color: var(--danger); }
|
||||||
|
.fp-collapsed {
|
||||||
|
align-self: flex-start; min-height: 44px; padding: 0; border: 0; background: none; color: var(--muted);
|
||||||
|
font: inherit; font-size: 15px; text-decoration: underline; cursor: pointer;
|
||||||
|
}
|
||||||
|
.fp-helped { display: flex; align-items: center; gap: 6px; font-size: 14px; color: var(--ok); }
|
||||||
|
.fp-helped svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
|
.fp-actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||||
|
.fp-spacer { flex: 1; }
|
||||||
|
.fp-link {
|
||||||
|
min-height: 44px; padding: 0 8px; border: 0; background: none; color: var(--gold);
|
||||||
|
font: 500 15px var(--font-body); cursor: pointer;
|
||||||
|
}
|
||||||
|
.fp-link:hover { color: var(--gold-hover); }
|
||||||
|
.fp-tools { display: flex; align-items: center; gap: 2px; flex-wrap: wrap; }
|
||||||
|
.fp-tools:empty { display: none; }
|
||||||
|
.fp-tool {
|
||||||
|
min-height: 36px; padding: 0 8px; border: 0; border-radius: 8px; background: none; color: var(--muted);
|
||||||
|
font: 400 14px var(--font-body); cursor: pointer;
|
||||||
|
}
|
||||||
|
.fp-tool:hover { color: var(--ink); background: var(--f-hover); }
|
||||||
|
.fp-tool[aria-pressed="true"] { color: var(--ok); }
|
||||||
|
.fp-tool-mod { color: var(--danger); }
|
||||||
|
@media (min-width: 900px) {
|
||||||
|
.forum-inner .ftv { gap: 14px; }
|
||||||
|
.fp { display: grid; grid-template-columns: 150px minmax(0, 1fr); gap: 0 24px; padding: 20px 0; }
|
||||||
|
.fp.fp-removed { display: flex; flex-direction: column; }
|
||||||
|
.fp-head { display: none; }
|
||||||
|
.fp-author { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; min-width: 0; }
|
||||||
|
.fp-author-name { font-size: 16px; font-weight: 600; color: var(--ink); text-decoration: none; overflow-wrap: anywhere; margin-top: 2px; }
|
||||||
|
.fp-author-name:hover { color: var(--gold); }
|
||||||
|
.fp-author-signs { display: flex; flex-direction: column; gap: 1px; font-size: 13px; color: var(--muted); margin-top: 2px; }
|
||||||
|
.fp-when { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--muted); }
|
||||||
|
.ftv-children { margin-left: 40px; padding-left: 20px; }
|
||||||
|
.ftv-children .fp { grid-template-columns: 120px minmax(0, 1fr); }
|
||||||
|
.fr-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||||
|
.ftv-incoming { bottom: 20px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- reactions --- */
|
||||||
|
.fr-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
|
||||||
|
.fr-big {
|
||||||
|
display: flex; align-items: center; gap: 8px; min-height: 46px; padding: 0 12px; border-radius: 12px;
|
||||||
|
border: 1px solid var(--line-2); background: var(--panel); color: var(--ink); font: 500 15px var(--font-body); cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.fr-big:hover:not(:disabled) { border-color: var(--f-border-hover); }
|
||||||
|
.fr-big[aria-pressed="true"] { border-color: var(--gold); background: var(--f-tint-strong); }
|
||||||
|
.fr-big:disabled { cursor: default; }
|
||||||
|
.fr-big-label { flex: 1; min-width: 0; }
|
||||||
|
.fr-count { color: var(--muted); }
|
||||||
|
.fr-big[aria-pressed="true"] .fr-count { color: var(--gold); font-weight: 600; }
|
||||||
|
.fr-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||||
|
.fr-chip {
|
||||||
|
min-height: 44px; min-width: 44px; padding: 0 12px; border-radius: 999px; border: 1px solid var(--line-2);
|
||||||
|
background: none; color: var(--ink); font: 500 14px var(--font-body); cursor: pointer;
|
||||||
|
}
|
||||||
|
.fr-chip:disabled { cursor: default; }
|
||||||
|
.fr-chip:hover:not(:disabled) { border-color: var(--f-border-hover); }
|
||||||
|
.fr-chip[aria-pressed="true"] { border-color: var(--gold); background: var(--f-tint-strong); }
|
||||||
|
.fr-add { border-style: dashed; color: var(--muted); font-size: 18px; }
|
||||||
|
.fr-down { color: var(--muted); font-size: 18px; }
|
||||||
|
.fr-down[aria-pressed="true"] { background: var(--f-hover); color: var(--ink); }
|
||||||
|
.fr-more { position: relative; }
|
||||||
|
.fr-pop {
|
||||||
|
position: absolute; left: 0; bottom: calc(100% + 6px); z-index: 10; min-width: 210px; padding: 6px;
|
||||||
|
display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px;
|
||||||
|
box-shadow: var(--f-shadow);
|
||||||
|
}
|
||||||
|
.fr-pop-item {
|
||||||
|
display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border: 0; border-radius: 8px;
|
||||||
|
background: none; color: var(--ink); font: 400 15px var(--font-body); text-align: left; cursor: pointer;
|
||||||
|
}
|
||||||
|
.fr-pop-item:hover { background: var(--f-hover); }
|
||||||
|
|
||||||
|
/* --- composer --- */
|
||||||
|
.fc { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.fc-text {
|
||||||
|
width: 100%; min-height: 96px; box-sizing: border-box; padding: 12px 14px; border-radius: 12px;
|
||||||
|
border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink); font: 400 16px/1.45 var(--font-body);
|
||||||
|
resize: vertical; caret-color: var(--gold);
|
||||||
|
}
|
||||||
|
.fc-text::placeholder { color: var(--muted); }
|
||||||
|
.fc-text:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px var(--f-tint-strong); background: var(--panel); }
|
||||||
|
.fc-actions { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.fc-spacer { flex: 1; }
|
||||||
|
.fc-icon-btn {
|
||||||
|
width: 44px; height: 44px; flex: none; display: inline-flex; align-items: center; justify-content: center;
|
||||||
|
border: 0; border-radius: 10px; background: none; color: var(--ink-2); cursor: pointer;
|
||||||
|
}
|
||||||
|
.fc-icon-btn:hover, .fc-icon-btn[aria-expanded="true"] { color: var(--gold); background: var(--f-tint); }
|
||||||
|
.fc-icon-btn svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; }
|
||||||
|
.fc-tray {
|
||||||
|
display: grid; grid-template-columns: repeat(auto-fill, minmax(42px, 1fr)); gap: 2px; padding: 8px;
|
||||||
|
border: 1px solid var(--line-2); border-radius: 12px; background: var(--panel-2);
|
||||||
|
}
|
||||||
|
.fc-emoji {
|
||||||
|
width: 100%; height: 42px; border: 0; border-radius: 8px; background: none; color: var(--ink);
|
||||||
|
font-size: 22px; cursor: pointer; font-family: var(--font-symbols), sans-serif;
|
||||||
|
}
|
||||||
|
.fc-emoji:hover { background: var(--f-hover); }
|
||||||
|
|
||||||
|
/* --- new thread and profile forms --- */
|
||||||
|
.fnew, .fprof { display: flex; flex-direction: column; gap: 22px; width: 100%; max-width: 760px; }
|
||||||
|
.fnew-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
||||||
|
.fnew-set legend { font-size: 14px; font-weight: 500; margin-bottom: 8px; padding: 0; }
|
||||||
|
.fnew-topics, .fnew-intents { display: grid; gap: 8px; }
|
||||||
|
@media (min-width: 640px) { .fnew-topics { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
|
.fnew-topic, .fnew-intent, .fprof-check {
|
||||||
|
display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid var(--line-2);
|
||||||
|
border-radius: 12px; cursor: pointer; background: var(--panel);
|
||||||
|
}
|
||||||
|
.fnew-topic:has(input:checked), .fnew-intent:has(input:checked) { border-color: var(--gold); background: var(--f-tint); }
|
||||||
|
.fnew-topic > span, .fnew-intent > span, .fprof-check > span { display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.fnew-topic input, .fnew-intent input, .fprof-check input { margin-top: 4px; accent-color: var(--gold); width: 18px; height: 18px; flex: none; }
|
||||||
|
.fprof-avatars { display: grid; grid-template-columns: repeat(auto-fill, minmax(54px, 1fr)); gap: 6px; }
|
||||||
|
.fprof-avatar {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center; padding: 3px; border-radius: 50%;
|
||||||
|
border: 2px solid transparent; cursor: pointer; justify-self: center;
|
||||||
|
}
|
||||||
|
.fprof-avatar:has(input:checked) { border-color: var(--gold); }
|
||||||
|
.fprof-avatar:has(input:focus-visible) { outline: 2px solid var(--gold); outline-offset: 2px; }
|
||||||
|
.fprof-rank { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); }
|
||||||
|
|
||||||
|
/* --- member page (two columns on wide screens) and moderation --- */
|
||||||
|
.fmember { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
|
||||||
|
.fmember-head { display: flex; align-items: center; gap: 16px; }
|
||||||
|
.fmember-names { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.fmember-names h1 { font-size: 30px; line-height: 1.1; }
|
||||||
|
.fmember-badges { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||||
|
.fmember-signs { color: var(--ink-2); }
|
||||||
|
@media (min-width: 900px) {
|
||||||
|
.fh-member { display: grid; grid-template-columns: 340px minmax(0, 1fr); gap: 28px; align-items: start; }
|
||||||
|
.fh-member .fmember { position: sticky; top: 88px; }
|
||||||
|
}
|
||||||
|
.fban { align-self: stretch; }
|
||||||
|
.fban summary { list-style: none; cursor: pointer; display: inline-flex; }
|
||||||
|
.fban summary::-webkit-details-marker { display: none; }
|
||||||
|
.fban-body { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; padding: 14px; border: 1px solid var(--line-2); border-radius: 12px; }
|
||||||
|
.fmodlog { list-style: none; margin: 0; }
|
||||||
|
.fmodlog li { display: flex; flex-direction: column; gap: 2px; padding: 12px 16px; }
|
||||||
|
.fmodlog li + li { border-top: 1px solid var(--line); }
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import { ThreadList } from "@/components/forum/ThreadList";
|
||||||
|
import type { ForumViewer, ThreadCard } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
export const metadata = { title: "Követett szálak", robots: { index: false } };
|
||||||
|
|
||||||
|
/** The threads the member follows (their own and the ones they replied to), with what is new. */
|
||||||
|
export default async function FollowedPage() {
|
||||||
|
const res = await forumGet<{ viewer: ForumViewer; threads: ThreadCard[] }>("/v1/forum/followed");
|
||||||
|
if (!res.ok) redirect("/belepes?vissza=/forum/kovetett");
|
||||||
|
const { threads } = res.data;
|
||||||
|
return (
|
||||||
|
<div className="fh">
|
||||||
|
<h1 className="fpage-title">Követett szálak</h1>
|
||||||
|
<p className="muted">A saját szálaid, azok, amelyekhez hozzászóltál, és amelyeket követni kezdtél.</p>
|
||||||
|
{threads.length === 0 ? (
|
||||||
|
<p className="fh-card fh-empty">Még nem követsz egy szálat sem.</p>
|
||||||
|
) : (
|
||||||
|
<div className="fh-card fh-flush">
|
||||||
|
<ThreadList threads={threads} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { ForumNav } from "@/components/forum/ForumNav";
|
||||||
|
import { ThemeToggle } from "@/components/forum/ThemeToggle";
|
||||||
|
import { PublicHeader } from "@/components/SiteHeader";
|
||||||
|
import { FORUM_THEME_COOKIE, type ForumTheme, type ForumViewer } from "@/lib/forum";
|
||||||
|
import { forumEnabled, forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
import "./forum.css";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
|
||||||
|
description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The forum's frame: the visitor header (the logged-in one comes from the
|
||||||
|
* root layout), the forum's bar with its menu and the light/dark switch.
|
||||||
|
* Light by default; the choice lives in a cookie.
|
||||||
|
*/
|
||||||
|
export default async function ForumLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
if (!forumEnabled()) notFound();
|
||||||
|
const [nav, jar] = await Promise.all([
|
||||||
|
forumGet<{ viewer: ForumViewer; followed: { new_replies: number } | null }>("/v1/forum/nav"),
|
||||||
|
cookies(),
|
||||||
|
]);
|
||||||
|
const viewer = nav.ok ? nav.data.viewer : null;
|
||||||
|
const theme: ForumTheme = jar.get(FORUM_THEME_COOKIE)?.value === "dark" ? "dark" : "light";
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{!viewer?.logged_in && <PublicHeader current="forum" />}
|
||||||
|
<div className="forum" data-theme={theme}>
|
||||||
|
<div className="forum-inner">
|
||||||
|
<div className="forum-bar">
|
||||||
|
<Link href="/forum" className="forum-mark">
|
||||||
|
Fórum
|
||||||
|
</Link>
|
||||||
|
<ForumNav
|
||||||
|
member={viewer?.member?.nickname ?? null}
|
||||||
|
loggedIn={viewer?.logged_in ?? false}
|
||||||
|
unread={nav.ok ? (nav.data.followed?.new_replies ?? 0) : 0}
|
||||||
|
/>
|
||||||
|
<ThemeToggle initial={theme} />
|
||||||
|
</div>
|
||||||
|
<main className="forum-main">{children}</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { type ModLogEntry, banText, memberHref, threadHref } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
export const metadata = { title: "Moderálási napló", robots: { index: false } };
|
||||||
|
|
||||||
|
const ACTIONS: Record<string, string> = {
|
||||||
|
delete_post: "hozzászólást távolított el",
|
||||||
|
restore_post: "hozzászólást állított vissza",
|
||||||
|
delete_thread: "szálat távolított el",
|
||||||
|
restore_thread: "szálat állított vissza",
|
||||||
|
ban: "eltiltotta",
|
||||||
|
unban: "feloldotta az eltiltását",
|
||||||
|
lock: "lezárta a szálat",
|
||||||
|
unlock: "feloldotta a szálat",
|
||||||
|
pin: "kitűzte a szálat",
|
||||||
|
unpin: "levette a kitűzést",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Every moderation step: who, what, why (moderators only). */
|
||||||
|
export default async function ModLogPage() {
|
||||||
|
const res = await forumGet<{ entries: ModLogEntry[] }>("/v1/forum/mod/log");
|
||||||
|
if (!res.ok) notFound();
|
||||||
|
return (
|
||||||
|
<div className="fh">
|
||||||
|
<h1 className="fpage-title">Moderálási napló</h1>
|
||||||
|
{res.data.entries.length === 0 ? (
|
||||||
|
<p className="fh-card fh-empty">Még nem volt moderálás.</p>
|
||||||
|
) : (
|
||||||
|
<ul className="fh-card fh-flush fmodlog">
|
||||||
|
{res.data.entries.map((e) => (
|
||||||
|
<li key={e.id}>
|
||||||
|
<span className="hint">
|
||||||
|
{new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
|
||||||
|
{e.actor_kind === "ai" && " · AI"}
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<strong>{e.actor ?? "?"}</strong> {ACTIONS[e.action] ?? e.action}
|
||||||
|
{e.target && (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
(<Link href={memberHref(e.target)}>{e.target}</Link>)
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{e.thread && (
|
||||||
|
<>
|
||||||
|
{": "}
|
||||||
|
<Link href={threadHref({ id: e.thread.id, slug: "" }, e.post_id ?? undefined)}>
|
||||||
|
{e.thread.title ?? `#${e.thread.id}`}
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{e.until && ` · ${banText(e.until)}`}
|
||||||
|
</span>
|
||||||
|
{e.reason && <span className="hint">Ok: {e.reason}</span>}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { Avatar } from "@/components/forum/Avatar";
|
||||||
|
import { ThreadList, WaitingCard } from "@/components/forum/ThreadList";
|
||||||
|
import { MoonPhaseIcon } from "@/components/MoonChip";
|
||||||
|
import { MOON_PHASES, SIGNS } from "@/lib/astro";
|
||||||
|
import { type ForumHome, ago, memberHref } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
import { loadSky } from "@/lib/sky";
|
||||||
|
import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText";
|
||||||
|
import type { SkyNow } from "@/lib/types";
|
||||||
|
|
||||||
|
export const metadata = { title: { absolute: "Fórum · Sorsfonalak" } };
|
||||||
|
|
||||||
|
function TopicIcon({ slug }: { slug: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true" className="topic-icon">
|
||||||
|
{slug === "ami-a-szivemen-van" && (
|
||||||
|
<path d="M12 20s-7.5-4.6-7.5-10.2A4.2 4.2 0 0 1 12 7.3a4.2 4.2 0 0 1 7.5 2.5C19.5 15.4 12 20 12 20z" />
|
||||||
|
)}
|
||||||
|
{slug === "belso-utak" && (
|
||||||
|
<>
|
||||||
|
<path d="M12 12a1.2 1.2 0 1 0 1.2-1.2" />
|
||||||
|
<path d="M13.2 10.8A3.4 3.4 0 1 0 15.4 14" />
|
||||||
|
<path d="M15.4 14A5.6 5.6 0 1 1 12 6.4" />
|
||||||
|
<path d="M12 6.4a7.8 7.8 0 1 1-7.6 9.4" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{slug === "egbolt-es-kepletek" && (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="8.5" />
|
||||||
|
<path d="M12 7.5l1.2 3.3 3.3 1.2-3.3 1.2L12 16.5l-1.2-3.3L7.5 12l3.3-1.2z" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{slug === "torzsasztal" && (
|
||||||
|
<>
|
||||||
|
<path d="M4.5 10h11v4.5a5 5 0 0 1-5 5h-1a5 5 0 0 1-5-5z" />
|
||||||
|
<path d="M15.5 11.5h1.3a2.4 2.4 0 0 1 0 4.8h-1.6" />
|
||||||
|
<path d="M8.5 3.5c0 1.4 1 1.6 1 3M12 3.5c0 1.4 1 1.6 1 3" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{!["ami-a-szivemen-van", "belso-utak", "egbolt-es-kepletek", "torzsasztal"].includes(slug) && (
|
||||||
|
<circle cx="12" cy="12" r="8.5" />
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Mai égbolt": the Moon today, the same for everyone; never empty. */
|
||||||
|
function SkyCard({ sky }: { sky: SkyNow }) {
|
||||||
|
const moon = sky.moon;
|
||||||
|
const sign = moon.position.sign;
|
||||||
|
const date = new Date(sky.local_time.slice(0, 10) + "T12:00:00Z").toLocaleDateString("hu-HU", {
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
weekday: "long",
|
||||||
|
timeZone: "UTC",
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<section className="fh-card fh-sky" aria-labelledby="fh-sky-title">
|
||||||
|
<div className="fh-card-head">
|
||||||
|
<span className="eyebrow">Mai égbolt</span>
|
||||||
|
<span className="hint">{date}</span>
|
||||||
|
</div>
|
||||||
|
<div className="fh-sky-body">
|
||||||
|
<span className="fh-moon">
|
||||||
|
<MoonPhaseIcon illumination={moon.illumination} waxing={moon.waxing} />
|
||||||
|
</span>
|
||||||
|
<div className="fh-sky-text">
|
||||||
|
<h2 id="fh-sky-title">
|
||||||
|
{MOON_PHASES[moon.phase] ?? moon.phase}, <span className="sym">{SIGNS[sign]?.glyph}</span> Hold{" "}
|
||||||
|
{withArticle(SIGN_IN[sign] ?? sign)}
|
||||||
|
</h2>
|
||||||
|
<p>{MOON_IN_SIGN[sign]}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Link href="/holdnaptar" className="fh-sky-link">
|
||||||
|
Holdnaptár és a következő holdfázisok
|
||||||
|
</Link>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ForumHomePage() {
|
||||||
|
const [home, sky] = await Promise.all([forumGet<ForumHome>("/v1/forum/home"), loadSky()]);
|
||||||
|
if (!home.ok) notFound();
|
||||||
|
const { viewer, followed, topics, unanswered, hot } = home.data;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fh fh-home">
|
||||||
|
<div className="fh-col fh-col-main">
|
||||||
|
{!viewer.logged_in && (
|
||||||
|
<section className="fh-card fh-intro o-1">
|
||||||
|
<h1>Fórum</h1>
|
||||||
|
<p>
|
||||||
|
Beszélgetés a spiritualitásról, az égboltról, az álmokról és arról, ami a szívedet nyomja. Itt mindenki
|
||||||
|
álnéven ír, a tempó nyugodt, és a meghallgatás fontosabb a vitánál.
|
||||||
|
</p>
|
||||||
|
<p className="hint">
|
||||||
|
Olvasni belépés nélkül is lehet. Hozzászólni és az „Ami a szívemen van” témát olvasni belépve.
|
||||||
|
</p>
|
||||||
|
<Link href="/belepes?vissza=/forum" className="btn btn-primary">
|
||||||
|
Belépés
|
||||||
|
</Link>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{viewer.needs_nickname && (
|
||||||
|
<Link href="/forum/beallitasok" className="fh-banner o-2">
|
||||||
|
<span>
|
||||||
|
<strong>Válassz álnevet</strong>, hogy hozzászólhass. A valódi neved soha nem jelenik meg a fórumon.
|
||||||
|
</span>
|
||||||
|
<span aria-hidden="true">›</span>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{viewer.member?.banned && (
|
||||||
|
<p className="fh-banner fh-banner-warn o-2">
|
||||||
|
Most nem írhatsz a fórumba. A részleteket a beállításaidnál látod.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{followed && followed.new_replies > 0 && (
|
||||||
|
<Link href="/forum/kovetett" className="fh-banner o-2">
|
||||||
|
<span>
|
||||||
|
<strong>{followed.new_replies} új válasz</strong> a követett szálaidban
|
||||||
|
</span>
|
||||||
|
<span aria-hidden="true">›</span>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{unanswered.length > 0 && (
|
||||||
|
<section className="fh-section o-4" aria-labelledby="fh-waiting">
|
||||||
|
<div className="fh-section-head">
|
||||||
|
<h2 id="fh-waiting">Várják a válaszod</h2>
|
||||||
|
<span className="hint">még senki nem válaszolt</span>
|
||||||
|
</div>
|
||||||
|
<div className="fh-waiting-grid">
|
||||||
|
{unanswered.map((t) => (
|
||||||
|
<WaitingCard key={t.id} thread={t} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hot.length > 0 && (
|
||||||
|
<section className="fh-section o-5" aria-labelledby="fh-hot">
|
||||||
|
<div className="fh-section-head">
|
||||||
|
<h2 id="fh-hot">Pörgős most</h2>
|
||||||
|
<span className="hint">az utóbbi 24 órában</span>
|
||||||
|
</div>
|
||||||
|
<div className="fh-card fh-flush">
|
||||||
|
<ThreadList threads={hot} />
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<section className="fh-section o-6" aria-labelledby="fh-topics">
|
||||||
|
<div className="fh-section-head">
|
||||||
|
<h2 id="fh-topics">Témák</h2>
|
||||||
|
</div>
|
||||||
|
<ul className="fh-card fh-flush fh-topics">
|
||||||
|
{topics.map((t) => (
|
||||||
|
<li key={t.slug}>
|
||||||
|
<Link href={t.readable ? `/forum/${t.slug}` : `/belepes?vissza=/forum/${t.slug}`} className="fh-topic">
|
||||||
|
<span className="fh-topic-icon">
|
||||||
|
<TopicIcon slug={t.slug} />
|
||||||
|
</span>
|
||||||
|
<span className="fh-topic-text">
|
||||||
|
<span className="fh-topic-name">
|
||||||
|
{t.name}
|
||||||
|
{t.visibility !== "public" && (
|
||||||
|
<svg viewBox="0 0 24 24" className="fh-lock" role="img" aria-label="Csak tagoknak">
|
||||||
|
<rect x="5" y="11" width="14" height="9" rx="2" />
|
||||||
|
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span className="fh-topic-desc">{t.description}</span>
|
||||||
|
{t.readable && t.last && (
|
||||||
|
<span className="fh-topic-last">
|
||||||
|
{t.last.author && (
|
||||||
|
<Avatar avatar={t.last.author.avatar} size={18} online={t.last.author.online} />
|
||||||
|
)}
|
||||||
|
{t.last.author?.nickname ?? "Törölt tag"},{" "}
|
||||||
|
<time suppressHydrationWarning dateTime={t.last.at}>
|
||||||
|
{ago(t.last.at)}
|
||||||
|
</time>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{!t.readable && <span className="fh-topic-last">Belépés után olvasható</span>}
|
||||||
|
</span>
|
||||||
|
{t.readable && (
|
||||||
|
<span className="fh-topic-count">
|
||||||
|
<strong>{t.thread_count ?? 0}</strong> szál
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{t.readable && t.new_count ? (
|
||||||
|
<span className="ft-new">{t.new_count > 99 ? "99+" : t.new_count} új</span>
|
||||||
|
) : null}
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside className="fh-col fh-col-side" aria-label="Oldalsáv">
|
||||||
|
{sky && (
|
||||||
|
<div className="o-3">
|
||||||
|
<SkyCard sky={sky} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{viewer.member && (
|
||||||
|
<section className="fh-card fh-me o-7" aria-label="Saját">
|
||||||
|
<div className="fh-me-head">
|
||||||
|
<Avatar avatar={viewer.member.avatar} size={48} />
|
||||||
|
<span className="fh-me-names">
|
||||||
|
<Link href={memberHref(viewer.member.nickname)} className="fa-name">
|
||||||
|
{viewer.member.nickname}
|
||||||
|
</Link>
|
||||||
|
<span className="fa-rank">{viewer.member.rank_name}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="fh-me-actions">
|
||||||
|
<Link href="/forum/uj" className="btn btn-primary btn-sm">
|
||||||
|
Új szál
|
||||||
|
</Link>
|
||||||
|
<Link href="/forum/beallitasok" className="btn btn-sm">
|
||||||
|
Fórumprofil
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
{viewer.moderator && (
|
||||||
|
<Link href="/forum/moderalas" className="fh-side-link o-8">
|
||||||
|
Moderálási napló
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { notFound, permanentRedirect, redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import { ThreadView } from "@/components/forum/ThreadView";
|
||||||
|
import type { ThreadPage } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
type Props = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
|
/** `123-nem-tudom-elengedni` → 123; the words after the number are only for reading. */
|
||||||
|
function threadId(param: string): number | null {
|
||||||
|
const match = /^(\d{1,15})(?:-|$)/.exec(decodeURIComponent(param));
|
||||||
|
return match ? Number(match[1]) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(param: string) {
|
||||||
|
const id = threadId(param);
|
||||||
|
if (id === null) return null;
|
||||||
|
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
|
const res = await load((await params).id);
|
||||||
|
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
|
||||||
|
const { thread, posts } = res.data;
|
||||||
|
const open = thread.topic.visibility === "public" && !thread.deleted;
|
||||||
|
const opening = posts.find((p) => p.is_opening)?.body ?? "";
|
||||||
|
return {
|
||||||
|
title: thread.title,
|
||||||
|
description: open ? opening.slice(0, 160) : undefined,
|
||||||
|
alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` },
|
||||||
|
// Members-only topics and removed threads stay out of search engines.
|
||||||
|
robots: open ? undefined : { index: false, follow: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ThreadPageView({ params }: Props) {
|
||||||
|
const param = (await params).id;
|
||||||
|
const res = await load(param);
|
||||||
|
if (!res) notFound();
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 401) redirect(`/belepes?vissza=/forum/szal/${encodeURIComponent(param)}`);
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
const { thread } = res.data;
|
||||||
|
const canonical = thread.slug ? `${thread.id}-${thread.slug}` : `${thread.id}`;
|
||||||
|
if (decodeURIComponent(param) !== canonical) permanentRedirect(`/forum/szal/${canonical}`);
|
||||||
|
return <ThreadView initial={res.data} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
|
||||||
|
const DURATIONS: { hours: number | null; label: string }[] = [
|
||||||
|
{ hours: 3, label: "3 óra" },
|
||||||
|
{ hours: 24, label: "1 nap" },
|
||||||
|
{ hours: 72, label: "3 nap" },
|
||||||
|
{ hours: 168, label: "1 hét" },
|
||||||
|
{ hours: 720, label: "30 nap" },
|
||||||
|
{ hours: null, label: "Végleg" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Moderators: ban a member for a while or for good (they may still read), or lift it. */
|
||||||
|
export function BanPanel({ nickname, banned }: { nickname: string; banned: boolean }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [hours, setHours] = useState<string>("24");
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const path = `/forum/members/${encodeURIComponent(nickname)}/ban`;
|
||||||
|
|
||||||
|
async function act(work: () => Promise<unknown>) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await work();
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
setError(errorText(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<details className="fban">
|
||||||
|
<summary className="btn btn-sm btn-ghost">Moderálás</summary>
|
||||||
|
<div className="fban-body">
|
||||||
|
{banned && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => act(() => api(path, { method: "DELETE" }))}
|
||||||
|
>
|
||||||
|
Eltiltás feloldása
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="fban-hours">Eltiltás</label>
|
||||||
|
<select id="fban-hours" className="inp" value={hours} onChange={(e) => setHours(e.target.value)}>
|
||||||
|
{DURATIONS.map((d) => (
|
||||||
|
<option key={d.label} value={d.hours ?? "forever"}>
|
||||||
|
{d.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="fban-reason">Indoklás (a tag látja)</label>
|
||||||
|
<input
|
||||||
|
id="fban-reason"
|
||||||
|
className="inp"
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
maxLength={300}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-sm btn-danger"
|
||||||
|
disabled={busy || reason.trim().length < 3}
|
||||||
|
onClick={() => act(() => api(path, { body: { hours: hours === "forever" ? null : Number(hours), reason } }))}
|
||||||
|
>
|
||||||
|
Eltiltom
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { Avatar } from "@/components/forum/Avatar";
|
||||||
|
import { signsText } from "@/components/forum/AuthorLine";
|
||||||
|
import { PostBody } from "@/components/forum/PostBody";
|
||||||
|
import { type MemberProfile, ago, banText, threadHref } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
import { BanPanel } from "./BanPanel";
|
||||||
|
|
||||||
|
type Props = { params: Promise<{ nev: string }> };
|
||||||
|
|
||||||
|
async function load(nev: string) {
|
||||||
|
return forumGet<MemberProfile>(`/v1/forum/members/${encodeURIComponent(decodeURIComponent(nev))}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
|
const res = await load((await params).nev);
|
||||||
|
return res.ok ? { title: res.data.member.author.nickname, robots: { index: false } } : { title: "Fórum" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const LAST_SEEN: Record<string, string> = {
|
||||||
|
online: "Most online",
|
||||||
|
day: "Az elmúlt napban járt itt",
|
||||||
|
week: "Ezen a héten járt itt",
|
||||||
|
earlier: "Régebben járt itt",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A member's profile: what they chose to show, and their recent posts. */
|
||||||
|
export default async function MemberPage({ params }: Props) {
|
||||||
|
const res = await load((await params).nev);
|
||||||
|
if (!res.ok) notFound();
|
||||||
|
const { member, recent, viewer } = res.data;
|
||||||
|
const a = member.author;
|
||||||
|
const signs = signsText(a.signs);
|
||||||
|
const since = new Date(member.created_at).toLocaleDateString("hu-HU", { year: "numeric", month: "long" });
|
||||||
|
return (
|
||||||
|
<div className="fh fh-member">
|
||||||
|
<section className="fh-card fmember">
|
||||||
|
<div className="fmember-head">
|
||||||
|
<Avatar avatar={a.avatar} size={72} online={a.online} />
|
||||||
|
<div className="fmember-names">
|
||||||
|
<h1>{a.nickname}</h1>
|
||||||
|
<span className="fmember-badges">
|
||||||
|
<span className="fa-rank">{a.rank_name}</span>
|
||||||
|
{a.moderator && <span className="fa-badge fa-badge-mod">Moderátor</span>}
|
||||||
|
</span>
|
||||||
|
{member.last_seen && <span className="hint">{LAST_SEEN[member.last_seen]}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{signs && <p className="sym fmember-signs">{signs}</p>}
|
||||||
|
{member.bio && <PostBody text={member.bio} />}
|
||||||
|
<p className="hint">
|
||||||
|
Tag {since} óta · {member.post_count} hozzászólás · {member.thread_count} szál
|
||||||
|
</p>
|
||||||
|
{member.banned_until && (
|
||||||
|
<p className="fh-banner fh-banner-warn">
|
||||||
|
Eltiltva ({banText(member.banned_until)}).{member.ban_reason && ` Indok: ${member.ban_reason}`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{member.own && (
|
||||||
|
<Link href="/forum/beallitasok" className="btn btn-sm">
|
||||||
|
Profil szerkesztése
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{viewer.moderator && !member.own && !a.moderator && (
|
||||||
|
<BanPanel nickname={a.nickname} banned={member.banned_until !== null} />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="fh-section" aria-labelledby="fmember-recent">
|
||||||
|
<div className="fh-section-head">
|
||||||
|
<h2 id="fmember-recent">Legutóbbi hozzászólások</h2>
|
||||||
|
</div>
|
||||||
|
{recent.length === 0 ? (
|
||||||
|
<p className="fh-card fh-empty">
|
||||||
|
Még nincs hozzászólása{viewer.logged_in ? "." : ", vagy csak belépve látható."}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<ul className="fh-card fh-flush ft-list">
|
||||||
|
{recent.map((r) => (
|
||||||
|
<li key={r.id}>
|
||||||
|
<Link href={threadHref({ id: r.thread_id, slug: r.thread_slug }, r.id)} className="ft-row">
|
||||||
|
<span className="ft-main">
|
||||||
|
<span className="ft-title">{r.thread_title}</span>
|
||||||
|
<span className="ft-excerpt">{r.excerpt}</span>
|
||||||
|
<span className="ft-meta">
|
||||||
|
{r.is_opening ? "Szálat indított" : "Hozzászólt"} · {r.topic.name} ·{" "}
|
||||||
|
<time suppressHydrationWarning dateTime={r.created_at}>
|
||||||
|
{ago(r.created_at)}
|
||||||
|
</time>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { EMOJI, type ForumTopic, threadHref } from "@/lib/forum";
|
||||||
|
|
||||||
|
type Intent = "listen" | "advice" | "";
|
||||||
|
|
||||||
|
export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[]; initialTopic: string }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [topic, setTopic] = useState(initialTopic);
|
||||||
|
const listening = topics.find((t) => t.slug === topic)?.listening ?? false;
|
||||||
|
const [intent, setIntent] = useState<Intent>(listening ? "listen" : "");
|
||||||
|
const [title, setTitle] = useState("");
|
||||||
|
const [body, setBody] = useState("");
|
||||||
|
const [tray, setTray] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
function pickTopic(slug: string) {
|
||||||
|
setTopic(slug);
|
||||||
|
const t = topics.find((x) => x.slug === slug);
|
||||||
|
if (t?.listening) setIntent("listen");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const created = await api<{ id: number; slug: string }>("/forum/threads", {
|
||||||
|
body: { topic, title, body, intent: intent || null },
|
||||||
|
});
|
||||||
|
router.push(threadHref(created));
|
||||||
|
router.refresh();
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorText(err));
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="fnew" onSubmit={submit}>
|
||||||
|
<fieldset className="fnew-set">
|
||||||
|
<legend>Téma</legend>
|
||||||
|
<div className="fnew-topics">
|
||||||
|
{topics.map((t) => (
|
||||||
|
<label key={t.slug} className="fnew-topic">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="topic"
|
||||||
|
value={t.slug}
|
||||||
|
checked={topic === t.slug}
|
||||||
|
onChange={() => pickTopic(t.slug)}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<strong>{t.name}</strong>
|
||||||
|
<span className="hint">{t.description}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset className="fnew-set">
|
||||||
|
<legend>Mit szeretnél?</legend>
|
||||||
|
<div className="fnew-intents">
|
||||||
|
<label className="fnew-intent">
|
||||||
|
<input type="radio" name="intent" checked={intent === "listen"} onChange={() => setIntent("listen")} />
|
||||||
|
<span>
|
||||||
|
<strong>Csak meghallgatást kérek</strong>
|
||||||
|
<span className="hint">Nem kérek tanácsot, jólesne, ha valaki meghallgatna.</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<label className="fnew-intent">
|
||||||
|
<input type="radio" name="intent" checked={intent === "advice"} onChange={() => setIntent("advice")} />
|
||||||
|
<span>
|
||||||
|
<strong>Tanácsot, véleményt kérek</strong>
|
||||||
|
<span className="hint">Kíváncsi vagyok, ti mit gondoltok, mit tennétek.</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{!listening && (
|
||||||
|
<label className="fnew-intent">
|
||||||
|
<input type="radio" name="intent" checked={intent === ""} onChange={() => setIntent("")} />
|
||||||
|
<span>
|
||||||
|
<strong>Csak beszélgetnék</strong>
|
||||||
|
<span className="hint">Egy téma, egy gondolat, egy élmény.</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="fnew-title">Cím</label>
|
||||||
|
<input
|
||||||
|
id="fnew-title"
|
||||||
|
className="inp"
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
maxLength={120}
|
||||||
|
required
|
||||||
|
placeholder="Miről szeretnél beszélgetni?"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="fnew-body">Az első hozzászólás</label>
|
||||||
|
<textarea
|
||||||
|
id="fnew-body"
|
||||||
|
className="fc-text"
|
||||||
|
rows={8}
|
||||||
|
value={body}
|
||||||
|
onChange={(e) => setBody(e.target.value)}
|
||||||
|
maxLength={10000}
|
||||||
|
required
|
||||||
|
placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"}
|
||||||
|
/>
|
||||||
|
<div className="fc-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="fc-icon-btn"
|
||||||
|
aria-label="Emoji"
|
||||||
|
aria-expanded={tray}
|
||||||
|
onClick={() => setTray((t) => !t)}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<circle cx="12" cy="12" r="9" />
|
||||||
|
<path d="M8.5 14.5a4 4 0 0 0 7 0" />
|
||||||
|
<path d="M9 9.5h.01M15 9.5h.01" strokeWidth="2.6" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<span className="hint">
|
||||||
|
Szöveg és emoji. Képet és videót nem lehet beilleszteni, a linkek sima szövegként látszanak.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{tray && (
|
||||||
|
<div className="fc-tray" role="group" aria-label="Emoji">
|
||||||
|
{EMOJI.map((em) => (
|
||||||
|
<button
|
||||||
|
key={em}
|
||||||
|
type="button"
|
||||||
|
className="fc-emoji"
|
||||||
|
onClick={() => setBody((b) => b + em)}
|
||||||
|
aria-label={`${em} beszúrása`}
|
||||||
|
>
|
||||||
|
{em}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={busy || !title.trim() || !body.trim() || !topic}>
|
||||||
|
{busy ? "Küldés…" : "Szál indítása"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import type { ForumTopic, ForumViewer } from "@/lib/forum";
|
||||||
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
|
import { NewThreadForm } from "./NewThreadForm";
|
||||||
|
|
||||||
|
export const metadata = { title: "Új szál", robots: { index: false } };
|
||||||
|
|
||||||
|
type Props = { searchParams: Promise<{ tema?: string }> };
|
||||||
|
|
||||||
|
/** Starting a thread: a nickname first, then topic, wish, title and text. */
|
||||||
|
export default async function NewThreadPage({ searchParams }: Props) {
|
||||||
|
const { tema } = await searchParams;
|
||||||
|
const back = `/forum/uj${tema ? `?tema=${encodeURIComponent(tema)}` : ""}`;
|
||||||
|
const res = await forumGet<{ topics: ForumTopic[] }>("/v1/forum/topics");
|
||||||
|
const nav = await forumGet<{ viewer: ForumViewer }>("/v1/forum/nav");
|
||||||
|
const viewer = nav.ok ? nav.data.viewer : null;
|
||||||
|
if (!viewer?.logged_in) redirect(`/belepes?vissza=${encodeURIComponent(back)}`);
|
||||||
|
if (viewer.needs_nickname) redirect(`/forum/beallitasok?vissza=${encodeURIComponent(back)}`);
|
||||||
|
const topics = res.ok ? res.data.topics.filter((t) => t.readable) : [];
|
||||||
|
const initial = topics.find((t) => t.slug === tema)?.slug ?? topics[0]?.slug ?? "";
|
||||||
|
return (
|
||||||
|
<div className="fh">
|
||||||
|
<h1 className="fpage-title">Új szál</h1>
|
||||||
|
{viewer.member?.banned ? (
|
||||||
|
<p className="fh-banner fh-banner-warn">Most nem írhatsz a fórumba.</p>
|
||||||
|
) : (
|
||||||
|
<NewThreadForm topics={topics} initialTopic={initial} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ export type NavIconName =
|
|||||||
| "moon"
|
| "moon"
|
||||||
| "retro"
|
| "retro"
|
||||||
| "packages"
|
| "packages"
|
||||||
|
| "forum"
|
||||||
| "admin";
|
| "admin";
|
||||||
|
|
||||||
const GLYPHS: Partial<Record<NavIconName, string>> = {
|
const GLYPHS: Partial<Record<NavIconName, string>> = {
|
||||||
@@ -62,6 +63,12 @@ export function NavIcon({ name }: { name: NavIconName }) {
|
|||||||
<path d="M3.5 7.2L12 12l8.5-4.8M12 12v9.5" />
|
<path d="M3.5 7.2L12 12l8.5-4.8M12 12v9.5" />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{name === "forum" && (
|
||||||
|
<>
|
||||||
|
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
|
||||||
|
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{name === "admin" && (
|
{name === "admin" && (
|
||||||
<>
|
<>
|
||||||
<circle cx="12" cy="12" r="3" />
|
<circle cx="12" cy="12" r="3" />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { forumEnabled } from "@/lib/forumServer";
|
||||||
import type { Me, SkyNow } from "@/lib/types";
|
import type { Me, SkyNow } from "@/lib/types";
|
||||||
|
|
||||||
import { MobileMenu } from "./MobileMenu";
|
import { MobileMenu } from "./MobileMenu";
|
||||||
@@ -42,10 +43,11 @@ export function PublicHeader({
|
|||||||
current,
|
current,
|
||||||
}: {
|
}: {
|
||||||
onHome?: boolean;
|
onHome?: boolean;
|
||||||
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd";
|
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd" | "forum";
|
||||||
}) {
|
}) {
|
||||||
const home = onHome ? "" : "/";
|
const home = onHome ? "" : "/";
|
||||||
const here = (page: typeof current) => (current === page ? "page" : undefined);
|
const here = (page: typeof current) => (current === page ? "page" : undefined);
|
||||||
|
const forum = forumEnabled();
|
||||||
return (
|
return (
|
||||||
<header className="site-header lp-header">
|
<header className="site-header lp-header">
|
||||||
<Logo />
|
<Logo />
|
||||||
@@ -56,6 +58,11 @@ export function PublicHeader({
|
|||||||
<Link href="/pelda" aria-current={here("pelda")}>
|
<Link href="/pelda" aria-current={here("pelda")}>
|
||||||
Példa
|
Példa
|
||||||
</Link>
|
</Link>
|
||||||
|
{forum && (
|
||||||
|
<Link href="/forum" aria-current={here("forum")}>
|
||||||
|
Fórum
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
<nav className="lp-free" aria-label="Ingyenes, belépés nélkül">
|
<nav className="lp-free" aria-label="Ingyenes, belépés nélkül">
|
||||||
<span className="lp-free-label">Ingyenes</span>
|
<span className="lp-free-label">Ingyenes</span>
|
||||||
@@ -81,6 +88,7 @@ export function PublicHeader({
|
|||||||
{ href: `${home}#elorejelzes`, label: "Előrejelzés" },
|
{ href: `${home}#elorejelzes`, label: "Előrejelzés" },
|
||||||
{ href: `${home}#osszevetes`, label: "Összevetés" },
|
{ href: `${home}#osszevetes`, label: "Összevetés" },
|
||||||
{ href: "/pelda", label: "Példa" },
|
{ href: "/pelda", label: "Példa" },
|
||||||
|
...(forum ? [{ href: "/forum", label: "Fórum" }] : []),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -148,6 +156,7 @@ export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
|||||||
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
||||||
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
||||||
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
||||||
|
...(forumEnabled() ? [{ href: "/forum", label: "Fórum", icon: "forum" as const }] : []),
|
||||||
];
|
];
|
||||||
const packages: NavItem = { href: "/csomagok", label: "Csomagok", icon: "packages" };
|
const packages: NavItem = { href: "/csomagok", label: "Csomagok", icon: "packages" };
|
||||||
const team: NavItem[] = me.user.roles.includes("admin")
|
const team: NavItem[] = me.user.roles.includes("admin")
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { POINTS, SIGNS } from "@/lib/astro";
|
||||||
|
import { type ForumAuthor, ago, memberHref } from "@/lib/forum";
|
||||||
|
|
||||||
|
import { Avatar } from "./Avatar";
|
||||||
|
|
||||||
|
/** "☉ Halak · ☽ Rák · Asz Szűz": the signs a member chose to share. */
|
||||||
|
export function signsText(signs: Record<string, string> | null | undefined): string | null {
|
||||||
|
if (!signs) return null;
|
||||||
|
const parts = Object.entries(signs)
|
||||||
|
.sort(([a], [b]) => order(a) - order(b))
|
||||||
|
.map(([point, sign]) => {
|
||||||
|
const name = SIGNS[sign]?.hu ?? sign;
|
||||||
|
return point === "ascendant" ? `Asz ${name}` : `${POINTS[point]?.glyph ?? point} ${name}`;
|
||||||
|
});
|
||||||
|
return parts.length ? parts.join(" · ") : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ORDER = [
|
||||||
|
"sun",
|
||||||
|
"moon",
|
||||||
|
"ascendant",
|
||||||
|
"mercury",
|
||||||
|
"venus",
|
||||||
|
"mars",
|
||||||
|
"jupiter",
|
||||||
|
"saturn",
|
||||||
|
"uranus",
|
||||||
|
"neptune",
|
||||||
|
"pluto",
|
||||||
|
];
|
||||||
|
function order(point: string) {
|
||||||
|
const i = ORDER.indexOf(point);
|
||||||
|
return i < 0 ? 99 : i;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who wrote it: avatar with the online dot, nickname, rank, badges, the
|
||||||
|
* shared signs and the time. A deleted account shows as "Törölt tag".
|
||||||
|
*/
|
||||||
|
export function AuthorLine({
|
||||||
|
author,
|
||||||
|
size = 40,
|
||||||
|
time,
|
||||||
|
edited = false,
|
||||||
|
badges,
|
||||||
|
signs = true,
|
||||||
|
}: {
|
||||||
|
author: ForumAuthor | null;
|
||||||
|
size?: number;
|
||||||
|
time?: string;
|
||||||
|
edited?: boolean;
|
||||||
|
badges?: React.ReactNode;
|
||||||
|
signs?: boolean;
|
||||||
|
}) {
|
||||||
|
if (!author) {
|
||||||
|
return (
|
||||||
|
<div className="fa-line">
|
||||||
|
<Avatar avatar={null} size={size} />
|
||||||
|
<span className="fa-meta">
|
||||||
|
<span className="fa-name muted">Törölt tag</span>
|
||||||
|
{time && <span className="fa-sub">{ago(time)}</span>}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const shown = signs ? signsText(author.signs) : null;
|
||||||
|
return (
|
||||||
|
<div className="fa-line">
|
||||||
|
<Link href={memberHref(author.nickname)} className="fa-avatar" tabIndex={-1} aria-hidden="true">
|
||||||
|
<Avatar avatar={author.avatar} size={size} online={author.online} />
|
||||||
|
</Link>
|
||||||
|
<span className="fa-meta">
|
||||||
|
<span className="fa-names">
|
||||||
|
<Link href={memberHref(author.nickname)} className="fa-name">
|
||||||
|
{author.nickname}
|
||||||
|
</Link>
|
||||||
|
{author.online && <span className="sr-only">(online)</span>}
|
||||||
|
<span className="fa-rank">{author.rank_name}</span>
|
||||||
|
{author.moderator && <span className="fa-badge fa-badge-mod">Moderátor</span>}
|
||||||
|
{badges}
|
||||||
|
</span>
|
||||||
|
{(shown || time) && (
|
||||||
|
<span className="fa-sub">
|
||||||
|
{shown && <span className="sym">{shown}</span>}
|
||||||
|
{shown && time && " · "}
|
||||||
|
{time && (
|
||||||
|
<time
|
||||||
|
suppressHydrationWarning
|
||||||
|
dateTime={time}
|
||||||
|
title={new Date(time).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
|
||||||
|
>
|
||||||
|
{ago(time)}
|
||||||
|
</time>
|
||||||
|
)}
|
||||||
|
{edited && " · szerkesztve"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// The starter avatars: a gold glyph on a night colour, `<glyph>-<colour>`
|
||||||
|
// (the forum service checks the same lists). With `online`, the green dot.
|
||||||
|
|
||||||
|
export const AVATAR_GLYPHS = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"] as const;
|
||||||
|
export const AVATAR_COLOURS = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"] as const;
|
||||||
|
|
||||||
|
const BACKGROUND: Record<string, string> = {
|
||||||
|
ejkek: "#1c2540",
|
||||||
|
lila: "#2a2342",
|
||||||
|
tenger: "#1d3038",
|
||||||
|
borostyan: "#33291c",
|
||||||
|
rozsa: "#3a2230",
|
||||||
|
erdo: "#1f3326",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const GLYPH_NAMES: Record<string, string> = {
|
||||||
|
hold: "Hold",
|
||||||
|
csillag: "Csillag",
|
||||||
|
nap: "Nap",
|
||||||
|
hullam: "Hullám",
|
||||||
|
level: "Levél",
|
||||||
|
lotusz: "Lótusz",
|
||||||
|
kristaly: "Kristály",
|
||||||
|
toll: "Toll",
|
||||||
|
};
|
||||||
|
|
||||||
|
function Glyph({ name }: { name: string }) {
|
||||||
|
switch (name) {
|
||||||
|
case "hold":
|
||||||
|
return <path d="M23 10A10 10 0 1 0 23 30A8 8 0 1 1 23 10Z" className="av-fill" />;
|
||||||
|
case "csillag":
|
||||||
|
return <path d="M20 9 L22.5 17.5 L31 20 L22.5 22.5 L20 31 L17.5 22.5 L9 20 L17.5 17.5 Z" className="av-fill" />;
|
||||||
|
case "nap":
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<circle cx="20" cy="20" r="5" className="av-fill" />
|
||||||
|
<path d="M20 8v4M20 28v4M8 20h4M28 20h4M11.5 11.5l2.8 2.8M25.7 25.7l2.8 2.8M28.5 11.5l-2.8 2.8M14.3 25.7l-2.8 2.8" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
case "hullam":
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<path d="M9 18 q5.5-6 11 0 t11 0" />
|
||||||
|
<path d="M12 25 q4-4 8 0 t8 0" opacity="0.6" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
case "level":
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<path d="M12 28 C12 16 20 11 29 11 C29 20 24 28 12 28 Z" />
|
||||||
|
<path d="M12 28 L22 18" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
case "lotusz":
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<path d="M20 11c3 4 3 9 0 14c-3-5-3-10 0-14z" />
|
||||||
|
<path d="M20 25c-4-1-8-4-9-9c4 0 7 3 9 9zM20 25c4-1 8-4 9-9c-4 0-7 3-9 9z" />
|
||||||
|
<path d="M12 29h16" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
case "kristaly":
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<path d="M20 9l7 9-7 13-7-13z" />
|
||||||
|
<path d="M13 18h14" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<path d="M28 10c-8 1-13 7-15 18l3-1c1-6 5-11 12-17z" />
|
||||||
|
<path d="M13 29l9-11" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Avatar({
|
||||||
|
avatar,
|
||||||
|
size = 40,
|
||||||
|
online = false,
|
||||||
|
}: {
|
||||||
|
avatar: string | null | undefined;
|
||||||
|
size?: number;
|
||||||
|
online?: boolean;
|
||||||
|
}) {
|
||||||
|
const [glyph, colour] = (avatar ?? "hold-ejkek").split("-");
|
||||||
|
return (
|
||||||
|
<span className="av" style={{ width: size, height: size }}>
|
||||||
|
<svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
|
||||||
|
<circle cx="20" cy="20" r="20" fill={BACKGROUND[colour] ?? BACKGROUND.ejkek} />
|
||||||
|
<g className="av-glyph">
|
||||||
|
<Glyph name={glyph} />
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
{online && <span className="av-online" title="Most online" />}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRef, useState } from "react";
|
||||||
|
|
||||||
|
import { EMOJI } from "@/lib/forum";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The text box with an emoji tray (phones have emoji on the keyboard; the
|
||||||
|
* tray is mostly for computers) and the send button.
|
||||||
|
*/
|
||||||
|
export function Composer({
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
placeholder,
|
||||||
|
initial = "",
|
||||||
|
submitLabel = "Küldés",
|
||||||
|
busy,
|
||||||
|
onSubmit,
|
||||||
|
onCancel,
|
||||||
|
rows = 3,
|
||||||
|
autoFocus = false,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
placeholder?: string;
|
||||||
|
initial?: string;
|
||||||
|
submitLabel?: string;
|
||||||
|
busy: boolean;
|
||||||
|
onSubmit: (text: string) => Promise<boolean>;
|
||||||
|
onCancel?: () => void;
|
||||||
|
rows?: number;
|
||||||
|
autoFocus?: boolean;
|
||||||
|
}) {
|
||||||
|
const [text, setText] = useState(initial);
|
||||||
|
const [tray, setTray] = useState(false);
|
||||||
|
const area = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
function insert(emoji: string) {
|
||||||
|
const el = area.current;
|
||||||
|
if (!el) {
|
||||||
|
setText((t) => t + emoji);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const start = el.selectionStart ?? text.length;
|
||||||
|
const end = el.selectionEnd ?? text.length;
|
||||||
|
const next = text.slice(0, start) + emoji + text.slice(end);
|
||||||
|
setText(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
el.focus();
|
||||||
|
el.setSelectionRange(start + emoji.length, start + emoji.length);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!text.trim() || busy) return;
|
||||||
|
if (await onSubmit(text)) {
|
||||||
|
setText("");
|
||||||
|
setTray(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="fc" onSubmit={submit}>
|
||||||
|
<label htmlFor={id} className="sr-only">
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id={id}
|
||||||
|
ref={area}
|
||||||
|
className="fc-text"
|
||||||
|
rows={rows}
|
||||||
|
placeholder={placeholder}
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
maxLength={10000}
|
||||||
|
autoFocus={autoFocus}
|
||||||
|
/>
|
||||||
|
{tray && (
|
||||||
|
<div className="fc-tray" role="group" aria-label="Emoji">
|
||||||
|
{EMOJI.map((e) => (
|
||||||
|
<button key={e} type="button" className="fc-emoji" onClick={() => insert(e)} aria-label={`${e} beszúrása`}>
|
||||||
|
{e}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="fc-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="fc-icon-btn"
|
||||||
|
aria-label="Emoji"
|
||||||
|
aria-expanded={tray}
|
||||||
|
onClick={() => setTray((t) => !t)}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<circle cx="12" cy="12" r="9" />
|
||||||
|
<path d="M8.5 14.5a4 4 0 0 0 7 0" />
|
||||||
|
<path d="M9 9.5h.01M15 9.5h.01" strokeWidth="2.6" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<span className="fc-spacer" />
|
||||||
|
{onCancel && (
|
||||||
|
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
|
||||||
|
Mégse
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || !text.trim()}>
|
||||||
|
{busy ? "Küldés…" : submitLabel}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
|
||||||
|
/** Every minute while the page is in front: keeps the member's online dot. */
|
||||||
|
function usePresence(member: boolean) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (!member) return;
|
||||||
|
const ping = () => {
|
||||||
|
if (document.visibilityState === "visible") api("/forum/presence", { method: "POST" }).catch(() => {});
|
||||||
|
};
|
||||||
|
const timer = window.setInterval(ping, 60_000);
|
||||||
|
document.addEventListener("visibilitychange", ping);
|
||||||
|
return () => {
|
||||||
|
window.clearInterval(timer);
|
||||||
|
document.removeEventListener("visibilitychange", ping);
|
||||||
|
};
|
||||||
|
}, [member]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Icon({ name }: { name: "forum" | "followed" | "new" | "profile" }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true" className="fn-icon">
|
||||||
|
{name === "forum" && (
|
||||||
|
<>
|
||||||
|
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
|
||||||
|
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{name === "followed" && (
|
||||||
|
<>
|
||||||
|
<path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z" />
|
||||||
|
<path d="M10 20.5a2 2 0 0 0 4 0" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{name === "new" && (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="9" />
|
||||||
|
<path d="M12 8v8M8 12h8" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{name === "profile" && (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="8" r="4" />
|
||||||
|
<path d="M4.5 20.5c0-3.8 3.4-6 7.5-6s7.5 2.2 7.5 6" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The forum's own menu: a bar at the bottom of the screen on phones, tabs
|
||||||
|
* above the content on wider screens. `unread`: new replies in followed threads.
|
||||||
|
*/
|
||||||
|
export function ForumNav({ member, loggedIn, unread }: { member: string | null; loggedIn: boolean; unread: number }) {
|
||||||
|
const path = usePathname();
|
||||||
|
usePresence(member !== null);
|
||||||
|
const items = [
|
||||||
|
{
|
||||||
|
href: "/forum",
|
||||||
|
label: "Fórum",
|
||||||
|
icon: "forum" as const,
|
||||||
|
current: path === "/forum" || path.startsWith("/forum/szal"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: loggedIn ? "/forum/kovetett" : "/belepes?vissza=/forum/kovetett",
|
||||||
|
label: "Követett",
|
||||||
|
icon: "followed" as const,
|
||||||
|
current: path.startsWith("/forum/kovetett"),
|
||||||
|
badge: unread,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: loggedIn ? "/forum/uj" : "/belepes?vissza=/forum/uj",
|
||||||
|
label: "Új szál",
|
||||||
|
icon: "new" as const,
|
||||||
|
current: path.startsWith("/forum/uj"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: member
|
||||||
|
? `/forum/tag/${encodeURIComponent(member)}`
|
||||||
|
: loggedIn
|
||||||
|
? "/forum/beallitasok"
|
||||||
|
: "/belepes?vissza=/forum",
|
||||||
|
label: member ? "Profilom" : loggedIn ? "Álnév" : "Belépés",
|
||||||
|
icon: "profile" as const,
|
||||||
|
current: path.startsWith("/forum/tag/") || path.startsWith("/forum/beallitasok"),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<nav className="forum-nav" aria-label="Fórum menü">
|
||||||
|
{items.map((item) => (
|
||||||
|
<Link key={item.label} href={item.href} aria-current={item.current ? "page" : undefined} className="fn-item">
|
||||||
|
<span className="fn-icon-wrap">
|
||||||
|
<Icon name={item.icon} />
|
||||||
|
{item.badge ? (
|
||||||
|
<span className="fn-badge" aria-label={`${item.badge} új`}>
|
||||||
|
{item.badge > 99 ? "99+" : item.badge}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
<span className="fn-label">{item.label}</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/** A post's text: paragraphs and line breaks as typed; links stay plain text. */
|
||||||
|
export function PostBody({ text }: { text: string }) {
|
||||||
|
return (
|
||||||
|
<div className="fp-body">
|
||||||
|
{text.split(/\n{2,}/).map((para, i) => (
|
||||||
|
<p key={i}>
|
||||||
|
{para.split("\n").map((line, j) => (
|
||||||
|
<span key={j}>
|
||||||
|
{j > 0 && <br />}
|
||||||
|
{line}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { FORUM_THEME_COOKIE, type ForumTheme } from "@/lib/forum";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Light (the forum's default) or dark. Remembered in a cookie, so the server
|
||||||
|
* renders the chosen one and nothing flashes on load.
|
||||||
|
*/
|
||||||
|
export function ThemeToggle({ initial }: { initial: ForumTheme }) {
|
||||||
|
const [theme, setTheme] = useState<ForumTheme>(initial);
|
||||||
|
const next: ForumTheme = theme === "light" ? "dark" : "light";
|
||||||
|
|
||||||
|
function toggle() {
|
||||||
|
document.cookie = `${FORUM_THEME_COOKIE}=${next}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`;
|
||||||
|
document.querySelector<HTMLElement>(".forum")?.setAttribute("data-theme", next);
|
||||||
|
setTheme(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="forum-theme"
|
||||||
|
onClick={toggle}
|
||||||
|
aria-label={next === "dark" ? "Sötét téma" : "Világos téma"}
|
||||||
|
title={next === "dark" ? "Sötét téma" : "Világos téma"}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
{next === "dark" ? (
|
||||||
|
<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="4" />
|
||||||
|
<path d="M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.3 5.3l1.4 1.4M17.3 17.3l1.4 1.4M5.3 18.7l1.4-1.4M17.3 6.7l1.4-1.4" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
<span className="forum-theme-label">{next === "dark" ? "Sötét" : "Világos"}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum";
|
||||||
|
|
||||||
|
import { Avatar } from "./Avatar";
|
||||||
|
|
||||||
|
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
|
||||||
|
if (!intent) return null;
|
||||||
|
const text = long ? INTENTS[intent].label : INTENTS[intent].short;
|
||||||
|
return <span className={`ft-intent ft-intent-${intent}`}>{text}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function UnreadPill({ n }: { n: number | null }) {
|
||||||
|
if (n === null) return null;
|
||||||
|
if (n === 0) return <span className="ft-read">olvasva</span>;
|
||||||
|
return <span className="ft-new">{n > 99 ? "99+" : n} új</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Threads in a list: title, topic, replies, the starter, what is new. */
|
||||||
|
export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) {
|
||||||
|
return (
|
||||||
|
<ul className="ft-list">
|
||||||
|
{threads.map((t) => (
|
||||||
|
<li key={t.id}>
|
||||||
|
<Link href={threadHref(t)} className="ft-row">
|
||||||
|
<span className="ft-main">
|
||||||
|
<span className="ft-title">
|
||||||
|
{t.pinned && <span className="ft-pin">Kitűzve</span>}
|
||||||
|
{t.locked && <span className="ft-pin">Lezárva</span>}
|
||||||
|
{t.title}
|
||||||
|
</span>
|
||||||
|
<span className="ft-meta">
|
||||||
|
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
|
||||||
|
<span>
|
||||||
|
{t.author?.nickname ?? "Törölt tag"}
|
||||||
|
{showTopic && ` · ${t.topic.name}`}
|
||||||
|
<span className="ft-m-narrow">
|
||||||
|
{" "}
|
||||||
|
· {t.reply_count} válasz ·{" "}
|
||||||
|
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
||||||
|
{ago(t.last_post_at)}
|
||||||
|
</time>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span className="ft-col ft-col-replies">
|
||||||
|
<strong>{t.reply_count}</strong> válasz
|
||||||
|
{t.participants > 1 && <span className="hint">{t.participants} résztvevő</span>}
|
||||||
|
</span>
|
||||||
|
<span className="ft-col ft-col-last">
|
||||||
|
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
||||||
|
{ago(t.last_post_at)}
|
||||||
|
</time>
|
||||||
|
</span>
|
||||||
|
<UnreadPill n={t.unread} />
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Várják a válaszod": a thread without replies, with the starter's wish and a reply button. */
|
||||||
|
export function WaitingCard({ thread }: { thread: ThreadCard }) {
|
||||||
|
return (
|
||||||
|
<article className="ft-waiting">
|
||||||
|
<IntentTag intent={thread.intent} long />
|
||||||
|
<Link href={threadHref(thread)} className="ft-waiting-title">
|
||||||
|
{thread.title}
|
||||||
|
</Link>
|
||||||
|
<span className="ft-meta">
|
||||||
|
{thread.author && <Avatar avatar={thread.author.avatar} size={24} online={thread.author.online} />}
|
||||||
|
<span>
|
||||||
|
{thread.author?.nickname ?? "Törölt tag"} · {thread.topic.name} ·{" "}
|
||||||
|
<time suppressHydrationWarning dateTime={thread.created_at}>
|
||||||
|
{ago(thread.created_at)}
|
||||||
|
</time>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<Link href={`${threadHref(thread)}#valasz`} className="btn btn-sm ft-answer">
|
||||||
|
Válaszolok
|
||||||
|
</Link>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,632 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { type ForumPost, INTENTS, REACTIONS, type ReactionKind, type ThreadPage, memberHref } from "@/lib/forum";
|
||||||
|
|
||||||
|
import { AuthorLine, signsText } from "./AuthorLine";
|
||||||
|
import { Avatar } from "./Avatar";
|
||||||
|
import { Composer } from "./Composer";
|
||||||
|
import { PostBody } from "./PostBody";
|
||||||
|
|
||||||
|
/** How often the open thread looks for new replies (while the page is in front). */
|
||||||
|
const POLL_MS = 30_000;
|
||||||
|
|
||||||
|
type Actions = {
|
||||||
|
busy: boolean;
|
||||||
|
react: (post: ForumPost, kind: ReactionKind | "down") => void;
|
||||||
|
replyTo: (post: ForumPost) => void;
|
||||||
|
edit: (post: ForumPost, body: string) => Promise<boolean>;
|
||||||
|
remove: (post: ForumPost) => void;
|
||||||
|
restore: (post: ForumPost) => void;
|
||||||
|
helped: (post: ForumPost) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
function ReactionGrid({ post, enabled, onReact }: { post: ForumPost; enabled: boolean; onReact: Actions["react"] }) {
|
||||||
|
return (
|
||||||
|
<div className="fr-grid" role="group" aria-label="Reakciók">
|
||||||
|
{REACTIONS.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.kind}
|
||||||
|
type="button"
|
||||||
|
className="fr-big"
|
||||||
|
aria-pressed={post.mine === r.kind}
|
||||||
|
disabled={!enabled}
|
||||||
|
onClick={() => onReact(post, r.kind)}
|
||||||
|
>
|
||||||
|
<span aria-hidden="true">{r.emoji}</span>
|
||||||
|
<span className="fr-big-label">{r.label}</span>
|
||||||
|
<span className="fr-count">{post.reactions[r.kind]}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ReactionRow({
|
||||||
|
post,
|
||||||
|
enabled,
|
||||||
|
canDownvote,
|
||||||
|
onReact,
|
||||||
|
}: {
|
||||||
|
post: ForumPost;
|
||||||
|
enabled: boolean;
|
||||||
|
canDownvote: boolean;
|
||||||
|
onReact: Actions["react"];
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const given = REACTIONS.filter((r) => post.reactions[r.kind] > 0 || post.mine === r.kind);
|
||||||
|
return (
|
||||||
|
<div className="fr-row" role="group" aria-label="Reakciók">
|
||||||
|
{given.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.kind}
|
||||||
|
type="button"
|
||||||
|
className="fr-chip"
|
||||||
|
aria-pressed={post.mine === r.kind}
|
||||||
|
aria-label={`${r.label}, ${post.reactions[r.kind]}`}
|
||||||
|
disabled={!enabled}
|
||||||
|
onClick={() => onReact(post, r.kind)}
|
||||||
|
>
|
||||||
|
{r.emoji} {post.reactions[r.kind]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{enabled && (
|
||||||
|
<span className="fr-more">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="fr-chip fr-add"
|
||||||
|
aria-label="Reakció hozzáadása"
|
||||||
|
aria-expanded={open}
|
||||||
|
onClick={() => setOpen((o) => !o)}
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
{open && (
|
||||||
|
<span className="fr-pop" role="menu">
|
||||||
|
{REACTIONS.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.kind}
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className="fr-pop-item"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
onReact(post, r.kind);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span aria-hidden="true">{r.emoji}</span> {r.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{canDownvote && enabled && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="fr-chip fr-down"
|
||||||
|
aria-pressed={post.mine === "down"}
|
||||||
|
aria-label="Nem visz előre"
|
||||||
|
title="Nem visz előre"
|
||||||
|
onClick={() => onReact(post, "down")}
|
||||||
|
>
|
||||||
|
⌄
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The author column of wide screens: avatar, nickname, rank, badges, signs one per line. */
|
||||||
|
function AuthorPanel({ author, starter }: { author: ForumPost["author"]; starter: boolean }) {
|
||||||
|
if (!author) {
|
||||||
|
return (
|
||||||
|
<aside className="fp-author">
|
||||||
|
<Avatar avatar={null} size={56} />
|
||||||
|
<span className="fp-author-name muted">Törölt tag</span>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const signs = signsText(author.signs);
|
||||||
|
return (
|
||||||
|
<aside className="fp-author">
|
||||||
|
<Link href={memberHref(author.nickname)} tabIndex={-1} aria-hidden="true">
|
||||||
|
<Avatar avatar={author.avatar} size={56} online={author.online} />
|
||||||
|
</Link>
|
||||||
|
<Link href={memberHref(author.nickname)} className="fp-author-name">
|
||||||
|
{author.nickname}
|
||||||
|
</Link>
|
||||||
|
{author.online && <span className="sr-only">(online)</span>}
|
||||||
|
<span className="fa-rank">{author.rank_name}</span>
|
||||||
|
{author.moderator && <span className="fa-badge fa-badge-mod">Moderátor</span>}
|
||||||
|
{starter && <span className="fa-badge fa-badge-starter">Szálindító</span>}
|
||||||
|
{signs && (
|
||||||
|
<span className="fp-author-signs sym">
|
||||||
|
{signs.split(" · ").map((line) => (
|
||||||
|
<span key={line}>{line}</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PostCard({
|
||||||
|
post,
|
||||||
|
page,
|
||||||
|
actions,
|
||||||
|
isNew,
|
||||||
|
}: {
|
||||||
|
post: ForumPost;
|
||||||
|
page: ThreadPage;
|
||||||
|
actions: Actions;
|
||||||
|
isNew: boolean;
|
||||||
|
}) {
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [showCollapsed, setShowCollapsed] = useState(false);
|
||||||
|
const { viewer, thread, access } = page;
|
||||||
|
const writer = viewer.member !== null && !viewer.member.banned;
|
||||||
|
const starter = post.author !== null && post.author.nickname === thread.author?.nickname;
|
||||||
|
const canReact = writer && !post.own && !post.deleted && !thread.locked;
|
||||||
|
|
||||||
|
if (post.deleted && !viewer.moderator) {
|
||||||
|
return (
|
||||||
|
<article className="fp fp-removed" id={`h${post.id}`}>
|
||||||
|
<span>
|
||||||
|
{post.deleted.by_moderator
|
||||||
|
? "A moderátor eltávolította ezt a hozzászólást."
|
||||||
|
: "A szerző törölte ezt a hozzászólást."}
|
||||||
|
</span>
|
||||||
|
{post.deleted.reason && <span className="hint">Ok: {post.deleted.reason}</span>}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article className={post.is_opening ? "fp fp-opening" : "fp"} id={`h${post.id}`}>
|
||||||
|
{/* Wide screens: the old forums' author column. */}
|
||||||
|
<AuthorPanel author={post.author} starter={starter && !post.is_opening} />
|
||||||
|
<div className="fp-content">
|
||||||
|
<div className="fp-head">
|
||||||
|
<AuthorLine
|
||||||
|
author={post.author}
|
||||||
|
size={post.is_opening ? 44 : 36}
|
||||||
|
time={post.created_at}
|
||||||
|
edited={post.edited_at !== null}
|
||||||
|
badges={
|
||||||
|
<>
|
||||||
|
{starter && !post.is_opening && <span className="fa-badge fa-badge-starter">Szálindító</span>}
|
||||||
|
{isNew && <span className="fa-badge fa-badge-new">új</span>}
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="fp-when">
|
||||||
|
<time suppressHydrationWarning dateTime={post.created_at}>
|
||||||
|
{new Date(post.created_at).toLocaleString("hu-HU", {
|
||||||
|
timeZone: "Europe/Budapest",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})}
|
||||||
|
</time>
|
||||||
|
{post.edited_at && " · szerkesztve"}
|
||||||
|
{isNew && <span className="fa-badge fa-badge-new">új</span>}
|
||||||
|
</p>
|
||||||
|
{post.deleted && (
|
||||||
|
<p className="fp-mod-note">
|
||||||
|
Eltávolítva{post.deleted.reason ? ` (ok: ${post.deleted.reason})` : " a szerző által"}. Csak a moderátorok
|
||||||
|
látják.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{post.collapsed && !showCollapsed ? (
|
||||||
|
<button type="button" className="fp-collapsed" onClick={() => setShowCollapsed(true)}>
|
||||||
|
Sokan jelezték, hogy ez nem visz előre. Megjelenítés
|
||||||
|
</button>
|
||||||
|
) : editing ? (
|
||||||
|
<Composer
|
||||||
|
id={`szerk-${post.id}`}
|
||||||
|
label="Hozzászólás szerkesztése"
|
||||||
|
initial={post.body ?? ""}
|
||||||
|
submitLabel="Mentés"
|
||||||
|
busy={actions.busy}
|
||||||
|
autoFocus
|
||||||
|
onCancel={() => setEditing(false)}
|
||||||
|
onSubmit={async (text) => {
|
||||||
|
const ok = await actions.edit(post, text);
|
||||||
|
if (ok) setEditing(false);
|
||||||
|
return ok;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
post.body !== null && <PostBody text={post.body} />
|
||||||
|
)}
|
||||||
|
{post.helped && (
|
||||||
|
<p className="fp-helped">
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M5 12.5l4.5 4.5L19 7.5" />
|
||||||
|
</svg>
|
||||||
|
{thread.author?.nickname ?? "A szál indítója"} szerint ez segített
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!post.deleted && !editing && (
|
||||||
|
<>
|
||||||
|
{post.is_opening ? (
|
||||||
|
<ReactionGrid post={post} enabled={canReact} onReact={actions.react} />
|
||||||
|
) : (
|
||||||
|
<div className="fp-actions">
|
||||||
|
<ReactionRow
|
||||||
|
post={post}
|
||||||
|
enabled={canReact}
|
||||||
|
canDownvote={access?.can_downvote ?? false}
|
||||||
|
onReact={actions.react}
|
||||||
|
/>
|
||||||
|
<span className="fp-spacer" />
|
||||||
|
{access?.can_reply && writer && (
|
||||||
|
<button type="button" className="fp-link" onClick={() => actions.replyTo(post)}>
|
||||||
|
Válasz
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="fp-tools">
|
||||||
|
{access?.is_thread_author && !post.is_opening && !post.own && writer && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="fp-tool"
|
||||||
|
onClick={() => actions.helped(post)}
|
||||||
|
aria-pressed={post.helped}
|
||||||
|
>
|
||||||
|
{post.helped ? "Segített ✓" : "Ez segített"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{post.own && writer && !thread.locked && (
|
||||||
|
<button type="button" className="fp-tool" onClick={() => setEditing(true)}>
|
||||||
|
Szerkesztés
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{post.own && (
|
||||||
|
<button type="button" className="fp-tool" onClick={() => actions.remove(post)}>
|
||||||
|
Törlés
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{viewer.moderator && !post.own && (
|
||||||
|
<button type="button" className="fp-tool fp-tool-mod" onClick={() => actions.remove(post)}>
|
||||||
|
Eltávolítás
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{viewer.moderator && typeof post.down === "number" && post.down > 0 && (
|
||||||
|
<span className="hint">⌄ {post.down}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{post.deleted && viewer.moderator && (
|
||||||
|
<div className="fp-tools">
|
||||||
|
<button type="button" className="fp-tool" onClick={() => actions.restore(post)}>
|
||||||
|
Visszaállítás (admin)
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The thread page: posts, reactions, replies, read marks, new replies while open. */
|
||||||
|
export function ThreadView({ initial }: { initial: ThreadPage }) {
|
||||||
|
const [page, setPage] = useState(initial);
|
||||||
|
const [incoming, setIncoming] = useState<ThreadPage | null>(null);
|
||||||
|
const [replyTo, setReplyTo] = useState<ForumPost | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
// Where the visitor stopped reading when they opened the page.
|
||||||
|
const [readUpTo] = useState(initial.access?.last_read_post_id ?? null);
|
||||||
|
const composer = useRef<HTMLDivElement>(null);
|
||||||
|
const { viewer, thread, access } = page;
|
||||||
|
const member = viewer.member !== null;
|
||||||
|
const base = `/forum/threads/${thread.id}`;
|
||||||
|
|
||||||
|
const lastId = page.posts.length ? page.posts[page.posts.length - 1].id : 0;
|
||||||
|
|
||||||
|
// Mark read up to the newest post shown.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!member || lastId === 0) return;
|
||||||
|
api(`${base}/read`, { body: { post_id: lastId } }).catch(() => {});
|
||||||
|
}, [member, lastId, base]);
|
||||||
|
|
||||||
|
// New replies while the page is open: offered, not pushed into the text being read.
|
||||||
|
const poll = useCallback(async () => {
|
||||||
|
if (document.visibilityState !== "visible" || thread.deleted) return;
|
||||||
|
try {
|
||||||
|
const fresh = await api<ThreadPage>(base);
|
||||||
|
const freshLast = fresh.posts.length ? fresh.posts[fresh.posts.length - 1].id : 0;
|
||||||
|
if (freshLast > lastId) setIncoming(fresh);
|
||||||
|
} catch {
|
||||||
|
/* a missed poll is retried later */
|
||||||
|
}
|
||||||
|
}, [base, lastId, thread.deleted]);
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = window.setInterval(poll, POLL_MS);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [poll]);
|
||||||
|
|
||||||
|
const newCount = incoming ? incoming.posts.filter((p) => p.id > lastId && !p.own).length : 0;
|
||||||
|
|
||||||
|
async function run<T>(work: () => Promise<T>): Promise<T | null> {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
return await work();
|
||||||
|
} catch (e) {
|
||||||
|
setError(errorText(e));
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const replacePost = useCallback((post: ForumPost) => {
|
||||||
|
setPage((p) => ({ ...p, posts: p.posts.map((x) => (x.id === post.id ? post : x)) }));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const reload = useCallback(async () => {
|
||||||
|
const fresh = await api<ThreadPage>(base);
|
||||||
|
setPage(fresh);
|
||||||
|
setIncoming(null);
|
||||||
|
}, [base]);
|
||||||
|
|
||||||
|
const actions: Actions = {
|
||||||
|
busy,
|
||||||
|
react: (post, kind) =>
|
||||||
|
void run(async () => {
|
||||||
|
const updated =
|
||||||
|
post.mine === kind
|
||||||
|
? await api<ForumPost>(`/forum/posts/${post.id}/reaction`, { method: "DELETE" })
|
||||||
|
: await api<ForumPost>(`/forum/posts/${post.id}/reaction`, { method: "PUT", body: { kind } });
|
||||||
|
replacePost(updated);
|
||||||
|
}),
|
||||||
|
replyTo: (post) => {
|
||||||
|
setReplyTo(post);
|
||||||
|
composer.current?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||||
|
},
|
||||||
|
edit: async (post, body) => {
|
||||||
|
const updated = await run(() => api<ForumPost>(`/forum/posts/${post.id}`, { method: "PATCH", body: { body } }));
|
||||||
|
if (updated) replacePost(updated);
|
||||||
|
return updated !== null;
|
||||||
|
},
|
||||||
|
remove: (post) => {
|
||||||
|
let reason: string | null = null;
|
||||||
|
if (post.own) {
|
||||||
|
if (!window.confirm("Biztosan törlöd a hozzászólásodat?")) return;
|
||||||
|
} else {
|
||||||
|
reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik.");
|
||||||
|
if (!reason) return;
|
||||||
|
}
|
||||||
|
void run(async () => {
|
||||||
|
await api(`/forum/posts/${post.id}`, { method: "DELETE", body: { reason } });
|
||||||
|
await reload();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
restore: (post) =>
|
||||||
|
void run(async () => {
|
||||||
|
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
|
||||||
|
await reload();
|
||||||
|
}),
|
||||||
|
helped: (post) =>
|
||||||
|
void run(async () => {
|
||||||
|
const updated = await api<ForumPost>(`/forum/posts/${post.id}/helped`, {
|
||||||
|
method: post.helped ? "DELETE" : "PUT",
|
||||||
|
});
|
||||||
|
replacePost(updated);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
async function sendReply(text: string): Promise<boolean> {
|
||||||
|
const post = await run(() =>
|
||||||
|
api<ForumPost>(`${base}/posts`, { body: { body: text, parent_id: replyTo?.id ?? null } }),
|
||||||
|
);
|
||||||
|
if (!post) return false;
|
||||||
|
setReplyTo(null);
|
||||||
|
await reload().catch(() => setPage((p) => ({ ...p, posts: [...p.posts, post] })));
|
||||||
|
requestAnimationFrame(() => document.getElementById(`h${post.id}`)?.scrollIntoView({ block: "center" }));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleFollow() {
|
||||||
|
const following = access?.following ?? false;
|
||||||
|
await run(() => api(`${base}/follow`, { method: following ? "DELETE" : "PUT" }));
|
||||||
|
setPage((p) => (p.access ? { ...p, access: { ...p.access, following: !following } } : p));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function moderateThread(change: { locked?: boolean; pinned?: boolean }) {
|
||||||
|
await run(() => api(base, { method: "PATCH", body: change }));
|
||||||
|
await reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeThread() {
|
||||||
|
const reason = window.prompt("Miért távolítod el az egész szálat? Az indoklás látszik a helyén.");
|
||||||
|
if (!reason) return;
|
||||||
|
await run(() => api(base, { method: "DELETE", body: { reason } }));
|
||||||
|
await reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
const opening = page.posts.find((p) => p.is_opening);
|
||||||
|
const replies = useMemo(() => page.posts.filter((p) => !p.is_opening), [page.posts]);
|
||||||
|
const tops = replies.filter((p) => p.parent_id === null);
|
||||||
|
const childrenOf = (id: number) => replies.filter((p) => p.parent_id === id);
|
||||||
|
// "Itt hagytad abba": before the first post by someone else after the last visit.
|
||||||
|
const firstUnread = readUpTo !== null ? (replies.find((p) => p.id > readUpTo && !p.own)?.id ?? null) : null;
|
||||||
|
const unreadCount = firstUnread !== null ? replies.filter((p) => p.id >= firstUnread && !p.own).length : 0;
|
||||||
|
const topOf = (id: number) => {
|
||||||
|
const p = replies.find((x) => x.id === id);
|
||||||
|
return p?.parent_id ?? id;
|
||||||
|
};
|
||||||
|
const markerTop = firstUnread !== null ? topOf(firstUnread) : null;
|
||||||
|
const intent = thread.intent ? INTENTS[thread.intent] : null;
|
||||||
|
const starter = thread.author?.nickname ?? "A szál indítója";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ftv">
|
||||||
|
<nav className="forum-crumbs" aria-label="Morzsamenü">
|
||||||
|
<Link href="/forum">Fórum</Link>
|
||||||
|
<span aria-hidden="true">›</span>
|
||||||
|
<Link href={`/forum/${thread.topic.slug}`}>{thread.topic.name}</Link>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div className="ftv-toolbar">
|
||||||
|
{member && access && (
|
||||||
|
<button type="button" className="btn btn-sm" aria-pressed={access.following} onClick={toggleFollow}>
|
||||||
|
{access.following ? "Követem ✓" : "Követem"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{viewer.moderator && !thread.deleted && (
|
||||||
|
<details className="ftv-mod">
|
||||||
|
<summary className="btn btn-sm btn-ghost">Moderálás</summary>
|
||||||
|
<div className="ftv-mod-menu">
|
||||||
|
<button type="button" onClick={() => moderateThread({ locked: !thread.locked })}>
|
||||||
|
{thread.locked ? "Szál feloldása" : "Szál lezárása"}
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={() => moderateThread({ pinned: !thread.pinned })}>
|
||||||
|
{thread.pinned ? "Kitűzés levétele" : "Kitűzés"}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="danger" onClick={removeThread}>
|
||||||
|
Szál eltávolítása
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{thread.deleted ? (
|
||||||
|
<div className="fp fp-removed">
|
||||||
|
<span>A moderátor eltávolította ezt a szálat.</span>
|
||||||
|
{thread.deleted.reason && <span className="hint">Ok: {thread.deleted.reason}</span>}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{intent && thread.intent === "listen" && (
|
||||||
|
<div className="ftv-intent">
|
||||||
|
<strong>{intent.label}</strong>
|
||||||
|
<span>{starter} most nem kér tanácsot. Elég, ha jelen vagy, és leírod, ha veled is történt hasonló.</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{intent && thread.intent === "advice" && (
|
||||||
|
<div className="ftv-intent ftv-intent-advice">
|
||||||
|
<strong>{intent.label}</strong>
|
||||||
|
<span>{starter} kíváncsi a véleményetekre és a tapasztalataitokra.</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<h1 className="ftv-title">
|
||||||
|
{thread.pinned && <span className="ft-pin">Kitűzve</span>}
|
||||||
|
{thread.locked && <span className="ft-pin">Lezárva</span>}
|
||||||
|
{thread.title}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
{opening && <PostCard post={opening} page={page} actions={actions} isNew={false} />}
|
||||||
|
|
||||||
|
{(replies.length > 0 || !thread.deleted) && (
|
||||||
|
<div className="ftv-count">
|
||||||
|
<h2>{replies.filter((p) => !p.deleted).length} válasz</h2>
|
||||||
|
<span className="hint">időrendben</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tops.map((top) => (
|
||||||
|
<div key={top.id} className="ftv-branch">
|
||||||
|
{markerTop === top.id && (
|
||||||
|
<div className="ftv-marker" role="separator" aria-label={`Itt hagytad abba, ${unreadCount} új`}>
|
||||||
|
<span>Itt hagytad abba · {unreadCount} új</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<PostCard
|
||||||
|
post={top}
|
||||||
|
page={page}
|
||||||
|
actions={actions}
|
||||||
|
isNew={firstUnread !== null && top.id >= firstUnread && !top.own}
|
||||||
|
/>
|
||||||
|
{childrenOf(top.id).length > 0 && (
|
||||||
|
<div className="ftv-children">
|
||||||
|
{childrenOf(top.id).map((child) => (
|
||||||
|
<PostCard
|
||||||
|
key={child.id}
|
||||||
|
post={child}
|
||||||
|
page={page}
|
||||||
|
actions={actions}
|
||||||
|
isNew={firstUnread !== null && child.id >= firstUnread && !child.own}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{newCount > 0 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="ftv-incoming"
|
||||||
|
onClick={() => incoming && (setPage(incoming), setIncoming(null))}
|
||||||
|
>
|
||||||
|
{newCount === 1 ? "1 új válasz érkezett" : `${newCount} új válasz érkezett`}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="ftv-compose" id="valasz" ref={composer}>
|
||||||
|
{thread.deleted ? null : !viewer.logged_in ? (
|
||||||
|
<p className="ftv-gate">
|
||||||
|
<Link href={`/belepes?vissza=/forum/szal/${thread.id}-${thread.slug}`}>Lépj be</Link>, hogy hozzászólhass.
|
||||||
|
</p>
|
||||||
|
) : viewer.needs_nickname ? (
|
||||||
|
<p className="ftv-gate">
|
||||||
|
<Link href={`/forum/beallitasok?vissza=/forum/szal/${thread.id}-${thread.slug}`}>Válassz álnevet</Link>,
|
||||||
|
hogy hozzászólhass.
|
||||||
|
</p>
|
||||||
|
) : viewer.member?.banned ? (
|
||||||
|
<p className="ftv-gate">Most nem írhatsz a fórumba.</p>
|
||||||
|
) : !access?.can_reply ? (
|
||||||
|
<p className="ftv-gate">Ez a szál le van zárva, új hozzászólás nem írható.</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{thread.intent === "listen" && (
|
||||||
|
<p className="ftv-hint">
|
||||||
|
{starter} meghallgatást kér: tanács helyett írd le, ha veled is történt hasonló, vagy csak azt, hogy itt
|
||||||
|
vagy.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{replyTo && (
|
||||||
|
<p className="ftv-replyto">
|
||||||
|
Válasz neki: <strong>{replyTo.author?.nickname ?? "Törölt tag"}</strong>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="fp-link"
|
||||||
|
onClick={() => setReplyTo(null)}
|
||||||
|
aria-label="Válasz visszavonása"
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Composer
|
||||||
|
id="valasz-szoveg"
|
||||||
|
label="Válaszod"
|
||||||
|
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
|
||||||
|
busy={busy}
|
||||||
|
onSubmit={sendReply}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -58,6 +58,7 @@ export const ROLE_LABELS: Record<string, string> = {
|
|||||||
premium: "Prémium",
|
premium: "Prémium",
|
||||||
vip: "VIP",
|
vip: "VIP",
|
||||||
creator: "Szerző",
|
creator: "Szerző",
|
||||||
|
moderator: "Moderátor",
|
||||||
admin: "Admin",
|
admin: "Admin",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
// The forum's data as the forum service sends it, and small helpers shared
|
||||||
|
// by its server and client components.
|
||||||
|
|
||||||
|
/** The forum's colours: light by default, dark on request (a cookie). */
|
||||||
|
export const FORUM_THEME_COOKIE = "sf_forum_theme";
|
||||||
|
export type ForumTheme = "light" | "dark";
|
||||||
|
|
||||||
|
export type Rank = "vandor" | "kereso" | "fono" | "csillagfono" | "sorsfono";
|
||||||
|
export type ReactionKind = "with_you" | "thanks" | "me_too" | "insight";
|
||||||
|
export type ChartShare = "none" | "sun" | "big3" | "planets";
|
||||||
|
|
||||||
|
/** How a member appears next to what they wrote. */
|
||||||
|
export interface ForumAuthor {
|
||||||
|
nickname: string;
|
||||||
|
avatar: string;
|
||||||
|
rank: Rank;
|
||||||
|
rank_name: string;
|
||||||
|
moderator: boolean;
|
||||||
|
online: boolean;
|
||||||
|
/** Planet (or `ascendant`) → sign, as the member chose to share. */
|
||||||
|
signs: Record<string, string> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForumViewer {
|
||||||
|
logged_in: boolean;
|
||||||
|
needs_nickname: boolean;
|
||||||
|
moderator: boolean;
|
||||||
|
member: { nickname: string; avatar: string; rank: Rank; rank_name: string; banned: boolean } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TopicRef {
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForumTopic extends TopicRef {
|
||||||
|
id: number;
|
||||||
|
description: string;
|
||||||
|
visibility: "public" | "members" | "restricted";
|
||||||
|
listening: boolean;
|
||||||
|
readable: boolean;
|
||||||
|
thread_count?: number;
|
||||||
|
new_count?: number | null;
|
||||||
|
last?: { author: ForumAuthor | null; at: string } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ThreadCard {
|
||||||
|
id: number;
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
intent: "listen" | "advice" | null;
|
||||||
|
topic: TopicRef;
|
||||||
|
author: ForumAuthor | null;
|
||||||
|
created_at: string;
|
||||||
|
last_post_at: string;
|
||||||
|
reply_count: number;
|
||||||
|
participants: number;
|
||||||
|
pinned: boolean;
|
||||||
|
locked: boolean;
|
||||||
|
unread: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForumHome {
|
||||||
|
viewer: ForumViewer;
|
||||||
|
followed: { new_replies: number; threads: number } | null;
|
||||||
|
topics: ForumTopic[];
|
||||||
|
unanswered: ThreadCard[];
|
||||||
|
hot: ThreadCard[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TopicPage {
|
||||||
|
viewer: ForumViewer;
|
||||||
|
topic: TopicRef & { description: string; visibility: string; listening: boolean };
|
||||||
|
threads: ThreadCard[];
|
||||||
|
page: number;
|
||||||
|
has_more: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForumPost {
|
||||||
|
id: number;
|
||||||
|
parent_id: number | null;
|
||||||
|
is_opening: boolean;
|
||||||
|
author: ForumAuthor | null;
|
||||||
|
own: boolean;
|
||||||
|
body: string | null;
|
||||||
|
deleted: { by_moderator: boolean; reason: string | null } | null;
|
||||||
|
created_at: string;
|
||||||
|
edited_at: string | null;
|
||||||
|
helped: boolean;
|
||||||
|
reactions: Record<ReactionKind, number>;
|
||||||
|
score: number;
|
||||||
|
collapsed: boolean;
|
||||||
|
mine: ReactionKind | "down" | null;
|
||||||
|
/** Moderators only. */
|
||||||
|
down?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ThreadPage {
|
||||||
|
viewer: ForumViewer;
|
||||||
|
thread: {
|
||||||
|
id: number;
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
intent: "listen" | "advice" | null;
|
||||||
|
topic: TopicRef & { visibility: string; listening: boolean };
|
||||||
|
author: ForumAuthor | null;
|
||||||
|
created_at: string;
|
||||||
|
locked: boolean;
|
||||||
|
pinned: boolean;
|
||||||
|
deleted: { reason: string | null } | null;
|
||||||
|
};
|
||||||
|
posts: ForumPost[];
|
||||||
|
access?: {
|
||||||
|
can_reply: boolean;
|
||||||
|
can_downvote: boolean;
|
||||||
|
is_thread_author: boolean;
|
||||||
|
following: boolean;
|
||||||
|
last_read_post_id: number | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForumMe {
|
||||||
|
viewer: ForumViewer;
|
||||||
|
member: {
|
||||||
|
nickname: string;
|
||||||
|
avatar: string;
|
||||||
|
bio: string;
|
||||||
|
chart_share: ChartShare;
|
||||||
|
invisible: boolean;
|
||||||
|
points: number;
|
||||||
|
post_count: number;
|
||||||
|
created_at: string;
|
||||||
|
rank: Rank;
|
||||||
|
rank_name: string;
|
||||||
|
next_rank: { rank: Rank; name: string; points: number; days: number } | null;
|
||||||
|
nickname_change_after: string | null;
|
||||||
|
banned_until: string | null;
|
||||||
|
ban_reason: string | null;
|
||||||
|
} | null;
|
||||||
|
chart: Record<Exclude<ChartShare, "none">, Record<string, string> | null> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberProfile {
|
||||||
|
viewer: ForumViewer;
|
||||||
|
member: {
|
||||||
|
author: ForumAuthor;
|
||||||
|
bio: string;
|
||||||
|
created_at: string;
|
||||||
|
post_count: number;
|
||||||
|
thread_count: number;
|
||||||
|
last_seen: "online" | "day" | "week" | "earlier" | null;
|
||||||
|
own: boolean;
|
||||||
|
banned_until: string | null;
|
||||||
|
ban_reason: string | null;
|
||||||
|
};
|
||||||
|
recent: {
|
||||||
|
id: number;
|
||||||
|
thread_id: number;
|
||||||
|
thread_slug: string;
|
||||||
|
thread_title: string;
|
||||||
|
topic: TopicRef;
|
||||||
|
created_at: string;
|
||||||
|
excerpt: string;
|
||||||
|
is_opening: boolean;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModLogEntry {
|
||||||
|
id: number;
|
||||||
|
actor: string | null;
|
||||||
|
actor_kind: "human" | "ai";
|
||||||
|
action: string;
|
||||||
|
target: string | null;
|
||||||
|
thread: { id: number; title: string | null } | null;
|
||||||
|
post_id: number | null;
|
||||||
|
reason: string | null;
|
||||||
|
until: string | null;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const REACTIONS: { kind: ReactionKind; emoji: string; label: string }[] = [
|
||||||
|
{ kind: "with_you", emoji: "🤍", label: "Veled vagyok" },
|
||||||
|
{ kind: "thanks", emoji: "🙏", label: "Köszönöm" },
|
||||||
|
{ kind: "me_too", emoji: "✨", label: "Rám is igaz" },
|
||||||
|
{ kind: "insight", emoji: "💡", label: "Érdekes gondolat" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const INTENTS = {
|
||||||
|
listen: { label: "Csak meghallgatást kér", short: "Meghallgatást kér" },
|
||||||
|
advice: { label: "Tanácsot, véleményt kér", short: "Tanácsot kér" },
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** The emoji offered first in the composer: the Moon, the signs, warmth. */
|
||||||
|
export const EMOJI = [
|
||||||
|
"🙂",
|
||||||
|
"😊",
|
||||||
|
"🤍",
|
||||||
|
"🙏",
|
||||||
|
"✨",
|
||||||
|
"🌙",
|
||||||
|
"🌕",
|
||||||
|
"🌑",
|
||||||
|
"⭐",
|
||||||
|
"🌸",
|
||||||
|
"🍀",
|
||||||
|
"🕯️",
|
||||||
|
"🌿",
|
||||||
|
"☕",
|
||||||
|
"😢",
|
||||||
|
"🤗",
|
||||||
|
"♈",
|
||||||
|
"♉",
|
||||||
|
"♊",
|
||||||
|
"♋",
|
||||||
|
"♌",
|
||||||
|
"♍",
|
||||||
|
"♎",
|
||||||
|
"♏",
|
||||||
|
"♐",
|
||||||
|
"♑",
|
||||||
|
"♒",
|
||||||
|
"♓",
|
||||||
|
];
|
||||||
|
|
||||||
|
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
||||||
|
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
||||||
|
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
||||||
|
return postId ? `${path}#h${postId}` : path;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function memberHref(nickname: string): string {
|
||||||
|
return `/forum/tag/${encodeURIComponent(nickname)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "most", "12 perce", "3 órája", "tegnap", "4 napja", then the date. */
|
||||||
|
export function ago(iso: string, now: Date = new Date()): string {
|
||||||
|
const then = new Date(iso);
|
||||||
|
const minutes = Math.floor((now.getTime() - then.getTime()) / 60000);
|
||||||
|
if (minutes < 1) return "most";
|
||||||
|
if (minutes < 60) return `${minutes} perce`;
|
||||||
|
const hours = Math.floor(minutes / 60);
|
||||||
|
if (hours < 24) return `${hours} órája`;
|
||||||
|
const days = Math.floor(hours / 24);
|
||||||
|
if (days === 1) return "tegnap";
|
||||||
|
if (days < 7) return `${days} napja`;
|
||||||
|
return then.toLocaleDateString("hu-HU", {
|
||||||
|
timeZone: "Europe/Budapest",
|
||||||
|
year: then.getFullYear() === now.getFullYear() ? undefined : "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A ban's end as the member reads it. */
|
||||||
|
export function banText(until: string | null): string {
|
||||||
|
if (!until) return "";
|
||||||
|
if (until === "infinity") return "véglegesen";
|
||||||
|
return `eddig: ${new Date(until).toLocaleString("hu-HU", { timeZone: "Europe/Budapest", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit" })}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// Forum service calls from server components, with the visitor's session.
|
||||||
|
// Without FORUM_URL the forum is switched off (no menu item, its pages 404).
|
||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
|
import { BackendError, SESSION_COOKIE } from "./server";
|
||||||
|
|
||||||
|
export const FORUM_URL = (process.env.FORUM_URL ?? "").replace(/\/$/, "");
|
||||||
|
|
||||||
|
export function forumEnabled(): boolean {
|
||||||
|
return FORUM_URL !== "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The answer of a forum GET: the data, or why there is none. */
|
||||||
|
export type ForumResult<T> = { ok: true; data: T } | { ok: false; status: 401 | 404 };
|
||||||
|
|
||||||
|
/** GET from the forum service as the visitor (logged in or not). */
|
||||||
|
export async function forumGet<T>(path: string): Promise<ForumResult<T>> {
|
||||||
|
if (!forumEnabled()) return { ok: false, status: 404 };
|
||||||
|
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||||
|
const headers: HeadersInit = token ? { authorization: `Bearer ${token}` } : {};
|
||||||
|
const res = await fetch(`${FORUM_URL}${path}`, { headers, cache: "no-store" });
|
||||||
|
if (res.status === 401 || res.status === 404) return { ok: false, status: res.status };
|
||||||
|
// Not allowed (e.g. the moderation log for a member): the page does not exist for them.
|
||||||
|
if (res.status === 403) return { ok: false, status: 404 };
|
||||||
|
if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`);
|
||||||
|
return { ok: true, data: (await res.json()) as T };
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Shapes of the backend responses the frontend uses.
|
// Shapes of the backend responses the frontend uses.
|
||||||
|
|
||||||
export type Role = "admin" | "creator" | "premium" | "vip" | "user";
|
export type Role = "admin" | "creator" | "moderator" | "premium" | "vip" | "user";
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user