Compare commits

...
Author SHA1 Message Date
fecoandClaude Opus 5.5 ad9702a82e Merge main: the forum (community module), Cloudflare Turnstile on e-mail sign-up, password eye button
CI / test (push) Successful in 3m7s
CI / build (push) Successful in 11m56s
CI / deploy (push) Successful in 1m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 17:27:51 +00:00
fecoandClaude Opus 5.5 178416e069 Password fields with an eye button to show or hide the password
CI / test (push) Successful in 3m22s
CI / build (push) Skipped
CI / deploy (push) Skipped
The login form and the new password page (both fields) use PasswordInput:
an eye button shows what was typed and hides it again (the caret stays in
the field; Edge's own reveal button is hidden so there are not two).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 17:23:59 +00:00
fecoandClaude Opus 5.5 9eff714e6a Phones: the forum's text boxes are not in a form (no card AutoFill on iOS)
iOS Safari kept offering card and address AutoFill for the reply box and
the new thread form despite autocomplete="off": it looks at the whole
<form>. The boxes now sit in plain blocks; the button sends, and so does
Ctrl/Cmd+Enter. KeyboardSafe keeps such a block (data-kb-block) with its
send button above the keyboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 17:18:26 +00:00
fecoandClaude Opus 5.5 a622d30b39 Phones: no AutoFill bar over text boxes, steadier scrolling above the keyboard
- Text boxes say autocomplete="off" (the forum's in the markup, any other
  textarea when it gets the focus), so iOS Safari does not lay its AutoFill
  bar (passwords, cards, addresses) over them.
- KeyboardSafe scrolls at once instead of smoothly (the browser's own
  scroll cut the smooth one short on iOS), once more when that has
  settled, and keeps a little more room above the keyboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 17:14:45 +00:00
fecoandClaude Opus 5.5 c07c7b68bf Forum: a lighter new thread form
The topic is a row of small labels with the topic icons (its description
and who sees it below), the wish a three-way switch (Meghallgatásra,
Véleményekre, Beszélgetésre; two in a listening topic) with its meaning
below, and the title and the text are one writing surface with the send
button at its foot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 17:09:10 +00:00
fecoandClaude Opus 5.5 67cb3c6b8c Forum: the attached chart's wheel in the question
A question with a shared chart shows the chart's wheel, one with a shared
synastry the two charts on one wheel, at a fixed size beside the details
(above them on phones). The forum sends the wheel's data (positions, angles,
houses, aspects; never birth date, time or place) to logged-in members only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 16:57:04 +00:00
fecoandClaude Opus 5.5 e7767573d7 Merge the forum (community module) into main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 16:43:19 +00:00
fecoandClaude Opus 5.5 469f321ac0 Cloudflare Turnstile on e-mail sign-up and password reset, and a limit per address
- The sign-up and "forgot password" forms carry a token from Cloudflare
  Turnstile's widget (managed, shown only when Cloudflare asks for a
  click); the backend checks it before an e-mail goes out. Off without
  TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY (development); the site key
  comes to the page through /v1/config.
- At most ten such e-mail requests an hour per visitor address, so a
  script cannot make the site mail thousands of strangers.
- The privacy notice (HU, EN) mentions Turnstile with Cloudflare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 16:43:07 +00:00
fecoandClaude Opus 5.5 1d4f18b5d6 Forum: the link module, with YouTube previews
- services/forum/src/links: recognises the links in a post and shows a
  preview for the ones a provider knows; for now YouTube (watch, shorts,
  live, embed and youtu.be links, with the start time). Title and channel
  come from YouTube's oEmbed answer, the thumbnail is cut to 16:9 and kept
  in our own storage, so reading a thread loads nothing from YouTube. Made
  when a post is written or edited; without it the link stays text.
- The card: on a computer a click plays the video in place
  (youtube-nocookie.com); on a phone it opens the YouTube app (Android:
  an intent with the web page as fallback; iOS: the link the app takes
  over), and "Lejátszás itt" plays it in place.
- The privacy notice (HU, EN) says what YouTube sees when one plays it.
- "Pörgős most" is now "Élénk beszélgetések"; the new thread form lost its
  note about text and emoji.
- docs: the Turnstile captcha is on the list before going live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 16:26:37 +00:00
fecoandClaude Opus 5.5 493539bf56 Forum: founders are the first fifteen; the admin can take or give the badge
The site has few members yet, some of them test accounts: the badge goes to
the first fifteen, and the admin can take it from a test account on its
profile (the place goes to the next newcomer) or give it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 15:46:44 +00:00
fecoandClaude Opus 5.5 8fc550662e Forum: the "Alapító tag" badge for the first hundred members
The first hundred members (in the order they chose a nickname) keep it for
good; joining is serialised so there are never more than a hundred. Shown
next to the nickname in posts, author lines and profiles; the privacy
notice mentions it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 15:43:24 +00:00
fecoandClaude Opus 5.5 863002c1e7 Forum: asking about one's own chart, forecast or comparison
- "Kérdezek róla a fórumon" on the chart, yearly forecast and comparison
  pages: after a window that says what goes out, a share link made for the
  forum (never birth data, names or a title) and a new thread in "Égbolt és
  képletek" with it attached.
- The question shows a card (Sun, Moon, Ascendant with sign, degree and
  house, the summary's title, a link to the shared page) to logged-in
  members only; visitors and search engines see only that there is one.
  The author can take it off, and deleting the question ends the link.
- The shared page (/s/...) now shows comparisons (one wheel, the aspects,
  no names) and yearly forecasts (keys, timeline, transits, the detailed
  text; without the birthday's place); the backend shares forecasts.
- The privacy notice (HU, EN) covers attached charts and muted members.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 14:52:00 +00:00
fecoandClaude Opus 5.5 9ca3f478be Forum: search, muting members, archived topics, the public threads in the sitemap
- Search (/forum/kereses, the magnifier in the forum bar): thread titles
  and posts the viewer may read, Hungarian stems and word beginnings
  without accents ("alvas" finds "alvásban"), one result per thread with
  the matching words marked.
- Muting a member (post menu, profile; the list in the settings): their
  threads leave the lists, their posts fold up, their replies and mentions
  no longer count or send e-mails. They are not told.
- The admin archives a topic (Moderálás → Témák): it stays readable but
  takes no new threads or replies, and folds away on the front page.
- The public topics and threads are in the sitemap; the forum's own pages
  are kept from robots.
- A reply e-mail goes to the one answered, also on the second level.
- Migration 0043 also prepares charts attached to a forum question.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 14:31:05 +00:00
fecoandClaude Opus 5.5 4800a30e6d Forum: the sky card's and the companions' links as rows too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 13:47:07 +00:00
fecoandClaude Opus 5.5 23316d6042 Forum: the side links as rows in one card
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 13:44:25 +00:00
fecoandClaude Opus 5.5 42283d740e Forum: answers to me as the only count, reply box in the branch, keyboard-safe inputs
- The "Követett" tab becomes "Válaszok": its count is the unread answers
  to the member (a reply to their post, a first-level reply in their
  thread, or a post naming them), listed on /forum/valaszok with "Mind
  olvasott"; the followed threads are its second view. The other counts
  are gone from the menu; listeners see the waiting threads on their card
  on the front page.
- Replying to a post opens the box at the bottom of its branch and scrolls
  there; another branch moves it (with the text typed so far).
- Phones: while typing, the forum's bottom menu and floating bars step
  aside and the box with its send button is scrolled above the keyboard
  (KeyboardSafe, site-wide; Android resizes the page for the keyboard).
- The "Meghallgató" badge is now "Kísérő", with a new icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 13:31:00 +00:00
fecoandClaude Opus 5.5 8bc426460d Forum: whom a reply answers, icon badges, the new features on the pages
- Replies stay two levels deep, but a reply to a reply says whom it is
  for ("↪ Holdfény"): posts.reply_to_id.
- The question stands apart on its own card; the listening reminder above
  the reply box is gone.
- Every rank and badge has its own line icon (Vándor, Kereső, Fonó,
  Csillagfonó, Sorsfonó; Moderátor, Meghallgató, Támogató, Szálindító).
- Pages for the new features: own avatar upload and the moderator's reset,
  the listener and supporter switches, mention and weekly summary e-mails
  (the weekly one off by default), "@" suggestions and mention links, the
  daily sky thread by "Sorsfonalak", "Most itt vannak", joining restricted
  topics, and the moderators' Témák tab (requests; topics for the admin).
- Members-only topics say so to members too.
- The privacy notice (HU, EN) and point 8.1 of the terms cover own
  pictures, badges, mentions, restricted topics and the weekly summary;
  the data export and account deletion include them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 13:02:38 +00:00
fecoandClaude Opus 5.5 564c22176f Forum: daily sky thread, listeners, mentions, own avatars, restricted topics
- The worker opens a "Mai égbolt" thread every morning from the day's sky
  (no AI), pinned for the day.
- Volunteer listeners (from the Kereső rank) get a badge, a count of the
  threads asking to be heard that still wait for a reply, and, if they ask,
  an e-mail after two hours of waiting.
- "@Holdfény" names a member (nicknames with spaces too): they follow the
  thread, hear of it live and, if they asked, by e-mail; a search helps
  typing it.
- From the Kereső rank a member may upload an own avatar: a small square
  JPEG without metadata in the object storage (now a shared crate with the
  backend), served by the forum; moderators can put the starter back.
- The "Támogató" badge for buyers who switch it on.
- The admin creates and edits topics; restricted ones are read by their
  approved members, who ask to join and moderators decide.
- "Most itt vannak" on the front page; the weekly summary e-mail on Sunday
  evening for those who ask (off by default).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 12:37:52 +00:00
fecoandClaude Opus 5.5 0a2308c491 Forum design: own reaction marks, compact posts, avatars for the light theme
As on the approved canvas: reactions are the forum's own line marks
(heart, lotus, two circles, star) with a count, the viewer's own filled;
the big 2x2 boxes under the opening post are gone and the names live in
the + menu and tooltips. A post's head is one line (avatar, name, rank,
Sun/Moon/Ascendant as glyphs, time), on wide screens the text lines up
under the name instead of the tall author column. "Válasz" is a small
button; edit, delete, report and moderation sit in a ⋯ menu. The
listening wish is a thin line under the title. In the light theme the
avatars get a pale tint and a darker glyph (the night circle read as a
black blot).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 12:20:17 +00:00
fecoandClaude Opus 5.5 7c3c9e5565 Home page: the forum first among the free boxes, highlighted
Across the whole row, with a "Közösség" label: thoughtful conversations
under a nickname, and calm attention instead of fast-moving videos. Shown
only when the forum is switched on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:56:19 +00:00
fecoandClaude Opus 5.5 ee16974c77 Forum: typing notices, smileys to emoji while typing, no emoji tray
"Holdfény gépel…" shows in threads and private conversations: the page
says over the live connection (every few seconds while typing) that its
member types, and the forum service passes it to those who may see that
place, never back to the typer. The emoji tray is gone (phones have their
emoji keyboard); character smileys turn into emoji as they are typed,
from a longer list shared with the server (which also converts titles
now; <3 is a red heart). Emoji show in colour: the forum's font stack
names the systems' colour emoji fonts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:50:09 +00:00
fecoandClaude Opus 5.5 2cf7266fc1 Forum: live notices over WebSocket
A doorbell, not the data: the forum service tells a member's page that
their menu counts, a thread or a conversation changed, and the page
fetches the news over HTTP. Events go through Postgres NOTIFY so every
instance hears them; pings keep the connection (and the online dot)
alive; only the site's own origin may connect. The menu now refreshes
its badges live, on every page change and when the page comes back to
the front, and polls while there is no connection. Caddy sends
/api/v1/forum/ws straight to the forum service; in development
FORUM_WS_URL points at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:41:45 +00:00
fecoandClaude Opus 5.5 88d9a5df3e Privacy policy: the forum, and the export and retention it states
Both languages: rows for the forum profile, posts, last visit, private
conversations, reports and the moderation log (DSA legal obligation);
what is public and what moderators see; forum content never goes to AI;
retention periods; the forum theme cookie; the rights (the export covers
the forum, posts kept as "Törölt tag" can be deleted on request). In
force from 2026-11-26.

So that it holds: the account export includes the forum, and the hourly
cleanup clears text removed by moderators after a year, closed reports
and old ban reasons after a year, the moderation log after two years,
and requests never accepted after 90 days.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:26:09 +00:00
fecoandClaude Opus 5.5 da42c92e71 ÁSZF: the forum chapter, and the moderation e-mails it promises
A new point 8 (the old 8–11 become 9–12): reading, writing and the
nickname, the house rules, posts (they stay as "Törölt tag" after an
account is deleted), private messages, ranks and limits, reports and
moderation under the DSA (receipt, decision notice, statement of reasons,
objection, point of contact; every decision is made by a person),
notifications. In force from 2026-11-26 (TERMS_UPDATED, TERMS_VERSION).

So that it holds: the member gets an e-mail with the reason when a
moderator removes their post or thread or bans them, and every reporter
gets the decision on their report, whatever their notification settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:08:13 +00:00
fecoandClaude Opus 5.5 7c768fccff Forum: e-mail notifications with a daily digest
Members choose per kind: replies to them (daily digest, instant or off),
new posts in followed threads (daily or off), private messages and
requests (instant or off). The forum service queues the instant e-mails
(none while online, at most one per thread an hour); the worker's new
forum task makes the evening digest of what is unread. Every forum e-mail
greets by the nickname and has a one-click unsubscribe (RFC 8058).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 10:59:29 +00:00
fecoandClaude Opus 5.5 4def9569b1 Forum: reports for moderators and private messages by request
Any logged-in user can report a post, or a private message received; a
possible crisis shows the helplines at once. Moderators get the open
reports (crisis first) with what was reported, remove or close them, and
every step goes to the log; the operator gets a Telegram notice of each
new report (kind and link only). Private conversations start with a
request and a short introduction (from the Kereső rank, a few a day); the
recipient accepts, declines silently or blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 10:48:28 +00:00
fecoandClaude Opus 5.5 36b38525c3 Forum: a service of its own and the /forum pages
services/forum (axum, port 8083) on the same database and login, in the
forum schema (migration 0038, which also adds the moderator role):
nicknames, profiles with shared signs, topics, threads with listening or
advice intent, two-level replies, read marks and followed threads,
reactions as ratings with points and ranks, newcomer limits (lifted by a
purchase), moderation with reasons, bans and a log. Integration tests run
in CI.

The frontend's /forum pages (light by default, dark on request, phone
first with a desktop layout) are switched on by FORUM_URL; the /api/v1
proxy sends /api/v1/forum/* to the forum service. Concept and status:
docs/kozosseg.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 10:29:49 +00:00
fecoandClaude Opus 5.5 670a6f0584 Merge main: new prices, forecast in Egy elemzés, free person slots (30)
CI / test (push) Successful in 2m39s
CI / build (push) Successful in 9m49s
CI / deploy (push) Successful in 41s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 18:38:54 +00:00
fecoandClaude Opus 5.5 fa46dcb757 Free person slots (up to 30), Páros 3 500 Ft
CI / test (push) Successful in 2m42s
CI / build (push) Skipped
CI / deploy (push) Skipped
- Persons are free up to FREE_PERSON_SLOTS (30); packages give no person
  slots, the "+5 személy" add-on is retired (still known for old orders and
  payments in flight). At the cap: write to us, an admin grants more.
- Páros 3 500 Ft; "bought one by one" prices without persons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 18:32:34 +00:00
fecoandClaude Opus 5.5 e6aacd0baa New prices: a forecast in the single package, cheaper Páros, Család and add-ons
- Egy elemzés: 2 000 Ft, now with a yearly forecast.
- Páros 5 000 Ft, Család 7 000 Ft, +1 kapcsolati and +1 előrejelzés 1 500 Ft.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 18:17:38 +00:00
fecoandClaude Opus 5.5 86f61c215a Merge main: Christmas gifts, timed gift e-mails, public gift pages
CI / test (push) Successful in 2m30s
CI / build (push) Successful in 7m52s
CI / deploy (push) Successful in 41s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 17:08:44 +00:00
fecoandClaude Opus 5.5 5feaa6836c Gift withdrawal in the confirmation e-mail through the feedback page
CI / test (push) Successful in 2m36s
CI / build (push) Skipped
CI / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 17:08:17 +00:00
fecoandClaude Opus 5.5 c367c218ac Gift withdrawal through the feedback form, not by e-mail
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 17:04:07 +00:00
fecoandClaude Opus 5.5 e0605a7653 Public gift pages for visitors and search engines
- /ajandek shows a page about giving to visitors (indexable, in the sitemap);
  the form still needs a login.
- A gift band on the home page and "Ajándékozás" in the footer (to
  /karacsony in the Christmas season).
- A link preview image for /karacsony.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 16:56:17 +00:00
fecoandClaude Opus 5.5 2d1373edd6 A Christmas tree in the packages page gift box
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 16:04:36 +00:00
fecoandClaude Opus 5.5 382bd31271 Christmas gifts and timed gift e-mails
- Gifts bought 15 Nov - 6 Jan get a Christmas card ("Boldog karácsonyt és
  csillagos 2027-et!", snowflakes) and a Christmas e-mail subject.
- The buyer can time the gift e-mail (e.g. Christmas morning); "Küldés most"
  replaces a waiting one, a refund takes it back.
- Admin: timed e-mails by hour (waiting / sent / failed), e-mail state per gift.
- /karacsony landing page; seasonal hints on /csomagok and /ajandek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 13:46:35 +00:00
173 changed files with 19720 additions and 703 deletions
+4 -3
View File
@@ -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
Generated
+82
View File
@@ -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",
+3
View File
@@ -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"] }
@@ -0,0 +1,6 @@
-- A gift e-mailed later (e.g. on Christmas morning): when (NULL: at once),
-- and the e-mail queued for it, to show whether it went out (the outbox row
-- itself is cleaned up a week after sending).
ALTER TABLE gifts
ADD COLUMN send_at timestamptz,
ADD COLUMN email_id uuid;
+151
View File
@@ -0,0 +1,151 @@
-- The forum (services/forum, docs/kozosseg.md): pseudonymous members, topics,
-- threads, posts, reactions, read marks, followed threads and the moderation
-- log, in a schema of its own.
CREATE SCHEMA forum;
-- 'moderator': appointed by an admin; may delete posts and threads and ban members.
ALTER TABLE users DROP CONSTRAINT users_roles_valid;
ALTER TABLE users ADD CONSTRAINT users_roles_valid
CHECK (cardinality(roles) > 0
AND roles <@ ARRAY['admin', 'creator', 'moderator', 'premium', 'vip', 'user']::text[]);
-- A user who chose a nickname. Nothing here is the real name: the nickname is
-- typed by the user, never taken from the Google or Apple account.
CREATE TABLE forum.members (
user_id uuid PRIMARY KEY REFERENCES users ON DELETE CASCADE,
nickname text NOT NULL,
-- The nickname folded (no accents, case, spaces or look-alike digits): unique.
nickname_key text NOT NULL UNIQUE,
-- A starter avatar, '<glyph>-<colour>' (the frontend draws it).
avatar text NOT NULL,
bio text NOT NULL DEFAULT '',
-- What the profile shows of the user's own chart: nothing, the Sun sign,
-- Sun, Moon and Ascendant, or every planet's sign. Never degrees.
chart_share text NOT NULL DEFAULT 'none' CHECK (chart_share IN ('none', 'sun', 'big3', 'planets')),
-- Not shown as online.
invisible boolean NOT NULL DEFAULT false,
-- Reactions received (counted ones), "Ez segített" marks; the rank comes from these.
points integer NOT NULL DEFAULT 0,
post_count integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
nickname_changed_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz,
-- Banned until then (year 9999: for good): may read, not write.
banned_until timestamptz,
ban_reason text
);
-- A nickname given up stays reserved for a while, so nobody can take over a
-- known member's name.
CREATE TABLE forum.retired_nicknames (
nickname_key text PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
until timestamptz NOT NULL
);
CREATE TABLE forum.topics (
id smallint PRIMARY KEY,
slug text NOT NULL UNIQUE,
name text NOT NULL,
description text NOT NULL,
-- public: anyone reads (search engines too); members: logged-in users;
-- restricted: approved members only (not used yet: moderators only).
visibility text NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'members', 'restricted')),
-- A listening topic: no ⌄ there, and new threads ask for listening by default.
listening boolean NOT NULL DEFAULT false,
position smallint NOT NULL
);
INSERT INTO forum.topics (id, slug, name, description, visibility, listening, position) VALUES
(1, 'ami-a-szivemen-van', 'Ami a szívemen van', 'Meghallgatás, élethelyzetek', 'members', true, 1),
(2, 'belso-utak', 'Belső utak', 'Spiritualitás, meditáció, álmok', 'public', false, 2),
(3, 'egbolt-es-kepletek', 'Égbolt és képletek', 'Asztrológia, megosztott elemzések', 'public', false, 3),
(4, 'torzsasztal', 'Törzsasztal', 'Bármi, ami eszedbe jut', 'public', false, 4);
CREATE TABLE forum.threads (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
topic_id smallint NOT NULL REFERENCES forum.topics,
-- NULL once the account is deleted (the thread stays, "törölt tag").
author_id uuid REFERENCES users ON DELETE SET NULL,
title text NOT NULL,
-- What the author asks for: only listening, or advice and opinions.
intent text CHECK (intent IN ('listen', 'advice')),
created_at timestamptz NOT NULL DEFAULT now(),
last_post_at timestamptz NOT NULL DEFAULT now(),
-- Visible replies (the opening post not counted).
reply_count integer NOT NULL DEFAULT 0,
pinned boolean NOT NULL DEFAULT false,
locked boolean NOT NULL DEFAULT false,
deleted_at timestamptz,
deleted_by uuid REFERENCES users ON DELETE SET NULL,
delete_reason text
);
CREATE INDEX threads_topic_idx ON forum.threads (topic_id, pinned DESC, last_post_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX threads_author_idx ON forum.threads (author_id, created_at DESC);
CREATE TABLE forum.posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE,
author_id uuid REFERENCES users ON DELETE SET NULL,
-- A reply to a reply (two levels at most: the parent is never itself a reply).
parent_id bigint REFERENCES forum.posts ON DELETE SET NULL,
is_opening boolean NOT NULL DEFAULT false,
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
edited_at timestamptz,
-- The thread's author marked it "Ez segített".
helped_at timestamptz,
-- Hidden, not erased: a moderator's reason shows in its place, an admin can restore it.
deleted_at timestamptz,
deleted_by uuid REFERENCES users ON DELETE SET NULL,
delete_reason text
);
CREATE INDEX posts_thread_idx ON forum.posts (thread_id, id);
CREATE INDEX posts_author_idx ON forum.posts (author_id, created_at DESC);
CREATE INDEX posts_recent_idx ON forum.posts (created_at DESC);
CREATE UNIQUE INDEX posts_opening_key ON forum.posts (thread_id) WHERE is_opening;
-- One reaction per member and post; each is +1 to the author's points, 'down' (⌄) is -1.
CREATE TABLE forum.reactions (
post_id bigint NOT NULL REFERENCES forum.posts ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
kind text NOT NULL CHECK (kind IN ('with_you', 'thanks', 'me_too', 'insight', 'down')),
-- Whether it moved the author's points (a new member's reaction does not).
counted boolean NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (post_id, user_id)
);
-- How far a member has read a thread ("Itt hagytad abba").
CREATE TABLE forum.reads (
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE,
last_post_id bigint NOT NULL,
read_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, thread_id)
);
-- Followed threads: one's own and the ones replied to, or followed by hand.
CREATE TABLE forum.follows (
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
thread_id bigint NOT NULL REFERENCES forum.threads ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, thread_id)
);
CREATE INDEX follows_thread_idx ON forum.follows (thread_id);
-- Every moderation step: who (a person or, later, the AI), what, why.
CREATE TABLE forum.mod_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
actor_id uuid REFERENCES users ON DELETE SET NULL,
actor_kind text NOT NULL DEFAULT 'human' CHECK (actor_kind IN ('human', 'ai')),
action text NOT NULL CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread',
'ban', 'unban', 'lock', 'unlock', 'pin', 'unpin')),
target_user uuid REFERENCES users ON DELETE SET NULL,
thread_id bigint,
post_id bigint,
reason text,
until timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX mod_log_created_idx ON forum.mod_log (created_at DESC);
@@ -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;
@@ -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);
+55
View File
@@ -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:<file>` 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'));
@@ -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;
@@ -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)
);
@@ -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);
@@ -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)
);
+4 -1
View File
@@ -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",
+431 -21
View File
@@ -50,7 +50,7 @@ struct Content {
/// A personal message, shown as a quote.
quote: Option<String>,
/// A short list after the intro, with its heading.
points: Option<(&'static str, Vec<&'static str>)>,
points: Option<(&'static str, Vec<String>)>,
/// 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<Rendered,
("purchase_confirmation", _) => 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<Content, Templ
"a születési képleted kiszámolva és megrajzolva, ingyen,",
"egy rövid, személyre szóló elemzést róla,",
"összevetést a szeretteiddel: mennyire illetek össze.",
],
]
.into_iter()
.map(String::from)
.collect(),
)),
button: "Meghívás elfogadása",
url,
@@ -279,7 +291,10 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
"your birth chart, calculated and drawn, for free,",
"a short, personal reading of it,",
"comparisons with your loved ones: how well you match.",
],
]
.into_iter()
.map(String::from)
.collect(),
)),
button: "Accept the invitation",
url,
@@ -297,6 +312,285 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, Templ
})
}
/// The forum e-mails' common footer: why it came, where to change it, and the
/// one-click unsubscribe of every forum e-mail.
fn forum_footer(payload: &Value, mut content: Content, why: &str) -> Result<Content, TemplateError> {
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<String> {
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::<String>().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<Content, TemplateError> {
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<Content, TemplateError> {
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<Content, TemplateError> {
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<Content, TemplateError> {
let lines = |key: &'static str| -> Vec<String> {
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<Content, TemplateError> {
let lines: Vec<String> = 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<Content, TemplateError> {
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<Content, TemplateError> {
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<Content, TemplateError> {
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<String, TemplateError> {
payload[name].as_str().filter(|u| !u.is_empty()).map(str::to_owned).ok_or(TemplateError::MissingField(name))
}
@@ -320,6 +614,8 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
payload["paid_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("paid_on"))?;
let terms_url = field(payload, "terms_url")?;
let invoices_url = field(payload, "invoices_url")?;
// Gift withdrawals come through the feedback page (easier to handle there).
let feedback_url = format!("{}/visszajelzes", terms_url.trim_end_matches("/aszf"));
let greeting = |hu: bool| match (hu, name(payload, "display_name")) {
(true, Some(n)) => format!("Szia {n}!"),
(true, None) => "Szia!".to_owned(),
@@ -334,7 +630,13 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
.as_str()
.map(|e| e.chars().filter(|c| !c.is_control()).take(254).collect::<String>());
let whom = name(&payload["gift"], "recipient_name");
(code, to, whom)
// `2026-12-24 08:00`, Budapest clock: when it is e-mailed.
let when = payload["gift"]["send_at"].as_str().and_then(|t| {
let (day, clock) = t.split_once(' ')?;
let clock: String = clock.chars().filter(|c| c.is_ascii_digit() || *c == ':').take(5).collect();
Some((date(lang, day)?, clock))
});
(code, to, whom, when)
});
let contents_hu = contents.as_ref().map(|c| format!(" Tartalma: {c}.")).unwrap_or_default();
let contents_en = contents.as_ref().map(|c| format!(" It contains: {c}.")).unwrap_or_default();
@@ -359,9 +661,10 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
unsubscribe: None,
unsubscribe_post_url: None,
},
(Lang::Hu, Some((code, to, whom))) => Content {
(Lang::Hu, Some((code, to, whom, when))) => Content {
subject: format!("Köszönjük a vásárlást: {package} (ajándék)"),
preheader: Some(match &to {
Some(e) if when.is_some() => format!("Az ajándékot időzítve küldjük el ide: {e}."),
Some(e) => format!("Az ajándékot elküldtük ide: {e}."),
None => "Az ajándékutalványt csatoltuk ehhez a levélhez.".into(),
}),
@@ -370,13 +673,15 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
"Megkaptuk a fizetésed ({amount}, {paid_on}): a(z) „{package}” csomagot ajándékba vetted{}.{contents_hu} {}",
whom.as_ref().map(|w| format!(" {w} részére")).unwrap_or_default(),
match &to {
Some(e) => format!("Az ajándékkódot az utalvánnyal együtt elküldtük ide: {e}. Ha nem e-mailben adnád át, az Ajándékaim oldalon letöltheted az utalványt PDF-ben."),
Some(e) => match &when {
Some((day, clock)) => format!("Az ajándékkódot az utalvánnyal együtt {day}, {clock}-kor küldjük el ide: {e}. Addig az Ajándékaim oldalon letöltheted az utalványt PDF-ben, vagy elküldheted azonnal is."),
None => format!("Az ajándékkódot az utalvánnyal együtt elküldtük ide: {e}. Ha nem e-mailben adnád át, az Ajándékaim oldalon letöltheted az utalványt PDF-ben."),
},
None => "Az ajándékutalványt PDF-ben csatoltuk ehhez a levélhez, és az Ajándékaim oldalon is letöltheted: kinyomtathatod, vagy továbbküldheted annak, akinek szánod.".into(),
}
),
quote: Some(
"A vásárlástól számított 14 napon belül, amíg az ajándékkódot nem váltották be, elállhatsz a vásárlástól: írj az info@sorsfonalak.hu címre, és visszatérítjük az árát. A fizetés előtt kérted, hogy a kód beváltásakor a szolgáltatás azonnal megkezdődjön: a beváltással az elállási jog megszűnik."
.into(),
format!("A vásárlástól számított 14 napon belül, amíg az ajándékkódot nem váltották be, elállhatsz a vásárlástól: írd meg nekünk az oldalon, belépve ({feedback_url}), és visszatérítjük az árát. A fizetés előtt kérted, hogy a kód beváltásakor a szolgáltatás azonnal megkezdődjön: a beváltással az elállási jog megszűnik."),
),
points: None,
code: code.map(|c| ("AJÁNDÉKKÓD", c)),
@@ -409,7 +714,7 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
unsubscribe: None,
unsubscribe_post_url: None,
},
(Lang::En, Some((code, to, whom))) => Content {
(Lang::En, Some((code, to, whom, when))) => Content {
subject: format!("Thank you for your purchase: {package} (gift)"),
preheader: Some(match &to {
Some(e) => format!("We sent the gift to {e}."),
@@ -420,13 +725,15 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result<Con
"We received your payment ({amount}, {paid_on}): you bought the “{package}” package as a gift{}.{contents_en} {}",
whom.as_ref().map(|w| format!(" for {w}")).unwrap_or_default(),
match &to {
Some(e) => format!("We sent the gift code with the gift card to {e}. To hand it over another way, download the card as a PDF on the My gifts page."),
Some(e) => match &when {
Some((day, clock)) => format!("We send the gift code with the gift card to {e} on {day} at {clock}. Until then you can download the card on the My gifts page, or send it at once."),
None => format!("We sent the gift code with the gift card to {e}. To hand it over another way, download the card as a PDF on the My gifts page."),
},
None => "The gift card is attached to this e-mail as a PDF, and you can download it on the My gifts page: print it, or forward it to the person it is for.".into(),
}
),
quote: Some(
"Within 14 days of the purchase, while the gift code is not redeemed, you may withdraw from the purchase: write to info@sorsfonalak.hu and we refund it. Before paying you asked for the service to start as soon as the code is redeemed: redeeming it ends the right of withdrawal."
.into(),
format!("Within 14 days of the purchase, while the gift code is not redeemed, you may withdraw from the purchase: tell us on the site, logged in ({feedback_url}), and we refund it. Before paying you asked for the service to start as soon as the code is redeemed: redeeming it ends the right of withdrawal."),
),
points: None,
code: code.map(|c| ("GIFT CODE", c)),
@@ -459,16 +766,21 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
payload["contents"].as_str().map(|c| c.chars().filter(|c| !c.is_control()).take(300).collect::<String>());
let from = name(payload, "from_name");
let to = name(payload, "recipient_name");
// Bought for Christmas: said so, with the wishes.
let christmas = payload["christmas_year"].as_i64().is_some();
let xmas = if christmas { "karácsonyi " } else { "" };
Ok(match lang {
Lang::Hu => Content {
subject: match &from {
Some(f) => format!("{f} ajándékot küldött neked: „{package}” csomag"),
Some(f) => format!("{f} {xmas}ajándékot küldött neked: „{package}” csomag"),
None if christmas => format!("Karácsonyi ajándékot kaptál: „{package}” csomag a Sorsfonalakon"),
None => format!("Ajándékot kaptál: „{package}” csomag a Sorsfonalakon"),
},
preheader: Some("Születési képlet és személyre szóló elemzések: a kód beváltásával a tiéd.".into()),
greeting: to.as_ref().map_or_else(|| "Szia!".into(), |t| format!("Szia {t}!")),
intro: format!(
"{} egy „{package}” csomagot a Sorsfonalakon.{}",
"{}{} egy „{package}” csomagot a Sorsfonalakon.{}",
if christmas { "Boldog karácsonyt! " } else { "" },
match &from {
Some(f) => format!("{f} ajándékozott neked"),
None => "Ajándékba kaptál".into(),
@@ -483,7 +795,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
"kattints a gombra, és lépj be, vagy regisztrálj, ha még nincs fiókod;",
"a kód már ki lesz töltve, csak a beváltásra kell kattintanod;",
"utána a csomag a tiéd: elkészítheted a képleted és az elemzéseidet.",
],
].into_iter().map(String::from).collect(),
)),
button: "Ajándék beváltása",
url,
@@ -497,6 +809,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
},
Lang::En => Content {
subject: match &from {
Some(f) if christmas => format!("{f} sent you a Christmas gift: the “{package}” package"),
Some(f) => format!("{f} sent you a gift: the “{package}” package"),
None => format!("A gift for you: the “{package}” package on Sorsfonalak"),
},
@@ -518,7 +831,7 @@ fn gift_package(lang: Lang, payload: &Value, url: String) -> Result<Content, Tem
"click the button and log in, or sign up if you have no account yet;",
"the code is filled in for you: just click Redeem;",
"the package is yours: make your chart and your readings.",
],
].into_iter().map(String::from).collect(),
)),
button: "Redeem the gift",
url,
@@ -604,7 +917,7 @@ fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content,
vec![
"a születési képleted percre pontosan kiszámolva és megrajzolva, egy rövid elemzéssel,",
"részletes elemzés, éves előrejelzés és kapcsolati összevetés azokkal, akiket szeretsz.",
],
].into_iter().map(String::from).collect(),
)),
button: "Körülnézek",
url,
@@ -626,7 +939,7 @@ fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result<Content,
vec![
"your birth chart, calculated to the minute and drawn, with a short reading,",
"detailed readings, a yearly forecast and comparisons with the people you love.",
],
].into_iter().map(String::from).collect(),
)),
button: "Take a look",
url,
@@ -666,7 +979,10 @@ fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result<Content,
vec![
"a saját születési képleted kiszámolva és megrajzolva, egy rövid elemzéssel, ingyen,",
"a kettőtök összevetését: hol erős és hol kényes a kapcsolatotok.",
],
]
.into_iter()
.map(String::from)
.collect(),
)),
button: "Megnézem",
url,
@@ -698,7 +1014,10 @@ fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result<Content,
vec![
"your own birth chart, calculated and drawn, with a short reading, for free,",
"the comparison of the two of you: where your relationship is strong and where it is delicate.",
],
]
.into_iter()
.map(String::from)
.collect(),
)),
button: "Take a look",
url,
@@ -981,7 +1300,11 @@ mod tests {
assert!(hu.text.contains("Tartalma: 2 részletes képletelemzés, 3 kérdés."), "{}", hu.text);
let units = json!({"url": "https://sorsfonalak.hu/csomagok", "gift": "2 kérdést"});
let hu = render("gift", "hu", &units).unwrap();
assert!(hu.text.contains("Szia!") && hu.text.contains("Ajándékba kaptad 2 kérdést,") && !hu.text.contains("Tartalma"));
assert!(
hu.text.contains("Szia!")
&& hu.text.contains("Ajándékba kaptad 2 kérdést,")
&& !hu.text.contains("Tartalma")
);
assert!(render("gift", "en", &payload).unwrap().subject.starts_with("A gift"));
assert_eq!(render("gift", "hu", &json!({"url": "x"})), Err(TemplateError::MissingField("gift")));
}
@@ -1021,6 +1344,11 @@ mod tests {
);
assert!(hu.html.contains("&lt;b&gt;Ölel&lt;/b&gt;") && hu.html.contains(">ABCD-EFGH-JKMN</div>"));
assert!(hu.text.contains("PDF-ben is csatoltuk") && hu.text.contains("mert Ági a Sorsfonalakon"));
let mut xmas = payload.clone();
xmas["christmas_year"] = 2027.into();
let hu = render("gift_package", "hu", &xmas).unwrap();
assert_eq!(hu.subject, "Ági karácsonyi ajándékot küldött neked: „Páros” csomag");
assert!(hu.text.contains("Boldog karácsonyt! Ági ajándékozott neked"));
let anonymous = serde_json::json!({"url": "u", "package_name": "Család", "promo_code": "X1-<script>"});
let hu = render("gift_package", "hu", &anonymous).unwrap();
assert_eq!(hu.subject, "Ajándékot kaptál: „Család” csomag a Sorsfonalakon");
@@ -1046,6 +1374,10 @@ mod tests {
assert!(hu.text.contains("AJÁNDÉKKÓD: ABCD-EFGH-JKMN") && hu.text.contains("14 napon belül"));
assert!(hu.text.contains("a beváltással az elállási jog megszűnik"));
assert!(!hu.text.contains("jóváírtuk"));
payload["gift"]["send_at"] = Value::from("2026-12-24 08:00");
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
assert!(hu.text.contains("2026. december 24., 08:00-kor küldjük el ide: bea@example.com"), "{}", hu.text);
assert!(hu.text.contains("belépve (https://sorsfonalak.hu/visszajelzes)"), "{}", hu.text);
payload["gift"]["recipient_email"] = Value::Null;
let hu = render("purchase_confirmation", "hu", &payload).unwrap();
assert!(hu.text.contains("PDF-ben csatoltuk ehhez a levélhez"));
@@ -1058,4 +1390,82 @@ mod tests {
assert_eq!(date(Lang::En, "2027-01-05T10:00:00Z").as_deref(), Some("5 January 2027"));
assert_eq!(date(Lang::Hu, "2027-13-05"), None);
}
fn forum_links() -> 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());
}
}
+1
View File
@@ -28,6 +28,7 @@ fn main() {
code: &code,
redeem_url: &url,
recipient_name: Some(to.as_str()),
christmas: std::env::var("CHRISTMAS").ok().and_then(|y| y.parse().ok()),
from_name: Some(from.as_str()),
message: (!message.is_empty()).then_some(message.as_str()),
};
+97 -12
View File
@@ -38,6 +38,8 @@ const GOLD: &str = "#a07a2c";
const MUTED: &str = "#5f6578";
const LINE: &str = "#d9c9a3";
const PAPER: &str = "#fdfaf3";
/// The Christmas snowflakes: gold, lighter than the text.
const GOLD_SOFT: &str = "#c9a862";
/// Where the code box starts; the message fills the space above it.
const CODE_TOP: f32 = 636.0;
@@ -64,6 +66,27 @@ pub struct Card<'a> {
pub from_name: Option<&'a str>,
/// The buyer's message (line breaks kept).
pub message: Option<&'a str>,
/// A Christmas gift: the card is festive and wishes a happy new year
/// (this one).
pub christmas: Option<i32>,
}
/// "2027-et", "2028-at": a year in the accusative, by how its last word sounds.
pub fn year_accusative(year: i32) -> String {
let ending = match year.rem_euclid(10) {
1 | 4 | 7 | 9 => "et",
2 => "t",
3 | 8 => "at",
5 => "öt",
6 => "ot",
// Tens: "…tízet", "…húszat", "…harmincat"…; hundreds and thousands: "…százat", "…ezret".
_ => match (year / 10).rem_euclid(10) {
1 | 4 | 7 | 9 => "et",
0 if (year / 100).rem_euclid(10) == 0 => "et",
_ => "at",
},
};
format!("{year}-{ending}")
}
#[derive(Debug)]
@@ -252,6 +275,11 @@ impl Message {
let (text, signature) = match (message, from) {
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
(None, Some(f)) => (format!("Szeretettel küldi: {f}"), None),
(None, None) if card.christmas.is_some() => (
"Boldog karácsonyt! Fedezd fel, mit mesélnek rólad a csillagok, és mit hoz neked a következő év."
.to_string(),
None,
),
(None, None) => (
"Fedezd fel, mit mesélnek rólad a csillagok: a születési képleted, személyre szóló elemzések, \
és válaszok a kérdéseidre."
@@ -323,6 +351,26 @@ fn star(x: f32, y: f32, r: f32, fill: &str) -> String {
)
}
/// A six-armed snowflake of gold lines, centred on (x, y).
fn snowflake(x: f32, y: f32, r: f32, color: &str) -> String {
let mut d = String::new();
for k in 0..6 {
let a = (k as f32 * 60.0 - 90.0).to_radians();
let (sin, cos) = a.sin_cos();
let _ = write!(d, "M{x} {y}L{} {}", x + r * cos, y + r * sin);
// Two small branches on each arm.
let (bx, by) = (x + r * 0.6 * cos, y + r * 0.6 * sin);
for side in [-1.0_f32, 1.0] {
let b = a + side * 0.75;
let _ = write!(d, "M{bx} {by}L{} {}", bx + r * 0.32 * b.cos(), by + r * 0.32 * b.sin());
}
}
format!(
r#"<path d="{d}" fill="none" stroke="{color}" stroke-width="{}" stroke-linecap="round"/>"#,
(r / 9.0).max(0.6)
)
}
/// The QR code of the redeem link as a path of `size` points at (x, y).
fn qr(url: &str, x: f32, y: f32, size: f32) -> String {
let Ok(code) = qrcode::QrCode::with_error_correction_level(url, qrcode::EcLevel::M) else {
@@ -388,7 +436,7 @@ pub fn svg(card: &Card) -> String {
);
// "AJÁNDÉKUTALVÁNY" between two short lines.
let eyebrow = "AJÁNDÉKUTALVÁNY";
let eyebrow = if card.christmas.is_some() { "KARÁCSONYI AJÁNDÉK" } else { "AJÁNDÉKUTALVÁNY" };
let spacing = 3.2;
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
let _ = write!(
@@ -413,7 +461,12 @@ pub fn svg(card: &Card) -> String {
for (x, y, r) in
[(124.0, 164.0, 5.0), (462.0, 148.0, 6.5), (470.0, 304.0, 4.0), (134.0, 322.0, 6.0), (420.0, 350.0, 3.0)]
{
s.push_str(&star(x, y, r, LINE));
// Christmas: snowflakes instead of stars, a little bigger.
if card.christmas.is_some() {
s.push_str(&snowflake(x, y, r * 1.9, GOLD_SOFT));
} else {
s.push_str(&star(x, y, r, LINE));
}
}
let inner = WHEEL.split_once("viewBox=\"0 0 680 680\">").map_or("", |(_, rest)| rest);
let inner = inner.trim_end().trim_end_matches("</svg>");
@@ -451,17 +504,32 @@ pub fn svg(card: &Card) -> String {
y += 15.0;
}
// A divider with a small diamond.
// A divider with a small diamond; at Christmas, the wishes on it.
let divider = y + 10.0;
let _ = write!(
s,
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
cx - 150.0,
cx - 10.0,
cx + 10.0,
cx + 150.0,
divider - 3.5
);
if let Some(year) = card.christmas {
let wish = format!("Boldog karácsonyt és csillagos {}!", year_accusative(year));
let ww = width(Face::SerifItalic, &wish, 16.0, 0.0);
let _ = write!(
s,
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><text x="{cx}" y="{}" text-anchor="middle" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="16" fill="{GOLD}">{}</text>"#,
cx - ww / 2.0 - 70.0,
cx - ww / 2.0 - 12.0,
cx + ww / 2.0 + 12.0,
cx + ww / 2.0 + 70.0,
divider + 5.0,
escape(&wish)
);
} else {
let _ = write!(
s,
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
cx - 150.0,
cx - 10.0,
cx + 10.0,
cx + 150.0,
divider - 3.5
);
}
// The message next to the avatar, centred in the room above the code box.
let room_top = divider + 22.0;
@@ -568,6 +636,7 @@ mod tests {
recipient_name: Some("Bea"),
from_name: from,
message,
christmas: None,
}
}
@@ -625,6 +694,22 @@ mod tests {
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
}
#[test]
fn a_christmas_card_wishes_a_happy_new_year() {
let contents = contents();
let plain = svg(&card(&contents, None, None));
assert!(plain.contains("AJÁNDÉKUTALVÁNY") && !plain.contains("karácsony"));
let festive = Card { christmas: Some(2027), ..card(&contents, None, None) };
let svg = svg(&festive);
assert!(svg.contains("KARÁCSONYI AJÁNDÉK") && svg.contains("Boldog karácsonyt és csillagos 2027-et!"));
assert!(svg.contains("mit hoz neked a következő év"));
assert!(pdf(&festive).unwrap().starts_with(b"%PDF-"));
assert_eq!(
[2027, 2028, 2030, 2026, 2032, 2035, 2100, 2000].map(year_accusative),
["2027-et", "2028-at", "2030-at", "2026-ot", "2032-t", "2035-öt", "2100-at", "2000-et"]
);
}
#[test]
fn without_a_message_the_card_still_says_something() {
let contents = contents();
+19
View File
@@ -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
+294
View File
@@ -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<String>,
}
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<Option<Self>, 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<u8>,
content_type: Option<&str>,
) -> Result<reqwest::Response, StorageError> {
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<reqwest::Response, StorageError> {
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<u8>, 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<Option<Object>, 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<Sha256>;
fn hmac(key: &[u8], data: &str) -> Vec<u8> {
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::<Vec<_>>().join("/")
}
fn signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec<u8> {
[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();
}
}
+3
View File
@@ -18,6 +18,9 @@ MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>
# 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
+14 -4
View File
@@ -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}
}
}
}
+37 -3
View File
@@ -102,7 +102,7 @@ services:
USER_INVITES: ${USER_INVITES:-false}
# A new user from a shared link earns the sharer an analysis: off until sign-up opens.
REFERRAL_REWARDS: ${REFERRAL_REWARDS:-false}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-30}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
# Famous people's photos: DigitalOcean Spaces (S3_ACCESS_KEY_ID and
@@ -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:
+8
View File
@@ -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:
+39 -1
View File
@@ -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;
@@ -62,7 +66,7 @@ services:
TERMS_CONSENT: ${TERMS_CONSENT:-false}
# VAT on the invoices: AAM (alanyi adómentes) or a rate like 27%.
INVOICE_VAT: ${INVOICE_VAT:-AAM}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-30}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
# Famous people's photos (S3-compatible storage; the override file
@@ -96,6 +100,8 @@ services:
SMTP_URL: ${SMTP_URL:-}
MAIL_FROM: ${MAIL_FROM:-Sorsfonalak <noreply@sorsfonalak.local>}
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
+22 -5
View File
@@ -7,6 +7,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
## A vásárló: `/ajandek`
- **Hol indul:**
- a főoldal ajándéksávja és a lábléc „Ajándékozás” pontja (nyilvános, lásd Karácsony);
- a Csomagok oldal fő csomagjai alatt az „Ajándékba adom →” link (`/ajandek?csomag=couple`);
- ugyanott az „Ajándékba is adhatod” doboz;
- a fiókmenü „Ajándékozás” pontja.
@@ -17,6 +18,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- **Hogyan kapja meg:**
- „E-mailben küldjük el neki”: a címzett e-mail-címe kétszer, a kettőnek egyeznie kell (a szerver is ellenőrzi);
- „Én adom át”: nincs címzett, a vásárló letölti az utalványt.
- **Mikor kapja meg?** (csak e-mailnél): „Fizetés után azonnal”, vagy „Időzítve” (nap és időpont, a vásárló saját órája szerint, alapból 8:00). Karácsony előtt egy gomb is van: „Karácsony reggel (dec. 24., 8:00)”. Legalább 5 perccel későbbre (a böngésző 10 percet kér), legfeljebb egy évre előre.
- **Személyes üzenet:** legfeljebb 300 karakter, link nélkül (mint a meghívóknál). Rajta van az utalványon és a levélben.
- **Fizetés:** a Stripe-on, mint bármelyik csomagnál; a termék neve „Sorsfonalak – Páros (ajándék)”.
- Az elfogadott szöveg itt más: „…kérem, hogy az ajándékkód beváltásakor a szolgáltatás azonnal megkezdődjön. Tudomásul veszem, hogy a beváltással a 14 napos elállási jog megszűnik.”
@@ -25,6 +27,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- **Fizetés után:** visszatér az **Ajándékaim** oldalra (`/ajandekaim`), ahol a visszaigazolás megmondja, hova ment az ajándék.
- **Visszaigazoló levél** (`purchase_confirmation`):
- azt írja, hogy ajándékba vette, és benne van a kód;
- időzítésnél: „…2026. december 24., 08:00-kor küldjük el ide: …” (magyar idő);
- ha ő adja át, az utalvány PDF-ben csatolva van.
## Ajándékaim: `/ajandekaim`
@@ -33,13 +36,14 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- a csomag, kinek szól, és a vásárlás napja;
- az állapot: „Még nincs beváltva” vagy „Beváltva: dátum”;
- a kód, másolás gombbal;
- kinek ment e-mailben (és hányszor), vagy hogy ő adja át;
- kinek ment e-mailben (és hányszor), vagy hogy ő adja át; időzítésnél „Időzítve: december 24. 8:00, ide: …”, sikertelen küldésnél hibaüzenet;
- a küldő neve és az üzenet.
- **Utalvány letöltése (PDF):** bármikor.
- **Küldés e-mailben:** amíg nincs beváltva.
- Újra ugyanoda, vagy másik címre (elírás); az „Én adom át” ajándékot is el lehet így küldeni.
- A cím itt is kétszer kell.
- Legfeljebb 3 levél ajándékonként, és kettő között legalább 10 perc.
- Időzített, még ki nem ment levélnél a gomb „Küldés most”: a várakozó levelet visszavonja, és azonnal küldi (ez nem számít külön levélnek, és nem kell 10 percet várni). Ugyanígy, ha az első levél még ki sem ment, a javított cím kiváltja.
## A címzett
@@ -53,6 +57,15 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- Könyvelés: egy `package_orders` sor `gift` forrással, 0 Ft-tal (az ár a vásárló fizetésénél van).
- Egy kód egyszer váltható be, és nem jár le.
## Karácsony
- **Az időszak:** november 15. és január 6. között (magyar idő) vett ajándék karácsonyi. A backend a fizetés idejéből számolja (`christmas_year`): novemberben és decemberben a következő év, januárban az aktuális.
- **Az utalványon:** „KARÁCSONYI AJÁNDÉK” felirat, hópelyhek a csillagok helyett, és „Boldog karácsonyt és csillagos 2027-et!” (a toldalékot a `year_accusative` adja). Üzenet nélkül egy karácsonyi szöveg áll rajta.
- **A levélben:** a tárgy „Anna karácsonyi ajándékot küldött neked: …”, a bevezető „Boldog karácsonyt! …”.
- **A `/karacsony` oldal:** a kampány nyitóoldala (a sitemapban is): mit kap (képlet, a következő éve, kapcsolati elemzés), karácsony reggelre időzítés, a három csomag „Ezt adom ajándékba” gombbal. Az éves előrejelzés a születésnaptól egy évre szól; ezt hívjuk itt „a következő évének”.
- **Nyilvános oldalak (a Google is látja):** a `/karacsony` és kijelentkezve az `/ajandek` egy bemutató oldal (`components/GiftLanding.tsx`, egész évben „Horoszkóp ajándékba”); a gombok a belépésen át (`/belepes?vissza=/ajandek?csomag=…`) az űrlapra visznek. Belépve az `/ajandek` az űrlap. Mindkettő a sitemapban van; rájuk linkel a főoldal ajándéksávja és a lábléc „Ajándékozás” pontja (karácsonykor a `/karacsony`-ra). A `/karacsony` Facebook-előnézete a `/kep/karacsony.png`.
- Az időszakban a Csomagok oldal ajándékdoboza a `/karacsony` oldalra visz, a `/ajandek` oldal a karácsonyi mintát mutatja (`public/img/ajandek-karacsony.webp`, `CHRISTMAS=2027`). A frontend ugyanazt az időszakot használja (`lib/season.ts`).
## Az utalvány (PDF)
- **Mi van rajta:** egy A4-es, világos, nyomtatóbarát oldal:
@@ -85,6 +98,9 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
## Admin
- **Időzített levelek** (Admin → Ajándékok, felül, ha van ilyen): óránként (magyar idő), hány levél vár, hány ment ki, hány hibás, az elmúlt 30 napra és előre. Az időpont után figyelni kell, hogy a „Kiment” megnőjön, és ne legyen hiba.
- Soronként is látszik a levél állapota: „levél időzítve · időpont”, „küldés alatt”, „kiment”, „hiba”.
- Visszatérítéskor a még ki nem ment időzített levél törlődik.
- Az ajándékkódok nem jelennek meg az Admin → Promókódok listában; az ajándékok az Admin → Ajándékok oldalon vannak.
## Adatok
@@ -93,6 +109,7 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
- `gifts`: vásárló, csomag, a címzett neve és címe, a küldő neve, üzenet, fizetés ideje, a kód, a beváltás (ki, mikor, melyik rendelés), kiküldött levelek;
- `stripe_checkouts.gift_id`: a fizetés ajándéka;
- `gifts.refunded_at`, `refunded_by`, `refund_id`, `refund_error`: a visszatérítés;
- `gifts.send_at`: az időzítés; `gifts.email_id`: az utolsó sorba állított levél (`email_outbox`; a levél a `next_attempt_at` időpontig vár, a worker 30 másodpercenként néz rá);
- `invoice_cancellations`: a számla sztornója (állapot, próbálkozások, a Billingo sztornószámlája).
- **A kód:** ugyanolyan formájú, mint a promókód (`ABCD-EFGH-JKLM`), és sosem egyezik eggyel sem (mindkét oldal ellenőrzi a másik táblát).
- **Fiók törlése:** az ajándék beváltható marad, de a címzett neve és címe, a küldő neve és az üzenet törlődik.
@@ -102,11 +119,11 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában),
| Végpont | Ki | Mit csinál |
|---|---|---|
| `POST /v1/gifts/checkout` `{package, recipient_name, recipient_email?, recipient_email_confirm?, from_name?, message?}` | belépett felhasználó | ajándék indítása; a válaszban a Stripe-oldal címe (`url`; tesztüzemben `null`, és már ki is fizette) |
| `GET /v1/gifts` | belépett felhasználó | a kifizetett ajándékai |
| `POST /v1/gifts/checkout` `{package, recipient_name, recipient_email?, recipient_email_confirm?, from_name?, message?, send_at?}` (RFC 3339) | belépett felhasználó | ajándék indítása; a válaszban a Stripe-oldal címe (`url`; tesztüzemben `null`, és már ki is fizette) |
| `GET /v1/gifts` | belépett felhasználó | a kifizetett ajándékai (`send_at`, `email_state`, `christmas` is) |
| `GET /v1/gifts/{id}/card.pdf` | a vásárló | az utalvány |
| `POST /v1/gifts/{id}/send` `{recipient_email, recipient_email_confirm}` | a vásárló | küldés e-mailben (újra, vagy másik címre) |
| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | promókód vagy ajándékkód beváltása; ajándéknál `gift: {from_name}` is |
| `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email}` is |
| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval |
| `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email, send_at}` is |
| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval, a levél állapotával; `schedule`: az időzített levelek óránként |
| `POST /v1/admin/gifts/{id}/refund` | admin | visszatérítés (csak beváltatlan ajándéknál; újrapróbálható, ha a Stripe visszautasította) |
+14 -11
View File
@@ -10,29 +10,32 @@ Egy részletes képletelemzés és egy kapcsolati elemzés is kb. **$0,21 (≈ 8
| Csomag | Tartalom | Ár | Elemzésenként | Külön megvéve | Megtakarítás |
|---|---|---|---|---|---|
| Egy elemzés | 1 képletelemzés, 3 kérdés, 2 kártyajóslás | 2 000 Ft | 2 000 Ft | – | – |
| Páros | 2 képletelemzés, 2 éves előrejelzés, 1 kapcsolati, 1 személy, 3 kérdés, 5 kártyajóslás | 6 000 Ft | 1 200 Ft | 11 800 Ft | 49% |
| **Család** (Legnépszerűbb) | 6 képletelemzés, 6 éves előrejelzés, 5 kapcsolati, 5 személy, 3 kérdés, 10 kártyajóslás | 11 000 Ft | 647 Ft | 41 000 Ft | 73% |
| +1 kapcsolati elemzés | kiegészítő | 2 500 Ft | | | |
| +1 éves előrejelzés | kiegészítő | 2 500 Ft | | | |
| +5 személy | kiegészítő | 1 500 Ft | | | |
| Egy elemzés | 1 képletelemzés, 1 éves előrejelzés, 3 kérdés, 2 kártyajóslás | 2 000 Ft | 1 000 Ft | 3 500 Ft | 43% |
| Páros | 2 képletelemzés, 2 éves előrejelzés, 1 kapcsolati, 3 kérdés, 5 kártyajóslás | 3 500 Ft | 700 Ft | 8 500 Ft | 59% |
| **Család** (Legnépszerűbb) | 6 képletelemzés, 6 éves előrejelzés, 5 kapcsolati, 3 kérdés, 10 kártyajóslás | 7 000 Ft | 412 Ft | 28 500 Ft | 75% |
| +1 kapcsolati elemzés | kiegészítő | 1 500 Ft | | | |
| +1 éves előrejelzés | kiegészítő | 1 500 Ft | | | |
| +5 kérdés | kiegészítő | 1 000 Ft | | | |
| +5 kártyajóslás | kiegészítő | 1 000 Ft | | | |
A „külön megvéve” ár egységárakból jön: képletelemzés 2 000 Ft, kapcsolati elemzés 2 500 Ft, éves előrejelzés 2 500 Ft, személy 300 Ft (`NATAL_PRICE`, `SYNASTRY_PRICE`, `FORECAST_PRICE`, `PERSON_PRICE`).
Az árak 2026. november 24. óta érvényesek (előtte: Egy elemzés 2 000 Ft előrejelzés nélkül, Páros 6 000 Ft 1 személyhellyel, Család 11 000 Ft 5 személyhellyel, a kapcsolati és az előrejelzés kiegészítő 2 500 Ft, +5 személy 1 500 Ft).
**Személyek:** 2026. november 24. óta ingyenesek, felhasználónként 30-ig (`FREE_PERSON_SLOTS`). A képletük és a rövid összefoglalójuk ingyenes (az összefoglaló kb. 4 Ft), fizetni a részletes elemzésért és az előrejelzésért kell; így a felvett családtagok inkább elemzésvásárlásra ösztönöznek. A 30 egy plafon a tömeges (pl. gépi) felvétel ellen: aki többet kér (a határnál a Visszajelzés oldalra küldjük), annak az admin ad személyhelyet vagy korlátlan jogosultságot. A „+5 személy” kiegészítőt kivettük (`RETIRED`: a régi rendelések és a még folyamatban lévő fizetések miatt ismert marad, de nem vehető).
A „külön megvéve” ár egységárakból jön: képletelemzés 2 000 Ft, kapcsolati elemzés 1 500 Ft, éves előrejelzés 1 500 Ft (`NATAL_PRICE`, `SYNASTRY_PRICE`, `FORECAST_PRICE`).
A kérdések (2026 novembere óta) minden csomagban ráadásként járnak (`QUESTIONS_INCLUDED` = 3), a „külön megvéve” árban és a megtakarításban nem szerepelnek. Egy kérdés a kész képletelemzésre vagy éves előrejelzésre vonatkozik, a választ ugyanaz a modell írja, amelyik az elemzést (legfeljebb 250 szó); költsége kb. $0,04–0,07 (15–25 Ft). Részletek: `docs/kerdesek.md`.
A kártyajóslások (2026 novembere óta) szintén ráadásként járnak (Egy elemzés 2, Páros 5, Család 10), a megtakarításban nem szerepelnek. Részletek: `docs/kartyajoslas.md`.
Az éves előrejelzés (2026 novembere óta) a Páros és a Család csomagban mindenkinek benne van; külön megvéve drágább, mint egy képletelemzés. Az Egy elemzés csomag változatlanul egy képletelemzés 2 000 Ft-ért. Részletek: `docs/elorejelzes.md`.
Az éves előrejelzés mindhárom csomagban benne van (az Egy elemzésben 2026. november 24. óta); külön 1 500 Ft. Részletek: `docs/elorejelzes.md`.
## Miért így (a nagyobb felé terelés)
- **Horgony:** az Egy elemzés ára (2 000 Ft) az egységár. Minden más ehhez mérve látszik olcsónak; a kártyákon áthúzva ott a „külön megvéve” ár.
- **Kis lépések, nagy ugrások:** minden szint csak egy kicsivel drágább az előzőnél, de sokkal többet ad. Páros: +4 000 Ft-ért ötször annyi elemzés. Család: +5 000 Ft-ért több mint háromszor annyi. A kártyán ki is írjuk: „Csak +5 000 Ft a Páros csomaghoz képest”.
- **Csali:** a Páros szándékosan „csak jó” ajánlat (−49%), hogy mellette a Család (−73%) kiugorjon. A Család kapja a kiemelést és a „Legnépszerűbb” címkét.
- **Drága kiegészítők:** a +1 kapcsolati elemzés és a +1 éves előrejelzés 2 500 Ft, többe kerül, mint egy képletelemzés, és a Páros alig kétszer ennyiért ad egyet, kettőtök képletével együtt. Aki darabonként venne, annak jobban megéri csomagot venni.
- **Kis lépések, nagy ugrások:** minden szint csak egy kicsivel drágább az előzőnél, de sokkal többet ad. Páros: +1 500 Ft-ért 2,5-szer annyi elemzés. Család: +3 500 Ft-ért több mint háromszor annyi. A kártyán ki is írjuk: „Csak +3 500 Ft a Páros csomaghoz képest”.
- **Elemzésenként:** 1 000 Ft → 700 Ft → 412 Ft; megtakarítás 43% → 59% → 75%. A Család kapja a kiemelést és a „Legnépszerűbb” címkét.
- **Kiegészítők:** a +1 kapcsolati elemzés és a +1 éves előrejelzés 1 500 Ft.
- **A vásárlás pillanatában** (a „Részletes elemzés kérése” után) nem egy darabot kínálunk, hanem három csomagot egymás mellett, kiemelt Családdal.
- **Nem jár le:** a megvett elemzések megmaradnak, ezért a nagyobb csomag nem kockázat a vevőnek.
+449
View File
@@ -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` → ❤️, `</3` → 💔.
- Csak az önálló kód alakul át, így a linkek változatlanok maradnak.
- **Színes emojik:** a fórum betűtípus-sorában ott vannak a rendszer színes emojibetűi (Apple, Segoe, Noto Color Emoji).
### Ami elkészült (6. kör)
- **Új dizájn:** saját reakcióikonok, tömörebb hozzászólások, a kérdés (a nyitó hozzászólás) külön kártyán, a válaszok a lapon. A szövegdoboz feletti meghallgatós emlékeztető kikerült; a cím alatti „Csak meghallgatást kér” jelzés maradt.
- **Jelvények ikonnal:** minden rangnak saját ikonja van (Vándor: ösvény, Kereső: iránytű, Fonó: orsó, Csillagfonó: csillag fonallal, Sorsfonó: a sorsfonal köre; a magasabb rangoké arany). Ikont kapott a Moderátor (pajzs), a Kísérő (két alak), a Támogató (drágakő), a Szálindító (toll) és a napi égbolt (holdsarló) is.
- **Kinek válaszolsz:** a válaszok legfeljebb két szint mélyek (az eredeti hozzászólás és alatta a válaszok). Ha valaki egy válaszra válaszol, az ugyanoda kerül, de a neve mellett látszik, kinek szól: „↪ Holdfény” (`posts.reply_to_id`, 0042).
- **Napi „Mai égbolt” szál:** a worker reggel 5 órától nyitja meg az „Égbolt és képletek” témában, a backend nyilvános égboltjából (a Hold jegye és fázisa, jegyváltás, retrográd bolygók, a következő holdfázis), kötött magyar mondatokkal, AI nélkül. Egy napig ki van tűzve; a szerzője „Sorsfonalak”.
- **Önkéntes kísérők** (a Kereső rangtól; eredetileg „meghallgató”, a felhasználó átnevezte): „Kísérő” jelvény; a fórum főoldalán, a saját kártyájukon látják, hány meghallgatást kérő szál vár válaszra; e-mail, ha egy szál két órája vár (ha kérik, legfeljebb hatóránként egy).
- **Említés:** „@Holdfény” (szóközös álnévvel is). Az említett tag követni kezdi a szálat, élőben és (ha kéri) e-mailben is értesül. Gépelés közben ajánló segít, az említés link a profilra.
- **Saját avatar** a Kereső rangtól: 256×256-os JPEG lesz belőle, a kép rejtett adatai (EXIF) nélkül, a backenddel közös tárolóban (`crates/object-storage`, `forum-avatars/`). A moderátor visszaállíthatja a kezdő avatart. A fiók törlésekor a kép is törlődik.
- **„Támogató” jelvény:** csak vásárlóknak, és csak ha bekapcsolják. Rangot nem ad.
- **Zárt témák:** az admin a Moderálás → Témák fülön hoz létre és szerkeszt témát. A zárt témába a tag pár szóval jelentkezik, egy moderátor jóváhagyja vagy elutasítja, és később el is távolíthatja. Az elutasított jelentkezés azonnal törlődik (a moderálási naplóban marad nyoma).
- **Csak tagoknak szóló témák:** a téma oldalán és a szál morzsamenüjében belépve is látszik, hogy kívülről és a keresőkből nem olvasható.
- **„Most itt vannak”** a főoldal oldalsávjában (a láthatatlan módú tagok nélkül).
- **Heti összefoglaló e-mail:** vasárnap este, a hét legélénkebb szálaival és a válaszra várókkal. Alapból ki van kapcsolva, az e-mail-értesítések között kapcsolható be.
- **Jogi szövegek:** az adatkezelési tájékoztató (magyar és angol) és az ÁSZF 8.1 pontja kiegészült (saját kép, jelvények, említések, zárt témák, heti összefoglaló). Az adatexport ezeket is tartalmazza.
### Ami elkészült (7. kör)
- **Egyetlen jelzés a menüben:** a „Válaszok” fül száma azt mutatja, hány olvasatlan válasz érkezett neked: valaki a hozzászólásodra vagy a száladban válaszolt, vagy megemlített. A lista a `/forum/valaszok` oldalon van, „Mind olvasott” gombbal; a követett szálak ennek második nézete. A kísérők a főoldali saját kártyájukon látják, hány szál vár első válaszra.
- **Válasz a 2. szinten:** a szövegdoboz az ág aljára kerül; másik ágra kattintva átkerül oda, a félig megírt szöveg megmarad.
- **Mobil billentyűzet:** gépelés közben eltűnik a fórum alsó menüje, és a szövegdoboz a küldés gombbal együtt a billentyűzet fölé görgetődik (`KeyboardSafe`, az egész oldalon).
- **„Kísérő”** lett a „Meghallgató” jelvény neve.
### Ami elkészült (8. kör)
- **Oldaltérkép:** a nyilvános témák és szálak bekerültek a `sitemap.xml`-be; a fórum saját oldalait (beállítások, üzenetek, válaszok, keresés stb.) a `robots.txt` kizárja.
- **Keresés** (`/forum/kereses`, nagyító a fórum fejlécében): szálcímek és hozzászólások abból, amit a látogató olvashat. Magyar szótövezés, és ékezet nélkül, szókezdetre is talál („alvas” → „alvásban”). Szálanként egy találat, kiemelt szavakkal. Az elnémított tagokat kihagyja.
- **Némítás** (hozzászólás ⋯ menüje, profil; a lista a beállításokban): az elnémított tag szálai eltűnnek a listákból, a hozzászólásai összecsukva látszanak, a válaszai és említései nem számítanak és nem küldenek e-mailt. Ő erről nem tud.
- **Archiválás** (admin, Moderálás → Témák): a téma olvasható marad, de új szál és válasz nem írható bele; a főoldalon összecsukva, „Archivált témák” alatt látszik.
- **Kérdés a saját képletről:** a képlet, az éves előrejelzés és az összevetés oldalán „Kérdezek róla a fórumon” gomb. Egy ablak elmondja, mi kerül ki, aztán az oldal fórumos megosztó linket készít (`shares.for_forum`: soha nincs benne születési adat, név vagy cím), és új szálat nyit az „Égbolt és képletek” témában, a linkkel csatolva.
- A hozzászólásban kártya: Nap, Hold, Aszcendens jeggyel, fokkal és házzal, a rövid összefoglaló címe, és „Megnyitom” a megosztó oldalra. Csak belépett tagok látják; a látogatók és a keresők csak annyit, hogy van csatolt képlet.
- A szerző leveheti („Képlet levétele”); ha törli a kérdést, a link is megszűnik.
- A megosztó oldal (`/s/…`) mostantól az összevetést (közös kerék, fényszögek, nevek nélkül) és az éves előrejelzést (kulcsok, idővonal, tranzitok, a részletes szöveg, a születésnapi helyszín nélkül) is megmutatja.
- **A válasz-e-mail** a második szinten annak megy, akinek valóban válaszoltak.
- **Adatvédelem:** a tájékoztató (magyar és angol) kiegészült a csatolt képlettel és a némítással.
### Ami elkészült (9. kör)
- **Kitalált tartalom helyben** (csak a helyi adatbázisban): 30 tag 18–70 év között, valódi képlettel és kézzel írt tömör elemzéssel, 20 szál, 139 hozzászólás. A szkriptek a munkamenet ideiglenes mappájában vannak, nem a repóban; élesre nem kerülhet.
- **Alapító tag:** az első 15 tag jelvénye, véglegesen; az admin a profilon elveheti (például próbafióktól) vagy megadhatja, a felszabaduló hely a következő új tagé.
- **Link-modul** (`services/forum/src/links`): a hozzászólásokban felismeri a linkeket, és amit egy szolgáltató ismer, ahhoz előnézetet mutat. Most a YouTube: cím, csatorna, és a bélyegkép a saját tárolónkban (`forum-links/`), így a fórum olvasásakor semmi nem töltődik a YouTube-ról. Gépen a kártyára kattintva ott helyben lejátssza (youtube-nocookie.com), telefonon a YouTube alkalmazást nyitja (Androidon intenttel, a weboldal a tartalék), és ott is van „Lejátszás itt”. Az előnézet íráskor és szerkesztéskor készül; ha nem sikerül, a link sima szöveg marad. Új szolgáltatót a `links/` alá lehet tenni.
- **„Élénk beszélgetések”** lett a „Pörgős most”.
### Élesítéskor
- **Turnstile (Cloudflare captcha)** az e-mailes regisztrációra és az elfelejtett jelszó űrlapra, mellé egy gépenkénti korlát a szerveren: élesítés előtt meg kell csinálni (a Cloudflare-felületen létre kell hozni a widgetet; a kulcs az `.env`-be, a titok a `.env.secrets`-be).
- `FORUM_URL=http://forum:8083` az éles `.env`-be.
- Az adatvédelmi tájékoztató dátumát (`PRIVACY_UPDATED` és `PRIVACY_UPDATED_EN` a `legal.ts`-ben) szintén az élesítés napjára kell írni.
- Az ÁSZF hatálybalépési dátumát (`TERMS_UPDATED` a `services/frontend/src/lib/legal.ts`-ben és `TERMS_VERSION` a `services/backend/src/routes/payments.rs`-ben) az élesítés napjára kell átírni, ha az nem 2026. november 26.
- Ha közben a `main`-re új migráció került, a fórumé (0038–0045) ütközhet vele, és át kell számozni. A 0043 az `unaccent` bővítményt is létrehozza (megbízható bővítmény, az adatbázis tulajdonosa létrehozhatja).
- A fórum szolgáltatásnak kell az `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION` (az éles `.env`-ben, ugyanaz, mint a backendé) és a kulcsok (`.env.secrets`); a workernek a `BACKEND_URL` (a compose fájlban már benne van).
### Ami még hátravan
- **Hírlevél:** az oldalnak még nincs hírlevele. Ha lesz, külön, kifejezett hozzájárulással, nem a fórum beállításai között.
- **AI-funkciók:** egyelőre nem kellenek (előszűrés, krízisjelzés, összefoglaló a főoldalon).
## Cél
A régi fórumok hangulata: mély beszélgetések, törzsgárda, valódi párbeszéd. Az emberek **beszélgessenek egymással**, főleg azok, akik meghallgatásra vágynak. A téma a spiritualitás, de nem csak asztrológia, és nem csak a horoszkópokból indul ki. Ha a közösség működik, a fizetős horoszkóp a háttérbe kerülhet.
Ne videónézegető közösség legyen: **elsősorban szöveg**, a média visszaszorítva.
## Alapelvek
- **Tartós álnév:** mindenki álnéven ír, ami nem változik naponta, így felépül a bizalom.
- **Időrend, algoritmus nélkül.**
- **Kevés téma az elején,** hogy a fórum ne tűnjön üresnek.
- **Az AI soha nem szól hozzá tagként.** Lehet moderátor vagy háttérsegéd, de aki meghallgatást kér, annak ember válaszol. (javaslat)
## Témák és láthatóság
Témák (javaslat):
- **Ami a szívemen van** – meghallgatás, élethelyzetek
- **Belső utak** – spiritualitás, meditáció, megélések (az elején az **Álomnapló** is ide tartozhat)
- **Égbolt és képletek** – asztrológia, megosztott elemzésrészletek
- **Törzsasztal** – bármi más
A fórum **nyilvános**. A Reddit mintájára lehetnek zárt terek is, ahová jelentkezni kell. A láthatóság a téma tulajdonsága, három szinttel (javaslat):
| Szint | Olvasás | Írás | Kereső |
|---|---|---|---|
| Nyilvános | bárki | belépett tag | indexeli |
| Csak tagoknak | belépett tag | belépett tag | nem indexeli |
| Zárt | jóváhagyott tag | jóváhagyott tag | nem indexeli |
Az **Ami a szívemen van** csak tagoknak szól, mert egy álnév kevésbé véd, mint gondolnánk: a részletekből az ismerősök felismerik az írót, és a Google évekig őrzi a szöveget. (javaslat)
## Szálak és hozzászólások (javaslat)
- Szálazott válaszok, két szint mélységig, idézéssel.
- **„Az utolsó látogatásod óta”** jelölés szálanként, és egy link, ami az első olvasatlan hozzászólásra ugrik.
- A szál indítója jelöli, mit kér: **csak meghallgatást** vagy **tanácsot / véleményt**.
- Megosztott AI-elemzésrészlet mellé kötelező legalább néhány mondat saját gondolat.
- Naponta automatikus **„Mai égbolt”** szál, újhold- és teliholdszál, ami utána archiválódik.
## Meghallgatás (javaslat)
- **„Még senki nem válaszolt”** lista, a legrégebbi felül.
- **Önkéntes kísérők** (korábban „meghallgatók”): szerepkör jelvénnyel, értesítést kapnak, ha egy szál néhány órája válasz nélkül áll.
## Értékelés és reakciók
A **„B” változat**: a reakció maga az értékelés.
- Négy rögzített reakció, mindegyik +1 pont: 🤍 *Veled vagyok*, 🙏 *Köszönöm*, ✨ *Rám is igaz*, 💡 *Érdekes gondolat*. A készlet később bővíthető, de tetszőleges emojival nem lehet reagálni.
- Mellette egy diszkrét **⌄** („nem visz előre”), ami −1. A meghallgató témákban nem jelenik meg, és csak egy bizonyos rangtól használható. (javaslat)
- A sok mínuszt kapott hozzászólás nem tűnik el, csak összecsukódik („kattints a megjelenítéshez”). (javaslat)
- A szál indítója hozzászólásonként egyszer adhat **„Ez segített”** jelölést, ami többet ér, pl. +5. (javaslat)
## Rangok és szerepkörök
A rang az értékelésekhez kötődik, de nem csak azokból jön (javaslat):
- pontok az értékelésekből és az „Ez segített” jelölésekből;
- tagság ideje és aktív napok száma, ami lassítja a felkapaszkodást;
- moderálási figyelmeztetések, amik visszavetnek.
Csalás ellen (javaslat): saját magára senki nem szavazhat, a friss tagok szavazata eleinte nem számít a rangba, és figyelni kell a folyton egymást értékelő fiókokra.
Rangnevek (javaslat): *Vándor → Kereső → Fonó → Csillagfonó → Sorsfonó*. A rang neve nyilvános, a pontszámot csak a tag látja.
A rang egyben **jogosultsági szint** is: ettől függ, ki küldhet privát üzenetkérést, ki tölthet fel saját avatart, ki tehet be linket, és ki használhatja a ⌄ jelet.
**A kezdő (Vándor) is nyithat szálat és hozzászólhat**, mert lehet, hogy épp segítségre van szüksége. A hozzászólásai nem várnak moderátori jóváhagyásra. **Privát üzenetet viszont nem kezdeményezhet.** Ha valaki más kérést küld neki, azt elfogadhatja. (az elfogadás javaslat)
A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderátor, kísérő, támogató.
### Vásárlás és rang
**A csomagvásárlás nem ad rangot.** A rang bizalmat jelent, ezért pénzért nem járhat, és a csalóknak is megérné egy olcsó csomagért hamarabb privát üzenetet írni. Helyette:
- **Feloldja a kezdő korlátokat** (napi hozzászólásszám, a szavazat beszámítása), mert aki fizetett, az szinte biztosan valódi ember. Privát üzenetkéréshez továbbra is rang kell.
- **„Támogató” jelvény,** amit a tag maga dönt el, hogy kiteszi-e. Alapból rejtve.
## Profil és álnév
- **Álnevet kötelező választani** az első hozzászólás, reakció vagy szálindítás előtt. Olvasni álnév nélkül is lehet.
- Az álnév soha nem a Google- vagy Apple-fiók nevéből jön, és az oldal fel sem ajánlja. Egy rövid figyelmeztetés: „Ne a valódi neved legyen, ha nem szeretnéd, hogy felismerjenek.”
- Az álnév szabályai (javaslat):
- **egyedi**, kis- és nagybetűtől, ékezettől és hasonló kinézetű betűktől függetlenül;
- **foglalt nevek** (admin, moderátor, sorsfonalak stb.) nem választhatók;
- **30 naponta** egyszer módosítható, és a régi nevet egy ideig más nem kaphatja meg.
- **Bemutatkozás:** rövid szöveg, kb. 500 karakter, emojival, link nélkül. (a hossz és a link javaslat)
- **A horoszkópjából a tag választja ki, mit oszt meg.** Lépcsők (javaslat): semmi / Nap-jegy / Nap, Hold, Aszcendens (ez a név mellett is látszik) / az összes bolygó jegyekben / a rövid AI-összefoglaló.
- **Pontos fokokat nem mutatunk,** mert azokból visszaszámolható a születési dátum, az idő és nagyjából a hely. (javaslat)
- Magától látszik a profilon (javaslat): rang, szerepkörök, csatlakozás ideje, hozzászólások száma, utolsó aktivitás durván, legutóbbi hozzászólások (a csak tagoknak szóló témákból kívülállónak nem), „Beszélgetést kezdeményezek” gomb.
## Avatar
- Egyelőre **egy** avatarja van mindenkinek.
- **Kezdő készlet:** néhány tucat generált kép. SVG-ben, a márka színeivel (holdfázisok, csillagképek, növények, szimbólumok), így tárolni sem kell őket. (az SVG javaslat)
- **Saját kép:** a DO Spacesbe kerül, a meglévő `services/backend/src/storage.rs` mintájára (privát tároló, a szolgáltatás adja ki, a Cloudflare tartja gyorsítótárban). Csak egy rang fölött tölthető fel, a moderátor egy kattintással visszaállíthatja. Feltöltéskor csak az első képkocka marad meg, animált avatar nincs. (javaslat)
## Média
- **GIF nincs.**
- **Emoji van,** a hozzászólásokban is: a telefon emojibillentyűzete, és a régi fórumos karakterkódok (`:)`, `<3` stb.) gépelés közben emojivá alakulnak. Külön emojiválasztó nincs.
- **Videó** nem játszódik le helyben, a link sima szöveges linkként jelenik meg, előnézet nélkül. (javaslat)
- **Kép:** az elején nincs, később hozzászólásonként legfeljebb egy, rang fölött, kis méretben. (javaslat)
- Az aláírás csak szöveg lehet. (javaslat)
## Privát üzenetek
Kellenek, de az első verzió egyszerű legyen. **Előbb kérést kell küldeni,** nem lehet csak úgy ráírni valakire.
Javasolt első verzió:
1. **Kérés:** a profilon egy „Beszélgetést kezdeményezek” gomb, hozzá legfeljebb 200 karakteres bemutatkozás, link és kép nélkül.
2. **A címzett dönt:** elfogad, elutasít vagy letilt.
3. **Az elutasítás csendes:** a küldő nem kap róla értesítést, a kérés 14 nap után lejár.
4. **Elfogadás után** kettes beszélgetés: szöveg és emoji, kép nincs, a link nem kattintható.
Visszaélés ellen:
- kérést csak az küldhet, aki elért egy rangot és írt már nyilvánosan;
- naponta legfeljebb 3 nyitott kérés;
- a letiltott tag nem küldhet újabb kérést.
A moderátor csak jelentés után látja a beszélgetést, és ezt az adatvédelmi tájékoztatónak is tartalmaznia kell.
Később: csoportos beszélgetés, „gépel…” jelzés, olvasási visszaigazolás.
## Értesítések
- **Beállítási oldal,** ahol típusonként ki-be kapcsolható, ki miről kér értesítést, és a hírlevél is.
- **Az oldalon belül WebSocketen** jelez, ha egy másik szálban válasz érkezett.
- **Web push egyelőre nem kell.**
Típusok és alapértékek (javaslat):
| Esemény | Az oldalon | E-mail |
|---|---|---|
| Válasz a hozzászólásomra | be | napi összesítő |
| Új hozzászólás egy követett szálban | be | ki |
| Megemlítettek (@álnév) | be | azonnal |
| Válasz nélküli szál (kísérőknek) | be | ki |
| Heti összefoglaló | – | ki |
| Hírlevél | – | ki |
A hírlevélhez a reklámtörvény szerint kifejezett, előzetes hozzájárulás kell, ezért alapból kikapcsolt, külön kapcsolóval.
## Online jelenlét
- **Zöld pötty** az avatar mellett, ha a tag az elmúlt 5 percben aktív volt.
- **„Most itt vannak” lista** csak később, ha nagyobb lesz a forgalom.
- **Láthatatlan mód** a beállításokban, és az „utoljára itt” csak durván látszik („ma”, „ezen a héten”). (javaslat)
## Moderáció
- **A moderátorokat az admin jelöli ki.**
- **Szerepkörök:** admin, moderátor (az egész fórum), témamoderátor (csak a saját témája). (a témamoderátor javaslat)
- **A moderátor jogai:** hozzászólást és szálat törölhet, néhány órára vagy napra eltilthat, és véglegesen is kitilthat.
- Kiegészítő eszközök (javaslat): áthelyezés, szál lezárása, kitűzés, figyelmeztetés, tag jóváhagyása zárt témába.
- **A törlés valójában elrejtés** (javaslat):
- A helyén egy sor marad: „A moderátor eltávolította (ok: …)”, így a szál olvasható marad.
- Az admin visszaállíthatja, és a tartalom egy ideig megmarad bizonyítéknak.
- A szerző értesítést kap az okkal, mert ezt a DSA előírja. Fellebbezni a meglévő visszajelzés-oldalon lehet.
- **Eltiltás:** az eltiltott tag olvashat, de nem írhat, nem reagálhat és nem küldhet privát üzenetet. Látja, meddig tart az eltiltás. (javaslat)
- **Kitiltás:** csak a fórumra vonatkozik, a megvásárolt horoszkópszolgáltatásokat nem érinti, hiszen azokért fizetett. (javaslat)
- **A moderátor határai:** nem tilthat ki másik moderátort vagy admint, és minden lépését az admin visszacsinálhatja. (javaslat)
- **Moderálási napló:** ki, mit, miért, és hogy **ember vagy AI** tette. Ez a DSA miatt is kell, mert eltávolításkor meg kell adni az okot. (javaslat)
- **AI később:** először csak jelöl és sorba állít, ember dönt. Ha bevált, egyértelmű esetekben (spam, hirdetés) önállóan is dönthet. A DSA szerint az érintettnek tudnia kell, ha automatikus eszköz döntött. (az ütemezés javaslat)
- **Lelki krízis** (javaslat): ha egy hozzászólás komoly bajra utal, az AI jelöli, a szerző mellett megjelenik a lelki elsősegély száma (116-123), és az admin értesítést kap.
- **Szolgáltatást hirdetni tilos:** jóslást, energetikai gyógyítást, tanfolyamot nem lehet árulni. (javaslat)
- **DSA-követelmények:** bejelentési lehetőség, kapcsolattartási pont, indoklás az eltávolításhoz, és ezekhez az ÁSZF bővítése.
## Főoldal
Kell hozzá dizájn. Ami biztos: a **legpörgősebb szálak**, és ha van valami **napi aktuális**, az. A többi javaslat.
Mobilon, fentről lefelé (javaslat):
1. **„Mióta nem jártál itt” sáv:** csak visszatérőknek, pl. „5 új válasz a követett szálaidban”.
2. **Mai égbolt kártya:**
- holdfázis, a nap fő égi eseménye egy mondatban, és link a napi szálra a hozzászólások számával;
- **mindig van tartalma**, mert az AI generálja, így a főoldal az induláskor sem üres;
- később a belépett tagnak egy személyes sor is: „Nálad most…”.
3. **AI-összefoglaló és ajánló** (felmerült ötlet, még nincs kidolgozva):
- **„Tegnap a fórumon”:** két-három mondat a nyilvános témák beszélgetéseiről;
- **„Neked ajánljuk”:** két szál, mellettük az ok, pl. „mert ezt a témát követed”, később „a te Napodat is érinti”;
- **adatvédelem:** csak a nyilvános témákból készül, az „Ami a szívemen van” témát nem olvassa, tagot nem idéz és nem nevez meg;
- **AI-címke:** jól láthatóan AI-összefoglalóként van jelölve. Nem tagként szól, így nem ütközik azzal az elvvel, hogy az AI nem szól hozzá a beszélgetésekhez.
4. **Várják a válaszod:** 1–3 válasz nélküli szál, finoman kiemelve. A meghallgatás elve miatt ez közel van a tetejéhez.
5. **Élénk beszélgetések** (korábban „Pörgős most”):
- az utóbbi 24 óra legélénkebb szálai, a válaszok és a résztvevők száma szerint;
- átlátható, felcímkézett sorrend, nem rejtett algoritmus;
- amíg kevés a forgalom, nem jelenik meg.
6. **Témák:**
- témánként az új hozzászólások száma és a legutóbbi hozzászóló avatarja online pöttyel;
- a témán belül a sorrend időrendi.
7. **Alsó navigációs sáv.**
Aki nincs belépve, annak az oldal tetején egy rövid bemutatkozás jelenik meg: miről szól ez a hely, és egy belépés gomb.
Az a szakasz, amihez nincs elég tartalom, nem jelenik meg. Az üres doboz kihaltnak mutatja a fórumot.
## Mobil
**A legtöbben telefonról írnak, ezért a modulnak elsősorban mobilon kell jól működnie.** A tervezés is a telefonnal kezdődjön. (a részletek javaslatok)
- **Alsó navigációs sáv:** Témák · Értesítések · Üzenetek · Profil.
- **Nagy gombok és betűk az 50+ korosztálynak:** legalább 44 px-es koppintási felület, legalább 17 px-es szöveg. A reakciógombok mindig látszanak, nem kell hozzájuk hosszan nyomni.
- **Szálak:** a két szint mélység mobilon még olvasható. Mélyebb válaszlánc helyett idézés, és az ágak összecsukhatók.
- **Szövegdoboz** a képernyő alján, ami a billentyűzettel együtt mozog. Emojinak a telefon billentyűzete elég, a külön emojiválasztó főleg asztali gépre kell.
- **WebSocket a telefonon:** a háttérbe tett lapot a telefon felfüggeszti. Amikor a lap újra előtérbe kerül, újracsatlakozik, és lekéri, mi történt közben. A csengős felépítés ezt külön munka nélkül kezeli.
- **Később PWA:** a fórum ikonként a kezdőképernyőre tehető, push nélkül.
## Architektúra
A fórummotor **külön szolgáltatás**, hogy később, például Kubernetesen, külön lehessen skálázni. Ez a WebSocketet nem nehezíti meg, ha a WebSocket csak csengőként működik. (a részletek javaslatok)
- **`services/forum`:** külön program, axum. Ugyanabban a Postgresben fut, de saját sémában (`forum.*`), saját adatbázis-felhasználóval, korlátozott jogokkal.
- **Belépés:** ugyanabból a `sessions` táblából ellenőrzi, mint a backend. Ezt a kódot közös crate-be kell kiemelni, így egy belépés elég mindkettőhöz.
- **A WebSocket csak jelez:** pl. „új válasz a 123-as szálban”. A tartalmat a böngésző REST-en kéri le. Újracsatlakozáskor megkérdezi: „mi történt X óta?”. Így egy pod bármikor újraindítható, és semmi nem vész el.
- **Több példány esetén** minden példány egy Postgres LISTEN/NOTIFY csatornát hallgat (`forum_events`), és a saját kapcsolatainak továbbítja az eseményeket. A worker már most is így kapja az e-maileket. Redis nem kell, és ha egyszer szükséges, a csatorna kicserélhető NATS-ra vagy Redisre.
- **Online pötty:** a kapcsolat legfeljebb percenként frissíti a `last_seen` mezőt, így minden példány ugyanazt látja.
- **Buktatók:**
- A Next.js `/api/v1` proxy WebSocketet nem tud továbbítani, ezért a `/ws` útvonalat a frontend előtti proxyban kell közvetlenül a fórumszolgáltatásra irányítani.
- A Cloudflare kb. 100 másodperc tétlenség után bontja a kapcsolatot, ezért 30 másodpercenként szívverés-üzenet kell.
## Később
- **„Nálad is most van”:** tagok, akiknél most ugyanaz a tranzit zajlik, és amit megéléseikről írtak. Ehhez tranzitszámítás és a tagok összepárosítása kell.
- **Képlettestvérek:** szálak azonos Hold-jegyűektől vagy Aszcendensűektől.
- **Csillagszülinap:** az oldal felköszönti a tagot a Nap-visszatérésén. **Csak kifejezett engedéllyel,** mert elárulja a születésnapot.
- **Élő Tranzit-szoba:** időhöz kötött élő beszélgetés újholdkor és teliholdkor, ha már elég ember van hozzá.
## AI-szereplők? (bizonytalan)
Felmerült, hogy „cuki” AI-robotok néha beszóljanak a beszélgetésekbe. Még nincs eldöntve. Ha lesz, ezek a keretek (javaslat):
- **Egy kabalafigura,** nem több robot. Jól láthatóan **AI**-ként jelölve: az EU AI Act 2026 augusztusa óta előírja, hogy az ember tudja, ha géppel beszél.
- **Soha nem az „Ami a szívemen van” témában,** és soha nem válaszol elsőként egy meghallgatást kérő szálra.
- **Bejelentésekkel és köszöntésekkel kezdene:** megnyitja a napi égbolt-szálat, köszönti az újholdat, gratulál a századik hozzászóláshoz, üdvözli az új tagokat egy külön üdvözlő szálban.
- **Korlátok:** ritkán szólal meg, nem szavaz, és nem kap rangot.
- **Bővítés csak bizonyítás után:** csak ha ez bevált, szólhat hozzá beszélgetésekhez is, és akkor is csak könnyed témákban (Törzsasztal, Égbolt).
## Nyitott kérdések
- **AI-kabala:** legyen-e, és mit csináljon.
- **A főoldal dizájnja** (a szerkezet fent, javaslatként).
- **A rangok határai** és a pontértékek.
- **A kezdő korlátok** pontos számai (napi hozzászólás, a szavazat mikortól számít).
+1
View File
@@ -11,6 +11,7 @@ db.workspace = true
analysis-prompt.workspace = true
email-templates.workspace = true
gift-card.workspace = true
object-storage.workspace = true
hmac.workspace = true
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
rand.workspace = true
+2 -2
View File
@@ -15,7 +15,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| `SESSION_TTL_DAYS` | `30` | a munkamenet élettartama |
| `PASSWORD_LOGIN` | `false` | e-mail + jelszó regisztráció és belépés; élesben ki van kapcsolva (csak Google, Apple, Facebook), a jelszavas végpontok ilyenkor 403-at adnak |
| `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` `{"package": "<id>"}` azonnal jóváírja a katalógus egy csomagját (`{"unit": "natal"}` rövidítés: a legkisebb ilyen csomag); a compose-fájlokban egyelőre `true` |
| `FREE_PERSON_SLOTS` | `0` | ennyi személyt vehet fel csomag nélkül egy felhasználó |
| `FREE_PERSON_SLOTS` | `30` | ennyi személyt vehet fel egy felhasználó (ingyen; a csomagok 2026 novembere óta nem adnak személyhelyet, az admin adhat többet) |
| `SIGNUP_MODE` | `invite` | `invite`: új fiók csak meghívóval jön létre (403 `not_invited`); `open`: bárki regisztrálhat |
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
| `APPLE_CLIENT_IDS` | – | Sign in with Apple: a Services ID(k) vesszővel elválasztva (pl. `hu.sorsfonalak.web`), az ID token `aud` mezője ezek egyike kell legyen; üresen az Apple-belépés ki van kapcsolva |
@@ -149,5 +149,5 @@ A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket
## Korlátok
- **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti.
- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. A név (`label`) bármikor változhat; ha a `birth` ugyanaz, mint a tárolt (vagy ugyanazt a képletet adja), nincs újraszámolás, és az elemzések, összevetések maradnak. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. A helyek ingyenesek (`FREE_PERSON_SLOTS`, 30), többet az admin ad (egységként vagy az `unlimited_persons` jogosultsággal). Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. A név (`label`) bármikor változhat; ha a `birth` ugyanaz, mint a tárolt (vagy ugyanazt a képletet adja), nincs újraszámolás, és az elemzések, összevetések maradnak. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
- **Admin:** nincs módosítási korlát, korlátlan személy, a személyek adatai bármikor javíthatók, és a részletes elemzés ingyenes (nem fogy egység).
+16 -2
View File
@@ -101,7 +101,8 @@ pub struct Config {
pub prompt_version: String,
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
pub max_charts_per_user: i64,
/// `FREE_PERSON_SLOTS` (default 0): persons a user may add without a package.
/// `FREE_PERSON_SLOTS` (default 30): persons a user may add (packages give
/// none since November 2026; an admin can grant more).
pub free_person_slots: i64,
/// `SIGNUP_MODE` (`invite` or `open`, default `invite`): whether new
/// accounts need an invitation.
@@ -109,6 +110,10 @@ pub struct Config {
/// Object storage of the uploaded photos (see [`crate::storage`]); `None`
/// when `S3_ENDPOINT` is not set (photo uploads are then refused).
pub storage: Option<crate::storage::StorageConfig>,
/// `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<crate::turnstile::TurnstileConfig>,
/// `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,
@@ -219,12 +224,20 @@ impl Config {
.unwrap_or_else(|| "https://openrouter.ai/api/v1/models".into()),
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v3".into()),
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 30)?,
signup_mode: match var("SIGNUP_MODE").as_deref() {
None | Some("invite") => SignupMode::Invite,
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 {
@@ -278,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(),
+5
View File
@@ -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),
+41 -34
View File
@@ -15,10 +15,8 @@ use crate::error::ApiError;
/// List prices of the single items, for showing what a package saves.
const NATAL_PRICE: i64 = 2_000;
const SYNASTRY_PRICE: i64 = 2_500;
/// A yearly forecast bought alone costs more than one in a package.
const FORECAST_PRICE: i64 = 2_500;
const PERSON_PRICE: i64 = 300; // 1 500 Ft for five
const SYNASTRY_PRICE: i64 = 1_500;
const FORECAST_PRICE: i64 = 1_500;
/// Questions every package of the main ladder comes with (not counted in the
/// "bought one by one" price: they are a bonus).
const QUESTIONS_INCLUDED: i64 = 3;
@@ -51,16 +49,16 @@ pub struct Package {
pub badge: Option<&'static str>,
}
pub const CATALOG: [Package; 8] = [
pub const CATALOG: [Package; 7] = [
Package {
id: "single",
name: "Egy elemzés",
tagline: "Egy részletes képletelemzés: neked vagy egy felvett személynek.",
tagline: "Egy részletes képletelemzés és egy éves előrejelzés: neked vagy egy felvett személynek.",
tier: Tier::Main,
price_huf: 2_000,
natal: 1,
synastry: 0,
forecast: 0,
forecast: 1,
persons: 0,
questions: QUESTIONS_INCLUDED,
tarot: 2,
@@ -71,11 +69,11 @@ pub const CATALOG: [Package; 8] = [
name: "Páros",
tagline: "Te és ő: mindkettőtök képlete, éves előrejelzése és a kapcsolati elemzés.",
tier: Tier::Main,
price_huf: 6_000,
price_huf: 3_500,
natal: 2,
synastry: 1,
forecast: 2,
persons: 1,
persons: 0,
questions: QUESTIONS_INCLUDED,
tarot: 5,
badge: None,
@@ -85,11 +83,11 @@ pub const CATALOG: [Package; 8] = [
name: "Család",
tagline: "Az egész család: öt személy, mindenki képlete és éves előrejelzése, és öt kapcsolat.",
tier: Tier::Main,
price_huf: 11_000,
price_huf: 7_000,
natal: 6,
synastry: 5,
forecast: 6,
persons: 5,
persons: 0,
questions: QUESTIONS_INCLUDED,
tarot: 10,
badge: Some("Legnépszerűbb"),
@@ -99,7 +97,7 @@ pub const CATALOG: [Package; 8] = [
name: "+1 kapcsolati elemzés",
tagline: "Egy újabb összevetés részletes elemzése.",
tier: Tier::Addon,
price_huf: 2_500,
price_huf: SYNASTRY_PRICE,
natal: 0,
synastry: 1,
forecast: 0,
@@ -122,20 +120,6 @@ pub const CATALOG: [Package; 8] = [
tarot: 0,
badge: None,
},
Package {
id: "addon_persons",
name: "+5 személy",
tagline: "Még öt ember képlete (az elemzés külön jár).",
tier: Tier::Addon,
price_huf: 1_500,
natal: 0,
synastry: 0,
forecast: 0,
persons: 5,
questions: 0,
tarot: 0,
badge: None,
},
Package {
id: "addon_questions",
name: "+5 kérdés",
@@ -166,7 +150,32 @@ pub const CATALOG: [Package; 8] = [
},
];
/// Packages no longer sold: still known, for orders and payments started
/// before (the person slots have been free since 24 November 2026).
const RETIRED: [Package; 1] = [
Package {
id: "addon_persons",
name: "+5 személy",
tagline: "Még öt ember képlete (az elemzés külön jár).",
tier: Tier::Addon,
price_huf: 1_500,
natal: 0,
synastry: 0,
forecast: 0,
persons: 5,
questions: 0,
tarot: 0,
badge: None,
},
];
/// A package on sale, or a retired one (for old orders and late payments).
pub fn find(id: &str) -> Option<&'static Package> {
CATALOG.iter().chain(RETIRED.iter()).find(|p| p.id == id)
}
/// A package that can be bought (or given) now.
pub fn on_sale(id: &str) -> Option<&'static Package> {
CATALOG.iter().find(|p| p.id == id)
}
@@ -176,7 +185,6 @@ impl Package {
self.natal * NATAL_PRICE
+ self.synastry * SYNASTRY_PRICE
+ self.forecast * FORECAST_PRICE
+ self.persons * PERSON_PRICE
}
pub fn view(&self) -> Value {
@@ -416,12 +424,11 @@ mod tests {
#[test]
fn bigger_packages_are_cheaper_per_analysis() {
let per = |id: &str| find(id).unwrap().view()["per_analysis_huf"].as_i64().unwrap();
assert!(per("single") > per("couple") && per("couple") > per("family"));
assert_eq!(find("family").unwrap().view()["savings_percent"], 73);
assert_eq!(find("couple").unwrap().view()["savings_percent"], 49);
// Alone a forecast costs more than a natal analysis.
assert!(find("addon_forecast").unwrap().price_huf > find("single").unwrap().price_huf);
assert!(find("single").unwrap().view()["savings_percent"].is_null());
assert!(per("single") >= per("couple") && per("couple") > per("family"));
assert_eq!(find("family").unwrap().view()["savings_percent"], 75);
assert_eq!(find("couple").unwrap().view()["savings_percent"], 59);
assert!(on_sale("addon_persons").is_none() && find("addon_persons").is_some());
assert_eq!(find("single").unwrap().view()["savings_percent"], 43);
assert!(find("unlimited").is_none());
assert!(CATALOG.iter().all(|p| find(p.id).is_some()));
// Every package of the ladder comes with questions; more can be bought.
@@ -436,7 +443,7 @@ mod tests {
assert_eq!(
comment,
"Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: \
2 képletelemzés, 1 kapcsolati elemzés, 2 éves előrejelzés, 1 további személy felvétele, 3 kérdés, \
2 képletelemzés, 1 kapcsolati elemzés, 2 éves előrejelzés, 3 kérdés, \
5 egyedi szöveges tartalom. Digitális tartalom."
);
let (name, comment) = find("addon_persons").unwrap().invoice_item();
+7 -4
View File
@@ -1,7 +1,9 @@
//! Persons: charts of other people (name and birth data) a user adds next to
//! their own. Each new person uses one `person` unit, bought in packages;
//! deleting a person does not give it back. The `unlimited_persons`
//! entitlement and admins have no limit.
//! their own. Each new person uses one `person` slot; deleting a person does
//! not give it back. Since 24 November 2026 the slots are free
//! (`FREE_PERSON_SLOTS`, 30), a cap against mass use: whoever needs more
//! writes to us, and an admin grants slots or the `unlimited_persons`
//! entitlement. Admins have no limit. (Before, packages gave the slots.)
//!
//! A person's birth data can be corrected within an hour of adding them,
//! then it is locked (admins: any time).
@@ -18,7 +20,8 @@ use db::Role;
/// How long after adding a person their birth data can be corrected.
pub const EDIT_WINDOW: Duration = Duration::hours(1);
pub const LIMIT_MESSAGE: &str = "Elérted a felvehető személyek számát. További személyekhez bővítsd a csomagodat.";
pub const LIMIT_MESSAGE: &str =
"Elérted a felvehető személyek számát. Ha többre van szükséged, írj nekünk a Visszajelzés oldalon, és megnöveljük.";
pub const LOCKED_MESSAGE: &str = "A személy születési adatai csak a felvételt követő egy órán belül javíthatók.";
/// A user's person slots.
+19
View File
@@ -179,6 +179,15 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
"questions": rows("SELECT json_build_object('id', q.id, 'analysis_id', q.analysis_id, 'question', q.question, 'status', q.status, 'answer', q.answer, 'created_at', q.created_at) FROM questions q WHERE q.asked_by = $1").await?,
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
"shares": rows("SELECT json_build_object('slug', slug, 'kind', kind, 'title', title, 'show_birth_data', show_birth_data, 'view_count', view_count, 'created_at', created_at, 'revoked_at', revoked_at) FROM shares WHERE owner_id = $1").await?,
// The forum (services/forum): what the user wrote and set there.
"forum_profile": rows("SELECT json_build_object('nickname', nickname, 'avatar', avatar, 'bio', bio, 'chart_share', chart_share, 'invisible', invisible, 'points', points, 'post_count', post_count, 'created_at', created_at, 'email_replies', email_replies, 'email_followed', email_followed, 'email_messages', email_messages, 'email_mentions', email_mentions, 'email_listener', email_listener, 'email_weekly', email_weekly, 'listener', listener, 'supporter_badge', supporter_badge, 'banned_until', banned_until, 'ban_reason', ban_reason) FROM forum.members WHERE user_id = $1").await?,
"forum_topic_memberships": rows("SELECT json_build_object('topic', tp.name, 'status', tm.status, 'note', tm.note, 'requested_at', tm.requested_at) FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id WHERE tm.user_id = $1").await?,
"forum_posts": rows("SELECT json_build_object('id', p.id, 'thread_id', p.thread_id, 'thread_title', th.title, 'opening', p.is_opening, 'body', p.body, 'created_at', p.created_at, 'edited_at', p.edited_at, 'removed_at', p.deleted_at, 'removal_reason', p.delete_reason) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.author_id = $1 ORDER BY p.id").await?,
"forum_reactions": rows("SELECT json_build_object('post_id', post_id, 'kind', kind, 'created_at', created_at) FROM forum.reactions WHERE user_id = $1 ORDER BY created_at").await?,
"forum_followed_threads": rows("SELECT json_build_object('thread_id', thread_id, 'since', created_at) FROM forum.follows WHERE user_id = $1").await?,
"forum_conversations": rows("SELECT json_build_object('id', c.id, 'with', m.nickname, 'requested_by_me', c.requested_by = $1, 'intro', c.intro, 'status', c.status, 'created_at', c.created_at) FROM forum.conversations c LEFT JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $1 THEN c.user_b ELSE c.user_a END WHERE $1 IN (c.user_a, c.user_b)").await?,
"forum_messages_sent": rows("SELECT json_build_object('conversation_id', conversation_id, 'body', body, 'created_at', created_at) FROM forum.messages WHERE sender_id = $1 ORDER BY id").await?,
"forum_reports_sent": rows("SELECT json_build_object('post_id', post_id, 'message_id', message_id, 'kind', kind, 'note', note, 'status', status, 'created_at', created_at) FROM forum.reports WHERE reporter_id = $1").await?,
});
Ok(([("content-disposition", "attachment; filename=\"sorsfonalak-export.json\"")], Json(document)))
}
@@ -249,8 +258,18 @@ pub async fn delete_me(
.bind(auth.id())
.execute(&mut *tx)
.await?;
// The forum's own avatar picture (in the object storage) goes too.
let avatar: Option<String> = 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))))
}
+1 -1
View File
@@ -190,7 +190,7 @@ pub async fn grant_package(
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<GrantPackage>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
let package = packages::on_sale(&req.package).ok_or(ApiError::NotFound("package"))?;
let exists: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
exists.ok_or(ApiError::NotFound("user"))?;
+40 -3
View File
@@ -132,18 +132,35 @@ pub async fn queue_email_to(
locale: &str,
payload: Value,
) -> Result<(), ApiError> {
queue_email_at(conn, user_id, to, template, locale, payload, None).await.map(drop)
}
/// Queues an e-mail that the worker sends not before `at` (none: at once);
/// returns its id.
pub async fn queue_email_at(
conn: &mut PgConnection,
user_id: Option<Uuid>,
to: &str,
template: &str,
locale: &str,
payload: Value,
at: Option<time::OffsetDateTime>,
) -> Result<Uuid, ApiError> {
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload, next_attempt_at) \
VALUES ($1, $2, $3, $4, $5, $6, coalesce($7, now()))",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(user_id)
.bind(to)
.bind(template)
.bind(locale)
.bind(payload)
.bind(at)
.execute(conn)
.await?;
Ok(())
Ok(id)
}
/// The e-mails that carry a password link.
@@ -210,6 +227,19 @@ pub struct RegisterRequest {
invite_token: Option<String>,
/// The slug of the shared link the visitor came from.
referral: Option<String>,
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
#[serde(default)]
turnstile_token: Option<String>,
}
/// 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.
@@ -227,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<RegisterRequest>,
) -> ApiResult<impl IntoResponse> {
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?;
@@ -536,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<String>,
}
/// Forgotten password: a link to set a new one (also adds a password to a
@@ -543,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<ResetRequest>,
) -> ApiResult<StatusCode> {
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<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
+176 -18
View File
@@ -26,7 +26,7 @@ use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::{normalize_email, queue_email_to};
use super::auth::{normalize_email, queue_email_at};
use super::promo::{CODE_LEN, display};
use super::{Body, IdPath, St, payments};
use crate::AppState;
@@ -43,7 +43,7 @@ const SEND_GAP: time::Duration = time::Duration::minutes(10);
/// The packages that can be given (the main ladder: a good first package).
fn giftable(id: &str) -> Option<&'static Package> {
packages::find(id).filter(|p| p.tier == Tier::Main)
packages::on_sale(id).filter(|p| p.tier == Tier::Main)
}
/// The recipient's address, typed twice (both the same); `None`: no address.
@@ -92,10 +92,31 @@ struct Gift {
last_sent_at: Option<OffsetDateTime>,
refunded_at: Option<OffsetDateTime>,
refund_id: Option<String>,
/// E-mailed not before this (none: at once).
send_at: Option<OffsetDateTime>,
/// The last e-mail queued for it.
email_id: Option<Uuid>,
/// That e-mail: `scheduled`, `sending`, `sent` or `failed` (none: no
/// e-mail, or cleaned up a week after it went out).
email_state: Option<String>,
}
const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \
redeemed_at, sendings, last_sent_at, refunded_at, refund_id";
redeemed_at, sendings, last_sent_at, refunded_at, refund_id, send_at, email_id, \
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
FROM email_outbox o WHERE o.id = gifts.email_id) AS email_state";
/// The year a Christmas gift wishes for ("csillagos 2027-et"), if bought
/// between 15 November and 6 January (Budapest time; no summer time then).
fn christmas_year(paid: OffsetDateTime) -> Option<i32> {
let local = paid.to_offset(time::UtcOffset::from_hms(1, 0, 0).expect("an offset"));
match (local.month(), local.day()) {
(time::Month::November, 15..) | (time::Month::December, _) => Some(local.year() + 1),
(time::Month::January, ..=6) => Some(local.year()),
_ => None,
}
}
impl Gift {
fn package(&self) -> Result<&'static Package, ApiError> {
@@ -117,9 +138,15 @@ impl Gift {
"recipient_name": self.recipient_name,
"from_name": self.from_name,
"message": self.message,
"christmas_year": self.christmas(),
}))
}
/// The year a Christmas gift wishes for (see `christmas_year`).
fn christmas(&self) -> Option<i32> {
christmas_year(self.paid_at.unwrap_or_else(OffsetDateTime::now_utc))
}
fn status(&self) -> &'static str {
match (self.redeemed_at, self.refunded_at) {
(Some(_), _) => "redeemed",
@@ -141,6 +168,8 @@ impl Gift {
fn view(&self) -> Value {
let status = self.status();
let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc());
// A timed e-mail still waiting can be sent now instead.
let waiting = self.email_state.as_deref() == Some("scheduled");
json!({
"id": self.id,
"package": { "id": self.package, "name": packages::find(&self.package).map(|p| p.name) },
@@ -153,9 +182,12 @@ impl Gift {
"status": status,
"redeemed_at": rfc3339_opt(self.redeemed_at),
"refunded_at": rfc3339_opt(self.refunded_at),
"send_at": rfc3339_opt(self.send_at),
"email_state": self.email_state,
"christmas": self.christmas().is_some(),
"sendings": self.sendings,
"can_send": status == "open" && self.sendings < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send),
"can_send": status == "open" && self.sendings - i32::from(waiting) < MAX_SENDINGS,
"send_again_at": rfc3339_opt(next_send.filter(|_| !waiting)),
})
}
}
@@ -185,6 +217,26 @@ pub struct GiftCheckout {
recipient_email_confirm: Option<String>,
from_name: Option<String>,
message: Option<String>,
/// E-mail it then (RFC 3339; none: right after paying), e.g. on Christmas morning.
send_at: Option<String>,
}
/// How far ahead a gift e-mail can be timed.
const MAX_SCHEDULE: time::Duration = time::Duration::days(366);
/// A time to e-mail a gift: in the future (a few minutes at least), within a year.
fn schedule(at: Option<&str>) -> Result<Option<OffsetDateTime>, ApiError> {
let Some(at) = at.map(str::trim).filter(|a| !a.is_empty()) else { return Ok(None) };
let at = OffsetDateTime::parse(at, &time::format_description::well_known::Rfc3339)
.map_err(|_| ApiError::BadRequest("send_at must be an RFC 3339 time".into()))?;
let now = OffsetDateTime::now_utc();
if at < now + time::Duration::minutes(5) {
return Err(ApiError::BadRequest("Az időzítés legyen a jövőben.".into()));
}
if at > now + MAX_SCHEDULE {
return Err(ApiError::BadRequest("Legfeljebb egy évre előre lehet időzíteni.".into()));
}
Ok(Some(at))
}
/// Starts paying for a gift: returns the address of Stripe's payment page.
@@ -200,6 +252,10 @@ pub async fn checkout(
let to = recipient(req.recipient_email.as_deref(), req.recipient_email_confirm.as_deref())?;
let from = clean_name(req.from_name)?;
let message = super::invitations::clean_message(req.message)?;
let send_at = schedule(req.send_at.as_deref())?;
if send_at.is_some() && to.is_none() {
return Err(ApiError::BadRequest("Időzíteni csak az e-mailben küldött ajándékot lehet.".into()));
}
// Whether this user may pay, before anything is written.
let stripe = match payments::method(&state.config) {
Some("stripe") => Some(payments::stripe_for(&state, &auth)?),
@@ -208,8 +264,8 @@ pub async fn checkout(
};
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message) \
VALUES ($1, $2, $3, $4, $5, $6, $7)",
"INSERT INTO gifts (id, buyer_id, package, recipient_name, recipient_email, from_name, message, send_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
)
.bind(id)
.bind(auth.id())
@@ -218,6 +274,7 @@ pub async fn checkout(
.bind(&to)
.bind(&from)
.bind(&message)
.bind(send_at)
.execute(&state.db)
.await?;
let url = match stripe {
@@ -242,6 +299,8 @@ pub struct Paid {
pub recipient_name: Option<String>,
pub recipient_email: Option<String>,
pub card: Value,
/// When it is e-mailed, on the Budapest clock (`2026-12-24 08:00`); none: at once.
pub send_at_local: Option<String>,
}
/// A new gift code, never the same as a promo code or another gift's.
@@ -276,20 +335,38 @@ pub async fn fulfil(tx: &mut PgConnection, state: &AppState, id: Uuid) -> Result
.await?;
gift.code = Some(code);
if let Some(to) = gift.recipient_email.clone() {
send(tx, state, &gift, &to).await?;
// Timed for a moment already past (paid late): at once.
let at = gift.send_at.filter(|t| *t > OffsetDateTime::now_utc());
send(tx, state, &gift, &to, at).await?;
}
tracing::info!(gift = %id, package = %gift.package, by_email = gift.recipient_email.is_some(), "gift paid");
}
let send_at_local: Option<String> = sqlx::query_scalar(
"SELECT to_char(send_at AT TIME ZONE 'Europe/Budapest', 'YYYY-MM-DD HH24:MI') FROM gifts \
WHERE id = $1 AND send_at > now()",
)
.bind(id)
.fetch_optional(&mut *tx)
.await?
.flatten();
Ok(Paid {
code: display(gift.code()?),
card: gift.card_payload(state)?,
recipient_name: gift.recipient_name,
recipient_email: gift.recipient_email,
send_at_local,
})
}
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language.
async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) -> Result<(), ApiError> {
/// Queues the gift e-mail (with the card) to `to`, in the buyer's language,
/// not before `at` (none: at once).
async fn send(
tx: &mut PgConnection,
state: &AppState,
gift: &Gift,
to: &str,
at: Option<OffsetDateTime>,
) -> Result<(), ApiError> {
let locale: Option<String> = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1")
.bind(gift.buyer_id)
.fetch_optional(&mut *tx)
@@ -304,16 +381,38 @@ async fn send(tx: &mut PgConnection, state: &AppState, gift: &Gift, to: &str) ->
"from_name": gift.from_name,
"message": gift.message,
"gift_card": gift.card_payload(state)?,
"christmas_year": gift.christmas(),
});
// Not the recipient's account (if they have one): no user id.
queue_email_to(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now() WHERE id = $1")
let email = queue_email_at(tx, None, to, "gift_package", locale.as_deref().unwrap_or("hu"), payload, at).await?;
sqlx::query("UPDATE gifts SET sendings = sendings + 1, last_sent_at = now(), email_id = $2 WHERE id = $1")
.bind(gift.id)
.bind(email)
.execute(&mut *tx)
.await?;
Ok(())
}
/// Takes back the gift's e-mail if it has not gone out yet (sent now
/// instead, or refunded): a timed one would come later otherwise. It does
/// not count as a sending then.
async fn cancel_pending_email(conn: &mut PgConnection, gift: &Gift) -> Result<bool, sqlx::Error> {
let Some(email) = gift.email_id else { return Ok(false) };
let taken = sqlx::query("DELETE FROM email_outbox WHERE id = $1 AND sent_at IS NULL AND failed_at IS NULL")
.bind(email)
.execute(&mut *conn)
.await?
.rows_affected()
== 1;
if taken {
sqlx::query("UPDATE gifts SET sendings = greatest(sendings - 1, 0) WHERE id = $1")
.bind(gift.id)
.execute(&mut *conn)
.await?;
}
Ok(taken)
}
/// The user's paid gifts, newest first.
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let gifts: Vec<Gift> = sqlx::query_as(&format!(
@@ -339,6 +438,7 @@ pub async fn card(
let code = display(gift.code()?);
let url = redeem_url(&state, gift.code()?);
let filename = format!("sorsfonalak-ajandek-{code}.pdf");
let christmas = gift.christmas();
let pdf = tokio::task::spawn_blocking(move || {
let contents = package.contents_items();
gift_card::pdf(&gift_card::Card {
@@ -349,6 +449,7 @@ pub async fn card(
recipient_name: gift.recipient_name.as_deref(),
from_name: gift.from_name.as_deref(),
message: gift.message.as_deref(),
christmas,
})
})
.await
@@ -387,18 +488,26 @@ pub async fn send_again(
return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották."));
}
gift.refused_if_refunded()?;
if gift.sendings >= MAX_SENDINGS {
// A timed e-mail still waiting is replaced by this one, not added to it.
let waiting = gift.email_state.as_deref() == Some("scheduled");
if gift.sendings - i32::from(waiting) >= MAX_SENDINGS {
return Err(ApiError::conflict(
"gift_send_limit",
"Ezt az ajándékot már háromszor elküldtük e-mailben. Töltsd le az utalványt, és küldd el te magad.",
));
}
if gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
if !waiting && gift.last_sent_at.is_some_and(|t| t + SEND_GAP > OffsetDateTime::now_utc()) {
return Err(ApiError::conflict("gift_send_wait", "Pár perc múlva küldheted el újra."));
}
sqlx::query("UPDATE gifts SET recipient_email = $2 WHERE id = $1").bind(id).bind(&to).execute(&mut *tx).await?;
// Now, instead of a timed e-mail still waiting.
cancel_pending_email(&mut tx, &gift).await?;
sqlx::query("UPDATE gifts SET recipient_email = $2, send_at = NULL WHERE id = $1")
.bind(id)
.bind(&to)
.execute(&mut *tx)
.await?;
gift.recipient_email = Some(to.clone());
send(&mut tx, &state, &gift, &to).await?;
send(&mut tx, &state, &gift, &to, None).await?;
let gift = own_gift(&mut tx, id, auth.id(), false).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), gift = %id, "gift sent by e-mail");
@@ -469,6 +578,8 @@ struct AdminGift {
storno_status: Option<String>,
storno_number: Option<String>,
storno_error: Option<String>,
send_at: Option<OffsetDateTime>,
email_state: Option<String>,
}
#[derive(Deserialize)]
@@ -493,7 +604,11 @@ pub async fn admin_list(
g.redeemed_at, r.email AS redeemed_by, g.refunded_at, g.refund_id, g.refund_error, \
c.id AS checkout_id, c.live, coalesce(c.amount_huf, c.price_huf) AS amount_huf, \
i.invoice_number, i.status AS invoice_status, \
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error \
x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error, \
g.send_at, \
(SELECT CASE WHEN o.sent_at IS NOT NULL THEN 'sent' WHEN o.failed_at IS NOT NULL THEN 'failed' \
WHEN o.next_attempt_at > now() THEN 'scheduled' ELSE 'sending' END \
FROM email_outbox o WHERE o.id = g.email_id) AS email_state \
FROM gifts g LEFT JOIN users b ON b.id = g.buyer_id LEFT JOIN users r ON r.id = g.redeemed_by \
LEFT JOIN stripe_checkouts c ON c.gift_id = g.id LEFT JOIN invoices i ON i.checkout_id = c.id \
LEFT JOIN invoice_cancellations x ON x.invoice_id = i.id \
@@ -535,10 +650,29 @@ pub async fn admin_list(
"checkout": g.checkout_id.map(|id| json!({ "id": id, "live": g.live, "amount_huf": g.amount_huf })),
"invoice": g.invoice_status.map(|s| json!({ "number": g.invoice_number, "status": s })),
"storno": g.storno_status.map(|s| json!({ "status": s, "number": g.storno_number, "error": g.storno_error })),
"send_at": rfc3339_opt(g.send_at),
"email_state": g.email_state,
})
})
.collect();
Ok(Json(json!({ "gifts": gifts, "withdrawal_days": WITHDRAWAL_DAYS })))
// The timed e-mails by hour (Budapest clock): how many wait, went out or failed.
let schedule: Vec<(String, i64, i64, i64)> = sqlx::query_as(
"SELECT to_char(date_trunc('hour', g.send_at AT TIME ZONE 'Europe/Budapest'), 'YYYY-MM-DD HH24:MI'), \
count(*) FILTER (WHERE o.id IS NOT NULL AND o.sent_at IS NULL AND o.failed_at IS NULL), \
count(*) FILTER (WHERE o.sent_at IS NOT NULL OR (o.id IS NULL AND g.send_at <= now())), \
count(*) FILTER (WHERE o.failed_at IS NOT NULL) \
FROM gifts g LEFT JOIN email_outbox o ON o.id = g.email_id \
WHERE g.send_at IS NOT NULL AND g.paid_at IS NOT NULL AND g.refunded_at IS NULL \
AND g.send_at > now() - interval '30 days' \
GROUP BY 1 ORDER BY 1",
)
.fetch_all(&state.db)
.await?;
let schedule: Vec<Value> = schedule
.into_iter()
.map(|(at, waiting, sent, failed)| json!({ "at": at, "waiting": waiting, "sent": sent, "failed": failed }))
.collect();
Ok(Json(json!({ "gifts": gifts, "schedule": schedule, "withdrawal_days": WITHDRAWAL_DAYS })))
}
/// Admin: refunds a gift the buyer withdrew from. Refused once it is
@@ -577,6 +711,8 @@ pub async fn admin_refund(
.bind(admin.0.id())
.execute(&mut *tx)
.await?;
// A timed e-mail not gone out yet stays unsent.
cancel_pending_email(&mut tx, &gift).await?;
if let Some((checkout_id, _)) = &checkout {
let reason = format!("Elállás az ajándékcsomag vásárlásától (beváltás előtt), kód: {}", display(gift.code()?));
sqlx::query(
@@ -634,3 +770,25 @@ pub async fn admin_refund(
json!({ "status": gift.status(), "refund_id": gift.refund_id, "refunded_at": rfc3339_opt(gift.refunded_at) }),
))
}
#[cfg(test)]
mod tests {
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use super::christmas_year;
fn at(s: &str) -> OffsetDateTime {
OffsetDateTime::parse(s, &Rfc3339).unwrap()
}
#[test]
fn christmas_runs_from_mid_november_to_epiphany() {
assert_eq!(christmas_year(at("2026-11-14T22:59:00Z")), None);
assert_eq!(christmas_year(at("2026-11-14T23:00:00Z")), Some(2027));
assert_eq!(christmas_year(at("2026-12-31T23:30:00Z")), Some(2027));
assert_eq!(christmas_year(at("2027-01-06T22:59:00Z")), Some(2027));
assert_eq!(christmas_year(at("2027-01-06T23:00:00Z")), None);
assert_eq!(christmas_year(at("2027-07-01T12:00:00Z")), None);
}
}
+2 -2
View File
@@ -232,7 +232,7 @@ pub async fn create(
let message = clean_message(req.message)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
let package = match req.package.as_deref().filter(|p| !p.is_empty()) {
Some(id) => Some(packages::find(id).ok_or(ApiError::NotFound("package"))?),
Some(id) => Some(packages::on_sale(id).ok_or(ApiError::NotFound("package"))?),
None => None,
};
let inviter = admin.user.display_name.clone();
@@ -523,7 +523,7 @@ pub async fn preview(
let message = clean_message(req.message)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
let gift = match req.package.as_deref().filter(|p| !p.is_empty()) {
Some(id) => Some(("MINT-AKOD-XXXX".to_string(), packages::find(id).ok_or(ApiError::NotFound("package"))?.name)),
Some(id) => Some(("MINT-AKOD-XXXX".to_string(), packages::on_sale(id).ok_or(ApiError::NotFound("package"))?.name)),
None => None,
};
let payload = payload(
+2
View File
@@ -233,5 +233,7 @@ async fn public_config(State(state): St) -> Json<Value> {
"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()),
}))
}
+10 -7
View File
@@ -62,12 +62,11 @@ pub async fn mock(
(None, Some(Unit::Natal)) => "single",
(None, Some(Unit::Synastry)) => "addon_synastry",
(None, Some(Unit::Forecast)) => "addon_forecast",
(None, Some(Unit::Person)) => "addon_persons",
(None, Some(Unit::Question)) => "addon_questions",
(None, Some(Unit::Tarot)) => "addon_tarot",
_ => return Err(ApiError::BadRequest("give either package or unit".into())),
};
let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
let package = packages::on_sale(id).ok_or(ApiError::NotFound("package"))?;
let mut tx = state.db.begin().await?;
packages::grant(&mut tx, auth.id(), package, Source::Mock, Some(auth.id()), Some("mock payment")).await?;
tx.commit().await?;
@@ -86,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
@@ -130,7 +129,7 @@ pub async fn checkout(
WithRejection(Json(req), _): Body<CheckoutRequest>,
) -> ApiResult<Json<Value>> {
let config = stripe_for(&state, &auth)?;
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
let package = packages::on_sale(&req.package).ok_or(ApiError::NotFound("package"))?;
let url = start_checkout(&state, config, &auth, package, req.return_path.as_deref(), None).await?;
Ok(Json(json!({ "url": url })))
}
@@ -327,6 +326,7 @@ async fn confirm_by_email(
"promo_code": gift.code,
"recipient_name": gift.recipient_name,
"recipient_email": gift.recipient_email,
"send_at": gift.send_at_local,
});
// Handed over by the buyer: the card comes with the confirmation.
if gift.recipient_email.is_none() {
@@ -375,13 +375,16 @@ pub async fn checkout_status(
}
let gift = match gift_id {
Some(id) => {
let (name, to): (Option<String>, Option<String>) =
sqlx::query_as("SELECT recipient_name, recipient_email FROM gifts WHERE id = $1")
let (name, to, send_at): (Option<String>, Option<String>, Option<OffsetDateTime>) =
sqlx::query_as("SELECT recipient_name, recipient_email, send_at FROM gifts WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?
.unwrap_or_default();
Some(json!({ "id": id, "recipient_name": name, "recipient_email": to }))
Some(json!({
"id": id, "recipient_name": name, "recipient_email": to,
"send_at": crate::views::rfc3339_opt(send_at.filter(|t| *t > OffsetDateTime::now_utc())),
}))
}
None => None,
};
+1 -1
View File
@@ -107,7 +107,7 @@ pub async fn create(
admin: AdminUser,
WithRejection(Json(req), _): Body<NewCodes>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
let package = packages::on_sale(&req.package).ok_or(ApiError::NotFound("package"))?;
if !(1..=MAX_BATCH).contains(&req.count) {
return Err(ApiError::BadRequest(format!("count must be 1 to {MAX_BATCH}")));
}
+82 -11
View File
@@ -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<Uuid>,
synastry_id: Option<Uuid>,
analysis_id: Option<Uuid>,
forecast_id: Option<Uuid>,
title: Option<String>,
show_birth_data: bool,
for_forum: bool,
view_count: i64,
created_at: OffsetDateTime,
revoked_at: Option<OffsetDateTime>,
owner_ip_hash: Option<Vec<u8>>,
}
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<CreateShare>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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::<String>()).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<ShareRow> = 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<Value, ApiError> {
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<Value>, Option<OffsetDateTime>)> = 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)
}
+2 -275
View File
@@ -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<String>,
}
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<u8>,
content_type: Option<&str>,
) -> Result<reqwest::Response, StorageError> {
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<reqwest::Response, StorageError> {
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<u8>, 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<Option<Object>, 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<Sha256>;
fn hmac(key: &[u8], data: &str) -> Vec<u8> {
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::<Vec<_>>().join("/")
}
fn signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec<u8> {
[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::*;
+202 -20
View File
@@ -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<std::collections::HashMap<String, String>>) -> Json<Value> {
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<uuid::Uuid>) = 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);
}
@@ -1350,7 +1409,7 @@ async fn admins_use_units_too_and_mock_payments_add_units(pool: PgPool) {
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
assert_eq!(
(r.status, &r.body["analyses_left"]),
(StatusCode::OK, &json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 3, "tarot": 2})),
(StatusCode::OK, &json!({"natal": 1, "synastry": 0, "forecast": 1, "question": 3, "tarot": 2})),
"{}",
r.body
);
@@ -1359,7 +1418,7 @@ async fn admins_use_units_too_and_mock_payments_add_units(pool: PgPool) {
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(1)), "{}", r.body);
assert_eq!(
app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 3, "tarot": 2})
json!({"natal": 0, "synastry": 0, "forecast": 1, "question": 3, "tarot": 2})
);
// without MOCK_PAYMENTS there is no such payment
@@ -1391,17 +1450,17 @@ async fn persons_use_package_slots(pool: PgPool) {
assert_eq!(r.status, StatusCode::NO_CONTENT);
assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 0);
// a person package adds five slots
// packages give no slots any more (they are free, up to a cap)
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "family"})).await;
assert_eq!(r.body["persons"], json!({"used": 1, "limit": 1, "left": 0, "unlimited": false}), "{}", r.body);
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "addon_persons"})).await;
assert_eq!(r.body["persons"], json!({"used": 1, "limit": 6, "left": 5, "unlimited": false}), "{}", r.body);
assert_eq!(r.status, StatusCode::NOT_FOUND);
// more slots from an admin (as granted units)
grant_units(&app, &anna, "person", 5).await;
let second = app.chart(&anna, "Cili", false, "1986-01-01").await;
app.chart(&anna, "Dani", false, "1987-01-01").await;
assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 3);
// the family package adds five more
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "family"})).await;
assert_eq!(r.body["persons"], json!({"used": 3, "limit": 11, "left": 8, "unlimited": false}));
app.chart(&anna, "Emma", false, "1988-01-01").await;
assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 2);
let list = app.get("/v1/charts", Some(&anna)).await.body;
let kinds: Vec<&str> = list["charts"].as_array().unwrap().iter().map(|c| c["kind"].as_str().unwrap()).collect();
assert_eq!(kinds, ["own", "person", "person", "person"]);
@@ -1656,14 +1715,13 @@ async fn packages_grant_units(pool: PgPool) {
"family",
"addon_synastry",
"addon_forecast",
"addon_persons",
"addon_questions",
"addon_tarot"
]
);
assert_eq!(
(&r.body["packages"][2]["badge"], &r.body["packages"][2]["per_analysis_huf"]),
(&json!("Legnépszerűbb"), &json!(647))
(&json!("Legnépszerűbb"), &json!(412))
);
// an admin gives a package as a gift
@@ -1685,7 +1743,7 @@ async fn packages_grant_units(pool: PgPool) {
r.body
);
let me = app.get("/v1/me", Some(&anna)).await.body;
assert_eq!(me["persons"]["limit"], 10); // 5 free + 5
assert_eq!(me["persons"]["limit"], 5); // the free ones: packages give no person slots
let (source, price): (String, i32) =
sqlx::query_as("SELECT source, price_huf FROM package_orders WHERE package = 'family'")
.fetch_one(&pool)
@@ -1703,9 +1761,9 @@ async fn packages_grant_units(pool: PgPool) {
);
let (price,): (i32,) =
sqlx::query_as("SELECT price_huf FROM package_orders WHERE package = 'couple'").fetch_one(&pool).await.unwrap();
assert_eq!(price, 6000);
assert_eq!(price, 3500);
// the header shows the latest main package; a top-up does not change it
app.post("/v1/payments/mock", Some(&anna), json!({"package": "addon_persons"})).await;
app.post("/v1/payments/mock", Some(&anna), json!({"package": "addon_questions"})).await;
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["package"]["name"], "Páros");
// the unlimited package is not sold any more; an old order of it is skipped
@@ -1933,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;
@@ -2632,7 +2703,7 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
let url = r.body["url"].as_str().unwrap();
let id = url.rsplit('/').next().unwrap().to_string();
assert_eq!(stripe_form(&id, "line_items[0][price_data][currency]").as_deref(), Some("huf"));
assert_eq!(stripe_form(&id, "line_items[0][price_data][unit_amount]").as_deref(), Some("600000"));
assert_eq!(stripe_form(&id, "line_items[0][price_data][unit_amount]").as_deref(), Some("350000"));
assert_eq!(
stripe_form(&id, "line_items[0][price_data][product_data][name]").as_deref(),
Some("Sorsfonalak – Páros")
@@ -2694,7 +2765,7 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
assert_eq!(stripe_orders(&app.pool, "anna@example.com").await, vec![("couple".to_string(), 6000)]);
assert_eq!(stripe_orders(&app.pool, "anna@example.com").await, vec![("couple".to_string(), 3500)]);
// What the invoice needs is kept, and the invoice is queued.
let (intent, amount, customer, terms): (String, i32, Value, Option<String>) = sqlx::query_as(
"SELECT payment_intent, amount_huf, customer, terms_version FROM stripe_checkouts \
@@ -2809,7 +2880,7 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
assert_eq!(r.body["status"], "paid");
assert_eq!(
stripe_orders(&app.pool, "anna@example.com").await,
vec![("couple".to_string(), 6000), ("single".to_string(), 2000)]
vec![("couple".to_string(), 3500), ("single".to_string(), 2000)]
);
let (name, tax_type): (String, String) =
sqlx::query_as("SELECT buyer_name, buyer_tax_type FROM invoices WHERE checkout_id = $1")
@@ -3413,7 +3484,7 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
.unwrap();
assert_eq!(
confirmation["gift"],
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com"})
json!({"promo_code": code, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
);
assert!(confirmation["gift_card"].is_null(), "the recipient has the card");
assert_eq!(confirmation["url"], "https://sorsfonalak.test/ajandekaim");
@@ -3426,7 +3497,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
.unwrap();
assert_eq!(invoices, 1);
let r = app.get(&format!("/v1/payments/checkout/{session}"), Some(&anna)).await;
assert_eq!(r.body["gift"], json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com"}));
assert_eq!(
r.body["gift"],
json!({"id": gift_id, "recipient_name": "Bea", "recipient_email": "bea@example.com", "send_at": null})
);
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
@@ -3459,8 +3533,10 @@ async fn a_paid_gift_goes_to_its_recipient_and_adds_the_whole_package(pool: PgPo
sqlx::query("UPDATE gifts SET last_sent_at = now() - interval '11 minutes'").execute(&app.pool).await.unwrap();
let r = send("cili@example.com").await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(2)));
// The first e-mail had not gone out yet (no worker here): the corrected address replaces it.
assert_eq!((&r.body["recipient_email"], &r.body["sendings"]), (&json!("cili@example.com"), &json!(1)));
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 0);
let r = app
.post(
&format!("/v1/gifts/{gift_id}/send"),
@@ -3960,3 +4036,109 @@ async fn the_recommendation_question_comes_once_after_two_contents(pool: PgPool)
);
assert_eq!(nps["comments"][0]["comment"], "Nagyon tetszik.");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) {
// The stand-in payment: paid at once.
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
let admin = app.register("admin@example.com", "Admin").await;
let at = (time::OffsetDateTime::now_utc() + time::Duration::days(10))
.replace_nanosecond(0)
.unwrap()
.format(&time::format_description::well_known::Rfc3339)
.unwrap();
let body = |send_at: &str, email: Option<&str>| {
json!({"package": "couple", "recipient_name": "Bea", "recipient_email": email,
"recipient_email_confirm": email, "send_at": send_at})
};
// In the past, or with nobody to e-mail: refused.
let past = app.post("/v1/gifts/checkout", Some(&anna), body("2020-01-01T08:00:00Z", Some("bea@example.com"))).await;
assert_eq!(past.status, StatusCode::BAD_REQUEST);
let nobody = app.post("/v1/gifts/checkout", Some(&anna), body(&at, None)).await;
assert_eq!(nobody.status, StatusCode::BAD_REQUEST);
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("bea@example.com"))).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let id = r.body["id"].as_str().unwrap().to_string();
// Queued for that moment, not sent yet.
let (due, sent): (time::OffsetDateTime, Option<time::OffsetDateTime>) = sqlx::query_as(
"SELECT next_attempt_at, sent_at FROM email_outbox WHERE to_email = 'bea@example.com' AND template = 'gift_package'",
)
.fetch_one(&app.pool)
.await
.unwrap();
assert_eq!((due.format(&time::format_description::well_known::Rfc3339).unwrap(), sent), (at.clone(), None));
let r = app.get("/v1/gifts", Some(&anna)).await;
let gift = &r.body["gifts"][0];
assert_eq!(
(&gift["email_state"], &gift["send_at"], &gift["can_send"]),
(&json!("scheduled"), &json!(at), &json!(true))
);
let r = app.get("/v1/admin/gifts", Some(&admin)).await;
assert_eq!(r.body["gifts"][0]["email_state"], "scheduled");
let slot = &r.body["schedule"][0];
assert_eq!((&slot["waiting"], &slot["sent"]), (&json!(1), &json!(0)));
// Sent now after all: the timed one is taken back (one e-mail, not two), and it is no extra sending.
let r = app
.post(
&format!("/v1/gifts/{id}/send"),
Some(&anna),
json!({"recipient_email": "bea@example.com", "recipient_email_confirm": "bea@example.com"}),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(
(&r.body["send_at"], &r.body["sendings"], &r.body["email_state"]),
(&Value::Null, &json!(1), &json!("sending"))
);
assert_eq!(app.outbox_count("bea@example.com", "gift_package").await, 1);
// A timed gift refunded before it goes out: the e-mail stays unsent.
let r = app.post("/v1/gifts/checkout", Some(&anna), body(&at, Some("cili@example.com"))).await;
let other = r.body["id"].as_str().unwrap().to_string();
assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 1);
let r = app.post(&format!("/v1/admin/gifts/{other}/refund"), Some(&admin), json!({})).await;
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);
}
+63
View File
@@ -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<String>,
}
fn client() -> &'static reqwest::Client {
static CLIENT: OnceLock<reqwest::Client> = 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())
}
}
+34
View File
@@ -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"
+33
View File
@@ -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"]
+166
View File
@@ -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<OffsetDateTime>,
pub ban_reason: Option<String>,
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<User>,
pub member: Option<Member>,
/// The restricted topics the member was approved into.
pub topics: Vec<i16>,
/// The members they muted.
pub mutes: Vec<Uuid>,
}
impl Viewer {
pub fn user_id(&self) -> Option<Uuid> {
self.user.as_ref().map(|u| u.id)
}
pub fn logged_in(&self) -> bool {
self.user.is_some()
}
pub fn is_admin(&self) -> bool {
self.user.as_ref().is_some_and(|u| u.has_role(Role::Admin))
}
/// A moderator or an admin.
pub fn is_moderator(&self) -> bool {
self.user.as_ref().is_some_and(|u| u.has_role(Role::Moderator) || u.has_role(Role::Admin))
}
pub fn require_user(&self) -> Result<&User, ApiError> {
self.user.as_ref().ok_or(ApiError::Unauthorized)
}
pub fn require_member(&self) -> Result<&Member, ApiError> {
self.require_user()?;
self.member.as_ref().ok_or(ApiError::NicknameRequired)
}
/// A member who may write (not banned).
pub fn require_writer(&self) -> Result<&Member, ApiError> {
let member = self.require_member()?;
if member.banned(OffsetDateTime::now_utc()) {
let reason = member.ban_reason.as_deref().map(|r| format!(" Indok: {r}")).unwrap_or_default();
return Err(ApiError::Banned(format!("Most nem írhatsz a fórumba.{reason}")));
}
Ok(member)
}
pub fn require_moderator(&self) -> Result<&User, ApiError> {
let user = self.require_user()?;
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
}
}
fn session_token(parts: &Parts) -> Option<String> {
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
&& let Some(token) = value.strip_prefix("Bearer ")
{
return Some(token.trim().to_string());
}
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
}
impl FromRequestParts<Arc<AppState>> for Viewer {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
let member = load_member(&state.db, user.id).await?;
if member.is_some() {
// At most once a minute per member: the online dot.
sqlx::query(
"UPDATE forum.members SET last_seen_at = now() \
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
)
.bind(user.id)
.execute(&state.db)
.await?;
}
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<Option<Member>, sqlx::Error> {
sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1"))
.bind(user_id)
.fetch_optional(db)
.await
}
+92
View File
@@ -0,0 +1,92 @@
use axum::Json;
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::json;
/// API error, rendered as `{"error": {"code", "message"}}` like the backend's.
/// Messages meant for the user are Hungarian.
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
#[error("{0}")]
BadRequest(String),
#[error("authentication required")]
Unauthorized,
/// Logged in, but no nickname yet: the frontend sends the user to choose one.
#[error("Előbb válassz álnevet.")]
NicknameRequired,
#[error("{0}")]
Forbidden(String),
/// Banned from writing; the message tells until when.
#[error("{0}")]
Banned(String),
#[error("{0} not found")]
NotFound(&'static str),
#[error("{message}")]
Conflict { code: &'static str, message: String },
/// A usage limit; the message is shown to the user as is.
#[error("{0}")]
Limited(String),
#[error("internal error")]
Internal(String),
}
impl ApiError {
pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
ApiError::Conflict { code, message: message.into() }
}
pub fn bad(message: impl Into<String>) -> Self {
ApiError::BadRequest(message.into())
}
fn status_and_code(&self) -> (StatusCode, &'static str) {
match self {
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
ApiError::NicknameRequired => (StatusCode::FORBIDDEN, "nickname_required"),
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
ApiError::Banned(_) => (StatusCode::FORBIDDEN, "banned"),
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
ApiError::Limited(_) => (StatusCode::TOO_MANY_REQUESTS, "limited"),
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, code) = self.status_and_code();
if let ApiError::Internal(detail) = &self {
tracing::error!(error = %detail, code, "request failed");
}
(status, Json(json!({ "error": { "code": code, "message": self.to_string() } }))).into_response()
}
}
impl From<sqlx::Error> for ApiError {
fn from(e: sqlx::Error) -> Self {
ApiError::Internal(format!("database: {e}"))
}
}
impl From<JsonRejection> for ApiError {
fn from(rejection: JsonRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
impl From<QueryRejection> for ApiError {
fn from(rejection: QueryRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
impl From<PathRejection> for ApiError {
fn from(rejection: PathRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
pub type ApiResult<T> = Result<T, ApiError>;
+195
View File
@@ -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<u32>,
}
/// The links of a text the providers know (each video once, at most [`MAX_PER_POST`]).
pub fn find(text: &str) -> Vec<Found> {
let mut out: Vec<Found> = 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<std::collections::HashMap<i64, Value>, sqlx::Error> {
let found: Vec<(i64, Vec<Found>)> =
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<String> = found.iter().flat_map(|(_, f)| f.iter().map(|x| x.key.clone())).collect();
type Row = (String, String, String, Option<String>, Option<String>);
let rows: Vec<Row> =
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<Value> = 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<Path<String>, ApiError>,
) -> ApiResult<Response> {
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());
}
}
+175
View File
@@ -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<u32> {
if let Ok(n) = raw.parse::<u32>() {
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<u32>)> {
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<String>,
#[serde(default)]
author_name: Option<String>,
}
/// 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::<String>())
})?;
// 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::<String>());
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<String> {
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<Vec<u8>> {
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);
}
}
+349
View File
@@ -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<i64>,
/// A conversation changed (only its two members hear it, through `users`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation: Option<i64>,
/// Whose menu counts changed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub users: Vec<Uuid>,
/// 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<Typing>,
}
#[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<Uuid>) -> 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<String> {
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<Arc<Event>>,
}
impl Default for Hub {
fn default() -> Self {
Self { tx: broadcast::channel(1024).0 }
}
}
impl Hub {
pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
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::<Event>(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<Arc<AppState>>,
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<Event> {
let incoming: Incoming = serde_json::from_str(text).ok()?;
let users = match incoming.typing.as_str() {
"conversation" => {
let other: Option<Uuid> = 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<String> = 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<Arc<Event>>, 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<Uuid> {
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<Uuid>| 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());
}
}
+267
View File
@@ -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<i64>,
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<i64>,
body: &str,
) -> Result<(), sqlx::Error> {
let recipients: Vec<Recipient> = 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<String>) = 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::<String>(),
});
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<Recipient> = 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<String> = 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<String>,
}
/// 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<Option<Person>, 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<Uuid>], outcome: &str) {
let mut seen: Vec<Uuid> = 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<Recipient> = 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<String>) = 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::<String>(),
});
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");
}
}
+84
View File
@@ -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<object_storage::Storage>,
/// The link module's providers (YouTube previews).
pub links: links::LinkConfig,
}
impl AppState {
pub fn new(db: PgPool, base_url: String, storage: Option<object_storage::Storage>) -> 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(())
}
+86
View File
@@ -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());
}
}
+172
View File
@@ -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<Value>,
year: Option<i32>,
summary_title: Option<String>,
/// A synastry: the two charts and the aspects between them.
chart1: Option<Value>,
chart2: Option<Value>,
pair_aspects: Option<Value>,
}
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<Value>, bool) {
let time_known = natal.pointer("/time/time_known").and_then(Value::as_bool).unwrap_or(false);
let mut points: Vec<Value> = ["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<HashMap<Uuid, Value>, sqlx::Error> {
if ids.is_empty() {
return Ok(HashMap::new());
}
let rows: Vec<CardRow> =
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<Uuid> {
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<Path<String>, ApiError>,
) -> ApiResult<Json<Value>> {
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)))
}
+204
View File
@@ -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<Vec<u8>, 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<Json<Value>> {
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<Path<String>, ApiError>,
) -> ApiResult<Response> {
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<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
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<u8> {
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"));
}
}
+335
View File
@@ -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<i64>,
last_author: Option<Uuid>,
last_at: Option<OffsetDateTime>,
}
/// The topics in order: counts and the latest post for those the viewer may
/// read, the others (a members-only topic for a visitor) only by name.
async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
let (me, since) = card_params(viewer);
let rows: Vec<TopicRow> = sqlx::query_as(
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \
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<bool> = 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<i16> = 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<Json<Value>> {
let (me, since) = card_params(&viewer);
let topics = topic_list(&state, &viewer).await?;
let followed = followed_counts(&state, &viewer).await?;
let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 AND 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<CardRow> = sqlx::query_as(&format!(
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
GROUP BY thread_id HAVING count(*) >= $3) \
{} AND th.id IN (SELECT thread_id FROM recent) 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<Uuid> = 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<Value> =
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<Option<Value>> {
let (Some(me), Some(since)) = card_params(viewer) else { return Ok(None) };
let (replies, threads): (i64, i64) = sqlx::query_as(
"SELECT count(*), count(DISTINCT p.thread_id) FROM forum.follows f \
JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \
JOIN forum.posts p ON p.thread_id = f.thread_id AND p.deleted_at IS NULL \
WHERE f.user_id = $1 AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2 \
AND 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<i64> {
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<Json<Value>> {
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<Json<Value>> {
Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? })))
}
#[derive(Deserialize)]
pub struct PageQuery {
#[serde(default)]
page: Option<i64>,
}
/// A topic's threads: pinned ones first, then by the latest post.
pub async fn topic(
State(state): St,
viewer: Viewer,
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let topic: Option<(i16, String, String, String, bool, 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<CardRow> = sqlx::query_as(&format!(
"{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5",
card_sql(&viewer)
))
.bind(me)
.bind(since)
.bind(id)
.bind(PAGE_SIZE + 1)
.bind((page - 1) * PAGE_SIZE)
.fetch_all(&state.db)
.await?;
let has_more = rows.len() as i64 > PAGE_SIZE;
let rows = rows.into_iter().take(PAGE_SIZE as usize).collect();
Ok(Json(json!({
"viewer": viewer_json(&viewer),
"topic": {
"slug": slug, "name": name, "description": description,
"visibility": visibility, "listening": listening, "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<Json<Value>> {
viewer.require_member()?;
let (me, since) = card_params(&viewer);
let rows: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \
ORDER BY th.last_post_at DESC LIMIT 50",
card_sql(&viewer)
))
.bind(me)
.bind(since)
.fetch_all(&state.db)
.await?;
Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? })))
}
+431
View File
@@ -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<Json<Value>> {
let user = viewer.require_user()?;
let now = OffsetDateTime::now_utc();
let member = viewer.member.as_ref().map(|m| {
let rank = m.rank(now);
let change_after = m.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
json!({
"nickname": m.nickname,
"avatar": m.avatar,
"bio": m.bio,
"chart_share": m.chart_share,
"invisible": m.invisible,
"points": m.points,
"post_count": m.post_count,
"created_at": rfc3339(m.created_at),
"rank": rank,
"rank_name": rank.name(),
"next_rank": rank.next().map(|(r, points, days)| json!({
"rank": r, "name": r.name(), "points": points, "days": days,
})),
"nickname_change_after": (change_after > now).then(|| rfc3339(change_after)),
"banned_until": m.banned_until.filter(|u| *u > now).map(|u| {
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
}),
"ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)),
"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<String>,
#[serde(default)]
bio: Option<String>,
#[serde(default)]
chart_share: Option<String>,
#[serde(default)]
invisible: Option<bool>,
/// E-mail notifications: `{"replies": "off|daily|instant", "followed": "off|daily", "messages": "off|instant"}`.
#[serde(default)]
email: Option<EmailSettings>,
/// Volunteering as a listener (from the Kereső rank).
#[serde(default)]
listener: Option<bool>,
/// Showing the "Támogató" badge (buyers only).
#[serde(default)]
supporter_badge: Option<bool>,
}
#[derive(Deserialize)]
pub struct EmailSettings {
#[serde(default)]
replies: Option<String>,
#[serde(default)]
followed: Option<String>,
#[serde(default)]
messages: Option<String>,
#[serde(default)]
mentions: Option<String>,
#[serde(default)]
listener: Option<String>,
#[serde(default)]
weekly: Option<bool>,
}
fn one_of(value: Option<&str>, allowed: &[&str]) -> ApiResult<Option<String>> {
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<bool, sqlx::Error> {
sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM forum.members WHERE nickname_key = $1 AND user_id <> $2) \
OR EXISTS (SELECT 1 FROM forum.retired_nicknames \
WHERE nickname_key = $1 AND user_id <> $2 AND until > now())",
)
.bind(key)
.bind(me)
.fetch_one(db)
.await
}
fn taken() -> ApiError {
ApiError::conflict("nickname_taken", "Ezt az álnevet már más használja. Válassz másikat.")
}
/// Creates the forum profile (choosing a nickname is the first step) or changes it.
pub async fn save_me(
State(state): St,
viewer: Viewer,
WithRejection(Json(req), _): Body<SaveMe>,
) -> ApiResult<Json<Value>> {
let user = viewer.require_user()?;
let nickname = text::nickname(&req.nickname)?;
let key = text::nickname_key(&nickname);
// 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<Query<NameQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let user = viewer.require_user()?;
let nickname = match text::nickname(&q.name) {
Ok(n) => n,
Err(e) => return Ok(Json(json!({ "ok": false, "message": e.to_string() }))),
};
if nickname_taken(&state.db, &text::nickname_key(&nickname), user.id).await? {
return Ok(Json(json!({ "ok": false, "message": taken().to_string() })));
}
Ok(Json(json!({ "ok": true, "nickname": nickname })))
}
#[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<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
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<OffsetDateTime>,
banned_until: Option<OffsetDateTime>,
ban_reason: Option<String>,
}
#[derive(sqlx::FromRow)]
struct RecentRow {
id: i64,
thread_id: i64,
title: String,
topic_slug: String,
topic_name: String,
created_at: OffsetDateTime,
excerpt: String,
is_opening: bool,
}
/// A member's public profile: nickname, avatar, rank, shared signs, bio,
/// activity (coarsely), and recent posts from the topics the viewer may read.
pub async fn profile(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Json<Value>> {
let row: ProfileRow = sqlx::query_as(
"SELECT user_id, bio, created_at, post_count, invisible, last_seen_at, banned_until, ban_reason \
FROM forum.members WHERE nickname_key = $1",
)
.bind(text::nickname_key(&nickname))
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("member"))?;
let brief = authors(&state.db, [row.user_id]).await?.remove(&row.user_id).ok_or(ApiError::NotFound("member"))?;
let recent: Vec<RecentRow> = sqlx::query_as(&format!(
"SELECT p.id, p.thread_id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, p.created_at, \
left(p.body, 200) AS excerpt, p.is_opening \
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE p.author_id = $1 AND p.deleted_at IS NULL AND th.deleted_at IS NULL AND ({}) \
ORDER BY p.id DESC LIMIT 10",
visible_topics(&viewer)
))
.bind(row.user_id)
.fetch_all(&state.db)
.await?;
let thread_count: i64 =
sqlx::query_scalar("SELECT count(*) FROM forum.threads WHERE author_id = $1 AND deleted_at IS NULL")
.bind(row.user_id)
.fetch_one(&state.db)
.await?;
let now = OffsetDateTime::now_utc();
let own = viewer.user_id() == Some(row.user_id);
let last_seen = if row.invisible && !own {
None
} else if online(false, row.last_seen_at, now) {
Some("online")
} else {
row.last_seen_at.map(|t| match now - t {
d if d < time::Duration::days(1) => "day",
d if d < time::Duration::days(7) => "week",
_ => "earlier",
})
};
let banned = row.banned_until.filter(|u| *u > now);
let show_ban = own || viewer.is_moderator();
Ok(Json(json!({
"viewer": viewer_json(&viewer),
"member": {
"author": brief,
"bio": row.bio,
"created_at": rfc3339(row.created_at),
"post_count": row.post_count,
"thread_count": thread_count,
"last_seen": last_seen,
"own": own,
"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::<Vec<_>>(),
})))
}
+179
View File
@@ -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<Vec<String>> {
let chars: Vec<char> = 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<Vec<Uuid>, sqlx::Error> {
let per_at = candidates(body);
let all: Vec<String> = per_at.iter().flatten().cloned().collect::<HashSet<_>>().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<Uuid> {
let result: Result<Vec<Uuid>, sqlx::Error> = async {
let users = named(&state.db, body, author).await?;
if users.is_empty() {
return Ok(Vec::new());
}
let readers: Vec<Uuid> = 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<Query<SearchQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
viewer.require_member()?;
let key = text::nickname_key(&q.q);
if key.is_empty() {
return Ok(Json(json!({ "members": [] })));
}
let ids: Vec<Uuid> = 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::<Vec<_>>() })))
}
#[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");
}
}
+517
View File
@@ -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<Uuid>,
created_at: OffsetDateTime,
responded_at: Option<OffsetDateTime>,
last_message_at: Option<OffsetDateTime>,
}
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<Value> {
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<Conversation> = 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<String> {
let intro: String = raw.split_whitespace().collect::<Vec<_>>().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<NewRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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<Conversation> = 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<Conversation> {
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<Uuid>,
body: String,
}
/// The viewer's conversations and requests, and how many messages are unread.
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
let me = viewer.require_member()?.user_id;
let rows: Vec<Conversation> = 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<i64> = rows.iter().map(|c| c.id).collect();
let last: Vec<LastMessage> = 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<Value> = 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<i64, sqlx::Error> {
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<Json<Value>> {
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<Uuid>, 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::<Vec<_>>(),
})))
}
/// The recipient answers a request: accept, decline (silently) or block.
pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static str) -> ApiResult<StatusCode> {
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<StatusCode> {
respond(state, viewer, path, "accept").await
}
pub async fn decline(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "decline").await
}
pub async fn block(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "block").await
}
pub async fn unblock(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
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<NewMessage>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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<ReadMark>,
) -> ApiResult<StatusCode> {
let me = viewer.require_member()?.user_id;
own(&state.db, me, id).await?;
let last: Option<i64> = 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)
}
+373
View File
@@ -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<T> = WithRejection<Json<T>, ApiError>;
pub type IdPath = WithRejection<Path<i64>, ApiError>;
pub type St = State<Arc<AppState>>;
pub fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/healthz", get(health))
.route("/v1/forum/home", get(home::home))
.route("/v1/forum/nav", get(home::nav))
.route("/v1/forum/topics", get(home::topics).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<Json<Value>, ApiError> {
sqlx::query("SELECT 1").execute(&state.db).await?;
Ok(Json(json!({ "status": "ok" })))
}
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
/// Built from the viewer's flags 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<String> = 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<String>,
pub author_id: Option<Uuid>,
pub created_at: OffsetDateTime,
pub last_post_at: OffsetDateTime,
pub reply_count: i32,
pub pinned: bool,
pub locked: bool,
pub topic_slug: String,
pub topic_name: String,
pub participants: i64,
/// Posts by others the member has not read; `None` for visitors.
pub unread: Option<i64>,
/// 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<Uuid>, Option<OffsetDateTime>) {
match &viewer.member {
Some(m) => (Some(m.user_id), Some(m.created_at)),
None => (None, None),
}
}
pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, sqlx::Error> {
let people = authors(db, rows.iter().filter_map(|r| r.author_id)).await?;
Ok(rows
.into_iter()
.map(|r| {
json!({
"id": r.id,
"slug": crate::text::slug(&r.title),
"title": r.title,
"intent": r.intent,
"topic": { "slug": r.topic_slug, "name": r.topic_name },
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
"created_at": rfc3339(r.created_at),
"last_post_at": rfc3339(r.last_post_at),
"reply_count": r.reply_count,
"participants": r.participants,
"pinned": r.pinned,
"locked": r.locked,
"unread": r.unread,
"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<OffsetDateTime>,
chart_share: String,
roles: Vec<String>,
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<Item = Uuid>) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
let mut ids: Vec<Uuid> = ids.into_iter().collect();
ids.sort_unstable();
ids.dedup();
if ids.is_empty() {
return Ok(HashMap::new());
}
let rows: Vec<AuthorRow> = sqlx::query_as(
"SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \
m.chart_share, u.roles, 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<Uuid> = rows.iter().filter(|r| r.chart_share != "none").map(|r| r.user_id).collect();
let signs = shared_signs(db, &sharing).await?;
let now = OffsetDateTime::now_utc();
Ok(rows
.into_iter()
.map(|r| {
let rank = Rank::of(r.points, r.created_at, now);
let moderator = r.roles.iter().any(|role| role == "moderator" || role == "admin");
let shown = signs.get(&r.user_id).map(|chart| chart.share(&r.chart_share));
let value = json!({
"nickname": r.nickname,
"avatar": r.avatar,
"rank": rank,
"rank_name": rank.name(),
"moderator": moderator,
"online": online(r.invisible, r.last_seen_at, now),
"signs": shown,
"listener": r.listener,
"supporter": r.supporter,
"founder": r.founder,
});
(r.user_id, value)
})
.collect())
}
pub fn online(invisible: bool, last_seen_at: Option<OffsetDateTime>, now: OffsetDateTime) -> bool {
!invisible && last_seen_at.is_some_and(|t| now - t < time::Duration::minutes(ONLINE_MINUTES))
}
/// The signs of a member's own chart (never degrees: they would give away the
/// birth date and time).
#[derive(Debug, Clone, Default)]
pub struct ChartSigns {
/// Planet id → sign id, in the chart's order.
pub planets: Vec<(String, String)>,
/// Only when the birth time is known.
pub ascendant: Option<String>,
}
const PLANETS: [&str; 10] =
["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
impl ChartSigns {
fn sign(&self, id: &str) -> Option<&str> {
self.planets.iter().find(|(p, _)| p == id).map(|(_, s)| s.as_str())
}
/// What a sharing level shows; `None` for "none".
pub fn share(&self, level: &str) -> Option<Value> {
let mut out = serde_json::Map::new();
let mut put = |key: &str, sign: Option<&str>| {
if let Some(sign) = sign {
out.insert(key.to_string(), json!(sign));
}
};
match level {
"sun" => put("sun", self.sign("sun")),
"big3" => {
put("sun", self.sign("sun"));
put("moon", self.sign("moon"));
put("ascendant", self.ascendant.as_deref());
}
"planets" => {
for planet in PLANETS {
put(planet, self.sign(planet));
}
put("ascendant", self.ascendant.as_deref());
}
_ => return None,
}
if out.is_empty() { None } else { Some(Value::Object(out)) }
}
}
/// The signs of each user's own chart (the current one first).
pub async fn shared_signs(db: &PgPool, users: &[Uuid]) -> Result<HashMap<Uuid, ChartSigns>, sqlx::Error> {
if users.is_empty() {
return Ok(HashMap::new());
}
type Row = (Uuid, Option<Value>, Option<String>, Option<bool>);
let rows: Vec<Row> = sqlx::query_as(
"SELECT DISTINCT ON (owner_id) owner_id, result->'points', result->'angles'->'ascendant'->>'sign', \
(result->'time'->>'time_known')::boolean \
FROM charts WHERE owner_id = ANY($1) AND kind = 'own' ORDER BY owner_id, is_primary DESC, created_at",
)
.bind(users)
.fetch_all(db)
.await?;
Ok(rows
.into_iter()
.map(|(owner, points, ascendant, time_known)| {
let planets = points
.as_ref()
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|p| Some((p["id"].as_str()?.to_string(), p["sign"].as_str()?.to_string())))
.filter(|(id, _)| PLANETS.contains(&id.as_str()))
.collect();
let ascendant = ascendant.filter(|_| time_known.unwrap_or(false));
(owner, ChartSigns { planets, ascendant })
})
.collect())
}
pub fn rfc3339(t: OffsetDateTime) -> String {
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
}
/// Whether the user bought a package (lifts the newcomer limits).
pub async fn has_purchase(db: &PgPool, user: Uuid) -> Result<bool, sqlx::Error> {
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')")
.bind(user)
.fetch_one(db)
.await
}
+247
View File
@@ -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<Uuid>,
thread_id: Option<i64>,
post_id: Option<i64>,
reason: Option<&str>,
until: Option<OffsetDateTime>,
) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \
VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)",
)
.bind(actor)
.bind(action.as_str())
.bind(target_user)
.bind(thread_id)
.bind(post_id)
.bind(reason)
.bind(until)
.execute(db)
.await?;
Ok(())
}
/// 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<i64>,
) -> 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<i64>,
#[serde(default)]
reason: Option<String>,
}
/// The member behind a nickname, and whether they are a moderator or admin.
async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> {
let row: Option<(Uuid, Vec<String>)> = sqlx::query_as(
"SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1",
)
.bind(text::nickname_key(nickname))
.fetch_optional(db)
.await?;
let (id, roles) = row.ok_or(ApiError::NotFound("member"))?;
Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin")))
}
/// A moderator bans a member for some hours or for good: they may still
/// read, not write. Moderators and admins cannot be banned this way.
pub async fn ban(
State(state): St,
viewer: Viewer,
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
WithRejection(Json(req), _): Body<BanRequest>,
) -> ApiResult<Json<Value>> {
let moderator = viewer.require_moderator()?;
let (user, protected) = target(&state.db, &nickname).await?;
if protected {
return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into()));
}
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
let until = match req.hours {
Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h),
Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))),
None => forever(),
};
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1")
.bind(user)
.bind(until)
.bind(&reason)
.execute(&mut *tx)
.await?;
record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?;
tx.commit().await?;
tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned");
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<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let (user, _) = target(&state.db, &nickname).await?;
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1")
.bind(user)
.execute(&mut *tx)
.await?;
record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(sqlx::FromRow)]
struct LogRow {
id: i64,
actor: Option<String>,
actor_kind: String,
action: String,
target: Option<String>,
thread_id: Option<i64>,
thread_title: Option<String>,
post_id: Option<i64>,
report_id: Option<i64>,
reason: Option<String>,
until: Option<OffsetDateTime>,
created_at: OffsetDateTime,
}
/// The latest moderation steps, for moderators.
pub async fn log(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<LogRow> = sqlx::query_as(
"SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \
tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.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::<Vec<_>>(),
})))
}
+94
View File
@@ -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<Uuid> {
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<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
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<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
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<Json<Value>> {
viewer.require_member()?;
let people = authors(&state.db, viewer.mutes.iter().copied()).await?;
let mut muted: Vec<Value> = 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<Path<String>, ApiError>,
WithRejection(axum::Json(req), _): WithRejection<axum::Json<FounderChange>, ApiError>,
) -> ApiResult<StatusCode> {
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,
}
+348
View File
@@ -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<Edit>,
) -> ApiResult<Json<Value>> {
let member = viewer.require_writer()?;
let (post, _) = load(&state.db, &viewer, id).await?;
if post.author_id != Some(member.user_id) || post.deleted_at.is_some() {
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into()));
}
open_thread(&state.db, &viewer, post.thread_id).await?;
let body = text::body(&req.body)?;
let post: PostRow = sqlx::query_as(&format!(
"UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}"
))
.bind(id)
.bind(&body)
.fetch_one(&state.db)
.await?;
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<Reason>,
) -> ApiResult<StatusCode> {
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<StatusCode> {
let admin = viewer.require_user()?;
if !viewer.is_admin() {
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
}
let (post, _) = load(&state.db, &viewer, id).await?;
if post.deleted_at.is_none() {
return Ok(StatusCode::NO_CONTENT);
}
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
if !post.is_opening {
sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1")
.bind(post.thread_id)
.execute(&mut *tx)
.await?;
}
moderation::record(
&mut *tx,
admin.id,
Action::RestorePost,
post.author_id,
Some(post.thread_id),
Some(id),
None,
None,
)
.await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
pub struct React {
kind: String,
}
fn points_of(kind: &str) -> i32 {
if kind == "down" { -1 } else { 1 }
}
/// Gives (or changes) the viewer's one reaction to a post. A newcomer's
/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is
/// not offered in listening topics.
pub async fn react(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<React>,
) -> ApiResult<Json<Value>> {
let member = viewer.require_writer()?;
let (post, thread) = load(&state.db, &viewer, id).await?;
if post.deleted_at.is_some() {
return Err(ApiError::NotFound("post"));
}
open_thread(&state.db, &viewer, thread.id).await?;
if post.author_id == Some(member.user_id) {
return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into()));
}
let kind = req.kind.as_str();
let now = OffsetDateTime::now_utc();
let rank = member.rank(now);
if kind == "down" {
if thread.listening {
return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into()));
}
if !rank.may_downvote() {
return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into()));
}
} else if !REACTIONS.contains(&kind) {
return Err(ApiError::bad("Ismeretlen reakció."));
}
let counted = !rank.is_newcomer();
let mut tx = state.db.begin().await?;
let previous: Option<(String, bool)> =
sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE")
.bind(id)
.bind(member.user_id)
.fetch_optional(&mut *tx)
.await?;
let mut delta = if counted { points_of(kind) } else { 0 };
if let Some((old, true)) = &previous {
delta -= points_of(old);
}
sqlx::query(
"INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \
ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()",
)
.bind(id)
.bind(member.user_id)
.bind(kind)
.bind(counted)
.execute(&mut *tx)
.await?;
add_points(&mut tx, post.author_id, delta).await?;
tx.commit().await?;
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<Json<Value>> {
let member = viewer.require_writer()?;
let (post, _) = load(&state.db, &viewer, id).await?;
let mut tx = state.db.begin().await?;
let removed: Option<(String, bool)> =
sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted")
.bind(id)
.bind(member.user_id)
.fetch_optional(&mut *tx)
.await?;
if let Some((kind, true)) = removed {
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
}
tx.commit().await?;
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<uuid::Uuid>, delta: i32) -> Result<(), sqlx::Error> {
if let (Some(author), true) = (author, delta != 0) {
sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1")
.bind(author)
.bind(delta)
.execute(&mut *tx)
.await?;
}
Ok(())
}
/// The thread's author marks a reply that helped (worth more than a reaction).
pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
set_helped(state, viewer, path, true).await
}
pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
set_helped(state, viewer, path, false).await
}
async fn set_helped(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
on: bool,
) -> ApiResult<Json<Value>> {
let member = viewer.require_writer()?;
let (post, thread) = load(&state.db, &viewer, id).await?;
if thread.author_id != Some(member.user_id) {
return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into()));
}
if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() {
return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted."));
}
let mut tx = state.db.begin().await?;
let changed: Option<i64> = if on {
sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id")
} else {
sqlx::query_scalar(
"UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id",
)
}
.bind(id)
.fetch_optional(&mut *tx)
.await?;
if changed.is_some() {
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
}
tx.commit().await?;
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<StatusCode> {
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)
}
+135
View File
@@ -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<i64, sqlx::Error> {
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<i64>,
}
#[derive(sqlx::FromRow)]
struct Row {
id: i64,
thread_id: i64,
title: String,
author_id: Option<Uuid>,
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<Query<ListQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let member = viewer.require_member()?;
let page = q.page.unwrap_or(1).clamp(1, 1000);
let rows: Vec<Row> = 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<Value> = 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<StatusCode> {
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::<Vec<_>>().join(" ");
match line.char_indices().nth(160) {
Some((at, _)) => format!("{}…", line[..at].trim_end()),
None => line,
}
}
+351
View File
@@ -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<String>,
}
fn check(req: &ReportRequest) -> ApiResult<String> {
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::<Vec<_>>().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<Value> {
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<ReportRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let user = viewer.require_user()?;
let note = check(&req)?;
let post: Option<(i64, Option<Uuid>)> =
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(&note)
.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<ReportRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let user = viewer.require_user()?;
let note = check(&req)?;
let found: Option<(Option<Uuid>,)> = 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(&note)
.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<i64>,
message_id: Option<i64>,
reporter: Option<String>,
kind: String,
note: String,
status: String,
handled_by: Option<String>,
handled_at: Option<OffsetDateTime>,
created_at: OffsetDateTime,
}
#[derive(sqlx::FromRow)]
struct PostTarget {
id: i64,
thread_id: i64,
title: String,
author_id: Option<Uuid>,
body: String,
deleted: bool,
}
#[derive(sqlx::FromRow)]
struct MessageRow {
id: i64,
conversation_id: i64,
sender_id: Option<Uuid>,
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<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<ReportRow> = 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<i64> = rows.iter().filter_map(|r| r.post_id).collect();
let posts: Vec<PostTarget> = 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<i64> = 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<Uuid>, 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<i64>, Option<i64>, 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<Value> = 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<Value> = 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<Handle>,
) -> ApiResult<StatusCode> {
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<i64>, Option<i64>)> =
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<Option<Uuid>> = 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<Vec<Option<Uuid>>, 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<i64, sqlx::Error> {
sqlx::query_scalar("SELECT count(*) FROM forum.reports WHERE status = 'open'").fetch_one(db).await
}
+139
View File
@@ -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<String>,
#[serde(default)]
page: Option<i64>,
}
#[derive(sqlx::FromRow)]
struct Hit {
id: i64,
title: String,
topic_slug: String,
topic_name: String,
author_id: Option<Uuid>,
last_post_at: OffsetDateTime,
reply_count: i32,
post_id: Option<i64>,
snippet: Option<String>,
}
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<Query<SearchQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
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<String> = query
.split(|c: char| !c.is_alphanumeric())
.filter(|w| w.chars().count() >= 3)
.take(8)
.map(|w| format!("{w}:*"))
.collect();
let rows: Vec<Hit> = 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<Value> = 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<Json<Value>> {
let topics: Vec<(String, Option<OffsetDateTime>)> = 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<MapThread> = 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::<Vec<_>>(),
"threads": threads.iter().map(|t| json!({
"id": t.id, "slug": text::slug(&t.title), "updated": rfc3339(t.last_post_at),
})).collect::<Vec<_>>(),
})))
}
+655
View File
@@ -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<Uuid>,
pub title: String,
pub intent: Option<String>,
pub created_at: OffsetDateTime,
pub locked: bool,
pub pinned: bool,
pub deleted_at: Option<OffsetDateTime>,
pub delete_reason: Option<String>,
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<ThreadRow> {
let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1"))
.bind(id)
.fetch_optional(db)
.await?
.ok_or(ApiError::NotFound("thread"))?;
if !may_read(viewer, &thread.visibility, 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<ThreadRow> {
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<i64>,
pub is_opening: bool,
pub author_id: Option<Uuid>,
pub body: String,
pub created_at: OffsetDateTime,
pub edited_at: Option<OffsetDateTime>,
pub helped_at: Option<OffsetDateTime>,
pub deleted_at: Option<OffsetDateTime>,
pub deleted_by: Option<Uuid>,
pub delete_reason: Option<String>,
/// 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<i64>,
/// A chart, forecast or synastry shared with the question.
pub share_id: Option<Uuid>,
}
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<Vec<Value>> {
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
let shares: Vec<Uuid> = 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<i64, HashMap<String, i64>> = HashMap::new();
for (post, kind, n) in counts {
by_post.entry(post).or_default().insert(kind, n);
}
let mine: HashMap<i64, String> = match viewer.user_id() {
Some(me) => {
sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2")
.bind(&ids)
.bind(me)
.fetch_all(db)
.await?
.into_iter()
.collect()
}
None => HashMap::new(),
};
let 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<i64> = posts.iter().filter_map(|p| p.reply_to_id).collect();
let answered: HashMap<i64, Option<String>> = sqlx::query_as::<_, (i64, Option<String>)>(
"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::<serde_json::Map<_, _>>(),
"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<Json<Value>> {
let thread = readable_thread(&state.db, &viewer, id).await?;
let people = authors(&state.db, thread.author_id).await?;
let moderator = viewer.is_moderator();
let mut out = json!({
"viewer": viewer_json(&viewer),
"thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())),
});
if thread.deleted_at.is_some() && !moderator {
out["posts"] = json!([]);
return Ok(Json(out));
}
let posts: Vec<PostRow> =
sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id"))
.bind(id)
.fetch_all(&state.db)
.await?;
out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?);
let now = OffsetDateTime::now_utc();
let (following, last_read) = match viewer.user_id() {
Some(me) => {
let following: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)")
.bind(me)
.bind(id)
.fetch_one(&state.db)
.await?;
let last_read: Option<i64> =
sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2")
.bind(me)
.bind(id)
.fetch_optional(&state.db)
.await?;
(following, last_read)
}
None => (false, None),
};
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
let open = thread.deleted_at.is_none() && !thread.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>) -> 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<String>,
/// A share made for the forum on the main site (`/s/<slug>`).
#[serde(default)]
share: Option<String>,
}
/// Starts a thread with its opening post; the author follows it.
pub async fn create(
State(state): St,
viewer: Viewer,
WithRejection(Json(req), _): Body<CreateThread>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?;
let topic: Option<(i16, String, bool, 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<i64>,
}
pub async fn reply(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<Reply>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?;
open_thread(&state.db, &viewer, id).await?;
let body = text::body(&req.body)?;
// 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<i64>, bool, bool)> = sqlx::query_as(
"SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2",
)
.bind(parent_id)
.bind(id)
.fetch_optional(&state.db)
.await?;
let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?;
if deleted {
return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni."));
}
if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) }
}
};
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<ReadMark>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
readable_thread(&state.db, &viewer, id).await?;
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1")
.bind(id)
.fetch_one(&state.db)
.await?;
let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) };
upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
readable_thread(&state.db, &viewer, id).await?;
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(member.user_id)
.bind(id)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2")
.bind(member.user_id)
.bind(id)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
pub struct ThreadChange {
#[serde(default)]
locked: Option<bool>,
#[serde(default)]
pinned: Option<bool>,
}
/// Moderators lock (no more replies) or pin (first in its topic) a thread.
pub async fn update(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ThreadChange>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let thread = readable_thread(&state.db, &viewer, id).await?;
let mut tx = state.db.begin().await?;
if let Some(locked) = req.locked.filter(|l| *l != thread.locked) {
sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1")
.bind(id)
.bind(locked)
.execute(&mut *tx)
.await?;
let action = if locked { Action::Lock } else { Action::Unlock };
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
}
if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) {
sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1")
.bind(id)
.bind(pinned)
.execute(&mut *tx)
.await?;
let action = if pinned { Action::Pin } else { Action::Unpin };
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
}
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
pub struct Reason {
#[serde(default)]
pub reason: Option<String>,
}
/// A moderator removes a whole thread; its place keeps the reason.
pub async fn remove(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<Reason>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let thread = readable_thread(&state.db, &viewer, id).await?;
if thread.deleted_at.is_some() {
return Ok(StatusCode::NO_CONTENT);
}
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
.bind(id)
.bind(moderator.id)
.bind(&reason)
.execute(&mut *tx)
.await?;
moderation::record(
&mut *tx,
moderator.id,
Action::DeleteThread,
thread.author_id,
Some(id),
None,
Some(&reason),
None,
)
.await?;
tx.commit().await?;
tracing::info!(thread = id, moderator = %moderator.id, "thread removed");
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<StatusCode> {
let admin = viewer.require_user()?;
if !viewer.is_admin() {
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
}
let thread = readable_thread(&state.db, &viewer, id).await?;
if thread.deleted_at.is_none() {
return Ok(StatusCode::NO_CONTENT);
}
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
+307
View File
@@ -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<Uuid> {
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<String> {
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<String> {
let text: String = raw.split_whitespace().collect::<Vec<_>>().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<NewTopic>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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<i16, sqlx::Error> = 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<String>,
#[serde(default)]
description: Option<String>,
#[serde(default)]
visibility: Option<String>,
#[serde(default)]
listening: Option<bool>,
#[serde(default)]
position: Option<i16>,
/// Archive (true) or bring back (false).
#[serde(default)]
archived: Option<bool>,
}
/// 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<Path<String>, ApiError>,
WithRejection(Json(req), _): Body<TopicChange>,
) -> ApiResult<StatusCode> {
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<String>,
}
/// 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<Path<String>, ApiError>,
WithRejection(Json(req), _): Body<JoinRequest>,
) -> ApiResult<StatusCode> {
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::<Vec<_>>().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(&note)
.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<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
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<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<RequestRow> = 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::<Vec<_>>(),
})))
}
#[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<Decision>,
) -> ApiResult<StatusCode> {
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)
}
File diff suppressed because it is too large Load Diff
+279
View File
@@ -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, `<glyph>-<colour>`.
/// The frontend draws them (`src/components/forum/Avatar.tsx`).
pub const AVATAR_GLYPHS: [&str; 8] = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"];
pub const AVATAR_COLOURS: [&str; 6] = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"];
/// Words a nickname may not contain (compared folded, see [`nickname_key`]).
const RESERVED: [&str; 7] = ["admin", "moderator", "sorsfonalak", "rendszer", "ugyfelszolgalat", "torolttag", "forum"];
const SEPARATORS: [char; 4] = [' ', '-', '_', '.'];
/// A nickname as it will be shown: trimmed, inner spaces collapsed, checked.
/// Letters (accented ones too), digits, and single spaces, `-`, `_` or `.`
/// between them; it starts with a letter.
pub fn nickname(raw: &str) -> Result<String, ApiError> {
let name = raw.split_whitespace().collect::<Vec<_>>().join(" ");
let len = name.chars().count();
if !(NICKNAME_MIN..=NICKNAME_MAX).contains(&len) {
return Err(ApiError::bad(format!("Az álnév {NICKNAME_MIN}–{NICKNAME_MAX} karakter legyen.")));
}
if !name.chars().next().is_some_and(latin_letter) {
return Err(ApiError::bad("Az álnév betűvel kezdődjön."));
}
let mut previous_separator = false;
for c in name.chars() {
let separator = SEPARATORS.contains(&c);
if !(separator || latin_letter(c) || c.is_ascii_digit()) {
return Err(ApiError::bad("Az álnévben betűk, számok, szóköz, kötőjel, aláhúzás és pont lehet."));
}
if separator && previous_separator {
return Err(ApiError::bad("Az álnévben ne legyen két elválasztó jel egymás után."));
}
previous_separator = separator;
}
if previous_separator {
return Err(ApiError::bad("Az álnév ne végződjön elválasztó jellel."));
}
let key = nickname_key(&name);
if RESERVED.iter().any(|word| key.contains(&nickname_key(word))) {
return Err(ApiError::bad("Ezt az álnevet nem választhatod."));
}
Ok(name)
}
/// A letter of the Latin script (accented ones included), so look-alike
/// letters of other scripts cannot imitate a nickname.
fn latin_letter(c: char) -> bool {
c.is_alphabetic()
&& matches!(c as u32,
0x41..=0x5A | 0x61..=0x7A // ASCII
| 0xC0..=0x24F // Latin-1 Supplement, Latin Extended-A and -B
| 0x1E00..=0x1EFF) // Latin Extended Additional
}
/// The nickname folded for uniqueness: no accents, case or separators, and
/// characters that look alike made the same (`I`, `l`, `1` → `l`; `0` → `o`),
/// so "Holdfény", "holdfeny" and "Ho1d-feny" are one name.
pub fn nickname_key(name: &str) -> String {
deunicode::deunicode(name)
.to_lowercase()
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| match c {
'i' | '1' => 'l',
'0' => 'o',
other => other,
})
.collect()
}
/// A thread title: one line, spaces collapsed.
pub fn title(raw: &str) -> Result<String, ApiError> {
let title: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
let len = title.chars().count();
if len < TITLE_MIN {
return Err(ApiError::bad(format!("A cím legalább {TITLE_MIN} karakter legyen.")));
}
if len > TITLE_MAX {
return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet.")));
}
Ok(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<String, ApiError> {
let text = clean_multiline(raw, 2);
if text.is_empty() {
return Err(ApiError::bad("A hozzászólás nem lehet üres."));
}
if text.chars().count() > BODY_MAX {
return Err(ApiError::bad(format!("A hozzászólás legfeljebb {BODY_MAX} karakter lehet.")));
}
Ok(smileys(&text))
}
/// The profile's short introduction: no links (old-school profile spam).
pub fn bio(raw: &str) -> Result<String, ApiError> {
let text = clean_multiline(raw, 1);
if text.chars().count() > BIO_MAX {
return Err(ApiError::bad(format!("A bemutatkozás legfeljebb {BIO_MAX} karakter lehet.")));
}
let lower = text.to_lowercase();
if lower.contains("http") || lower.contains("www.") {
return Err(ApiError::bad("A bemutatkozásba nem tehetsz linket."));
}
Ok(smileys(&text))
}
/// A moderator's reason, shown in place of what was removed.
pub fn reason(raw: &str) -> Result<String, ApiError> {
let text: String = raw.split_whitespace().collect::<Vec<_>>().join(" ");
let len = text.chars().count();
if !(REASON_MIN..=REASON_MAX).contains(&len) {
return Err(ApiError::bad(format!("Az indoklás {REASON_MIN}–{REASON_MAX} karakter legyen.")));
}
Ok(text)
}
pub fn avatar(raw: &str) -> Result<String, ApiError> {
let valid = raw
.split_once('-')
.is_some_and(|(glyph, colour)| AVATAR_GLYPHS.contains(&glyph) && AVATAR_COLOURS.contains(&colour));
if valid { Ok(raw.to_string()) } else { Err(ApiError::bad("Ismeretlen avatar.")) }
}
/// A default avatar for a new member, picked from the nickname.
pub fn default_avatar(key: &str) -> String {
let n: usize = key.bytes().map(usize::from).sum();
format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()])
}
/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`.
pub fn slug(title: &str) -> String {
let ascii = deunicode::deunicode(title).to_lowercase();
let mut slug = String::new();
for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) {
if !slug.is_empty() && slug.len() + 1 + word.len() > 60 {
break;
}
if !slug.is_empty() {
slug.push('-');
}
slug.push_str(word);
}
slug
}
/// Lines with control characters removed and trailing spaces dropped; at most
/// `max_breaks` line breaks in a row; trimmed.
fn clean_multiline(raw: &str, max_breaks: usize) -> String {
let normalized = raw.replace("\r\n", "\n").replace('\r', "\n");
let mut out = String::with_capacity(normalized.len());
let mut breaks = 0;
for line in normalized.split('\n') {
let line: String = line.chars().map(|c| if c == '\t' { ' ' } else { c }).filter(|c| !c.is_control()).collect();
let line = line.trim_end();
if line.trim().is_empty() {
breaks += 1;
continue;
}
if !out.is_empty() {
out.push_str(&"\n".repeat(breaks.clamp(1, max_breaks)));
}
breaks = 1;
out.push_str(line);
}
out.trim().to_string()
}
/// 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", "❤️"),
("</3", "💔"),
];
fn smileys(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut word = String::new();
let flush = |word: &mut String, out: &mut String| {
let emoji = 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());
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+48
View File
@@ -4,6 +4,9 @@ import { ChartWheel } from "@/components/ChartWheel";
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";
import type { AnalysisContent, ChartResult } from "@/lib/types";
@@ -42,6 +45,8 @@ const SYNASTRY_TOPICS = ["Vonzás", "Kommunikáció", "Érzelmi kötődés", "S
/** The home page for visitors: what the site does, shown on the example chart. */
/** `loggedIn`: the layout shows the app's header, and the buttons lead to the user's chart instead of the login. */
export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean; loggedIn?: boolean }) {
// In the Christmas season the gift band leads to the Christmas page.
const xmas = isChristmasTime();
const chart = example.chart as unknown as ChartResult;
const analysis = example.analysis as AnalysisContent;
const sections = ["emotions", "love"].map((k) => analysis.sections?.[k]).filter((s) => s !== undefined);
@@ -130,6 +135,20 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
</h2>
</div>
<div className="lp-free-grid">
{forumEnabled() && (
<Link href="/forum" className="card lp-free-card lp-free-featured">
<span className="lp-free-featured-label">Közösség</span>
<strong>Fórum</strong>
<span className="lp-free-featured-text">
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.
</span>
<span className="lp-free-featured-quiet">
Pörgő videók helyett csendes, figyelmes beszélgetés: itt az elmélyülés a lényeg.
</span>
<span className="lp-free-go">Benézek →</span>
</Link>
)}
<Link href="/szuletesi-horoszkop" className="card lp-free-card">
<strong>Születési horoszkóp</strong>
<span className="muted">
@@ -442,6 +461,35 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
</div>
</section>
<section className="lp-band lp-alt lp-gift" aria-labelledby="gift-band-title">
<div className="lp-wrap lp-gift-inner">
{xmas && <ChristmasTree size={72} />}
<div className="lp-gift-text">
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "Ajándék"}</span>
<h2 id="gift-band-title" className="lp-h2">
{xmas ? "Ajándékozz csillagokat karácsonyra" : "Horoszkópot ajándékba"}
</h2>
<p className="lp-text">
Születési képlet, személyre szóló elemzés, és hogy mit hoz neki a következő éve, egy szép, nyomtatható
utalvánnyal.{" "}
{xmas ? "Az e-mailt karácsony reggelre is időzítheted." : "E-mailben küldjük el neki, vagy te adod át."}
</p>
<Link href={xmas ? "/karacsony" : "/ajandek"} className="btn lp-btn">
{xmas ? "Karácsonyi ajándék" : "Ajándékozás"}
</Link>
</div>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className="lp-gift-card"
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
width={200}
height={283}
alt=""
loading="lazy"
/>
</div>
</section>
<section className="lp-band">
<div className="lp-wrap lp-stack">
<h2 className="lp-h2 lp-center">Így működik</h2>
+105 -6
View File
@@ -147,6 +147,61 @@ export default async function PrivacyPage() {
<td>Hibák kijavítása, kérdések megválaszolása</td>
<td>Jogos érdek (6. cikk (1) f)</td>
</tr>
<tr>
<td>
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
</td>
<td>Részvétel a fórumon; a jegyek megosztása és a jelvények a saját döntésed</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>
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
</td>
<td>A fórum működése, a rangok, az újdonságok jelzése</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>
A fórumkérdéseidhez csatolt képlet, éves előrejelzés vagy összevetés megosztó linkje
</td>
<td>Hogy a tagok lássák, amiről kérdezel; a csatolás a saját döntésed</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>Zárt témákba küldött jelentkezéseid (a pár szavas indoklással) és a tagságaid</td>
<td>A zárt témák: a moderátorok döntenek a felvételről</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>Mikor jártál utoljára a fórumon</td>
<td>Az online jelzés (zöld pötty); a láthatatlan móddal kikapcsolhatod</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>
Privát beszélgetéseid: a kérések bemutatkozása, az elfogadás, elutasítás vagy tiltás, és az
üzenetek
</td>
<td>Privát beszélgetés más tagokkal</td>
<td>Szerződés teljesítése</td>
</tr>
<tr>
<td>
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
</td>
<td>A házirend betartatása, a bejelentések kezelése, a döntések visszakereshetősége</td>
<td>
Jogi kötelezettség ((EU) 2022/2065 rendelet, DSA; 6. cikk (1) c); jogos érdek (6. cikk (1) f)
</td>
</tr>
<tr>
<td>IP-cím, böngésző adatai, a kérések ideje (szervernaplók)</td>
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
@@ -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.
</p>
<p>
<strong>Fórum:</strong> 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{" "}
<Link href="/aszf#forum">ÁSZF 8. pontjában</Link> vannak.
</p>
</section>
<section>
@@ -186,7 +260,8 @@ export default async function PrivacyPage() {
</ul>
<p>
<strong>Mire használjuk:</strong> 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.
</p>
<p>
@@ -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.
</p>
<p>
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.
</p>
</section>
<section>
@@ -254,7 +333,9 @@ export default async function PrivacyPage() {
</li>
<li>
<strong>Cloudflare, Inc.</strong> – 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).
</li>
<li>
<strong>Google LLC</strong> – 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.
</li>
<li>A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.</li>
<li>
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.
</li>
<li>
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.
</li>
<li>
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.
</li>
</ul>
</section>
<section>
<h2>8. Sütik</h2>
<p>
Csak egy, a működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), 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 (<code>sf_session</code>), 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 (<code>sf_forum_theme</code>)
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.
</p>
<p>
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
@@ -323,13 +420,15 @@ export default async function PrivacyPage() {
<ul>
<li>
<strong>Hozzáférés és adathordozhatóság:</strong> a <Link href="/profil#adataim">Profil</Link> oldalon
egy kattintással letöltheted minden adatodat.
egy kattintással letöltheted minden adatodat, a fórumon írtakat és beállítottakat is.
</li>
<li>
<strong>Helyesbítés:</strong> a nevedet és a születési adataidat a Profil oldalon módosíthatod.
</li>
<li>
<strong>Törlés:</strong> a fiókodat és minden adatodat a Profil oldalon törölheted.
<strong>Törlés:</strong> 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.
</li>
<li>
<strong>Korlátozás és tiltakozás:</strong> a fenti e-mail-címen kérheted.
@@ -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). */
@@ -8,6 +8,16 @@ import type { AdminGift } from "@/lib/types";
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
/** The timed gift e-mails of one hour. */
type Slot = { at: string; waiting: number; sent: number; failed: number };
const EMAIL: Record<string, string> = {
scheduled: "levél időzítve",
sending: "levél küldés alatt",
sent: "levél kiment",
failed: "levél hiba",
};
const STORNO: Record<string, string> = {
pending: "sztornó folyamatban",
done: "sztornózva",
@@ -17,6 +27,7 @@ const STORNO: Record<string, string> = {
/** The gifts with their payment, invoice and storno, and the refund button. */
export function AdminGifts() {
const [gifts, setGifts] = useState<AdminGift[] | null>(null);
const [schedule, setSchedule] = useState<Slot[]>([]);
const [q, setQ] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -24,10 +35,11 @@ export function AdminGifts() {
const load = useCallback(async (search: string) => {
try {
const r = await api<{ gifts: AdminGift[] }>(
const r = await api<{ gifts: AdminGift[]; schedule: Slot[] }>(
`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`,
);
setGifts(r.gifts);
setSchedule(r.schedule ?? []);
} catch (e) {
setError(errorText(e));
}
@@ -66,153 +78,203 @@ export function AdminGifts() {
}
return (
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? (
<span className="hint">{huf(g.checkout.amount_huf)}</span>
) : null}
{g.checkout && g.checkout.live === false && (
<span className="hint">teszt fizetés</span>
)}
</td>
<td>
{g.buyer_email ?? (
<span className="muted">törölt fiók</span>
)}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email
? ` (${g.recipient_email})`
: " (maga adja át)"}
</span>
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva{" "}
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && (
<span className="hint">{g.redeemed_by}</span>
)}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">
visszatérítés félbemaradt
</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && (
<span className="hint">{g.refund_error}</span>
)}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">
{g.within_withdrawal
? "14 napon belül"
: "14 nap letelt"}
</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ??
(g.invoice.status === "pending"
? "kiállítás alatt"
: g.invoice.status)}
{g.storno && (
<span
className={
g.storno.status === "failed"
? "hint msg-error"
: "hint"
}
>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id
? "Folyamatban…"
: g.status === "refunded"
? "Újrapróbálás"
: "Visszatérítés"}
</button>
)}
</td>
<>
{schedule.length > 0 && (
<section className="card" aria-labelledby="schedule-title">
<h2 id="schedule-title">Időzített levelek</h2>
<p className="hint">
Az időzítve küldött ajándéklevelek óránként (magyar idő, az elmúlt
30 nap és ami még jön). Figyeld, hogy a kiment levelek száma az
időpont után megnőjön, és ne legyen hiba.
</p>
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Időpont</th>
<th>Vár</th>
<th>Kiment</th>
<th>Hiba</th>
</tr>
))}
</tbody>
</table>
</div>
</thead>
<tbody>
{schedule.map((s) => (
<tr key={s.at}>
<td className="num">{s.at}</td>
<td className="num">{s.waiting || "–"}</td>
<td className="num">{s.sent || "–"}</td>
<td className={s.failed ? "num msg-error" : "num"}>
{s.failed || "–"}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
)}
</section>
<section className="card">
<div className="field">
<label htmlFor="gift-search">Keresés</label>
<input
id="gift-search"
className="inp"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve"
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{done && (
<p className="msg msg-ok" role="status">
{done}
</p>
)}
{gifts === null ? (
<p className="muted">Betöltés…</p>
) : gifts.length === 0 ? (
<p className="muted">Nincs ilyen ajándék.</p>
) : (
<div className="table-wrap">
<table className="promo-table">
<thead>
<tr>
<th>Kód</th>
<th>Csomag</th>
<th>Vásárló → címzett</th>
<th>Fizetve</th>
<th>Állapot</th>
<th>Számla</th>
<th />
</tr>
</thead>
<tbody>
{gifts.map((g) => (
<tr key={g.id}>
<td>
<code className="promo-code">{g.code}</code>
</td>
<td>
{g.package.name ?? g.package.id}
{g.checkout?.amount_huf ? (
<span className="hint">
{huf(g.checkout.amount_huf)}
</span>
) : null}
{g.checkout && g.checkout.live === false && (
<span className="hint">teszt fizetés</span>
)}
</td>
<td>
{g.buyer_email ?? (
<span className="muted">törölt fiók</span>
)}
<span className="hint">
→ {g.recipient_name ?? "?"}
{g.recipient_email
? ` (${g.recipient_email})`
: " (maga adja át)"}
</span>
{g.email_state && (
<span
className={
g.email_state === "failed"
? "hint msg-error"
: "hint"
}
>
{EMAIL[g.email_state]}
{g.send_at ? ` · ${formatDate(g.send_at, true)}` : ""}
</span>
)}
</td>
<td className="num">{formatDate(g.paid_at, true)}</td>
<td>
{g.status === "redeemed" ? (
<>
beváltva{" "}
{g.redeemed_at ? formatDate(g.redeemed_at, true) : ""}
{g.redeemed_by && (
<span className="hint">{g.redeemed_by}</span>
)}
</>
) : g.status === "refunded" ? (
<>
{g.refund_pending ? (
<span className="msg-error">
visszatérítés félbemaradt
</span>
) : (
"visszatérítve"
)}{" "}
{g.refunded_at ? formatDate(g.refunded_at, true) : ""}
{g.refund_pending && g.refund_error && (
<span className="hint">{g.refund_error}</span>
)}
</>
) : (
<>
<span className="promo-open">beváltatlan</span>
<span className="hint">
{g.within_withdrawal
? "14 napon belül"
: "14 nap letelt"}
</span>
</>
)}
</td>
<td>
{g.invoice ? (
<>
{g.invoice.number ??
(g.invoice.status === "pending"
? "kiállítás alatt"
: g.invoice.status)}
{g.storno && (
<span
className={
g.storno.status === "failed"
? "hint msg-error"
: "hint"
}
>
{STORNO[g.storno.status] ?? g.storno.status}
{g.storno.number ? `: ${g.storno.number}` : ""}
{g.storno.error ? ` – ${g.storno.error}` : ""}
</span>
)}
</>
) : (
<span className="muted">–</span>
)}
</td>
<td>
{(g.status === "open" || g.refund_pending) && (
<button
type="button"
className="btn btn-sm"
onClick={() => refund(g)}
disabled={busy !== null}
>
{busy === g.id
? "Folyamatban…"
: g.status === "refunded"
? "Újrapróbálás"
: "Visszatérítés"}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</>
);
}
+112 -1
View File
@@ -7,6 +7,7 @@ import { useEffect, useId, useState } from "react";
import { huf } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { contents } from "@/lib/packageContents";
import { christmasMorning } from "@/lib/season";
import type { Package, PayMethod } from "@/lib/types";
const MAX_MESSAGE = 300;
@@ -17,6 +18,19 @@ const looksLikeEmail = (s: string) =>
const same = (a: string, b: string) =>
a.trim().toLowerCase() === b.trim().toLowerCase();
/** `2026-12-24` on the browser's clock. */
const localDay = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
/** "dec. 24. 8:00" */
const whenText = (d: Date) =>
d.toLocaleString("hu-HU", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
/**
* The gift order: which package, whom it is for and from whom, how it gets
* to the recipient (we e-mail it, the address typed twice; or the buyer
@@ -49,6 +63,10 @@ export function GiftForm({
const [confirm, setConfirm] = useState("");
const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME));
const [message, setMessage] = useState("");
const [timed, setTimed] = useState(false);
const xmas = christmasMorning();
const [day, setDay] = useState(xmas ? localDay(xmas) : "");
const [clock, setClock] = useState("08:00");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Back from Stripe's page (the browser may restore this page as it was).
@@ -64,6 +82,14 @@ export function GiftForm({
const mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm);
const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm));
const stripe = canPay === "stripe" || canPay === "stripe_test";
// The chosen moment on the buyer's own clock.
const sendAt = day && clock ? new Date(`${day}T${clock}`) : null;
const ahead = sendAt ? sendAt.getTime() - Date.now() : 0;
const timeOk =
sendAt !== null &&
!Number.isNaN(ahead) &&
ahead > 10 * 60 * 1000 &&
ahead < 365 * 86400 * 1000;
async function submit(e: React.FormEvent) {
e.preventDefault();
@@ -81,6 +107,7 @@ export function GiftForm({
recipient_email_confirm: byEmail ? confirm.trim() : null,
from_name: from.trim() || null,
message: message.trim() || null,
send_at: byEmail && timed && sendAt ? sendAt.toISOString() : null,
},
},
);
@@ -223,6 +250,81 @@ export function GiftForm({
</div>
</div>
)}
{byEmail && (
<div className="gift-when">
<span className="label">Mikor kapja meg?</span>
<div className="gift-when-choices">
<label
className={!timed ? "feedback-kind is-on" : "feedback-kind"}
>
<input
type="radio"
name={`${id}-when`}
checked={!timed}
onChange={() => setTimed(false)}
/>
Fizetés után azonnal
</label>
<label
className={timed ? "feedback-kind is-on" : "feedback-kind"}
>
<input
type="radio"
name={`${id}-when`}
checked={timed}
onChange={() => setTimed(true)}
/>
Időzítve
</label>
{xmas && (
<button
type="button"
className="btn btn-sm"
onClick={() => {
setTimed(true);
setDay(localDay(xmas));
setClock("08:00");
}}
>
Karácsony reggel (dec. 24., 8:00)
</button>
)}
</div>
{timed && (
<div className="gift-when-fields">
<div className="field">
<label htmlFor={`${id}-day`}>Nap</label>
<input
id={`${id}-day`}
className="inp"
type="date"
value={day}
min={localDay(new Date())}
onChange={(e) => setDay(e.target.value)}
/>
</div>
<div className="field">
<label htmlFor={`${id}-clock`}>Időpont</label>
<input
id={`${id}-clock`}
className="inp"
type="time"
step={900}
value={clock}
onChange={(e) => setClock(e.target.value)}
/>
</div>
</div>
)}
<span className={timed && !timeOk ? "msg msg-error" : "hint"}>
{timed
? timeOk
? "A te időd szerint. Addig az Ajándékaim oldalon letöltheted az utalványt, vagy elküldheted azonnal is."
: "Válassz egy jövőbeli időpontot (legfeljebb egy évre előre)."
: "Ha későbbre szánod, időzítsd, vagy válaszd az „Én adom át” lehetőséget."}
</span>
</div>
)}
</fieldset>
<div className="field">
@@ -253,6 +355,9 @@ export function GiftForm({
<span className="muted">
„{chosen.name}” csomag ajándékba
{name.trim() ? `, ${name.trim()} részére` : ""}
{byEmail && timed && sendAt && timeOk
? ` · küldés: ${whenText(sendAt)}`
: ""}
</span>
<strong className="num">{huf(chosen.price_huf)}</strong>
</p>
@@ -261,7 +366,13 @@ export function GiftForm({
<button
type="submit"
className="btn btn-primary"
disabled={busy || !chosen || !emailOk || !name.trim()}
disabled={
busy ||
!chosen ||
!emailOk ||
!name.trim() ||
(byEmail && timed && !timeOk)
}
>
{busy
? stripe
+42 -11
View File
@@ -1,25 +1,50 @@
import type { Metadata } from "next";
import Link from "next/link";
import { GiftLanding } from "@/components/GiftLanding";
import { PublicHeader } from "@/components/SiteHeader";
import { payMethod } from "@/lib/payments";
import { backendGet, requireMe } from "@/lib/server";
import { isChristmasTime } from "@/lib/season";
import { backendGet, getMe } from "@/lib/server";
import { siteUrl } from "@/lib/share";
import type { Gift, Package, PublicConfig } from "@/lib/types";
import { GiftForm } from "./GiftForm";
export const metadata: Metadata = {
title: "Ajándék csomag",
robots: { index: false },
};
export async function generateMetadata(): Promise<Metadata> {
const base = await siteUrl();
const title = "Horoszkóp ajándékba";
const description =
"Ajándékozz születési képletet, személyre szóló elemzést és éves előrejelzést. Nyomtatható utalvány, e-mailben időzítve vagy személyesen átadva.";
return {
title,
description,
alternates: { canonical: `${base}/ajandek` },
openGraph: { type: "website", siteName: "Sorsfonalak", locale: "hu_HU", url: `${base}/ajandek`, title, description },
};
}
type Props = { searchParams: Promise<{ csomag?: string }> };
/** Buying a package as a gift; `?csomag=` picks the package (links on the package cards). */
export default async function GiftPage({ searchParams }: Props) {
const { csomag } = await searchParams;
const me = await requireMe(
csomag ? `/ajandek?csomag=${encodeURIComponent(csomag)}` : "/ajandek",
);
const me = await getMe();
if (!me) {
// Visitors (and search engines) get the page about giving; the form needs a login.
const catalog = await backendGet<{ packages: Package[] }>("/v1/packages");
return (
<>
<PublicHeader />
<GiftLanding
packages={(catalog?.packages ?? []).filter((p) => p.tier === "main")}
loggedIn={false}
christmas={false}
season={isChristmasTime()}
/>
</>
);
}
const [catalog, config, mine] = await Promise.all([
backendGet<{ packages: Package[] }>("/v1/packages"),
backendGet<PublicConfig>("/v1/config"),
@@ -27,11 +52,13 @@ export default async function GiftPage({ searchParams }: Props) {
]);
const packages = (catalog?.packages ?? []).filter((p) => p.tier === "main");
const given = mine?.gifts.length ?? 0;
// Gifts bought now get the Christmas card.
const xmas = isChristmasTime();
return (
<main className="page" style={{ maxWidth: 1080 }}>
<div className="page-head">
<span className="eyebrow">Ajándék</span>
<span className="eyebrow">{xmas ? "Karácsonyi ajándék" : "Ajándék"}</span>
<h1>Ajándékozz csomagot</h1>
<p className="muted">
Születési képlet, személyre szóló elemzések, kapcsolati összevetés:
@@ -57,7 +84,7 @@ export default async function GiftPage({ searchParams }: Props) {
<figure className="gift-sample">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/img/ajandek-utalvany.webp"
src={xmas ? "/img/ajandek-karacsony.webp" : "/img/ajandek-utalvany.webp"}
width={420}
height={594}
alt="Minta ajándékutalvány: a csomag neve, a személyes üzenet, az ajándékkód és a QR-kód"
@@ -81,7 +108,11 @@ export default async function GiftPage({ searchParams }: Props) {
<p className="hint">
A kód nem jár le, és egyszer váltható be. A számlát te kapod. Ha
meggondolod magad, 14 napon belül, beváltás előtt visszakérheted
az árát: írj az info@sorsfonalak.hu címre.
az árát:{" "}
<Link href="/visszajelzes?tipus=other&honnan=/ajandekaim">
írd meg nekünk itt
</Link>
.
</p>
</section>
</aside>
@@ -12,6 +12,15 @@ const day = (iso: string) =>
month: "long",
day: "numeric",
});
/** "december 24., 8:00" */
const when = (iso: string) =>
new Date(iso).toLocaleString("hu-HU", {
timeZone: "Europe/Budapest",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
const time = (iso: string) =>
new Date(iso).toLocaleTimeString("hu-HU", {
timeZone: "Europe/Budapest",
@@ -127,7 +136,19 @@ function GiftItem({
</div>
<p className="gift-to">
{gift.recipient_email ? (
{gift.recipient_email &&
gift.email_state === "scheduled" &&
gift.send_at ? (
<>
Időzítve: <strong>{when(gift.send_at)}</strong>, ide:{" "}
<strong>{gift.recipient_email}</strong>
</>
) : gift.recipient_email && gift.email_state === "failed" ? (
<>
Nem sikerült elküldeni ide: <strong>{gift.recipient_email}</strong>.
Ellenőrizd a címet, és küldd újra.
</>
) : gift.recipient_email ? (
<>
E-mailben elküldve ide: <strong>{gift.recipient_email}</strong>
{gift.sendings > 1 ? ` (${gift.sendings}×)` : ""}
@@ -165,9 +186,11 @@ function GiftItem({
className="btn btn-sm"
onClick={() => setSending(true)}
>
{gift.recipient_email
? "Újraküldés e-mailben"
: "Küldés e-mailben"}
{gift.email_state === "scheduled"
? "Küldés most"
: gift.recipient_email
? "Újraküldés e-mailben"
: "Küldés e-mailben"}
</button>
)}
</div>
@@ -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 });
+116 -9
View File
@@ -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).
</p>
<p>
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() {
</p>
</section>
<section>
<h2>8. A fiók megszüntetése</h2>
<section id="forum">
<h2>8. A fórum</h2>
<p>
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.
</p>
<h3>8.1. Olvasás, írás, álnév</h3>
<p>
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.
</p>
<h3>8.2. Házirend</h3>
<p>A fórum a nyugodt beszélgetés és a meghallgatás helye. Kérjük:</p>
<ul>
<li>tisztelettel írj másokról és másokhoz, kioktatás és gúnyolódás nélkül;</li>
<li>ha valaki csak meghallgatást kér, ne adj neki kéretlen tanácsot;</li>
<li>vitatkozz gondolatokkal, ne mások hitével, világnézetével vagy életével.</li>
</ul>
<p>Tilos:</p>
<ul>
<li>mások zaklatása, fenyegetése, sértegetése, a gyűlöletkeltés;</li>
<li>jogsértő tartalom, például szerzői jogot sértő szöveg vagy bűncselekményre való felhívás;</li>
<li>
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;
</li>
<li>
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;
</li>
<li>pénz, adatok vagy szívességek kérése megtévesztéssel, más nevében való fellépés;</li>
<li>biztatás orvosi kezelés abbahagyására vagy helyettesítésére.</li>
</ul>
<p>
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.
</p>
<h3>8.3. A hozzászólások</h3>
<p>
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.
</p>
<h3>8.4. Privát üzenetek</h3>
<p>
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.
</p>
<h3>8.5. Rangok és korlátok</h3>
<p>
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.
</p>
<h3>8.6. Bejelentés és moderálás</h3>
<p>
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.
</p>
<p>
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.
</p>
<p>
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.
</p>
<p>
Kapcsolattartási pont a hatóságok és a felhasználók számára (DSA 11. és 12. cikk): {email}, magyar nyelven.
</p>
<h3>8.7. Értesítések</h3>
<p>
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.
</p>
</section>
<section>
<h2>9. Panaszkezelés, jogorvoslat</h2>
<h2>9. A fiók megszüntetése</h2>
<p>
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).
</p>
</section>
<section>
<h2>10. Panaszkezelés, jogorvoslat</h2>
<p>
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() {
</section>
<section>
<h2>10. Egyéb</h2>
<h2>11. Egyéb</h2>
<p>
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() {
</section>
<section>
<h2>11. A szolgáltató adatai</h2>
<h2>12. A szolgáltató adatai</h2>
<OperatorDetails hosting />
</section>
</main>
@@ -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<string | null>(null);
const [sent, setSent] = useState<Mode | null>(null);
const [uninvited, setUninvited] = useState(false);
// Turnstile's token (sign-up and reset only); a new round after each try.
const [token, setToken] = useState<string | null>(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ó?
</button>
</div>
<input
<PasswordInput
id="pw-password"
className="inp"
type="password"
required
autoComplete="current-password"
value={password}
@@ -156,14 +173,17 @@ export function PasswordLogin({
jelszót is beállíthatsz.
</p>
)}
<button type="submit" className="btn btn-primary" disabled={busy}>
{mode !== "login" && turnstileKey && <Turnstile siteKey={turnstileKey} onToken={setToken} round={round} />}
<button type="submit" className="btn btn-primary" disabled={busy || (!checked && !token)}>
{busy
? "Küldés…"
: mode === "login"
? "Belépés"
: mode === "register"
? "Regisztráció"
: "Link küldése"}
: !checked && !token
? "Egy pillanat…"
: mode === "login"
? "Belépés"
: mode === "register"
? "Regisztráció"
: "Link küldése"}
</button>
{error && (
<p className="msg msg-error" role="alert" style={{ margin: 0 }}>
+7 -1
View File
@@ -169,7 +169,13 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
</div>
)}
{password && (
<PasswordLogin target={target} inviteToken={pendingInvite} referral={referral} initialMode={initialMode} />
<PasswordLogin
target={target}
inviteToken={pendingInvite}
referral={referral}
initialMode={initialMode}
turnstileKey={config?.turnstile_site_key ?? null}
/>
)}
</>
) : (
+12 -7
View File
@@ -5,6 +5,8 @@ import { AiNote } from "@/components/AiNote";
import { PackageCards } from "@/components/PackageCards";
import { RedeemCode } from "@/components/RedeemCode";
import { payMethod } from "@/lib/payments";
import { isChristmasTime } from "@/lib/season";
import { ChristmasTree } from "@/components/ChristmasTree";
import { backendGet, requireMe } from "@/lib/server";
import type { Package, PublicConfig } from "@/lib/types";
@@ -17,7 +19,7 @@ const FAQ: [string, string][] = [
],
[
"Lejárnak a megvett elemzések?",
"Nem. A csomagokban kapott elemzések és személyhelyek addig megmaradnak, amíg fel nem használod őket.",
"Nem. A csomagokban kapott elemzések addig megmaradnak, amíg fel nem használod őket.",
],
[
"Mi a különbség a képletelemzés és a kapcsolati elemzés között?",
@@ -36,8 +38,8 @@ const FAQ: [string, string][] = [
"Kérdezel, kiválasztasz egy kirakást (1, 3 vagy 5 lap), és húzol a megkevert pakliból. A kihúzott lapokra, a kérdésedre és a képleted Napjára, Holdjára és Aszcendensére személyre szabott értelmezés készül. Egy jóslás egyet használ, a kirakás méretétől függetlenül. A csomagokban van néhány, és külön is vehetsz ötöt egyben.",
],
[
"Mire kell a személyhely?",
"A saját képleted mellé felvett emberekhez (társ, gyerek, barát). Egy személy felvétele egy helyet használ; a képlete és a rövid összefoglalója ingyenes, a részletes elemzés külön jár.",
"Kell fizetni a személyek felvételéért?",
"Nem. A saját képleted mellé ingyen felvehetsz 30 embert (társ, gyerek, barát): a képletük és a rövid összefoglalójuk ingyenes, csomag a részletes elemzésükhöz és az előrejelzésükhöz kell. Ha ennél több kell, írj nekünk, és megnöveljük.",
],
];
@@ -50,6 +52,7 @@ export default async function PackagesPage() {
]);
const packages = catalog?.packages ?? [];
const canPay = payMethod(config, me);
const xmas = isChristmasTime();
const left = me.analyses_left;
const slots = me.persons;
@@ -99,15 +102,17 @@ export default async function PackagesPage() {
<PackageCards packages={packages} canPay={canPay} giftLinks />
<section className="card gift-banner" aria-labelledby="gift-title">
<div>
<h2 id="gift-title">Ajándékba is adhatod</h2>
{xmas && <ChristmasTree />}
<div className="gift-banner-text">
<h2 id="gift-title">{xmas ? "Karácsonyi ajándék a csillagokból" : "Ajándékba is adhatod"}</h2>
<p className="muted">
A három fő csomag bármelyikét megveheted másnak: e-mailben elküldjük neki egy nyomtatható utalvánnyal, vagy
letöltöd, és te adod át. A kódot ő váltja be a saját fiókjában, és nem jár le.
{xmas && " Karácsony reggelre is időzítheted."}
</p>
</div>
<Link className="btn" href="/ajandek">
Megajándékozok valakit
<Link className="btn" href={xmas ? "/karacsony" : "/ajandek"}>
{xmas ? "Karácsonyi ajándék" : "Megajándékozok valakit"}
</Link>
</section>
@@ -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<TopicPage>(`/v1/forum/topics/${encodeURIComponent(slug)}?page=${page}`);
}
function pageOf(raw: string | undefined): number {
const n = Number(raw ?? 1);
return Number.isInteger(n) && n > 0 ? n : 1;
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { tema } = await params;
const res = await load(tema, 1);
if (!res.ok) return { title: "Fórum" };
const { topic } = res.data;
// Members-only topics stay out of search engines.
return {
title: topic.name,
description: topic.description,
robots: topic.visibility === "public" ? undefined : { index: false, follow: false },
};
}
/** A topic's threads: pinned ones first, then by the latest post. */
export default async function TopicPageView({ params, searchParams }: Props) {
const { tema } = await params;
const page = pageOf((await searchParams).oldal);
const res = await load(tema, page);
if (!res.ok) {
if (res.status === 401) redirect(`/belepes?vissza=/forum/${tema}`);
notFound();
}
const { topic, threads, has_more, viewer } = res.data;
return (
<div className="fh">
<nav className="forum-crumbs" aria-label="Morzsamenü">
<Link href="/forum">Fórum</Link>
</nav>
<header className="ftopic-head">
<div>
<h1>{topic.name}</h1>
<p className="muted">{topic.description}</p>
{topic.visibility !== "public" && (
<p className="ftopic-private">
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="5" y="11" width="14" height="9" rx="2" />
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
</svg>
{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."}
</p>
)}
{topic.archived && (
<p className="ftopic-private">
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="3.5" y="4.5" width="17" height="4.5" rx="1" />
<path d="M5 9v9.5a1.5 1.5 0 0 0 1.5 1.5h11a1.5 1.5 0 0 0 1.5-1.5V9M10 13h4" />
</svg>
Archivált téma: a szálak olvashatók, de új szál és hozzászólás már nem írható.
</p>
)}
</div>
{!topic.archived && (
<Link
href={viewer.logged_in ? `/forum/uj?tema=${topic.slug}` : `/belepes?vissza=/forum/uj?tema=${topic.slug}`}
className="btn btn-primary"
>
Új szál
</Link>
)}
</header>
{threads.length === 0 ? (
<p className="fh-card fh-empty">Ebben a témában még nincs szál. Nyisd meg te az elsőt!</p>
) : (
<div className="fh-card fh-flush">
<ThreadList threads={threads} showTopic={false} />
</div>
)}
{(page > 1 || has_more) && (
<nav className="forum-pager" aria-label="Lapozás">
{page > 1 ? <Link href={`/forum/${topic.slug}?oldal=${page - 1}`}>‹ Újabbak</Link> : <span />}
<span className="hint">{page}. oldal</span>
{has_more ? <Link href={`/forum/${topic.slug}?oldal=${page + 1}`}>Régebbiek ›</Link> : <span />}
</nav>
)}
</div>
);
}
@@ -0,0 +1,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<ForumAuthor[] | null>(null);
useEffect(() => {
api<{ muted: ForumAuthor[] }>("/forum/me/mutes")
.then((res) => setMuted(res.muted))
.catch(() => setMuted([]));
}, []);
if (!muted || muted.length === 0) return null;
return (
<fieldset className="fnew-set">
<legend>Elnémított tagok</legend>
<ul className="fmuted">
{muted.map((m) => (
<li key={m.nickname}>
<span className="fh-online-item">
<Avatar avatar={m.avatar} size={28} />
{m.nickname}
</span>
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={async () => {
await api(`/forum/members/${encodeURIComponent(m.nickname)}/mute`, { method: "DELETE" });
setMuted((list) => (list ?? []).filter((x) => x.nickname !== m.nickname));
}}
>
Feloldás
</button>
</li>
))}
</ul>
<span className="hint">
Az elnémított tagok szálai nem jelennek meg a listáidban, és nem kapsz értesítést tőlük.
</span>
</fieldset>
);
}
@@ -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<ChartShare>(member?.chart_share ?? "none");
const [invisible, setInvisible] = useState(member?.invisible ?? false);
const [email, setEmail] = useState<EmailSettings>(
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<string | null>(null);
const [saved, setSaved] = useState(false);
// While typing: valid and free? (Not for the member's own current name.)
useEffect(() => {
const name = nickname.trim();
if (!name || name === member?.nickname) {
setCheck(null);
return;
}
const timer = window.setTimeout(() => {
api<{ ok: boolean; message?: string }>(`/forum/nickname-check?name=${encodeURIComponent(name)}`)
.then(setCheck)
.catch(() => setCheck(null));
}, 400);
return () => window.clearTimeout(timer);
}, [nickname, member?.nickname]);
async function submit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
setSaved(false);
try {
const res = await api<ForumMe>("/forum/me", {
method: "PUT",
body: {
nickname,
avatar: avatar || null,
bio,
chart_share: share,
invisible,
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 (
<form className="fprof" onSubmit={submit}>
{member?.banned_until && (
<p className="fh-banner fh-banner-warn">
Most nem írhatsz a fórumba ({banText(member.banned_until)}).
{member.ban_reason && ` Indok: ${member.ban_reason}`}
</p>
)}
<div className="field">
<label htmlFor="fprof-nick">Álnév</label>
<input
id="fprof-nick"
className="inp"
value={nickname}
onChange={(e) => setNickname(e.target.value)}
maxLength={24}
required
autoComplete="off"
aria-describedby="fprof-nick-hint"
/>
<span id="fprof-nick-hint" className={check && !check.ok ? "hint warn" : "hint"}>
{check && !check.ok
? check.message
: check?.ok
? "Szabad, választhatod."
: "Ne a valódi neved legyen, ha nem szeretnéd, hogy felismerjenek. 3–24 karakter: betűk, számok, szóköz, kötőjel."}
</span>
{member?.nickname_change_after && (
<span className="hint">
Új álnevet{" "}
{new Date(member.nickname_change_after).toLocaleDateString("hu-HU", { month: "long", day: "numeric" })} után
választhatsz (az ékezet és a kis- és nagybetű javítható addig is).
</span>
)}
</div>
<fieldset className="fnew-set">
<legend>Avatar</legend>
<div className="fprof-avatars">
{AVATAR_COLOURS.flatMap((colour) =>
AVATAR_GLYPHS.map((glyph) => {
const value = `${glyph}-${colour}`;
return (
<label key={value} className="fprof-avatar" title={GLYPH_NAMES[glyph]}>
<input
type="radio"
name="avatar"
value={value}
checked={avatar === value}
onChange={() => setAvatar(value)}
className="sr-only"
/>
<Avatar avatar={value} size={44} />
<span className="sr-only">{GLYPH_NAMES[glyph]}</span>
</label>
);
}),
)}
</div>
{!avatar && <span className="hint">Ha nem választasz, az álneved alapján kapsz egyet.</span>}
{member?.can_upload_avatar && (
<div className="fprof-upload">
{uploaded && <Avatar avatar={avatar} size={56} />}
<label className="btn btn-sm fprof-upload-btn">
{uploading ? "Feltöltés…" : uploaded ? "Másik kép" : "Saját kép feltöltése"}
<input
type="file"
accept="image/jpeg,image/png,image/webp"
className="sr-only"
disabled={uploading}
onChange={async (e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
setUploading(true);
setError(null);
try {
const res = await fetch("/api/v1/forum/me/avatar", {
method: "PUT",
body: file,
headers: { "content-type": file.type || "application/octet-stream" },
credentials: "same-origin",
});
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error(data?.error?.message ?? "A feltöltés nem sikerült.");
setAvatar(data.avatar);
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : errorText(err));
} finally {
setUploading(false);
}
}}
/>
</label>
<span className="hint">
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.
</span>
</div>
)}
</fieldset>
<div className="field">
<label htmlFor="fprof-bio">Bemutatkozás</label>
<textarea
id="fprof-bio"
className="fc-text"
rows={4}
maxLength={500}
value={bio}
onChange={(e) => withEmoji(e, setBio)}
placeholder="Pár mondat magadról, ha szeretnéd."
/>
<span className="hint">{bio.length}/500 · link nem tehető bele</span>
</div>
<fieldset className="fnew-set">
<legend>Mit mutatsz meg a képletedből?</legend>
<div className="fnew-intents">
{SHARE_LEVELS.map((level) => (
<label key={level.value} className="fnew-intent">
<input type="radio" name="share" checked={share === level.value} onChange={() => setShare(level.value)} />
<span>
<strong>{level.label}</strong>
</span>
</label>
))}
</div>
<span className="hint">
{me.chart === null
? "Még nincs saját képleted, így most semmi nem látszana."
: preview
? `Így látszik a neved mellett: ${signsText(preview)}`
: share === "none"
? "Semmi nem látszik a képletedből."
: "Ehhez a szinthez nincs adat a képletedben."}{" "}
Fokokat soha nem mutatunk, mert azokból kiszámolható a születési időd.
</span>
</fieldset>
<label className="fprof-check">
<input type="checkbox" checked={invisible} onChange={(e) => setInvisible(e.target.checked)} />
<span>
<strong>Láthatatlan mód</strong>
<span className="hint">Nem jelenik meg mellettem a zöld pötty, és az sem, mikor jártam itt utoljára.</span>
</span>
</label>
{member?.can_listen && (
<label className="fprof-check">
<input type="checkbox" checked={listener} onChange={(e) => setListener(e.target.checked)} />
<span>
<strong>Önkéntes kísérő vagyok</strong>
<span className="hint">
Szívesen válaszolok azoknak, akik meghallgatást kérnek. A nevem mellett megjelenik a „Kísérő” jelvény, és
a fórum főoldalán látom, hány ilyen szál vár válaszra. E-mailt is kérhetsz róla lent.
</span>
</span>
</label>
)}
{me.can_supporter && (
<label className="fprof-check">
<input type="checkbox" checked={supporter} onChange={(e) => setSupporter(e.target.checked)} />
<span>
<strong>Támogató jelvény</strong>
<span className="hint">
Vásároltál csomagot: ha szeretnéd, a neved mellett megjelenik a „Támogató” jelvény. Rangot nem ad.
</span>
</span>
</label>
)}
<fieldset className="fnew-set">
<legend>Értesítések e-mailben</legend>
<div className="fprof-mail">
<label htmlFor="fprof-mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
<select
id="fprof-mail-replies"
className="inp"
value={email.replies}
onChange={(e) => setEmail({ ...email, replies: e.target.value as EmailSettings["replies"] })}
>
<option value="daily">Napi összesítőben, este</option>
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
<option value="off">Ne küldjetek</option>
</select>
<label htmlFor="fprof-mail-followed">Új hozzászólás a követett szálaimban</label>
<select
id="fprof-mail-followed"
className="inp"
value={email.followed}
onChange={(e) => setEmail({ ...email, followed: e.target.value as EmailSettings["followed"] })}
>
<option value="off">Ne küldjetek</option>
<option value="daily">Napi összesítőben, este</option>
</select>
<label htmlFor="fprof-mail-messages">Privát üzenet vagy beszélgetési kérés</label>
<select
id="fprof-mail-messages"
className="inp"
value={email.messages}
onChange={(e) => setEmail({ ...email, messages: e.target.value as EmailSettings["messages"] })}
>
<option value="instant">Azonnal</option>
<option value="off">Ne küldjetek</option>
</select>
<label htmlFor="fprof-mail-mentions">Ha valaki megemlít (@{nickname || "álnév"})</label>
<select
id="fprof-mail-mentions"
className="inp"
value={email.mentions}
onChange={(e) => setEmail({ ...email, mentions: e.target.value as EmailSettings["mentions"] })}
>
<option value="instant">Azonnal</option>
<option value="off">Ne küldjetek</option>
</select>
{listener && (
<>
<label htmlFor="fprof-mail-listener">
Kísérőként: ha egy meghallgatást kérő szál két órája válasz nélkül vár
</label>
<select
id="fprof-mail-listener"
className="inp"
value={email.listener}
onChange={(e) => setEmail({ ...email, listener: e.target.value as EmailSettings["listener"] })}
>
<option value="off">Ne küldjetek</option>
<option value="instant">Azonnal (hat óránként legfeljebb egy levél)</option>
</select>
</>
)}
</div>
<label className="fprof-check fprof-check-plain">
<input
type="checkbox"
checked={email.weekly}
onChange={(e) => setEmail({ ...email, weekly: e.target.checked })}
/>
<span>
<strong>Heti összefoglaló</strong>
<span className="hint">Vasárnap este: a hét legélénkebb szálai, és ami még válaszra vár.</span>
</span>
</label>
<span className="hint">
Ha éppen itt vagy a fórumon, nem küldünk levelet: a válaszokat a Válaszok fülön, az üzeneteket az Üzenetek
fülön látod. A privát üzenetek szövege nem kerül bele a levélbe.
</span>
</fieldset>
{member && <MutedList />}
{member && (
<div className="fprof-rank">
<span className="eyebrow">Rangod</span>
<strong>{member.rank_name}</strong>
<span className="hint">
{member.points} pont · {member.post_count} hozzászólás
{member.next_rank &&
` · a ${member.next_rank.name} ranghoz ${member.next_rank.points} pont és ${member.next_rank.days} nap tagság kell`}
</span>
</div>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{saved && <p className="msg">Elmentve.</p>}
<button type="submit" className="btn btn-primary" disabled={busy || !nickname.trim() || check?.ok === false}>
{busy ? "Mentés…" : member ? "Mentés" : "Álnév mentése"}
</button>
</form>
);
}
@@ -0,0 +1,32 @@
import { redirect } from "next/navigation";
import type { ForumMe } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
import { ProfileForm } from "./ProfileForm";
export const metadata = { title: "Fórumprofil", robots: { index: false } };
type Props = { searchParams: Promise<{ vissza?: string }> };
/** The member's forum profile: the nickname first, then avatar, bio, signs, visibility. */
export default async function ForumSettingsPage({ searchParams }: Props) {
const { vissza } = await searchParams;
const res = await forumGet<ForumMe>("/v1/forum/me");
if (!res.ok) redirect(`/belepes?vissza=${encodeURIComponent("/forum/beallitasok")}`);
// Only back into the forum.
const back = vissza?.startsWith("/forum") ? vissza : null;
const me = res.data;
return (
<div className="fh">
<h1 className="fpage-title">{me.member ? "Fórumprofil" : "Válassz álnevet"}</h1>
{!me.member && (
<p className="muted">
A fórumon mindenki álnéven ír. A valódi neved, az e-mail-címed és a születési adataid soha nem jelennek meg
itt.
</p>
)}
<ProfileForm me={me} back={back} />
</div>
);
}
+788
View File
@@ -0,0 +1,788 @@
/* The forum: phones first (most members write from a phone), big touch
targets and text for the 50+ readers. Light by default, dark on request
(data-theme on .forum, from a cookie): both redefine the site's colour
tokens for the forum's part of the page, so the shared .btn, .inp, .hint
and links follow. */
/* --- themes --- */
.forum {
/* Colour emoji wherever the system has them (no monochrome symbol fonts). */
--font-body: var(--font-inter), Inter, system-ui, "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
font-family: var(--font-body);
--f-hover: rgba(255, 255, 255, 0.04);
--f-tint: rgba(217, 180, 106, 0.1);
--f-tint-strong: rgba(217, 180, 106, 0.14);
--f-nav-bg: rgba(13, 18, 32, 0.97);
--f-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);
--f-border-hover: #5a6790;
--f-online: #9fd8b0;
--f-blue-tint: rgba(127, 176, 224, 0.12);
--f-orange-tint: rgba(240, 163, 94, 0.12);
--f-red-tint: rgba(242, 160, 160, 0.08);
--f-green-tint: rgba(159, 216, 176, 0.12);
--r-with_you: #e58aa6;
--r-thanks: #d9b46a;
--r-me_too: #7fb0e0;
--r-insight: #c3a6f0;
color: var(--ink);
}
.forum[data-theme="light"] {
--bg: #f6f3ed;
--panel: #ffffff;
--panel-2: #faf8f4;
--line: #e6dfd2;
--line-2: #d3c9b6;
--ink: #1b2236;
--ink-2: #3a4259;
--muted: #5c6376;
--gold: #8a6a24;
--gold-hover: #6e5419;
--gold-ink: #ffffff;
--danger: #b03a3a;
--ok: #2d7a4c;
--harmonic: #2c66a0;
--square: #9c520e;
--f-hover: rgba(27, 34, 54, 0.04);
--f-tint: rgba(167, 128, 47, 0.09);
--f-tint-strong: rgba(167, 128, 47, 0.14);
--f-nav-bg: rgba(255, 255, 255, 0.97);
--f-shadow: 0 12px 32px rgba(27, 34, 54, 0.14);
--f-border-hover: #a99d86;
--f-online: #2fa865;
--f-blue-tint: rgba(44, 102, 160, 0.09);
--f-orange-tint: rgba(156, 82, 14, 0.09);
--f-red-tint: rgba(176, 58, 58, 0.07);
--f-green-tint: rgba(45, 122, 76, 0.1);
--r-with_you: #b4466a;
--r-thanks: #8a6a24;
--r-me_too: #2c66a0;
--r-insight: #6b4fa0;
color-scheme: light;
}
/* The light forum takes the whole page between the (dark) header and footer
(the body rule; the background here is for browsers without :has). */
.forum[data-theme="light"] { background: var(--bg); min-height: 70vh; }
body:has(.forum[data-theme="light"]) { background: #f6f3ed; }
body:has(.forum[data-theme="light"]) .night-sky { display: none; }
body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
.forum[data-theme="light"] .inp:focus { background-color: var(--panel); box-shadow: 0 0 0 3px rgba(167, 128, 47, 0.22); }
.forum[data-theme="light"] .inp::placeholder { color: #8b8f9c; }
.forum[data-theme="light"] .btn:hover { border-color: var(--f-border-hover); background: var(--f-hover); }
.forum[data-theme="light"] .moon-phase-icon .moon-dark { fill: #ebe5d8; stroke: #b99550; }
.forum[data-theme="light"] .moon-phase-icon .moon-lit { fill: #d9b46a; }
/* --- frame --- */
.forum-inner { max-width: 1180px; margin: 0 auto; padding: 8px 16px 104px; }
.forum-main { display: flex; flex-direction: column; }
.forum h1, .forum h2 { font-family: var(--font-display); font-weight: 600; color: var(--ink); }
.forum-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 52px; margin-bottom: 8px; }
.forum-mark { font-family: var(--font-display); font-size: 26px; font-weight: 600; color: var(--ink); text-decoration: none; }
.forum-mark:hover { color: var(--gold); }
.forum-theme {
display: inline-flex; align-items: center; gap: 8px; min-width: 44px; min-height: 44px; padding: 0 10px; justify-content: center;
border: 1px solid var(--line-2); border-radius: 999px; background: var(--panel); color: var(--ink-2);
font: 500 14px var(--font-body); cursor: pointer;
}
.forum-theme:hover { color: var(--gold); border-color: var(--f-border-hover); }
.forum-theme svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.forum-theme-label { display: none; }
.forum-tools { display: flex; align-items: center; gap: 8px; }
.forum-search { padding: 0; width: 44px; }
/* The forum's menu: a bar at the bottom on phones, tabs in the forum bar on wider screens. */
.forum-nav {
position: fixed; left: 0; right: 0; bottom: 0; z-index: 25;
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr));
background: var(--f-nav-bg); border-top: 1px solid var(--line);
padding-bottom: env(safe-area-inset-bottom);
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
}
.fn-item {
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
min-height: 62px; color: var(--ink-2); text-decoration: none; font-size: 12px;
}
.fn-item[aria-current="page"] { color: var(--gold); font-weight: 600; }
.fn-item:hover { color: var(--gold); }
.fn-icon-wrap { position: relative; display: inline-flex; }
.fn-icon { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
.fn-badge {
position: absolute; top: -6px; right: -11px; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box;
border-radius: 999px; background: var(--gold); color: var(--gold-ink); font-size: 11px; font-weight: 600; line-height: 18px; text-align: center;
}
@media (min-width: 760px) {
.forum-inner { padding: 20px 24px 64px; }
.forum-bar {
gap: 16px; margin-bottom: 24px; padding: 6px 6px 6px 18px;
background: var(--panel); border: 1px solid var(--line); border-radius: 16px;
}
.forum-nav {
position: static; flex: 1; display: flex; gap: 4px; padding: 0;
background: none; border: 0; box-shadow: none;
}
.fn-item { flex-direction: row; gap: 8px; min-height: 44px; padding: 0 14px; border-radius: 10px; font-size: 15px; }
.fn-item[aria-current="page"] { background: var(--f-tint); }
.fn-icon { width: 20px; height: 20px; }
.forum-theme { padding: 0 14px; }
.forum-search { padding: 0; }
.forum-theme-label { display: inline; }
}
/* --- avatars and the author line --- */
.av { position: relative; display: inline-flex; flex: none; --av-bg: #1c2540; --av-ink: #d9b46a; }
.av svg { display: block; }
.av-lila { --av-bg: #2a2342; }
.av-tenger { --av-bg: #1d3038; }
.av-borostyan { --av-bg: #33291c; }
.av-rozsa { --av-bg: #3a2230; }
.av-erdo { --av-bg: #1f3326; }
/* Light theme: a pale tint and a darker glyph (a night circle read as a black blot). */
.forum[data-theme="light"] .av-ejkek { --av-bg: #e4e8f3; --av-ink: #2f3d6b; }
.forum[data-theme="light"] .av-lila { --av-bg: #ece6f5; --av-ink: #5b4691; }
.forum[data-theme="light"] .av-tenger { --av-bg: #e0eff0; --av-ink: #2a6670; }
.forum[data-theme="light"] .av-borostyan { --av-bg: #f5ead7; --av-ink: #8a6a24; }
.forum[data-theme="light"] .av-rozsa { --av-bg: #f6e3ea; --av-ink: #9b3f5f; }
.forum[data-theme="light"] .av-erdo { --av-bg: #e2efe4; --av-ink: #3d6b47; }
.av-bg { fill: var(--av-bg); }
.av-glyph { fill: none; stroke: var(--av-ink); stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }
.av-glyph .av-fill { fill: var(--av-ink); stroke: none; }
.av-online {
position: absolute; right: -1px; bottom: -1px; width: 28%; height: 28%; min-width: 9px; min-height: 9px;
border-radius: 50%; background: var(--f-online); border: 2px solid var(--panel); box-sizing: border-box;
}
.fa-line { display: flex; align-items: center; gap: 10px; min-width: 0; }
.fa-avatar { display: inline-flex; }
.fa-meta { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
.fa-names { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
.fa-name { font-size: 16px; font-weight: 600; color: var(--ink); text-decoration: none; }
.fa-name:hover { color: var(--gold); }
.fa-rank { font-size: 12px; color: var(--ink-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 0 6px; }
.fa-badge { font-size: 12px; border-radius: 6px; padding: 0 6px; }
.fa-rank, .fa-badge { display: inline-flex; align-items: center; gap: 3px; line-height: 18px; white-space: nowrap; }
.fa-icon {
width: 12px; height: 12px; flex: none; fill: none; stroke: currentColor; stroke-width: 2;
stroke-linecap: round; stroke-linejoin: round;
}
.fa-badge-new .fa-icon { display: none; }
/* The higher ranks: a golden icon. */
.fa-rank-fono .fa-icon, .fa-rank-csillagfono .fa-icon, .fa-rank-sorsfono .fa-icon { color: var(--gold); }
.fa-badge-mod { color: var(--ok); background: var(--f-green-tint); }
.fa-badge-starter { color: var(--gold); border: 1px solid var(--line-2); }
.fa-badge-new { color: var(--gold-ink); background: var(--gold); font-weight: 600; }
.fa-sub { font-size: 13px; color: var(--muted); }
/* --- cards, banners, sections --- */
.fh { display: flex; flex-direction: column; gap: 22px; }
.fh-card { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 18px; }
.forum[data-theme="light"] .fh-card { box-shadow: 0 1px 2px rgba(27, 34, 54, 0.04); }
.fh-flush { padding: 0; overflow: hidden; }
.fh-empty { color: var(--muted); }
.fh-card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; margin-bottom: 12px; }
.fh-intro { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
.fh-intro h1 { font-size: 36px; }
.fh-banner {
display: flex; align-items: center; gap: 12px; justify-content: space-between;
min-height: 52px; padding: 12px 14px; border-radius: 12px;
background: var(--f-tint); border: 1px solid var(--line-2); color: var(--ink); text-decoration: none;
}
.fh-banner strong { color: var(--gold); font-weight: 600; }
.fh-banner:hover { color: var(--ink); background: var(--f-tint-strong); }
.fh-banner-warn { background: var(--f-red-tint); border-color: var(--danger); }
.fh-section { display: flex; flex-direction: column; gap: 12px; }
.fh-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
.fh-section-head h2 { font-size: 24px; }
.fh-sky-body { display: flex; gap: 16px; align-items: flex-start; }
.fh-moon .moon-phase-icon { width: 56px; height: 56px; }
.fh-sky-text { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.fh-sky-text h2 { font-size: 24px; line-height: 1.15; }
.fh-sky-text p { color: var(--ink-2); font-size: 16px; }
.fh-waiting-grid { display: grid; gap: 12px; }
@media (min-width: 760px) { .fh-waiting-grid { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } }
.fh-me { display: flex; flex-direction: column; gap: 14px; }
.fh-me-head { display: flex; align-items: center; gap: 12px; }
.fh-me-names { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; }
.fh-me-actions { display: flex; gap: 8px; flex-wrap: wrap; }
/* Front page: one column on phones in reading order (the two columns'
blocks interleave), main column and sidebar from 1024 px. */
.fh-home .fh-col { display: contents; }
.o-1 { order: 1; } .o-2 { order: 2; } .o-3 { order: 3; } .o-4 { order: 4; }
.o-5 { order: 5; } .o-6 { order: 6; } .o-7 { order: 7; } .o-8 { order: 8; }
@media (min-width: 1024px) {
.fh-home { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 28px; align-items: start; }
.fh-home .fh-col { display: flex; flex-direction: column; gap: 22px; }
.fh-home .fh-col-side { position: sticky; top: 88px; }
}
/* --- topics --- */
.fh-topics { list-style: none; margin: 0; }
.fh-topics li + li { border-top: 1px solid var(--line); }
.fh-topic { display: flex; align-items: center; gap: 14px; padding: 14px 16px; min-height: 76px; color: var(--ink); text-decoration: none; }
.fh-topic:hover { color: var(--ink); background: var(--f-hover); }
.fh-topic-icon {
flex: none; width: 44px; height: 44px; border-radius: 12px; background: var(--f-tint);
display: inline-flex; align-items: center; justify-content: center;
}
.topic-icon { width: 24px; height: 24px; fill: none; stroke: var(--gold); stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
.fh-topic-text { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }
.fh-topic-name { display: flex; align-items: center; gap: 8px; font-size: 17px; font-weight: 600; }
.fh-lock { width: 14px; height: 14px; fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; }
.fh-topic-desc { font-size: 14px; color: var(--muted); }
.fh-topic-last { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--muted); }
.fh-topic-count { display: none; flex: none; font-size: 14px; color: var(--muted); text-align: right; min-width: 64px; }
.fh-topic-count strong { color: var(--ink); font-weight: 600; }
@media (min-width: 640px) { .fh-topic-count { display: block; } }
/* --- thread lists: a meta line on phones, columns on wider screens --- */
.ft-list { list-style: none; margin: 0; padding: 0; }
.ft-list li + li { border-top: 1px solid var(--line); }
.ft-row { display: flex; align-items: center; gap: 12px; padding: 14px 16px; min-height: 64px; color: var(--ink); text-decoration: none; }
.ft-row:hover { color: var(--ink); background: var(--f-hover); }
.ft-main { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
.ft-title { font-size: 17px; font-weight: 600; line-height: 1.35; }
.ft-row:hover .ft-title { color: var(--gold); }
.ft-excerpt { font-size: 14px; color: var(--ink-2); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.ft-meta { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--muted); }
.ft-col { display: none; }
.ft-new {
flex: none; font-size: 13px; font-weight: 600; color: var(--gold-ink); background: var(--gold);
border-radius: 999px; padding: 2px 9px; white-space: nowrap;
}
.ft-read { flex: none; font-size: 13px; color: var(--muted); }
@media (min-width: 760px) {
.ft-row { display: grid; grid-template-columns: minmax(0, 1fr) 110px 100px 72px; gap: 16px; padding: 14px 20px; }
.ft-m-narrow { display: none; }
.ft-col { display: flex; flex-direction: column; align-items: flex-end; font-size: 14px; color: var(--muted); }
.ft-col strong { color: var(--ink); font-weight: 600; font-size: 16px; }
.ft-col-replies { flex-direction: row; gap: 4px; align-items: baseline; justify-content: flex-end; flex-wrap: wrap; }
.ft-col-replies .hint { flex-basis: 100%; text-align: right; }
.ft-new, .ft-read { justify-self: end; }
}
.ft-pin {
display: inline-block; margin-right: 8px; vertical-align: 2px; font-size: 12px; font-weight: 500;
color: var(--ink-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 0 6px;
}
.ft-intent { align-self: flex-start; font-size: 13px; font-weight: 500; border-radius: 999px; padding: 3px 10px; }
.ft-intent-listen { color: var(--harmonic); background: var(--f-blue-tint); }
.ft-intent-advice { color: var(--square); background: var(--f-orange-tint); }
.ft-waiting {
display: flex; flex-direction: column; gap: 10px; padding: 16px; border-radius: 14px;
background: var(--panel); border: 1px solid var(--line);
}
.ft-waiting-title { font-size: 18px; font-weight: 600; line-height: 1.35; color: var(--ink); text-decoration: none; }
.ft-waiting-title:hover { color: var(--gold); }
.ft-answer { align-self: flex-start; min-height: 44px; border-color: var(--gold); color: var(--gold); margin-top: auto; }
/* --- topic page and the other headings --- */
.forum-crumbs { display: flex; gap: 8px; align-items: center; font-size: 14px; color: var(--muted); }
.forum-crumbs a { color: var(--ink-2); text-decoration: none; min-height: 32px; display: inline-flex; align-items: center; }
.forum-crumbs a:hover { color: var(--gold); }
.ftopic-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 16px; }
.ftopic-head h1, .fpage-title { font-size: 34px; line-height: 1.1; }
.ftopic-head > div { display: flex; flex-direction: column; gap: 6px; max-width: 620px; }
.forum-pager { display: flex; justify-content: space-between; align-items: center; min-height: 44px; }
/* --- thread view --- */
.ftv { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 980px; margin: 0 auto; }
.ftv-toolbar { display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
.ftv-toolbar:empty { display: none; }
.ftv-mod { position: relative; }
.ftv-mod summary { list-style: none; cursor: pointer; }
.ftv-mod summary::-webkit-details-marker { display: none; }
.ftv-mod-menu {
position: absolute; right: 0; top: calc(100% + 6px); z-index: 10; min-width: 200px; padding: 6px;
display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px;
box-shadow: var(--f-shadow);
}
.ftv-mod-menu button {
min-height: 44px; padding: 0 12px; border: 0; border-radius: 8px; background: none; color: var(--ink);
font: inherit; font-size: 15px; text-align: left; cursor: pointer;
}
.ftv-mod-menu button:hover { background: var(--f-hover); color: var(--gold); }
.ftv-mod-menu button.danger { color: var(--danger); }
.ftv-intent {
display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border-radius: 12px;
background: var(--f-blue-tint); font-size: 14px; line-height: 1.45; color: var(--ink-2);
}
.ftv-intent strong { color: var(--harmonic); font-weight: 600; }
.ftv-intent-advice { background: var(--f-orange-tint); }
.ftv-intent-advice strong { color: var(--square); }
.ftv-title { font-size: 30px; line-height: 1.12; }
.ftv-intent-line { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; margin-top: -4px; font-size: 14px; color: var(--muted); }
.ftv-intent-line .ft-intent { align-self: center; padding: 1px 10px; font-weight: 600; }
.ftv-count { display: flex; justify-content: space-between; align-items: baseline; padding-top: 6px; }
.ftv .ftv-count h2 { font-family: var(--font-body); font-size: 15px; color: var(--ink-2); }
.ftv-branch { display: flex; flex-direction: column; }
.ftv-children { margin-left: 17px; padding-left: 14px; border-left: 2px solid var(--line); display: flex; flex-direction: column; }
.ftv-marker { display: flex; align-items: center; gap: 10px; margin: 8px 0 0; color: var(--gold); font-size: 13px; font-weight: 600; }
.ftv-marker::before, .ftv-marker::after { content: ""; flex: 1; height: 1px; background: var(--gold); opacity: 0.5; }
.ftv-incoming {
position: sticky; bottom: 84px; align-self: center; z-index: 5;
display: inline-flex; align-items: center; min-height: 44px; padding: 0 18px; border: 0; border-radius: 999px;
background: var(--gold); color: var(--gold-ink); font: 600 15px var(--font-body); cursor: pointer;
box-shadow: var(--f-shadow);
}
.ftv-compose { display: flex; flex-direction: column; gap: 8px; padding-top: 14px; border-top: 1px solid var(--line); scroll-margin-top: 90px; }
.ftv-hint { font-size: 14px; color: var(--harmonic); }
.ftv-replyto { display: flex; align-items: center; gap: 6px; font-size: 14px; color: var(--ink-2); }
.ftv-gate { padding: 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); }
/* --- posts: a one-line head (avatar, name, rank, signs, time), the text, a
small action row; on wide screens the text lines up under the name --- */
.fp {
display: grid; grid-template-columns: auto minmax(0, 1fr);
grid-template-areas: "av head" "body body" "actions actions" "report report";
column-gap: 10px; row-gap: 6px; padding: 12px 0; border-bottom: 1px solid var(--line); scroll-margin-top: 90px;
}
.fp-av { grid-area: av; display: inline-flex; align-self: center; }
.fp-av a { display: inline-flex; }
.fp-head { grid-area: head; display: flex; align-items: center; gap: 8px; min-width: 0; }
.fp-names { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 6px; flex: 1; min-width: 0; }
.fp-names .fa-name { font-size: 15px; }
.fp-signs { font-size: 13px; color: var(--muted); letter-spacing: 0.5px; }
.fp-time { flex: none; font-size: 13px; color: var(--muted); }
.fp-content { grid-area: body; min-width: 0; display: flex; flex-direction: column; gap: 8px; }
.fp-actions { grid-area: actions; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.fp-report { grid-area: report; }
/* The question (the opening post) stands apart: a card; the replies sit on the page. */
.fp.fp-opening {
margin: 6px 0 10px; padding: 16px 18px 14px; border: 1px solid var(--line); border-radius: 16px;
background: var(--panel);
}
.forum[data-theme="light"] .fp.fp-opening { box-shadow: 0 1px 3px rgba(27, 34, 54, 0.06); }
.fp-opening .fp-body { font-size: 17px; }
.fp-opening .fp-names .fa-name { font-size: 16px; }
.ftv-children .fp:last-child { border-bottom: 0; }
.fp-nested { padding: 8px 0; row-gap: 4px; }
.fp-nested .fp-body { font-size: 15px; }
.fp-body { font-size: 16px; line-height: 1.55; overflow-wrap: anywhere; color: var(--ink); }
.fp-body p + p { margin-top: 8px; }
.fp.fp-removed { display: flex; flex-direction: column; }
.fp-removed {
gap: 4px; margin: 10px 0; padding: 12px 14px; border: 1px dashed var(--line-2);
border-radius: 12px; color: var(--ink-2); font-size: 15px;
}
.fp-mod-note { font-size: 13px; color: var(--danger); }
.fp-collapsed {
align-self: flex-start; min-height: 40px; padding: 0; border: 0; background: none; color: var(--muted);
font: inherit; font-size: 15px; text-decoration: underline; cursor: pointer;
}
.fp-helped { display: inline-flex; align-items: center; gap: 4px; margin-right: 2px; font-size: 12px; font-weight: 500; color: var(--ok); }
.fp-helped svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }
.fp-spacer { flex: 1; }
.fp-reply {
display: inline-flex; align-items: center; gap: 5px; min-height: 32px; padding: 0 8px; border: 0; border-radius: 8px;
background: none; color: var(--ink-2); font: 500 13px var(--font-body); cursor: pointer;
}
.fp-reply:hover { color: var(--gold); background: var(--f-hover); }
.fp-reply svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; }
.fp-more {
display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border: 0; border-radius: 8px;
background: none; color: var(--muted); cursor: pointer;
}
.fp-more:hover, .fp-more[aria-expanded="true"] { color: var(--ink); background: var(--f-hover); }
.fp-more svg { width: 18px; height: 18px; fill: currentColor; }
@media (min-width: 760px) {
.fp { grid-template-columns: 44px minmax(0, 1fr); grid-template-areas: "av head" ". body" ". actions" ". report"; column-gap: 14px; }
.fp-av { justify-content: center; }
.fp-nested { grid-template-columns: 30px minmax(0, 1fr); column-gap: 10px; }
.ftv-incoming { bottom: 20px; }
}
/* --- reactions: the forum's own marks, an icon and a count --- */
.ri { fill: none; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; flex: none; }
.ri-with_you { stroke: var(--r-with_you); }
.ri-thanks { stroke: var(--r-thanks); }
.ri-me_too { stroke: var(--r-me_too); }
.ri-insight { stroke: var(--r-insight); }
.ri-filled.ri-with_you { fill: color-mix(in srgb, var(--r-with_you) 28%, transparent); }
.ri-filled.ri-thanks { fill: color-mix(in srgb, var(--r-thanks) 28%, transparent); }
.ri-filled.ri-me_too { fill: color-mix(in srgb, var(--r-me_too) 24%, transparent); }
.ri-filled.ri-insight { fill: color-mix(in srgb, var(--r-insight) 28%, transparent); }
.ri-filled .ri-line { fill: none; }
.fr-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.fr-chip {
display: inline-flex; align-items: center; gap: 5px; min-height: 32px; min-width: 32px; padding: 0 10px; box-sizing: border-box;
border-radius: 999px; border: 1px solid var(--line); background: var(--panel); color: var(--ink);
font: 500 13px var(--font-body); cursor: pointer; justify-content: center;
}
.fp-nested .fr-chip { min-height: 30px; }
.fr-chip:disabled { cursor: default; }
.fr-chip:hover:not(:disabled) { border-color: var(--line-2); }
.fr-chip[aria-pressed="true"]:has(.ri-with_you) { border-color: var(--r-with_you); background: color-mix(in srgb, var(--r-with_you) 9%, var(--panel)); }
.fr-chip[aria-pressed="true"]:has(.ri-thanks) { border-color: var(--r-thanks); background: color-mix(in srgb, var(--r-thanks) 9%, var(--panel)); }
.fr-chip[aria-pressed="true"]:has(.ri-me_too) { border-color: var(--r-me_too); background: color-mix(in srgb, var(--r-me_too) 9%, var(--panel)); }
.fr-chip[aria-pressed="true"]:has(.ri-insight) { border-color: var(--r-insight); background: color-mix(in srgb, var(--r-insight) 9%, var(--panel)); }
.fr-add { padding: 0; border-style: dashed; border-color: var(--line-2); background: none; color: var(--muted); }
.fr-add svg, .fr-down svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.fr-down { padding: 0; border-color: transparent; background: none; color: var(--muted); }
.fr-down svg { width: 18px; height: 18px; }
.fr-down[aria-pressed="true"] { background: var(--f-hover); color: var(--ink); }
/* --- small menus (the + of reactions, the ⋯ of a post) --- */
.fpop-wrap { position: relative; display: inline-flex; }
.fpop {
position: absolute; left: 0; top: calc(100% + 6px); z-index: 20; min-width: 210px; padding: 6px;
display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px;
box-shadow: var(--f-shadow);
}
.fpop-right { left: auto; right: 0; }
.fpop-item {
display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 12px; border: 0; border-radius: 8px;
background: none; color: var(--ink); font: 400 15px var(--font-body); text-align: left; cursor: pointer; white-space: nowrap;
}
.fpop-item:hover, .fpop-item[aria-pressed="true"] { background: var(--f-hover); }
.fpop-danger { color: var(--danger); }
/* --- composer --- */
.fc { display: flex; flex-direction: column; gap: 8px; }
.fc-text {
width: 100%; min-height: 96px; box-sizing: border-box; padding: 12px 14px; border-radius: 12px;
border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink); font: 400 16px/1.45 var(--font-body);
resize: vertical; caret-color: var(--gold);
}
.fc-text::placeholder { color: var(--muted); }
.fc-text:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px var(--f-tint-strong); background: var(--panel); }
.fc-actions { display: flex; align-items: center; gap: 8px; }
.fc-spacer { flex: 1; }
.fc-icon-btn {
width: 44px; height: 44px; flex: none; display: inline-flex; align-items: center; justify-content: center;
border: 0; border-radius: 10px; background: none; color: var(--ink-2); cursor: pointer;
}
.fc-icon-btn:hover, .fc-icon-btn[aria-expanded="true"] { color: var(--gold); background: var(--f-tint); }
.fc-icon-btn svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; }
/* --- new thread and profile forms --- */
.fnew, .fprof { display: flex; flex-direction: column; gap: 22px; width: 100%; max-width: 760px; }
.fnew-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
.fnew-set legend { font-size: 14px; font-weight: 500; margin-bottom: 8px; padding: 0; }
.fnew-topics, .fnew-intents { display: grid; gap: 8px; }
@media (min-width: 640px) { .fnew-topics { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.fnew-topic, .fnew-intent, .fprof-check {
display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid var(--line-2);
border-radius: 12px; cursor: pointer; background: var(--panel);
}
.fnew-topic:has(input:checked), .fnew-intent:has(input:checked) { border-color: var(--gold); background: var(--f-tint); }
.fnew-topic > span, .fnew-intent > span, .fprof-check > span { display: flex; flex-direction: column; gap: 2px; }
.fnew-topic input, .fnew-intent input, .fprof-check input { margin-top: 4px; accent-color: var(--gold); width: 18px; height: 18px; flex: none; }
.fprof-avatars { display: grid; grid-template-columns: repeat(auto-fill, minmax(54px, 1fr)); gap: 6px; }
.fprof-avatar {
display: inline-flex; align-items: center; justify-content: center; padding: 3px; border-radius: 50%;
border: 2px solid transparent; cursor: pointer; justify-self: center;
}
.fprof-avatar:has(input:checked) { border-color: var(--gold); }
.fprof-avatar:has(input:focus-visible) { outline: 2px solid var(--gold); outline-offset: 2px; }
.fprof-rank { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); }
/* --- member page (two columns on wide screens) and moderation --- */
.fmember { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
.fmember-head { display: flex; align-items: center; gap: 16px; }
.fmember-names { display: flex; flex-direction: column; gap: 4px; }
.fmember-names h1 { font-size: 30px; line-height: 1.1; }
.fmember-badges { display: flex; gap: 6px; flex-wrap: wrap; }
.fmember-signs { color: var(--ink-2); }
@media (min-width: 900px) {
.fh-member { display: grid; grid-template-columns: 340px minmax(0, 1fr); gap: 28px; align-items: start; }
.fh-member .fmember { position: sticky; top: 88px; }
}
.fban { align-self: stretch; }
.fban summary { list-style: none; cursor: pointer; display: inline-flex; }
.fban summary::-webkit-details-marker { display: none; }
.fban-body { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; padding: 14px; border: 1px solid var(--line-2); border-radius: 12px; }
.fmodlog { list-style: none; margin: 0; }
.fmodlog li { display: flex; flex-direction: column; gap: 2px; padding: 12px 16px; }
.fmodlog li + li { border-top: 1px solid var(--line); }
/* --- reports --- */
.frep { flex-basis: 100%; display: flex; flex-direction: column; gap: 10px; margin-top: 6px; padding: 14px; border: 1px solid var(--line-2); border-radius: 12px; background: var(--panel); }
.frep-kind { display: flex; align-items: center; gap: 10px; min-height: 40px; font-size: 15px; cursor: pointer; }
.frep-kind input { accent-color: var(--gold); width: 18px; height: 18px; flex: none; }
.frep-crisis { padding: 10px 12px; border-radius: 10px; background: var(--f-blue-tint); color: var(--ink); font-size: 15px; line-height: 1.45; }
.frep-crisis strong { color: var(--harmonic); }
.forum-modchip {
display: inline-flex; align-items: center; min-height: 36px; padding: 0 12px; border-radius: 999px;
background: var(--f-red-tint); border: 1px solid var(--danger); color: var(--danger); font-size: 14px; font-weight: 600;
text-decoration: none; white-space: nowrap;
}
.forum-modchip:hover { color: var(--danger); background: var(--f-tint); }
@media (max-width: 759px) { .forum-bar { flex-wrap: wrap; } .forum-modchip { order: 3; } }
/* --- moderation page --- */
.fmod-tabs { display: flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); align-self: flex-start; }
.fmod-tabs a { min-height: 40px; display: inline-flex; align-items: center; padding: 0 16px; border-radius: 9px; color: var(--ink-2); text-decoration: none; font-weight: 500; }
.fmod-tabs a[aria-current="page"] { background: var(--f-tint-strong); color: var(--gold); }
.fmod-report { display: flex; flex-direction: column; gap: 10px; }
.fmod-crisis { border-color: var(--harmonic); box-shadow: 0 0 0 1px var(--harmonic); }
.fmod-report-head { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; flex-wrap: wrap; }
.fmod-note { color: var(--ink-2); font-style: italic; }
.fmod-target { display: flex; flex-direction: column; gap: 6px; padding: 12px 14px; border-radius: 10px; background: var(--panel-2); border: 1px solid var(--line); }
.fmod-target .fp-body { font-size: 15px; }
.fmod-chat { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 15px; }
.fmod-chat-reported { padding: 4px 8px; border-radius: 6px; background: var(--f-red-tint); }
/* --- private messages --- */
.fmsg-h { font-family: var(--font-body) !important; font-size: 16px; font-weight: 600; color: var(--ink-2); }
.fmsg-request { display: flex; flex-direction: column; gap: 12px; }
.fmsg-intro { font-style: italic; color: var(--ink-2); }
.fmsg-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.ft-row.fmsg-row { display: flex; }
.fmsg-when { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; font-size: 13px; color: var(--muted); flex: none; }
.freq { display: flex; flex-direction: column; gap: 8px; align-self: stretch; }
.freq label { font-size: 14px; font-weight: 500; }
.fchat { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 820px; margin: 0 auto; }
.fchat-head { display: flex; align-items: center; gap: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--line); }
.fchat-who { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; flex: 1; min-width: 0; }
.fchat-intro { font-size: 15px; color: var(--ink-2); font-style: italic; }
.fchat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.fchat-msg { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; max-width: 86%; }
.fchat-mine { align-self: flex-end; align-items: flex-end; }
.fchat-bubble { padding: 10px 14px; border-radius: 16px 16px 16px 4px; background: var(--panel); border: 1px solid var(--line); }
.fchat-mine .fchat-bubble { border-radius: 16px 16px 4px 16px; background: var(--f-tint-strong); border-color: transparent; }
.fchat-bubble .fp-body { font-size: 16px; line-height: 1.5; }
.fchat-meta { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); }
.fchat-report { min-height: 32px; padding: 0 6px; border: 0; background: none; color: var(--muted); font: 400 12px var(--font-body); cursor: pointer; }
.fchat-report:hover { color: var(--danger); }
.fchat-msg .frep { width: min(420px, 86vw); }
.fchat-compose { display: flex; flex-direction: column; gap: 6px; padding-top: 12px; border-top: 1px solid var(--line); }
@media (min-width: 760px) { .forum-nav .fn-item { padding: 0 12px; } }
/* --- e-mail settings --- */
.fprof-mail { display: grid; gap: 6px; }
.fprof-mail label { font-size: 14px; font-weight: 500; margin-top: 8px; }
.fprof-mail label:first-child { margin-top: 0; }
/* --- "… gépel" --- */
.ftyping { min-height: 22px; display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--muted); margin: 0; }
.ftyping-dots { display: inline-flex; gap: 3px; }
.ftyping-dots span { width: 5px; height: 5px; border-radius: 50%; background: var(--muted); animation: ftyping 1.2s infinite ease-in-out; }
.ftyping-dots span:nth-child(2) { animation-delay: 0.15s; }
.ftyping-dots span:nth-child(3) { animation-delay: 0.3s; }
@keyframes ftyping { 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }
@media (prefers-reduced-motion: reduce) { .ftyping-dots span { animation: none; opacity: 0.6; } }
.fp-link { min-height: 32px; padding: 0 8px; border: 0; background: none; color: var(--gold); font: 500 15px var(--font-body); cursor: pointer; }
.fp-link:hover { color: var(--gold-hover); }
/* --- whom a reply answers, mentions, badges --- */
.fp-replyto { display: inline-flex; align-items: center; gap: 3px; font-size: 13px; color: var(--muted); }
.fp-replyto svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.fp-mention { color: var(--gold); font-weight: 500; text-decoration: none; background: var(--f-tint); border-radius: 4px; padding: 0 2px; }
.fp-mention:hover { color: var(--gold-hover); }
.fa-badge-listener { color: var(--harmonic); background: var(--f-blue-tint); }
.fa-badge-supporter { color: var(--gold); background: var(--f-tint); }
.fa-badge-founder { color: var(--ok); border: 1px solid var(--line-2); }
/* --- own pictures and the site's mark --- */
.av-picture img { display: block; width: 100%; height: 100%; border-radius: 50%; object-fit: cover; }
.av-site { --av-bg: #1c2540; }
.av-site-mark { stroke: #d9b46a; }
.forum[data-theme="light"] .av-site { --av-bg: #f5ead7; }
.forum[data-theme="light"] .av-site-mark { stroke: #8a6a24; }
/* --- "@" suggestions while typing --- */
.fc-suggest {
display: flex; flex-direction: column; align-self: flex-start; min-width: 220px; max-width: 320px; padding: 4px;
background: var(--panel); border: 1px solid var(--line-2); border-radius: 12px; box-shadow: var(--f-shadow);
}
.fc-suggest-item {
display: flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 10px; border: 0; border-radius: 8px;
background: none; color: var(--ink); font: 400 15px var(--font-body); text-align: left; cursor: pointer;
}
.fc-suggest-item:hover, .fc-suggest-item:focus-visible { background: var(--f-hover); }
/* --- who is here, restricted topics --- */
.fh-online { display: flex; flex-direction: column; gap: 10px; }
.forum .fh-online-title { font-family: var(--font-body); font-size: 15px; font-weight: 600; color: var(--ink-2); }
.fh-online-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 12px; }
.fh-online-item { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; color: var(--ink); text-decoration: none; }
a.fh-online-item:hover { color: var(--gold); }
.fh-topic-closed { flex-wrap: wrap; }
.fjoin { flex-basis: 100%; display: flex; flex-direction: column; gap: 8px; }
/* --- profile form extras, the topics tab --- */
.fprof-upload { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 6px; }
.fprof-upload-btn { cursor: pointer; }
.fprof-check-plain { border: 0; padding: 6px 0 0; background: none; }
.fmodlog li.ftop-member { flex-direction: row; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.ftop-vis { width: auto; min-height: 36px; }
/* --- members-only and restricted topics: said plainly, also to members --- */
.ftopic-private { display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: var(--ink-2); }
.ftopic-private svg, .ftv-private svg { width: 15px; height: 15px; flex: none; margin-top: 2px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
.ftv-private { display: inline-flex; align-items: center; gap: 4px; margin-left: 4px; font-size: 13px; color: var(--muted); }
.ftv-private svg { margin-top: 0; width: 13px; height: 13px; }
/* --- "Válaszok": answers to the member --- */
.frep-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.fanswers { list-style: none; margin: 0; padding: 0; }
.fanswers li + li { border-top: 1px solid var(--line); }
.fanswer {
display: grid; grid-template-columns: 36px minmax(0, 1fr) auto; gap: 12px; align-items: start;
padding: 14px 16px; color: var(--ink); text-decoration: none;
}
.fanswer:hover { background: var(--f-hover); }
.fanswer-new { background: var(--f-tint); }
.fanswer-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.fanswer-who { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: 15px; }
.fanswer-thread { font-size: 14px; color: var(--ink-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fanswer-excerpt {
font-size: 14px; color: var(--muted); overflow: hidden;
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
}
.fanswer-time { font-size: 12px; color: var(--muted); white-space: nowrap; }
/* The reply box at the bottom of a branch, where the answers to that post go. */
.ftv-inline {
display: flex; flex-direction: column; gap: 6px; margin: 4px 0 8px 17px; padding: 8px 0 4px 14px;
border-left: 2px solid var(--gold); scroll-margin: 96px 0 120px;
}
.ftv-inline .ftv-replyto { display: flex; align-items: center; gap: 5px; margin: 0; }
.ftv-inline .ftv-replyto svg {
width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
}
/* Phones, while typing: the bottom menu and the floating button step aside
for the keyboard (KeyboardSafe sets kb-open), and a focused box keeps room
around it for its send button. */
@media (max-width: 759px) {
.kb-open .forum-nav, .kb-open .ftv-incoming { display: none; }
}
.forum textarea, .forum input { scroll-margin: 88px 0 96px; }
/* The small links at the bottom of the side column: rows in one card. */
.fh-links { display: flex; flex-direction: column; }
.fh-link {
display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 10px 16px;
color: var(--ink); text-decoration: none;
}
.fh-link + .fh-link { border-top: 1px solid var(--line); }
.fh-link:hover { background: var(--f-hover); }
.fh-link svg {
width: 20px; height: 20px; flex: none; fill: none; stroke: var(--gold); stroke-width: 1.8;
stroke-linecap: round; stroke-linejoin: round;
}
.fh-link-text { display: flex; flex-direction: column; flex: 1; min-width: 0; font-size: 15px; font-weight: 500; }
.fh-link-text .hint { font-size: 13px; font-weight: 400; }
.fh-link-arrow { color: var(--muted); font-size: 20px; line-height: 1; }
/* The same row at the foot of a card, or framed inside one. */
.fh-link-foot { margin: 14px -18px -18px; border-top: 1px solid var(--line); border-radius: 0 0 16px 16px; }
.fh-link-boxed { min-height: 52px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 12px; }
/* --- search --- */
.fsearch-form { display: flex; gap: 8px; }
.fsearch-form .inp { flex: 1; min-width: 0; }
.fsearch-results { list-style: none; margin: 0; padding: 0; }
.fsearch-results li + li { border-top: 1px solid var(--line); }
.fsearch-hit { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; color: var(--ink); text-decoration: none; }
.fsearch-hit:hover { background: var(--f-hover); }
.fsearch-title { font-size: 17px; font-weight: 600; }
.fsearch-meta { font-size: 13px; color: var(--muted); }
.fsearch-snippet { font-size: 15px; color: var(--ink-2); }
.fsearch-snippet mark { background: var(--f-tint-strong); color: var(--ink); border-radius: 3px; padding: 0 2px; }
/* --- muted members --- */
.fp-muted { padding: 4px 0; }
.fmute { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.fmuted { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.fmuted li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
/* --- archived topics --- */
.fh-archived { margin-top: 10px; }
.fh-archived summary { min-height: 44px; display: flex; align-items: center; color: var(--ink-2); font-size: 15px; cursor: pointer; }
.fh-archived .fh-links { list-style: none; margin: 0; padding: 0; }
.fh-archived li + li .fh-link { border-top: 1px solid var(--line); }
/* --- a chart shared with a question --- */
.fshare {
display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin-top: 12px; padding: 14px 16px;
border: 1px solid var(--line-2); border-radius: 14px; background: var(--f-tint);
}
.fshare-quiet { background: none; border-style: dashed; }
.fshare-head { display: flex; align-items: center; justify-content: space-between; width: 100%; }
.fshare-title { font-size: 16px; }
.fshare-summary { font-family: var(--font-display); font-size: 19px; color: var(--ink-2); }
.fshare-points { list-style: none; margin: 2px 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 16px; font-size: 15px; }
.fshare-open { margin-top: 4px; }
.fnew-share { display: flex; flex-direction: column; gap: 8px; }
.fnew-share .fshare { margin-top: 0; }
/* --- link previews (YouTube) --- */
.flinks { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }
.flink {
display: flex; flex-direction: column; max-width: 480px; overflow: hidden;
border: 1px solid var(--line-2); border-radius: 14px; background: var(--panel);
}
.flink-thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: #0e1424; }
.flink-thumb img { display: block; width: 100%; height: 100%; object-fit: cover; }
.flink-noimg { display: block; width: 100%; height: 100%; }
.flink-play {
position: absolute; left: 50%; top: 50%; width: 56px; height: 40px; transform: translate(-50%, -50%);
display: grid; place-items: center; border-radius: 12px; background: rgba(15, 15, 15, 0.78);
transition: background 0.15s;
}
.flink-play svg { width: 22px; height: 22px; fill: #fff; }
.flink-thumb:hover .flink-play, .flink-thumb:focus-visible .flink-play { background: #d32020; }
.flink-meta { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px 12px; }
.flink-title { font-weight: 600; font-size: 15px; line-height: 1.35; }
.flink-here { align-self: flex-start; margin-top: 4px; }
.flink-frame { position: relative; aspect-ratio: 16 / 9; background: #000; }
.flink-frame iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
.flink .fp-link { display: inline-flex; align-items: center; padding: 0; text-decoration: none; }
/* The attached chart's wheel: a fixed size, beside the details (above them on phones). */
.fshare-info { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; min-width: 0; }
.fshare-drawn { flex-direction: column; align-items: center; }
.fshare-wheel { flex: none; width: 240px; height: 240px; }
.fshare-wheel svg { display: block; width: 100%; height: 100%; }
@media (min-width: 640px) {
.fshare-drawn { flex-direction: row; align-items: center; gap: 18px; }
}
/* --- new thread: topic labels, a wish switch, one writing surface --- */
.fnew .fnew-set legend { font-size: 15px; font-weight: 600; color: var(--ink); margin-bottom: 10px; }
.fnew-chips { display: flex; flex-wrap: wrap; gap: 8px; }
.fnew-chip {
display: inline-flex; align-items: center; gap: 8px; min-height: 42px; padding: 0 14px 0 12px;
border: 1px solid var(--line-2); border-radius: 999px; background: var(--panel); color: var(--ink-2);
font-size: 15px; cursor: pointer; transition: border-color 0.15s, background 0.15s, color 0.15s;
}
.fnew-chip:hover { border-color: var(--f-border-hover); color: var(--ink); }
.fnew-chip .topic-icon {
width: 18px; height: 18px; flex: none; fill: none; stroke: var(--gold); stroke-width: 1.8;
stroke-linecap: round; stroke-linejoin: round;
}
.fnew-chip:has(input:checked) { border-color: var(--gold); background: var(--f-tint-strong); color: var(--ink); font-weight: 600; }
.fnew-chip:has(input:focus-visible), .fnew-switch-opt:has(input:focus-visible) { outline: 2px solid var(--gold); outline-offset: 2px; }
.fnew-note { margin: 8px 2px 0; font-size: 14px; color: var(--muted); display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
.fnew-audience { display: inline-flex; align-items: center; gap: 4px; color: var(--ink-2); }
.fnew-audience svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
.fnew-switch { display: grid; gap: 4px; padding: 4px; border-radius: 14px; background: var(--f-tint); border: 1px solid var(--line); }
.fnew-switch-opt {
display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 44px; padding: 0 8px;
border-radius: 10px; color: var(--ink-2); font-size: 15px; text-align: center; cursor: pointer;
transition: background 0.15s, color 0.15s, box-shadow 0.15s;
}
.fnew-switch-opt svg { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.fnew-switch-opt:hover { color: var(--ink); }
.fnew-switch-opt:has(input:checked) { background: var(--panel); color: var(--ink); font-weight: 600; box-shadow: 0 1px 3px rgba(27, 34, 54, 0.1); }
.fnew-switch-opt:has(input:checked) svg { color: var(--gold); }
@media (max-width: 479px) {
.fnew-switch-opt { flex-direction: column; gap: 3px; min-height: 58px; font-size: 13px; }
}
.fnew-paper {
display: flex; flex-direction: column; border: 1px solid var(--line-2); border-radius: 16px; background: var(--panel);
overflow: hidden; transition: border-color 0.15s, box-shadow 0.15s;
}
.fnew-paper:focus-within { border-color: var(--gold); box-shadow: 0 0 0 3px var(--f-tint-strong); }
.fnew-title {
border: 0; border-bottom: 1px solid var(--line); background: none; padding: 16px 18px 12px; color: var(--ink);
font: 600 21px/1.3 var(--font-display); outline: none;
}
.fnew-body {
border: 0; background: none; padding: 14px 18px; min-height: 200px; resize: vertical; color: var(--ink);
font: 400 16px/1.6 var(--font-body); outline: none;
}
.fnew-title::placeholder, .fnew-body::placeholder { color: var(--muted); }
.fnew-foot {
display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
padding: 10px 12px 10px 18px; border-top: 1px solid var(--line); background: var(--f-tint);
}
@@ -0,0 +1,104 @@
import type { Metadata } from "next";
import Link from "next/link";
import { ago, threadHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
export const metadata: Metadata = { title: "Keresés a fórumban", robots: { index: false, follow: true } };
interface SearchResult {
thread: { id: number; title: string; slug: string };
topic: { slug: string; name: string };
author: { nickname: string } | null;
last_post_at: string;
reply_count: number;
post_id: number | null;
/** The matching words between ⟦ and ⟧. */
snippet: string | null;
}
/** The words the search found, marked. */
function Marked({ text }: { text: string }) {
return (
<>
{text
.split(/(⟦[^⟧]*⟧)/)
.map((part, i) =>
part.startsWith("⟦") ? <mark key={i}>{part.slice(1, -1)}</mark> : <span key={i}>{part}</span>,
)}
</>
);
}
/** Search in the threads and posts the visitor may read. */
export default async function SearchPage({ searchParams }: { searchParams: Promise<{ q?: string; oldal?: string }> }) {
const params = await searchParams;
const q = (params.q ?? "").trim();
const page = Math.max(1, Number(params.oldal) || 1);
const res =
q.length >= 2
? await forumGet<{ results: SearchResult[]; more: boolean }>(
`/v1/forum/search?q=${encodeURIComponent(q)}&page=${page}`,
)
: null;
const results = res?.ok ? res.data.results : [];
const more = res?.ok ? res.data.more : false;
const link = (p: number) => `/forum/kereses?q=${encodeURIComponent(q)}&oldal=${p}`;
return (
<div className="fh">
<h1 className="fpage-title">Keresés</h1>
<form className="fsearch-form" action="/forum/kereses" role="search">
<label htmlFor="fsearch-q" className="sr-only">
Mit keresel?
</label>
<input
id="fsearch-q"
name="q"
type="search"
autoComplete="off"
className="inp"
defaultValue={q}
placeholder="Mit keresel? Például: alvás, telihold, gyász"
minLength={2}
maxLength={100}
autoFocus={!q}
/>
<button type="submit" className="btn btn-primary">
Keresés
</button>
</form>
{q.length >= 2 &&
(results.length === 0 ? (
<p className="fh-card fh-empty">Erre nincs találat. Próbáld más szóval, vagy rövidebben.</p>
) : (
<ul className="fh-card fh-flush fsearch-results">
{results.map((r) => (
<li key={r.thread.id}>
<Link href={threadHref(r.thread, r.post_id ?? undefined)} className="fsearch-hit">
<span className="fsearch-title">{r.thread.title}</span>
<span className="fsearch-meta">
{r.topic.name} · {r.author?.nickname ?? "Törölt tag"} · {r.reply_count} válasz · utoljára{" "}
<time suppressHydrationWarning dateTime={r.last_post_at}>
{ago(r.last_post_at)}
</time>
</span>
{r.snippet && (
<span className="fsearch-snippet">
<Marked text={r.snippet} />
</span>
)}
</Link>
</li>
))}
</ul>
))}
{(page > 1 || more) && (
<nav className="forum-pager" aria-label="Lapozás">
{page > 1 ? <Link href={link(page - 1)}>‹ Előző</Link> : <span />}
<span className="hint">{page}. oldal</span>
{more ? <Link href={link(page + 1)}>Következő ›</Link> : <span />}
</nav>
)}
</div>
);
}
@@ -0,0 +1,29 @@
import { redirect } from "next/navigation";
import { RepliesTabs } from "@/components/forum/RepliesTabs";
import { ThreadList } from "@/components/forum/ThreadList";
import type { ForumViewer, ThreadCard } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
export const metadata = { title: "Követett szálak", robots: { index: false } };
/** The threads the member follows (their own and the ones they replied to), with what is new. */
export default async function FollowedPage() {
const res = await forumGet<{ viewer: ForumViewer; threads: ThreadCard[] }>("/v1/forum/followed");
if (!res.ok) redirect("/belepes?vissza=/forum/kovetett");
const { threads } = res.data;
return (
<div className="fh">
<h1 className="fpage-title">Válaszok</h1>
<RepliesTabs current="followed" />
<p className="muted">A saját szálaid, azok, amelyekhez hozzászóltál, és amelyeket követni kezdtél.</p>
{threads.length === 0 ? (
<p className="fh-card fh-empty">Még nem követsz egy szálat sem.</p>
) : (
<div className="fh-card fh-flush">
<ThreadList threads={threads} />
</div>
)}
</div>
);
}
@@ -0,0 +1,66 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ForumNav } from "@/components/forum/ForumNav";
import { ThemeToggle } from "@/components/forum/ThemeToggle";
import { PublicHeader } from "@/components/SiteHeader";
import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
import { forumEnabled, forumGet } from "@/lib/forumServer";
import "./forum.css";
export const metadata: Metadata = {
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.",
};
/**
* The live connection's address: in production Caddy sends `/api/v1/forum/ws`
* straight to the forum service; in development FORUM_WS_URL points at it.
*
* The forum's frame: the visitor header (the logged-in one comes from the
* root layout), the forum's bar with its menu and the light/dark switch.
* Light by default; the choice lives in a cookie.
*/
export default async function ForumLayout({ children }: { children: React.ReactNode }) {
if (!forumEnabled()) notFound();
const [nav, jar] = await Promise.all([forumGet<ForumNavData>("/v1/forum/nav"), cookies()]);
const viewer = nav.ok ? nav.data.viewer : null;
const theme: ForumTheme = jar.get(FORUM_THEME_COOKIE)?.value === "dark" ? "dark" : "light";
return (
<>
{!viewer?.logged_in && <PublicHeader current="forum" />}
<div className="forum" data-theme={theme}>
<div className="forum-inner">
<div className="forum-bar">
<Link href="/forum" className="forum-mark">
Fórum
</Link>
<ForumNav
member={viewer?.member?.nickname ?? null}
loggedIn={viewer?.logged_in ?? false}
initial={{
replies: nav.ok ? (nav.data.replies ?? 0) : 0,
messages: nav.ok ? (nav.data.messages ?? 0) : 0,
reports: nav.ok ? (nav.data.reports ?? 0) : 0,
}}
wsUrl={process.env.FORUM_WS_URL || "/api/v1/forum/ws"}
/>
<div className="forum-tools">
<Link href="/forum/kereses" className="forum-theme forum-search" aria-label="Keresés a fórumban">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="11" cy="11" r="6.5" />
<path d="M16 16l4.5 4.5" />
</svg>
</Link>
<ThemeToggle initial={theme} />
</div>
</div>
<main className="forum-main">{children}</main>
</div>
</div>
</>
);
}
@@ -0,0 +1,48 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
export function ForumUnsubscribe({ token }: { token: string | null }) {
const [state, setState] = useState<"idle" | "busy" | "done">("idle");
const [error, setError] = useState<string | null>(null);
if (!token)
return <p className="msg msg-error">Hiányzik a leiratkozó link vége. Nyisd meg újra a levélben lévő linket.</p>;
async function unsubscribe() {
setState("busy");
setError(null);
try {
await api(`/forum/unsubscribe?token=${encodeURIComponent(token ?? "")}`, { method: "POST" });
setState("done");
} catch (e) {
setError(errorText(e));
setState("idle");
}
}
if (state === "done") {
return (
<p className="fh-banner">
<span>
Kész, a fórum nem küld több levelet. Ha meggondolod magad, a{" "}
<Link href="/forum/beallitasok">fórumprofilodnál</Link> újra bekapcsolhatod.
</span>
</p>
);
}
return (
<>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<button type="button" className="btn btn-primary" disabled={state === "busy"} onClick={unsubscribe}>
{state === "busy" ? "Leiratkozás…" : "Leiratkozom a fórum leveleiről"}
</button>
</>
);
}
@@ -0,0 +1,20 @@
import { ForumUnsubscribe } from "./ForumUnsubscribe";
export const metadata = { title: "Leiratkozás a fórum leveleiről", robots: { index: false } };
type Props = { searchParams: Promise<{ token?: string | string[] }> };
/** From the footer of a forum e-mail: every forum e-mail off, no login needed. */
export default async function ForumUnsubscribePage({ searchParams }: Props) {
const raw = (await searchParams).token;
const token = Array.isArray(raw) ? raw[0] : raw;
return (
<div className="fh fprof">
<h1 className="fpage-title">Leiratkozás</h1>
<p className="muted">
Nem kérsz több levelet a fórumról: se válaszértesítést, se napi összesítőt, se üzenetértesítést.
</p>
<ForumUnsubscribe token={token ?? null} />
</div>
);
}
@@ -0,0 +1,154 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { PostBody } from "@/components/forum/PostBody";
import { api, errorText } from "@/lib/api";
import { REPORT_KINDS, type ReportEntry, ago, memberHref, threadHref } from "@/lib/forum";
const STATUS: Record<string, string> = { resolved: "Lezárva", dismissed: "Alaptalan" };
/** The reports: open ones first (a possible crisis on top), with what was reported and the actions. */
export function ReportsList({ initial }: { initial: ReportEntry[] }) {
const router = useRouter();
const [busy, setBusy] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const open = initial.filter((r) => r.status === "open");
const handled = initial.filter((r) => r.status !== "open");
async function act(r: ReportEntry, work: () => Promise<unknown>) {
setBusy(r.id);
setError(null);
try {
await work();
router.refresh();
} catch (e) {
setError(errorText(e));
} finally {
setBusy(null);
}
}
function removePost(r: ReportEntry) {
if (r.target?.type !== "post") return;
const reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik.");
if (!reason) return;
const id = r.target.id;
void act(r, () => api(`/forum/posts/${id}`, { method: "DELETE", body: { reason } }));
}
const card = (r: ReportEntry) => {
const kind = REPORT_KINDS.find((k) => k.kind === r.kind)?.label ?? r.kind;
const t = r.target;
return (
<article
key={r.id}
className={
r.kind === "crisis" && r.status === "open" ? "fh-card fmod-report fmod-crisis" : "fh-card fmod-report"
}
>
<div className="fmod-report-head">
<strong>{kind}</strong>
<span className="hint">
{r.reporter} ·{" "}
<time suppressHydrationWarning dateTime={r.created_at}>
{ago(r.created_at)}
</time>
{r.open_reports_of_target > 1 && r.status === "open" && ` · ${r.open_reports_of_target} jelentés`}
</span>
</div>
{r.note && <p className="fmod-note">„{r.note}”</p>}
{r.kind === "crisis" && r.status === "open" && (
<p className="hint warn">
Lehet, hogy valaki bajban van. Ha a hozzászólás közvetlen veszélyre utal, ne csak moderálj: írj neki
kedvesen, és mutasd meg a 116-123-as lelki elsősegély-számot.
</p>
)}
{t?.type === "post" && (
<div className="fmod-target">
<span className="hint">
Hozzászólás:{" "}
{t.author ? <Link href={memberHref(t.author.nickname)}>{t.author.nickname}</Link> : "törölt tag"} ·{" "}
<Link href={threadHref(t.thread, t.id)}>{t.thread.title}</Link>
{t.deleted && " · már eltávolítva"}
</span>
<PostBody text={t.body} />
</div>
)}
{t?.type === "message" && (
<div className="fmod-target">
<span className="hint">Privát üzenet, az előzményeivel (csak a jelentés miatt látod):</span>
<ol className="fmod-chat">
{t.messages.map((m) => (
<li key={m.id} className={m.reported ? "fmod-chat-reported" : undefined}>
<strong>{m.sender?.nickname ?? "Törölt tag"}:</strong> {m.body}
</li>
))}
</ol>
</div>
)}
{r.status === "open" ? (
<div className="fmsg-actions">
{t?.type === "post" && !t.deleted && (
<button
type="button"
className="btn btn-sm btn-danger"
disabled={busy === r.id}
onClick={() => removePost(r)}
>
Eltávolítás
</button>
)}
<button
type="button"
className="btn btn-sm"
disabled={busy === r.id}
onClick={() => act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "resolve" } }))}
>
Kezeltem, lezárom
</button>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy === r.id}
onClick={() => act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "dismiss" } }))}
>
Alaptalan
</button>
</div>
) : (
<p className="hint">
{STATUS[r.status]}
{r.handled_by && ` · ${r.handled_by}`}
</p>
)}
</article>
);
};
return (
<>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<section className="fh-section" aria-labelledby="fmod-open">
<h2 id="fmod-open" className="fmsg-h">
Nyitott jelentések ({open.length})
</h2>
{open.length === 0 ? <p className="fh-card fh-empty">Nincs nyitott jelentés.</p> : open.map(card)}
</section>
{handled.length > 0 && (
<section className="fh-section" aria-labelledby="fmod-done">
<h2 id="fmod-done" className="fmsg-h">
Az elmúlt 30 nap lezárt jelentései
</h2>
{handled.map(card)}
</section>
)}
</>
);
}
@@ -0,0 +1,253 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Avatar } from "@/components/forum/Avatar";
import { RankBadge } from "@/components/forum/Badges";
import { api, errorText } from "@/lib/api";
import { type ForumTopic, type TopicRequest, ago } from "@/lib/forum";
const VISIBILITY: Record<string, string> = {
public: "Nyilvános (a keresők is látják)",
members: "Csak tagoknak",
restricted: "Zárt (jóváhagyással)",
};
/** Moderators: requests to join restricted topics. Admins also: opening and editing topics. */
export function TopicsAdmin({
requests,
topics,
admin,
}: {
requests: TopicRequest[];
topics: ForumTopic[];
admin: boolean;
}) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [form, setForm] = useState({ name: "", description: "", visibility: "restricted", listening: false });
async function act(work: () => Promise<unknown>) {
setBusy(true);
setError(null);
try {
await work();
router.refresh();
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
const decide = (r: TopicRequest, action: "approve" | "reject" | "remove") =>
act(() =>
api("/forum/mod/topic-requests", {
body: { topic: r.topic.slug, nickname: r.member?.nickname ?? "", action },
}),
);
const pending = requests.filter((r) => r.status === "pending");
const approved = requests.filter((r) => r.status === "approved");
return (
<>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<section className="fh-section" aria-labelledby="ftop-pending">
<h2 id="ftop-pending" className="fmsg-h">
Jelentkezések zárt témákba ({pending.length})
</h2>
{pending.length === 0 ? (
<p className="fh-card fh-empty">Nincs várakozó jelentkezés.</p>
) : (
pending.map((r) => (
<article key={`${r.topic.slug}-${r.member?.nickname}`} className="fh-card fmod-report">
<div className="fmod-report-head">
<span className="fh-online-item">
<Avatar avatar={r.member?.avatar} size={28} />
<strong>{r.member?.nickname ?? "?"}</strong>
{r.member && <RankBadge rank={r.member.rank} name={r.member.rank_name} />}
</span>
<span className="hint">
{r.topic.name} ·{" "}
<time suppressHydrationWarning dateTime={r.requested_at}>
{ago(r.requested_at)}
</time>
</span>
</div>
{r.note && <p className="fmod-note">„{r.note}”</p>}
<div className="fmsg-actions">
<button
type="button"
className="btn btn-sm btn-primary"
disabled={busy}
onClick={() => decide(r, "approve")}
>
Jóváhagyom
</button>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy}
onClick={() => decide(r, "reject")}
>
Elutasítom
</button>
</div>
</article>
))
)}
</section>
{approved.length > 0 && (
<section className="fh-section" aria-labelledby="ftop-members">
<h2 id="ftop-members" className="fmsg-h">
Zárt témák tagjai
</h2>
<ul className="fh-card fh-flush fmodlog">
{approved.map((r) => (
<li key={`${r.topic.slug}-${r.member?.nickname}`} className="ftop-member">
<span className="fh-online-item">
<Avatar avatar={r.member?.avatar} size={24} />
{r.member?.nickname ?? "?"}
<span className="hint">· {r.topic.name}</span>
</span>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy}
onClick={() =>
window.confirm(`Eltávolítod ${r.member?.nickname} tagot a(z) „${r.topic.name}” témából?`) &&
decide(r, "remove")
}
>
Eltávolítom
</button>
</li>
))}
</ul>
</section>
)}
{admin && (
<section className="fh-section" aria-labelledby="ftop-admin">
<h2 id="ftop-admin" className="fmsg-h">
Témák (admin)
</h2>
<ul className="fh-card fh-flush fmodlog">
{topics.map((t) => (
<li key={t.slug} className="ftop-member">
<span>
<strong>{t.name}</strong> <span className="hint">· {VISIBILITY[t.visibility] ?? t.visibility}</span>
{t.archived && <span className="hint"> · archivált</span>}
</span>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy}
onClick={() =>
(t.archived ||
window.confirm(
`Archiválod a(z) „${t.name}” témát? A szálai olvashatók maradnak, de új szál és hozzászólás nem írható bele, és lekerül a főoldalról.`,
)) &&
act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { archived: !t.archived } }))
}
>
{t.archived ? "Visszaállítás" : "Archiválás"}
</button>
<select
className="inp ftop-vis"
aria-label={`${t.name} láthatósága`}
value={t.visibility}
disabled={busy}
onChange={(e) =>
act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { visibility: e.target.value } }))
}
>
{Object.entries(VISIBILITY).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</li>
))}
</ul>
<form
className="fh-card fnew"
onSubmit={(e) => {
e.preventDefault();
void act(async () => {
await api("/forum/topics", { body: form });
setForm({ name: "", description: "", visibility: "restricted", listening: false });
});
}}
>
<strong>Új téma</strong>
<div className="field">
<label htmlFor="ftop-name">Név</label>
<input
id="ftop-name"
className="inp"
value={form.name}
maxLength={60}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
/>
</div>
<div className="field">
<label htmlFor="ftop-desc">Rövid leírás</label>
<input
id="ftop-desc"
className="inp"
value={form.description}
maxLength={160}
onChange={(e) => setForm({ ...form, description: e.target.value })}
required
/>
</div>
<div className="field">
<label htmlFor="ftop-visibility">Láthatóság</label>
<select
id="ftop-visibility"
className="inp"
value={form.visibility}
onChange={(e) => setForm({ ...form, visibility: e.target.value })}
>
{Object.entries(VISIBILITY).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</div>
<label className="fprof-check">
<input
type="checkbox"
checked={form.listening}
onChange={(e) => setForm({ ...form, listening: e.target.checked })}
/>
<span>
<strong>Meghallgatós téma</strong>
<span className="hint">Az új szálak alapból meghallgatást kérnek, nem tanácsot.</span>
</span>
</label>
<button
type="submit"
className="btn btn-primary"
disabled={busy || !form.name.trim() || !form.description.trim()}
>
Téma létrehozása
</button>
</form>
</section>
)}
</>
);
}
@@ -0,0 +1,124 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import {
type ForumTopic,
type ModLogEntry,
type ReportEntry,
type TopicRequest,
banText,
memberHref,
threadHref,
} from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
import { getMe } from "@/lib/server";
import { ReportsList } from "./ReportsList";
import { TopicsAdmin } from "./TopicsAdmin";
export const metadata = { title: "Moderálás", robots: { index: false } };
const ACTIONS: Record<string, string> = {
delete_post: "hozzászólást távolított el",
restore_post: "hozzászólást állított vissza",
delete_thread: "szálat távolított el",
restore_thread: "szálat állított vissza",
ban: "eltiltotta",
unban: "feloldotta az eltiltását",
lock: "lezárta a szálat",
unlock: "feloldotta a szálat",
pin: "kitűzte a szálat",
unpin: "levette a kitűzést",
resolve_report: "lezárt egy jelentést",
dismiss_report: "alaptalannak ítélt egy jelentést",
approve_member: "felvette egy zárt témába",
reject_member: "elutasította a jelentkezését",
remove_member: "eltávolította egy zárt témából",
reset_avatar: "eltávolította a saját képét",
topic: "témát kezelt",
};
type Props = { searchParams: Promise<{ nezet?: string }> };
/** Moderators: the open reports, and the log of every moderation step. */
export default async function ModerationPage({ searchParams }: Props) {
const view = (await searchParams).nezet;
const log = view === "naplo";
const topics = view === "temak";
return (
<div className="fh">
<h1 className="fpage-title">Moderálás</h1>
<nav className="fmod-tabs" aria-label="Moderálás">
<Link href="/forum/moderalas" aria-current={log || topics ? undefined : "page"}>
Jelentések
</Link>
<Link href="/forum/moderalas?nezet=temak" aria-current={topics ? "page" : undefined}>
Témák
</Link>
<Link href="/forum/moderalas?nezet=naplo" aria-current={log ? "page" : undefined}>
Napló
</Link>
</nav>
{log ? <LogView /> : topics ? <TopicsView /> : <ReportsView />}
</div>
);
}
async function ReportsView() {
const res = await forumGet<{ reports: ReportEntry[] }>("/v1/forum/mod/reports");
if (!res.ok) notFound();
return <ReportsList initial={res.data.reports} />;
}
async function TopicsView() {
const [requests, list, me] = await Promise.all([
forumGet<{ requests: TopicRequest[] }>("/v1/forum/mod/topic-requests"),
forumGet<{ topics: ForumTopic[] }>("/v1/forum/topics"),
getMe(),
]);
if (!requests.ok) notFound();
return (
<TopicsAdmin
requests={requests.data.requests}
topics={list.ok ? list.data.topics : []}
admin={me?.user.roles.includes("admin") ?? false}
/>
);
}
async function LogView() {
const res = await forumGet<{ entries: ModLogEntry[] }>("/v1/forum/mod/log");
if (!res.ok) notFound();
if (res.data.entries.length === 0) return <p className="fh-card fh-empty">Még nem volt moderálás.</p>;
return (
<ul className="fh-card fh-flush fmodlog">
{res.data.entries.map((e) => (
<li key={e.id}>
<span className="hint">
{new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
{e.actor_kind === "ai" && " · AI"}
</span>
<span>
<strong>{e.actor ?? "?"}</strong> {ACTIONS[e.action] ?? e.action}
{e.target && (
<>
{" "}
(<Link href={memberHref(e.target)}>{e.target}</Link>)
</>
)}
{e.thread && (
<>
{": "}
<Link href={threadHref({ id: e.thread.id, slug: "" }, e.post_id ?? undefined)}>
{e.thread.title ?? `#${e.thread.id}`}
</Link>
</>
)}
{e.until && ` · ${banText(e.until)}`}
</span>
{e.reason && <span className="hint">Ok: {e.reason}</span>}
</li>
))}
</ul>
);
}
+333
View File
@@ -0,0 +1,333 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Avatar } from "@/components/forum/Avatar";
import { RankBadge } from "@/components/forum/Badges";
import { JoinTopic } from "@/components/forum/JoinTopic";
import { TopicIcon } from "@/components/forum/TopicIcon";
import { ThreadList, WaitingCard } from "@/components/forum/ThreadList";
import { MoonPhaseIcon } from "@/components/MoonChip";
import { MOON_PHASES, SIGNS } from "@/lib/astro";
import { type ForumHome, ago, memberHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
import { loadSky } from "@/lib/sky";
import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText";
import type { SkyNow } from "@/lib/types";
export const metadata = { title: { absolute: "Fórum · Sorsfonalak" } };
/** "Mai égbolt": the Moon today, the same for everyone; never empty. */
function SkyCard({ sky }: { sky: SkyNow }) {
const moon = sky.moon;
const sign = moon.position.sign;
const date = new Date(sky.local_time.slice(0, 10) + "T12:00:00Z").toLocaleDateString("hu-HU", {
month: "long",
day: "numeric",
weekday: "long",
timeZone: "UTC",
});
return (
<section className="fh-card fh-sky" aria-labelledby="fh-sky-title">
<div className="fh-card-head">
<span className="eyebrow">Mai égbolt</span>
<span className="hint">{date}</span>
</div>
<div className="fh-sky-body">
<span className="fh-moon">
<MoonPhaseIcon illumination={moon.illumination} waxing={moon.waxing} />
</span>
<div className="fh-sky-text">
<h2 id="fh-sky-title">
{MOON_PHASES[moon.phase] ?? moon.phase}, <span className="sym">{SIGNS[sign]?.glyph}</span> Hold{" "}
{withArticle(SIGN_IN[sign] ?? sign)}
</h2>
<p>{MOON_IN_SIGN[sign]}</p>
</div>
</div>
<Link href="/holdnaptar" className="fh-link fh-link-foot">
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="4" y="5.5" width="16" height="14.5" rx="2" />
<path d="M4 10h16M8.5 3.5v4M15.5 3.5v4" />
</svg>
<span className="fh-link-text">
Holdnaptár
<span className="hint">A következő holdfázisok</span>
</span>
<span className="fh-link-arrow" aria-hidden="true">
›
</span>
</Link>
</section>
);
}
export default async function ForumHomePage() {
const [home, sky] = await Promise.all([forumGet<ForumHome>("/v1/forum/home"), loadSky()]);
if (!home.ok) notFound();
const { viewer, replies, waiting, topics, unanswered, hot } = home.data;
return (
<div className="fh fh-home">
<div className="fh-col fh-col-main">
{!viewer.logged_in && (
<section className="fh-card fh-intro o-1">
<h1>Fórum</h1>
<p>
Beszélgetés a spiritualitásról, az égboltról, az álmokról és arról, ami a szívedet nyomja. Itt mindenki
álnéven ír, a tempó nyugodt, és a meghallgatás fontosabb a vitánál.
</p>
<p className="hint">
Olvasni belépés nélkül is lehet. Hozzászólni és az „Ami a szívemen van” témát olvasni belépve.
</p>
<Link href="/belepes?vissza=/forum" className="btn btn-primary">
Belépés
</Link>
</section>
)}
{viewer.needs_nickname && (
<Link href="/forum/beallitasok" className="fh-banner o-2">
<span>
<strong>Válassz álnevet</strong>, hogy hozzászólhass. A valódi neved soha nem jelenik meg a fórumon.
</span>
<span aria-hidden="true">›</span>
</Link>
)}
{viewer.member?.banned && (
<p className="fh-banner fh-banner-warn o-2">
Most nem írhatsz a fórumba. A részleteket a beállításaidnál látod.
</p>
)}
{replies !== null && replies > 0 && (
<Link href="/forum/valaszok" className="fh-banner o-2">
<span>
<strong>{replies === 1 ? "1 új válasz" : `${replies} új válasz`}</strong> érkezett neked
</span>
<span aria-hidden="true">›</span>
</Link>
)}
{unanswered.length > 0 && (
<section className="fh-section o-4" id="varnak" aria-labelledby="fh-waiting">
<div className="fh-section-head">
<h2 id="fh-waiting">Várják a válaszod</h2>
<span className="hint">még senki nem válaszolt</span>
</div>
<div className="fh-waiting-grid">
{unanswered.map((t) => (
<WaitingCard key={t.id} thread={t} />
))}
</div>
</section>
)}
{hot.length > 0 && (
<section className="fh-section o-5" aria-labelledby="fh-hot">
<div className="fh-section-head">
<h2 id="fh-hot">Élénk beszélgetések</h2>
<span className="hint">ma sokan írtak bennük</span>
</div>
<div className="fh-card fh-flush">
<ThreadList threads={hot} />
</div>
</section>
)}
<section className="fh-section o-6" aria-labelledby="fh-topics">
<div className="fh-section-head">
<h2 id="fh-topics">Témák</h2>
</div>
<ul className="fh-card fh-flush fh-topics">
{topics
.filter((t) => !t.archived)
.map((t) =>
t.visibility === "restricted" && !t.readable ? (
<li key={t.slug}>
<div className="fh-topic fh-topic-closed">
<span className="fh-topic-icon">
<TopicIcon slug={t.slug} />
</span>
<span className="fh-topic-text">
<span className="fh-topic-name">
{t.name}
<svg viewBox="0 0 24 24" className="fh-lock" role="img" aria-label="Zárt téma">
<rect x="5" y="11" width="14" height="9" rx="2" />
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
</svg>
</span>
<span className="fh-topic-desc">{t.description}</span>
<span className="fh-topic-last">Zárt kör: jóváhagyás után olvasható</span>
</span>
{viewer.member && <JoinTopic slug={t.slug} pending={t.membership === "pending"} />}
</div>
</li>
) : (
<li key={t.slug}>
<Link
href={t.readable ? `/forum/${t.slug}` : `/belepes?vissza=/forum/${t.slug}`}
className="fh-topic"
>
<span className="fh-topic-icon">
<TopicIcon slug={t.slug} />
</span>
<span className="fh-topic-text">
<span className="fh-topic-name">
{t.name}
{t.visibility !== "public" && (
<svg viewBox="0 0 24 24" className="fh-lock" role="img" aria-label="Csak tagoknak">
<rect x="5" y="11" width="14" height="9" rx="2" />
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
</svg>
)}
</span>
<span className="fh-topic-desc">{t.description}</span>
{t.readable && t.last && (
<span className="fh-topic-last">
{t.last.author && (
<Avatar avatar={t.last.author.avatar} size={18} online={t.last.author.online} />
)}
{t.last.author?.nickname ?? "Törölt tag"},{" "}
<time suppressHydrationWarning dateTime={t.last.at}>
{ago(t.last.at)}
</time>
</span>
)}
{!t.readable && <span className="fh-topic-last">Belépés után olvasható</span>}
</span>
{t.readable && (
<span className="fh-topic-count">
<strong>{t.thread_count ?? 0}</strong> szál
</span>
)}
{t.readable && t.new_count ? (
<span className="ft-new">{t.new_count > 99 ? "99+" : t.new_count} új</span>
) : null}
</Link>
</li>
),
)}
</ul>
{topics.some((t) => t.archived) && (
<details className="fh-archived">
<summary>Archivált témák ({topics.filter((t) => t.archived).length})</summary>
<ul className="fh-card fh-flush fh-links">
{topics
.filter((t) => t.archived && t.readable)
.map((t) => (
<li key={t.slug}>
<Link href={`/forum/${t.slug}`} className="fh-link">
<span className="fh-link-text">
{t.name}
<span className="hint">
{t.description} · {t.thread_count ?? 0} szál
</span>
</span>
<span className="fh-link-arrow" aria-hidden="true">
›
</span>
</Link>
</li>
))}
</ul>
</details>
)}
</section>
</div>
<aside className="fh-col fh-col-side" aria-label="Oldalsáv">
{sky && (
<div className="o-3">
<SkyCard sky={sky} />
</div>
)}
{home.data.online.length > 0 && (
<section className="fh-card fh-online o-7" aria-labelledby="fh-online-title">
<h2 id="fh-online-title" className="fh-online-title">
Most itt vannak <span className="hint">({home.data.online.length})</span>
</h2>
<ul className="fh-online-list">
{home.data.online.map((m) => (
<li key={m.nickname}>
<Link href={memberHref(m.nickname)} className="fh-online-item">
<Avatar avatar={m.avatar} size={28} online />
<span>{m.nickname}</span>
</Link>
</li>
))}
</ul>
</section>
)}
{viewer.member && (
<section className="fh-card fh-me o-7" aria-label="Saját">
<div className="fh-me-head">
<Avatar avatar={viewer.member.avatar} size={48} />
<span className="fh-me-names">
<Link href={memberHref(viewer.member.nickname)} className="fa-name">
{viewer.member.nickname}
</Link>
<RankBadge rank={viewer.member.rank} name={viewer.member.rank_name} />
</span>
</div>
{waiting !== null && waiting > 0 && (
<Link href="#varnak" className="fh-link fh-link-boxed">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="8" cy="6.5" r="2.5" />
<circle cx="16" cy="6.5" r="2.5" />
<path d="M3.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
<path d="M11.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
</svg>
<span className="fh-link-text">
{waiting === 1 ? "1 szál vár első válaszra" : `${waiting} szál vár első válaszra`}
<span className="hint">Meghallgatást kérnek, még senki nem válaszolt</span>
</span>
<span className="fh-link-arrow" aria-hidden="true">
›
</span>
</Link>
)}
<div className="fh-me-actions">
<Link href="/forum/uj" className="btn btn-primary btn-sm">
Új szál
</Link>
<Link href="/forum/beallitasok" className="btn btn-sm">
Fórumprofil
</Link>
</div>
</section>
)}
<nav className="fh-card fh-flush fh-links o-8" aria-label="Továbbiak">
<Link href="/aszf#forum" className="fh-link">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 4.5h9.5a3 3 0 0 1 3 3v12h-9.5a3 3 0 0 1-3-3z" />
<path d="M8.5 9h5.5M8.5 12.5h5.5" />
</svg>
<span className="fh-link-text">
Házirend
<span className="hint">A fórum szabályai</span>
</span>
<span className="fh-link-arrow" aria-hidden="true">
›
</span>
</Link>
{viewer.moderator && (
<Link href="/forum/moderalas" className="fh-link">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 3.5l7 2.5v5.5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z" />
<path d="M9 12l2.2 2.2L15.5 10" />
</svg>
<span className="fh-link-text">
Moderálás
<span className="hint">Jelentések, témák, napló</span>
</span>
<span className="fh-link-arrow" aria-hidden="true">
›
</span>
</Link>
)}
</nav>
</aside>
</div>
);
}
@@ -0,0 +1,49 @@
import type { Metadata } from "next";
import { notFound, permanentRedirect, redirect } from "next/navigation";
import { ThreadView } from "@/components/forum/ThreadView";
import type { ThreadPage } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
type Props = { params: Promise<{ id: string }> };
/** `123-nem-tudom-elengedni` → 123; the words after the number are only for reading. */
function threadId(param: string): number | null {
const match = /^(\d{1,15})(?:-|$)/.exec(decodeURIComponent(param));
return match ? Number(match[1]) : null;
}
async function load(param: string) {
const id = threadId(param);
if (id === null) return null;
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const res = await load((await params).id);
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
const { thread, posts } = res.data;
const open = thread.topic.visibility === "public" && !thread.deleted;
const opening = posts.find((p) => p.is_opening)?.body ?? "";
return {
title: thread.title,
description: open ? opening.slice(0, 160) : undefined,
alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` },
// Members-only topics and removed threads stay out of search engines.
robots: open ? undefined : { index: false, follow: false },
};
}
export default async function ThreadPageView({ params }: Props) {
const param = (await params).id;
const res = await load(param);
if (!res) notFound();
if (!res.ok) {
if (res.status === 401) redirect(`/belepes?vissza=/forum/szal/${encodeURIComponent(param)}`);
notFound();
}
const { thread } = res.data;
const canonical = thread.slug ? `${thread.id}-${thread.slug}` : `${thread.id}`;
if (decodeURIComponent(param) !== canonical) permanentRedirect(`/forum/szal/${canonical}`);
return <ThreadView initial={res.data} />;
}
@@ -0,0 +1,102 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
const DURATIONS: { hours: number | null; label: string }[] = [
{ hours: 3, label: "3 óra" },
{ hours: 24, label: "1 nap" },
{ hours: 72, label: "3 nap" },
{ hours: 168, label: "1 hét" },
{ hours: 720, label: "30 nap" },
{ hours: null, label: "Végleg" },
];
/** Moderators: ban a member for a while or for good (they may still read), or lift it. */
export function BanPanel({ nickname, banned, ownPicture }: { nickname: string; banned: boolean; ownPicture: boolean }) {
const router = useRouter();
const [hours, setHours] = useState<string>("24");
const [reason, setReason] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const path = `/forum/members/${encodeURIComponent(nickname)}/ban`;
async function act(work: () => Promise<unknown>) {
setBusy(true);
setError(null);
try {
await work();
router.refresh();
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
return (
<details className="fban">
<summary className="btn btn-sm btn-ghost">Moderálás</summary>
<div className="fban-body">
{ownPicture && (
<button
type="button"
className="btn btn-sm"
disabled={busy}
onClick={() =>
window.confirm("Visszaállítod a kezdő avatart? A feltöltött kép törlődik.") &&
act(() => api(`/forum/members/${encodeURIComponent(nickname)}/avatar-reset`, { method: "POST" }))
}
>
Saját kép eltávolítása
</button>
)}
{banned && (
<button
type="button"
className="btn btn-sm"
disabled={busy}
onClick={() => act(() => api(path, { method: "DELETE" }))}
>
Eltiltás feloldása
</button>
)}
<div className="field">
<label htmlFor="fban-hours">Eltiltás</label>
<select id="fban-hours" className="inp" value={hours} onChange={(e) => setHours(e.target.value)}>
{DURATIONS.map((d) => (
<option key={d.label} value={d.hours ?? "forever"}>
{d.label}
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="fban-reason">Indoklás (a tag látja)</label>
<input
id="fban-reason"
className="inp"
value={reason}
onChange={(e) => setReason(e.target.value)}
maxLength={300}
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<button
type="button"
className="btn btn-sm btn-danger"
disabled={busy || reason.trim().length < 3}
onClick={() => act(() => api(path, { body: { hours: hours === "forever" ? null : Number(hours), reason } }))}
>
Eltiltom
</button>
</div>
</details>
);
}

Some files were not shown because too many files have changed in this diff Show More