diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index f0c3030..6613488 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -60,7 +60,7 @@ jobs: # astro-engine and horoscope-api need the Swiss Ephemeris sources and # data (scripts/fetch-deps.sh); their tests run locally. - name: Test - run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates + run: cargo test --locked -p backend -p worker -p forum -p object-storage -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates build: needs: test @@ -95,6 +95,7 @@ jobs: build horoscope-api -f services/horoscope-api/Dockerfile . build backend -f services/backend/Dockerfile . build worker -f services/worker/Dockerfile . + build forum -f services/forum/Dockerfile . build frontend services/frontend # Only the last 5 commit images of each service stay in the registry, # plus `main`, `prod`, `latest` and the commit running in production @@ -107,7 +108,7 @@ jobs: set -eu apk add --no-cache -q curl jq prod=$(git ls-remote origin refs/heads/prod | cut -c1-12) - for svc in horoscope-api backend worker frontend; do + for svc in horoscope-api backend worker forum frontend; do name="sorsfonalak-$svc" page=1 : > versions.tsv @@ -132,7 +133,7 @@ jobs: if: always() run: | docker logout "$REGISTRY" || true - for svc in horoscope-api backend worker frontend; do + for svc in horoscope-api backend worker forum frontend; do docker images "$IMAGE_PREFIX-$svc" --format '{{.Repository}}:{{.Tag}}' | xargs -r docker rmi >/dev/null 2>&1 || true done docker image prune -f >/dev/null diff --git a/Cargo.lock b/Cargo.lock index 7e4d77f..431ccf4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -109,6 +109,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", @@ -127,8 +128,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1", "sync_wrapper", "tokio", + "tokio-tungstenite", "tower", "tower-layer", "tower-service", @@ -195,6 +198,7 @@ dependencies = [ "http-body-util", "image", "jsonwebtoken", + "object-storage", "password-hash", "rand 0.9.5", "reqwest", @@ -442,6 +446,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -693,6 +703,35 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "forum" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "axum-extra", + "db", + "deunicode", + "futures-util", + "http-body-util", + "image", + "object-storage", + "reqwest", + "serde", + "serde_json", + "service-kit", + "sha2", + "sqlx", + "thiserror", + "time", + "tokio", + "tokio-tungstenite", + "tower", + "tower-http", + "tracing", + "uuid", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1595,6 +1634,20 @@ dependencies = [ "libm", ] +[[package]] +name = "object-storage" +version = "0.1.0" +dependencies = [ + "bytes", + "hmac", + "reqwest", + "sha2", + "thiserror", + "time", + "tokio", + "tracing", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2901,6 +2954,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tower" version = "0.5.3" @@ -3051,6 +3116,22 @@ dependencies = [ "core_maths", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + [[package]] name = "typenum" version = "1.20.1" @@ -3498,6 +3579,7 @@ dependencies = [ "axum", "base64 0.22.1", "db", + "deunicode", "email-templates", "gift-card", "hmac", diff --git a/Cargo.toml b/Cargo.toml index 22a3aae..191c3c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,11 @@ members = [ "crates/analysis-prompt", "crates/email-templates", "crates/gift-card", + "crates/object-storage", "services/horoscope-api", "services/backend", "services/worker", + "services/forum", ] [workspace.package] @@ -31,6 +33,7 @@ horoscope-client = { path = "crates/horoscope-client" } analysis-prompt = { path = "crates/analysis-prompt" } email-templates = { path = "crates/email-templates" } gift-card = { path = "crates/gift-card" } +object-storage = { path = "crates/object-storage" } anyhow = "1" argon2 = { version = "0.5", features = ["std"] } diff --git a/crates/db/migrations/0038_forum.sql b/crates/db/migrations/0038_forum.sql new file mode 100644 index 0000000..c3b5947 --- /dev/null +++ b/crates/db/migrations/0038_forum.sql @@ -0,0 +1,151 @@ +-- The forum (services/forum, docs/kozosseg.md): pseudonymous members, topics, +-- threads, posts, reactions, read marks, followed threads and the moderation +-- log, in a schema of its own. +CREATE SCHEMA forum; + +-- 'moderator': appointed by an admin; may delete posts and threads and ban members. +ALTER TABLE users DROP CONSTRAINT users_roles_valid; +ALTER TABLE users ADD CONSTRAINT users_roles_valid + CHECK (cardinality(roles) > 0 + AND roles <@ ARRAY['admin', 'creator', 'moderator', 'premium', 'vip', 'user']::text[]); + +-- A user who chose a nickname. Nothing here is the real name: the nickname is +-- typed by the user, never taken from the Google or Apple account. +CREATE TABLE forum.members ( + user_id uuid PRIMARY KEY REFERENCES users ON DELETE CASCADE, + nickname text NOT NULL, + -- The nickname folded (no accents, case, spaces or look-alike digits): unique. + nickname_key text NOT NULL UNIQUE, + -- A starter avatar, '-' (the frontend draws it). + avatar text NOT NULL, + bio text NOT NULL DEFAULT '', + -- What the profile shows of the user's own chart: nothing, the Sun sign, + -- Sun, Moon and Ascendant, or every planet's sign. Never degrees. + chart_share text NOT NULL DEFAULT 'none' CHECK (chart_share IN ('none', 'sun', 'big3', 'planets')), + -- Not shown as online. + invisible boolean NOT NULL DEFAULT false, + -- Reactions received (counted ones), "Ez segített" marks; the rank comes from these. + points integer NOT NULL DEFAULT 0, + post_count integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now(), + nickname_changed_at timestamptz NOT NULL DEFAULT now(), + last_seen_at timestamptz, + -- Banned until then (year 9999: for good): may read, not write. + banned_until timestamptz, + ban_reason text +); + +-- A nickname given up stays reserved for a while, so nobody can take over a +-- known member's name. +CREATE TABLE forum.retired_nicknames ( + nickname_key text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + until timestamptz NOT NULL +); + +CREATE TABLE forum.topics ( + id smallint PRIMARY KEY, + slug text NOT NULL UNIQUE, + name text NOT NULL, + description text NOT NULL, + -- public: anyone reads (search engines too); members: logged-in users; + -- restricted: approved members only (not used yet: moderators only). + visibility text NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'members', 'restricted')), + -- A listening topic: no ⌄ there, and new threads ask for listening by default. + listening boolean NOT NULL DEFAULT false, + position smallint NOT NULL +); + +INSERT INTO forum.topics (id, slug, name, description, visibility, listening, position) VALUES + (1, 'ami-a-szivemen-van', 'Ami a szívemen van', 'Meghallgatás, élethelyzetek', 'members', true, 1), + (2, 'belso-utak', 'Belső utak', 'Spiritualitás, meditáció, álmok', 'public', false, 2), + (3, 'egbolt-es-kepletek', 'Égbolt és képletek', 'Asztrológia, megosztott elemzések', 'public', false, 3), + (4, 'torzsasztal', 'Törzsasztal', 'Bármi, ami eszedbe jut', 'public', false, 4); + +CREATE TABLE forum.threads ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + topic_id smallint NOT NULL REFERENCES forum.topics, + -- NULL once the account is deleted (the thread stays, "törölt tag"). + author_id uuid REFERENCES users ON DELETE SET NULL, + title text NOT NULL, + -- What the author asks for: only listening, or advice and opinions. + intent text CHECK (intent IN ('listen', 'advice')), + created_at timestamptz NOT NULL DEFAULT now(), + last_post_at timestamptz NOT NULL DEFAULT now(), + -- Visible replies (the opening post not counted). + reply_count integer NOT NULL DEFAULT 0, + pinned boolean NOT NULL DEFAULT false, + locked boolean NOT NULL DEFAULT false, + deleted_at timestamptz, + deleted_by uuid REFERENCES users ON DELETE SET NULL, + delete_reason text +); +CREATE INDEX threads_topic_idx ON forum.threads (topic_id, pinned DESC, last_post_at DESC) WHERE deleted_at IS NULL; +CREATE INDEX threads_author_idx ON forum.threads (author_id, created_at DESC); + +CREATE TABLE forum.posts ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE, + author_id uuid REFERENCES users ON DELETE SET NULL, + -- A reply to a reply (two levels at most: the parent is never itself a reply). + parent_id bigint REFERENCES forum.posts ON DELETE SET NULL, + is_opening boolean NOT NULL DEFAULT false, + body text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + edited_at timestamptz, + -- The thread's author marked it "Ez segített". + helped_at timestamptz, + -- Hidden, not erased: a moderator's reason shows in its place, an admin can restore it. + deleted_at timestamptz, + deleted_by uuid REFERENCES users ON DELETE SET NULL, + delete_reason text +); +CREATE INDEX posts_thread_idx ON forum.posts (thread_id, id); +CREATE INDEX posts_author_idx ON forum.posts (author_id, created_at DESC); +CREATE INDEX posts_recent_idx ON forum.posts (created_at DESC); +CREATE UNIQUE INDEX posts_opening_key ON forum.posts (thread_id) WHERE is_opening; + +-- One reaction per member and post; each is +1 to the author's points, 'down' (⌄) is -1. +CREATE TABLE forum.reactions ( + post_id bigint NOT NULL REFERENCES forum.posts ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('with_you', 'thanks', 'me_too', 'insight', 'down')), + -- Whether it moved the author's points (a new member's reaction does not). + counted boolean NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (post_id, user_id) +); + +-- How far a member has read a thread ("Itt hagytad abba"). +CREATE TABLE forum.reads ( + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE, + last_post_id bigint NOT NULL, + read_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, thread_id) +); + +-- Followed threads: one's own and the ones replied to, or followed by hand. +CREATE TABLE forum.follows ( + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, thread_id) +); +CREATE INDEX follows_thread_idx ON forum.follows (thread_id); + +-- Every moderation step: who (a person or, later, the AI), what, why. +CREATE TABLE forum.mod_log ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + actor_id uuid REFERENCES users ON DELETE SET NULL, + actor_kind text NOT NULL DEFAULT 'human' CHECK (actor_kind IN ('human', 'ai')), + action text NOT NULL CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', + 'ban', 'unban', 'lock', 'unlock', 'pin', 'unpin')), + target_user uuid REFERENCES users ON DELETE SET NULL, + thread_id bigint, + post_id bigint, + reason text, + until timestamptz, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX mod_log_created_idx ON forum.mod_log (created_at DESC); diff --git a/crates/db/migrations/0039_forum_reports_messages.sql b/crates/db/migrations/0039_forum_reports_messages.sql new file mode 100644 index 0000000..eb457e1 --- /dev/null +++ b/crates/db/migrations/0039_forum_reports_messages.sql @@ -0,0 +1,69 @@ +-- The forum, second round (docs/kozosseg.md): private messages that start +-- with a request, and reports of posts and messages (the DSA's notice and +-- action), handled by moderators. + +-- One conversation per pair of members (user_a < user_b). It starts as a +-- request with a short introduction; the recipient accepts, declines +-- (silently: the sender is not told) or blocks. +CREATE TABLE forum.conversations ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + user_a uuid NOT NULL REFERENCES users ON DELETE CASCADE, + user_b uuid NOT NULL REFERENCES users ON DELETE CASCADE, + requested_by uuid NOT NULL REFERENCES users ON DELETE CASCADE, + intro text NOT NULL, + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'declined', 'blocked')), + -- Who blocked (the other may not send a new request). + blocked_by uuid REFERENCES users ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + responded_at timestamptz, + last_message_at timestamptz, + UNIQUE (user_a, user_b), + CONSTRAINT conversations_ordered CHECK (user_a < user_b), + CONSTRAINT conversations_requester CHECK (requested_by IN (user_a, user_b)) +); +CREATE INDEX conversations_b_idx ON forum.conversations (user_b); + +CREATE TABLE forum.messages ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + conversation_id bigint NOT NULL REFERENCES forum.conversations ON DELETE CASCADE, + sender_id uuid REFERENCES users ON DELETE SET NULL, + body text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX messages_conversation_idx ON forum.messages (conversation_id, id); + +-- How far each member has read a conversation. +CREATE TABLE forum.conversation_reads ( + conversation_id bigint NOT NULL REFERENCES forum.conversations ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + last_message_id bigint NOT NULL, + PRIMARY KEY (conversation_id, user_id) +); + +-- A report of a post or a private message. Moderators see a reported +-- message (and the conversation around it) only through its report. +CREATE TABLE forum.reports ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + post_id bigint REFERENCES forum.posts ON DELETE CASCADE, + message_id bigint REFERENCES forum.messages ON DELETE CASCADE, + reporter_id uuid REFERENCES users ON DELETE SET NULL, + kind text NOT NULL CHECK (kind IN ('spam', 'ad', 'rude', 'crisis', 'illegal', 'other')), + note text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'resolved', 'dismissed')), + handled_by uuid REFERENCES users ON DELETE SET NULL, + handled_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + -- The operator's Telegram notice went out (worker notify task). + notified_at timestamptz, + CONSTRAINT reports_one_target CHECK ((post_id IS NULL) <> (message_id IS NULL)) +); +CREATE UNIQUE INDEX reports_post_once ON forum.reports (post_id, reporter_id) WHERE status = 'open' AND post_id IS NOT NULL; +CREATE UNIQUE INDEX reports_message_once ON forum.reports (message_id, reporter_id) WHERE status = 'open' AND message_id IS NOT NULL; +CREATE INDEX reports_open_idx ON forum.reports (created_at) WHERE status = 'open'; +CREATE INDEX reports_unnotified_idx ON forum.reports (created_at) WHERE notified_at IS NULL; + +ALTER TABLE forum.mod_log DROP CONSTRAINT mod_log_action_check; +ALTER TABLE forum.mod_log ADD CONSTRAINT mod_log_action_check + CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', 'ban', 'unban', + 'lock', 'unlock', 'pin', 'unpin', 'resolve_report', 'dismiss_report')); +ALTER TABLE forum.mod_log ADD COLUMN report_id bigint; diff --git a/crates/db/migrations/0040_forum_notifications.sql b/crates/db/migrations/0040_forum_notifications.sql new file mode 100644 index 0000000..1ecf8dd --- /dev/null +++ b/crates/db/migrations/0040_forum_notifications.sql @@ -0,0 +1,12 @@ +-- Forum e-mail notifications (docs/kozosseg.md), each switched by the member: +-- replies to them (instant, a daily digest, or off), new posts in followed +-- threads (daily or off), private messages and requests (instant or off). +-- The token is the one-click unsubscribe link of these e-mails. +ALTER TABLE forum.members + ADD COLUMN email_replies text NOT NULL DEFAULT 'daily' CHECK (email_replies IN ('off', 'daily', 'instant')), + ADD COLUMN email_followed text NOT NULL DEFAULT 'off' CHECK (email_followed IN ('off', 'daily')), + ADD COLUMN email_messages text NOT NULL DEFAULT 'instant' CHECK (email_messages IN ('off', 'instant')), + -- When the last daily digest was made (the worker's forum task). + ADD COLUMN digest_sent_at timestamptz, + ADD COLUMN email_token text NOT NULL DEFAULT replace(gen_random_uuid()::text, '-', ''); +CREATE UNIQUE INDEX members_email_token_key ON forum.members (email_token); diff --git a/crates/db/migrations/0041_forum_more.sql b/crates/db/migrations/0041_forum_more.sql new file mode 100644 index 0000000..89bd970 --- /dev/null +++ b/crates/db/migrations/0041_forum_more.sql @@ -0,0 +1,55 @@ +-- The forum, more (docs/kozosseg.md): the daily sky thread, volunteer +-- listeners, mentions, the weekly summary, the supporter badge, and +-- restricted topics with approval. (Own avatars need no column: the avatar +-- holds `upload:` then.) + +-- The site's own threads and posts (the daily "Mai égbolt"): no member author. +ALTER TABLE forum.threads ADD COLUMN system boolean NOT NULL DEFAULT false; +-- The daily sky thread of that day (one a day). +ALTER TABLE forum.threads ADD COLUMN daily_date date UNIQUE; +ALTER TABLE forum.posts ADD COLUMN system boolean NOT NULL DEFAULT false; + +-- Volunteer listeners: told when a thread asking to be heard waits for a reply. +ALTER TABLE forum.members ADD COLUMN listener boolean NOT NULL DEFAULT false; +ALTER TABLE forum.members ADD COLUMN email_listener text NOT NULL DEFAULT 'off' + CHECK (email_listener IN ('off', 'instant')); +-- The listeners were told about this thread (once). +ALTER TABLE forum.threads ADD COLUMN listeners_notified_at timestamptz; + +-- "@Holdfény" in a post: whom it names. +CREATE TABLE forum.mentions ( + post_id bigint NOT NULL REFERENCES forum.posts ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (post_id, user_id) +); +CREATE INDEX mentions_user_idx ON forum.mentions (user_id, created_at DESC); +ALTER TABLE forum.members ADD COLUMN email_mentions text NOT NULL DEFAULT 'instant' + CHECK (email_mentions IN ('off', 'instant')); + +-- The weekly summary e-mail: off until the member asks for it. +ALTER TABLE forum.members ADD COLUMN email_weekly boolean NOT NULL DEFAULT false; +ALTER TABLE forum.members ADD COLUMN weekly_sent_at timestamptz; + +-- The "Támogató" badge: only for buyers, and only when they switch it on. +ALTER TABLE forum.members ADD COLUMN supporter_badge boolean NOT NULL DEFAULT false; + +-- Members of a restricted topic: they ask, a moderator approves. +CREATE TABLE forum.topic_members ( + topic_id smallint NOT NULL REFERENCES forum.topics ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved')), + -- A few words from the member asking to join. + note text NOT NULL DEFAULT '', + requested_at timestamptz NOT NULL DEFAULT now(), + decided_at timestamptz, + decided_by uuid REFERENCES users ON DELETE SET NULL, + PRIMARY KEY (topic_id, user_id) +); +CREATE INDEX topic_members_user_idx ON forum.topic_members (user_id) WHERE status = 'approved'; + +ALTER TABLE forum.mod_log DROP CONSTRAINT mod_log_action_check; +ALTER TABLE forum.mod_log ADD CONSTRAINT mod_log_action_check + CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', 'ban', 'unban', + 'lock', 'unlock', 'pin', 'unpin', 'resolve_report', 'dismiss_report', + 'approve_member', 'reject_member', 'remove_member', 'reset_avatar', 'topic')); diff --git a/crates/db/migrations/0042_forum_reply_to.sql b/crates/db/migrations/0042_forum_reply_to.sql new file mode 100644 index 0000000..659f0da --- /dev/null +++ b/crates/db/migrations/0042_forum_reply_to.sql @@ -0,0 +1,4 @@ +-- Replies stay two levels deep (a reply to a reply goes under the same +-- first-level post, `parent_id`); `reply_to_id` keeps which post it answered, +-- so the page can say whom it is for ("↪ Holdfény"). +ALTER TABLE forum.posts ADD COLUMN reply_to_id bigint REFERENCES forum.posts ON DELETE SET NULL; diff --git a/crates/db/migrations/0043_forum_search_mutes_archive_charts.sql b/crates/db/migrations/0043_forum_search_mutes_archive_charts.sql new file mode 100644 index 0000000..72f382e --- /dev/null +++ b/crates/db/migrations/0043_forum_search_mutes_archive_charts.sql @@ -0,0 +1,52 @@ +-- Forum: archived topics, muted members, search, and charts attached to a +-- question. + +-- An archived topic stays readable at its address, but takes no new threads +-- or replies, and leaves the front page lists. +ALTER TABLE forum.topics ADD COLUMN archived_at timestamptz; + +-- "Némítás": the muted member's threads leave the lists, their posts fold +-- up, and their replies and mentions no longer notify. They are not told. +CREATE TABLE forum.mutes ( + user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + muted_id uuid NOT NULL REFERENCES users ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, muted_id), + CHECK (user_id <> muted_id) +); + +-- Search: Hungarian stems (szálak → szál), and the words without accents +-- too, so "alvas" finds "alvás". +CREATE EXTENSION IF NOT EXISTS unaccent; +CREATE TEXT SEARCH CONFIGURATION forum.plain (COPY = simple); +ALTER TEXT SEARCH CONFIGURATION forum.plain ALTER MAPPING FOR hword, hword_part, word WITH unaccent, simple; + +ALTER TABLE forum.threads ADD COLUMN search tsvector GENERATED ALWAYS AS ( + to_tsvector('hungarian'::regconfig, title) || to_tsvector('forum.plain'::regconfig, title) +) STORED; +ALTER TABLE forum.posts ADD COLUMN search tsvector GENERATED ALWAYS AS ( + to_tsvector('hungarian'::regconfig, body) || to_tsvector('forum.plain'::regconfig, body) +) STORED; +CREATE INDEX threads_search_idx ON forum.threads USING gin (search); +CREATE INDEX posts_search_idx ON forum.posts USING gin (search); + +-- A question about one's own chart, forecast or synastry: the opening post +-- carries a share made for the forum (see below), shown to members only. +ALTER TABLE forum.posts ADD COLUMN share_id uuid REFERENCES shares ON DELETE SET NULL; + +-- Shares made for the forum: never birth data, and the public view leaves +-- out the chart names (they may be real names next to a nickname). +ALTER TABLE shares ADD COLUMN for_forum boolean NOT NULL DEFAULT false; + +-- A yearly forecast can be shared too (its calculation, and the detailed +-- text if there is one), without the place of the birthday. +ALTER TABLE shares ADD COLUMN forecast_id uuid REFERENCES forecasts ON DELETE CASCADE; +ALTER TABLE shares DROP CONSTRAINT shares_kind_check; +ALTER TABLE shares ADD CONSTRAINT shares_kind_check CHECK (kind IN ('chart', 'synastry', 'analysis', 'forecast')); +ALTER TABLE shares DROP CONSTRAINT shares_target; +ALTER TABLE shares ADD CONSTRAINT shares_target CHECK ( + (kind = 'chart' AND chart_id IS NOT NULL AND synastry_id IS NULL AND analysis_id IS NULL AND forecast_id IS NULL) + OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND analysis_id IS NULL AND forecast_id IS NULL) + OR (kind = 'analysis' AND analysis_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL) + OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND analysis_id IS NULL) +); diff --git a/crates/db/migrations/0044_forum_founders.sql b/crates/db/migrations/0044_forum_founders.sql new file mode 100644 index 0000000..0970c05 --- /dev/null +++ b/crates/db/migrations/0044_forum_founders.sql @@ -0,0 +1,6 @@ +-- "Alapító tag": the first fifteen members (in the order they chose a +-- nickname) keep the badge for good. The admin can take it from a test +-- account or give it; a freed place goes to the next newcomer. +ALTER TABLE forum.members ADD COLUMN founder boolean NOT NULL DEFAULT false; +UPDATE forum.members SET founder = true +WHERE user_id IN (SELECT user_id FROM forum.members ORDER BY created_at, user_id LIMIT 15); diff --git a/crates/db/migrations/0045_forum_link_previews.sql b/crates/db/migrations/0045_forum_link_previews.sql new file mode 100644 index 0000000..8f22d7d --- /dev/null +++ b/crates/db/migrations/0045_forum_link_previews.sql @@ -0,0 +1,13 @@ +-- The forum's link module: what a recognised link shows under a post. For +-- now YouTube: title, channel and a thumbnail kept in our own storage, so a +-- page loads nothing from YouTube until someone plays the video. +CREATE TABLE forum.link_previews ( + provider text NOT NULL, + key text NOT NULL, + title text NOT NULL, + author text, + -- The thumbnail's file in the object storage (NULL: none). + thumbnail text, + fetched_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (provider, key) +); diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index f34e6ac..8cca945 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -36,6 +36,8 @@ pub enum Role { Admin, /// May write articles (phase 2). Creator, + /// Forum moderator, appointed by an admin. + Moderator, /// Paid tier: may use the models marked `@premium`. Premium, /// Top tier: may use the `@vip` and `@premium` models. @@ -44,12 +46,13 @@ pub enum Role { } impl Role { - pub const ALL: [Role; 5] = [Role::Admin, Role::Creator, Role::Premium, Role::Vip, Role::User]; + pub const ALL: [Role; 6] = [Role::Admin, Role::Creator, Role::Moderator, Role::Premium, Role::Vip, Role::User]; pub fn as_str(self) -> &'static str { match self { Role::Admin => "admin", Role::Creator => "creator", + Role::Moderator => "moderator", Role::Premium => "premium", Role::Vip => "vip", Role::User => "user", diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index a5547b2..63268d5 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -50,7 +50,7 @@ struct Content { /// A personal message, shown as a quote. quote: Option, /// A short list after the intro, with its heading. - points: Option<(&'static str, Vec<&'static str>)>, + points: Option<(&'static str, Vec)>, /// A code to type in, shown large in a box, with its label. code: Option<(&'static str, String)>, button: &'static str, @@ -182,6 +182,15 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result purchase_confirmation(lang, payload, url)?, ("gift", _) => gift(lang, payload, url)?, ("gift_package", _) => gift_package(lang, payload, url)?, + // The forum is Hungarian only. + ("forum_reply", _) => forum_reply(payload, url)?, + ("forum_digest", _) => forum_digest(payload, url)?, + ("forum_message", _) => forum_message(payload, url)?, + ("forum_moderation", _) => forum_moderation(payload, url)?, + ("forum_mention", _) => forum_mention(payload, url)?, + ("forum_listener", _) => forum_listener(payload, url)?, + ("forum_weekly", _) => forum_weekly(payload, url)?, + ("forum_report_result", _) => forum_report_result(payload, url)?, _ => return Err(TemplateError::UnknownTemplate(template.to_owned())), }; Ok(content.render(lang)) @@ -240,7 +249,10 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result Result Result Result { + content.reason = + Some(format!("Azért kapod ezt a levelet, mert {why}. Az értesítéseket a fórumprofilodnál állíthatod be.")); + content.unsubscribe = Some(("Leiratkozás a fórum összes leveléről", field(payload, "unsubscribe_url")?)); + content.unsubscribe_post_url = Some(field(payload, "unsubscribe_post_url")?); + Ok(content) +} + +/// "Szia Csendesvíz!": the forum greets by the nickname, never the real name. +fn hello(payload: &Value) -> String { + name(payload, "nickname").map_or_else(|| "Szia!".to_owned(), |n| format!("Szia {n}!")) +} + +/// A short excerpt of a member's text for a quote (never the whole post). +fn excerpt(payload: &Value, key: &str, max: usize) -> Option { + let text: String = payload[key].as_str()?.chars().filter(|c| !c.is_control() || *c == '\n').collect(); + let text = text.trim(); + if text.is_empty() { + return None; + } + Some(if text.chars().count() > max { + format!("{}…", text.chars().take(max).collect::().trim_end()) + } else { + text.to_owned() + }) +} + +/// Someone answered the member: in their thread or to their post. +fn forum_reply(payload: &Value, url: String) -> Result { + let author = name(payload, "author").unwrap_or_else(|| "Valaki".into()); + let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?; + let content = Content { + subject: format!("{author} válaszolt: „{title}”"), + preheader: excerpt(payload, "excerpt", 90), + greeting: hello(payload), + intro: format!("{author} válaszolt neked a Sorsfonalak fórumán, a(z) „{title}” szálban:"), + quote: excerpt(payload, "excerpt", 300), + points: None, + code: None, + button: "Megnézem", + url, + note: "Ha nem kérsz azonnali levelet, a fórumprofilodnál napi összesítőre válthatsz, vagy kikapcsolhatod." + .into(), + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + }; + forum_footer(payload, content, "a fórumon azonnali értesítést kértél a válaszokról") +} + +/// Someone named the member ("@Holdfény") in a post. +fn forum_mention(payload: &Value, url: String) -> Result { + let author = name(payload, "author").unwrap_or_else(|| "Valaki".into()); + let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?; + let content = Content { + subject: format!("{author} megemlített: „{title}”"), + preheader: excerpt(payload, "excerpt", 90), + greeting: hello(payload), + intro: format!("{author} megemlített a Sorsfonalak fórumán, a(z) „{title}” szálban:"), + quote: excerpt(payload, "excerpt", 300), + points: None, + code: None, + button: "Megnézem", + url, + note: "Az említésekről szóló leveleket a fórumprofilodnál kapcsolhatod ki.".into(), + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + }; + forum_footer(payload, content, "a fórumon értesítést kértél, ha megemlítenek") +} + +/// For a volunteer listener: a thread asking to be heard waits for a reply. +fn forum_listener(payload: &Value, url: String) -> Result { + let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?; + let content = Content { + subject: format!("Válaszra vár: „{title}”"), + preheader: Some("Valaki meghallgatást kért, és még senki nem válaszolt.".into()), + greeting: hello(payload), + intro: format!( + "A(z) „{title}” szálban valaki meghallgatást kért, és még senki nem válaszolt neki. Ha van rá időd, egy pár soros válasz is sokat jelenthet." + ), + quote: None, + points: None, + code: None, + button: "Elolvasom", + url, + note: "Tanács helyett elég, ha leírod, hogy itt vagy, vagy hogy veled is történt hasonló.".into(), + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + }; + forum_footer(payload, content, "önkéntes kísérőként értesítést kértél a válasz nélküli szálakról") +} + +/// The weekly summary: the busiest threads, and those still waiting. +fn forum_weekly(payload: &Value, url: String) -> Result { + let lines = |key: &'static str| -> Vec { + payload[key] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l.as_str()) + .map(|l| l.chars().filter(|c| !c.is_control()).take(160).collect()) + .collect() + }; + let busy = lines("busy"); + let waiting = lines("waiting"); + if busy.is_empty() && waiting.is_empty() { + return Err(TemplateError::MissingField("busy")); + } + let mut items = busy; + if !waiting.is_empty() { + items.push("Még válaszra vár:".into()); + items.extend(waiting.into_iter().map(|w| format!(" {w}"))); + } + let content = Content { + subject: "A hét a fórumon".into(), + preheader: items.first().cloned(), + greeting: hello(payload), + intro: "Ezekről beszélgettünk a héten a Sorsfonalak fórumán:".into(), + quote: None, + points: Some(("A hét szálai:", items)), + code: None, + button: "Benézek a fórumra", + url, + note: "Hetente egyszer, vasárnap este küldjük, ha kérted.".into(), + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + }; + forum_footer(payload, content, "a fórumon heti összefoglalót kértél") +} + +/// The daily digest: the threads with new posts for the member. +fn forum_digest(payload: &Value, url: String) -> Result { + let lines: Vec = payload["lines"] + .as_array() + .ok_or(TemplateError::MissingField("lines"))? + .iter() + .filter_map(|l| l.as_str()) + .map(|l| l.chars().filter(|c| !c.is_control()).take(160).collect()) + .collect(); + if lines.is_empty() { + return Err(TemplateError::MissingField("lines")); + } + let total = payload["total"].as_i64().unwrap_or(lines.len() as i64); + let content = Content { + subject: format!("{total} új hozzászólás vár a fórumon"), + preheader: lines.first().cloned(), + greeting: hello(payload), + intro: "Mióta utoljára írtunk, ezekben a szálakban jött új hozzászólás:".into(), + quote: None, + points: Some(("Szálak:", lines)), + code: None, + button: "Megnézem a fórumon", + url, + note: "Naponta legfeljebb egy ilyen levelet küldünk, és csak akkor, ha van újdonság.".into(), + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + }; + forum_footer(payload, content, "a fórumon napi összesítőt kértél") +} + +/// A private message, or a request to talk. The message itself is not in +/// the e-mail; a request's short introduction is. +fn forum_message(payload: &Value, url: String) -> Result { + let from = name(payload, "from").unwrap_or_else(|| "Valaki".into()); + let request = payload["kind"].as_str() == Some("request"); + let content = Content { + subject: if request { + format!("{from} beszélgetni szeretne veled") + } else { + format!("Új üzeneted jött: {from}") + }, + preheader: None, + greeting: hello(payload), + intro: if request { + format!("{from} beszélgetést kezdeményezett veled a Sorsfonalak fórumán. Ezt írta magáról:") + } else { + format!("{from} privát üzenetet küldött neked a Sorsfonalak fórumán.") + }, + quote: if request { excerpt(payload, "excerpt", 200) } else { None }, + points: None, + code: None, + button: if request { "Megnézem a kérést" } else { "Elolvasom" }, + url, + note: if request { + "Elfogadhatod, csendben elutasíthatod (erről nem kap értesítést), vagy letilthatod.".into() + } else { + "Az üzenet szövegét nem tesszük bele a levélbe: a fórumon olvashatod.".into() + }, + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + }; + forum_footer(payload, content, "a fórumon értesítést kértél a privát üzenetekről") +} + +/// A moderation step concerning the member (the DSA's statement of reasons): +/// what happened, why, on what ground, and how to object. Sent whatever the +/// member's notification settings. +fn forum_moderation(payload: &Value, url: String) -> Result { + let reason = excerpt(payload, "reason", 300).ok_or(TemplateError::MissingField("reason"))?; + let title = name(payload, "thread_title"); + let in_thread = title.as_deref().map(|t| format!(" a(z) „{t}” szálban")).unwrap_or_default(); + let (subject, intro) = match payload["action"].as_str() { + Some("post_removed") => ( + "Eltávolítottuk egy hozzászólásodat".to_owned(), + format!( + "Egy moderátor eltávolította egy hozzászólásodat{in_thread}. A hozzászólás helyén ez az indoklás látszik:" + ), + ), + Some("thread_removed") => ( + "Eltávolítottuk egy száladat".to_owned(), + format!("Egy moderátor eltávolította a száladat{in_thread}. A szál helyén ez az indoklás látszik:"), + ), + Some("banned") => match name(payload, "duration") { + Some(d) => ( + "Egy ideig nem írhatsz a fórumba".to_owned(), + format!( + "Egy moderátor {d} időre eltiltott a fórumon az írástól. Olvasni továbbra is tudsz. Az indoklás:" + ), + ), + None => ( + "Kitiltottunk a fórumról".to_owned(), + "Egy moderátor véglegesen eltiltott a fórumon az írástól. Olvasni továbbra is tudsz. Az indoklás:" + .to_owned(), + ), + }, + _ => return Err(TemplateError::MissingField("action")), + }; + Ok(Content { + subject, + preheader: None, + greeting: hello(payload), + intro, + quote: Some(reason), + points: None, + code: None, + button: "A fórum házirendje", + url, + note: "A döntés alapja a fórum házirendje (ÁSZF 8. pont). Ha szerinted tévedés történt, válaszolj erre a levélre, vagy írj az info@sorsfonalak.hu címre: a döntést egy másik moderátor vagy az üzemeltető vizsgálja felül. A megvásárolt szolgáltatásaidat ez nem érinti.".into(), + reason: Some("Ezt a levelet azért kapod, mert a fórumon egy moderálási döntés érintett.".into()), + unsubscribe: None, + unsubscribe_post_url: None, + }) +} + +/// The decision on a report the member sent. +fn forum_report_result(payload: &Value, url: String) -> Result { + let intro = match payload["outcome"].as_str() { + Some("removed") => "Köszönjük a jelentésedet. Megnéztük, és a tartalmat eltávolítottuk.", + Some("handled") => "Köszönjük a jelentésedet. Megnéztük, és intézkedtünk.", + Some("no_violation") => { + "Köszönjük a jelentésedet. Megnéztük, de nem találtunk benne a házirendbe ütköző dolgot, ezért a tartalom marad." + } + _ => return Err(TemplateError::MissingField("outcome")), + }; + Ok(Content { + subject: "Elbíráltuk a jelentésedet".into(), + preheader: None, + greeting: hello(payload), + intro: intro.into(), + quote: None, + points: None, + code: None, + button: "Vissza a fórumra", + url, + note: "Ha nem értesz egyet a döntéssel, írj az info@sorsfonalak.hu címre.".into(), + reason: Some("Ezt a levelet azért kapod, mert a fórumon jelentettél egy tartalmat.".into()), + unsubscribe: None, + unsubscribe_post_url: None, + }) +} + fn field(payload: &Value, name: &'static str) -> Result { payload[name].as_str().filter(|u| !u.is_empty()).map(str::to_owned).ok_or(TemplateError::MissingField(name)) } @@ -501,7 +795,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result Result Result Result Result Result serde_json::Value { + json!({ + "url": "https://sorsfonalak.hu/forum/szal/12-szia", + "nickname": "Csendesvíz", + "unsubscribe_url": "https://sorsfonalak.hu/forum/leiratkozas?token=t", + "unsubscribe_post_url": "https://sorsfonalak.hu/api/v1/forum/unsubscribe?token=t", + }) + } + + #[test] + fn forum_mails() { + let mut p = forum_links(); + p["author"] = json!("Holdfény"); + p["thread_title"] = json!("Nem tudom elengedni"); + p["excerpt"] = json!("Nem vagy egyedül. ".repeat(40)); + let m = render("forum_reply", "hu", &p).unwrap(); + assert_eq!(m.subject, "Holdfény válaszolt: „Nem tudom elengedni”"); + assert!(m.text.starts_with("Szia Csendesvíz!")); + assert!(m.text.contains("…"), "only an excerpt"); + assert!(m.html.contains("Leiratkozás a fórum összes leveléről")); + assert_eq!(m.unsubscribe_post_url.as_deref(), Some("https://sorsfonalak.hu/api/v1/forum/unsubscribe?token=t")); + + let mut p = forum_links(); + p["lines"] = json!(["„Téli levesek” – 2 új", "„Reggeli csend” – 1 új"]); + p["total"] = json!(3); + let m = render("forum_digest", "hu", &p).unwrap(); + assert_eq!(m.subject, "3 új hozzászólás vár a fórumon"); + assert!(m.text.contains("- „Téli levesek” – 2 új")); + p["lines"] = json!([]); + assert!(render("forum_digest", "hu", &p).is_err()); + + let mut p = forum_links(); + p["from"] = json!("Zöldág"); + p["kind"] = json!("message"); + p["excerpt"] = json!("titkos szöveg"); + let m = render("forum_message", "hu", &p).unwrap(); + assert_eq!(m.subject, "Új üzeneted jött: Zöldág"); + assert!(!m.text.contains("titkos"), "a message's text stays out of the e-mail"); + p["kind"] = json!("request"); + let m = render("forum_message", "hu", &p).unwrap(); + assert_eq!(m.subject, "Zöldág beszélgetni szeretne veled"); + assert!(m.text.contains("titkos"), "a request's introduction is shown"); + + let p = json!({ + "url": "https://sorsfonalak.hu/aszf#forum", "nickname": "Gyógyító", "action": "banned", + "duration": "3 napos", "reason": "szolgáltatás hirdetése", + }); + let m = render("forum_moderation", "hu", &p).unwrap(); + assert_eq!(m.subject, "Egy ideig nem írhatsz a fórumba"); + assert!(m.text.contains("3 napos időre") && m.text.contains("> szolgáltatás hirdetése")); + assert!(m.text.contains("ÁSZF 8. pont") && m.unsubscribe_post_url.is_none()); + let m = render("forum_moderation", "hu", &json!({"url": "u", "action": "banned", "reason": "x"})).unwrap(); + assert_eq!(m.subject, "Kitiltottunk a fórumról"); + let m = render( + "forum_moderation", + "hu", + &json!({"url": "u", "action": "post_removed", "reason": "sértő", "thread_title": "Téli levesek"}), + ) + .unwrap(); + assert!(m.text.contains("a(z) „Téli levesek” szálban")); + let m = render("forum_report_result", "hu", &json!({"url": "u", "outcome": "no_violation"})).unwrap(); + assert!(m.text.starts_with("Szia!") && m.text.contains("a tartalom marad")); + assert!(render("forum_report_result", "hu", &json!({"url": "u"})).is_err()); + + let mut p = forum_links(); + p["author"] = json!("Zöldág"); + p["thread_title"] = json!("Téli levesek"); + p["excerpt"] = json!("@Csendesvíz szerinted?"); + assert_eq!(render("forum_mention", "hu", &p).unwrap().subject, "Zöldág megemlített: „Téli levesek”"); + let m = render("forum_listener", "hu", &p).unwrap(); + assert_eq!(m.subject, "Válaszra vár: „Téli levesek”"); + let mut p = forum_links(); + p["busy"] = json!(["„Téli levesek” – 12 hozzászólás"]); + p["waiting"] = json!(["„Nehéz napok”"]); + let m = render("forum_weekly", "hu", &p).unwrap(); + assert!(m.text.contains("Még válaszra vár") && m.unsubscribe_post_url.is_some()); + } } diff --git a/crates/object-storage/Cargo.toml b/crates/object-storage/Cargo.toml new file mode 100644 index 0000000..6bf8539 --- /dev/null +++ b/crates/object-storage/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "object-storage" +description = "S3-compatible object storage (DigitalOcean Spaces, RustFS) for the Sorsfonalak services" +edition.workspace = true +version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +bytes = "1" +hmac.workspace = true +reqwest.workspace = true +sha2.workspace = true +thiserror.workspace = true +time.workspace = true +tracing.workspace = true + +[dev-dependencies] +tokio.workspace = true diff --git a/crates/object-storage/src/lib.rs b/crates/object-storage/src/lib.rs new file mode 100644 index 0000000..56a0932 --- /dev/null +++ b/crates/object-storage/src/lib.rs @@ -0,0 +1,294 @@ +//! Object storage for uploaded pictures (the backend's photos, the forum's +//! avatars): any S3-compatible service, addressed path-style +//! (`{endpoint}/{bucket}/{key}`). In production DigitalOcean Spaces, in +//! development a RustFS container. +//! +//! The bucket stays private: the services read the objects themselves and +//! serve them (the backend under `/v1/public/photos/...`, the forum under +//! `/v1/forum/avatars/...`). +//! +//! Requests are signed with AWS Signature Version 4. + +use std::time::Duration; + +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha256}; +use time::OffsetDateTime; + +/// `S3_ENDPOINT` (e.g. `https://fra1.digitaloceanspaces.com`), `S3_BUCKET`, +/// `S3_REGION` (default `us-east-1`; Spaces accepts it too), +/// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` (in `.env.secrets`). +#[derive(Clone)] +pub struct StorageConfig { + pub endpoint: String, + pub bucket: String, + pub region: String, + pub access_key: String, + pub secret_key: String, +} + +// The secret stays out of logs. +impl std::fmt::Debug for StorageConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StorageConfig") + .field("endpoint", &self.endpoint) + .field("bucket", &self.bucket) + .field("region", &self.region) + .finish() + } +} + +#[derive(Debug, thiserror::Error)] +pub enum StorageError { + #[error("object storage request failed: {0}")] + Http(#[from] reqwest::Error), + #[error("object storage answered {status}: {body}")] + Status { status: u16, body: String }, +} + +pub struct Storage { + config: StorageConfig, + http: reqwest::Client, +} + +/// An object read back: its bytes and content type. +pub struct Object { + pub bytes: bytes::Bytes, + pub content_type: Option, +} + +impl StorageConfig { + /// From `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION` (default `us-east-1`), + /// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`; `None` without an endpoint. + pub fn from_env() -> Result, String> { + let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty()); + let Some(endpoint) = var("S3_ENDPOINT") else { return Ok(None) }; + let required = |name: &str| var(name).ok_or_else(|| format!("{name} is required with S3_ENDPOINT")); + Ok(Some(Self { + endpoint: endpoint.trim_end_matches('/').to_string(), + bucket: required("S3_BUCKET")?, + region: var("S3_REGION").unwrap_or_else(|| "us-east-1".into()), + access_key: required("S3_ACCESS_KEY_ID")?, + secret_key: required("S3_SECRET_ACCESS_KEY")?, + })) + } +} + +impl Storage { + pub fn new(config: StorageConfig) -> Self { + let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration"); + Self { config, http } + } + + fn url(&self, key: &str) -> String { + let path = if key.is_empty() { String::new() } else { format!("/{}", encode_path(key)) }; + format!("{}/{}{path}", self.config.endpoint, encode_segment(&self.config.bucket)) + } + + async fn send( + &self, + method: reqwest::Method, + key: &str, + body: Vec, + content_type: Option<&str>, + ) -> Result { + let url = self.url(key); + let parsed = reqwest::Url::parse(&url).map_err(|e| StorageError::Status { status: 0, body: e.to_string() })?; + let host = match parsed.port() { + Some(port) => format!("{}:{port}", parsed.host_str().unwrap_or_default()), + None => parsed.host_str().unwrap_or_default().to_string(), + }; + let payload_hash = hex(&Sha256::digest(&body)); + let now = OffsetDateTime::now_utc(); + let auth = authorization(&self.config, method.as_str(), parsed.path(), &host, &payload_hash, now); + let mut request = self + .http + .request(method, url) + .header("x-amz-date", amz_date(now)) + .header("x-amz-content-sha256", &payload_hash) + .header("authorization", auth); + if let Some(ct) = content_type { + request = request.header("content-type", ct); + } + let response = request.body(body).send().await?; + Ok(response) + } + + async fn checked(response: reqwest::Response) -> Result { + if response.status().is_success() { + return Ok(response); + } + let status = response.status().as_u16(); + let body = response.text().await.unwrap_or_default().chars().take(500).collect(); + Err(StorageError::Status { status, body }) + } + + pub async fn put(&self, key: &str, body: Vec, content_type: &str) -> Result<(), StorageError> { + Self::checked(self.send(reqwest::Method::PUT, key, body, Some(content_type)).await?).await?; + Ok(()) + } + + /// The object, or `None` if there is no such key. + pub async fn get(&self, key: &str) -> Result, StorageError> { + let response = self.send(reqwest::Method::GET, key, Vec::new(), None).await?; + if response.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + let response = Self::checked(response).await?; + let content_type = response.headers().get("content-type").and_then(|v| v.to_str().ok()).map(str::to_owned); + Ok(Some(Object { bytes: response.bytes().await?, content_type })) + } + + /// Deletes the object; a missing one is not an error. + pub async fn delete(&self, key: &str) -> Result<(), StorageError> { + let response = self.send(reqwest::Method::DELETE, key, Vec::new(), None).await?; + if response.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(()); + } + Self::checked(response).await?; + Ok(()) + } + + /// Creates the bucket if it does not exist yet (development: a fresh + /// RustFS container has none; in production it is made in the console). + pub async fn ensure_bucket(&self) -> Result<(), StorageError> { + let head = self.send(reqwest::Method::HEAD, "", Vec::new(), None).await?; + if head.status().is_success() { + return Ok(()); + } + Self::checked(self.send(reqwest::Method::PUT, "", Vec::new(), None).await?).await?; + tracing::info!(bucket = %self.config.bucket, "object storage bucket created"); + Ok(()) + } +} + +type HmacSha256 = Hmac; + +fn hmac(key: &[u8], data: &str) -> Vec { + let mut mac = HmacSha256::new_from_slice(key).expect("HMAC takes any key length"); + mac.update(data.as_bytes()); + mac.finalize().into_bytes().to_vec() +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn amz_date(t: OffsetDateTime) -> String { + format!( + "{:04}{:02}{:02}T{:02}{:02}{:02}Z", + t.year(), + u8::from(t.month()), + t.day(), + t.hour(), + t.minute(), + t.second() + ) +} + +/// URI-encodes one path segment as SigV4 wants it (unreserved characters stay). +fn encode_segment(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), + _ => format!("%{b:02X}"), + }) + .collect() +} + +fn encode_path(key: &str) -> String { + key.split('/').map(encode_segment).collect::>().join("/") +} + +fn signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec { + [date, region, service, "aws4_request"] + .iter() + .fold(format!("AWS4{secret}").into_bytes(), |key, part| hmac(&key, part)) +} + +/// The `Authorization` header of a request (no query string; the path is +/// already encoded, as in the URL). +fn authorization( + config: &StorageConfig, + method: &str, + path: &str, + host: &str, + payload_hash: &str, + now: OffsetDateTime, +) -> String { + let date_time = amz_date(now); + let date = &date_time[..8]; + let signed_headers = "host;x-amz-content-sha256;x-amz-date"; + let canonical = format!( + "{method}\n{path}\n\nhost:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{date_time}\n\n\ + {signed_headers}\n{payload_hash}" + ); + let scope = format!("{date}/{}/s3/aws4_request", config.region); + let to_sign = format!("AWS4-HMAC-SHA256\n{date_time}\n{scope}\n{}", hex(&Sha256::digest(canonical.as_bytes()))); + let signature = hex(&hmac(&signing_key(&config.secret_key, date, &config.region, "s3"), &to_sign)); + format!( + "AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}", + config.access_key + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The signing key example of the AWS documentation ("Examples of how to + /// derive a signing key for Signature Version 4"). + #[test] + fn derives_the_signing_key_like_aws() { + let key = signing_key("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "20150830", "us-east-1", "iam"); + assert_eq!(hex(&key), "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9"); + } + + #[test] + fn builds_the_authorization_header() { + let config = StorageConfig { + endpoint: "http://rustfs:9000".into(), + bucket: "photos".into(), + region: "us-east-1".into(), + access_key: "AKIAIOSFODNN7EXAMPLE".into(), + secret_key: "secret".into(), + }; + let now = OffsetDateTime::from_unix_timestamp(1_369_353_600).unwrap(); + assert_eq!(amz_date(now), "20130524T000000Z"); + let empty = hex(&Sha256::digest(b"")); + assert_eq!(empty, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + let auth = authorization(&config, "GET", "/photos/a.jpg", "rustfs:9000", &empty, now); + assert!(auth.starts_with( + "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, \ + SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=" + )); + let storage = Storage::new(config); + assert_eq!(storage.url("celebrities/a b/ő.jpg"), "http://rustfs:9000/photos/celebrities/a%20b/%C5%91.jpg"); + assert_eq!(storage.url(""), "http://rustfs:9000/photos"); + } + + /// Against a real S3 service (e.g. the RustFS container of development): + /// `S3_TEST_ENDPOINT=http://127.0.0.1:9000 S3_TEST_KEY=… S3_TEST_SECRET=… + /// cargo test -p object-storage live_round_trip -- --ignored` + #[tokio::test] + #[ignore] + async fn live_round_trip() { + let env = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("{name} is not set")); + let storage = Storage::new(StorageConfig { + endpoint: env("S3_TEST_ENDPOINT"), + bucket: "storage-test".into(), + region: "us-east-1".into(), + access_key: env("S3_TEST_KEY"), + secret_key: env("S3_TEST_SECRET"), + }); + storage.ensure_bucket().await.unwrap(); + storage.ensure_bucket().await.unwrap(); + let key = "dir/próba kép.jpg"; + storage.put(key, b"hello".to_vec(), "image/jpeg").await.unwrap(); + let object = storage.get(key).await.unwrap().unwrap(); + assert_eq!((&object.bytes[..], object.content_type.as_deref()), (&b"hello"[..], Some("image/jpeg"))); + storage.delete(key).await.unwrap(); + assert!(storage.get(key).await.unwrap().is_none()); + storage.delete(key).await.unwrap(); + } +} diff --git a/deploy/.env.example b/deploy/.env.example index 9391397..847e945 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -18,6 +18,9 @@ MAIL_FROM=Sorsfonalak # invite: new accounts need an invitation (default); open: anyone can sign up SIGNUP_MODE=invite +# The forum (docs/kozosseg.md): it always runs, visitors see it once this is set +# FORUM_URL=http://forum:8083 + # Image version; every deployment rewrites it TAG=latest diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 7f164da..920e132 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -15,10 +15,20 @@ # No basic auth any more: the site is open, and new accounts need an # invitation (SIGNUP_MODE=invite in the backend). encode zstd gzip - reverse_proxy frontend:3000 { - # The address the backend trusts (rate limits, share visits); it - # overwrites whatever the browser sent in this header. - header_up X-Real-IP {client_ip} + # The forum's live connection (WebSocket) goes straight to the forum + # service: the frontend's /api/v1 proxy cannot carry it. + handle /api/v1/forum/ws { + rewrite * /v1/forum/ws + reverse_proxy forum:8083 { + header_up X-Real-IP {client_ip} + } + } + handle { + reverse_proxy frontend:3000 { + # The address the backend trusts (rate limits, share visits); it + # overwrites whatever the browser sent in this header. + header_up X-Real-IP {client_ip} + } } } diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index f16caca..6c40292 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -110,6 +110,9 @@ services: S3_ENDPOINT: ${S3_ENDPOINT:-} S3_BUCKET: ${S3_BUCKET:-} S3_REGION: ${S3_REGION:-us-east-1} + # Cloudflare Turnstile on the e-mail sign-up and reset forms (the + # TURNSTILE_SECRET_KEY is in .env.secrets). Without both: no check. + TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-} # The log also goes to the logs volume, one file a day, kept 30 days # (deploy/README.md: Logs). LOG_DIR: /logs @@ -134,7 +137,10 @@ services: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest} environment: DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak - WORKER_TASKS: email,cleanup,invoices,notify + # forum: the forum's digests, daily sky thread, listener e-mails, weekly summary. + WORKER_TASKS: email,cleanup,invoices,notify,forum + # The sky of the forum's daily thread. + BACKEND_URL: http://backend:8081 # Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets. TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-} # SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md); @@ -186,6 +192,32 @@ services: logging: *logging restart: unless-stopped + # The forum (docs/kozosseg.md): its own service on the same database and + # login; switched on for the visitors by FORUM_URL in the frontend below. + forum: + image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-forum:${TAG:-latest} + environment: + DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak + # The links in the forum's e-mails. + PUBLIC_BASE_URL: https://${DOMAIN} + # Uploaded avatars: the same Spaces bucket as the backend's photos + # (S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in .env.secrets). + S3_ENDPOINT: ${S3_ENDPOINT:-} + S3_BUCKET: ${S3_BUCKET:-} + S3_REGION: ${S3_REGION:-us-east-1} + LOG_DIR: /logs + env_file: + - path: .env.secrets + required: false + depends_on: + postgres: + condition: service_healthy + read_only: true + volumes: + - logs:/logs + logging: *logging + restart: unless-stopped + frontend: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest} environment: @@ -193,6 +225,8 @@ services: HOROSCOPE_API_URL: http://horoscope-api:8080 # Absolute links of the share previews (og:image). PUBLIC_BASE_URL: https://${DOMAIN} + # The forum: off until FORUM_URL=http://forum:8083 is in .env (no menu item, its pages 404). + FORUM_URL: ${FORUM_URL:-} depends_on: backend: condition: service_healthy @@ -222,7 +256,7 @@ services: volumes: pgdata: - # Backend and worker logs (backend.YYYY-MM-DD.log, worker…, worker-ai…). + # Backend, worker and forum logs (backend.YYYY-MM-DD.log, worker…, worker-ai…, forum…). logs: caddy-data: caddy-config: diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 50fa91c..c1aea7f 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -49,5 +49,13 @@ services: mailpit: condition: service_healthy + + forum: + environment: + S3_ENDPOINT: http://rustfs:9000 + S3_BUCKET: sorsfonalak-dev + S3_ACCESS_KEY_ID: rustfs-dev + S3_SECRET_ACCESS_KEY: rustfs-dev-secret + volumes: rustfs: diff --git a/docker-compose.yml b/docker-compose.yml index 13c2108..0469b50 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,10 @@ services: SUMMARY_MODEL: ${SUMMARY_MODEL:-} # E-mail + password login; off by default (Google, Apple and Facebook only). PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false} + # Cloudflare Turnstile (off without both keys; Cloudflare's test keys + # 1x00000000000000000000AA / 1x0000000000000000000000000000000AA always pass). + TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-} + TURNSTILE_SECRET_KEY: ${TURNSTILE_SECRET_KEY:-} # Stand-in payment (adds an analysis unit at once) until Stripe is connected. MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} # Stripe purchases for everyone (false: admins only, until the opening; @@ -96,6 +100,8 @@ services: SMTP_URL: ${SMTP_URL:-} MAIL_FROM: ${MAIL_FROM:-Sorsfonalak } PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001} + # The sky of the forum's daily thread. + BACKEND_URL: http://backend:8081 # Purchase notices to Telegram (TELEGRAM_BOT_TOKEN in .env.secrets). TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-} # OPENROUTER_API_KEY (not in git); without it analyses stay pending. @@ -108,6 +114,32 @@ services: read_only: true restart: unless-stopped + # The forum (services/forum): its own service on the same database and login. + forum: + build: + context: . + dockerfile: services/forum/Dockerfile + image: sorsfonalak/forum:latest + ports: + - "8083:8083" + environment: + DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD:-sorsfonalak-dev}@postgres:5432/sorsfonalak + # The links in the forum's e-mails. + PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001} + # Uploaded avatars, in the same object storage as the backend's photos + # (the override file points it at RustFS in development). + S3_ENDPOINT: ${S3_ENDPOINT:-} + S3_BUCKET: ${S3_BUCKET:-} + S3_REGION: ${S3_REGION:-us-east-1} + env_file: + - path: .env.secrets + required: false + depends_on: + postgres: + condition: service_healthy + read_only: true + restart: unless-stopped + frontend: build: context: services/frontend @@ -118,6 +150,12 @@ services: environment: BACKEND_URL: http://backend:8081 HOROSCOPE_API_URL: http://horoscope-api:8080 + # Empty: the forum is switched off (no menu item, its pages 404). + FORUM_URL: ${FORUM_URL:-http://forum:8083} + # The forum's live connection, as the browser reaches it (production: + # Caddy's /api/v1/forum/ws). Over an SSH tunnel, tunnel 8083 too, or the + # forum falls back to polling every 30 seconds. + FORUM_WS_URL: ${FORUM_WS_URL:-ws://localhost:8083/v1/forum/ws} depends_on: backend: condition: service_healthy diff --git a/docs/kozosseg.md b/docs/kozosseg.md new file mode 100644 index 0000000..c23ec6f --- /dev/null +++ b/docs/kozosseg.md @@ -0,0 +1,449 @@ +# 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, Élénk beszélgetések (legalább 3 válasz 24 órán belül; korábban „Pörgős most”), 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 elkészült (2. kör) + +- **Jelentés gomb:** + - Bármely belépett felhasználó jelentheti más hozzászólását vagy a neki küldött privát üzenetet. Az okok: bántó, szolgáltatást hirdet, spam, lelki krízis, jogsértő, más. + - Krízisjelentésnél azonnal megjelenik a 112 és a 116-123. + - Egy felhasználó naponta legfeljebb 20 jelentést küldhet. +- **A moderátorok jelentéslistája** (`/forum/moderalas`): + - Felül a nyitott jelentések, köztük legelöl a krízisjelentések; mellettük a jelentett tartalom. + - Privát üzenetnél csak a jelentett üzenet és az előtte lévő legfeljebb 9 látszik. + - Műveletek: eltávolítás, lezárás, alaptalan. Egy hozzászólás eltávolítása az összes jelentését is lezárja. + - Minden lépés bekerül a naplóba, ami egy második fülön érhető el. + - A fórum sávjában a moderátorok egy „Jelentés: N” jelzést látnak. +- **Telegram-értesítés** az adminnak minden új jelentésről (a worker `notify` feladata): csak a jelentés fajtája és a moderálási oldal linkje, krízisnél kiemelve és elsőként. +- **Privát üzenetek kéréssel:** + - Kérést a Kereső ranggal lehet küldeni, és csak akkor, ha a tag már írt a fórumba. Moderátorra ez nem vonatkozik. + - A kérés egy bemutatkozással megy, legfeljebb 200 karakter, link nélkül. Naponta legfeljebb 3 kérés küldhető. + - A címzett elfogadja, csendben elutasítja (a küldő továbbra is „válaszra vár”-t lát, 14 nap után „lejárt”-at) vagy letiltja a küldőt. + - A saját elutasított vagy lejárt kérés után 30 napig nem lehet újat küldeni. + - A beszélgetésben szöveg és emoji mehet, olvasási visszaigazolás nincs. Az új üzeneteket 15 másodpercenként kérdezi le. + - Bármelyik fél letilthatja a másikat, és csak a letiltó oldhatja fel a tiltást. + - Az „Üzenetek” menüpont jelvénye mutatja az olvasatlan üzeneteket és a megválaszolatlan kéréseket. A profilon jelenik meg a „Beszélgetést kezdeményezek” gomb. +- **E-mail értesítések:** + - A fórumprofilban három beállítás van: + - válasz neked (a száladban vagy a hozzászólásodra): napi összesítő (alapértelmezett), azonnal vagy kikapcsolva; + - új hozzászólás a követett szálakban: napi összesítő vagy kikapcsolva (alapértelmezett); + - privát üzenet és kérés: azonnal (alapértelmezett) vagy kikapcsolva. + - **Azonnali levél:** a fórumszolgáltatás teszi az `email_outbox`-ba. Nem megy levél annak, aki épp online, szálanként óránként legfeljebb egy, beszélgetésenként fél óránként legfeljebb egy. Az üzenet szövege nem kerül bele, a kérés bemutatkozása igen. + - **Napi összesítő:** a worker új `forum` feladata (élesben a `WORKER_TASKS`-ban). Este 18 és 22 óra között, magyar idő szerint, tagonként naponta legfeljebb egy levél, és csak az olvasatlanokról, ha van ilyen. + - **Megszólítás:** a levelek az álnéven szólítanak meg. + - **Leiratkozás:** minden levél alján egy kattintással lehet leiratkozni (a levélprogram leiratkozás gombjával is, RFC 8058), ez a fórum összes levelét kikapcsolja. Oldala: `/forum/leiratkozas`. +- **Adatbázis:** `0039_forum_reports_messages.sql` és `0040_forum_notifications.sql`. + +### Ami elkészült (3. kör) + +- **ÁSZF:** új 8. pont „A fórum” címmel, a régi 8–11. pont 9–12. lett. Tartalma: + - olvasás, írás és álnév; + - házirend: mit kérünk és mi tilos, plusz a 112 és a 116-123; + - a hozzászólások: a szerző felel, felhasználási engedélyt ad, fiók törlése után „Törölt tag”; + - privát üzenetek: a moderátor csak jelentett üzenetet lát; + - rangok és korlátok; + - bejelentés és moderálás: a DSA szerinti visszaigazolás, értesítés, indoklás, kifogás és kapcsolattartási pont; minden döntést ember hoz; + - értesítések. + - A hatály dátuma `2026. november 26.` lett (frontend `TERMS_UPDATED`, backend `TERMS_VERSION`). +- **A DSA-hoz tartozó levelek** (a tag értesítési beállításaitól függetlenül mennek ki): + - **az érintett tagnak** hozzászólás vagy szál eltávolításakor és eltiltáskor: mi történt, az indoklás, az alap (ÁSZF 8.), és hogyan kifogásolhatja; + - **a bejelentőnek** a döntésről: eltávolítottuk, intézkedtünk, vagy nem találtunk szabálysértést. +- **Fiók törlése:** a hozzászólások „Törölt tag” néven maradnak (eldöntve). + +- **Adatvédelmi tájékoztató** (magyarul és angolul): + - **Adattábla:** új sorok a fórumprofilról, a hozzászólásokról, az utolsó látogatásról, a privát beszélgetésekről, a jelentésekről és a moderálási naplóról. Utóbbiak jogalapja a DSA szerinti jogi kötelezettség. + - **Új bekezdések:** + - mi látszik nyilvánosan, és mit látnak a moderátorok; + - a fórum tartalmát nem kapja meg az AI; + - a megőrzési idők; + - a második süti (`sf_forum_theme`); + - a jogoknál a fórum adatai és a „Törölt tag” törlésének kérése. + - **Hatály:** 2026. november 26. +- **Adatexport:** a Profil oldali letöltés (backend `/v1/me/export`) a fórumot is tartalmazza: profil, hozzászólások, reakciók, követések, beszélgetések, elküldött üzenetek és jelentések. +- **Megőrzés** (a worker óránkénti takarítása): + - a moderátor által eltávolított szöveg 1 év után törlődik, a helye és az indoklás marad; + - a lezárt jelentések és a lejárt eltiltások oka 1 év után törlődik, a moderálási napló 2 év után; + - az el nem fogadott kérések 90 nap után törlődnek, és a régi álnevek foglalása is 90 nap után jár le. + +### Ami elkészült (4. kör) + +- **Élő jelzés WebSocketen** (`services/forum/src/live.rs`, `GET /v1/forum/ws`): + - Csak csengő, adatot nem visz: `{"t":"nav"}`, ha a menü számlálói változtak; `{"t":"thread","id":…}`, ha egy szálban történt valami; `{"t":"conversation","id":…}`, ha egy beszélgetésben. Az oldal ilyenkor HTTP-n kéri le az újat. + - Az eseményeket a Postgres `NOTIFY forum_events` viszi, így több fórumpéldánynál is mindenki megkapja. + - A szerver 30 másodpercenként pingel (a Cloudflare 100 másodperc tétlenség után bont), és ez frissíti az online pöttyöt is. + - Csak a saját oldalról lehet kapcsolódni: az `Origin` fejléc ellenőrzése véd az idegen oldalról nyitott kapcsolat ellen. + - Ha nincs kapcsolat, a menü 30 másodpercenként lekérdez. +- **A menü** kliensoldalon frissíti a jelvényeket: élő jelzésre, minden lapváltáskor, és amikor az oldal újra előtérbe kerül. Eddig csak teljes újratöltéskor frissült. +- **Azonnal frissül:** a nyitott szál, a beszélgetés és az üzenetlista. +- **Útvonal:** + - Élesben a Caddy küldi a `/api/v1/forum/ws`-t közvetlenül a fórumszolgáltatásnak (`deploy/Caddyfile`). + - Fejlesztéskor a frontend `FORUM_WS_URL` változója mutat rá (`ws://localhost:8083/v1/forum/ws`). SSH-alagúton át a 8083-as portot is át kell vinni, különben marad a 30 másodperces lekérdezés. + +### Apró módosítások (5. kör) + +- **Gépelésjelzés:** + - A szálban és a privát beszélgetésben látszik, ha valaki épp ír: „Holdfény gépel…”, három halványan mozgó pöttyel. + - Az oldal gépelés közben 3 másodpercenként szól a WebSocketen (`{"typing":"thread"|"conversation","id":…}`). + - A szerver ellenőrzi, hogy a tag láthatja-e az adott helyet (szál vagy elfogadott beszélgetés), és csak a többieknek adja tovább. A jelzés 6 másodperc után eltűnik, és akkor is, amikor megjön a hozzászólás. + - WebSocket nélkül nincs gépelésjelzés. +- **Az emojiválasztó kikerült** a szövegdoboz alól. Mobilon úgyis ott az emojibillentyűzet. +- **Karakterkódok:** gépelés közben emojivá alakulnak, amint szóköz vagy új sor jön utánuk; elküldéskor a sor végén lévők is. A szerver ugyanazt a listát alkalmazza mentéskor, a címekre is. + - A lista: `:)` `:-)` `(:` → 🙂, `:D` → 😄, `xD` → 😆, `;)` → 😉, `:(` → 🙁, `:'(` → 😢, `:P` → 😛, `:O` → 😮, `:*` → 😘, `:/` → 😕, `:|` → 😐, `B)` → 😎, `^^` → 😊, `<3` → ❤️, `, + /// `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`: Cloudflare Turnstile + /// on the e-mail sign-up and password reset forms (see [`crate::turnstile`]); + /// `None` without both (development): no check. + pub turnstile: Option, /// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it /// is missing (development; in production it is made in the console). pub storage_create_bucket: bool, @@ -226,6 +230,14 @@ impl Config { Some("open") => SignupMode::Open, Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"), }, + turnstile: match (var("TURNSTILE_SITE_KEY"), var("TURNSTILE_SECRET_KEY")) { + (Some(site_key), Some(secret)) => Some(crate::turnstile::TurnstileConfig { + site_key, + secret, + verify_url: var("TURNSTILE_VERIFY_URL").unwrap_or_else(|| crate::turnstile::VERIFY_URL.to_string()), + }), + _ => None, + }, storage: match var("S3_ENDPOINT") { None => None, Some(endpoint) => Some(crate::storage::StorageConfig { @@ -279,6 +291,7 @@ impl Config { max_charts_per_user: 50, free_person_slots: 5, signup_mode: SignupMode::Open, + turnstile: None, storage: Some(crate::storage::StorageConfig { endpoint: format!("{horoscope_api_url}/s3"), bucket: "photos".into(), diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index 034138c..9684092 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -23,6 +23,7 @@ mod storage; mod stripe; #[cfg(test)] mod tests; +mod turnstile; mod views; use std::sync::Arc; @@ -49,6 +50,9 @@ pub struct AppState { pub calculator_limiter: LoginLimiter, /// The public place search (typing makes several calls), per visitor address. pub places_limiter: LoginLimiter, + /// E-mail sign-ups and password reset requests, per visitor address (each + /// sends an e-mail, so a script must not send thousands). + pub signup_limiter: LoginLimiter, /// Share visits already counted (link and visitor address, for half an hour): /// a reload is not a new visit, without storing anything in the browser. pub share_visits: LoginLimiter, @@ -70,6 +74,7 @@ impl AppState { calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)), places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)), share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)), + signup_limiter: LoginLimiter::new(10, Duration::from_secs(60 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), storage: config.storage.clone().map(storage::Storage::new), diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs index a3228fa..8e59cad 100644 --- a/services/backend/src/routes/account.rs +++ b/services/backend/src/routes/account.rs @@ -179,6 +179,15 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult = sqlx::query_scalar("SELECT avatar FROM forum.members WHERE user_id = $1") + .bind(auth.id()) + .fetch_optional(&mut *tx) + .await?; sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?; tx.commit().await?; + if let (Some(file), Some(storage)) = (avatar.as_deref().and_then(|a| a.strip_prefix("upload:")), &state.storage) + && let Err(e) = storage.delete(&format!("forum-avatars/{file}")).await + { + tracing::warn!(error = %e, "removing a deleted account's forum avatar"); + } tracing::info!(user = %auth.id(), "account deleted"); Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config)))) } diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index 74e5e85..2877397 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -227,6 +227,19 @@ pub struct RegisterRequest { invite_token: Option, /// The slug of the shared link the visitor came from. referral: Option, + /// Cloudflare Turnstile's token (see [`crate::turnstile`]). + #[serde(default)] + turnstile_token: Option, +} + +/// Before a sign-up or reset e-mail goes out: at most a few per visitor +/// address an hour, and Cloudflare Turnstile's check when it is set up. +async fn not_a_robot(state: &AppState, headers: &axum::http::HeaderMap, token: Option<&str>) -> Result<(), ApiError> { + let ip = super::client_ip(headers); + if let Some(ip) = &ip { + state.signup_limiter.hit(ip)?; + } + crate::turnstile::verify(state.config.turnstile.as_ref(), token, ip.as_deref()).await } /// Password endpoints answer 403 while `PASSWORD_LOGIN` is off. @@ -244,10 +257,12 @@ pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> { /// password instead), so the form does not reveal who is registered. pub async fn register( State(state): St, + headers: axum::http::HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult { password_login_enabled(&state)?; let email = normalize_email(&req.email)?; + not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?; let locale = validate_locale(&state, req.locale.as_deref())?; let mut tx = state.db.begin().await?; @@ -553,6 +568,9 @@ pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> Api #[serde(deny_unknown_fields)] pub struct ResetRequest { email: String, + /// Cloudflare Turnstile's token (see [`crate::turnstile`]). + #[serde(default)] + turnstile_token: Option, } /// Forgotten password: a link to set a new one (also adds a password to a @@ -560,9 +578,11 @@ pub struct ResetRequest { /// whether the address is registered. pub async fn request_password_reset( State(state): St, + headers: axum::http::HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult { password_login_enabled(&state)?; + not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?; let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) }; let mut tx = state.db.begin().await?; let user: Option = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE")) diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 5d7b731..4435698 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -233,5 +233,7 @@ async fn public_config(State(state): St) -> Json { "referral_rewards": c.referral_rewards, "signup_mode": c.signup_mode.as_str(), "password_min_length": crate::auth::MIN_PASSWORD_LEN, + // Cloudflare Turnstile on the e-mail sign-up and reset forms (null: none). + "turnstile_site_key": c.turnstile.as_ref().map(|t| t.site_key.clone()), })) } diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index f813252..4baeba8 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -85,7 +85,7 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> { } /// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`. -pub const TERMS_VERSION: &str = "2026-11-23"; +pub const TERMS_VERSION: &str = "2026-11-26"; /// Only admins can buy through Stripe: until purchases open, and always with a /// test key (nobody gets packages with Stripe's test cards, nobody types a diff --git a/services/backend/src/routes/shares.rs b/services/backend/src/routes/shares.rs index 8e00436..675d3bf 100644 --- a/services/backend/src/routes/shares.rs +++ b/services/backend/src/routes/shares.rs @@ -13,6 +13,12 @@ //! per user: a click proves little. A natal analysis is earned by bringing a //! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and //! makes their own chart, at most [`REFERRAL_LIMIT`] times. +//! +//! A share made for the forum (`for_forum`, a question about one's chart, +//! forecast or synastry) never shows birth data, and its public view leaves +//! out the chart names: they may be real names next to a nickname. A yearly +//! forecast can be shared too: its calculation and its detailed text, without +//! the place of the birthday. use axum::Json; use axum::extract::{Path, State}; @@ -27,6 +33,7 @@ use uuid::Uuid; use super::analyses::{can_see, find_analysis}; use super::charts::{ChartRow, find_chart, owned_chart}; +use super::forecasts::{ForecastRow, find_forecast, owned_forecast}; use super::synastries::{VisibleSynastry, load_synastry, visible_synastry}; use super::{Body, IdPath, St}; use crate::auth::{AuthUser, user_agent}; @@ -39,6 +46,7 @@ pub enum ShareKind { Chart, Synastry, Analysis, + Forecast, } #[derive(Debug, sqlx::FromRow)] @@ -50,16 +58,18 @@ struct ShareRow { chart_id: Option, synastry_id: Option, analysis_id: Option, + forecast_id: Option, title: Option, show_birth_data: bool, + for_forum: bool, view_count: i64, created_at: OffsetDateTime, revoked_at: Option, owner_ip_hash: Option>, } -const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \ - view_count, created_at, revoked_at, owner_ip_hash"; +const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, forecast_id, title, \ + show_birth_data, for_forum, view_count, created_at, revoked_at, owner_ip_hash"; use super::client_ip; @@ -113,8 +123,10 @@ impl ShareRow { "chart_id": self.chart_id, "synastry_id": self.synastry_id, "analysis_id": self.analysis_id, + "forecast_id": self.forecast_id, "title": self.title, "show_birth_data": self.show_birth_data, + "for_forum": self.for_forum, "view_count": self.view_count, "created_at": rfc3339(self.created_at), "revoked_at": rfc3339_opt(self.revoked_at), @@ -132,6 +144,9 @@ pub struct CreateShare { /// Show birth date, time and place (only ever of the sharer's own charts). #[serde(default)] show_birth_data: bool, + /// For a forum post: no birth data, no names, no title. + #[serde(default)] + for_forum: bool, } pub async fn create( @@ -140,14 +155,22 @@ pub async fn create( headers: HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { - let (chart_id, synastry_id, analysis_id, kind) = match req.kind { + let (mut chart_id, mut synastry_id, mut analysis_id, mut forecast_id) = (None, None, None, None); + let kind = match req.kind { ShareKind::Chart => { owned_chart(&state.db, req.target_id, auth.id()).await?; - (Some(req.target_id), None, None, "chart") + chart_id = Some(req.target_id); + "chart" } ShareKind::Synastry => { visible_synastry(&state.db, req.target_id, auth.id()).await?; - (None, Some(req.target_id), None, "synastry") + synastry_id = Some(req.target_id); + "synastry" + } + ShareKind::Forecast => { + owned_forecast(&state.db, req.target_id, auth.id()).await?; + forecast_id = Some(req.target_id); + "forecast" } ShareKind::Analysis => { let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?; @@ -157,14 +180,18 @@ pub async fn create( if analysis.status != "done" { return Err(ApiError::conflict("analysis_not_ready", "Csak elkészült elemzést lehet megosztani.")); } - (None, None, Some(req.target_id), "analysis") + analysis_id = Some(req.target_id); + "analysis" } }; let title = req.title.map(|t| t.trim().chars().take(120).collect::()).filter(|t| !t.is_empty()); + // A forum share: never birth data, and no title of the sharer's own. + let (title, show_birth_data) = if req.for_forum { (None, false) } else { (title, req.show_birth_data) }; let open: Option = sqlx::query_as(&format!( "SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \ AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \ AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \ + AND forecast_id IS NOT DISTINCT FROM $8 AND for_forum = $9 \ ORDER BY created_at DESC LIMIT 1" )) .bind(auth.id()) @@ -173,7 +200,9 @@ pub async fn create( .bind(synastry_id) .bind(analysis_id) .bind(&title) - .bind(req.show_birth_data) + .bind(show_birth_data) + .bind(forecast_id) + .bind(req.for_forum) .fetch_optional(&state.db) .await?; if let Some(row) = open { @@ -182,8 +211,8 @@ pub async fn create( let slug = new_slug(); let row: ShareRow = sqlx::query_as(&format!( "INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \ - owner_ip_hash) \ - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}" + owner_ip_hash, forecast_id, for_forum) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING {SHARE_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(auth.id()) @@ -193,8 +222,10 @@ pub async fn create( .bind(synastry_id) .bind(analysis_id) .bind(title) - .bind(req.show_birth_data) + .bind(show_birth_data) .bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip))) + .bind(forecast_id) + .bind(req.for_forum) .fetch_one(&state.db) .await?; Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url)))) @@ -229,7 +260,27 @@ fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value { // Birth data only of the sharer's own chart, never of a partner's or of a // person they added (that is someone else's data). let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own"; - json!({ "label": chart.label, "chart": public_chart(&chart.result, show) }) + // A forum share leaves out the names (they may be real names next to a nickname). + let label = if share.for_forum { Value::Null } else { Value::from(chart.label.clone()) }; + json!({ "label": label, "chart": public_chart(&chart.result, show) }) +} + +/// A yearly forecast without where it was reckoned: the solar return chart +/// without its place and time zone, and the year's calculation. +fn public_forecast_block(forecast: &ForecastRow) -> Value { + let sr = &forecast.result["solar_return"]; + let solar_return = if sr.is_object() { + let mut chart = public_chart(sr, false); + if let Some(obj) = chart.as_object_mut() { + for key in ["local_time", "timezone", "utc_offset", "moment_utc", "location"] { + obj.remove(key); + } + } + chart + } else { + Value::Null + }; + json!({ "year": forecast.year, "forecast": forecast.result["forecast"], "solar_return": solar_return }) } fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value { @@ -269,6 +320,26 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result { let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?; body["synastry"] = public_synastry_block(&s, share); } + } else if let Some(forecast_id) = share.forecast_id { + let forecast = find_forecast(db, forecast_id).await?.ok_or(ApiError::NotFound("share"))?; + body["forecast"] = public_forecast_block(&forecast); + // The detailed text of the year, if it was written. + let analysis: Option<(String, Option, Option)> = sqlx::query_as( + "SELECT language, content, completed_at FROM analyses \ + WHERE forecast_id = $1 AND kind = 'forecast' AND status = 'done' ORDER BY completed_at DESC LIMIT 1", + ) + .bind(forecast_id) + .fetch_optional(db) + .await?; + body["analysis"] = match analysis { + Some((language, content, completed_at)) => json!({ + "kind": "forecast", + "language": language, + "content": content, + "completed_at": rfc3339_opt(completed_at), + }), + None => Value::Null, + }; } Ok(body) } diff --git a/services/backend/src/storage.rs b/services/backend/src/storage.rs index b791724..c2e650e 100644 --- a/services/backend/src/storage.rs +++ b/services/backend/src/storage.rs @@ -1,276 +1,3 @@ -//! Object storage for uploaded photos: any S3-compatible service, addressed -//! path-style (`{endpoint}/{bucket}/{key}`). In production DigitalOcean -//! Spaces, in development a RustFS container. -//! -//! The bucket stays private: the backend reads the objects itself and serves -//! them under `/v1/public/photos/...`, from where the frontend's image -//! optimizer makes the sized versions (and Cloudflare caches those). -//! -//! Requests are signed with AWS Signature Version 4. +//! Object storage for uploaded photos: the shared `object-storage` crate. -use std::time::Duration; - -use hmac::{Hmac, Mac}; -use sha2::{Digest, Sha256}; -use time::OffsetDateTime; - -/// `S3_ENDPOINT` (e.g. `https://fra1.digitaloceanspaces.com`), `S3_BUCKET`, -/// `S3_REGION` (default `us-east-1`; Spaces accepts it too), -/// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` (in `.env.secrets`). -#[derive(Clone)] -pub struct StorageConfig { - pub endpoint: String, - pub bucket: String, - pub region: String, - pub access_key: String, - pub secret_key: String, -} - -// The secret stays out of logs. -impl std::fmt::Debug for StorageConfig { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("StorageConfig") - .field("endpoint", &self.endpoint) - .field("bucket", &self.bucket) - .field("region", &self.region) - .finish() - } -} - -#[derive(Debug, thiserror::Error)] -pub enum StorageError { - #[error("object storage request failed: {0}")] - Http(#[from] reqwest::Error), - #[error("object storage answered {status}: {body}")] - Status { status: u16, body: String }, -} - -pub struct Storage { - config: StorageConfig, - http: reqwest::Client, -} - -/// An object read back: its bytes and content type. -pub struct Object { - pub bytes: axum::body::Bytes, - pub content_type: Option, -} - -impl Storage { - pub fn new(config: StorageConfig) -> Self { - let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration"); - Self { config, http } - } - - fn url(&self, key: &str) -> String { - let path = if key.is_empty() { String::new() } else { format!("/{}", encode_path(key)) }; - format!("{}/{}{path}", self.config.endpoint, encode_segment(&self.config.bucket)) - } - - async fn send( - &self, - method: reqwest::Method, - key: &str, - body: Vec, - content_type: Option<&str>, - ) -> Result { - let url = self.url(key); - let parsed = reqwest::Url::parse(&url).map_err(|e| StorageError::Status { status: 0, body: e.to_string() })?; - let host = match parsed.port() { - Some(port) => format!("{}:{port}", parsed.host_str().unwrap_or_default()), - None => parsed.host_str().unwrap_or_default().to_string(), - }; - let payload_hash = hex(&Sha256::digest(&body)); - let now = OffsetDateTime::now_utc(); - let auth = authorization(&self.config, method.as_str(), parsed.path(), &host, &payload_hash, now); - let mut request = self - .http - .request(method, url) - .header("x-amz-date", amz_date(now)) - .header("x-amz-content-sha256", &payload_hash) - .header("authorization", auth); - if let Some(ct) = content_type { - request = request.header("content-type", ct); - } - let response = request.body(body).send().await?; - Ok(response) - } - - async fn checked(response: reqwest::Response) -> Result { - if response.status().is_success() { - return Ok(response); - } - let status = response.status().as_u16(); - let body = response.text().await.unwrap_or_default().chars().take(500).collect(); - Err(StorageError::Status { status, body }) - } - - pub async fn put(&self, key: &str, body: Vec, content_type: &str) -> Result<(), StorageError> { - Self::checked(self.send(reqwest::Method::PUT, key, body, Some(content_type)).await?).await?; - Ok(()) - } - - /// The object, or `None` if there is no such key. - pub async fn get(&self, key: &str) -> Result, StorageError> { - let response = self.send(reqwest::Method::GET, key, Vec::new(), None).await?; - if response.status() == reqwest::StatusCode::NOT_FOUND { - return Ok(None); - } - let response = Self::checked(response).await?; - let content_type = response.headers().get("content-type").and_then(|v| v.to_str().ok()).map(str::to_owned); - Ok(Some(Object { bytes: response.bytes().await?, content_type })) - } - - /// Deletes the object; a missing one is not an error. - pub async fn delete(&self, key: &str) -> Result<(), StorageError> { - let response = self.send(reqwest::Method::DELETE, key, Vec::new(), None).await?; - if response.status() == reqwest::StatusCode::NOT_FOUND { - return Ok(()); - } - Self::checked(response).await?; - Ok(()) - } - - /// Creates the bucket if it does not exist yet (development: a fresh - /// RustFS container has none; in production it is made in the console). - pub async fn ensure_bucket(&self) -> Result<(), StorageError> { - let head = self.send(reqwest::Method::HEAD, "", Vec::new(), None).await?; - if head.status().is_success() { - return Ok(()); - } - Self::checked(self.send(reqwest::Method::PUT, "", Vec::new(), None).await?).await?; - tracing::info!(bucket = %self.config.bucket, "object storage bucket created"); - Ok(()) - } -} - -type HmacSha256 = Hmac; - -fn hmac(key: &[u8], data: &str) -> Vec { - let mut mac = HmacSha256::new_from_slice(key).expect("HMAC takes any key length"); - mac.update(data.as_bytes()); - mac.finalize().into_bytes().to_vec() -} - -fn hex(bytes: &[u8]) -> String { - bytes.iter().map(|b| format!("{b:02x}")).collect() -} - -fn amz_date(t: OffsetDateTime) -> String { - format!( - "{:04}{:02}{:02}T{:02}{:02}{:02}Z", - t.year(), - u8::from(t.month()), - t.day(), - t.hour(), - t.minute(), - t.second() - ) -} - -/// URI-encodes one path segment as SigV4 wants it (unreserved characters stay). -fn encode_segment(s: &str) -> String { - s.bytes() - .map(|b| match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), - _ => format!("%{b:02X}"), - }) - .collect() -} - -fn encode_path(key: &str) -> String { - key.split('/').map(encode_segment).collect::>().join("/") -} - -fn signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec { - [date, region, service, "aws4_request"] - .iter() - .fold(format!("AWS4{secret}").into_bytes(), |key, part| hmac(&key, part)) -} - -/// The `Authorization` header of a request (no query string; the path is -/// already encoded, as in the URL). -fn authorization( - config: &StorageConfig, - method: &str, - path: &str, - host: &str, - payload_hash: &str, - now: OffsetDateTime, -) -> String { - let date_time = amz_date(now); - let date = &date_time[..8]; - let signed_headers = "host;x-amz-content-sha256;x-amz-date"; - let canonical = format!( - "{method}\n{path}\n\nhost:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{date_time}\n\n\ - {signed_headers}\n{payload_hash}" - ); - let scope = format!("{date}/{}/s3/aws4_request", config.region); - let to_sign = format!("AWS4-HMAC-SHA256\n{date_time}\n{scope}\n{}", hex(&Sha256::digest(canonical.as_bytes()))); - let signature = hex(&hmac(&signing_key(&config.secret_key, date, &config.region, "s3"), &to_sign)); - format!( - "AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}", - config.access_key - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The signing key example of the AWS documentation ("Examples of how to - /// derive a signing key for Signature Version 4"). - #[test] - fn derives_the_signing_key_like_aws() { - let key = signing_key("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "20150830", "us-east-1", "iam"); - assert_eq!(hex(&key), "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9"); - } - - #[test] - fn builds_the_authorization_header() { - let config = StorageConfig { - endpoint: "http://rustfs:9000".into(), - bucket: "photos".into(), - region: "us-east-1".into(), - access_key: "AKIAIOSFODNN7EXAMPLE".into(), - secret_key: "secret".into(), - }; - let now = OffsetDateTime::from_unix_timestamp(1_369_353_600).unwrap(); - assert_eq!(amz_date(now), "20130524T000000Z"); - let empty = hex(&Sha256::digest(b"")); - assert_eq!(empty, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); - let auth = authorization(&config, "GET", "/photos/a.jpg", "rustfs:9000", &empty, now); - assert!(auth.starts_with( - "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, \ - SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=" - )); - let storage = Storage::new(config); - assert_eq!(storage.url("celebrities/a b/ő.jpg"), "http://rustfs:9000/photos/celebrities/a%20b/%C5%91.jpg"); - assert_eq!(storage.url(""), "http://rustfs:9000/photos"); - } - - /// Against a real S3 service (e.g. the RustFS container of development): - /// `S3_TEST_ENDPOINT=http://127.0.0.1:9000 S3_TEST_KEY=… S3_TEST_SECRET=… - /// cargo test -p backend live_round_trip -- --ignored` - #[tokio::test] - #[ignore] - async fn live_round_trip() { - let env = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("{name} is not set")); - let storage = Storage::new(StorageConfig { - endpoint: env("S3_TEST_ENDPOINT"), - bucket: "storage-test".into(), - region: "us-east-1".into(), - access_key: env("S3_TEST_KEY"), - secret_key: env("S3_TEST_SECRET"), - }); - storage.ensure_bucket().await.unwrap(); - storage.ensure_bucket().await.unwrap(); - let key = "dir/próba kép.jpg"; - storage.put(key, b"hello".to_vec(), "image/jpeg").await.unwrap(); - let object = storage.get(key).await.unwrap().unwrap(); - assert_eq!((&object.bytes[..], object.content_type.as_deref()), (&b"hello"[..], Some("image/jpeg"))); - storage.delete(key).await.unwrap(); - assert!(storage.get(key).await.unwrap().is_none()); - storage.delete(key).await.unwrap(); - } -} +pub use object_storage::*; diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 3647eec..3b9c77c 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -226,12 +226,20 @@ async fn fake_s3( } } +/// Cloudflare Turnstile: the token "ok" with the test secret passes. +async fn fake_turnstile(axum::Form(form): axum::Form>) -> Json { + let ok = form.get("secret").map(String::as_str) == Some("test-secret") + && form.get("response").map(String::as_str) == Some("ok"); + Json(json!({ "success": ok, "error-codes": if ok { json!([]) } else { json!(["invalid-input-response"]) } })) +} + async fn fake_services_with(s3: FakeS3) -> String { let objects = Router::new().route("/s3/photos/{*key}", get(fake_s3).put(fake_s3).delete(fake_s3)).with_state(s3); let app = Router::new() .merge(objects) .route("/billingo/documents/{id}/download", get(fake_billingo_pdf)) .route("/openrouter/models", get(fake_openrouter_models)) + .route("/turnstile/siteverify", post(fake_turnstile)) .route("/v1/checkout/sessions", post(fake_stripe_create)) .route("/v1/checkout/sessions/{id}", get(fake_stripe_get)) .route("/v1/refunds", post(fake_stripe_refund)) @@ -1011,6 +1019,21 @@ async fn public_shares(pool: PgPool) { ); assert_eq!(app.get(&format!("/v1/public/shares/{slug}"), None).await.status, StatusCode::NOT_FOUND); assert_eq!(app.get("/v1/public/shares/nincs-ilyen", None).await.status, StatusCode::NOT_FOUND); + + // A share for the forum: its own link, never birth data, no names, no title. + let r = app + .post( + "/v1/shares", + Some(&anna), + json!({"kind": "chart", "target_id": chart_id, "for_forum": true, "show_birth_data": true, "title": "Én"}), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + assert_eq!((r.body["for_forum"].as_bool(), r.body["show_birth_data"].as_bool()), (Some(true), Some(false))); + let r = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await; + assert!(r.body["chart"]["label"].is_null(), "{}", r.body); + assert!(r.body["chart"]["chart"].get("birth").is_none()); + assert!(r.body["title"].is_null()); } #[sqlx::test(migrator = "db::MIGRATOR")] @@ -1024,12 +1047,39 @@ async fn export_and_delete_account(pool: PgPool) { assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); let r = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": b["id"], "chart2_id": a["id"]})).await; assert_eq!(r.status, StatusCode::OK); // already exists + // Anna also wrote in the forum (services/forum keeps it in the same database). + let (anna_id,): (uuid::Uuid,) = + sqlx::query_as("SELECT id FROM users WHERE email = 'anna@example.com'").fetch_one(&app.pool).await.unwrap(); + sqlx::query( + "INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \ + VALUES ($1, 'Holdfény', 'holdfeny', 'hold-ejkek')", + ) + .bind(anna_id) + .execute(&app.pool) + .await + .unwrap(); + let thread: i64 = sqlx::query_scalar( + "INSERT INTO forum.threads (topic_id, author_id, title) VALUES (4, $1, 'Téli levesek') RETURNING id", + ) + .bind(anna_id) + .fetch_one(&app.pool) + .await + .unwrap(); + sqlx::query("INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'Sütőtök')") + .bind(thread) + .bind(anna_id) + .execute(&app.pool) + .await + .unwrap(); let r = app.get("/v1/me/export", Some(&anna)).await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.body["charts"].as_array().unwrap().len(), 2); assert_eq!(r.body["synastries"].as_array().unwrap().len(), 1); assert!(r.body["login_methods"][0].get("password_hash").is_none()); + assert_eq!(r.body["forum_profile"][0]["nickname"], "Holdfény"); + assert_eq!(r.body["forum_posts"][0]["body"], "Sütőtök"); + assert_eq!(r.body["forum_posts"][0]["thread_title"], "Téli levesek"); let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "yes"}))).await; assert_eq!(r.status, StatusCode::BAD_REQUEST); @@ -1041,6 +1091,15 @@ async fn export_and_delete_account(pool: PgPool) { assert_eq!(r.status, StatusCode::UNAUTHORIZED); let (left,): (i64,) = sqlx::query_as("SELECT count(*) FROM charts").fetch_one(&app.pool).await.unwrap(); assert_eq!(left, 0); + // Her forum profile is gone; her thread stays, by "Törölt tag" (no author). + let (members, author): (i64, Option) = sqlx::query_as( + "SELECT (SELECT count(*) FROM forum.members), (SELECT author_id FROM forum.threads WHERE id = $1)", + ) + .bind(thread) + .fetch_one(&app.pool) + .await + .unwrap(); + assert_eq!((members, author), (0, None)); assert_eq!(app.get("/v1/me", Some(&bela)).await.status, StatusCode::OK); } @@ -1932,6 +1991,19 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) { assert_eq!(app.get(&uri, Some(&bob)).await.status, StatusCode::NOT_FOUND); assert_eq!(app.get(&format!("/v1/forecasts/{id}"), Some(&anna)).await.body["year"], json!(year)); + // A forecast can be shared (not by others), without where it was reckoned. + let r = app.post("/v1/shares", Some(&bob), json!({"kind": "forecast", "target_id": away.body["id"]})).await; + assert_eq!(r.status, StatusCode::NOT_FOUND); + let r = app + .post("/v1/shares", Some(&anna), json!({"kind": "forecast", "target_id": away.body["id"], "for_forum": true})) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let shared = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await.body; + assert_eq!(shared["kind"], "forecast"); + assert_eq!(shared["forecast"]["forecast"]["start"], format!("{year}-03-15")); + assert!(!shared.to_string().contains("Tokió"), "the place stays private: {shared}"); + assert!(shared["analysis"].is_null(), "no detailed text yet"); + // the detailed text uses a forecast unit, not a natal one let analyses = format!("/v1/forecasts/{id}/analyses"); grant_units(&app, &anna, "natal", 1).await; @@ -4031,3 +4103,42 @@ async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) { assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn email_sign_up_checks_turnstile_and_limits_each_address(pool: PgPool) { + let app = TestApp::with_config(pool, |c| { + c.turnstile = Some(crate::turnstile::TurnstileConfig { + site_key: "site-key".into(), + secret: "test-secret".into(), + verify_url: format!("{}/turnstile/siteverify", c.horoscope_api_url), + }); + }) + .await; + assert_eq!(app.get("/v1/config", None).await.body["turnstile_site_key"], "site-key"); + let ip = [("x-real-ip", "203.0.113.50")]; + let sign_up = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token }); + + // No token or a wrong one: no account, no e-mail. + for token in [None, Some("rossz")] { + let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(token)), &ip).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST, "{}", r.body); + } + let users: i64 = sqlx::query_scalar("SELECT count(*) FROM users").fetch_one(&app.pool).await.unwrap(); + assert_eq!(users, 0); + let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(Some("ok"))), &ip).await; + assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body); + let reset = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token }); + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(None)), &ip).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + + // Ten e-mail requests an hour from one address (the four above count too). + for _ in 0..6 { + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await; + assert_eq!(r.status, StatusCode::ACCEPTED); + } + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await; + assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); + let elsewhere = [("x-real-ip", "198.51.100.60")]; + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &elsewhere).await; + assert_eq!(r.status, StatusCode::ACCEPTED); +} diff --git a/services/backend/src/turnstile.rs b/services/backend/src/turnstile.rs new file mode 100644 index 0000000..e601b57 --- /dev/null +++ b/services/backend/src/turnstile.rs @@ -0,0 +1,63 @@ +//! Cloudflare Turnstile: the e-mail sign-up and the password reset forms +//! carry a token from Cloudflare's widget (usually invisible), checked here +//! before an e-mail goes out. Without the keys (development) there is no +//! check. Cloudflare not answering counts as a failed check. + +use std::sync::OnceLock; +use std::time::Duration; + +use serde::Deserialize; + +use crate::error::ApiError; + +pub const VERIFY_URL: &str = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; + +#[derive(Clone, Debug)] +pub struct TurnstileConfig { + /// Public: the page's widget uses it (`/v1/config`). + pub site_key: String, + pub secret: String, + pub verify_url: String, +} + +#[derive(Deserialize)] +struct Answer { + success: bool, + #[serde(default, rename = "error-codes")] + error_codes: Vec, +} + +fn client() -> &'static reqwest::Client { + static CLIENT: OnceLock = OnceLock::new(); + CLIENT.get_or_init(|| reqwest::Client::builder().timeout(Duration::from_secs(8)).build().expect("an HTTP client")) +} + +fn refused() -> ApiError { + ApiError::BadRequest("Kérjük, igazold, hogy nem robot vagy (az ellenőrzés nem sikerült), és próbáld újra.".into()) +} + +/// Checks the widget's token (with the visitor's address, when known). +pub async fn verify(config: Option<&TurnstileConfig>, token: Option<&str>, ip: Option<&str>) -> Result<(), ApiError> { + let Some(config) = config else { return Ok(()) }; + let token = token.map(str::trim).filter(|t| !t.is_empty() && t.len() <= 2048).ok_or_else(refused)?; + let mut form = vec![("secret", config.secret.as_str()), ("response", token)]; + if let Some(ip) = ip { + form.push(("remoteip", ip)); + } + let answer: Answer = match client().post(&config.verify_url).form(&form).send().await { + Ok(res) => res.json().await.map_err(|e| { + tracing::warn!(error = %e, "turnstile answer not understood"); + refused() + })?, + Err(e) => { + tracing::warn!(error = %e, "turnstile not reachable"); + return Err(refused()); + } + }; + if answer.success { + Ok(()) + } else { + tracing::info!(codes = ?answer.error_codes, "turnstile check failed"); + Err(refused()) + } +} diff --git a/services/forum/Cargo.toml b/services/forum/Cargo.toml new file mode 100644 index 0000000..c1f6b15 --- /dev/null +++ b/services/forum/Cargo.toml @@ -0,0 +1,34 @@ +[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 +object-storage.workspace = true +image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] } +sha2.workspace = true +service-kit.workspace = true +anyhow.workspace = true +axum = { workspace = true, features = ["ws"] } +axum-extra.workspace = true +deunicode.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +sqlx.workspace = true +thiserror.workspace = true +time.workspace = true +tokio = { workspace = true, features = ["time"] } +tower-http.workspace = true +tracing.workspace = true +uuid.workspace = true + +[dev-dependencies] +tower = { version = "0.5", features = ["util"] } +tokio-tungstenite = "0.29" +futures-util = { version = "0.3", default-features = false } +http-body-util = "0.1" diff --git a/services/forum/Dockerfile b/services/forum/Dockerfile new file mode 100644 index 0000000..5167053 --- /dev/null +++ b/services/forum/Dockerfile @@ -0,0 +1,33 @@ +# syntax=docker/dockerfile:1 +# +# Build from the repository root: +# docker build -f services/forum/Dockerfile -t sorsfonalak/forum . + +ARG RUST_VERSION=1.99 + +# --- 1. static (musl) build ---------------------------------------------------- +FROM rust:${RUST_VERSION}-alpine AS build +RUN apk add --no-cache musl-dev +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY crates crates +COPY services services +RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \ + --mount=type=cache,target=/app/target,sharing=locked \ + cargo build --release --locked -p forum \ + && cp target/release/forum /forum +# The log directory (LOG_DIR); a volume mounted here takes over its owner. +RUN mkdir /logs + +# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) --- +FROM scratch +COPY --from=build /forum /forum +COPY --from=build --chown=65532:65532 /logs /logs +ENV BIND_ADDR=0.0.0.0:8083 \ + LOG_FORMAT=json \ + RUST_LOG=info +USER 65532:65532 +EXPOSE 8083 +HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ + CMD ["/forum", "healthcheck"] +ENTRYPOINT ["/forum"] diff --git a/services/forum/src/auth.rs b/services/forum/src/auth.rs new file mode 100644 index 0000000..8d34536 --- /dev/null +++ b/services/forum/src/auth.rs @@ -0,0 +1,166 @@ +//! Who is asking: the backend's session (cookie or Bearer token) and the +//! member behind it. Reading needs no login; writing needs a nickname. +//! Every request of a member also keeps the online dot fresh. + +use std::sync::Arc; + +use axum::extract::FromRequestParts; +use axum::http::header::AUTHORIZATION; +use axum::http::request::Parts; +use axum_extra::extract::cookie::CookieJar; +use db::{Role, User}; +use time::OffsetDateTime; +use uuid::Uuid; + +use crate::AppState; +use crate::error::ApiError; +use crate::rank::Rank; + +pub const SESSION_COOKIE: &str = "sf_session"; + +/// How long a member counts as online after the last request. +pub const ONLINE_MINUTES: i64 = 5; + +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct Member { + pub user_id: Uuid, + pub nickname: String, + pub avatar: String, + pub bio: String, + pub chart_share: String, + pub invisible: bool, + pub points: i32, + pub post_count: i32, + pub created_at: OffsetDateTime, + pub nickname_changed_at: OffsetDateTime, + pub banned_until: Option, + pub ban_reason: Option, + pub email_replies: String, + pub email_followed: String, + pub email_messages: String, + pub email_mentions: String, + pub email_listener: String, + pub email_weekly: bool, + pub listener: bool, + pub supporter_badge: bool, +} + +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, email_replies, email_followed, email_messages, \ + email_mentions, email_listener, email_weekly, listener, supporter_badge"; + +impl Member { + pub fn rank(&self, now: OffsetDateTime) -> Rank { + Rank::of(self.points, self.created_at, now) + } + + pub fn banned(&self, now: OffsetDateTime) -> bool { + self.banned_until.is_some_and(|until| until > now) + } +} + +/// The visitor: maybe logged in, maybe a member (has chosen a nickname). +#[derive(Debug, Clone, Default)] +pub struct Viewer { + pub user: Option, + pub member: Option, + /// The restricted topics the member was approved into. + pub topics: Vec, + /// The members they muted. + pub mutes: Vec, +} + +impl Viewer { + pub fn user_id(&self) -> Option { + self.user.as_ref().map(|u| u.id) + } + + pub fn logged_in(&self) -> bool { + self.user.is_some() + } + + pub fn is_admin(&self) -> bool { + self.user.as_ref().is_some_and(|u| u.has_role(Role::Admin)) + } + + /// A moderator or an admin. + pub fn is_moderator(&self) -> bool { + self.user.as_ref().is_some_and(|u| u.has_role(Role::Moderator) || u.has_role(Role::Admin)) + } + + pub fn require_user(&self) -> Result<&User, ApiError> { + self.user.as_ref().ok_or(ApiError::Unauthorized) + } + + pub fn require_member(&self) -> Result<&Member, ApiError> { + self.require_user()?; + self.member.as_ref().ok_or(ApiError::NicknameRequired) + } + + /// A member who may write (not banned). + pub fn require_writer(&self) -> Result<&Member, ApiError> { + let member = self.require_member()?; + if member.banned(OffsetDateTime::now_utc()) { + let reason = member.ban_reason.as_deref().map(|r| format!(" Indok: {r}")).unwrap_or_default(); + return Err(ApiError::Banned(format!("Most nem írhatsz a fórumba.{reason}"))); + } + Ok(member) + } + + pub fn require_moderator(&self) -> Result<&User, ApiError> { + let user = self.require_user()?; + if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) } + } +} + +fn session_token(parts: &Parts) -> Option { + if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()) + && let Some(token) = value.strip_prefix("Bearer ") + { + return Some(token.trim().to_string()); + } + CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string()) +} + +impl FromRequestParts> for Viewer { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { + let Some(token) = session_token(parts) else { return Ok(Viewer::default()) }; + let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) }; + let member = load_member(&state.db, user.id).await?; + if member.is_some() { + // At most once a minute per member: the online dot. + sqlx::query( + "UPDATE forum.members SET last_seen_at = now() \ + WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')", + ) + .bind(user.id) + .execute(&state.db) + .await?; + } + let (topics, mutes) = if member.is_some() { + let topics = sqlx::query_scalar( + "SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'approved'", + ) + .bind(user.id) + .fetch_all(&state.db) + .await?; + let mutes = sqlx::query_scalar("SELECT muted_id FROM forum.mutes WHERE user_id = $1") + .bind(user.id) + .fetch_all(&state.db) + .await?; + (topics, mutes) + } else { + (Vec::new(), Vec::new()) + }; + Ok(Viewer { user: Some(user), member, topics, mutes }) + } +} + +pub async fn load_member(db: &sqlx::PgPool, user_id: Uuid) -> Result, sqlx::Error> { + sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1")) + .bind(user_id) + .fetch_optional(db) + .await +} diff --git a/services/forum/src/error.rs b/services/forum/src/error.rs new file mode 100644 index 0000000..96a848c --- /dev/null +++ b/services/forum/src/error.rs @@ -0,0 +1,92 @@ +use axum::Json; +use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde_json::json; + +/// API error, rendered as `{"error": {"code", "message"}}` like the backend's. +/// Messages meant for the user are Hungarian. +#[derive(Debug, thiserror::Error)] +pub enum ApiError { + #[error("{0}")] + BadRequest(String), + #[error("authentication required")] + Unauthorized, + /// Logged in, but no nickname yet: the frontend sends the user to choose one. + #[error("Előbb válassz álnevet.")] + NicknameRequired, + #[error("{0}")] + Forbidden(String), + /// Banned from writing; the message tells until when. + #[error("{0}")] + Banned(String), + #[error("{0} not found")] + NotFound(&'static str), + #[error("{message}")] + Conflict { code: &'static str, message: String }, + /// A usage limit; the message is shown to the user as is. + #[error("{0}")] + Limited(String), + #[error("internal error")] + Internal(String), +} + +impl ApiError { + pub fn conflict(code: &'static str, message: impl Into) -> Self { + ApiError::Conflict { code, message: message.into() } + } + + pub fn bad(message: impl Into) -> Self { + ApiError::BadRequest(message.into()) + } + + fn status_and_code(&self) -> (StatusCode, &'static str) { + match self { + ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"), + ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"), + ApiError::NicknameRequired => (StatusCode::FORBIDDEN, "nickname_required"), + ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"), + ApiError::Banned(_) => (StatusCode::FORBIDDEN, "banned"), + ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"), + ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code), + ApiError::Limited(_) => (StatusCode::TOO_MANY_REQUESTS, "limited"), + ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"), + } + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let (status, code) = self.status_and_code(); + if let ApiError::Internal(detail) = &self { + tracing::error!(error = %detail, code, "request failed"); + } + (status, Json(json!({ "error": { "code": code, "message": self.to_string() } }))).into_response() + } +} + +impl From for ApiError { + fn from(e: sqlx::Error) -> Self { + ApiError::Internal(format!("database: {e}")) + } +} + +impl From for ApiError { + fn from(rejection: JsonRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} + +impl From for ApiError { + fn from(rejection: QueryRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} + +impl From for ApiError { + fn from(rejection: PathRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} + +pub type ApiResult = Result; diff --git a/services/forum/src/links/mod.rs b/services/forum/src/links/mod.rs new file mode 100644 index 0000000..d643d33 --- /dev/null +++ b/services/forum/src/links/mod.rs @@ -0,0 +1,195 @@ +//! The link module: recognises links in a post and shows a preview for the +//! ones a provider knows. For now only YouTube ([`youtube`]). Previews are +//! fetched when a post is written or edited (a few seconds at most), kept in +//! `forum.link_previews`, and found again from the text when posts are shown. +//! Thumbnails are stored in our own object storage and served by the forum, +//! so reading a thread sends nothing to the provider. + +pub mod youtube; + +use axum::extract::{Path, State}; +use axum::http::header; +use axum::response::{IntoResponse, Response}; +use axum_extra::extract::WithRejection; +use serde_json::{Value, json}; +use sqlx::PgPool; + +use crate::AppState; +use crate::error::{ApiError, ApiResult}; +use crate::routes::St; + +/// At most this many previews under one post. +pub const MAX_PER_POST: usize = 3; +/// The thumbnails' folder in the bucket. +pub const FOLDER: &str = "forum-links"; + +/// Where the providers are asked (the tests point them at a fake server). +#[derive(Clone)] +pub struct LinkConfig { + pub http: reqwest::Client, + pub youtube_oembed: String, + pub youtube_thumbs: String, +} + +impl LinkConfig { + pub fn new(youtube_oembed: &str, youtube_thumbs: &str) -> Self { + let http = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .user_agent("Sorsfonalak-Forum/1.0 (link preview)") + .build() + .expect("an HTTP client"); + Self { + http, + youtube_oembed: youtube_oembed.trim_end_matches('/').to_string(), + youtube_thumbs: youtube_thumbs.trim_end_matches('/').to_string(), + } + } + + pub fn from_env() -> Self { + let var = |name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.to_string()); + Self::new( + &var("YOUTUBE_OEMBED_URL", "https://www.youtube.com/oembed"), + &var("YOUTUBE_THUMBS_URL", "https://i.ytimg.com"), + ) + } +} + +/// A recognised link in a post's text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Found { + pub provider: &'static str, + pub key: String, + /// As written in the post. + pub url: String, + /// Where to start playing, in seconds. + pub start: Option, +} + +/// The links of a text the providers know (each video once, at most [`MAX_PER_POST`]). +pub fn find(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for word in text.split_whitespace() { + let word = word.trim_matches(|c: char| matches!(c, '(' | ')' | '<' | '>' | '"' | '\'' | '„' | '”' | '«' | '»')); + let word = word.trim_end_matches(['.', ',', ';', ':', '!', '?']); + if !word.starts_with("http://") && !word.starts_with("https://") { + continue; + } + let Ok(url) = reqwest::Url::parse(word) else { continue }; + if let Some((key, start)) = youtube::video(&url) + && !out.iter().any(|f| f.provider == youtube::PROVIDER && f.key == key) + { + out.push(Found { provider: youtube::PROVIDER, key, url: word.to_string(), start }); + } + if out.len() == MAX_PER_POST { + break; + } + } + out +} + +/// Fetches the previews a text needs and does not have yet. Failures only +/// leave a link without a preview (the next edit tries again). +pub async fn process(state: &AppState, text: &str) { + for found in find(text) { + let known: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.link_previews WHERE provider = $1 AND key = $2)") + .bind(found.provider) + .bind(&found.key) + .fetch_one(&state.db) + .await + .unwrap_or(true); + if known { + continue; + } + let result = match found.provider { + youtube::PROVIDER => youtube::fetch(state, &found.key).await, + _ => continue, + }; + if let Err(e) = result { + tracing::warn!(provider = found.provider, key = %found.key, error = %e, "link preview not made"); + } + } +} + +/// The previews of these posts' texts, by post id, as the page shows them. +pub async fn previews( + db: &PgPool, + texts: &[(i64, &str)], +) -> Result, sqlx::Error> { + let found: Vec<(i64, Vec)> = + texts.iter().map(|(id, text)| (*id, find(text))).filter(|(_, f)| !f.is_empty()).collect(); + if found.is_empty() { + return Ok(Default::default()); + } + let keys: Vec = found.iter().flat_map(|(_, f)| f.iter().map(|x| x.key.clone())).collect(); + type Row = (String, String, String, Option, Option); + let rows: Vec = + sqlx::query_as("SELECT provider, key, title, author, thumbnail FROM forum.link_previews WHERE key = ANY($1)") + .bind(&keys) + .fetch_all(db) + .await?; + Ok(found + .into_iter() + .filter_map(|(id, links)| { + let shown: Vec = links + .iter() + .filter_map(|f| { + let (_, _, title, author, thumb) = + rows.iter().find(|(provider, key, ..)| provider == f.provider && *key == f.key)?; + Some(json!({ + "provider": f.provider, + "id": f.key, + "url": f.url, + "start": f.start, + "title": title, + "author": author, + "thumbnail": thumb.as_ref().map(|t| format!("/api/v1/forum/link-thumbs/{t}")), + })) + }) + .collect(); + (!shown.is_empty()).then_some((id, Value::Array(shown))) + }) + .collect()) +} + +/// `GET /v1/forum/link-thumbs/{file}`: a stored thumbnail (cached for good). +pub async fn thumbnail( + State(state): St, + WithRejection(Path(file), _): WithRejection, ApiError>, +) -> ApiResult { + let valid = file.len() <= 64 + && file.ends_with(".jpg") + && file.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')); + if !valid { + return Err(ApiError::NotFound("thumbnail")); + } + let storage = state.storage.as_ref().ok_or(ApiError::NotFound("thumbnail"))?; + let object = storage + .get(&format!("{FOLDER}/{file}")) + .await + .map_err(|e| ApiError::Internal(format!("reading a thumbnail: {e}")))? + .ok_or(ApiError::NotFound("thumbnail"))?; + Ok(( + [(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")], + object.bytes, + ) + .into_response()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_the_links_providers_know() { + let text = "Nézzétek: https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s, és (https://youtu.be/dQw4w9WgXcQ) \ + meg https://youtube.com/shorts/abcdefghijk! Ez nem: https://example.com/watch?v=dQw4w9WgXcQ"; + let found = find(text); + assert_eq!(found.len(), 2, "{found:?}"); + assert_eq!(found[0].key, "dQw4w9WgXcQ"); + assert_eq!(found[0].start, Some(90)); + assert_eq!(found[0].url, "https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s"); + assert_eq!(found[1].key, "abcdefghijk"); + assert!(find("Nincs itt link, csak youtube.com/watch?v=dQw4w9WgXcQ").is_empty()); + } +} diff --git a/services/forum/src/links/youtube.rs b/services/forum/src/links/youtube.rs new file mode 100644 index 0000000..30128b3 --- /dev/null +++ b/services/forum/src/links/youtube.rs @@ -0,0 +1,175 @@ +//! YouTube links: the video's id (and where to start) from the usual forms +//! of address, its title and channel from YouTube's oEmbed answer, and its +//! thumbnail cut to 16:9 and kept in our storage. + +use std::io::Cursor; + +use image::codecs::jpeg::JpegEncoder; +use image::imageops::FilterType; +use image::{ImageFormat, ImageReader}; +use serde::Deserialize; + +use super::FOLDER; +use crate::AppState; + +pub const PROVIDER: &str = "youtube"; +/// The stored thumbnail: 480×270. +const WIDTH: u32 = 480; +const HEIGHT: u32 = 270; + +fn valid_id(id: &str) -> bool { + id.len() == 11 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +/// "90", "90s", "1m30s", "1h2m3s" as seconds. +fn seconds(raw: &str) -> Option { + if let Ok(n) = raw.parse::() { + return Some(n); + } + let (mut total, mut number) = (0u32, String::new()); + for c in raw.chars() { + match c { + '0'..='9' => number.push(c), + 'h' | 'm' | 's' => { + let n: u32 = number.parse().ok()?; + total += n * match c { + 'h' => 3600, + 'm' => 60, + _ => 1, + }; + number.clear(); + } + _ => return None, + } + } + number.is_empty().then_some(total).filter(|t| *t > 0) +} + +/// The video id and start (seconds) of a YouTube address: watch, shorts, +/// live, embed and youtu.be links, on www., m. and music. too. +pub fn video(url: &reqwest::Url) -> Option<(String, Option)> { + let host = url.host_str()?.to_ascii_lowercase(); + let host = host.strip_prefix("www.").unwrap_or(&host); + let param = |name: &str| url.query_pairs().find(|(k, _)| k == name).map(|(_, v)| v.into_owned()); + let mut segments = url.path_segments()?; + let id = match host { + "youtu.be" => segments.next().map(str::to_string), + "youtube.com" | "m.youtube.com" | "music.youtube.com" => match segments.next() { + Some("watch") => param("v"), + Some("shorts" | "live" | "embed") => segments.next().map(str::to_string), + _ => None, + }, + _ => None, + }?; + if !valid_id(&id) { + return None; + } + let start = param("t").or_else(|| param("start")).as_deref().and_then(seconds); + Some((id, start)) +} + +/// YouTube's oEmbed answer (live streams come without title and channel). +#[derive(Deserialize)] +struct OEmbed { + #[serde(default)] + title: Option, + #[serde(default)] + author_name: Option, +} + +/// The card's title when YouTube gives none. +const NO_TITLE: &str = "YouTube-videó"; + +/// The video's title and channel, and its thumbnail into the storage. +pub async fn fetch(state: &AppState, id: &str) -> anyhow::Result<()> { + let links = &state.links; + let watch = format!("https://www.youtube.com/watch?v={id}"); + let answer = links + .http + .get(&links.youtube_oembed) + .query(&[("url", watch.as_str()), ("format", "json")]) + .send() + .await? + .error_for_status()? + .text() + .await?; + let meta: OEmbed = serde_json::from_str(&answer).map_err(|e| { + anyhow::anyhow!("oEmbed answer not understood ({e}): {}", answer.chars().take(160).collect::()) + })?; + // Without a thumbnail the card still shows (title and play button). + let thumbnail = match &state.storage { + Some(storage) => match store_thumbnail(state, storage, id).await { + Ok(file) => Some(file), + Err(e) => { + tracing::warn!(key = id, error = %e, "no thumbnail for a YouTube link"); + None + } + }, + None => None, + }; + let title: String = meta.title.filter(|t| !t.trim().is_empty()).unwrap_or_else(|| NO_TITLE.into()); + let title: String = title.chars().take(200).collect(); + let author = meta.author_name.map(|a| a.chars().take(100).collect::()); + sqlx::query( + "INSERT INTO forum.link_previews (provider, key, title, author, thumbnail) VALUES ($1, $2, $3, $4, $5) \ + ON CONFLICT (provider, key) DO UPDATE SET title = EXCLUDED.title, author = EXCLUDED.author, \ + thumbnail = COALESCE(EXCLUDED.thumbnail, forum.link_previews.thumbnail), fetched_at = now()", + ) + .bind(PROVIDER) + .bind(id) + .bind(&title) + .bind(&author) + .bind(&thumbnail) + .execute(&state.db) + .await?; + Ok(()) +} + +async fn store_thumbnail(state: &AppState, storage: &object_storage::Storage, id: &str) -> anyhow::Result { + let bytes = state + .links + .http + .get(format!("{}/vi/{id}/hqdefault.jpg", state.links.youtube_thumbs)) + .send() + .await? + .error_for_status()? + .bytes() + .await?; + let jpeg = widescreen(&bytes)?; + let file = format!("{PROVIDER}-{id}.jpg"); + storage.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg").await?; + Ok(file) +} + +/// YouTube's 4:3 thumbnail (with black bands) as a 16:9 JPEG. +fn widescreen(bytes: &[u8]) -> anyhow::Result> { + let img = ImageReader::with_format(Cursor::new(bytes), ImageFormat::Jpeg).decode()?; + let (w, h) = (img.width(), img.height()); + let band_h = (w * 9 / 16).min(h); + let cropped = img.crop_imm(0, (h - band_h) / 2, w, band_h); + let small = cropped.resize_exact(WIDTH, HEIGHT, FilterType::Triangle).to_rgb8(); + let mut out = Vec::new(); + JpegEncoder::new_with_quality(&mut out, 82).encode_image(&small)?; + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_youtube_addresses() { + let id = |s: &str| video(&reqwest::Url::parse(s).unwrap()); + assert_eq!(id("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None))); + assert_eq!( + id("https://m.youtube.com/watch?feature=share&v=dQw4w9WgXcQ&t=42"), + Some(("dQw4w9WgXcQ".into(), Some(42))) + ); + assert_eq!(id("https://youtu.be/dQw4w9WgXcQ?t=1h2m3s"), Some(("dQw4w9WgXcQ".into(), Some(3723)))); + assert_eq!(id("https://youtube.com/shorts/dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None))); + assert_eq!(id("https://music.youtube.com/watch?v=dQw4w9WgXcQ&list=x"), Some(("dQw4w9WgXcQ".into(), None))); + assert_eq!(id("https://www.youtube.com/@csatorna"), None); + assert_eq!(id("https://www.youtube.com/watch?v=rovid"), None); + assert_eq!(id("https://notyoutube.com/watch?v=dQw4w9WgXcQ"), None); + } +} diff --git a/services/forum/src/live.rs b/services/forum/src/live.rs new file mode 100644 index 0000000..6aab4e4 --- /dev/null +++ b/services/forum/src/live.rs @@ -0,0 +1,349 @@ +//! Live notices over WebSocket: a doorbell, never the data. The server only +//! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread", +//! "id":…}`: a thread; `{"t":"conversation","id":…}`), and the page fetches the +//! news over HTTP as before. The one thing a page says is that its member is +//! typing (`{"typing":"thread"|"conversation","id":…}`, every few seconds while +//! they type); the others there get `{"t":"typing","kind":…,"id":…,"who":…}`. A dropped connection loses nothing: the page asks +//! again when it reconnects, and polls while it cannot. +//! +//! Events go through Postgres (`NOTIFY forum_events`), so every instance of the +//! service hears every change, whichever instance it happened on; each one +//! passes them to its own connections. + +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::State; +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use sqlx::PgPool; +use sqlx::postgres::PgListener; +use tokio::sync::broadcast; +use uuid::Uuid; + +use crate::AppState; +use crate::auth::Viewer; + +pub const CHANNEL: &str = "forum_events"; +/// A ping this often keeps the connection open through proxies (Cloudflare +/// closes one idle for 100 seconds), and refreshes the online dot. +const PING: Duration = Duration::from_secs(30); +/// Above this many recipients an event goes to everyone (NOTIFY payloads are small). +const MAX_USERS: usize = 300; + +/// What changed, and for whom. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub struct Event { + /// A thread got a post, an edit, a reaction or a removal (anyone viewing it refetches). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thread: Option, + /// A conversation changed (only its two members hear it, through `users`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// Whose menu counts changed. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub users: Vec, + /// Everyone's menu (too many recipients to list). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub everyone: bool, + /// The moderators' menu (the open reports). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub moderators: bool, + /// Someone is typing in a thread (everyone there sees it) or a + /// conversation (the other member, in `users`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub typing: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Typing { + /// `thread` or `conversation`. + pub kind: String, + pub id: i64, + /// The nickname shown ("Holdfény gépel…"). + pub who: String, + /// Who types (they do not hear of themselves). + pub from: Uuid, +} + +impl Event { + pub fn for_users(mut self, users: Vec) -> Self { + if users.len() > MAX_USERS { + self.everyone = true; + } else { + self.users = users; + } + self + } + + /// The messages one connection gets from this event. + pub fn messages_for(&self, user: Uuid, moderator: bool) -> Vec { + if let Some(t) = &self.typing { + let hears = t.from != user && (t.kind == "thread" || self.users.contains(&user)); + return if hears { + vec![json!({ "t": "typing", "kind": t.kind, "id": t.id, "who": t.who }).to_string()] + } else { + Vec::new() + }; + } + let mine = self.everyone || self.users.contains(&user); + let mut out = Vec::new(); + if let Some(id) = self.thread { + out.push(json!({ "t": "thread", "id": id }).to_string()); + } + if let (Some(id), true) = (self.conversation, self.users.contains(&user)) { + out.push(json!({ "t": "conversation", "id": id }).to_string()); + } + if mine || (self.moderators && moderator) { + out.push(json!({ "t": "nav" }).to_string()); + } + out + } +} + +/// The events of this instance, for its connections. +#[derive(Clone)] +pub struct Hub { + tx: broadcast::Sender>, +} + +impl Default for Hub { + fn default() -> Self { + Self { tx: broadcast::channel(1024).0 } + } +} + +impl Hub { + pub fn subscribe(&self) -> broadcast::Receiver> { + self.tx.subscribe() + } +} + +/// Announces a change to every instance. A failure is logged: the pages poll anyway. +pub async fn emit(db: &PgPool, event: Event) { + let payload = serde_json::to_string(&event).unwrap_or_default(); + if let Err(e) = sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&payload).execute(db).await { + tracing::warn!(error = %e, "announcing a forum event"); + } +} + +/// Passes the database's events to this instance's connections, for good +/// (it reconnects after a lost database connection). +pub async fn listen(db: PgPool, hub: Hub) { + loop { + match PgListener::connect_with(&db).await { + Ok(mut listener) => { + if let Err(e) = listener.listen(CHANNEL).await { + tracing::warn!(error = %e, "LISTEN forum_events failed"); + } else { + loop { + match listener.recv().await { + Ok(note) => match serde_json::from_str::(note.payload()) { + Ok(event) => { + // No connection listening is fine. + let _ = hub.tx.send(Arc::new(event)); + } + Err(e) => tracing::warn!(error = %e, "unreadable forum event"), + }, + Err(e) => { + tracing::warn!(error = %e, "forum events: listener lost"); + break; + } + } + } + } + } + Err(e) => tracing::warn!(error = %e, "forum events: cannot listen"), + } + tokio::time::sleep(Duration::from_secs(3)).await; + } +} + +/// Only the site itself may open a connection with the visitor's cookie +/// (no cross-site WebSocket hijacking). +fn origin_allowed(headers: &HeaderMap, base_url: &str) -> bool { + match headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) { + Some(origin) => origin.trim_end_matches('/') == base_url, + // Not a browser (no Origin header): it brings its own token. + None => headers.contains_key(header::AUTHORIZATION), + } +} + +/// `GET /v1/forum/ws`: a member's live connection. +pub async fn connect( + State(state): State>, + viewer: Viewer, + headers: HeaderMap, + ws: WebSocketUpgrade, +) -> Response { + if !origin_allowed(&headers, &state.base_url) { + return StatusCode::FORBIDDEN.into_response(); + } + let Some(member) = viewer.member.clone() else { return StatusCode::UNAUTHORIZED.into_response() }; + let me = Me { user: member.user_id, nickname: member.nickname, moderator: viewer.is_moderator() }; + let rx = state.hub.subscribe(); + let db = state.db.clone(); + ws.on_upgrade(move |socket| serve(socket, rx, db, me)) +} + +/// Who is on the other end of a connection. +struct Me { + user: Uuid, + nickname: String, + moderator: bool, +} + +#[derive(Deserialize)] +struct Incoming { + typing: String, + id: i64, +} + +/// At most one typing notice per target in this time. +const TYPING_EVERY: Duration = Duration::from_secs(2); + +/// "I am typing", from the page: passed on to those who may see that place. +async fn typing(db: &PgPool, me: &Me, text: &str) -> Option { + let incoming: Incoming = serde_json::from_str(text).ok()?; + let users = match incoming.typing.as_str() { + "conversation" => { + let other: Option = sqlx::query_scalar( + "SELECT CASE WHEN user_a = $2 THEN user_b ELSE user_a END FROM forum.conversations \ + WHERE id = $1 AND status = 'accepted' AND $2 IN (user_a, user_b)", + ) + .bind(incoming.id) + .bind(me.user) + .fetch_optional(db) + .await + .ok()?; + vec![other?] + } + "thread" => { + let visibility: Option = sqlx::query_scalar( + "SELECT tp.visibility FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ + WHERE th.id = $1 AND th.deleted_at IS NULL AND (NOT th.locked OR $2)", + ) + .bind(incoming.id) + .bind(me.moderator) + .fetch_optional(db) + .await + .ok()?; + if visibility? == "restricted" && !me.moderator { + return None; + } + Vec::new() + } + _ => return None, + }; + Some(Event { + users, + typing: Some(Typing { kind: incoming.typing, id: incoming.id, who: me.nickname.clone(), from: me.user }), + ..Default::default() + }) +} + +async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver>, db: PgPool, me: Me) { + let (user, moderator) = (me.user, me.moderator); + let mut last_typing: Option<(String, std::time::Instant)> = None; + let mut ping = tokio::time::interval(PING); + ping.tick().await; + loop { + tokio::select! { + event = rx.recv() => { + let messages = match event { + Ok(event) => event.messages_for(user, moderator), + // Too slow to follow: just refresh everything. + Err(broadcast::error::RecvError::Lagged(_)) => vec![json!({ "t": "nav" }).to_string()], + Err(broadcast::error::RecvError::Closed) => break, + }; + for message in messages { + if socket.send(Message::Text(message.into())).await.is_err() { + return; + } + } + } + _ = ping.tick() => { + if socket.send(Message::Ping(Vec::new().into())).await.is_err() { + return; + } + // Connected means present: the online dot. + let _ = 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) + .execute(&db) + .await; + } + incoming = socket.recv() => match incoming { + Some(Ok(Message::Text(text))) => { + // Typing notices, a few seconds apart per place. + let fresh = last_typing + .as_ref() + .is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY); + if fresh { + last_typing = Some((text.to_string(), std::time::Instant::now())); + if let Some(event) = typing(&db, &me, &text).await { + emit(&db, event).await; + } + } + } + // Pongs and the like are fine. + Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break, + Some(Ok(_)) => {} + }, + } + } +} + +/// The followers of a thread other than `except` (whose menu counts change). +pub async fn followers(db: &PgPool, thread: i64, except: Uuid) -> Vec { + sqlx::query_scalar("SELECT user_id FROM forum.follows WHERE thread_id = $1 AND user_id <> $2") + .bind(thread) + .bind(except) + .fetch_all(db) + .await + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn who_hears_what() { + let (anna, bea) = (Uuid::now_v7(), Uuid::now_v7()); + let post = Event { thread: Some(7), ..Default::default() }.for_users(vec![anna]); + assert_eq!(post.messages_for(anna, false), vec![r#"{"id":7,"t":"thread"}"#, r#"{"t":"nav"}"#]); + assert_eq!(post.messages_for(bea, false), vec![r#"{"id":7,"t":"thread"}"#]); + let message = Event { conversation: Some(3), ..Default::default() }.for_users(vec![bea]); + assert!(message.messages_for(anna, true).is_empty(), "nobody else hears of a conversation"); + assert_eq!(message.messages_for(bea, false).len(), 2); + let report = Event { moderators: true, ..Default::default() }; + assert!(report.messages_for(anna, false).is_empty()); + assert_eq!(report.messages_for(anna, true), vec![r#"{"t":"nav"}"#]); + let many = Event::default().for_users((0..400).map(|_| Uuid::now_v7()).collect()); + assert!(many.everyone && many.users.is_empty()); + let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap(); + assert_eq!(round, post); + + // Typing: never to oneself; a conversation only to the other member. + let typing = |kind: &str, users: Vec| Event { + users, + typing: Some(Typing { kind: kind.into(), id: 9, who: "Holdfény".into(), from: bea }), + ..Default::default() + }; + let in_thread = typing("thread", vec![]); + assert_eq!( + in_thread.messages_for(anna, false), + vec![r#"{"id":9,"kind":"thread","t":"typing","who":"Holdfény"}"#] + ); + assert!(in_thread.messages_for(bea, false).is_empty()); + let in_chat = typing("conversation", vec![anna]); + assert_eq!(in_chat.messages_for(anna, false).len(), 1); + assert!(in_chat.messages_for(Uuid::now_v7(), true).is_empty()); + } +} diff --git a/services/forum/src/mail.rs b/services/forum/src/mail.rs new file mode 100644 index 0000000..fe42318 --- /dev/null +++ b/services/forum/src/mail.rs @@ -0,0 +1,267 @@ +//! Instant forum e-mails (a reply to the member, a private message or a +//! request), queued in `email_outbox` for the worker to send. The daily +//! digest is the worker's own job (its `forum` task). +//! +//! Nobody gets an instant e-mail while online (they see the badge), and at +//! most one per thread an hour, one per conversation in half an hour. A +//! failure here is logged and never fails the post itself. + +use serde_json::{Value, json}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::AppState; +use crate::text; + +/// The one-click unsubscribe links of a member's forum e-mails. +fn unsubscribe_links(base: &str, token: &str) -> (String, String) { + (format!("{base}/forum/leiratkozas?token={token}"), format!("{base}/api/v1/forum/unsubscribe?token={token}")) +} + +#[derive(sqlx::FromRow)] +struct Recipient { + user_id: Uuid, + email: String, + locale: String, + nickname: String, + email_token: String, +} + +async fn queue(db: &PgPool, base: &str, to: &Recipient, template: &str, mut payload: Value) -> Result<(), sqlx::Error> { + let (unsubscribe_url, unsubscribe_post_url) = unsubscribe_links(base, &to.email_token); + payload["nickname"] = json!(to.nickname); + payload["unsubscribe_url"] = json!(unsubscribe_url); + payload["unsubscribe_post_url"] = json!(unsubscribe_post_url); + sqlx::query( + "INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(Uuid::now_v7()) + .bind(to.user_id) + .bind(&to.email) + .bind(template) + .bind(&to.locale) + .bind(payload) + .execute(db) + .await?; + Ok(()) +} + +/// Not online now (the last request more than five minutes ago). +const OFFLINE: &str = "(m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes')"; + +/// A reply: to the thread's author and to the author of the post answered, +/// if they asked for instant e-mails. +pub async fn after_reply( + state: &AppState, + thread_id: i64, + post_id: i64, + replier: Uuid, + parent: Option, + body: &str, +) { + if let Err(e) = reply_mails(state, thread_id, post_id, replier, parent, body).await { + tracing::error!(error = %e, thread = thread_id, "queueing the reply e-mails"); + } +} + +async fn reply_mails( + state: &AppState, + thread_id: i64, + post_id: i64, + replier: Uuid, + parent: Option, + body: &str, +) -> Result<(), sqlx::Error> { + let recipients: Vec = sqlx::query_as(&format!( + "SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \ + FROM forum.members m JOIN users u ON u.id = m.user_id \ + WHERE m.email_replies = 'instant' AND m.user_id <> $1 AND {OFFLINE} \ + AND m.user_id IN (SELECT author_id FROM forum.threads WHERE id = $2 \ + UNION SELECT author_id FROM forum.posts WHERE id = $3) \ + AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = m.user_id AND mu.muted_id = $1) \ + AND NOT EXISTS (SELECT 1 FROM email_outbox e \ + WHERE e.user_id = m.user_id AND e.template = 'forum_reply' \ + AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')" + )) + .bind(replier) + .bind(thread_id) + .bind(parent) + .fetch_all(&state.db) + .await?; + if recipients.is_empty() { + return Ok(()); + } + let (title, author): (String, Option) = sqlx::query_as( + "SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) \ + FROM forum.threads th WHERE th.id = $1", + ) + .bind(thread_id) + .bind(replier) + .fetch_one(&state.db) + .await?; + let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title)); + for to in &recipients { + let payload = json!({ + "url": url, + "author": author, + "thread_title": title, + "thread_id": thread_id.to_string(), + "excerpt": body.chars().take(300).collect::(), + }); + queue(&state.db, &state.base_url, to, "forum_reply", payload).await?; + } + Ok(()) +} + +/// A private message or a request: to the other member, if they asked for it. +pub async fn after_message(state: &AppState, conversation: i64, sender: Uuid, request: bool, intro: Option<&str>) { + if let Err(e) = message_mail(state, conversation, sender, request, intro).await { + tracing::error!(error = %e, conversation, "queueing the message e-mail"); + } +} + +async fn message_mail( + state: &AppState, + conversation: i64, + sender: Uuid, + request: bool, + intro: Option<&str>, +) -> Result<(), sqlx::Error> { + let to: Option = sqlx::query_as(&format!( + "SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \ + FROM forum.conversations c \ + JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $2 THEN c.user_b ELSE c.user_a END \ + JOIN users u ON u.id = m.user_id \ + WHERE c.id = $1 AND m.email_messages = 'instant' AND {OFFLINE} \ + AND NOT EXISTS (SELECT 1 FROM email_outbox e \ + WHERE e.user_id = m.user_id AND e.template = 'forum_message' \ + AND e.payload->>'conversation_id' = $1::text \ + AND e.created_at > now() - interval '30 minutes')" + )) + .bind(conversation) + .bind(sender) + .fetch_optional(&state.db) + .await?; + let Some(to) = to else { return Ok(()) }; + let from: Option = sqlx::query_scalar("SELECT nickname FROM forum.members WHERE user_id = $1") + .bind(sender) + .fetch_optional(&state.db) + .await?; + let payload = json!({ + "url": format!("{}/forum/uzenetek/{conversation}", state.base_url), + "from": from, + "kind": if request { "request" } else { "message" }, + "excerpt": intro, + "conversation_id": conversation.to_string(), + }); + queue(&state.db, &state.base_url, &to, "forum_message", payload).await +} + +#[derive(sqlx::FromRow)] +struct Person { + email: String, + locale: String, + nickname: Option, +} + +/// A notice that has to reach the user whatever their notification settings +/// (a moderation step concerning them, the decision on their report). +pub async fn notify_user(state: &AppState, user: Uuid, template: &str, mut payload: Value) { + let person: Result, sqlx::Error> = sqlx::query_as( + "SELECT u.email, u.locale, m.nickname FROM users u LEFT JOIN forum.members m ON m.user_id = u.id WHERE u.id = $1", + ) + .bind(user) + .fetch_optional(&state.db) + .await; + let result = match person { + Ok(Some(p)) => { + payload["nickname"] = json!(p.nickname); + sqlx::query( + "INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \ + VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(Uuid::now_v7()) + .bind(user) + .bind(&p.email) + .bind(template) + .bind(&p.locale) + .bind(payload) + .execute(&state.db) + .await + .map(|_| ()) + } + Ok(None) => Ok(()), + Err(e) => Err(e), + }; + if let Err(e) = result { + tracing::error!(error = %e, template, "queueing a moderation e-mail"); + } +} + +/// The forum rules, where the moderation e-mails point. +pub fn rules_url(state: &AppState) -> String { + format!("{}/aszf#forum", state.base_url) +} + +/// "3 napos" or "12 órás": a ban's length for the e-mail. +pub fn ban_duration(hours: i64) -> String { + if hours % 24 == 0 { format!("{} napos", hours / 24) } else { format!("{hours} órás") } +} + +/// Tells each reporter (once) how their report was decided. +pub async fn notify_reporters(state: &AppState, reporters: &[Option], outcome: &str) { + let mut seen: Vec = reporters.iter().flatten().copied().collect(); + seen.sort_unstable(); + seen.dedup(); + for reporter in seen { + let payload = json!({ "url": format!("{}/forum", state.base_url), "outcome": outcome }); + notify_user(state, reporter, "forum_report_result", payload).await; + } +} + +/// Members named in a post ("@Holdfény") who asked for an e-mail about it +/// (not while online, one per thread an hour). +pub async fn after_mention(state: &AppState, thread_id: i64, post_id: i64, author: Uuid, users: &[Uuid], body: &str) { + let result: Result<(), sqlx::Error> = async { + let recipients: Vec = sqlx::query_as(&format!( + "SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \ + FROM forum.members m JOIN users u ON u.id = m.user_id \ + WHERE m.user_id = ANY($1) AND m.email_mentions = 'instant' AND {OFFLINE} \ + AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = m.user_id AND mu.muted_id = $3) \ + AND NOT EXISTS (SELECT 1 FROM email_outbox e WHERE e.user_id = m.user_id \ + AND e.template IN ('forum_mention', 'forum_reply') \ + AND e.payload->>'thread_id' = $2::text AND e.created_at > now() - interval '1 hour')" + )) + .bind(users) + .bind(thread_id) + .bind(author) + .fetch_all(&state.db) + .await?; + if recipients.is_empty() { + return Ok(()); + } + let (title, who): (String, Option) = sqlx::query_as( + "SELECT th.title, (SELECT nickname FROM forum.members WHERE user_id = $2) FROM forum.threads th WHERE th.id = $1", + ) + .bind(thread_id) + .bind(author) + .fetch_one(&state.db) + .await?; + let url = format!("{}/forum/szal/{thread_id}-{}#h{post_id}", state.base_url, text::slug(&title)); + for to in &recipients { + let payload = json!({ + "url": url, + "author": who, + "thread_title": title, + "thread_id": thread_id.to_string(), + "excerpt": body.chars().take(300).collect::(), + }); + queue(&state.db, &state.base_url, to, "forum_mention", payload).await?; + } + Ok(()) + } + .await; + if let Err(e) = result { + tracing::error!(error = %e, thread = thread_id, "queueing the mention e-mails"); + } +} diff --git a/services/forum/src/main.rs b/services/forum/src/main.rs new file mode 100644 index 0000000..21ea48d --- /dev/null +++ b/services/forum/src/main.rs @@ -0,0 +1,84 @@ +//! 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`, `PUBLIC_BASE_URL` (the site, for e-mail +//! links; default `http://localhost:3001`), `S3_*` (avatar uploads, as the +//! backend's); `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 links; +mod live; +mod mail; +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, + /// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`); also + /// the only origin allowed to open a live connection. + pub base_url: String, + /// The live events of this instance (`live::listen` fills it). + pub hub: live::Hub, + /// Where uploaded avatars are kept (`S3_*`); `None`: no uploads. + pub storage: Option, + /// The link module's providers (YouTube previews). + pub links: links::LinkConfig, +} + +impl AppState { + pub fn new(db: PgPool, base_url: String, storage: Option) -> Self { + Self { + db, + flood_secs: 5, + base_url: base_url.trim_end_matches('/').to_string(), + hub: live::Hub::default(), + storage, + links: links::LinkConfig::from_env(), + } + } +} + +#[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 base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into()); + let storage = + object_storage::StorageConfig::from_env().map_err(anyhow::Error::msg)?.map(object_storage::Storage::new); + if storage.is_none() { + tracing::info!("S3_ENDPOINT is not set: no avatar uploads"); + } + let state = Arc::new(AppState::new(pool, base_url, storage)); + tokio::spawn(live::listen(state.db.clone(), state.hub.clone())); + let app = routes::router(state); + let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; + tracing::info!(%addr, "listening"); + axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?; + Ok(()) +} diff --git a/services/forum/src/rank.rs b/services/forum/src/rank.rs new file mode 100644 index 0000000..08d9796 --- /dev/null +++ b/services/forum/src/rank.rs @@ -0,0 +1,86 @@ +//! Ranks: earned from points (reactions and "Ez segített" marks received) +//! and time spent as a member, so nobody climbs in a few days. A rank is +//! also a permission level. Buying a package gives no rank: it only lifts the +//! newcomer's daily limits (docs/kozosseg.md). + +use serde::Serialize; +use time::OffsetDateTime; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Rank { + Vandor, + Kereso, + Fono, + Csillagfono, + Sorsfono, +} + +/// (rank, points needed, days of membership needed), lowest first. +const LADDER: [(Rank, i32, i64); 5] = [ + (Rank::Vandor, i32::MIN, 0), + (Rank::Kereso, 5, 3), + (Rank::Fono, 30, 14), + (Rank::Csillagfono, 100, 45), + (Rank::Sorsfono, 300, 120), +]; + +/// What an "Ez segített" mark is worth. +pub const HELPED_POINTS: i32 = 5; +/// Newcomer limits (lifted by a purchase): new threads and posts in 24 hours. +pub const NEWCOMER_THREADS_PER_DAY: i64 = 3; +pub const NEWCOMER_POSTS_PER_DAY: i64 = 20; +/// A post whose reactions add up to this or less is shown collapsed. +pub const COLLAPSE_SCORE: i64 = -3; + +impl Rank { + pub fn of(points: i32, member_since: OffsetDateTime, now: OffsetDateTime) -> Rank { + let days = (now - member_since).whole_days(); + LADDER.iter().rev().find(|(_, p, d)| points >= *p && days >= *d).map(|(r, _, _)| *r).unwrap_or(Rank::Vandor) + } + + pub fn name(self) -> &'static str { + match self { + Rank::Vandor => "Vándor", + Rank::Kereso => "Kereső", + Rank::Fono => "Fonó", + Rank::Csillagfono => "Csillagfonó", + Rank::Sorsfono => "Sorsfonó", + } + } + + /// A newcomer: daily limits, reactions that do not count yet, no ⌄. + pub fn is_newcomer(self) -> bool { + self == Rank::Vandor + } + + /// May use the ⌄ (never in a listening topic). + pub fn may_downvote(self) -> bool { + self >= Rank::Kereso + } + + /// The next rank and what it needs, for the member's own profile. + pub fn next(self) -> Option<(Rank, i32, i64)> { + LADDER.iter().find(|(r, _, _)| *r > self).copied() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ranks_need_points_and_time() { + let now = OffsetDateTime::now_utc(); + let days = |d: i64| now - time::Duration::days(d); + assert_eq!(Rank::of(0, days(400), now), Rank::Vandor); + assert_eq!(Rank::of(500, days(1), now), Rank::Vandor, "points alone are not enough"); + assert_eq!(Rank::of(5, days(3), now), Rank::Kereso); + assert_eq!(Rank::of(40, days(20), now), Rank::Fono); + assert_eq!(Rank::of(40, days(400), now), Rank::Fono); + assert_eq!(Rank::of(300, days(120), now), Rank::Sorsfono); + assert_eq!(Rank::Vandor.next().map(|n| n.0), Some(Rank::Kereso)); + assert_eq!(Rank::Sorsfono.next(), None); + assert!(!Rank::Vandor.may_downvote() && Rank::Kereso.may_downvote()); + } +} diff --git a/services/forum/src/routes/attachments.rs b/services/forum/src/routes/attachments.rs new file mode 100644 index 0000000..8d640c0 --- /dev/null +++ b/services/forum/src/routes/attachments.rs @@ -0,0 +1,172 @@ +//! A question about one's own chart, yearly forecast or synastry: the opening +//! post carries a share made for the forum on the main site (no birth data, +//! no names). The post shows it as a card to logged-in members only; a +//! visitor (and a search engine) sees that there is one. The sharer can +//! revoke it on the main site; the card then says so. + +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{Path, State}; +use axum_extra::extract::WithRejection; +use serde_json::{Value, json}; +use sqlx::PgPool; +use uuid::Uuid; + +use super::St; +use crate::auth::{Member, Viewer}; +use crate::error::{ApiError, ApiResult}; + +#[derive(sqlx::FromRow)] +struct CardRow { + id: Uuid, + slug: String, + kind: String, + revoked: bool, + natal: Option, + year: Option, + summary_title: Option, + /// A synastry: the two charts and the aspects between them. + chart1: Option, + chart2: Option, + pair_aspects: Option, +} + +const CARD_SELECT: &str = "SELECT s.id, s.slug, s.kind, s.revoked_at IS NOT NULL AS revoked, \ + COALESCE(c.result, fc.result) AS natal, f.year, \ + CASE s.kind \ + WHEN 'chart' THEN (SELECT a.content->>'title' FROM analyses a WHERE a.chart_id = s.chart_id \ + AND a.kind = 'summary' AND a.status = 'done' ORDER BY a.completed_at DESC LIMIT 1) \ + WHEN 'forecast' THEN (SELECT a.content->>'title' FROM analyses a WHERE a.forecast_id = s.forecast_id \ + AND a.kind = 'forecast' AND a.status = 'done' ORDER BY a.completed_at DESC LIMIT 1) \ + END AS summary_title, \ + c1.result AS chart1, c2.result AS chart2, sy.result->'aspects' AS pair_aspects \ + FROM shares s \ + LEFT JOIN charts c ON c.id = s.chart_id \ + LEFT JOIN forecasts f ON f.id = s.forecast_id \ + LEFT JOIN charts fc ON fc.id = f.chart_id \ + LEFT JOIN synastries sy ON sy.id = s.synastry_id \ + LEFT JOIN charts c1 ON c1.id = sy.chart1_id \ + LEFT JOIN charts c2 ON c2.id = sy.chart2_id"; + +/// Sun, Moon and (with a known birth time) the Ascendant: sign, degree, house. +fn big_three(natal: &Value) -> (Vec, bool) { + let time_known = natal.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false); + let mut points: Vec = ["sun", "moon"] + .iter() + .filter_map(|id| natal["points"].as_array()?.iter().find(|p| p["id"] == *id)) + .map(|p| { + json!({ + "id": p["id"], + "sign": p["sign"], + "degree": p["degree_in_sign"].as_f64().map(|d| d.floor() as i64), + "house": if time_known { p["house"].clone() } else { Value::Null }, + }) + }) + .collect(); + let asc = &natal["angles"]["ascendant"]; + if time_known && asc.is_object() { + points.push(json!({ + "id": "ascendant", + "sign": asc["sign"], + "degree": asc["degree_in_sign"].as_f64().map(|d| d.floor() as i64), + "house": null, + })); + } + (points, time_known) +} + +/// What the wheel is drawn from: the positions, angles, houses and aspects +/// (never the birth date, time or place). +fn wheel(chart: &Value) -> Value { + json!({ + "points": chart["points"], + "angles": chart["angles"], + "houses": chart["houses"], + "aspects": chart["aspects"], + }) +} + +fn time_known(chart: &Value) -> bool { + chart.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false) +} + +fn card(row: &CardRow) -> Value { + if row.revoked { + return json!({ "slug": row.slug, "kind": row.kind, "revoked": true }); + } + let title = match (row.kind.as_str(), row.year) { + ("synastry", _) => "Két képlet összevetése".to_string(), + ("forecast", Some(year)) => format!("Éves előrejelzés · {year}–{}", year + 1), + _ => "Születési képlet".to_string(), + }; + let (points, known) = row.natal.as_ref().map(big_three).unwrap_or_default(); + // The drawing itself: the chart's wheel, or the two charts on one wheel. + let chart = match (row.kind.as_str(), &row.natal) { + ("chart", Some(natal)) => wheel(natal), + _ => Value::Null, + }; + let pair = match (&row.chart1, &row.chart2) { + (Some(a), Some(b)) if row.kind == "synastry" => json!({ + "chart1": wheel(a), + "chart2": wheel(b), + "time1": time_known(a), + "time2": time_known(b), + "aspects": row.pair_aspects.clone().unwrap_or(Value::Array(Vec::new())), + }), + _ => Value::Null, + }; + json!({ + "slug": row.slug, + "kind": row.kind, + "revoked": false, + "title": title, + "summary": row.summary_title, + "points": points, + "time_known": known, + "chart": chart, + "pair": pair, + }) +} + +/// The cards of these shares, as the viewer may see them: in full for +/// logged-in members, only that there is one for visitors. +pub async fn cards(db: &PgPool, viewer: &Viewer, ids: &[Uuid]) -> Result, sqlx::Error> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let rows: Vec = + sqlx::query_as(&format!("{CARD_SELECT} WHERE s.id = ANY($1)")).bind(ids).fetch_all(db).await?; + Ok(rows + .iter() + .map(|r| { + let shown = if viewer.logged_in() { card(r) } else { json!({ "kind": r.kind, "locked": true }) }; + (r.id, shown) + }) + .collect()) +} + +/// A share the member made for the forum and has not revoked: its id. +pub async fn attachable(db: &PgPool, member: &Member, slug: &str) -> ApiResult { + let row: Option<(Uuid, Uuid, bool, bool)> = + sqlx::query_as("SELECT id, owner_id, for_forum, revoked_at IS NOT NULL FROM shares WHERE slug = $1") + .bind(slug.trim()) + .fetch_optional(db) + .await?; + match row { + Some((id, owner, true, false)) if owner == member.user_id => Ok(id), + _ => Err(ApiError::bad("Ez a képlet nem csatolható. Indítsd újra a kérdést a képlet oldaláról.")), + } +} + +/// The card of a share about to be attached (the new thread page shows it). +pub async fn preview( + State(state): St, + viewer: Viewer, + WithRejection(Path(slug), _): WithRejection, ApiError>, +) -> ApiResult> { + let member = viewer.require_member()?; + let id = attachable(&state.db, member, &slug).await?; + let row: CardRow = sqlx::query_as(&format!("{CARD_SELECT} WHERE s.id = $1")).bind(id).fetch_one(&state.db).await?; + Ok(Json(card(&row))) +} diff --git a/services/forum/src/routes/avatars.rs b/services/forum/src/routes/avatars.rs new file mode 100644 index 0000000..f015192 --- /dev/null +++ b/services/forum/src/routes/avatars.rs @@ -0,0 +1,204 @@ +//! Own avatars: a member from the Kereső rank may upload a picture instead of +//! a starter avatar. It is cut to a square, made small (256 pixels), stripped +//! of its metadata (EXIF: camera, place) and kept in the object storage; the +//! forum serves it. A moderator can put the starter avatar back. + +use std::io::Cursor; + +use axum::Json; +use axum::body::Bytes; +use axum::extract::{Path, State}; +use axum::http::{StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use axum_extra::extract::WithRejection; +use image::codecs::jpeg::JpegEncoder; +use image::imageops::FilterType; +use image::metadata::Orientation; +use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::St; +use super::moderation::{self, Action}; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +/// The largest upload accepted, in bytes. +pub const MAX_UPLOAD: usize = 8 * 1024 * 1024; +/// The stored picture's side, in pixels. +const SIDE: u32 = 256; +const MIN_SIDE: u32 = 64; +/// The objects' folder in the bucket. +const FOLDER: &str = "forum-avatars"; +pub const PREFIX: &str = "upload:"; + +/// A JPEG, PNG or WebP picture as an upright square JPEG of [`SIDE`] pixels. +/// The error is a message for the member. +pub fn normalize(bytes: &[u8]) -> Result, String> { + let unreadable = || "A képet nem sikerült beolvasni. JPEG, PNG vagy WebP képet tölts fel.".to_string(); + let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?; + if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP)) { + return Err(unreadable()); + } + let mut limits = Limits::default(); + limits.max_image_width = Some(12_000); + limits.max_image_height = Some(12_000); + reader.limits(limits); + let mut decoder = reader.into_decoder().map_err(|_| unreadable())?; + let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); + let mut img = DynamicImage::from_decoder(decoder).map_err(|_| unreadable())?; + img.apply_orientation(orientation); + let side = img.width().min(img.height()); + if side < MIN_SIDE { + return Err(format!("A kép túl kicsi: legalább {MIN_SIDE}×{MIN_SIDE} pixeles legyen.")); + } + // The middle square, then small. + let square = img.crop_imm((img.width() - side) / 2, (img.height() - side) / 2, side, side); + let small = square.resize_exact(SIDE, SIDE, FilterType::Lanczos3); + let rgb = if small.color().has_alpha() { + // JPEG has no transparency: a transparent part turns white. + let rgba = small.to_rgba8(); + image::RgbImage::from_fn(SIDE, SIDE, |x, y| { + let [r, g, b, a] = rgba.get_pixel(x, y).0; + let mix = |c: u8| ((u16::from(c) * u16::from(a) + 255 * (255 - u16::from(a))) / 255) as u8; + image::Rgb([mix(r), mix(g), mix(b)]) + }) + } else { + small.to_rgb8() + }; + let mut jpeg = Vec::new(); + JpegEncoder::new_with_quality(&mut jpeg, 85).encode_image(&rgb).map_err(|e| e.to_string())?; + Ok(jpeg) +} + +/// The stored file of an `upload:` avatar, if it is one. +pub fn uploaded_file(avatar: &str) -> Option<&str> { + avatar.strip_prefix(PREFIX) +} + +fn valid_file(file: &str) -> bool { + file.len() <= 80 + && file.ends_with(".jpg") + && file.trim_end_matches(".jpg").chars().all(|c| c.is_ascii_hexdigit() || c == '-') +} + +/// Removes a stored avatar (best effort: a leftover file is only storage). +pub async fn forget(state: &crate::AppState, avatar: &str) { + if let (Some(file), Some(storage)) = (uploaded_file(avatar), &state.storage) + && let Err(e) = storage.delete(&format!("{FOLDER}/{file}")).await + { + tracing::warn!(error = %e, "removing an old avatar"); + } +} + +/// `PUT /v1/forum/me/avatar`: the picture's bytes as the body. +pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult> { + let member = viewer.require_writer()?.clone(); + if member.rank(OffsetDateTime::now_utc()).is_newcomer() && !viewer.is_moderator() { + return Err(ApiError::Forbidden("Saját képet a Kereső rangtól tölthetsz fel.".into())); + } + let Some(storage) = &state.storage else { + return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into())); + }; + if body.len() > MAX_UPLOAD { + return Err(ApiError::bad("A kép legfeljebb 8 MB lehet.")); + } + let bytes = body.to_vec(); + let jpeg = tokio::task::spawn_blocking(move || normalize(&bytes)) + .await + .map_err(|e| ApiError::Internal(e.to_string()))? + .map_err(ApiError::BadRequest)?; + let hash: String = Sha256::digest(&jpeg).iter().take(6).map(|b| format!("{b:02x}")).collect(); + let file = format!("{}-{hash}.jpg", member.user_id.simple()); + storage + .put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg") + .await + .map_err(|e| ApiError::Internal(format!("storing an avatar: {e}")))?; + let avatar = format!("{PREFIX}{file}"); + sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1") + .bind(member.user_id) + .bind(&avatar) + .execute(&state.db) + .await?; + if member.avatar != avatar { + forget(&state, &member.avatar).await; + } + Ok(Json(json!({ "avatar": avatar }))) +} + +/// `GET /v1/forum/avatars/{file}`: a stored avatar (its name changes with +/// its content, so it is cached for good). +pub async fn serve( + State(state): St, + WithRejection(Path(file), _): WithRejection, ApiError>, +) -> ApiResult { + if !valid_file(&file) { + return Err(ApiError::NotFound("avatar")); + } + let storage = state.storage.as_ref().ok_or(ApiError::NotFound("avatar"))?; + let object = storage + .get(&format!("{FOLDER}/{file}")) + .await + .map_err(|e| ApiError::Internal(format!("reading an avatar: {e}")))? + .ok_or(ApiError::NotFound("avatar"))?; + Ok(( + [(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")], + object.bytes, + ) + .into_response()) +} + +/// A moderator puts back the starter avatar (an unfit picture). +pub async fn reset( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, +) -> ApiResult { + let moderator = viewer.require_moderator()?; + let key = text::nickname_key(&nickname); + let found: Option<(Uuid, String)> = + sqlx::query_as("SELECT user_id, avatar FROM forum.members WHERE nickname_key = $1") + .bind(&key) + .fetch_optional(&state.db) + .await?; + let (user, avatar) = found.ok_or(ApiError::NotFound("member"))?; + if uploaded_file(&avatar).is_none() { + return Ok(StatusCode::NO_CONTENT); + } + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.members SET avatar = $2 WHERE user_id = $1") + .bind(user) + .bind(text::default_avatar(&key)) + .execute(&mut *tx) + .await?; + moderation::record(&mut *tx, moderator.id, Action::ResetAvatar, Some(user), None, None, None, None).await?; + tx.commit().await?; + forget(&state, &avatar).await; + Ok(StatusCode::NO_CONTENT) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(width: u32, height: u32) -> Vec { + let img = + DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, image::Rgba([200, 100, 50, 255]))); + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap(); + out + } + + #[test] + fn makes_a_small_square_jpeg() { + let jpeg = normalize(&png(900, 400)).unwrap(); + let back = image::load_from_memory(&jpeg).unwrap(); + assert_eq!((back.width(), back.height()), (SIDE, SIDE)); + assert!(normalize(&png(40, 40)).unwrap_err().contains("túl kicsi")); + assert!(normalize(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;").is_err()); + assert!(valid_file("0190aa-3f2a1b.jpg") && !valid_file("../x.jpg") && !valid_file("a.png")); + } +} diff --git a/services/forum/src/routes/home.rs b/services/forum/src/routes/home.rs new file mode 100644 index 0000000..9048cdb --- /dev/null +++ b/services/forum/src/routes/home.rs @@ -0,0 +1,335 @@ +//! 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; +/// "Élénk beszélgetések": 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, + archived: bool, + thread_count: i64, + new_count: Option, + last_author: Option, + last_at: Option, +} + +/// The topics in order: counts and the latest post for those the viewer may +/// read, the others (a members-only topic for a visitor) only by name. +async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult> { + let (me, since) = card_params(viewer); + let rows: Vec = sqlx::query_as( + "SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \ + tp.archived_at IS NOT NULL AS archived, \ + (SELECT count(*) FROM forum.threads th WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) AS thread_count, \ + CASE WHEN $1::uuid IS NULL THEN NULL ELSE \ + (SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \ + WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \ + AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2::timestamptz \ + AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ + WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS new_count, \ + last.author_id AS last_author, last.created_at AS last_at \ + FROM forum.topics tp \ + LEFT JOIN LATERAL (SELECT p.author_id, p.created_at FROM forum.posts p \ + JOIN forum.threads th ON th.id = p.thread_id \ + WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \ + ORDER BY p.id DESC LIMIT 1) last ON true \ + ORDER BY tp.position", + ) + .bind(me) + .bind(since) + .fetch_all(&state.db) + .await?; + let readable: Vec = rows.iter().map(|r| may_read(viewer, &r.visibility, r.id)).collect(); + let people = + super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author)) + .await?; + // A restricted topic shows by name to members, who may ask to join. + let pending: Vec = match viewer.user_id() { + Some(me) => { + sqlx::query_scalar("SELECT topic_id FROM forum.topic_members WHERE user_id = $1 AND status = 'pending'") + .bind(me) + .fetch_all(&state.db) + .await? + } + None => Vec::new(), + }; + Ok(rows + .into_iter() + .zip(readable) + .filter(|(r, _)| r.visibility != "restricted" || viewer.member.is_some() || viewer.is_moderator()) + .map(|(r, readable)| { + let membership = (r.visibility == "restricted").then(|| { + if viewer.topics.contains(&r.id) { + "approved" + } else if pending.contains(&r.id) { + "pending" + } else { + "none" + } + }); + let mut topic = json!({ + "id": r.id, + "slug": r.slug, + "name": r.name, + "description": r.description, + "visibility": r.visibility, + "listening": r.listening, + "archived": r.archived, + "readable": readable, + "membership": membership, + }); + if readable { + topic["thread_count"] = json!(r.thread_count); + topic["new_count"] = json!(r.new_count); + topic["last"] = json!(r.last_at.map(|at| json!({ + "author": r.last_author.and_then(|id| people.get(&id).cloned()), + "at": rfc3339(at), + }))); + } + topic + }) + .collect()) +} + +/// What the header and the front page show about the viewer. +pub fn viewer_json(viewer: &Viewer) -> Value { + let now = OffsetDateTime::now_utc(); + json!({ + "logged_in": viewer.logged_in(), + "needs_nickname": viewer.logged_in() && viewer.member.is_none(), + "moderator": viewer.is_moderator(), + "member": viewer.member.as_ref().map(|m| { + let rank = m.rank(now); + json!({ + "nickname": m.nickname, + "avatar": m.avatar, + "rank": rank, + "rank_name": rank.name(), + "banned": m.banned(now), + }) + }), + }) +} + +/// The front page: the viewer, new replies in followed threads, the topics, +/// threads waiting for a first reply, and the busiest threads of the day. +pub async fn home(state: St, viewer: Viewer) -> ApiResult> { + let (me, since) = card_params(&viewer); + let topics = topic_list(&state, &viewer).await?; + + let followed = followed_counts(&state, &viewer).await?; + + let unanswered: Vec = sqlx::query_as(&format!( + "{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 AND tp.archived_at IS NULL \ + AND th.created_at > now() - make_interval(days => $3) \ + ORDER BY th.created_at LIMIT 3", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .bind(UNANSWERED_DAYS) + .fetch_all(&state.db) + .await?; + + let hot: Vec = sqlx::query_as(&format!( + "WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \ + WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \ + GROUP BY thread_id HAVING count(*) >= $3) \ + {} AND th.id IN (SELECT thread_id FROM recent) AND tp.archived_at IS NULL \ + ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .bind(HOT_MIN_REPLIES) + .fetch_all(&state.db) + .await?; + + // "Most itt vannak": members seen in the last few minutes (not the invisible ones). + let present: Vec = sqlx::query_scalar( + "SELECT user_id FROM forum.members WHERE NOT invisible \ + AND last_seen_at > now() - make_interval(mins => $1) ORDER BY last_seen_at DESC LIMIT 24", + ) + .bind(crate::auth::ONLINE_MINUTES as i32) + .fetch_all(&state.db) + .await?; + let people = super::authors(&state.db, present.iter().copied()).await?; + let online: Vec = + present.iter().filter(|id| !viewer.mutes.contains(id)).filter_map(|id| people.get(id).cloned()).collect(); + + // Volunteer listeners: threads asking to be heard, still without a reply. + let waiting = match &viewer.member { + Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?), + _ => None, + }; + let replies = match &viewer.member { + Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?), + None => None, + }; + Ok(Json(json!({ + "viewer": viewer_json(&viewer), + "followed": followed, + "replies": replies, + "waiting": waiting, + "online": online, + "topics": topics, + "unanswered": cards_json(&state.db, unanswered).await?, + "hot": cards_json(&state.db, hot).await?, + }))) +} + +/// New replies (by others, unread) in the member's followed threads. +async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult> { + let (Some(me), Some(since)) = card_params(viewer) else { return Ok(None) }; + let (replies, threads): (i64, i64) = sqlx::query_as( + "SELECT count(*), count(DISTINCT p.thread_id) FROM forum.follows f \ + JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \ + JOIN forum.posts p ON p.thread_id = f.thread_id AND p.deleted_at IS NULL \ + WHERE f.user_id = $1 AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2 \ + AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = p.author_id) \ + AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ + WHERE r.user_id = $1 AND r.thread_id = f.thread_id), 0)", + ) + .bind(me) + .bind(since) + .fetch_one(&state.db) + .await?; + Ok(Some(json!({ "new_replies": replies, "threads": threads }))) +} + +/// Threads asking to be heard (or in a listening topic) that have waited an +/// hour without a reply (two weeks at most), not the listener's own. +pub const WAITING_SQL: &str = "th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \ + AND th.created_at < now() - interval '1 hour' AND th.created_at > now() - interval '14 days' \ + AND (th.intent = 'listen' OR tp.listening) AND tp.archived_at IS NULL"; + +async fn waiting_count(state: &St, viewer: &Viewer) -> ApiResult { + let me = viewer.user_id(); + Ok(sqlx::query_scalar(&format!( + "SELECT count(*) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ + WHERE {WAITING_SQL} AND th.author_id IS DISTINCT FROM $1 AND ({})", + super::visible_topics(viewer) + )) + .bind(me) + .fetch_one(&state.db) + .await?) +} + +/// For the forum's menu on every page: who the viewer is, and the badge. +pub async fn nav(state: St, viewer: Viewer) -> ApiResult> { + let messages = match &viewer.member { + Some(m) => Some(super::messages::unread_count(&state.db, m.user_id).await?), + None => None, + }; + let reports = if viewer.is_moderator() { + let requests: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.topic_members WHERE status = 'pending'") + .fetch_one(&state.db) + .await?; + Some(super::reports::open_count(&state.db).await? + requests) + } else { + None + }; + // The only count on the forum tab: unread answers to the member. + let replies = match &viewer.member { + Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?), + None => None, + }; + Ok(Json(json!({ + "viewer": viewer_json(&viewer), + "replies": replies, + "messages": messages, + "reports": reports, + }))) +} + +pub async fn topics(state: St, viewer: Viewer) -> ApiResult> { + Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? }))) +} + +#[derive(Deserialize)] +pub struct PageQuery { + #[serde(default)] + page: Option, +} + +/// A topic's threads: pinned ones first, then by the latest post. +pub async fn topic( + State(state): St, + viewer: Viewer, + WithRejection(Path(slug), _): WithRejection, ApiError>, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let topic: Option<(i16, String, String, String, bool, bool)> = sqlx::query_as( + "SELECT id, name, description, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1", + ) + .bind(&slug) + .fetch_optional(&state.db) + .await?; + let (id, name, description, visibility, listening, archived) = topic.ok_or(ApiError::NotFound("topic"))?; + if !may_read(&viewer, &visibility, id) { + // A members-only topic asks for a login; a restricted one stays hidden. + return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") }); + } + let page = q.page.unwrap_or(1).clamp(1, 10_000); + let (me, since) = card_params(&viewer); + let rows: Vec = sqlx::query_as(&format!( + "{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .bind(id) + .bind(PAGE_SIZE + 1) + .bind((page - 1) * PAGE_SIZE) + .fetch_all(&state.db) + .await?; + let has_more = rows.len() as i64 > PAGE_SIZE; + let rows = rows.into_iter().take(PAGE_SIZE as usize).collect(); + Ok(Json(json!({ + "viewer": viewer_json(&viewer), + "topic": { + "slug": slug, "name": name, "description": description, + "visibility": visibility, "listening": listening, "archived": archived, + }, + "threads": cards_json(&state.db, rows).await?, + "page": page, + "has_more": has_more, + }))) +} + +/// The threads the member follows, the latest activity first, with what is unread. +pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_member()?; + let (me, since) = card_params(&viewer); + let rows: Vec = sqlx::query_as(&format!( + "{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \ + ORDER BY th.last_post_at DESC LIMIT 50", + card_sql(&viewer) + )) + .bind(me) + .bind(since) + .fetch_all(&state.db) + .await?; + Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? }))) +} diff --git a/services/forum/src/routes/members.rs b/services/forum/src/routes/members.rs new file mode 100644 index 0000000..da5aafa --- /dev/null +++ b/services/forum/src/routes/members.rs @@ -0,0 +1,431 @@ +//! 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; + +/// The first this many members get the "Alapító tag" badge for good. +pub const FOUNDERS: i64 = 15; + +/// A nickname may change once in this many days (spelling fixes that keep the +/// same folded form any time). +const NICKNAME_CHANGE_DAYS: i64 = 30; +/// A nickname given up stays reserved this long. +const NICKNAME_RESERVED_DAYS: i64 = 90; + +/// The viewer's own forum profile, and what each chart sharing level would show. +pub async fn me(State(state): St, viewer: Viewer) -> ApiResult> { + let user = viewer.require_user()?; + let now = OffsetDateTime::now_utc(); + let member = viewer.member.as_ref().map(|m| { + let rank = m.rank(now); + let change_after = m.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS); + json!({ + "nickname": m.nickname, + "avatar": m.avatar, + "bio": m.bio, + "chart_share": m.chart_share, + "invisible": m.invisible, + "points": m.points, + "post_count": m.post_count, + "created_at": rfc3339(m.created_at), + "rank": rank, + "rank_name": rank.name(), + "next_rank": rank.next().map(|(r, points, days)| json!({ + "rank": r, "name": r.name(), "points": points, "days": days, + })), + "nickname_change_after": (change_after > now).then(|| rfc3339(change_after)), + "banned_until": m.banned_until.filter(|u| *u > now).map(|u| { + if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) } + }), + "ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)), + "email": { + "replies": m.email_replies, + "followed": m.email_followed, + "messages": m.email_messages, + "mentions": m.email_mentions, + "listener": m.email_listener, + "weekly": m.email_weekly, + }, + "listener": m.listener, + "supporter_badge": m.supporter_badge, + // From the Kereső rank: volunteering as a listener, an own picture. + "can_listen": viewer.is_moderator() || !rank.is_newcomer(), + "can_upload_avatar": viewer.is_moderator() || !rank.is_newcomer(), + }) + }); + let buyer = super::has_purchase(&state.db, user.id).await?; + 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, "can_supporter": buyer }))) +} + +#[derive(Deserialize)] +pub struct SaveMe { + nickname: String, + #[serde(default)] + avatar: Option, + #[serde(default)] + bio: Option, + #[serde(default)] + chart_share: Option, + #[serde(default)] + invisible: Option, + /// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`. + #[serde(default)] + email: Option, + /// Volunteering as a listener (from the Kereső rank). + #[serde(default)] + listener: Option, + /// Showing the "Támogató" badge (buyers only). + #[serde(default)] + supporter_badge: Option, +} + +#[derive(Deserialize)] +pub struct EmailSettings { + #[serde(default)] + replies: Option, + #[serde(default)] + followed: Option, + #[serde(default)] + messages: Option, + #[serde(default)] + mentions: Option, + #[serde(default)] + listener: Option, + #[serde(default)] + weekly: Option, +} + +fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult> { + match value { + None => Ok(None), + Some(v) if allowed.contains(&v) => Ok(Some(v.to_string())), + Some(_) => Err(ApiError::bad("Ismeretlen értesítési beállítás.")), + } +} + +/// Whether someone else has (or recently had) this folded nickname. +async fn nickname_taken(db: &sqlx::PgPool, key: &str, me: Uuid) -> Result { + sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM forum.members WHERE nickname_key = $1 AND user_id <> $2) \ + OR EXISTS (SELECT 1 FROM forum.retired_nicknames \ + WHERE nickname_key = $1 AND user_id <> $2 AND until > now())", + ) + .bind(key) + .bind(me) + .fetch_one(db) + .await +} + +fn taken() -> ApiError { + ApiError::conflict("nickname_taken", "Ezt az álnevet már más használja. Válassz másikat.") +} + +/// Creates the forum profile (choosing a nickname is the first step) or changes it. +pub async fn save_me( + State(state): St, + viewer: Viewer, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let user = viewer.require_user()?; + let nickname = text::nickname(&req.nickname)?; + let key = text::nickname_key(&nickname); + // The current avatar sent back unchanged (an own picture too) is no change. + let current = viewer.member.as_ref().map(|m| m.avatar.as_str()); + let avatar = match req.avatar.as_deref() { + Some(a) if Some(a) == current => None, + other => other.map(text::avatar).transpose()?, + }; + let avatar_changed = avatar.is_some(); + 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.")), + }; + let email = req.email.as_ref(); + let email_replies = one_of(email.and_then(|e| e.replies.as_deref()), &["off", "daily", "instant"])?; + let email_followed = one_of(email.and_then(|e| e.followed.as_deref()), &["off", "daily"])?; + let email_messages = one_of(email.and_then(|e| e.messages.as_deref()), &["off", "instant"])?; + let email_mentions = one_of(email.and_then(|e| e.mentions.as_deref()), &["off", "instant"])?; + let email_listener = one_of(email.and_then(|e| e.listener.as_deref()), &["off", "instant"])?; + let email_weekly = email.and_then(|e| e.weekly); + if req.listener == Some(true) { + let newcomer = viewer.member.as_ref().is_none_or(|m| m.rank(OffsetDateTime::now_utc()).is_newcomer()); + if newcomer && !viewer.is_moderator() { + return Err(ApiError::Forbidden("Kísérőnek a Kereső rangtól jelentkezhetsz.".into())); + } + } + if req.supporter_badge == Some(true) && !super::has_purchase(&state.db, user.id).await? { + return Err(ApiError::Forbidden("A Támogató jelvény a csomagot vásárlóké.".into())); + } + 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 => { + // One newcomer at a time, so the hundredth founder is the last. + sqlx::query("SELECT pg_advisory_xact_lock(hashtext('forum_founders'))").execute(&mut *tx).await?; + sqlx::query(&format!( + "INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, bio, chart_share, invisible, founder) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, (SELECT count(*) < {FOUNDERS} FROM forum.members WHERE founder))" + )) + .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()), + } + sqlx::query( + "UPDATE forum.members SET email_replies = COALESCE($2, email_replies), \ + email_followed = COALESCE($3, email_followed), email_messages = COALESCE($4, email_messages), \ + email_mentions = COALESCE($5, email_mentions), email_listener = COALESCE($6, email_listener), \ + email_weekly = COALESCE($7, email_weekly), listener = COALESCE($8, listener), \ + supporter_badge = COALESCE($9, supporter_badge) \ + WHERE user_id = $1", + ) + .bind(user.id) + .bind(email_replies) + .bind(email_followed) + .bind(email_messages) + .bind(email_mentions) + .bind(email_listener) + .bind(email_weekly) + .bind(req.listener) + .bind(req.supporter_badge) + .execute(&mut *tx) + .await?; + tx.commit().await?; + // A starter avatar chosen instead of an own picture: the picture goes. + if let (Some(old), true) = (viewer.member.as_ref().map(|m| m.avatar.clone()), avatar_changed) { + super::avatars::forget(&state, &old).await; + } + let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer }; + me(State(state), viewer).await +} + +#[derive(Deserialize)] +pub struct NameQuery { + name: String, +} + +/// While typing: is this nickname valid and free? +pub async fn nickname_check( + State(state): St, + viewer: Viewer, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let user = viewer.require_user()?; + let nickname = match text::nickname(&q.name) { + Ok(n) => n, + Err(e) => return Ok(Json(json!({ "ok": false, "message": e.to_string() }))), + }; + if nickname_taken(&state.db, &text::nickname_key(&nickname), user.id).await? { + return Ok(Json(json!({ "ok": false, "message": taken().to_string() }))); + } + Ok(Json(json!({ "ok": true, "nickname": nickname }))) +} + +#[derive(Deserialize)] +pub struct TokenQuery { + token: String, +} + +/// One click from a forum e-mail (its footer link, or the mail client's +/// unsubscribe button, RFC 8058): every forum e-mail off, no login needed. +pub async fn unsubscribe( + State(state): St, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let done = sqlx::query( + "UPDATE forum.members SET email_replies = 'off', email_followed = 'off', email_messages = 'off', \ + email_mentions = 'off', email_listener = 'off', email_weekly = false \ + WHERE email_token = $1", + ) + .bind(q.token.trim()) + .execute(&state.db) + .await?; + if done.rows_affected() == 0 { + return Err(ApiError::NotFound("token")); + } + Ok(Json(json!({ "unsubscribed": true }))) +} + +/// The page is open: keeps the online dot (the viewer extractor does the work). +pub async fn presence(_viewer: Viewer) -> StatusCode { + StatusCode::NO_CONTENT +} + +#[derive(sqlx::FromRow)] +struct ProfileRow { + user_id: Uuid, + bio: String, + created_at: OffsetDateTime, + post_count: i32, + invisible: bool, + last_seen_at: Option, + banned_until: Option, + ban_reason: Option, +} + +#[derive(sqlx::FromRow)] +struct RecentRow { + id: i64, + thread_id: i64, + title: String, + topic_slug: String, + topic_name: String, + created_at: OffsetDateTime, + excerpt: String, + is_opening: bool, +} + +/// A member's public profile: nickname, avatar, rank, shared signs, bio, +/// activity (coarsely), and recent posts from the topics the viewer may read. +pub async fn profile( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, +) -> ApiResult> { + let row: ProfileRow = sqlx::query_as( + "SELECT user_id, bio, created_at, post_count, invisible, last_seen_at, banned_until, ban_reason \ + FROM forum.members WHERE nickname_key = $1", + ) + .bind(text::nickname_key(&nickname)) + .fetch_optional(&state.db) + .await? + .ok_or(ApiError::NotFound("member"))?; + let brief = authors(&state.db, [row.user_id]).await?.remove(&row.user_id).ok_or(ApiError::NotFound("member"))?; + let recent: Vec = sqlx::query_as(&format!( + "SELECT p.id, p.thread_id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, p.created_at, \ + left(p.body, 200) AS excerpt, p.is_opening \ + FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id JOIN forum.topics tp ON tp.id = th.topic_id \ + WHERE p.author_id = $1 AND p.deleted_at IS NULL AND th.deleted_at IS NULL AND ({}) \ + ORDER BY p.id DESC LIMIT 10", + visible_topics(&viewer) + )) + .bind(row.user_id) + .fetch_all(&state.db) + .await?; + let thread_count: i64 = + sqlx::query_scalar("SELECT count(*) FROM forum.threads WHERE author_id = $1 AND deleted_at IS NULL") + .bind(row.user_id) + .fetch_one(&state.db) + .await?; + let now = OffsetDateTime::now_utc(); + let own = viewer.user_id() == Some(row.user_id); + let last_seen = if row.invisible && !own { + None + } else if online(false, row.last_seen_at, now) { + Some("online") + } else { + row.last_seen_at.map(|t| match now - t { + d if d < time::Duration::days(1) => "day", + d if d < time::Duration::days(7) => "week", + _ => "earlier", + }) + }; + let banned = row.banned_until.filter(|u| *u > now); + let show_ban = own || viewer.is_moderator(); + Ok(Json(json!({ + "viewer": viewer_json(&viewer), + "member": { + "author": brief, + "bio": row.bio, + "created_at": rfc3339(row.created_at), + "post_count": row.post_count, + "thread_count": thread_count, + "last_seen": last_seen, + "own": own, + "muted": viewer.mutes.contains(&row.user_id), + "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()), + }, + "relation": super::messages::relation(&state.db, &viewer, row.user_id).await?, + "recent": recent.into_iter().map(|r| json!({ + "id": r.id, + "thread_id": r.thread_id, + "thread_slug": text::slug(&r.title), + "thread_title": r.title, + "topic": { "slug": r.topic_slug, "name": r.topic_name }, + "created_at": rfc3339(r.created_at), + "excerpt": r.excerpt, + "is_opening": r.is_opening, + })).collect::>(), + }))) +} diff --git a/services/forum/src/routes/mentions.rs b/services/forum/src/routes/mentions.rs new file mode 100644 index 0000000..c8f4b60 --- /dev/null +++ b/services/forum/src/routes/mentions.rs @@ -0,0 +1,179 @@ +//! "@Holdfény" in a post: the members it names follow the thread (so it shows +//! as new for them), hear of it live, and by e-mail if they asked. Nicknames +//! may hold spaces, so after an "@" the longest text that folds into a +//! member's nickname wins ("@Hold fény" too). + +use std::collections::HashSet; + +use axum::Json; +use axum::extract::{Query, State}; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::PgPool; +use uuid::Uuid; + +use super::{St, authors}; +use crate::AppState; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +/// Members named in one post, at most. +const MAX_MENTIONS: usize = 10; +/// Characters looked at after an "@". +const LOOK_AHEAD: usize = 30; + +/// For each "@" (at the start of a word), the folded forms of the text after +/// it, longest last. +fn candidates(body: &str) -> Vec> { + let chars: Vec = body.chars().collect(); + let mut out = Vec::new(); + for (i, c) in chars.iter().enumerate() { + if *c != '@' || (i > 0 && chars[i - 1].is_alphanumeric()) { + continue; + } + let mut keys = Vec::new(); + let mut taken = String::new(); + for &next in chars.iter().skip(i + 1).take(LOOK_AHEAD) { + if next == '\n' || next == '@' { + break; + } + taken.push(next); + let key = text::nickname_key(&taken); + if key.len() >= text::NICKNAME_MIN && keys.last() != Some(&key) { + keys.push(key); + } + } + if !keys.is_empty() { + out.push(keys); + } + } + out +} + +/// The members a text names (not its author), longest match per "@". +pub async fn named(db: &PgPool, body: &str, author: Uuid) -> Result, sqlx::Error> { + let per_at = candidates(body); + let all: Vec = per_at.iter().flatten().cloned().collect::>().into_iter().collect(); + if all.is_empty() { + return Ok(Vec::new()); + } + let found: Vec<(Uuid, String)> = + sqlx::query_as("SELECT user_id, nickname_key FROM forum.members WHERE nickname_key = ANY($1)") + .bind(&all) + .fetch_all(db) + .await?; + let mut users = Vec::new(); + for keys in per_at { + if let Some((user, _)) = keys.iter().rev().find_map(|k| found.iter().find(|(_, key)| key == k)) + && *user != author + && !users.contains(user) + { + users.push(*user); + } + if users.len() >= MAX_MENTIONS { + break; + } + } + Ok(users) +} + +/// Records the mentions of a post; returns the members named for the first +/// time, who may read the thread (a restricted topic: its members only). +pub async fn record(state: &AppState, thread: i64, post: i64, author: Uuid, body: &str) -> Vec { + let result: Result, sqlx::Error> = async { + let users = named(&state.db, body, author).await?; + if users.is_empty() { + return Ok(Vec::new()); + } + let readers: Vec = sqlx::query_scalar( + "SELECT u.id FROM users u JOIN forum.threads th ON th.id = $2 JOIN forum.topics tp ON tp.id = th.topic_id \ + WHERE u.id = ANY($1) AND (tp.visibility <> 'restricted' \ + OR 'moderator' = ANY(u.roles) OR 'admin' = ANY(u.roles) \ + OR EXISTS (SELECT 1 FROM forum.topic_members tm \ + WHERE tm.topic_id = tp.id AND tm.user_id = u.id AND tm.status = 'approved'))", + ) + .bind(&users) + .bind(thread) + .fetch_all(&state.db) + .await?; + let mut fresh = Vec::new(); + for user in readers { + let inserted = + sqlx::query("INSERT INTO forum.mentions (post_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING") + .bind(post) + .bind(user) + .execute(&state.db) + .await?; + if inserted.rows_affected() == 1 { + sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING") + .bind(user) + .bind(thread) + .execute(&state.db) + .await?; + fresh.push(user); + } + } + Ok(fresh) + } + .await; + match result { + Ok(fresh) => fresh, + Err(e) => { + tracing::error!(error = %e, post, "recording mentions"); + Vec::new() + } + } +} + +/// After a post is saved: mentions recorded, the named told live and by e-mail. +pub async fn after_post(state: &AppState, thread: i64, post: i64, author: Uuid, body: &str) { + let fresh = record(state, thread, post, author, body).await; + if fresh.is_empty() { + return; + } + crate::mail::after_mention(state, thread, post, author, &fresh, body).await; + crate::live::emit(&state.db, crate::live::Event::default().for_users(fresh)).await; +} + +#[derive(Deserialize)] +pub struct SearchQuery { + q: String, +} + +/// While typing "@Ho…": members whose nickname starts so (the recently seen first). +pub async fn search( + State(state): St, + viewer: Viewer, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + viewer.require_member()?; + let key = text::nickname_key(&q.q); + if key.is_empty() { + return Ok(Json(json!({ "members": [] }))); + } + let ids: Vec = sqlx::query_scalar( + "SELECT user_id FROM forum.members WHERE nickname_key LIKE $1 || '%' \ + ORDER BY last_seen_at DESC NULLS LAST LIMIT 6", + ) + .bind(&key) + .fetch_all(&state.db) + .await?; + let people = authors(&state.db, ids.iter().copied()).await?; + Ok(Json(json!({ "members": ids.iter().filter_map(|id| people.get(id)).collect::>() }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_the_text_after_each_at() { + let found = candidates("Szia @Hold fény, és @zöldág! e-mail: a@b.hu"); + assert_eq!(found.len(), 2, "not inside an e-mail address"); + assert!(found[0].contains(&"holdfeny".to_string())); + assert!(found[1].contains(&"zoldag".to_string())); + assert!(candidates("@ab").is_empty(), "too short to be a nickname"); + } +} diff --git a/services/forum/src/routes/messages.rs b/services/forum/src/routes/messages.rs new file mode 100644 index 0000000..991c5f7 --- /dev/null +++ b/services/forum/src/routes/messages.rs @@ -0,0 +1,517 @@ +//! Private messages. Nobody can just write to someone: first a request with +//! a short introduction (from the Kereső rank, after writing in public; at +//! most a few a day), which the recipient accepts, declines (silently: the +//! sender keeps seeing "sent" until it expires) or blocks. Then one-to-one +//! text. Moderators never read conversations, only a reported message. + +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::{Body, IdPath, St, authors, rfc3339}; +use crate::auth::{Member, Viewer}; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +/// A request not answered in this many days expires. +const REQUEST_DAYS: i64 = 14; +/// After a decline (or an expired request) a new request may come this much later. +const RETRY_DAYS: i64 = 30; +/// New requests one member may send in 24 hours. +const REQUESTS_PER_DAY: i64 = 3; +const INTRO_MIN: usize = 3; +const INTRO_MAX: usize = 200; +const MESSAGE_MAX: usize = 4000; +/// Messages one member may send in 24 hours (all conversations). +const MESSAGES_PER_DAY: i64 = 300; +/// Messages shown in a conversation. +const MESSAGES_SHOWN: i64 = 200; + +#[derive(Debug, Clone, sqlx::FromRow)] +struct Conversation { + id: i64, + user_a: Uuid, + user_b: Uuid, + requested_by: Uuid, + intro: String, + status: String, + blocked_by: Option, + created_at: OffsetDateTime, + responded_at: Option, + last_message_at: Option, +} + +const CONVERSATION_COLUMNS: &str = + "id, user_a, user_b, requested_by, intro, status, blocked_by, created_at, responded_at, last_message_at"; + +impl Conversation { + fn other(&self, me: Uuid) -> Uuid { + if self.user_a == me { self.user_b } else { self.user_a } + } + + fn expired(&self, now: OffsetDateTime) -> bool { + now - self.created_at > time::Duration::days(REQUEST_DAYS) + } + + /// How the conversation looks to `me`. A decline, or a block by the + /// other, looks like a request still waiting (then expired). + fn state_for(&self, me: Uuid, now: OffsetDateTime) -> &'static str { + match self.status.as_str() { + "accepted" => "accepted", + "blocked" if self.blocked_by == Some(me) => "blocked_by_me", + _ if self.requested_by == me => { + if self.expired(now) { + "expired" + } else { + "outgoing" + } + } + "pending" if !self.expired(now) => "incoming", + _ => "closed", + } + } +} + +fn pair(a: Uuid, b: Uuid) -> (Uuid, Uuid) { + if a < b { (a, b) } else { (b, a) } +} + +/// Whether a member may start conversations: from the Kereső rank and after +/// writing in public (moderators always). +fn may_request(viewer: &Viewer, member: &Member) -> bool { + viewer.is_moderator() || (!member.rank(OffsetDateTime::now_utc()).is_newcomer() && member.post_count > 0) +} + +/// The viewer's relation to another member, for the profile page. +pub async fn relation(db: &PgPool, viewer: &Viewer, other: Uuid) -> ApiResult { + let Some(member) = &viewer.member else { return Ok(Value::Null) }; + if member.user_id == other { + return Ok(Value::Null); + } + let (a, b) = pair(member.user_id, other); + let conversation: Option = sqlx::query_as(&format!( + "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE user_a = $1 AND user_b = $2" + )) + .bind(a) + .bind(b) + .fetch_optional(db) + .await?; + let now = OffsetDateTime::now_utc(); + let state = conversation.as_ref().map(|c| c.state_for(member.user_id, now)); + let can_request = + !member.banned(now) && may_request(viewer, member) && matches!(state, None | Some("expired") | Some("closed")); + Ok(json!({ + "conversation_id": conversation.as_ref().map(|c| c.id), + "state": state, + "can_request": can_request, + "eligible": may_request(viewer, member), + })) +} + +fn intro_text(raw: &str) -> ApiResult { + let intro: String = raw.split_whitespace().collect::>().join(" "); + let len = intro.chars().count(); + if !(INTRO_MIN..=INTRO_MAX).contains(&len) { + return Err(ApiError::bad(format!("A bemutatkozás {INTRO_MIN}–{INTRO_MAX} karakter legyen."))); + } + let lower = intro.to_lowercase(); + if lower.contains("http") || lower.contains("www.") { + return Err(ApiError::bad("A kérésbe nem tehetsz linket.")); + } + text::body(&intro) +} + +#[derive(Deserialize)] +pub struct NewRequest { + /// The other member's nickname. + to: String, + intro: String, +} + +/// Sends a conversation request. +pub async fn request( + State(state): St, + viewer: Viewer, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let me = viewer.require_writer()?; + if !may_request(&viewer, me) { + return Err(ApiError::Forbidden( + "Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba. A neked küldött kéréseket addig is elfogadhatod." + .into(), + )); + } + let other: Uuid = sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1") + .bind(text::nickname_key(&req.to)) + .fetch_optional(&state.db) + .await? + .ok_or(ApiError::NotFound("member"))?; + if other == me.user_id { + return Err(ApiError::bad("Magaddal nem kezdeményezhetsz beszélgetést.")); + } + let intro = intro_text(&req.intro)?; + let sent_today: i64 = sqlx::query_scalar( + "SELECT count(*) FROM forum.conversations WHERE requested_by = $1 AND created_at > now() - interval '24 hours'", + ) + .bind(me.user_id) + .fetch_one(&state.db) + .await?; + if sent_today >= REQUESTS_PER_DAY && !viewer.is_moderator() { + return Err(ApiError::Limited(format!("Naponta legfeljebb {REQUESTS_PER_DAY} kérést küldhetsz."))); + } + + let (a, b) = pair(me.user_id, other); + let now = OffsetDateTime::now_utc(); + let mut tx = state.db.begin().await?; + let existing: Option = sqlx::query_as(&format!( + "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE user_a = $1 AND user_b = $2 FOR UPDATE" + )) + .bind(a) + .bind(b) + .fetch_optional(&mut *tx) + .await?; + let waiting = || ApiError::conflict("request_pending", "Már elküldted a kérésedet."); + let id = match existing { + None => { + sqlx::query_scalar( + "INSERT INTO forum.conversations (user_a, user_b, requested_by, intro) VALUES ($1, $2, $3, $4) RETURNING id", + ) + .bind(a) + .bind(b) + .bind(me.user_id) + .bind(&intro) + .fetch_one(&mut *tx) + .await? + } + Some(c) => { + match c.state_for(me.user_id, now) { + "accepted" => return Err(ApiError::conflict("conversation_open", "Már beszélgettek.")), + "incoming" => { + return Err(ApiError::conflict("request_incoming", "Ő már küldött neked kérést: nézd meg az üzeneteidnél.")); + } + "blocked_by_me" => { + return Err(ApiError::conflict("blocked", "Letiltottad őt. Előbb oldd fel a tiltást az üzeneteidnél.")); + } + "outgoing" => return Err(waiting()), + _ => {} + } + // Blocked by the other: looks like a request still waiting. + if c.status == "blocked" { + return Err(waiting()); + } + // After one's own declined or expired request, a new one only + // after a while (the one who declined may write at once). + let since = c.responded_at.unwrap_or(c.created_at); + if c.requested_by == me.user_id && now - since < time::Duration::days(RETRY_DAYS) { + return Err(waiting()); + } + sqlx::query( + "UPDATE forum.conversations SET requested_by = $2, intro = $3, status = 'pending', blocked_by = NULL, \ + created_at = now(), responded_at = NULL WHERE id = $1", + ) + .bind(c.id) + .bind(me.user_id) + .bind(&intro) + .execute(&mut *tx) + .await?; + c.id + } + }; + tx.commit().await?; + crate::mail::after_message(&state, id, me.user_id, true, Some(&intro)).await; + crate::live::emit( + &state.db, + crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![other]), + ) + .await; + Ok((StatusCode::CREATED, Json(json!({ "id": id })))) +} + +/// A conversation of the viewer (any state), or 404. +async fn own(db: &PgPool, me: Uuid, id: i64) -> ApiResult { + sqlx::query_as(&format!( + "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE id = $1 AND $2 IN (user_a, user_b)" + )) + .bind(id) + .bind(me) + .fetch_optional(db) + .await? + .ok_or(ApiError::NotFound("conversation")) +} + +#[derive(sqlx::FromRow)] +struct LastMessage { + conversation_id: i64, + sender_id: Option, + body: String, +} + +/// The viewer's conversations and requests, and how many messages are unread. +pub async fn list(State(state): St, viewer: Viewer) -> ApiResult> { + let me = viewer.require_member()?.user_id; + let rows: Vec = sqlx::query_as(&format!( + "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE $1 IN (user_a, user_b) \ + ORDER BY COALESCE(last_message_at, created_at) DESC LIMIT 200" + )) + .bind(me) + .fetch_all(&state.db) + .await?; + let ids: Vec = rows.iter().map(|c| c.id).collect(); + let last: Vec = sqlx::query_as( + "SELECT DISTINCT ON (conversation_id) conversation_id, sender_id, left(body, 120) AS body \ + FROM forum.messages WHERE conversation_id = ANY($1) ORDER BY conversation_id, id DESC", + ) + .bind(&ids) + .fetch_all(&state.db) + .await?; + let unread: Vec<(i64, i64)> = sqlx::query_as( + "SELECT m.conversation_id, count(*) FROM forum.messages m \ + WHERE m.conversation_id = ANY($1) AND m.sender_id IS DISTINCT FROM $2 \ + AND m.id > COALESCE((SELECT r.last_message_id FROM forum.conversation_reads r \ + WHERE r.conversation_id = m.conversation_id AND r.user_id = $2), 0) \ + GROUP BY 1", + ) + .bind(&ids) + .bind(me) + .fetch_all(&state.db) + .await?; + let people = authors(&state.db, rows.iter().map(|c| c.other(me))).await?; + let now = OffsetDateTime::now_utc(); + let items: Vec = rows + .iter() + .filter_map(|c| { + let state = c.state_for(me, now); + if state == "closed" { + return None; + } + let last = last.iter().find(|l| l.conversation_id == c.id); + Some(json!({ + "id": c.id, + "other": people.get(&c.other(me)), + "state": state, + "intro": c.intro, + "created_at": rfc3339(c.created_at), + "last_message_at": c.last_message_at.map(rfc3339), + "last_message": last.map(|l| json!({ "excerpt": l.body, "mine": l.sender_id == Some(me) })), + "unread": unread.iter().find(|(id, _)| *id == c.id).map(|(_, n)| *n).unwrap_or(0), + })) + }) + .collect(); + Ok(Json(json!({ "conversations": items }))) +} + +/// Unread messages and requests waiting for an answer (the menu's badge). +pub async fn unread_count(db: &PgPool, me: Uuid) -> Result { + sqlx::query_scalar( + "SELECT (SELECT count(*) FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \ + WHERE $1 IN (c.user_a, c.user_b) AND c.status = 'accepted' AND m.sender_id IS DISTINCT FROM $1 \ + AND m.id > COALESCE((SELECT r.last_message_id FROM forum.conversation_reads r \ + WHERE r.conversation_id = c.id AND r.user_id = $1), 0)) \ + + (SELECT count(*) FROM forum.conversations c \ + WHERE $1 IN (c.user_a, c.user_b) AND c.status = 'pending' AND c.requested_by <> $1 \ + AND c.created_at > now() - make_interval(days => $2))", + ) + .bind(me) + .bind(REQUEST_DAYS as i32) + .fetch_one(db) + .await +} + +/// One conversation: the request, and the messages once accepted. +pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult> { + let me = viewer.require_member()?.user_id; + let c = own(&state.db, me, id).await?; + let now = OffsetDateTime::now_utc(); + let conversation_state = c.state_for(me, now); + if conversation_state == "closed" { + return Err(ApiError::NotFound("conversation")); + } + let messages: Vec<(i64, Option, String, OffsetDateTime)> = + if c.status == "accepted" || conversation_state == "blocked_by_me" { + sqlx::query_as( + "SELECT id, sender_id, body, created_at FROM \ + (SELECT id, sender_id, body, created_at FROM forum.messages WHERE conversation_id = $1 \ + ORDER BY id DESC LIMIT $2) recent ORDER BY id", + ) + .bind(id) + .bind(MESSAGES_SHOWN) + .fetch_all(&state.db) + .await? + } else { + Vec::new() + }; + let people = authors(&state.db, [c.other(me)]).await?; + Ok(Json(json!({ + "viewer": super::home::viewer_json(&viewer), + "conversation": { + "id": c.id, + "other": people.get(&c.other(me)), + "state": conversation_state, + "intro": c.intro, + "requested_by_me": c.requested_by == me, + "created_at": rfc3339(c.created_at), + }, + "messages": messages.into_iter().map(|(id, sender, body, at)| json!({ + "id": id, "mine": sender == Some(me), "body": body, "created_at": rfc3339(at), + })).collect::>(), + }))) +} + +/// The recipient answers a request: accept, decline (silently) or block. +pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static str) -> ApiResult { + let State(state) = state; + let WithRejection(Path(id), _) = path; + let me = viewer.require_member()?.user_id; + let c = own(&state.db, me, id).await?; + let now = OffsetDateTime::now_utc(); + match answer { + "block" => { + sqlx::query( + "UPDATE forum.conversations SET status = 'blocked', blocked_by = $2, responded_at = now() WHERE id = $1", + ) + .bind(id) + .bind(me) + .execute(&state.db) + .await?; + } + "unblock" => { + if c.blocked_by != Some(me) { + return Err(ApiError::bad("Ezt a tiltást nem te állítottad be.")); + } + sqlx::query( + "UPDATE forum.conversations SET status = 'declined', blocked_by = NULL, responded_at = now() WHERE id = $1", + ) + .bind(id) + .execute(&state.db) + .await?; + } + _ => { + if c.state_for(me, now) != "incoming" { + return Err(ApiError::bad("Erre a kérésre már nem lehet válaszolni.")); + } + let status = if answer == "accept" { "accepted" } else { "declined" }; + sqlx::query("UPDATE forum.conversations SET status = $2, responded_at = now() WHERE id = $1") + .bind(id) + .bind(status) + .execute(&state.db) + .await?; + } + } + let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me), me]); + crate::live::emit(&state.db, event).await; + Ok(StatusCode::NO_CONTENT) +} + +pub async fn accept(state: St, viewer: Viewer, path: IdPath) -> ApiResult { + respond(state, viewer, path, "accept").await +} + +pub async fn decline(state: St, viewer: Viewer, path: IdPath) -> ApiResult { + respond(state, viewer, path, "decline").await +} + +pub async fn block(state: St, viewer: Viewer, path: IdPath) -> ApiResult { + respond(state, viewer, path, "block").await +} + +pub async fn unblock(state: St, viewer: Viewer, path: IdPath) -> ApiResult { + respond(state, viewer, path, "unblock").await +} + +#[derive(Deserialize)] +pub struct NewMessage { + body: String, +} + +/// A message in an accepted conversation. +pub async fn send( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let me = viewer.require_writer()?.user_id; + let c = own(&state.db, me, id).await?; + if c.status != "accepted" { + return Err(ApiError::Forbidden("Ebben a beszélgetésben most nem lehet írni.".into())); + } + let body = text::body(&req.body)?; + if body.chars().count() > MESSAGE_MAX { + return Err(ApiError::bad(format!("Az üzenet legfeljebb {MESSAGE_MAX} karakter lehet."))); + } + let today: i64 = sqlx::query_scalar( + "SELECT count(*) FROM forum.messages WHERE sender_id = $1 AND created_at > now() - interval '24 hours'", + ) + .bind(me) + .fetch_one(&state.db) + .await?; + if today >= MESSAGES_PER_DAY { + return Err(ApiError::Limited("Ma már nagyon sok üzenetet küldtél. Holnap folytathatod.".into())); + } + let mut tx = state.db.begin().await?; + let (message_id, created_at): (i64, OffsetDateTime) = sqlx::query_as( + "INSERT INTO forum.messages (conversation_id, sender_id, body) VALUES ($1, $2, $3) RETURNING id, created_at", + ) + .bind(id) + .bind(me) + .bind(&body) + .fetch_one(&mut *tx) + .await?; + sqlx::query("UPDATE forum.conversations SET last_message_at = now() WHERE id = $1") + .bind(id) + .execute(&mut *tx) + .await?; + mark(&mut *tx, id, me, message_id).await?; + tx.commit().await?; + crate::mail::after_message(&state, id, me, false, None).await; + let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me)]); + crate::live::emit(&state.db, event).await; + Ok(( + StatusCode::CREATED, + Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })), + )) +} + +async fn mark(db: impl sqlx::PgExecutor<'_>, conversation: i64, user: Uuid, message: i64) -> Result<(), sqlx::Error> { + sqlx::query( + "INSERT INTO forum.conversation_reads (conversation_id, user_id, last_message_id) VALUES ($1, $2, $3) \ + ON CONFLICT (conversation_id, user_id) DO UPDATE \ + SET last_message_id = GREATEST(forum.conversation_reads.last_message_id, EXCLUDED.last_message_id)", + ) + .bind(conversation) + .bind(user) + .bind(message) + .execute(db) + .await?; + Ok(()) +} + +#[derive(Deserialize)] +pub struct ReadMark { + message_id: i64, +} + +/// Read up to that message. No read receipts: the other never sees this. +pub async fn read( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let me = viewer.require_member()?.user_id; + own(&state.db, me, id).await?; + let last: Option = sqlx::query_scalar("SELECT max(id) FROM forum.messages WHERE conversation_id = $1") + .bind(id) + .fetch_one(&state.db) + .await?; + if let Some(last) = last { + mark(&state.db, id, me, req.message_id.min(last)).await?; + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs new file mode 100644 index 0000000..ba71f78 --- /dev/null +++ b/services/forum/src/routes/mod.rs @@ -0,0 +1,373 @@ +//! 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 attachments; +mod avatars; +mod home; +mod members; +mod mentions; +mod messages; +mod moderation; +mod mutes; +mod posts; +mod replies; +mod reports; +mod search; +mod threads; +mod topics; + +use std::collections::HashMap; +use std::sync::Arc; + +use axum::extract::{Path, State}; +use axum::routing::{get, post, put}; +use axum::{Json, Router}; +use axum_extra::extract::WithRejection; +use serde_json::{Value, json}; +use sqlx::PgPool; +use time::OffsetDateTime; +use tower_http::trace::TraceLayer; +use uuid::Uuid; + +use crate::AppState; +use crate::auth::{ONLINE_MINUTES, Viewer}; +use crate::error::ApiError; +use crate::rank::Rank; + +pub type Body = WithRejection, ApiError>; +pub type IdPath = WithRejection, ApiError>; +pub type St = State>; + +pub fn router(state: Arc) -> Router { + Router::new() + .route("/healthz", get(health)) + .route("/v1/forum/home", get(home::home)) + .route("/v1/forum/nav", get(home::nav)) + .route("/v1/forum/topics", get(home::topics).post(topics::create)) + .route("/v1/forum/topics/{slug}", get(home::topic).patch(topics::update)) + .route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave)) + .route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide)) + .route("/v1/forum/followed", get(home::followed)) + .route("/v1/forum/replies", get(replies::list)) + .route("/v1/forum/search", get(search::search)) + .route("/v1/forum/share-card/{slug}", get(attachments::preview)) + .route("/v1/forum/link-thumbs/{file}", get(crate::links::thumbnail)) + .route("/v1/forum/posts/{id}/share", axum::routing::delete(posts::detach_share)) + .route("/v1/forum/sitemap", get(search::sitemap)) + .route("/v1/forum/replies/read", post(replies::read_all)) + .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/posts/{id}/report", post(reports::report_post)) + .route("/v1/forum/messages/{id}/report", post(reports::report_message)) + .route("/v1/forum/conversations", get(messages::list).post(messages::request)) + .route("/v1/forum/conversations/{id}", get(messages::show)) + .route("/v1/forum/conversations/{id}/accept", post(messages::accept)) + .route("/v1/forum/conversations/{id}/decline", post(messages::decline)) + .route("/v1/forum/conversations/{id}/block", post(messages::block).delete(messages::unblock)) + .route("/v1/forum/conversations/{id}/messages", post(messages::send)) + .route("/v1/forum/conversations/{id}/read", post(messages::read)) + .route("/v1/forum/me", get(members::me).put(members::save_me)) + .route( + "/v1/forum/me/avatar", + put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)), + ) + .route("/v1/forum/avatars/{file}", get(avatars::serve)) + .route("/v1/forum/members/{nickname}/avatar-reset", post(avatars::reset)) + .route("/v1/forum/nickname-check", get(members::nickname_check)) + .route("/v1/forum/presence", post(members::presence)) + .route("/v1/forum/unsubscribe", post(members::unsubscribe)) + .route("/v1/forum/ws", get(crate::live::connect)) + .route("/v1/forum/members/search", get(mentions::search)) + .route("/v1/forum/members/{nickname}", get(members::profile)) + .route("/v1/forum/members/{nickname}/mute", put(mutes::mute).delete(mutes::unmute)) + .route("/v1/forum/members/{nickname}/founder", put(mutes::set_founder)) + .route("/v1/forum/me/mutes", get(mutes::list)) + .route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban)) + .route("/v1/forum/mod/log", get(moderation::log)) + .route("/v1/forum/mod/reports", get(reports::list)) + .route("/v1/forum/mod/reports/{id}", post(reports::handle)) + // The request log: masked paths, health checks only when they fail. + .layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog)) + .with_state(state) +} + +async fn health(State(state): St) -> Result, ApiError> { + sqlx::query("SELECT 1").execute(&state.db).await?; + Ok(Json(json!({ "status": "ok" }))) +} + +/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics). +/// Built from the viewer's flags and their approved topic ids only, never +/// from input. +pub fn visible_topics(viewer: &Viewer) -> String { + if viewer.is_moderator() { + "TRUE".into() + } else if viewer.logged_in() { + let mut sql = "tp.visibility IN ('public', 'members')".to_string(); + if !viewer.topics.is_empty() { + let ids: Vec = viewer.topics.iter().map(|id| id.to_string()).collect(); + sql.push_str(&format!(" OR tp.id IN ({})", ids.join(", "))); + } + sql + } else { + "tp.visibility = 'public'".into() + } +} + +/// Whether the viewer may read a topic of this visibility (restricted: only +/// moderators and the approved members). +pub fn may_read(viewer: &Viewer, visibility: &str, topic: i16) -> bool { + match visibility { + "public" => true, + "members" => viewer.logged_in(), + _ => viewer.is_moderator() || viewer.topics.contains(&topic), + } +} + +/// A thread in a list: what the cards on the forum pages show. +#[derive(sqlx::FromRow)] +pub struct CardRow { + pub id: i64, + pub title: String, + pub intent: Option, + pub author_id: Option, + pub created_at: OffsetDateTime, + pub last_post_at: OffsetDateTime, + pub reply_count: i32, + pub pinned: bool, + pub locked: bool, + pub topic_slug: String, + pub topic_name: String, + pub participants: i64, + /// Posts by others the member has not read; `None` for visitors. + pub unread: Option, + /// The site's own thread (the daily sky). + pub system: bool, +} + +/// `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`. +/// `col` (an author) is not muted by the viewer, `$1` (true for visitors). +pub fn not_muted(col: &str) -> String { + format!("NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = {col})") +} + +pub fn card_sql(viewer: &Viewer) -> String { + 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 {} \ + 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, \ + th.system \ + FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ + WHERE th.deleted_at IS NULL AND ({}) AND {}", + not_muted("p.author_id"), + visible_topics(viewer), + not_muted("th.author_id"), + ) +} + +/// `$1` and `$2` of [`card_sql`]. +pub fn card_params(viewer: &Viewer) -> (Option, Option) { + match &viewer.member { + Some(m) => (Some(m.user_id), Some(m.created_at)), + None => (None, None), + } +} + +pub async fn cards_json(db: &PgPool, rows: Vec) -> Result, sqlx::Error> { + let people = authors(db, rows.iter().filter_map(|r| r.author_id)).await?; + Ok(rows + .into_iter() + .map(|r| { + json!({ + "id": r.id, + "slug": crate::text::slug(&r.title), + "title": r.title, + "intent": r.intent, + "topic": { "slug": r.topic_slug, "name": r.topic_name }, + "author": r.author_id.and_then(|id| people.get(&id).cloned()), + "created_at": rfc3339(r.created_at), + "last_post_at": rfc3339(r.last_post_at), + "reply_count": r.reply_count, + "participants": r.participants, + "pinned": r.pinned, + "locked": r.locked, + "unread": r.unread, + "system": r.system, + }) + }) + .collect()) +} + +#[derive(sqlx::FromRow)] +struct AuthorRow { + user_id: Uuid, + nickname: String, + avatar: String, + points: i32, + created_at: OffsetDateTime, + invisible: bool, + last_seen_at: Option, + chart_share: String, + roles: Vec, + listener: bool, + supporter: bool, + founder: bool, +} + +/// How members appear next to what they wrote: nickname, avatar, rank, +/// moderator badge, online dot, and the signs they chose to share. +pub async fn authors(db: &PgPool, ids: impl IntoIterator) -> Result, sqlx::Error> { + let mut ids: Vec = ids.into_iter().collect(); + ids.sort_unstable(); + ids.dedup(); + if ids.is_empty() { + return Ok(HashMap::new()); + } + let rows: Vec = sqlx::query_as( + "SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \ + m.chart_share, u.roles, m.listener, m.founder, \ + m.supporter_badge AND EXISTS (SELECT 1 FROM package_orders o \ + WHERE o.user_id = m.user_id AND o.source = 'stripe') AS supporter \ + FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.user_id = ANY($1)", + ) + .bind(&ids) + .fetch_all(db) + .await?; + let sharing: Vec = rows.iter().filter(|r| r.chart_share != "none").map(|r| r.user_id).collect(); + let signs = shared_signs(db, &sharing).await?; + let now = OffsetDateTime::now_utc(); + Ok(rows + .into_iter() + .map(|r| { + let rank = Rank::of(r.points, r.created_at, now); + let moderator = r.roles.iter().any(|role| role == "moderator" || role == "admin"); + let shown = signs.get(&r.user_id).map(|chart| chart.share(&r.chart_share)); + let value = json!({ + "nickname": r.nickname, + "avatar": r.avatar, + "rank": rank, + "rank_name": rank.name(), + "moderator": moderator, + "online": online(r.invisible, r.last_seen_at, now), + "signs": shown, + "listener": r.listener, + "supporter": r.supporter, + "founder": r.founder, + }); + (r.user_id, value) + }) + .collect()) +} + +pub fn online(invisible: bool, last_seen_at: Option, now: OffsetDateTime) -> bool { + !invisible && last_seen_at.is_some_and(|t| now - t < time::Duration::minutes(ONLINE_MINUTES)) +} + +/// The signs of a member's own chart (never degrees: they would give away the +/// birth date and time). +#[derive(Debug, Clone, Default)] +pub struct ChartSigns { + /// Planet id → sign id, in the chart's order. + pub planets: Vec<(String, String)>, + /// Only when the birth time is known. + pub ascendant: Option, +} + +const PLANETS: [&str; 10] = + ["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"]; + +impl ChartSigns { + fn sign(&self, id: &str) -> Option<&str> { + self.planets.iter().find(|(p, _)| p == id).map(|(_, s)| s.as_str()) + } + + /// What a sharing level shows; `None` for "none". + pub fn share(&self, level: &str) -> Option { + let mut out = serde_json::Map::new(); + let mut put = |key: &str, sign: Option<&str>| { + if let Some(sign) = sign { + out.insert(key.to_string(), json!(sign)); + } + }; + match level { + "sun" => put("sun", self.sign("sun")), + "big3" => { + put("sun", self.sign("sun")); + put("moon", self.sign("moon")); + put("ascendant", self.ascendant.as_deref()); + } + "planets" => { + for planet in PLANETS { + put(planet, self.sign(planet)); + } + put("ascendant", self.ascendant.as_deref()); + } + _ => return None, + } + if out.is_empty() { None } else { Some(Value::Object(out)) } + } +} + +/// The signs of each user's own chart (the current one first). +pub async fn shared_signs(db: &PgPool, users: &[Uuid]) -> Result, sqlx::Error> { + if users.is_empty() { + return Ok(HashMap::new()); + } + type Row = (Uuid, Option, Option, Option); + let rows: Vec = sqlx::query_as( + "SELECT DISTINCT ON (owner_id) owner_id, result->'points', result->'angles'->'ascendant'->>'sign', \ + (result->'time'->>'time_known')::boolean \ + FROM charts WHERE owner_id = ANY($1) AND kind = 'own' ORDER BY owner_id, is_primary DESC, created_at", + ) + .bind(users) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(owner, points, ascendant, time_known)| { + let planets = points + .as_ref() + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|p| Some((p["id"].as_str()?.to_string(), p["sign"].as_str()?.to_string()))) + .filter(|(id, _)| PLANETS.contains(&id.as_str())) + .collect(); + let ascendant = ascendant.filter(|_| time_known.unwrap_or(false)); + (owner, ChartSigns { planets, ascendant }) + }) + .collect()) +} + +pub fn rfc3339(t: OffsetDateTime) -> String { + t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default() +} + +/// Whether the user bought a package (lifts the newcomer limits). +pub async fn has_purchase(db: &PgPool, user: Uuid) -> Result { + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')") + .bind(user) + .fetch_one(db) + .await +} diff --git a/services/forum/src/routes/moderation.rs b/services/forum/src/routes/moderation.rs new file mode 100644 index 0000000..7cf26b0 --- /dev/null +++ b/services/forum/src/routes/moderation.rs @@ -0,0 +1,247 @@ +//! 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, + ResolveReport, + DismissReport, + ApproveMember, + RejectMember, + RemoveMember, + ResetAvatar, + Topic, +} + +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", + Action::ResolveReport => "resolve_report", + Action::DismissReport => "dismiss_report", + Action::ApproveMember => "approve_member", + Action::RejectMember => "reject_member", + Action::RemoveMember => "remove_member", + Action::ResetAvatar => "reset_avatar", + Action::Topic => "topic", + } + } +} + +/// Writes one line of the moderation log (a person's step). +#[allow(clippy::too_many_arguments)] +pub async fn record( + db: impl sqlx::PgExecutor<'_>, + actor: Uuid, + action: Action, + target_user: Option, + thread_id: Option, + post_id: Option, + reason: Option<&str>, + until: Option, +) -> Result<(), sqlx::Error> { + sqlx::query( + "INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \ + VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)", + ) + .bind(actor) + .bind(action.as_str()) + .bind(target_user) + .bind(thread_id) + .bind(post_id) + .bind(reason) + .bind(until) + .execute(db) + .await?; + Ok(()) +} + +/// Logs the closing of a report. +pub async fn record_report( + db: impl sqlx::PgExecutor<'_>, + actor: Uuid, + action: Action, + report_id: i64, + post_id: Option, +) -> Result<(), sqlx::Error> { + sqlx::query( + "INSERT INTO forum.mod_log (actor_id, actor_kind, action, report_id, post_id, \ + thread_id, target_user) \ + SELECT $1, 'human', $2, $3, $4, p.thread_id, p.author_id \ + FROM (SELECT 1) one LEFT JOIN forum.posts p ON p.id = $4", + ) + .bind(actor) + .bind(action.as_str()) + .bind(report_id) + .bind(post_id) + .execute(db) + .await?; + Ok(()) +} + +/// A ban for good: the last day of year 9999. +fn forever() -> OffsetDateTime { + let day = time::Date::from_calendar_date(9999, time::Month::December, 31).expect("valid date"); + time::PrimitiveDateTime::new(day, time::Time::MIDNIGHT).assume_utc() +} + +/// The longest temporary ban, in hours (a year); longer is a ban for good. +const MAX_BAN_HOURS: i64 = 24 * 365; + +#[derive(Deserialize)] +pub struct BanRequest { + /// Hours; missing or `null`: for good. + #[serde(default)] + hours: Option, + #[serde(default)] + reason: Option, +} + +/// The member behind a nickname, and whether they are a moderator or admin. +async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> { + let row: Option<(Uuid, Vec)> = sqlx::query_as( + "SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1", + ) + .bind(text::nickname_key(nickname)) + .fetch_optional(db) + .await?; + let (id, roles) = row.ok_or(ApiError::NotFound("member"))?; + Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin"))) +} + +/// A moderator bans a member for some hours or for good: they may still +/// read, not write. Moderators and admins cannot be banned this way. +pub async fn ban( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let moderator = viewer.require_moderator()?; + let (user, protected) = target(&state.db, &nickname).await?; + if protected { + return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into())); + } + let reason = text::reason(req.reason.as_deref().unwrap_or(""))?; + let until = match req.hours { + Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h), + Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))), + None => forever(), + }; + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1") + .bind(user) + .bind(until) + .bind(&reason) + .execute(&mut *tx) + .await?; + record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?; + tx.commit().await?; + tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned"); + let payload = json!({ + "url": crate::mail::rules_url(&state), + "action": "banned", + "reason": reason, + "duration": req.hours.map(crate::mail::ban_duration), + }); + crate::mail::notify_user(&state, user, "forum_moderation", payload).await; + Ok(Json(json!({ "banned_until": if req.hours.is_none() { "infinity".to_string() } else { rfc3339(until) } }))) +} + +pub async fn unban( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, +) -> ApiResult { + let moderator = viewer.require_moderator()?; + let (user, _) = target(&state.db, &nickname).await?; + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1") + .bind(user) + .execute(&mut *tx) + .await?; + record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(sqlx::FromRow)] +struct LogRow { + id: i64, + actor: Option, + actor_kind: String, + action: String, + target: Option, + thread_id: Option, + thread_title: Option, + post_id: Option, + report_id: Option, + reason: Option, + until: Option, + created_at: OffsetDateTime, +} + +/// The latest moderation steps, for moderators. +pub async fn log(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_moderator()?; + let rows: Vec = sqlx::query_as( + "SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \ + tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.report_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, + "report_id": r.report_id, + "reason": r.reason, + "until": r.until.map(|u| if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }), + "created_at": rfc3339(r.created_at), + })).collect::>(), + }))) +} diff --git a/services/forum/src/routes/mutes.rs b/services/forum/src/routes/mutes.rs new file mode 100644 index 0000000..626a083 --- /dev/null +++ b/services/forum/src/routes/mutes.rs @@ -0,0 +1,94 @@ +//! "Némítás": a member mutes another. The muted member's threads leave the +//! muter's lists, their posts fold up (one click shows them), their replies +//! and mentions no longer notify, and they drop out of "Most itt vannak". +//! The muted member is not told, and can still be reported. +//! (Also here: the admin's switch for the "Alapító tag" badge.) + +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum_extra::extract::WithRejection; +use serde_json::{Value, json}; +use uuid::Uuid; + +use super::{St, authors}; +use crate::AppState; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +async fn member_id(state: &AppState, nickname: &str) -> ApiResult { + sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1") + .bind(text::nickname_key(nickname)) + .fetch_optional(&state.db) + .await? + .ok_or(ApiError::NotFound("member")) +} + +pub async fn mute( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, +) -> ApiResult { + let member = viewer.require_member()?; + let target = member_id(&state, &nickname).await?; + if target == member.user_id { + return Err(ApiError::bad("Saját magadat nem némíthatod el.")); + } + sqlx::query("INSERT INTO forum.mutes (user_id, muted_id) VALUES ($1, $2) ON CONFLICT DO NOTHING") + .bind(member.user_id) + .bind(target) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +pub async fn unmute( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, +) -> ApiResult { + let member = viewer.require_member()?; + let target = member_id(&state, &nickname).await?; + sqlx::query("DELETE FROM forum.mutes WHERE user_id = $1 AND muted_id = $2") + .bind(member.user_id) + .bind(target) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +/// The members the viewer muted (for the settings page). +pub async fn list(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_member()?; + let people = authors(&state.db, viewer.mutes.iter().copied()).await?; + let mut muted: Vec = viewer.mutes.iter().filter_map(|id| people.get(id).cloned()).collect(); + muted.sort_by(|a, b| a["nickname"].as_str().cmp(&b["nickname"].as_str())); + Ok(Json(json!({ "muted": muted }))) +} + +/// The admin takes the "Alapító tag" badge from a member (a test account) or +/// gives it; a place taken away goes to the next newcomer. +pub async fn set_founder( + State(state): St, + viewer: Viewer, + WithRejection(Path(nickname), _): WithRejection, ApiError>, + WithRejection(axum::Json(req), _): WithRejection, ApiError>, +) -> ApiResult { + viewer.require_user()?; + if !viewer.is_admin() { + return Err(ApiError::Forbidden("Ezt csak az admin teheti meg.".into())); + } + let target = member_id(&state, &nickname).await?; + sqlx::query("UPDATE forum.members SET founder = $2 WHERE user_id = $1") + .bind(target) + .bind(req.founder) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(serde::Deserialize)] +pub struct FounderChange { + founder: bool, +} diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs new file mode 100644 index 0000000..4ef0750 --- /dev/null +++ b/services/forum/src/routes/posts.rs @@ -0,0 +1,348 @@ +//! 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; + +/// Anyone viewing the thread refetches it (reactions, edits, removals). +async fn announce(state: &crate::AppState, thread: i64) { + crate::live::emit(&state.db, crate::live::Event { thread: Some(thread), ..Default::default() }).await; +} + +/// A post and its thread, both readable by the viewer. +async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> { + let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1")) + .bind(id) + .fetch_optional(db) + .await? + .ok_or(ApiError::NotFound("post"))?; + let thread = readable_thread(db, viewer, post.thread_id).await?; + Ok((post, thread)) +} + +#[derive(Deserialize)] +pub struct Edit { + body: String, +} + +/// The author changes their post (while the thread is open). +pub async fn edit( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let member = viewer.require_writer()?; + let (post, _) = load(&state.db, &viewer, id).await?; + if post.author_id != Some(member.user_id) || post.deleted_at.is_some() { + return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into())); + } + open_thread(&state.db, &viewer, post.thread_id).await?; + let body = text::body(&req.body)?; + let post: PostRow = sqlx::query_as(&format!( + "UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}" + )) + .bind(id) + .bind(&body) + .fetch_one(&state.db) + .await?; + crate::links::process(&state, &body).await; + announce(&state, post.thread_id).await; + super::mentions::after_post(&state, post.thread_id, post.id, member.user_id, &body).await; + Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0))) +} + +/// The author takes back their post, or a moderator removes it with a reason. +/// Hidden, not erased: the admin can restore it. +pub async fn remove( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let user = viewer.require_user()?; + let (post, thread) = 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?; + } + // Deleting one's own question takes the shared chart's link down too. + if own && let Some(share) = post.share_id { + revoke_share(&mut *tx, share, user.id).await?; + } + let mut reporters = Vec::new(); + if !own { + reporters = super::reports::resolve_for_post(&mut tx, id, user.id).await?; + 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?; + if !own { + if let Some(author) = post.author_id { + let payload = serde_json::json!({ + "url": crate::mail::rules_url(&state), + "action": "post_removed", + "reason": reason, + "thread_title": thread.title, + }); + crate::mail::notify_user(&state, author, "forum_moderation", payload).await; + } + crate::mail::notify_reporters(&state, &reporters, "removed").await; + } + announce(&state, post.thread_id).await; + Ok(StatusCode::NO_CONTENT) +} + +/// The admin undoes a removal. +pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult { + let admin = viewer.require_user()?; + if !viewer.is_admin() { + return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into())); + } + let (post, _) = load(&state.db, &viewer, id).await?; + if post.deleted_at.is_none() { + return Ok(StatusCode::NO_CONTENT); + } + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1") + .bind(id) + .execute(&mut *tx) + .await?; + if !post.is_opening { + sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1") + .bind(post.thread_id) + .execute(&mut *tx) + .await?; + } + moderation::record( + &mut *tx, + admin.id, + Action::RestorePost, + post.author_id, + Some(post.thread_id), + Some(id), + None, + None, + ) + .await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Deserialize)] +pub struct React { + kind: String, +} + +fn points_of(kind: &str) -> i32 { + if kind == "down" { -1 } else { 1 } +} + +/// Gives (or changes) the viewer's one reaction to a post. A newcomer's +/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is +/// not offered in listening topics. +pub async fn react( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let member = viewer.require_writer()?; + let (post, thread) = load(&state.db, &viewer, id).await?; + if post.deleted_at.is_some() { + return Err(ApiError::NotFound("post")); + } + open_thread(&state.db, &viewer, thread.id).await?; + if post.author_id == Some(member.user_id) { + return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into())); + } + let kind = req.kind.as_str(); + let now = OffsetDateTime::now_utc(); + let rank = member.rank(now); + if kind == "down" { + if thread.listening { + return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into())); + } + if !rank.may_downvote() { + return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into())); + } + } else if !REACTIONS.contains(&kind) { + return Err(ApiError::bad("Ismeretlen reakció.")); + } + let counted = !rank.is_newcomer(); + + let mut tx = state.db.begin().await?; + let previous: Option<(String, bool)> = + sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE") + .bind(id) + .bind(member.user_id) + .fetch_optional(&mut *tx) + .await?; + let mut delta = if counted { points_of(kind) } else { 0 }; + if let Some((old, true)) = &previous { + delta -= points_of(old); + } + sqlx::query( + "INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \ + ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()", + ) + .bind(id) + .bind(member.user_id) + .bind(kind) + .bind(counted) + .execute(&mut *tx) + .await?; + add_points(&mut tx, post.author_id, delta).await?; + tx.commit().await?; + announce(&state, post.thread_id).await; + Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0))) +} + +pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult> { + let member = viewer.require_writer()?; + let (post, _) = load(&state.db, &viewer, id).await?; + let mut tx = state.db.begin().await?; + let removed: Option<(String, bool)> = + sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted") + .bind(id) + .bind(member.user_id) + .fetch_optional(&mut *tx) + .await?; + if let Some((kind, true)) = removed { + add_points(&mut tx, post.author_id, -points_of(&kind)).await?; + } + tx.commit().await?; + announce(&state, post.thread_id).await; + Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0))) +} + +async fn add_points(tx: &mut sqlx::PgConnection, author: Option, delta: i32) -> Result<(), sqlx::Error> { + if let (Some(author), true) = (author, delta != 0) { + sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1") + .bind(author) + .bind(delta) + .execute(&mut *tx) + .await?; + } + Ok(()) +} + +/// The thread's author marks a reply that helped (worth more than a reaction). +pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult> { + set_helped(state, viewer, path, true).await +} + +pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult> { + set_helped(state, viewer, path, false).await +} + +async fn set_helped( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + on: bool, +) -> ApiResult> { + let member = viewer.require_writer()?; + let (post, thread) = load(&state.db, &viewer, id).await?; + if thread.author_id != Some(member.user_id) { + return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into())); + } + if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() { + return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted.")); + } + let mut tx = state.db.begin().await?; + let changed: Option = if on { + sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id") + } else { + sqlx::query_scalar( + "UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id", + ) + } + .bind(id) + .fetch_optional(&mut *tx) + .await?; + if changed.is_some() { + add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?; + } + tx.commit().await?; + announce(&state, thread.id).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))) +} + +/// The sharer's link goes (as when revoked on the main site). +async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> { + sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL") + .bind(share) + .bind(owner) + .execute(db) + .await?; + Ok(()) +} + +/// The author takes the shared chart off their question: the card goes, and +/// the link stops working. +pub async fn detach_share( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, +) -> ApiResult { + let user = viewer.require_user()?; + let (post, _) = load(&state.db, &viewer, id).await?; + if post.author_id != Some(user.id) { + return Err(ApiError::Forbidden("Csak a saját kérdésedről veheted le a képletet.".into())); + } + let Some(share) = post.share_id else { return Ok(StatusCode::NO_CONTENT) }; + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.posts SET share_id = NULL WHERE id = $1").bind(id).execute(&mut *tx).await?; + revoke_share(&mut *tx, share, user.id).await?; + tx.commit().await?; + announce(&state, post.thread_id).await; + Ok(StatusCode::NO_CONTENT) +} diff --git a/services/forum/src/routes/replies.rs b/services/forum/src/routes/replies.rs new file mode 100644 index 0000000..b461830 --- /dev/null +++ b/services/forum/src/routes/replies.rs @@ -0,0 +1,135 @@ +//! "Válaszok": what answers the member. A reply to one of their posts (also +//! a reply to a reply of theirs, `reply_to_id`), a first-level reply in a +//! thread they opened, or a post that names them ("@Holdfény"). One stays +//! unread until the member has read that far in the thread; the forum menu +//! shows only this count. + +use axum::Json; +use axum::extract::{Query, 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::{St, rfc3339, visible_topics}; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; + +/// The posts that answer `$1`, from the threads the viewer may read. +fn answers(viewer: &Viewer) -> String { + format!( + "FROM forum.posts p \ + JOIN forum.threads th ON th.id = p.thread_id \ + JOIN forum.topics tp ON tp.id = th.topic_id \ + LEFT JOIN forum.posts target ON target.id = COALESCE(p.reply_to_id, p.parent_id) \ + LEFT JOIN forum.reads r ON r.user_id = $1 AND r.thread_id = p.thread_id \ + WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND NOT p.is_opening AND NOT p.system \ + AND p.author_id IS DISTINCT FROM $1 AND ({}) \ + AND NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = p.author_id) \ + AND (target.author_id = $1 \ + OR (p.parent_id IS NULL AND th.author_id = $1) \ + OR EXISTS (SELECT 1 FROM forum.mentions mn WHERE mn.post_id = p.id AND mn.user_id = $1))", + visible_topics(viewer) + ) +} + +const UNREAD: &str = "p.id > COALESCE(r.last_post_id, 0)"; + +/// How many answers wait unread (for the menu), at most 100. +pub async fn unread_count(db: &PgPool, viewer: &Viewer, me: Uuid) -> Result { + sqlx::query_scalar(&format!("SELECT count(*) FROM (SELECT 1 {} AND {UNREAD} LIMIT 100) x", answers(viewer))) + .bind(me) + .fetch_one(db) + .await +} + +#[derive(Deserialize)] +pub struct ListQuery { + #[serde(default)] + page: Option, +} + +#[derive(sqlx::FromRow)] +struct Row { + id: i64, + thread_id: i64, + title: String, + author_id: Option, + body: String, + created_at: OffsetDateTime, + kind: String, + unread: bool, +} + +const PAGE: i64 = 30; + +/// The member's answers, newest first. +pub async fn list( + State(state): St, + viewer: Viewer, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let member = viewer.require_member()?; + let page = q.page.unwrap_or(1).clamp(1, 1000); + let rows: Vec = sqlx::query_as(&format!( + "SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.created_at, \ + CASE WHEN target.author_id = $1 THEN 'reply' \ + WHEN p.parent_id IS NULL AND th.author_id = $1 THEN 'thread' \ + ELSE 'mention' END AS kind, \ + {UNREAD} AS unread \ + {} ORDER BY p.id DESC LIMIT {} OFFSET $2", + answers(&viewer), + PAGE + 1 + )) + .bind(member.user_id) + .bind((page - 1) * PAGE) + .fetch_all(&state.db) + .await?; + let more = rows.len() as i64 > PAGE; + let rows = &rows[..rows.len().min(PAGE as usize)]; + let authors = super::authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?; + let replies: Vec = rows + .iter() + .map(|r| { + json!({ + "id": r.id, + "thread": { "id": r.thread_id, "title": r.title, "slug": crate::text::slug(&r.title) }, + "author": r.author_id.and_then(|a| authors.get(&a).cloned()), + "excerpt": excerpt(&r.body), + "created_at": rfc3339(r.created_at), + "kind": r.kind, + "unread": r.unread, + }) + }) + .collect(); + let unread = unread_count(&state.db, &viewer, member.user_id).await?; + Ok(Json(json!({ "replies": replies, "unread": unread, "page": page, "more": more }))) +} + +/// "Mind olvasott": the threads with unread answers count as read up to them. +pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult { + let member = viewer.require_member()?; + sqlx::query(&format!( + "INSERT INTO forum.reads (user_id, thread_id, last_post_id) \ + SELECT $1, p.thread_id, max(p.id) {} AND {UNREAD} GROUP BY p.thread_id \ + 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()", + answers(&viewer) + )) + .bind(member.user_id) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +/// The start of a post, on one line. +fn excerpt(body: &str) -> String { + let line = body.split_whitespace().collect::>().join(" "); + match line.char_indices().nth(160) { + Some((at, _)) => format!("{}…", line[..at].trim_end()), + None => line, + } +} diff --git a/services/forum/src/routes/reports.rs b/services/forum/src/routes/reports.rs new file mode 100644 index 0000000..954964a --- /dev/null +++ b/services/forum/src/routes/reports.rs @@ -0,0 +1,351 @@ +//! Reports (the DSA's notice and action): any logged-in user may report a +//! post or a private message; moderators see the open ones, act on the post +//! (removal is in `posts`) and close the report. A reported private message +//! is the only way a moderator sees a conversation: the message and the few +//! before it. + +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::moderation::{self, Action}; +use super::threads::readable_thread; +use super::{Body, IdPath, St, authors, rfc3339}; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +pub const KINDS: [&str; 6] = ["spam", "ad", "rude", "crisis", "illegal", "other"]; +const NOTE_MAX: usize = 500; +/// Reports one user may send in 24 hours. +const PER_DAY: i64 = 20; +/// Messages shown to moderators around a reported one. +const MESSAGE_CONTEXT: i64 = 10; + +#[derive(Deserialize)] +pub struct ReportRequest { + kind: String, + #[serde(default)] + note: Option, +} + +fn check(req: &ReportRequest) -> ApiResult { + if !KINDS.contains(&req.kind.as_str()) { + return Err(ApiError::bad("Válaszd ki, mi a gond.")); + } + let note = req.note.as_deref().unwrap_or("").split_whitespace().collect::>().join(" "); + if note.chars().count() > NOTE_MAX { + return Err(ApiError::bad(format!("A megjegyzés legfeljebb {NOTE_MAX} karakter lehet."))); + } + if req.kind == "other" && note.chars().count() < 3 { + return Err(ApiError::bad("Írd le röviden, mi a gond.")); + } + Ok(note) +} + +async fn within_limit(db: &PgPool, user: Uuid) -> ApiResult<()> { + let today: i64 = sqlx::query_scalar( + "SELECT count(*) FROM forum.reports WHERE reporter_id = $1 AND created_at > now() - interval '24 hours'", + ) + .bind(user) + .fetch_one(db) + .await?; + if today >= PER_DAY { + return Err(ApiError::Limited("Ma már sok jelentést küldtél. Holnap újra lehet.".into())); + } + Ok(()) +} + +fn received(kind: &str) -> Json { + Json(json!({ "received": true, "crisis": kind == "crisis" })) +} + +/// Reports a post (not one's own). A second report of the same post by the +/// same user while the first is open changes nothing. +pub async fn report_post( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let user = viewer.require_user()?; + let note = check(&req)?; + let post: Option<(i64, Option)> = + sqlx::query_as("SELECT thread_id, author_id FROM forum.posts WHERE id = $1") + .bind(id) + .fetch_optional(&state.db) + .await?; + let (thread_id, author) = post.ok_or(ApiError::NotFound("post"))?; + readable_thread(&state.db, &viewer, thread_id).await?; + if author == Some(user.id) { + return Err(ApiError::bad("A saját hozzászólásodat nem jelentheted.")); + } + within_limit(&state.db, user.id).await?; + sqlx::query( + "INSERT INTO forum.reports (post_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING", + ) + .bind(id) + .bind(user.id) + .bind(&req.kind) + .bind(¬e) + .execute(&state.db) + .await?; + tracing::info!(post = id, kind = %req.kind, "post reported"); + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; + Ok((StatusCode::CREATED, received(&req.kind))) +} + +/// Reports a private message received in one's own conversation. +pub async fn report_message( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let user = viewer.require_user()?; + let note = check(&req)?; + let found: Option<(Option,)> = sqlx::query_as( + "SELECT m.sender_id FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \ + WHERE m.id = $1 AND $2 IN (c.user_a, c.user_b)", + ) + .bind(id) + .bind(user.id) + .fetch_optional(&state.db) + .await?; + let (sender,) = found.ok_or(ApiError::NotFound("message"))?; + if sender == Some(user.id) { + return Err(ApiError::bad("A saját üzenetedet nem jelentheted.")); + } + within_limit(&state.db, user.id).await?; + sqlx::query( + "INSERT INTO forum.reports (message_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING", + ) + .bind(id) + .bind(user.id) + .bind(&req.kind) + .bind(¬e) + .execute(&state.db) + .await?; + tracing::info!(message = id, kind = %req.kind, "message reported"); + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; + Ok((StatusCode::CREATED, received(&req.kind))) +} + +#[derive(sqlx::FromRow)] +struct ReportRow { + id: i64, + post_id: Option, + message_id: Option, + reporter: Option, + kind: String, + note: String, + status: String, + handled_by: Option, + handled_at: Option, + created_at: OffsetDateTime, +} + +#[derive(sqlx::FromRow)] +struct PostTarget { + id: i64, + thread_id: i64, + title: String, + author_id: Option, + body: String, + deleted: bool, +} + +#[derive(sqlx::FromRow)] +struct MessageRow { + id: i64, + conversation_id: i64, + sender_id: Option, + body: String, + created_at: OffsetDateTime, +} + +/// Open reports (the oldest first, crisis ones before all), and the last +/// handled ones, with what was reported. +pub async fn list(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_moderator()?; + let rows: Vec = sqlx::query_as( + "SELECT r.id, r.post_id, r.message_id, COALESCE(rm.nickname, 'tag') AS reporter, r.kind, r.note, r.status, \ + COALESCE(hm.nickname, hu.display_name) AS handled_by, r.handled_at, r.created_at \ + FROM forum.reports r \ + LEFT JOIN forum.members rm ON rm.user_id = r.reporter_id \ + LEFT JOIN forum.members hm ON hm.user_id = r.handled_by \ + LEFT JOIN users hu ON hu.id = r.handled_by \ + WHERE r.status = 'open' OR r.handled_at > now() - interval '30 days' \ + ORDER BY r.status <> 'open', r.kind <> 'crisis', \ + CASE WHEN r.status = 'open' THEN r.created_at END, r.handled_at DESC \ + LIMIT 200", + ) + .fetch_all(&state.db) + .await?; + + let post_ids: Vec = rows.iter().filter_map(|r| r.post_id).collect(); + let posts: Vec = sqlx::query_as( + "SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.deleted_at IS NOT NULL AS deleted \ + FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.id = ANY($1)", + ) + .bind(&post_ids) + .fetch_all(&state.db) + .await?; + let message_ids: Vec = rows.iter().filter_map(|r| r.message_id).collect(); + // Each reported message with the few before it in its conversation. + let messages: Vec<(i64, MessageRow)> = sqlx::query_as::<_, (i64, i64, i64, Option, String, OffsetDateTime)>( + "SELECT r.id AS reported, m.id, m.conversation_id, m.sender_id, m.body, m.created_at \ + FROM forum.messages r \ + JOIN LATERAL (SELECT * FROM forum.messages m WHERE m.conversation_id = r.conversation_id AND m.id <= r.id \ + ORDER BY m.id DESC LIMIT $2) m ON true \ + WHERE r.id = ANY($1) ORDER BY m.id", + ) + .bind(&message_ids) + .bind(MESSAGE_CONTEXT) + .fetch_all(&state.db) + .await? + .into_iter() + .map(|(reported, id, conversation_id, sender_id, body, created_at)| { + (reported, MessageRow { id, conversation_id, sender_id, body, created_at }) + }) + .collect(); + let people = authors( + &state.db, + posts.iter().filter_map(|p| p.author_id).chain(messages.iter().filter_map(|(_, m)| m.sender_id)), + ) + .await?; + let open_counts: Vec<(Option, Option, i64)> = + sqlx::query_as("SELECT post_id, message_id, count(*) FROM forum.reports WHERE status = 'open' GROUP BY 1, 2") + .fetch_all(&state.db) + .await?; + + let entries: Vec = rows + .into_iter() + .map(|r| { + let target = if let Some(post_id) = r.post_id { + posts.iter().find(|p| p.id == post_id).map(|p| { + json!({ + "type": "post", + "id": p.id, + "thread": { "id": p.thread_id, "title": p.title, "slug": text::slug(&p.title) }, + "author": p.author_id.and_then(|a| people.get(&a).cloned()), + "body": p.body, + "deleted": p.deleted, + }) + }) + } else { + let id = r.message_id.unwrap_or_default(); + let context: Vec = messages + .iter() + .filter(|(reported, _)| *reported == id) + .map(|(_, m)| { + json!({ + "id": m.id, + "sender": m.sender_id.and_then(|s| people.get(&s).cloned()), + "body": m.body, + "created_at": rfc3339(m.created_at), + "reported": m.id == id, + }) + }) + .collect(); + let conversation = + messages.iter().find(|(reported, _)| *reported == id).map(|(_, m)| m.conversation_id); + Some(json!({ "type": "message", "id": id, "conversation_id": conversation, "messages": context })) + }; + let reports = open_counts + .iter() + .find(|(p, m, _)| *p == r.post_id && *m == r.message_id) + .map(|(_, _, n)| *n) + .unwrap_or(0); + json!({ + "id": r.id, + "kind": r.kind, + "note": r.note, + "reporter": r.reporter, + "status": r.status, + "handled_by": r.handled_by, + "handled_at": r.handled_at.map(rfc3339), + "created_at": rfc3339(r.created_at), + "open_reports_of_target": reports, + "target": target, + }) + }) + .collect(); + Ok(Json(json!({ "reports": entries }))) +} + +#[derive(Deserialize)] +pub struct Handle { + /// `resolve`: acted on (or nothing needed beyond what was done); + /// `dismiss`: the report was unfounded. + action: String, +} + +/// Closes a report, and every other open report of the same post or message. +pub async fn handle( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let moderator = viewer.require_moderator()?; + let (status, action) = match req.action.as_str() { + "resolve" => ("resolved", Action::ResolveReport), + "dismiss" => ("dismissed", Action::DismissReport), + _ => return Err(ApiError::bad("Ismeretlen művelet.")), + }; + let report: Option<(Option, Option)> = + sqlx::query_as("SELECT post_id, message_id FROM forum.reports WHERE id = $1") + .bind(id) + .fetch_optional(&state.db) + .await?; + let (post_id, message_id) = report.ok_or(ApiError::NotFound("report"))?; + let mut tx = state.db.begin().await?; + let reporters: Vec> = sqlx::query_scalar( + "UPDATE forum.reports SET status = $2, handled_by = $3, handled_at = now() \ + WHERE status = 'open' AND (id = $1 OR ($4::bigint IS NOT NULL AND post_id = $4) \ + OR ($5::bigint IS NOT NULL AND message_id = $5)) \ + RETURNING reporter_id", + ) + .bind(id) + .bind(status) + .bind(moderator.id) + .bind(post_id) + .bind(message_id) + .fetch_all(&mut *tx) + .await?; + moderation::record_report(&mut *tx, moderator.id, action, id, post_id).await?; + tx.commit().await?; + let outcome = if status == "resolved" { "handled" } else { "no_violation" }; + crate::mail::notify_reporters(&state, &reporters, outcome).await; + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; + Ok(StatusCode::NO_CONTENT) +} + +/// When a moderator removes a post, its open reports are resolved with it. +/// Returns the reporters, to tell them. +pub async fn resolve_for_post( + tx: &mut sqlx::PgConnection, + post_id: i64, + moderator: Uuid, +) -> Result>, sqlx::Error> { + sqlx::query_scalar( + "UPDATE forum.reports SET status = 'resolved', handled_by = $2, handled_at = now() \ + WHERE post_id = $1 AND status = 'open' RETURNING reporter_id", + ) + .bind(post_id) + .bind(moderator) + .fetch_all(&mut *tx) + .await +} + +/// Open reports, for the moderators' badge. +pub async fn open_count(db: &PgPool) -> Result { + sqlx::query_scalar("SELECT count(*) FROM forum.reports WHERE status = 'open'").fetch_one(db).await +} diff --git a/services/forum/src/routes/search.rs b/services/forum/src/routes/search.rs new file mode 100644 index 0000000..db8f283 --- /dev/null +++ b/services/forum/src/routes/search.rs @@ -0,0 +1,139 @@ +//! Search in what the viewer may read: thread titles and posts, with +//! Hungarian stems ("szálak" finds "szál") and without accents ("alvas" +//! finds "alvás"). One result per thread, with the best matching post's +//! words marked; muted members are left out. + +use axum::Json; +use axum::extract::{Query, State}; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::{St, authors, not_muted, rfc3339, visible_topics}; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +#[derive(Deserialize)] +pub struct SearchQuery { + #[serde(default)] + q: Option, + #[serde(default)] + page: Option, +} + +#[derive(sqlx::FromRow)] +struct Hit { + id: i64, + title: String, + topic_slug: String, + topic_name: String, + author_id: Option, + last_post_at: OffsetDateTime, + reply_count: i32, + post_id: Option, + snippet: Option, +} + +const PAGE: i64 = 20; +/// Around the matching words in `snippet` (the page marks them). +pub const MARK_START: &str = "⟦"; +pub const MARK_END: &str = "⟧"; + +pub async fn search( + State(state): St, + viewer: Viewer, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let query: String = q.q.unwrap_or_default().trim().chars().take(100).collect(); + let page = q.page.unwrap_or(1).clamp(1, 50); + if query.chars().count() < 2 { + return Ok(Json(json!({ "query": query, "results": [], "more": false, "page": page }))); + } + // Word beginnings without accents too: "alvas" finds "alvásban". + let prefixes: Vec = query + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| w.chars().count() >= 3) + .take(8) + .map(|w| format!("{w}:*")) + .collect(); + let rows: Vec = sqlx::query_as(&format!( + "WITH q AS (SELECT websearch_to_tsquery('hungarian', $2) || to_tsquery('forum.plain', $6) AS q), \ + hits AS (SELECT p.thread_id, p.id, p.body, ts_rank(p.search, q.q) AS rank FROM forum.posts p, q \ + WHERE p.search @@ q.q AND p.deleted_at IS NULL AND {posts_ok}) \ + SELECT th.id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, th.author_id, th.last_post_at, \ + th.reply_count, best.id AS post_id, \ + CASE WHEN best.id IS NULL THEN NULL ELSE ts_headline('hungarian', best.body, q.q, $5) END AS snippet \ + FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id CROSS JOIN q \ + LEFT JOIN LATERAL (SELECT h.id, h.body, h.rank FROM hits h WHERE h.thread_id = th.id \ + ORDER BY h.rank DESC, h.id LIMIT 1) best ON true \ + WHERE th.deleted_at IS NULL AND ({visible}) AND {threads_ok} \ + AND (th.search @@ q.q OR th.id IN (SELECT thread_id FROM hits)) \ + ORDER BY (CASE WHEN th.search @@ q.q THEN 2 * ts_rank(th.search, q.q) ELSE 0 END + COALESCE(best.rank, 0)) DESC, \ + th.last_post_at DESC \ + LIMIT $3 OFFSET $4", + posts_ok = not_muted("p.author_id"), + visible = visible_topics(&viewer), + threads_ok = not_muted("th.author_id"), + )) + .bind(viewer.user_id()) + .bind(&query) + .bind(PAGE + 1) + .bind((page - 1) * PAGE) + .bind(format!( + "StartSel={MARK_START}, StopSel={MARK_END}, MaxWords=30, MinWords=12, ShortWord=2, MaxFragments=1" + )) + .bind(prefixes.join(" & ")) + .fetch_all(&state.db) + .await?; + let more = rows.len() as i64 > PAGE; + let rows = &rows[..rows.len().min(PAGE as usize)]; + let people = authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?; + let results: Vec = rows + .iter() + .map(|r| { + json!({ + "thread": { "id": r.id, "title": r.title, "slug": text::slug(&r.title) }, + "topic": { "slug": r.topic_slug, "name": r.topic_name }, + "author": r.author_id.and_then(|a| people.get(&a).cloned()), + "last_post_at": rfc3339(r.last_post_at), + "reply_count": r.reply_count, + "post_id": r.post_id, + "snippet": r.snippet, + }) + }) + .collect(); + Ok(Json(json!({ "query": query, "results": results, "more": more, "page": page }))) +} + +#[derive(sqlx::FromRow)] +struct MapThread { + id: i64, + title: String, + last_post_at: OffsetDateTime, +} + +/// For the sitemap: the public topics and their threads (newest activity first). +pub async fn sitemap(State(state): St) -> ApiResult> { + let topics: Vec<(String, Option)> = sqlx::query_as( + "SELECT tp.slug, (SELECT max(th.last_post_at) FROM forum.threads th \ + WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) \ + FROM forum.topics tp WHERE tp.visibility = 'public' ORDER BY tp.position", + ) + .fetch_all(&state.db) + .await?; + let threads: Vec = sqlx::query_as( + "SELECT th.id, th.title, th.last_post_at FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ + WHERE tp.visibility = 'public' AND th.deleted_at IS NULL ORDER BY th.last_post_at DESC LIMIT 5000", + ) + .fetch_all(&state.db) + .await?; + Ok(Json(json!({ + "topics": topics.iter().map(|(slug, at)| json!({ "slug": slug, "updated": at.map(rfc3339) })).collect::>(), + "threads": threads.iter().map(|t| json!({ + "id": t.id, "slug": text::slug(&t.title), "updated": rfc3339(t.last_post_at), + })).collect::>(), + }))) +} diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs new file mode 100644 index 0000000..1f12ad7 --- /dev/null +++ b/services/forum/src/routes/threads.rs @@ -0,0 +1,655 @@ +//! 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_id: i16, + pub topic_slug: String, + pub topic_name: String, + pub visibility: String, + pub listening: bool, + pub author_id: Option, + pub title: String, + pub intent: Option, + pub created_at: OffsetDateTime, + pub locked: bool, + pub pinned: bool, + pub deleted_at: Option, + pub delete_reason: Option, + pub system: bool, + /// Its topic is archived: readable, but takes nothing new. + pub archived: bool, +} + +const THREAD_SELECT: &str = "SELECT th.id, th.topic_id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \ + tp.listening, th.author_id, th.title, th.intent, th.created_at, th.locked, th.pinned, th.deleted_at, \ + th.delete_reason, th.system, tp.archived_at IS NOT NULL AS archived \ + FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id"; + +/// A thread the viewer may read (deleted ones too): 404 when it does not +/// exist or sits in a hidden topic, 401 in a members-only topic for a visitor. +pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult { + let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1")) + .bind(id) + .fetch_optional(db) + .await? + .ok_or(ApiError::NotFound("thread"))?; + if !may_read(viewer, &thread.visibility, thread.topic_id) { + 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, not in an +/// archived topic, and not locked (moderators may still write in a locked one). +pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult { + let thread = readable_thread(db, viewer, id).await?; + if thread.deleted_at.is_some() { + return Err(ApiError::NotFound("thread")); + } + if thread.archived { + return Err(ApiError::Forbidden("Ez a téma archivált: olvasható, de új hozzászólás nem írható.".into())); + } + if thread.locked && !viewer.is_moderator() { + return Err(ApiError::Forbidden("Ez a szál le van zárva.".into())); + } + Ok(thread) +} + +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct PostRow { + pub id: i64, + pub thread_id: i64, + pub parent_id: Option, + pub is_opening: bool, + pub author_id: Option, + pub body: String, + pub created_at: OffsetDateTime, + pub edited_at: Option, + pub helped_at: Option, + pub deleted_at: Option, + pub deleted_by: Option, + pub delete_reason: Option, + /// Written by the site itself (the daily sky thread). + pub system: bool, + /// The post this one answered (which may sit on the same level). + pub reply_to_id: Option, + /// A chart, forecast or synastry shared with the question. + pub share_id: Option, +} + +pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \ + delete_reason, system, reply_to_id, share_id"; + +/// Posts as the thread page shows them: authors, reactions, the viewer's own +/// reaction. A removed post keeps its place with the reason; only +/// moderators still see its text. +pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult> { + let ids: Vec = posts.iter().map(|p| p.id).collect(); + let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?; + let shares: Vec = posts.iter().filter(|p| p.deleted_at.is_none()).filter_map(|p| p.share_id).collect(); + let cards = super::attachments::cards(db, viewer, &shares).await?; + let texts: Vec<(i64, &str)> = + posts.iter().filter(|p| p.deleted_at.is_none()).map(|p| (p.id, p.body.as_str())).collect(); + let previews = crate::links::previews(db, &texts).await?; + let counts: Vec<(i64, String, i64)> = + sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2") + .bind(&ids) + .fetch_all(db) + .await?; + let mut by_post: HashMap> = HashMap::new(); + for (post, kind, n) in counts { + by_post.entry(post).or_default().insert(kind, n); + } + let mine: HashMap = match viewer.user_id() { + Some(me) => { + sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2") + .bind(&ids) + .bind(me) + .fetch_all(db) + .await? + .into_iter() + .collect() + } + None => HashMap::new(), + }; + let named: Vec<(i64, String)> = sqlx::query_as( + "SELECT mn.post_id, m.nickname FROM forum.mentions mn JOIN forum.members m ON m.user_id = mn.user_id \ + WHERE mn.post_id = ANY($1)", + ) + .bind(&ids) + .fetch_all(db) + .await?; + // Whom each reply answers: the author of the post it replied to. + let answered: Vec = posts.iter().filter_map(|p| p.reply_to_id).collect(); + let answered: HashMap> = sqlx::query_as::<_, (i64, Option)>( + "SELECT p.id, m.nickname FROM forum.posts p LEFT JOIN forum.members m ON m.user_id = p.author_id \ + WHERE p.id = ANY($1)", + ) + .bind(&answered) + .fetch_all(db) + .await? + .into_iter() + .collect(); + let moderator = viewer.is_moderator(); + Ok(posts + .iter() + .map(|p| { + let reply_to = + p.reply_to_id.map(|id| json!({ "id": id, "nickname": answered.get(&id).cloned().flatten() })); + let mentions: Vec<&String> = named.iter().filter(|(id, _)| *id == p.id).map(|(_, n)| n).collect(); + let counts = by_post.remove(&p.id).unwrap_or_default(); + let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum(); + let down = counts.get("down").copied().unwrap_or(0); + let score = positive - down; + let deleted = p.deleted_at.map(|_| { + json!({ + "by_moderator": p.deleted_by.is_some() && p.deleted_by != p.author_id, + "reason": p.delete_reason, + }) + }); + let mut post = json!({ + "id": p.id, + "parent_id": p.parent_id, + "is_opening": p.is_opening, + "author": p.author_id.and_then(|id| people.get(&id).cloned()), + "own": p.author_id.is_some() && p.author_id == viewer.user_id(), + "body": if p.deleted_at.is_none() || moderator { Some(&p.body) } else { None }, + "deleted": deleted, + "created_at": rfc3339(p.created_at), + "edited_at": p.edited_at.map(rfc3339), + "helped": p.helped_at.is_some(), + "reactions": REACTIONS.iter().map(|k| (k.to_string(), json!(counts.get(*k).copied().unwrap_or(0)))) + .collect::>(), + "score": score, + "collapsed": score <= COLLAPSE_SCORE, + "mine": mine.get(&p.id), + "mentions": mentions, + "system": p.system, + "reply_to": reply_to, + // The viewer muted the author: the page folds it up. + "muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)), + "share": p.share_id.and_then(|id| cards.get(&id).cloned()), + // Previews of the links a provider knows (YouTube). + "links": previews.get(&p.id), + }); + if moderator { + post["down"] = json!(down); + } + post + }) + .collect()) +} + +/// A thread with all its posts, oldest first. +pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult> { + let thread = readable_thread(&state.db, &viewer, id).await?; + let people = authors(&state.db, thread.author_id).await?; + let moderator = viewer.is_moderator(); + let mut out = json!({ + "viewer": viewer_json(&viewer), + "thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())), + }); + if thread.deleted_at.is_some() && !moderator { + out["posts"] = json!([]); + return Ok(Json(out)); + } + let posts: Vec = + sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id")) + .bind(id) + .fetch_all(&state.db) + .await?; + out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?); + + let now = OffsetDateTime::now_utc(); + let (following, last_read) = match viewer.user_id() { + Some(me) => { + let following: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)") + .bind(me) + .bind(id) + .fetch_one(&state.db) + .await?; + let last_read: Option = + sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2") + .bind(me) + .bind(id) + .fetch_optional(&state.db) + .await?; + (following, last_read) + } + None => (false, None), + }; + let writer = viewer.member.as_ref().filter(|m| !m.banned(now)); + let open = thread.deleted_at.is_none() && !thread.archived && (!thread.locked || moderator); + out["access"] = json!({ + "can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()), + "can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()), + "is_thread_author": thread.author_id.is_some() && thread.author_id == viewer.user_id(), + "following": following, + "last_read_post_id": last_read, + }); + Ok(Json(out)) +} + +fn thread_json(thread: &ThreadRow, author: Option) -> Value { + json!({ + "id": thread.id, + "slug": text::slug(&thread.title), + "title": thread.title, + "intent": thread.intent, + "topic": { + "slug": thread.topic_slug, "name": thread.topic_name, + "visibility": thread.visibility, "listening": thread.listening, "archived": thread.archived, + }, + "author": author, + "created_at": rfc3339(thread.created_at), + "locked": thread.locked, + "pinned": thread.pinned, + "deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })), + "system": thread.system, + }) +} + +/// 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, + /// A share made for the forum on the main site (`/s/`). + #[serde(default)] + share: Option, +} + +/// Starts a thread with its opening post; the author follows it. +pub async fn create( + State(state): St, + viewer: Viewer, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let member = viewer.require_writer()?; + let topic: Option<(i16, String, bool, bool)> = + sqlx::query_as("SELECT id, visibility, listening, archived_at IS NOT NULL FROM forum.topics WHERE slug = $1") + .bind(&req.topic) + .fetch_optional(&state.db) + .await?; + let (topic_id, visibility, listening, archived) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?; + if archived { + return Err(ApiError::bad("Ez a téma archivált, új szál nem nyitható benne.")); + } + if !may_read(&viewer, &visibility, topic_id) { + return Err(ApiError::bad("Ismeretlen téma.")); + } + let title = text::title(&req.title)?; + let body = text::body(&req.body)?; + let share = match req.share.as_deref().filter(|s| !s.trim().is_empty()) { + Some(slug) => Some(super::attachments::attachable(&state.db, member, slug).await?), + None => None, + }; + 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, share_id) \ + VALUES ($1, $2, true, $3, $4) RETURNING id", + ) + .bind(thread_id) + .bind(member.user_id) + .bind(&body) + .bind(share) + .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"); + super::mentions::after_post(&state, thread_id, post_id, member.user_id, &body).await; + crate::links::process(&state, &body).await; + Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) })))) +} + +/// After a post: the author's count, following the thread, and the read mark +/// up to their own post. +async fn after_post( + tx: &mut sqlx::PgConnection, + author: Uuid, + thread_id: i64, + post_id: i64, +) -> Result<(), sqlx::Error> { + sqlx::query("UPDATE forum.members SET post_count = post_count + 1 WHERE user_id = $1") + .bind(author) + .execute(&mut *tx) + .await?; + sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING") + .bind(author) + .bind(thread_id) + .execute(&mut *tx) + .await?; + upsert_read(&mut *tx, author, thread_id, post_id).await +} + +async fn upsert_read( + db: impl sqlx::PgExecutor<'_>, + user: Uuid, + thread_id: i64, + post_id: i64, +) -> Result<(), sqlx::Error> { + sqlx::query( + "INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3) \ + ON CONFLICT (user_id, thread_id) DO UPDATE \ + SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()", + ) + .bind(user) + .bind(thread_id) + .bind(post_id) + .execute(db) + .await?; + Ok(()) +} + +#[derive(Deserialize)] +pub struct Reply { + body: String, + /// The post answered; a reply to a reply goes under the same first-level + /// post (two levels at most), a reply to the opening post is first-level. + #[serde(default)] + parent_id: Option, +} + +pub async fn reply( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let member = viewer.require_writer()?; + open_thread(&state.db, &viewer, id).await?; + let body = text::body(&req.body)?; + // The post answered (shown as "↪ Holdfény"), and where the reply goes: + // under the first-level post (two levels at most). + let reply_to = req.parent_id; + let parent = match req.parent_id { + None => None, + Some(parent_id) => { + let parent: Option<(Option, bool, bool)> = sqlx::query_as( + "SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2", + ) + .bind(parent_id) + .bind(id) + .fetch_optional(&state.db) + .await?; + let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?; + if deleted { + return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni.")); + } + if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) } + } + }; + let reply_to = reply_to.filter(|_| parent.is_some()); + 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, reply_to_id, body) VALUES ($1, $2, $3, $4, $5) \ + RETURNING {POST_COLUMNS}" + )) + .bind(id) + .bind(member.user_id) + .bind(parent) + .bind(reply_to) + .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?; + // The one answered hears of it (on the second level, not the branch's first post). + crate::mail::after_reply(&state, id, post.id, member.user_id, post.reply_to_id.or(post.parent_id), &body).await; + super::mentions::after_post(&state, id, post.id, member.user_id, &body).await; + crate::links::process(&state, &body).await; + let followers = crate::live::followers(&state.db, id, member.user_id).await; + crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers)) + .await; + let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0); + Ok((StatusCode::CREATED, Json(post))) +} + +#[derive(Deserialize)] +pub struct ReadMark { + post_id: i64, +} + +/// Read up to that post (never backwards). +pub async fn mark_read( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let member = viewer.require_member()?; + readable_thread(&state.db, &viewer, id).await?; + let last: Option = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1") + .bind(id) + .fetch_one(&state.db) + .await?; + let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) }; + upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?; + Ok(StatusCode::NO_CONTENT) +} + +pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult { + let member = viewer.require_member()?; + readable_thread(&state.db, &viewer, id).await?; + sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING") + .bind(member.user_id) + .bind(id) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult { + let member = viewer.require_member()?; + sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2") + .bind(member.user_id) + .bind(id) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Deserialize)] +pub struct ThreadChange { + #[serde(default)] + locked: Option, + #[serde(default)] + pinned: Option, +} + +/// Moderators lock (no more replies) or pin (first in its topic) a thread. +pub async fn update( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let moderator = viewer.require_moderator()?; + let thread = readable_thread(&state.db, &viewer, id).await?; + let mut tx = state.db.begin().await?; + if let Some(locked) = req.locked.filter(|l| *l != thread.locked) { + sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1") + .bind(id) + .bind(locked) + .execute(&mut *tx) + .await?; + let action = if locked { Action::Lock } else { Action::Unlock }; + moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?; + } + if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) { + sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1") + .bind(id) + .bind(pinned) + .execute(&mut *tx) + .await?; + let action = if pinned { Action::Pin } else { Action::Unpin }; + moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?; + } + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Deserialize)] +pub struct Reason { + #[serde(default)] + pub reason: Option, +} + +/// A moderator removes a whole thread; its place keeps the reason. +pub async fn remove( + State(state): St, + viewer: Viewer, + WithRejection(Path(id), _): IdPath, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let moderator = viewer.require_moderator()?; + let thread = readable_thread(&state.db, &viewer, id).await?; + if thread.deleted_at.is_some() { + return Ok(StatusCode::NO_CONTENT); + } + let reason = text::reason(req.reason.as_deref().unwrap_or(""))?; + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1") + .bind(id) + .bind(moderator.id) + .bind(&reason) + .execute(&mut *tx) + .await?; + moderation::record( + &mut *tx, + moderator.id, + Action::DeleteThread, + thread.author_id, + Some(id), + None, + Some(&reason), + None, + ) + .await?; + tx.commit().await?; + tracing::info!(thread = id, moderator = %moderator.id, "thread removed"); + if let Some(author) = thread.author_id { + let payload = json!({ + "url": crate::mail::rules_url(&state), + "action": "thread_removed", + "reason": reason, + "thread_title": thread.title, + }); + crate::mail::notify_user(&state, author, "forum_moderation", payload).await; + } + Ok(StatusCode::NO_CONTENT) +} + +/// The admin undoes a thread's removal. +pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult { + let admin = viewer.require_user()?; + if !viewer.is_admin() { + return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into())); + } + let thread = readable_thread(&state.db, &viewer, id).await?; + if thread.deleted_at.is_none() { + return Ok(StatusCode::NO_CONTENT); + } + let mut tx = state.db.begin().await?; + sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1") + .bind(id) + .execute(&mut *tx) + .await?; + moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/services/forum/src/routes/topics.rs b/services/forum/src/routes/topics.rs new file mode 100644 index 0000000..9e9c44f --- /dev/null +++ b/services/forum/src/routes/topics.rs @@ -0,0 +1,307 @@ +//! Topics: the admin creates and edits them; a restricted topic is read and +//! written only by its approved members (and moderators): members ask to +//! join, moderators approve or turn them down. + +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 uuid::Uuid; + +use super::moderation::{self, Action}; +use super::{Body, St, authors, rfc3339}; +use crate::auth::Viewer; +use crate::error::{ApiError, ApiResult}; +use crate::text; + +const NAME_MAX: usize = 60; +const DESCRIPTION_MAX: usize = 160; +const NOTE_MAX: usize = 300; + +fn require_admin(viewer: &Viewer) -> ApiResult { + let user = viewer.require_user()?; + if viewer.is_admin() { Ok(user.id) } else { Err(ApiError::Forbidden("Témát csak az admin kezelhet.".into())) } +} + +fn visibility(raw: &str) -> ApiResult { + match raw { + "public" | "members" | "restricted" => Ok(raw.to_string()), + _ => Err(ApiError::bad("Ismeretlen láthatóság.")), + } +} + +fn one_line(raw: &str, max: usize, what: &str) -> ApiResult { + let text: String = raw.split_whitespace().collect::>().join(" "); + let len = text.chars().count(); + if len < 2 || len > max { + return Err(ApiError::bad(format!("A {what} 2–{max} karakter legyen."))); + } + Ok(text) +} + +#[derive(Deserialize)] +pub struct NewTopic { + name: String, + description: String, + #[serde(default = "public")] + visibility: String, + #[serde(default)] + listening: bool, +} + +fn public() -> String { + "public".into() +} + +/// The admin opens a topic (last in the list); its address comes from the name. +pub async fn create( + State(state): St, + viewer: Viewer, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let admin = require_admin(&viewer)?; + let name = one_line(&req.name, NAME_MAX, "név")?; + let description = one_line(&req.description, DESCRIPTION_MAX, "leírás")?; + let visibility = visibility(&req.visibility)?; + let slug = text::slug(&name); + if slug.is_empty() { + return Err(ApiError::bad("A névből nem lesz cím: írj bele betűket.")); + } + let mut tx = state.db.begin().await?; + let created: Result = sqlx::query_scalar( + "INSERT INTO forum.topics (id, slug, name, description, visibility, listening, position) \ + SELECT COALESCE(max(id), 0) + 1, $1, $2, $3, $4, $5, COALESCE(max(position), 0) + 1 FROM forum.topics \ + RETURNING id", + ) + .bind(&slug) + .bind(&name) + .bind(&description) + .bind(&visibility) + .bind(req.listening) + .fetch_one(&mut *tx) + .await; + let id = match created { + Ok(id) => id, + Err(sqlx::Error::Database(e)) if e.is_unique_violation() => { + return Err(ApiError::conflict("topic_exists", "Ilyen nevű téma már van.")); + } + Err(e) => return Err(e.into()), + }; + moderation::record(&mut *tx, admin, Action::Topic, None, None, None, Some(&format!("új téma: {name}")), None) + .await?; + tx.commit().await?; + Ok((StatusCode::CREATED, Json(json!({ "id": id, "slug": slug })))) +} + +#[derive(Deserialize)] +pub struct TopicChange { + #[serde(default)] + name: Option, + #[serde(default)] + description: Option, + #[serde(default)] + visibility: Option, + #[serde(default)] + listening: Option, + #[serde(default)] + position: Option, + /// Archive (true) or bring back (false). + #[serde(default)] + archived: Option, +} + +/// The admin renames, describes, moves or changes the visibility of a topic +/// (its address stays, so links keep working). +pub async fn update( + State(state): St, + viewer: Viewer, + WithRejection(Path(slug), _): WithRejection, ApiError>, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let admin = require_admin(&viewer)?; + let name = req.name.as_deref().map(|n| one_line(n, NAME_MAX, "név")).transpose()?; + let description = req.description.as_deref().map(|d| one_line(d, DESCRIPTION_MAX, "leírás")).transpose()?; + let visibility = req.visibility.as_deref().map(visibility).transpose()?; + let mut tx = state.db.begin().await?; + let changed = sqlx::query( + "UPDATE forum.topics SET name = COALESCE($2, name), description = COALESCE($3, description), \ + visibility = COALESCE($4, visibility), listening = COALESCE($5, listening), \ + position = COALESCE($6, position), \ + archived_at = CASE WHEN $7::boolean IS NULL THEN archived_at \ + WHEN $7 THEN COALESCE(archived_at, now()) ELSE NULL END \ + WHERE slug = $1", + ) + .bind(&slug) + .bind(&name) + .bind(&description) + .bind(&visibility) + .bind(req.listening) + .bind(req.position) + .bind(req.archived) + .execute(&mut *tx) + .await?; + if changed.rows_affected() == 0 { + return Err(ApiError::NotFound("topic")); + } + moderation::record( + &mut *tx, + admin, + Action::Topic, + None, + None, + None, + Some(&match req.archived { + Some(true) => format!("téma archiválva: {slug}"), + Some(false) => format!("téma visszaállítva: {slug}"), + None => format!("téma módosítva: {slug}"), + }), + None, + ) + .await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Deserialize)] +pub struct JoinRequest { + #[serde(default)] + note: Option, +} + +/// A member asks to join a restricted topic (with a few words, if they like). +pub async fn join( + State(state): St, + viewer: Viewer, + WithRejection(Path(slug), _): WithRejection, ApiError>, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let member = viewer.require_writer()?; + let topic: Option<(i16, String)> = sqlx::query_as("SELECT id, visibility FROM forum.topics WHERE slug = $1") + .bind(&slug) + .fetch_optional(&state.db) + .await?; + let (id, visibility) = topic.ok_or(ApiError::NotFound("topic"))?; + if visibility != "restricted" { + return Err(ApiError::bad("Ebbe a témába nem kell jelentkezni.")); + } + let note: String = req.note.as_deref().unwrap_or("").split_whitespace().collect::>().join(" "); + if note.chars().count() > NOTE_MAX { + return Err(ApiError::bad(format!("Legfeljebb {NOTE_MAX} karakter."))); + } + sqlx::query("INSERT INTO forum.topic_members (topic_id, user_id, note) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING") + .bind(id) + .bind(member.user_id) + .bind(¬e) + .execute(&state.db) + .await?; + crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await; + Ok(StatusCode::NO_CONTENT) +} + +/// Leaving a restricted topic, or taking back the request. +pub async fn leave( + State(state): St, + viewer: Viewer, + WithRejection(Path(slug), _): WithRejection, ApiError>, +) -> ApiResult { + let member = viewer.require_member()?; + sqlx::query( + "DELETE FROM forum.topic_members WHERE user_id = $1 AND topic_id = (SELECT id FROM forum.topics WHERE slug = $2)", + ) + .bind(member.user_id) + .bind(&slug) + .execute(&state.db) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(sqlx::FromRow)] +struct RequestRow { + topic_slug: String, + topic_name: String, + user_id: Uuid, + status: String, + note: String, + requested_at: time::OffsetDateTime, +} + +/// For moderators: who waits to join a restricted topic, and who is in. +pub async fn requests(State(state): St, viewer: Viewer) -> ApiResult> { + viewer.require_moderator()?; + let rows: Vec = sqlx::query_as( + "SELECT tp.slug AS topic_slug, tp.name AS topic_name, tm.user_id, tm.status, tm.note, tm.requested_at \ + FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id \ + ORDER BY tm.status <> 'pending', tp.position, tm.requested_at", + ) + .fetch_all(&state.db) + .await?; + let people = authors(&state.db, rows.iter().map(|r| r.user_id)).await?; + Ok(Json(json!({ + "requests": rows.iter().map(|r| json!({ + "topic": { "slug": r.topic_slug, "name": r.topic_name }, + "member": people.get(&r.user_id), + "status": r.status, + "note": r.note, + "requested_at": rfc3339(r.requested_at), + })).collect::>(), + }))) +} + +#[derive(Deserialize)] +pub struct Decision { + topic: String, + nickname: String, + /// `approve`, `reject` (a request) or `remove` (a member). + action: String, +} + +/// A moderator approves or turns down a request, or removes a member. +pub async fn decide( + State(state): St, + viewer: Viewer, + WithRejection(Json(req), _): Body, +) -> ApiResult { + let moderator = viewer.require_moderator()?; + let found: Option<(i16, Uuid)> = sqlx::query_as( + "SELECT tp.id, m.user_id FROM forum.topics tp, forum.members m WHERE tp.slug = $1 AND m.nickname_key = $2", + ) + .bind(&req.topic) + .bind(text::nickname_key(&req.nickname)) + .fetch_optional(&state.db) + .await?; + let (topic, user) = found.ok_or(ApiError::NotFound("request"))?; + let mut tx = state.db.begin().await?; + let (done, action) = match req.action.as_str() { + "approve" => ( + sqlx::query( + "UPDATE forum.topic_members SET status = 'approved', decided_at = now(), decided_by = $3 \ + WHERE topic_id = $1 AND user_id = $2", + ) + .bind(topic) + .bind(user) + .bind(moderator.id) + .execute(&mut *tx) + .await?, + Action::ApproveMember, + ), + "reject" | "remove" => ( + sqlx::query("DELETE FROM forum.topic_members WHERE topic_id = $1 AND user_id = $2") + .bind(topic) + .bind(user) + .execute(&mut *tx) + .await?, + if req.action == "reject" { Action::RejectMember } else { Action::RemoveMember }, + ), + _ => return Err(ApiError::bad("Ismeretlen döntés.")), + }; + if done.rows_affected() == 0 { + return Err(ApiError::NotFound("request")); + } + moderation::record(&mut *tx, moderator.id, action, Some(user), None, None, Some(&req.topic), None).await?; + tx.commit().await?; + let event = crate::live::Event { moderators: true, ..Default::default() }.for_users(vec![user]); + crate::live::emit(&state.db, event).await; + Ok(StatusCode::NO_CONTENT) +} diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs new file mode 100644 index 0000000..5e048a7 --- /dev/null +++ b/services/forum/src/tests.rs @@ -0,0 +1,1405 @@ +//! 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 { + Self::with_links(pool, crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9")) + } + + /// With the link providers at these (fake) addresses. + fn with_links(pool: PgPool, links: crate::links::LinkConfig) -> Self { + let state = AppState { + db: pool.clone(), + flood_secs: 0, + base_url: "https://sorsfonalak.test".into(), + hub: crate::live::Hub::default(), + storage: None, + links, + }; + Self { router: routes::router(Arc::new(state)), pool } + } + + /// A user with a session, as after a login in the backend. + async fn user(&self, email: &str, roles: &[&str]) -> User { + let id = Uuid::now_v7(); + sqlx::query("INSERT INTO users (id, email, display_name, roles) VALUES ($1, $2, 'Valódi Név', $3)") + .bind(id) + .bind(email) + .bind(roles.iter().map(|r| r.to_string()).collect::>()) + .execute(&self.pool) + .await + .unwrap(); + let token = db::new_token(); + sqlx::query( + "INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES ($1, $2, $3, now() + interval '1 day')", + ) + .bind(Uuid::now_v7()) + .bind(id) + .bind(db::token_hash(&token)) + .execute(&self.pool) + .await + .unwrap(); + User { id, token } + } + + /// A user who already chose a nickname. + async fn member(&self, email: &str, nickname: &str, roles: &[&str]) -> User { + let user = self.user(email, roles).await; + let (status, body) = self.call("PUT", "/v1/forum/me", Some(&user), json!({ "nickname": nickname })).await; + assert_eq!(status, StatusCode::OK, "{body}"); + user + } + + /// Makes a member older and gives them points (rank Kereső and up). + async fn season(&self, user: &User, days: i32, points: i32) { + sqlx::query( + "UPDATE forum.members SET created_at = now() - make_interval(days => $2), points = $3, \ + nickname_changed_at = now() - make_interval(days => $2) WHERE user_id = $1", + ) + .bind(user.id) + .bind(days) + .bind(points) + .execute(&self.pool) + .await + .unwrap(); + } + + async fn points(&self, user: &User) -> i32 { + sqlx::query_scalar("SELECT points FROM forum.members WHERE user_id = $1") + .bind(user.id) + .fetch_one(&self.pool) + .await + .unwrap() + } + + async fn call(&self, method: &str, uri: &str, user: Option<&User>, body: Value) -> (StatusCode, Value) { + let mut req = Request::builder().method(method).uri(uri); + if let Some(u) = user { + req = req.header("authorization", format!("Bearer {}", u.token)); + } + let req = if body.is_null() { + req.body(Body::empty()).unwrap() + } else { + req.header("content-type", "application/json").body(Body::from(body.to_string())).unwrap() + }; + let resp = self.router.clone().oneshot(req).await.unwrap(); + let status = resp.status(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + let value = if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap() }; + (status, value) + } + + /// The queued e-mails of a template: (recipient, payload), oldest first. + async fn mails(&self, template: &str) -> Vec<(String, Value)> { + sqlx::query_as("SELECT to_email, payload FROM email_outbox WHERE template = $1 ORDER BY created_at, id") + .bind(template) + .fetch_all(&self.pool) + .await + .unwrap() + } + + async fn get(&self, uri: &str, user: Option<&User>) -> Value { + let (status, body) = self.call("GET", uri, user, Value::Null).await; + assert_eq!(status, StatusCode::OK, "GET {uri}: {body}"); + body + } + + /// Starts a thread; returns its id. + async fn thread(&self, user: &User, topic: &str, title: &str) -> i64 { + let (status, body) = self + .call( + "POST", + "/v1/forum/threads", + Some(user), + json!({ "topic": topic, "title": title, "body": "Az első gondolat." }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + body["id"].as_i64().unwrap() + } + + /// Replies; returns the new post. + async fn reply(&self, user: &User, thread: i64, body: &str, parent: Option) -> Value { + let (status, post) = self + .call( + "POST", + &format!("/v1/forum/threads/{thread}/posts"), + Some(user), + json!({ "body": body, "parent_id": parent }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{post}"); + post + } +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn a_nickname_comes_first_and_stays_unique(pool: PgPool) { + let app = TestApp::new(pool); + let visitor_try = app + .call("POST", "/v1/forum/threads", None, json!({ "topic": "torzsasztal", "title": "Szia", "body": "x" })) + .await; + assert_eq!(visitor_try.0, StatusCode::UNAUTHORIZED); + + let anna = app.user("anna@example.com", &["user"]).await; + let (status, body) = app + .call( + "POST", + "/v1/forum/threads", + Some(&anna), + json!({ "topic": "torzsasztal", "title": "Szia mindenki", "body": "x" }), + ) + .await; + assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("nickname_required"))); + let me = app.get("/v1/forum/me", Some(&anna)).await; + assert!(me["member"].is_null()); + assert_eq!(me["viewer"]["needs_nickname"], true); + + // The real name is never offered or shown. + let (status, me) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": " Hold fény " })).await; + assert_eq!(status, StatusCode::OK, "{me}"); + assert_eq!(me["member"]["nickname"], "Hold fény"); + assert_eq!(me["member"]["rank"], "vandor"); + assert!(!me.to_string().contains("Valódi")); + + // Folded the same: taken. + let bea = app.user("bea@example.com", &["user"]).await; + let check = app.get("/v1/forum/nickname-check?name=holdfeny", Some(&bea)).await; + assert_eq!(check["ok"], false); + let (status, body) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Ho1dfény" })).await; + assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_taken"))); + assert_eq!(app.get("/v1/forum/nickname-check?name=Napraforgó", Some(&bea)).await["ok"], true); + app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Napraforgó" })).await; + + // A spelling fix any time; a new name once in 30 days. + let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Holdfény" })).await; + assert_eq!(status, StatusCode::OK); + let (status, body) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await; + assert_eq!((status, body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("nickname_too_soon"))); + app.season(&anna, 31, 0).await; + let (status, _) = app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csillagpor" })).await; + assert_eq!(status, StatusCode::OK); + // The old name stays reserved for others… + let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Holdfény" })).await; + assert_eq!(status, StatusCode::CONFLICT); + // …and the profile is found by the new one, in any spelling. + let profile = app.get("/v1/forum/members/csillagpor", None).await; + assert_eq!(profile["member"]["author"]["nickname"], "Csillagpor"); + + let (status, _) = app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Admin Bea" })).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _) = + app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Bea", "avatar": "hold-piros" })).await; + assert_eq!(status, StatusCode::BAD_REQUEST); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn threads_replies_and_what_is_new(pool: PgPool) { + let app = TestApp::new(pool); + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + + // A listening topic: members only, threads ask for listening by default. + let heart = app.thread(&anna, "ami-a-szivemen-van", "Nem tudom elengedni anyukám házát").await; + let (status, _) = app.call("GET", &format!("/v1/forum/threads/{heart}"), None, Value::Null).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "visitors may not read a members-only topic"); + let (status, _) = app.call("GET", "/v1/forum/topics/ami-a-szivemen-van", None, Value::Null).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let shown = app.get(&format!("/v1/forum/threads/{heart}"), Some(&bea)).await; + assert_eq!(shown["thread"]["intent"], "listen"); + assert_eq!(shown["thread"]["slug"], "nem-tudom-elengedni-anyukam-hazat"); + assert_eq!(shown["access"]["can_downvote"], false); + + // A visitor sees the public topics and that the members-only one exists. + let public = app.thread(&anna, "torzsasztal", "Téli levesek").await; + let home = app.get("/v1/forum/home", None).await; + let topics = home["topics"].as_array().unwrap(); + assert_eq!(topics[0]["readable"], false); + assert!(topics[0].get("thread_count").is_none()); + assert_eq!(topics[3]["thread_count"], 1); + let waiting: Vec = home["unanswered"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect(); + assert_eq!(waiting, vec![public], "the visitor sees only the public thread waiting"); + + // Bea sees both waiting and both as new; Anna does not see her own. + let home = app.get("/v1/forum/home", Some(&bea)).await; + assert_eq!(home["unanswered"].as_array().unwrap().len(), 2); + assert_eq!(home["topics"][0]["new_count"], 1); + assert!(app.get("/v1/forum/home", Some(&anna)).await["unanswered"].as_array().unwrap().is_empty()); + + // Replies: a reply to a reply stays on the second level. + let first = app.reply(&bea, heart, "Nem vagy egyedül :)", None).await; + assert_eq!(first["body"], "Nem vagy egyedül 🙂"); + assert_eq!(first["author"]["nickname"], "Holdfény"); + let second = app.reply(&anna, heart, "Köszönöm.", first["id"].as_i64()).await; + let third = app.reply(&bea, heart, "Szívesen.", second["id"].as_i64()).await; + assert_eq!(third["parent_id"], first["id"], "two levels at most"); + assert_eq!(third["reply_to"], json!({"id": second["id"], "nickname": "Csendesvíz"}), "but it says whom it answers"); + assert!(first["reply_to"].is_null()); + + // 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 lively ("Élénk beszélgetések"). + 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"); + // The author is told what and why (whatever their notification settings). + let told = app.mails("forum_moderation").await; + assert_eq!(told.len(), 1); + assert_eq!(told[0].0, "spam@example.com"); + assert_eq!(told[0].1["action"], "post_removed"); + assert_eq!(told[0].1["reason"], "szolgáltatás hirdetése"); + assert_eq!(told[0].1["thread_title"], "Energiák"); + assert_eq!(told[0].1["nickname"], "Gyógyító"); + + // 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 told = app.mails("forum_moderation").await; + assert_eq!((told[1].1["action"].as_str(), told[1].1["duration"].as_str()), (Some("banned"), Some("2 napos"))); + 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()); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn reports_reach_moderators(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.user("cili@example.com", &["user"]).await; // no nickname: may still report + let moderator = app.member("mod@example.com", "Őrangyal", &["user", "moderator"]).await; + let thread = app.thread(&anna, "belso-utak", "Energiák").await; + let post = app.reply(&bea, thread, "Energetikai gyógyítás, írj!", None).await["id"].as_i64().unwrap(); + + let report = |user: &User, body: Value| { + let uri = format!("/v1/forum/posts/{post}/report"); + let user = User { id: user.id, token: user.token.clone() }; + let app = &app; + async move { app.call("POST", &uri, Some(&user), body).await } + }; + assert_eq!( + app.call("POST", &format!("/v1/forum/posts/{post}/report"), None, json!({"kind": "ad"})).await.0, + StatusCode::UNAUTHORIZED + ); + assert_eq!(report(&bea, json!({"kind": "ad"})).await.0, StatusCode::BAD_REQUEST, "not one's own"); + assert_eq!(report(&anna, json!({"kind": "other"})).await.0, StatusCode::BAD_REQUEST, "'other' needs a note"); + assert_eq!(report(&anna, json!({"kind": "nonsense"})).await.0, StatusCode::BAD_REQUEST); + let (status, body) = report(&anna, json!({"kind": "ad", "note": "jóslást árul"})).await; + assert_eq!((status, body["crisis"].as_bool()), (StatusCode::CREATED, Some(false))); + assert_eq!(report(&anna, json!({"kind": "ad"})).await.0, StatusCode::CREATED, "a repeat changes nothing"); + let (_, body) = report(&cili, json!({"kind": "crisis"})).await; + assert_eq!(body["crisis"], true); + + // Only moderators see them; the crisis one first; the menu shows the count. + assert_eq!(app.call("GET", "/v1/forum/mod/reports", Some(&anna), Value::Null).await.0, StatusCode::FORBIDDEN); + let list = app.get("/v1/forum/mod/reports", Some(&moderator)).await; + let reports = list["reports"].as_array().unwrap(); + assert_eq!(reports.len(), 2); + assert_eq!(reports[0]["kind"], "crisis"); + assert_eq!(reports[1]["reporter"], "Csendesvíz"); + assert_eq!(reports[1]["target"]["body"], "Energetikai gyógyítás, írj!"); + assert_eq!(reports[1]["open_reports_of_target"], 2); + assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 2); + assert!(app.get("/v1/forum/nav", Some(&anna)).await["reports"].is_null()); + + // Removing the post resolves every open report of it, and it is logged. + let (status, _) = app + .call( + "DELETE", + &format!("/v1/forum/posts/{post}"), + Some(&moderator), + json!({ "reason": "szolgáltatás hirdetése" }), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let list = app.get("/v1/forum/mod/reports", Some(&moderator)).await; + assert!(list["reports"].as_array().unwrap().iter().all(|r| r["status"] == "resolved")); + // Both reporters hear the decision, once each. + let told = app.mails("forum_report_result").await; + let mut to: Vec<&str> = told.iter().map(|(t, _)| t.as_str()).collect(); + to.sort_unstable(); + assert_eq!(to, vec!["anna@example.com", "cili@example.com"]); + assert!(told.iter().all(|(_, p)| p["outcome"] == "removed")); + assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 0); + + // A report can also be dismissed. + let other = app.reply(&bea, thread, "Bocsánat.", None).await["id"].as_i64().unwrap(); + app.call("POST", &format!("/v1/forum/posts/{other}/report"), Some(&anna), json!({"kind": "rude"})).await; + let id = app.get("/v1/forum/mod/reports", Some(&moderator)).await["reports"][0]["id"].as_i64().unwrap(); + let (status, _) = app + .call("POST", &format!("/v1/forum/mod/reports/{id}"), Some(&moderator), json!({ "action": "dismiss" })) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let told = app.mails("forum_report_result").await; + assert_eq!((told[2].0.as_str(), told[2].1["outcome"].as_str()), ("anna@example.com", Some("no_violation"))); + let log = app.get("/v1/forum/mod/log", Some(&moderator)).await; + assert_eq!(log["entries"][0]["action"], "dismiss_report"); + assert_eq!(log["entries"][0]["target"], "Holdfény"); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn private_messages_start_with_a_request(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 request = |from: &User, to: &str, intro: &str| { + let user = User { id: from.id, token: from.token.clone() }; + let body = json!({ "to": to, "intro": intro }); + let app = &app; + async move { app.call("POST", "/v1/forum/conversations", Some(&user), body).await } + }; + + // A newcomer may not start one; a seasoned member who wrote in public may. + let (status, _) = request(&anna, "Holdfény", "Szia, olvastam a hozzászólásodat.").await; + assert_eq!(status, StatusCode::FORBIDDEN); + let profile = app.get("/v1/forum/members/Holdfény", Some(&anna)).await; + assert_eq!(profile["relation"]["can_request"], false); + app.thread(&anna, "torzsasztal", "Sziasztok").await; + app.season(&anna, 5, 10).await; + assert_eq!(app.get("/v1/forum/members/Holdfény", Some(&anna)).await["relation"]["can_request"], true); + assert_eq!(request(&anna, "Holdfény", "Nézd: www.pelda.hu").await.0, StatusCode::BAD_REQUEST); + assert_eq!(request(&anna, "Csendesvíz", "Szia, én vagyok.").await.0, StatusCode::BAD_REQUEST); + let (status, body) = request(&anna, "holdfeny", "Szia, olvastam a hozzászólásodat :)").await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + let id = body["id"].as_i64().unwrap(); + let (_, body) = request(&anna, "Holdfény", "Még egyszer").await; + assert_eq!(body["error"]["code"], "request_pending"); + + // Bea sees the request (and the badge); no messages before accepting. + assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1); + let list = app.get("/v1/forum/conversations", Some(&bea)).await; + assert_eq!(list["conversations"][0]["state"], "incoming"); + assert_eq!(list["conversations"][0]["intro"], "Szia, olvastam a hozzászólásodat 🙂"); + let (status, _) = + app.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó"})).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/accept"), Some(&anna), Value::Null).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "only the recipient accepts"); + let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/accept"), Some(&bea), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); + + // Messages both ways; unread counts; no read receipts. + let (status, msg) = app + .call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó <3"})) + .await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(msg["body"], "Hahó ❤️"); + assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1); + let shown = app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await; + assert_eq!(shown["conversation"]["state"], "accepted"); + assert_eq!(shown["messages"][0]["mine"], false); + app.call("POST", &format!("/v1/forum/conversations/{id}/read"), Some(&bea), json!({"message_id": msg["id"]})).await; + assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 0); + let reply = app + .call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&bea), json!({"body": "Szia!"})) + .await + .1; + // Nobody else sees the conversation. + let (status, _) = app.call("GET", &format!("/v1/forum/conversations/{id}"), Some(&cili), Value::Null).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + // A reported message is what moderators see, with the messages before it. + let moderator = app.member("mod@example.com", "Őrangyal", &["moderator"]).await; + let (status, _) = app + .call("POST", &format!("/v1/forum/messages/{}/report", reply["id"]), Some(&cili), json!({"kind": "rude"})) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "only a participant may report it"); + let (status, _) = app + .call("POST", &format!("/v1/forum/messages/{}/report", reply["id"]), Some(&anna), json!({"kind": "rude"})) + .await; + assert_eq!(status, StatusCode::CREATED); + let reports = app.get("/v1/forum/mod/reports", Some(&moderator)).await; + let context = reports["reports"][0]["target"]["messages"].as_array().unwrap().clone(); + assert_eq!(context.len(), 2); + assert_eq!(context[1]["reported"], true); + assert_eq!(context[0]["sender"]["nickname"], "Csendesvíz"); + + // A decline is silent: Cili's request just stays "sent" for her. + app.thread(&cili, "torzsasztal", "Én is itt vagyok").await; + app.season(&cili, 5, 10).await; + let (_, body) = request(&cili, "Holdfény", "Szia, beszélgetnénk?").await; + let second = body["id"].as_i64().unwrap(); + app.call("POST", &format!("/v1/forum/conversations/{second}/decline"), Some(&bea), Value::Null).await; + let list = app.get("/v1/forum/conversations", Some(&cili)).await; + assert_eq!(list["conversations"][0]["state"], "outgoing"); + assert!( + app.get("/v1/forum/conversations", Some(&bea)).await["conversations"] + .as_array() + .unwrap() + .iter() + .all(|c| c["id"] != second) + ); + let (_, body) = request(&cili, "Holdfény", "Újra én").await; + assert_eq!(body["error"]["code"], "request_pending"); + + // Blocking stops the conversation; unblocking is the blocker's. + let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _) = + app.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "?"})).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + app.get(&format!("/v1/forum/conversations/{id}"), Some(&anna)).await["conversation"]["state"], + "outgoing" + ); + assert_eq!( + app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await["conversation"]["state"], + "blocked_by_me" + ); + let (status, _) = + app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&anna), Value::Null).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _) = app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn instant_mails_and_unsubscribe(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 me = app.get("/v1/forum/me", Some(&anna)).await; + assert_eq!( + me["member"]["email"], + json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant", + "listener": "off", "weekly": false}) + ); + let (status, _) = app + .call( + "PUT", + "/v1/forum/me", + Some(&anna), + json!({ "nickname": "Csendesvíz", "email": { "replies": "instant" } }), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, _) = app + .call( + "PUT", + "/v1/forum/me", + Some(&anna), + json!({ "nickname": "Csendesvíz", "email": { "followed": "instant" } }), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await; + let offline = |who: &str| { + let pool = app.pool.clone(); + let who = who.to_string(); + async move { + sqlx::query( + "UPDATE forum.members m SET last_seen_at = now() - interval '10 minutes' \ + FROM users u WHERE u.id = m.user_id AND u.email = $1", + ) + .bind(who) + .execute(&pool) + .await + .unwrap(); + } + }; + let mails = |template: &str| { + let pool = app.pool.clone(); + let template = template.to_string(); + async move { + sqlx::query_as::<_, (String, Value)>( + "SELECT to_email, payload FROM email_outbox WHERE template = $1 ORDER BY created_at", + ) + .bind(template) + .fetch_all(&pool) + .await + .unwrap() + } + }; + + // Online: no e-mail (the badge is enough). + app.reply(&bea, thread, "Én hajnalban ülök le.", None).await; + assert!(mails("forum_reply").await.is_empty()); + // Away: one e-mail, then no more for this thread within the hour. + offline("anna@example.com").await; + let post = app.reply(&bea, thread, "Négyig be, hatig ki :)", None).await; + app.reply(&cili, thread, "Gyertyát gyújtok.", None).await; + let sent = mails("forum_reply").await; + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].0, "anna@example.com"); + assert_eq!(sent[0].1["author"], "Holdfény"); + assert_eq!(sent[0].1["nickname"], "Csendesvíz"); + assert_eq!(sent[0].1["excerpt"], "Négyig be, hatig ki 🙂"); + assert_eq!(sent[0].1["url"], format!("https://sorsfonalak.test/forum/szal/{thread}-reggeli-csend#h{}", post["id"])); + // Bea answered under her own post too, but asked only for the daily digest. + offline("bea@example.com").await; + app.reply(&cili, thread, "Szép gondolat.", post["id"].as_i64()).await; + assert!(mails("forum_reply").await.iter().all(|(to, _)| to != "bea@example.com")); + + // A request to Bea (instant messages by default), while she is away. + app.season(&anna, 5, 10).await; + offline("bea@example.com").await; + let (status, _) = app + .call( + "POST", + "/v1/forum/conversations", + Some(&anna), + json!({ "to": "Holdfény", "intro": "Szia, beszélgetnénk?" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let sent = mails("forum_message").await; + assert_eq!((sent.len(), sent[0].0.as_str()), (1, "bea@example.com")); + assert_eq!(sent[0].1["kind"], "request"); + assert_eq!(sent[0].1["excerpt"], "Szia, beszélgetnénk?"); + + // One click turns every forum e-mail off. + let token: String = sqlx::query_scalar("SELECT email_token FROM forum.members WHERE user_id = $1") + .bind(anna.id) + .fetch_one(&app.pool) + .await + .unwrap(); + assert!( + sent[0].1["unsubscribe_post_url"] + .as_str() + .unwrap() + .starts_with("https://sorsfonalak.test/api/v1/forum/unsubscribe?token=") + ); + let (status, _) = app.call("POST", "/v1/forum/unsubscribe?token=nope", None, Value::Null).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = app.call("POST", &format!("/v1/forum/unsubscribe?token={token}"), None, Value::Null).await; + assert_eq!(status, StatusCode::OK); + let me = app.get("/v1/forum/me", Some(&anna)).await; + assert_eq!( + me["member"]["email"], + json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off", + "listener": "off", "weekly": false}) + ); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn live_doorbell_over_websocket(pool: PgPool) { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + + let state = Arc::new(AppState { + db: pool.clone(), + flood_secs: 0, + base_url: "https://sorsfonalak.test".into(), + hub: crate::live::Hub::default(), + storage: None, + links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"), + }); + tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone())); + let router = routes::router(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let served = router.clone(); + tokio::spawn(async move { axum::serve(listener, served).await.unwrap() }); + let app = TestApp { router, pool }; + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await; + // Give the database listener a moment to start. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + let request = |token: &str, origin: Option<&str>| { + let mut req = format!("ws://{addr}/v1/forum/ws").into_client_request().unwrap(); + req.headers_mut().insert("authorization", format!("Bearer {token}").parse().unwrap()); + if let Some(o) = origin { + req.headers_mut().insert("origin", o.parse().unwrap()); + } + req + }; + // Another site may not open it with the visitor's credentials. + let refused = tokio_tungstenite::connect_async(request(&anna.token, Some("https://evil.example"))).await; + assert!(refused.is_err()); + let (mut ws, _) = + tokio_tungstenite::connect_async(request(&anna.token, Some("https://sorsfonalak.test"))).await.unwrap(); + + // Bea replies in Anna's thread: Anna hears of the thread and of her menu. + app.reply(&bea, thread, "Én hajnalban ülök le.", None).await; + let mut heard = Vec::new(); + while heard.len() < 2 { + let next = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut ws)).await; + match next { + Ok(Some(text)) => heard.push(text), + _ => break, + } + } + assert_eq!(heard, vec![format!(r#"{{"id":{thread},"t":"thread"}}"#), r#"{"t":"nav"}"#.to_string()]); + + // Anna types in the thread: Bea, there too, sees it; Anna does not hear of herself. + use futures_util::SinkExt; + let (mut bea_ws, _) = + tokio_tungstenite::connect_async(request(&bea.token, Some("https://sorsfonalak.test"))).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let typing = format!(r#"{{"typing":"thread","id":{thread}}}"#); + ws.send(tokio_tungstenite::tungstenite::Message::Text(typing.into())).await.unwrap(); + let seen = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut bea_ws)).await.unwrap(); + assert_eq!(seen, Some(format!(r#"{{"id":{thread},"kind":"thread","t":"typing","who":"Csendesvíz"}}"#))); + let echo = tokio::time::timeout(std::time::Duration::from_millis(500), futures_next(&mut ws)).await; + assert!(echo.is_err(), "no echo of one's own typing"); +} + +/// The next text message of a test WebSocket. +async fn futures_next( + ws: &mut tokio_tungstenite::WebSocketStream>, +) -> Option { + use futures_util::StreamExt; + use tokio_tungstenite::tungstenite::Message; + loop { + match ws.next().await? { + Ok(Message::Text(t)) => return Some(t.to_string()), + Ok(_) => continue, + Err(_) => return None, + } + } +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn restricted_topics_by_approval(pool: PgPool) { + let app = TestApp::new(pool); + let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await; + let moderator = app.member("mod@example.com", "Őrangyal", &["moderator"]).await; + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + + // Only the admin opens topics. + let body = + json!({ "name": "Gyászolók köre", "description": "Akik elveszítettek valakit", "visibility": "restricted" }); + assert_eq!(app.call("POST", "/v1/forum/topics", Some(&moderator), body.clone()).await.0, StatusCode::FORBIDDEN); + let (status, created) = app.call("POST", "/v1/forum/topics", Some(&admin), body).await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + assert_eq!(created["slug"], "gyaszolok-kore"); + + // Members see it by name and may ask to join; visitors do not see it. + let home = app.get("/v1/forum/home", Some(&anna)).await; + let topic = home["topics"].as_array().unwrap().iter().find(|t| t["slug"] == "gyaszolok-kore").unwrap().clone(); + assert_eq!((topic["readable"].as_bool(), topic["membership"].as_str()), (Some(false), Some("none"))); + assert!( + app.get("/v1/forum/home", None).await["topics"] + .as_array() + .unwrap() + .iter() + .all(|t| t["slug"] != "gyaszolok-kore") + ); + let (status, _) = app.call("GET", "/v1/forum/topics/gyaszolok-kore", Some(&anna), Value::Null).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = app + .call( + "POST", + "/v1/forum/threads", + Some(&anna), + json!({ "topic": "gyaszolok-kore", "title": "Apukám", "body": "x" }), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _) = app + .call( + "POST", + "/v1/forum/topics/gyaszolok-kore/join", + Some(&anna), + json!({ "note": "Tavaly vesztettem el anyukámat." }), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 1, "the request shows for moderators"); + + // A moderator approves: now Anna reads and writes there, Bea still not. + let requests = app.get("/v1/forum/mod/topic-requests", Some(&moderator)).await; + assert_eq!(requests["requests"][0]["member"]["nickname"], "Csendesvíz"); + assert_eq!(requests["requests"][0]["note"], "Tavaly vesztettem el anyukámat."); + let (status, _) = app + .call( + "POST", + "/v1/forum/mod/topic-requests", + Some(&moderator), + json!({ "topic": "gyaszolok-kore", "nickname": "Csendesvíz", "action": "approve" }), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let thread = app.thread(&anna, "gyaszolok-kore", "Apukám emléke").await; + app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await; + let (status, _) = app.call("GET", &format!("/v1/forum/threads/{thread}"), Some(&bea), Value::Null).await; + assert_eq!(status, StatusCode::NOT_FOUND); + app.get(&format!("/v1/forum/threads/{thread}"), Some(&moderator)).await; + assert_eq!(app.get("/v1/forum/mod/log", Some(&moderator)).await["entries"][0]["action"], "approve_member"); + + // The admin renames it; the address stays. + let (status, _) = app + .call("PATCH", "/v1/forum/topics/gyaszolok-kore", Some(&admin), json!({ "name": "Gyász és emlékezés" })) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/topics/gyaszolok-kore", Some(&anna)).await["topic"]["name"], "Gyász és emlékezés"); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn mentions_listeners_supporters_and_who_is_here(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", "Hold fény", &["user"]).await; + let cili = app.member("cili@example.com", "Zöldág", &["user"]).await; + + // "@Hold fény" (with its space) names Bea: she follows the thread, it is new for her. + let thread = app.thread(&anna, "torzsasztal", "Téli levesek").await; + let post = app.reply(&cili, thread, "Szerinted, @Hold fény, mi a legjobb? És @Senki?", None).await; + assert_eq!(post["mentions"], json!(["Hold fény"])); + let followed = app.get("/v1/forum/followed", Some(&bea)).await; + assert_eq!(followed["threads"][0]["id"], thread); + let found = app.get("/v1/forum/members/search?q=hold", Some(&anna)).await; + assert_eq!(found["members"][0]["nickname"], "Hold fény"); + + // Listening volunteers: from the Kereső rank; they see what waits for a reply. + let (status, _) = + app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Hold fény", "listener": true })).await; + assert_eq!(status, StatusCode::FORBIDDEN); + app.season(&bea, 5, 10).await; + let (status, _) = + app.call("PUT", "/v1/forum/me", Some(&bea), json!({ "nickname": "Hold fény", "listener": true })).await; + assert_eq!(status, StatusCode::OK); + let waiting = app.thread(&anna, "ami-a-szivemen-van", "Nehéz napok").await; + sqlx::query("UPDATE forum.threads SET created_at = now() - interval '2 hours' WHERE id = $1") + .bind(waiting) + .execute(&app.pool) + .await + .unwrap(); + assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["waiting"], 1); + assert!(app.get("/v1/forum/home", Some(&cili)).await["waiting"].is_null()); + let shown = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await; + assert!(shown["posts"].as_array().unwrap().iter().all(|p| p["author"]["supporter"] == false)); + + // The supporter badge: buyers only, and only when they switch it on. + let (status, _) = + app.call("PUT", "/v1/forum/me", Some(&cili), json!({ "nickname": "Zöldág", "supporter_badge": true })).await; + assert_eq!(status, StatusCode::FORBIDDEN); + sqlx::query("INSERT INTO package_orders (id, user_id, package, source, price_huf) VALUES ($1, $2, 'egyeni', 'stripe', 4900)") + .bind(Uuid::now_v7()) + .bind(cili.id) + .execute(&app.pool) + .await + .unwrap(); + assert_eq!(app.get("/v1/forum/me", Some(&cili)).await["can_supporter"], true); + let (status, _) = + app.call("PUT", "/v1/forum/me", Some(&cili), json!({ "nickname": "Zöldág", "supporter_badge": true })).await; + assert_eq!(status, StatusCode::OK); + let profile = app.get("/v1/forum/members/Zöldág", None).await; + assert_eq!( + (profile["member"]["author"]["supporter"].as_bool(), profile["member"]["author"]["listener"].as_bool()), + (Some(true), Some(false)) + ); + assert_eq!(app.get("/v1/forum/members/hold%20f%C3%A9ny", None).await["member"]["author"]["listener"], true); + + // Who is here: the members seen in the last minutes, not the invisible. + app.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "invisible": true })).await; + let here: Vec = app.get("/v1/forum/home", None).await["online"] + .as_array() + .unwrap() + .iter() + .map(|m| m["nickname"].as_str().unwrap().to_string()) + .collect(); + assert!(here.contains(&"Zöldág".to_string()) && !here.contains(&"Csendesvíz".to_string())); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn answers_to_the_member(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 answers = |v: Value| -> Vec<(i64, String, bool)> { + v["replies"] + .as_array() + .unwrap() + .iter() + .map(|r| (r["id"].as_i64().unwrap(), r["kind"].as_str().unwrap().to_string(), r["unread"] == true)) + .collect() + }; + + // Anna's thread: Bea replies to it, Anna answers, Cili answers Anna's answer + // (on the second level, under Bea's post) and names Bea elsewhere. + let thread = app.thread(&anna, "torzsasztal", "Téli levesek").await; + let first = app.reply(&bea, thread, "Gulyás.", None).await["id"].as_i64().unwrap(); + let second = app.reply(&anna, thread, "Az jó ötlet.", Some(first)).await["id"].as_i64().unwrap(); + let third = app.reply(&cili, thread, "Szerintem is.", Some(second)).await["id"].as_i64().unwrap(); + let fourth = app.reply(&cili, thread, "@Holdfény, babbal?", None).await["id"].as_i64().unwrap(); + + // Anna: Bea's reply in her thread (read once she answered it), Cili's answer + // to her, and Cili's first-level post in her thread. + assert_eq!( + answers(app.get("/v1/forum/replies", Some(&anna)).await), + vec![(fourth, "thread".into(), true), (third, "reply".into(), true), (first, "thread".into(), false)] + ); + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 2); + // Bea: Anna answered her; Cili named her. Cili's answer was to Anna, not to her. + assert_eq!( + answers(app.get("/v1/forum/replies", Some(&bea)).await), + vec![(fourth, "mention".into(), true), (second, "reply".into(), true)] + ); + // Nothing for Cili; a visitor gets nothing. + assert_eq!(app.get("/v1/forum/nav", Some(&cili)).await["replies"], 0); + assert!(app.get("/v1/forum/nav", None).await["replies"].is_null()); + + // Reading the thread clears them; so does "Mind olvasott". + let (status, _) = + app.call("POST", &format!("/v1/forum/threads/{thread}/read"), Some(&anna), json!({ "post_id": fourth })).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 0); + let (status, _) = app.call("POST", "/v1/forum/replies/read", Some(&bea), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["replies"], 0); + assert_eq!(answers(app.get("/v1/forum/replies", Some(&bea)).await).len(), 2, "the list stays"); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn search_mutes_and_archived_topics(pool: PgPool) { + let app = TestApp::new(pool); + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + let admin = app.member("admin@example.com", "Gazda", &["user", "admin"]).await; + let found = |v: Value| -> Vec { + let mut ids: Vec = + v["results"].as_array().unwrap().iter().map(|r| r["thread"]["id"].as_i64().unwrap()).collect(); + ids.sort(); + ids + }; + + // Search: word beginnings without accents, titles, and only what one may read. + let sleep = app.thread(&anna, "torzsasztal", "Nehezen alszom").await; + app.reply(&bea, sleep, "Nekem az esti séták segítettek az alvásban.", None).await; + let hidden = app.thread(&anna, "ami-a-szivemen-van", "Alvászavar titokban").await; + assert_eq!(found(app.get("/v1/forum/search?q=alvas", None).await), vec![sleep], "a visitor: public topics"); + assert_eq!(found(app.get("/v1/forum/search?q=alv%C3%A1s", Some(&anna)).await), vec![sleep, hidden]); + let hit = app.get("/v1/forum/search?q=s%C3%A9t%C3%A1k", None).await; + assert!(hit["results"][0]["snippet"].as_str().unwrap().contains("⟦séták⟧"), "{hit}"); + assert!(found(app.get("/v1/forum/search?q=a", None).await).is_empty(), "too short"); + let map = app.get("/v1/forum/sitemap", None).await; + let mapped: Vec = map["threads"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect(); + assert_eq!(mapped, vec![sleep], "public threads only"); + + // Muting Bea: her threads leave Anna's lists, her posts fold up, her + // answers stop counting, and search leaves her out. She is not told. + let soups = app.thread(&bea, "torzsasztal", "Téli levesek").await; + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 1); + let (status, _) = app.call("PUT", "/v1/forum/members/Holdf%C3%A9ny/mute", Some(&anna), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let listed = app.get("/v1/forum/topics/torzsasztal", Some(&anna)).await; + assert!(listed["threads"].as_array().unwrap().iter().all(|t| t["id"] != soups)); + let thread = app.get(&format!("/v1/forum/threads/{sleep}"), Some(&anna)).await; + assert_eq!(thread["posts"][1]["muted"], true); + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 0); + assert!(found(app.get("/v1/forum/search?q=s%C3%A9t%C3%A1k", Some(&anna)).await).is_empty()); + assert_eq!(app.get("/v1/forum/me/mutes", Some(&anna)).await["muted"][0]["nickname"], "Holdfény"); + assert_eq!(app.get("/v1/forum/members/Holdf%C3%A9ny", Some(&anna)).await["member"]["muted"], true); + assert_eq!(app.get(&format!("/v1/forum/threads/{sleep}"), Some(&bea)).await["posts"][0]["muted"], false); + let (status, _) = app.call("PUT", "/v1/forum/members/Csendesv%C3%ADz/mute", Some(&anna), Value::Null).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "not oneself"); + let (status, _) = app.call("DELETE", "/v1/forum/members/Holdf%C3%A9ny/mute", Some(&anna), Value::Null).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 1); + + // Archiving the topic: readable, but nothing new; brought back, it works again. + let (status, _) = + app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": true })).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let topic = app.get("/v1/forum/topics/torzsasztal", Some(&anna)).await; + assert_eq!(topic["topic"]["archived"], true); + let thread = app.get(&format!("/v1/forum/threads/{sleep}"), Some(&anna)).await; + assert_eq!(thread["access"]["can_reply"], false); + assert_eq!(thread["thread"]["topic"]["archived"], true); + let (status, _) = app + .call("POST", &format!("/v1/forum/threads/{sleep}/posts"), Some(&bea), json!({ "body": "Még egy szó." })) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = app + .call( + "POST", + "/v1/forum/threads", + Some(&anna), + json!({ "topic": "torzsasztal", "title": "Új", "body": "Szia" }), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let home = app.get("/v1/forum/home", Some(&anna)).await; + let archived = home["topics"].as_array().unwrap().iter().find(|t| t["slug"] == "torzsasztal").unwrap(); + assert_eq!(archived["archived"], true); + let (status, _) = + app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&anna), json!({ "archived": false })).await; + assert_eq!(status, StatusCode::FORBIDDEN, "admins only"); + app.call("PATCH", "/v1/forum/topics/torzsasztal", Some(&admin), json!({ "archived": false })).await; + app.reply(&bea, sleep, "Még egy szó.", None).await; +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn a_question_about_ones_chart(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; + // Anna's chart (made-up data) and a share of it made for the forum; Bea's own share. + let chart = Uuid::now_v7(); + let result = json!({ + "time": {"time_known": true}, + "points": [ + {"id": "sun", "sign": "leo", "degree_in_sign": 12.7, "house": 10}, + {"id": "moon", "sign": "pisces", "degree_in_sign": 3.2, "house": 5} + ], + "angles": {"ascendant": {"sign": "scorpio", "degree_in_sign": 21.9}} + }); + sqlx::query( + "INSERT INTO charts (id, owner_id, label, birth_data, result, chart_hash, kind) \ + VALUES ($1, $2, 'Kovács Anna', '{}', $3, 'h', 'own')", + ) + .bind(chart) + .bind(anna.id) + .bind(&result) + .execute(&app.pool) + .await + .unwrap(); + for (slug, owner, for_forum) in [("annaforum000001", anna.id, true), ("annaplain000001", anna.id, false)] { + sqlx::query( + "INSERT INTO shares (id, owner_id, slug, kind, chart_id, for_forum) VALUES ($1, $2, $3, 'chart', $4, $5)", + ) + .bind(Uuid::now_v7()) + .bind(owner) + .bind(slug) + .bind(chart) + .bind(for_forum) + .execute(&app.pool) + .await + .unwrap(); + } + + // Only one's own forum share can go with a question. + let preview = app.get("/v1/forum/share-card/annaforum000001", Some(&anna)).await; + assert_eq!(preview["title"], "Születési képlet"); + assert_eq!(preview["points"][0], json!({"id": "sun", "sign": "leo", "degree": 12, "house": 10})); + assert_eq!(preview["points"][2]["id"], "ascendant"); + assert_eq!(preview["chart"]["points"][1]["sign"], "pisces", "the wheel's data"); + assert!(preview["chart"].get("time").is_none(), "no birth time"); + assert!(!preview.to_string().contains("Kovács"), "no names"); + for (slug, who) in [("annaplain000001", &anna), ("annaforum000001", &bea), ("nincsilyen", &anna)] { + let (status, _) = app.call("GET", &format!("/v1/forum/share-card/{slug}"), Some(who), Value::Null).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{slug}"); + } + let (status, _) = app + .call( + "POST", + "/v1/forum/threads", + Some(&bea), + json!({ "topic": "egbolt-es-kepletek", "title": "Az övé", "body": "Kérdés", "share": "annaforum000001" }), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, created) = app + .call( + "POST", + "/v1/forum/threads", + Some(&anna), + json!({ + "topic": "egbolt-es-kepletek", + "title": "Mit jelent a Hold az ötödik házban?", + "body": "Sokat gondolkodom rajta.", + "share": "annaforum000001" + }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + let id = created["id"].as_i64().unwrap(); + + // Members see the card; a visitor only that there is one. + let shown = app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await; + assert_eq!(shown["posts"][0]["share"]["slug"], "annaforum000001"); + assert_eq!(shown["posts"][0]["share"]["points"][1]["sign"], "pisces"); + let public = app.get(&format!("/v1/forum/threads/{id}"), None).await; + assert_eq!(public["posts"][0]["share"], json!({ "kind": "chart", "locked": true })); + assert!(!public.to_string().contains("annaforum000001")); + + // Revoked on the main site: the card says so. + sqlx::query("UPDATE shares SET revoked_at = now() WHERE slug = 'annaforum000001'") + .execute(&app.pool) + .await + .unwrap(); + let shown = app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await; + assert_eq!(shown["posts"][0]["share"]["revoked"], true); + assert!(shown["posts"][0]["share"].get("points").is_none()); + + // The author takes it off (only she may): the card goes, the link stops working. + sqlx::query("UPDATE shares SET revoked_at = NULL WHERE slug = 'annaforum000001'").execute(&app.pool).await.unwrap(); + let opening = shown["posts"][0]["id"].as_i64().unwrap(); + let uri = format!("/v1/forum/posts/{opening}/share"); + assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN); + assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT); + assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null()); + let revoked: bool = sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'") + .fetch_one(&app.pool) + .await + .unwrap(); + assert!(revoked); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn the_first_fifteen_are_founders(pool: PgPool) { + let app = TestApp::new(pool); + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await; + // Thirteen more founders already (made up): fifteen in all, then Bea comes too late. + sqlx::query( + "WITH u AS (INSERT INTO users (id, email, display_name) \ + SELECT gen_random_uuid(), 'f' || n || '@example.invalid', 'F' FROM generate_series(1, 13) n \ + RETURNING id, email) \ + INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, founder) \ + SELECT id, 'Alapito' || split_part(email, '@', 1), \ + translate('alapito' || split_part(email, '@', 1), 'i10', 'llo'), 'hold-ejkek', true FROM u", + ) + .execute(&app.pool) + .await + .unwrap(); + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + let thread = app.thread(&anna, "torzsasztal", "Sziasztok").await; + app.reply(&bea, thread, "Szia!", None).await; + let shown = app.get(&format!("/v1/forum/threads/{thread}"), None).await; + assert_eq!(shown["posts"][0]["author"]["founder"], true); + assert_eq!(shown["posts"][1]["author"]["founder"], false); + + // The admin takes it from a test account: the next newcomer gets the place. + let uri = "/v1/forum/members/Alapitof1/founder"; + let (status, _) = app.call("PUT", uri, Some(&anna), json!({ "founder": false })).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = app.call("PUT", uri, Some(&admin), json!({ "founder": false })).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let cili = app.member("cili@example.com", "Zöldág", &["user"]).await; + app.reply(&cili, thread, "Sziasztok!", None).await; + let shown = app.get(&format!("/v1/forum/threads/{thread}"), None).await; + assert_eq!(shown["posts"][2]["author"]["founder"], true); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn youtube_links_get_a_preview(pool: PgPool) { + // A fake YouTube: the oEmbed answer for one video, 404 for the rest. + let fake = Router::new().route( + "/oembed", + axum::routing::get(|q: axum::extract::Query>| async move { + if q.get("url").is_some_and(|u| u.ends_with("v=dQw4w9WgXcQ")) { + Ok(axum::Json(json!({ "title": "Telihold meditáció", "author_name": "Csendes Csatorna" }))) + } else { + Err(StatusCode::NOT_FOUND) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, fake).await.unwrap() }); + let app = TestApp::with_links( + pool, + crate::links::LinkConfig::new(&format!("http://{addr}/oembed"), &format!("http://{addr}")), + ); + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let thread = app.thread(&anna, "belso-utak", "Esti meditáció").await; + let post = app + .reply( + &anna, + thread, + "Ezt hallgatom esténként: https://youtu.be/dQw4w9WgXcQ?t=95 – és ez nincs: https://youtu.be/aaaaaaaaaaa", + None, + ) + .await; + assert_eq!(post["links"].as_array().unwrap().len(), 1, "{post}"); + let link = &post["links"][0]; + assert_eq!(link["provider"], "youtube"); + assert_eq!(link["id"], "dQw4w9WgXcQ"); + assert_eq!(link["start"], 95); + assert_eq!(link["title"], "Telihold meditáció"); + assert_eq!(link["author"], "Csendes Csatorna"); + assert!(link["thumbnail"].is_null(), "no storage in the tests"); + // Shown again with the thread, from the stored preview; a deleted post shows none. + let shown = app.get(&format!("/v1/forum/threads/{thread}"), None).await; + assert_eq!(shown["posts"][1]["links"][0]["title"], "Telihold meditáció"); + assert!(shown["posts"][0]["links"].is_null()); +} diff --git a/services/forum/src/text.rs b/services/forum/src/text.rs new file mode 100644 index 0000000..7f3959c --- /dev/null +++ b/services/forum/src/text.rs @@ -0,0 +1,279 @@ +//! Rules for what members type: nicknames, titles, posts, the bio, avatars. + +use crate::error::ApiError; + +pub const NICKNAME_MIN: usize = 3; +pub const NICKNAME_MAX: usize = 24; +pub const TITLE_MIN: usize = 4; +pub const TITLE_MAX: usize = 120; +pub const BODY_MAX: usize = 10_000; +pub const BIO_MAX: usize = 500; +pub const REASON_MIN: usize = 3; +pub const REASON_MAX: usize = 300; + +/// The starter avatars: a glyph on a background colour, `-`. +/// The frontend draws them (`src/components/forum/Avatar.tsx`). +pub const AVATAR_GLYPHS: [&str; 8] = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"]; +pub const AVATAR_COLOURS: [&str; 6] = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"]; + +/// Words a nickname may not contain (compared folded, see [`nickname_key`]). +const RESERVED: [&str; 7] = ["admin", "moderator", "sorsfonalak", "rendszer", "ugyfelszolgalat", "torolttag", "forum"]; + +const SEPARATORS: [char; 4] = [' ', '-', '_', '.']; + +/// A nickname as it will be shown: trimmed, inner spaces collapsed, checked. +/// Letters (accented ones too), digits, and single spaces, `-`, `_` or `.` +/// between them; it starts with a letter. +pub fn nickname(raw: &str) -> Result { + let name = raw.split_whitespace().collect::>().join(" "); + let len = name.chars().count(); + if !(NICKNAME_MIN..=NICKNAME_MAX).contains(&len) { + return Err(ApiError::bad(format!("Az álnév {NICKNAME_MIN}–{NICKNAME_MAX} karakter legyen."))); + } + if !name.chars().next().is_some_and(latin_letter) { + return Err(ApiError::bad("Az álnév betűvel kezdődjön.")); + } + let mut previous_separator = false; + for c in name.chars() { + let separator = SEPARATORS.contains(&c); + if !(separator || latin_letter(c) || c.is_ascii_digit()) { + return Err(ApiError::bad("Az álnévben betűk, számok, szóköz, kötőjel, aláhúzás és pont lehet.")); + } + if separator && previous_separator { + return Err(ApiError::bad("Az álnévben ne legyen két elválasztó jel egymás után.")); + } + previous_separator = separator; + } + if previous_separator { + return Err(ApiError::bad("Az álnév ne végződjön elválasztó jellel.")); + } + let key = nickname_key(&name); + if RESERVED.iter().any(|word| key.contains(&nickname_key(word))) { + return Err(ApiError::bad("Ezt az álnevet nem választhatod.")); + } + Ok(name) +} + +/// A letter of the Latin script (accented ones included), so look-alike +/// letters of other scripts cannot imitate a nickname. +fn latin_letter(c: char) -> bool { + c.is_alphabetic() + && matches!(c as u32, + 0x41..=0x5A | 0x61..=0x7A // ASCII + | 0xC0..=0x24F // Latin-1 Supplement, Latin Extended-A and -B + | 0x1E00..=0x1EFF) // Latin Extended Additional +} + +/// The nickname folded for uniqueness: no accents, case or separators, and +/// characters that look alike made the same (`I`, `l`, `1` → `l`; `0` → `o`), +/// so "Holdfény", "holdfeny" and "Ho1d-feny" are one name. +pub fn nickname_key(name: &str) -> String { + deunicode::deunicode(name) + .to_lowercase() + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .map(|c| match c { + 'i' | '1' => 'l', + '0' => 'o', + other => other, + }) + .collect() +} + +/// A thread title: one line, spaces collapsed. +pub fn title(raw: &str) -> Result { + let title: String = raw.split_whitespace().collect::>().join(" "); + let len = title.chars().count(); + if len < TITLE_MIN { + return Err(ApiError::bad(format!("A cím legalább {TITLE_MIN} karakter legyen."))); + } + if len > TITLE_MAX { + return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet."))); + } + Ok(smileys(&title)) +} + +/// A post: control characters removed, at most one empty line in a row, +/// trailing spaces dropped, the old smileys turned into emoji. +pub fn body(raw: &str) -> Result { + let text = clean_multiline(raw, 2); + if text.is_empty() { + return Err(ApiError::bad("A hozzászólás nem lehet üres.")); + } + if text.chars().count() > BODY_MAX { + return Err(ApiError::bad(format!("A hozzászólás legfeljebb {BODY_MAX} karakter lehet."))); + } + Ok(smileys(&text)) +} + +/// The profile's short introduction: no links (old-school profile spam). +pub fn bio(raw: &str) -> Result { + let text = clean_multiline(raw, 1); + if text.chars().count() > BIO_MAX { + return Err(ApiError::bad(format!("A bemutatkozás legfeljebb {BIO_MAX} karakter lehet."))); + } + let lower = text.to_lowercase(); + if lower.contains("http") || lower.contains("www.") { + return Err(ApiError::bad("A bemutatkozásba nem tehetsz linket.")); + } + Ok(smileys(&text)) +} + +/// A moderator's reason, shown in place of what was removed. +pub fn reason(raw: &str) -> Result { + let text: String = raw.split_whitespace().collect::>().join(" "); + let len = text.chars().count(); + if !(REASON_MIN..=REASON_MAX).contains(&len) { + return Err(ApiError::bad(format!("Az indoklás {REASON_MIN}–{REASON_MAX} karakter legyen."))); + } + Ok(text) +} + +pub fn avatar(raw: &str) -> Result { + let valid = raw + .split_once('-') + .is_some_and(|(glyph, colour)| AVATAR_GLYPHS.contains(&glyph) && AVATAR_COLOURS.contains(&colour)); + if valid { Ok(raw.to_string()) } else { Err(ApiError::bad("Ismeretlen avatar.")) } +} + +/// A default avatar for a new member, picked from the nickname. +pub fn default_avatar(key: &str) -> String { + let n: usize = key.bytes().map(usize::from).sum(); + format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()]) +} + +/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`. +pub fn slug(title: &str) -> String { + let ascii = deunicode::deunicode(title).to_lowercase(); + let mut slug = String::new(); + for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) { + if !slug.is_empty() && slug.len() + 1 + word.len() > 60 { + break; + } + if !slug.is_empty() { + slug.push('-'); + } + slug.push_str(word); + } + slug +} + +/// Lines with control characters removed and trailing spaces dropped; at most +/// `max_breaks` line breaks in a row; trimmed. +fn clean_multiline(raw: &str, max_breaks: usize) -> String { + let normalized = raw.replace("\r\n", "\n").replace('\r', "\n"); + let mut out = String::with_capacity(normalized.len()); + let mut breaks = 0; + for line in normalized.split('\n') { + let line: String = line.chars().map(|c| if c == '\t' { ' ' } else { c }).filter(|c| !c.is_control()).collect(); + let line = line.trim_end(); + if line.trim().is_empty() { + breaks += 1; + continue; + } + if !out.is_empty() { + out.push_str(&"\n".repeat(breaks.clamp(1, max_breaks))); + } + breaks = 1; + out.push_str(line); + } + out.trim().to_string() +} + +/// The old forums' character smileys and their emoji. A smiley becomes the +/// emoji only standing alone (between spaces), so links and the like stay as +/// typed. The frontend converts the same list while typing +/// (`src/lib/emoticons.ts`); this catches what it did not. +pub const EMOTICONS: [(&str, &str); 27] = [ + (":)", "🙂"), + (":-)", "🙂"), + ("(:", "🙂"), + (":D", "😄"), + (":-D", "😄"), + ("xD", "😆"), + ("XD", "😆"), + (";)", "😉"), + (";-)", "😉"), + (":(", "🙁"), + (":-(", "🙁"), + (":'(", "😢"), + (":P", "😛"), + (":-P", "😛"), + (":p", "😛"), + (":O", "😮"), + (":o", "😮"), + (":-O", "😮"), + (":*", "😘"), + (":-*", "😘"), + (":/", "😕"), + (":|", "😐"), + ("B)", "😎"), + ("^^", "😊"), + ("^_^", "😊"), + ("<3", "❤️"), + (" String { + let mut out = String::with_capacity(text.len()); + let mut word = String::new(); + let flush = |word: &mut String, out: &mut String| { + let emoji = EMOTICONS.iter().find(|(code, _)| code == word).map(|(_, e)| *e); + 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("Hiányzol :'( xD ^^").unwrap(), "Hiányzol 😢 😆 😊"); + assert_eq!(body("http://x.hu/:)").unwrap(), "http://x.hu/:)", "only smileys standing alone"); + assert!(body(" \n\t ").is_err()); + assert_eq!(body("a\u{0007}b").unwrap(), "ab"); + assert!(bio("Látogass meg: www.pelda.hu").is_err()); + assert_eq!(bio("Első sor\n\n\nMásodik").unwrap(), "Első sor\nMásodik"); + } + + #[test] + fn titles_slugs_avatars() { + assert_eq!(title(" Nem tudom elengedni ").unwrap(), "Nem tudom elengedni"); + assert!(title("abc").is_err()); + assert_eq!(slug("Nem tudom elengedni anyukám házát!"), "nem-tudom-elengedni-anyukam-hazat"); + assert!(slug(&"hosszú ".repeat(30)).len() <= 60); + assert!(avatar("hold-ejkek").is_ok()); + assert!(avatar("hold-piros").is_err()); + assert!(avatar(&default_avatar("csendesvlz")).is_ok()); + } +} diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx index 5a541a4..c50e133 100644 --- a/services/frontend/src/app/Landing.tsx +++ b/services/frontend/src/app/Landing.tsx @@ -5,6 +5,7 @@ import { Rich } from "@/components/Rich"; import { TarotCard, TarotCardBack } from "@/components/tarot/TarotCard"; import { PublicHeader } from "@/components/SiteHeader"; import { ChristmasTree } from "@/components/ChristmasTree"; +import { forumEnabled } from "@/lib/forumServer"; import { isChristmasTime } from "@/lib/season"; import example from "@/content/pelda.json"; import { tarotCard } from "@/lib/tarot"; @@ -134,6 +135,20 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
+ {forumEnabled() && ( + + Közösség + Fórum + + Tartalmas beszélgetések, ahol álnéven, a valódi neved nélkül oszthatod meg, ami foglalkoztat vagy a + szívedet nyomja. Spiritualitás, álmok, az égbolt, és bármi, amiről jólesik beszélni. + + + Pörgő videók helyett csendes, figyelmes beszélgetés: itt az elmélyülés a lényeg. + + Benézek → + + )} Születési horoszkóp diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 7e7dfb0..8d008ab 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -147,6 +147,61 @@ export default async function PrivacyPage() { Hibák kijavítása, kérdések megválaszolása Jogos érdek (6. cikk (1) f) + + + Fórumprofilod: az álneved (a korábbiakat 90 napig, hogy más ne vehesse fel), az avatarod vagy a + feltöltött saját képed (kicsinyítve, a kép rejtett adatai, például a helyszín nélkül), a + bemutatkozásod, a képletedből megosztott jegyek, hogy önkéntes kísérő vagy-e, a Támogató + jelvény (ha bekapcsolod, mások látják, hogy vásároltál), hogy az első tizenöt tag közé tartozol-e + (Alapító tag), a láthatatlan mód és az e-mail-értesítések beállítása + + Részvétel a fórumon; a jegyek megosztása és a jelvények a saját döntésed + Szerződés teljesítése + + + + A fórumon írt szálaid és hozzászólásaid, a reakcióid és „Ez segített” jelöléseid, a pontjaid és a + rangod; kiket említettél (@álnév); hogy mit olvastál el, mely szálakat követed, és kiket + némítottál el + + A fórum működése, a rangok, az újdonságok jelzése + Szerződés teljesítése + + + + A fórumkérdéseidhez csatolt képlet, éves előrejelzés vagy összevetés megosztó linkje + + Hogy a tagok lássák, amiről kérdezel; a csatolás a saját döntésed + Szerződés teljesítése + + + Zárt témákba küldött jelentkezéseid (a pár szavas indoklással) és a tagságaid + A zárt témák: a moderátorok döntenek a felvételről + Szerződés teljesítése + + + Mikor jártál utoljára a fórumon + Az online jelzés (zöld pötty); a láthatatlan móddal kikapcsolhatod + Szerződés teljesítése + + + + Privát beszélgetéseid: a kérések bemutatkozása, az elfogadás, elutasítás vagy tiltás, és az + üzenetek + + Privát beszélgetés más tagokkal + Szerződés teljesítése + + + + Jelentések (ki, mit, milyen okból jelentett), a moderálási napló (ki, mikor, mit és miért döntött), az + eltiltások ideje és oka + + A házirend betartatása, a bejelentések kezelése, a döntések visszakereshetősége + + Jogi kötelezettség ((EU) 2022/2065 rendelet, DSA; 6. cikk (1) c); jogos érdek (6. cikk (1) f) + + IP-cím, böngésző adatai, a kérések ideje (szervernaplók) Biztonság, hibakeresés, visszaélések kiszűrése @@ -170,6 +225,25 @@ export default async function PrivacyPage() { képlet rajzát és a legfrissebb rövid összefoglalót. Nevet és születési adatot nem tesz közzé, a keresők nem listázzák, és a linket bármikor visszavonhatod.

+

+ Fórum: amit a nyilvános témákban írsz, bárki láthatja, a keresők is; a csak tagoknak szóló + témákat csak belépett felhasználók látják, a zárt témákat csak a jóváhagyott tagjaik. A hozzászólásaid + mellett az álneved, az avatarod, a rangod, az általad megosztott jegyek és a bekapcsolt jelvényeid + (Kísérő, Támogató) látszanak; a valódi neved, az e-mail-címed és a születési adataid nem, és a + képletedből soha nem mutatunk fokokat. A privát üzeneteidet csak a beszélgetés két résztvevője látja; a + moderátorok csak akkor, ha valaki egy üzenetet jelent, és akkor is csak a jelentett üzenetet és az előtte + lévő néhányat. A moderátorok (az üzemeltető által kijelölt tagok) a valódi nevedet és az e-mail-címedet nem + látják. Ha egy kérdésedhez csatolod a képletedet, az éves előrejelzésedet vagy egy összevetést, azt csak a + belépett tagok látják: a rajzot fokokkal és házakkal, a rövid összefoglalót vagy az előrejelzés szövegét, + nevek, születési dátum, idő és hely nélkül. A fokokból egy jártas asztrológus nagyjából kiszámolhatja a + születési napot és időt, az előrejelzés kezdőnapjából pedig a születésnap kiderül. A csatolt képletet + bármikor leveheted, és a kérdés törlésével a link is megszűnik. Ha egy hozzászólásban YouTube-link van, a + videó címét és képét a szerverünk kéri le, és a saját szerverünkről mutatjuk: a fórum olvasásakor a YouTube + nem kap rólad adatot. Ha a videót a fórumon elindítod, a lejátszó a YouTube (Google) szerveréről töltődik be + (youtube-nocookie.com), amely látja az IP-címedet és a lejátszás adatait; telefonon a megnyitás a YouTube + alkalmazásába visz. A fórum szabályai az{" "} + ÁSZF 8. pontjában vannak. +

@@ -186,7 +260,8 @@ export default async function PrivacyPage() {

Mire használjuk: a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az - e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed vagy elfogadták a meghívódat); a + e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy + válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted); a nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.

@@ -234,6 +309,10 @@ export default async function PrivacyPage() { kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.

+

+ A fórumon írt hozzászólásokat és a privát üzeneteket nem küldjük el mesterséges intelligenciának. Ha ezt + később bevezetnénk (például a kéretlen hirdetések kiszűrésére), előtte itt jelezzük. +

@@ -254,7 +333,9 @@ export default async function PrivacyPage() {
  • Cloudflare, Inc. – a forgalom továbbítása és a támadások elleni védelem; az oldal - letöltésekor kezeli az IP-címedet és a kérés adatait. + letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a + Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is + vizsgálja).
  • Google LLC – bejelentkezés Google-fiókkal. @@ -299,14 +380,30 @@ export default async function PrivacyPage() { törlése után név és megjegyzés nélkül, statisztikaként megtartjuk.
  • A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.
  • +
  • + A fórumprofilodat (a saját képeddel együtt), a privát beszélgetéseidet, a reakcióidat, a követéseidet és + a zárt témák tagságát a fiókod törléséig; az elutasított jelentkezést azonnal töröljük. A fiók + törlésekor a privát beszélgetéseid a másik fél számára is törlődnek. A szálaid és a hozzászólásaid „Törölt + tag” néven megmaradnak, hogy a beszélgetések érthetők maradjanak; ha a törlésüket is kéred, írj a fenti + e-mail-címre. +
  • +
  • + A moderátor által eltávolított hozzászólás szövegét az esetleges kifogás miatt 1 évig őrizzük, utána csak a + helye és az indoklás marad. A lezárt jelentéseket és a lejárt eltiltások okát 1 évig, a moderálási naplót + 2 évig őrizzük. +
  • +
  • + Az el nem fogadott beszélgetési kéréseket 90 nap után töröljük. A korábbi álneveidet 90 napig foglaljuk le. +
  • 8. Sütik

    - Csak egy, a működéshez feltétlenül szükséges sütit használunk (sf_session), amely belépve - tart. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk. + A működéshez feltétlenül szükséges sütit használunk (sf_session), amely belépve tart. Ha a + fórumon világos vagy sötét témát választasz, a választásodat egy második süti (sf_forum_theme) + őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.

    A belépés nélküli születési horoszkópnál a megadott születési adatokat @@ -323,13 +420,15 @@ export default async function PrivacyPage() {

    • Hozzáférés és adathordozhatóság: a Profil oldalon - egy kattintással letöltheted minden adatodat. + egy kattintással letöltheted minden adatodat, a fórumon írtakat és beállítottakat is.
    • Helyesbítés: a nevedet és a születési adataidat a Profil oldalon módosíthatod.
    • - Törlés: a fiókodat és minden adatodat a Profil oldalon törölheted. + Törlés: a fiókodat és minden adatodat a Profil oldalon törölheted. A fórumon a saját + hozzászólásaidat egyenként is törölheted; a fiók törlése után „Törölt tag” néven maradók törlését + e-mailben kérheted.
    • Korlátozás és tiltakozás: a fenti e-mail-címen kérheted. diff --git a/services/frontend/src/app/admin/AdminUsers.tsx b/services/frontend/src/app/admin/AdminUsers.tsx index 877d292..f3825f0 100644 --- a/services/frontend/src/app/admin/AdminUsers.tsx +++ b/services/frontend/src/app/admin/AdminUsers.tsx @@ -9,7 +9,7 @@ import { ROLE_LABELS, formatDate } from "@/lib/astro"; import type { AdminUser, Package, Role } from "@/lib/types"; const PAGE_SIZE = 25; -const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"]; +const EDITABLE_ROLES: Role[] = ["user", "creator", "moderator", "admin"]; type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot"; /** `short`: the mark in the list, where the names do not fit (explained under it). */ diff --git a/services/frontend/src/app/api/v1/[...path]/route.ts b/services/frontend/src/app/api/v1/[...path]/route.ts index 4a380af..aedf18a 100644 --- a/services/frontend/src/app/api/v1/[...path]/route.ts +++ b/services/frontend/src/app/api/v1/[...path]/route.ts @@ -1,9 +1,11 @@ -// Forwards /api/v1/* to the backend, so the browser talks to one origin and -// the session cookie belongs to the frontend's host (no CORS needed). +// Forwards /api/v1/* to the backend (and /api/v1/forum/* to the forum +// service), so the browser talks to one origin and the session cookie belongs +// to the frontend's host (no CORS needed). import { revalidateTag } from "next/cache"; import type { NextRequest } from "next/server"; import { CELEBRITIES_TAG } from "@/lib/celebrities"; +import { FORUM_URL } from "@/lib/forumServer"; import { BACKEND_URL } from "@/lib/server"; import { SHARES_TAG } from "@/lib/share"; @@ -22,7 +24,13 @@ const SKIP_RESPONSE_HEADERS = new Set(["connection", "content-encoding", "conten async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { const { path } = await ctx.params; - const target = `${BACKEND_URL}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`; + // The forum is a service of its own; without FORUM_URL it is switched off. + const forum = path[0] === "forum"; + if (forum && !FORUM_URL) { + return Response.json({ error: { code: "not_found", message: "A fórum nincs bekapcsolva." } }, { status: 404 }); + } + const base = forum ? FORUM_URL : BACKEND_URL; + const target = `${base}/v1/${path.map(encodeURIComponent).join("/")}${req.nextUrl.search}`; const headers = new Headers(); for (const name of REQUEST_HEADERS) { @@ -53,7 +61,9 @@ async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }); for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie); // A revoked link must disappear at once from the cached share pages. - if (req.method === "DELETE" && path[0] === "shares" && res.ok) revalidateTag(SHARES_TAG, { expire: 0 }); + // A revoked link (also a chart taken off a forum question, or the question deleted) goes from the cache. + const revokes = path[0] === "shares" || (path[0] === "forum" && path[1] === "posts"); + if (req.method === "DELETE" && revokes && res.ok) revalidateTag(SHARES_TAG, { expire: 0 }); // An admin's change to a famous person shows on the public pages at once. if (req.method !== "GET" && path[0] === "admin" && path[1] === "celebrities" && res.ok) { revalidateTag(CELEBRITIES_TAG, { expire: 0 }); diff --git a/services/frontend/src/app/aszf/page.tsx b/services/frontend/src/app/aszf/page.tsx index 05d68a2..82b853f 100644 --- a/services/frontend/src/app/aszf/page.tsx +++ b/services/frontend/src/app/aszf/page.tsx @@ -35,7 +35,8 @@ export default async function TermsPage() { megadott születési adatokból kiszámítja és megrajzolja a születési képletet, és ingyenes rövid összefoglalót ad. Csomagok vásárlásával a felhasználó szoftveresen (mesterséges intelligenciával) előállított, személyre szabott szöveges tartalmakat kérhet: részletes képletelemzést, kapcsolati elemzést, éves előrejelzést, - kártyajóslást és kérdésekre adott válaszokat, valamint további személyeket vehet fel. + kártyajóslást és kérdésekre adott válaszokat, valamint további személyeket vehet fel. A Sorsfonalak része egy + ingyenes közösségi fórum is (8. pont).

      A tartalmak szórakoztató és önismereti célúak. Nem minősülnek orvosi, pszichológiai, pénzügyi, jogi vagy @@ -136,17 +137,123 @@ export default async function TermsPage() {

    -
    -

    8. A fiók megszüntetése

    +
    +

    8. A fórum

    - A fiók a Profil oldalon bármikor törölhető. A fel nem használt egységek ezzel megszűnnek; ezekért - visszatérítés nem jár, kivéve, ha a törlést a szolgáltatás hibája tette szükségessé. A jogszabálysértő - vagy a szolgáltatással visszaélő felhasználó fiókját felfüggeszthetjük vagy megszüntethetjük. + A Sorsfonalak része egy ingyenes közösségi fórum (sorsfonalak.hu/forum). Ez a pont a fórum szabályait + (házirend), a moderálás rendjét és a jogsértő tartalmak bejelentését írja le, az Európai Unió digitális + szolgáltatásokról szóló (EU) 2022/2065 rendelete (DSA) szerint. +

    + +

    8.1. Olvasás, írás, álnév

    +

    + A nyilvános témákat bárki olvashatja, és a keresők is megjeleníthetik. A csak tagoknak szóló témákat + (például „Ami a szívemen van”) csak belépve lehet olvasni, és a keresők nem látják. A zárt témákat csak a jóváhagyott tagjaik olvashatják; a + csatlakozásról egy moderátor dönt. Írni, reagálni és üzenni + belépve, egy választott álnévvel lehet. Az álnév ne legyen a valódi neved, ha nem szeretnéd, hogy + felismerjenek; nem lehet sértő vagy megtévesztő, és nem utánozhat más tagot, moderátort vagy a + Sorsfonalakat. A valódi neved, az e-mail-címed és a születési adataid a fórumon nem jelennek meg; a + képletedből csak annyi látszik, amennyit a fórumprofilodban megosztasz, fokok nélkül. + A Kereső rangtól saját képet is feltölthetsz avatarnak: csak olyat, amelyhez jogod van, és amelyen más nem + ismerhető fel a hozzájárulása nélkül; a moderátorok a nem odaillő képet eltávolíthatják. +

    + +

    8.2. Házirend

    +

    A fórum a nyugodt beszélgetés és a meghallgatás helye. Kérjük:

    +
      +
    • tisztelettel írj másokról és másokhoz, kioktatás és gúnyolódás nélkül;
    • +
    • ha valaki csak meghallgatást kér, ne adj neki kéretlen tanácsot;
    • +
    • vitatkozz gondolatokkal, ne mások hitével, világnézetével vagy életével.
    • +
    +

    Tilos:

    +
      +
    • mások zaklatása, fenyegetése, sértegetése, a gyűlöletkeltés;
    • +
    • jogsértő tartalom, például szerzői jogot sértő szöveg vagy bűncselekményre való felhívás;
    • +
    • + más személyes adatainak (név, elérhetőség, születési adatok, fénykép) közzététele az érintett + hozzájárulása nélkül; +
    • +
    • + szolgáltatás vagy termék hirdetése és árusítása (például jóslás, energetikai gyógyítás, tanfolyam), + reklám, kéretlen üzenetek; +
    • +
    • pénz, adatok vagy szívességek kérése megtévesztéssel, más nevében való fellépés;
    • +
    • biztatás orvosi kezelés abbahagyására vagy helyettesítésére.
    • +
    +

    + A fórum nem helyettesíti az orvost, a pszichológust és más szakembert. Ha te vagy valaki más veszélyben van, + hívd a 112-t. A lelki elsősegély-szolgálat ingyenes, éjjel-nappal hívható száma: 116-123. +

    + +

    8.3. A hozzászólások

    +

    + A hozzászólásaidért te felelsz. A szerzői jogod a tiéd marad; a közzététellel ingyenes, nem kizárólagos + engedélyt adsz arra, hogy a hozzászólást a fórumon megjelenítsük (a nyilvános témákban a keresők számára + is), amíg ott van. A saját hozzászólásodat szerkesztheted és törölheted. Ha a fiókodat törlöd, a szálaid és + a hozzászólásaid „Törölt tag” néven megmaradnak, hogy a beszélgetések érthetők maradjanak. Ha ezt nem + szeretnéd, előtte töröld őket, vagy kérd a törlésüket a {email} címen. +

    + +

    8.4. Privát üzenetek

    +

    + Privát beszélgetést a Kereső rangtól, egy rövid bemutatkozást tartalmazó kéréssel lehet kezdeményezni. A + címzett elfogadhatja, elutasíthatja (erről a küldő nem kap értesítést), vagy letilthatja a küldőt. A privát + üzeneteket a moderátorok nem olvassák. Ha valaki egy üzenetet jelent, a moderátorok a jelentett üzenetet és + az előtte lévő néhány üzenetet látják, hogy dönteni tudjanak. +

    + +

    8.5. Rangok és korlátok

    +

    + A rang a hozzászólásokra kapott reakciókból és a tagság idejéből jön; pénzbeli értéke nincs, és nem + vásárolható meg. Az új tagok (Vándor rang) naponta legfeljebb 3 szálat nyithatnak és 20 hozzászólást + írhatnak; ezt a korlátot egy csomag megvásárlása feloldja. A visszaélések megelőzésére további korlátok is + vannak, például néhány másodperc két hozzászólás között, és napi felső határ a beszélgetési kérésekre és a + jelentésekre. +

    + +

    8.6. Bejelentés és moderálás

    +

    + Jogsértő vagy a házirendbe ütköző tartalmat a hozzászólás (vagy a neked küldött üzenet) melletti „Jelentés” + gombbal jelezhetsz; fiók nélkül a {email} címen, a tartalom linkjével és azzal, hogy mi vele a gond. A + gombbal küldött jelentés beérkezését azonnal visszaigazoljuk, és a döntésről e-mailben értesítünk. +

    +

    + A fórumot és a jelentéseket az üzemeltető által kijelölt moderátorok figyelik. Minden döntést ember hoz; + automatikus (algoritmikus) moderálást jelenleg nem használunk, és ha bevezetjük, itt jelezzük. A lehetséges + intézkedések: a hozzászólás vagy a szál eltávolítása (a helyén az indoklás látszik), a szál lezárása, és a + tag eltiltása az írástól meghatározott időre vagy véglegesen. Az eltiltott tag olvashat, de nem írhat; az + eltiltás a megvásárolt szolgáltatásokat nem érinti. Az intézkedésről és az indokáról az érintett tagot + e-mailben is tájékoztatjuk. +

    +

    + Ha szerinted egy döntés téves, a {email} címen kifogást tehetsz: a döntést egy másik moderátor vagy az + üzemeltető vizsgálja felül, és válaszolunk. A 10. pontban írt jogorvoslati lehetőségek ezen túl is + megilletnek. +

    +

    + Kapcsolattartási pont a hatóságok és a felhasználók számára (DSA 11. és 12. cikk): {email}, magyar nyelven. +

    + +

    8.7. Értesítések

    +

    + A fórum e-mailben értesíthet a neked írt válaszokról, a követett szálakról és a privát üzenetekről. Ezeket a + fórumprofilodban állíthatod be, és minden ilyen levél alján egy kattintással leiratkozhatsz. A moderálásról + és a jelentéseid elbírálásáról szóló leveleket ettől függetlenül elküldjük.

    -

    9. Panaszkezelés, jogorvoslat

    +

    9. A fiók megszüntetése

    +

    + A fiók a Profil oldalon bármikor törölhető. A fel nem használt egységek ezzel megszűnnek; ezekért + visszatérítés nem jár, kivéve, ha a törlést a szolgáltatás hibája tette szükségessé. A jogszabálysértő + vagy a szolgáltatással visszaélő felhasználó fiókját felfüggeszthetjük vagy megszüntethetjük. A fórumon írt + hozzászólások a fiók törlése után „Törölt tag” néven megmaradnak (8.3. pont). +

    +
    + +
    +

    10. Panaszkezelés, jogorvoslat

    Panaszt a {email} címen tehetsz; 30 napon belül írásban válaszolunk. Ha a panaszt nem rendezzük, a szolgáltató székhelye szerint illetékes békéltető testülethez fordulhatsz ({ARBITRATION_BOARD.name},{" "} @@ -157,7 +264,7 @@ export default async function TermsPage() {

    -

    10. Egyéb

    +

    11. Egyéb

    Az ÁSZF módosítása a módosítás után kötött vásárlásokra vonatkozik; a lényeges változásokat az oldalon jelezzük. A szerződés és a szolgáltatás nyelve magyar, a szerződésre a magyar jog irányadó. @@ -165,7 +272,7 @@ export default async function TermsPage() {

    -

    11. A szolgáltató adatai

    +

    12. A szolgáltató adatai

    diff --git a/services/frontend/src/app/belepes/PasswordLogin.tsx b/services/frontend/src/app/belepes/PasswordLogin.tsx index ad53be0..630a405 100644 --- a/services/frontend/src/app/belepes/PasswordLogin.tsx +++ b/services/frontend/src/app/belepes/PasswordLogin.tsx @@ -3,6 +3,8 @@ import { useRouter } from "next/navigation"; import { useState } from "react"; +import { PasswordInput } from "@/components/PasswordInput"; +import { Turnstile } from "@/components/Turnstile"; import { ApiError, api, errorText } from "@/lib/api"; type Mode = "login" | "register" | "forgot"; @@ -25,9 +27,12 @@ export function PasswordLogin({ inviteToken = null, referral = null, initialMode = "login", + turnstileKey = null, }: { target: string; inviteToken?: string | null; + /** Cloudflare Turnstile on the sign-up and reset forms (null: none). */ + turnstileKey?: string | null; /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ referral?: string | null; initialMode?: Mode; @@ -41,6 +46,10 @@ export function PasswordLogin({ const [error, setError] = useState(null); const [sent, setSent] = useState(null); const [uninvited, setUninvited] = useState(false); + // Turnstile's token (sign-up and reset only); a new round after each try. + const [token, setToken] = useState(null); + const [round, setRound] = useState(0); + const checked = mode === "login" || !turnstileKey; function switchTo(next: Mode) { setMode(next); @@ -63,10 +72,17 @@ export function PasswordLogin({ } if (mode === "register") { await api("/auth/register", { - body: { email, display_name: name.trim() || null, locale: "hu", invite_token: inviteToken, referral }, + body: { + email, + display_name: name.trim() || null, + locale: "hu", + invite_token: inviteToken, + referral, + turnstile_token: token, + }, }); } else { - await api("/auth/password-reset", { body: { email } }); + await api("/auth/password-reset", { body: { email, turnstile_token: token } }); } setSent(mode); } catch (err) { @@ -74,6 +90,8 @@ export function PasswordLogin({ else setError(mode === "login" ? loginError(err) : errorText(err)); } finally { setBusy(false); + // A token works once. + if (mode !== "login" && turnstileKey) setRound((r) => r + 1); } } @@ -134,10 +152,9 @@ export function PasswordLogin({ Elfelejtett jelszó?
    - )} - {error && (

    diff --git a/services/frontend/src/app/belepes/page.tsx b/services/frontend/src/app/belepes/page.tsx index 720b922..4241f52 100644 --- a/services/frontend/src/app/belepes/page.tsx +++ b/services/frontend/src/app/belepes/page.tsx @@ -169,7 +169,13 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis )} {password && ( - + )} ) : ( diff --git a/services/frontend/src/app/forum/[tema]/page.tsx b/services/frontend/src/app/forum/[tema]/page.tsx new file mode 100644 index 0000000..e75576e --- /dev/null +++ b/services/frontend/src/app/forum/[tema]/page.tsx @@ -0,0 +1,98 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; + +import { ThreadList } from "@/components/forum/ThreadList"; +import type { TopicPage } from "@/lib/forum"; +import { forumGet } from "@/lib/forumServer"; + +type Props = { params: Promise<{ tema: string }>; searchParams: Promise<{ oldal?: string }> }; + +async function load(slug: string, page: number) { + return forumGet(`/v1/forum/topics/${encodeURIComponent(slug)}?page=${page}`); +} + +function pageOf(raw: string | undefined): number { + const n = Number(raw ?? 1); + return Number.isInteger(n) && n > 0 ? n : 1; +} + +export async function generateMetadata({ params }: Props): Promise { + const { tema } = await params; + const res = await load(tema, 1); + if (!res.ok) return { title: "Fórum" }; + const { topic } = res.data; + // Members-only topics stay out of search engines. + return { + title: topic.name, + description: topic.description, + robots: topic.visibility === "public" ? undefined : { index: false, follow: false }, + }; +} + +/** A topic's threads: pinned ones first, then by the latest post. */ +export default async function TopicPageView({ params, searchParams }: Props) { + const { tema } = await params; + const page = pageOf((await searchParams).oldal); + const res = await load(tema, page); + if (!res.ok) { + if (res.status === 401) redirect(`/belepes?vissza=/forum/${tema}`); + notFound(); + } + const { topic, threads, has_more, viewer } = res.data; + return ( +

    + +
    +
    +

    {topic.name}

    +

    {topic.description}

    + {topic.visibility !== "public" && ( +

    + + {topic.visibility === "members" + ? "Ezt a témát csak belépett tagok látják: amit itt írsz, kívülről és a keresőkből nem olvasható." + : "Zárt kör: ezt a témát csak a jóváhagyott tagjai látják."} +

    + )} + {topic.archived && ( +

    + + Archivált téma: a szálak olvashatók, de új szál és hozzászólás már nem írható. +

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

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

    + ) : ( +
    + +
    + )} + {(page > 1 || has_more) && ( + + )} +
    + ); +} diff --git a/services/frontend/src/app/forum/beallitasok/MutedList.tsx b/services/frontend/src/app/forum/beallitasok/MutedList.tsx new file mode 100644 index 0000000..7e38939 --- /dev/null +++ b/services/frontend/src/app/forum/beallitasok/MutedList.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import { Avatar } from "@/components/forum/Avatar"; +import { api } from "@/lib/api"; +import type { ForumAuthor } from "@/lib/forum"; + +/** The members the viewer muted, each with "Feloldás". */ +export function MutedList() { + const [muted, setMuted] = useState(null); + useEffect(() => { + api<{ muted: ForumAuthor[] }>("/forum/me/mutes") + .then((res) => setMuted(res.muted)) + .catch(() => setMuted([])); + }, []); + if (!muted || muted.length === 0) return null; + return ( +
    + Elnémított tagok +
      + {muted.map((m) => ( +
    • + + + {m.nickname} + + +
    • + ))} +
    + + Az elnémított tagok szálai nem jelennek meg a listáidban, és nem kapsz értesítést tőlük. + +
    + ); +} diff --git a/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx new file mode 100644 index 0000000..4724d8f --- /dev/null +++ b/services/frontend/src/app/forum/beallitasok/ProfileForm.tsx @@ -0,0 +1,377 @@ +"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 { withEmoji } from "@/lib/emoticons"; +import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum"; + +import { MutedList } from "./MutedList"; + +const SHARE_LEVELS: { value: ChartShare; label: string }[] = [ + { value: "none", label: "Semmit" }, + { value: "sun", label: "Csak a Nap-jegyemet" }, + { value: "big3", label: "Nap, Hold és Aszcendens" }, + { value: "planets", label: "Minden bolygó jegyét" }, +]; + +export function ProfileForm({ me, back }: { me: ForumMe; back: string | null }) { + const router = useRouter(); + const member = me.member; + const [nickname, setNickname] = useState(member?.nickname ?? ""); + const [check, setCheck] = useState<{ ok: boolean; message?: string } | null>(null); + const [avatar, setAvatar] = useState(member?.avatar ?? ""); + const [bio, setBio] = useState(member?.bio ?? ""); + const [share, setShare] = useState(member?.chart_share ?? "none"); + const [invisible, setInvisible] = useState(member?.invisible ?? false); + const [email, setEmail] = useState( + member?.email ?? { + replies: "daily", + followed: "off", + messages: "instant", + mentions: "instant", + listener: "off", + weekly: false, + }, + ); + const [listener, setListener] = useState(member?.listener ?? false); + const [supporter, setSupporter] = useState(member?.supporter_badge ?? false); + const [uploading, setUploading] = useState(false); + const uploaded = avatar.startsWith("upload:"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + + // While typing: valid and free? (Not for the member's own current name.) + useEffect(() => { + const name = nickname.trim(); + if (!name || name === member?.nickname) { + setCheck(null); + return; + } + const timer = window.setTimeout(() => { + api<{ ok: boolean; message?: string }>(`/forum/nickname-check?name=${encodeURIComponent(name)}`) + .then(setCheck) + .catch(() => setCheck(null)); + }, 400); + return () => window.clearTimeout(timer); + }, [nickname, member?.nickname]); + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + setSaved(false); + try { + const res = await api("/forum/me", { + method: "PUT", + body: { + nickname, + avatar: avatar || null, + bio, + chart_share: share, + invisible, + email, + listener, + supporter_badge: supporter, + }, + }); + if (back) { + router.push(back); + } else if (!member && res.member) { + router.push(memberHref(res.member.nickname)); + } else { + setSaved(true); + } + router.refresh(); + } catch (err) { + setError(errorText(err)); + } finally { + setBusy(false); + } + } + + const preview = share === "none" ? null : me.chart?.[share]; + + return ( +
    + {member?.banned_until && ( +

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

    + )} + +
    + + setNickname(e.target.value)} + maxLength={24} + required + autoComplete="off" + aria-describedby="fprof-nick-hint" + /> + + {check && !check.ok + ? check.message + : check?.ok + ? "Szabad, választhatod." + : "Ne a valódi neved legyen, ha nem szeretnéd, hogy felismerjenek. 3–24 karakter: betűk, számok, szóköz, kötőjel."} + + {member?.nickname_change_after && ( + + Új álnevet{" "} + {new Date(member.nickname_change_after).toLocaleDateString("hu-HU", { month: "long", day: "numeric" })} után + választhatsz (az ékezet és a kis- és nagybetű javítható addig is). + + )} +
    + +
    + Avatar +
    + {AVATAR_COLOURS.flatMap((colour) => + AVATAR_GLYPHS.map((glyph) => { + const value = `${glyph}-${colour}`; + return ( + + ); + }), + )} +
    + {!avatar && Ha nem választasz, az álneved alapján kapsz egyet.} + {member?.can_upload_avatar && ( +
    + {uploaded && } + + + JPEG, PNG vagy WebP, legfeljebb 8 MB. Négyzetre vágjuk és kicsinyítjük, a kép adatait (hely, gép) + eltávolítjuk. Ha egy kezdő avatart választasz, a saját kép törlődik. + +
    + )} +
    + +
    + +