Compare commits

...
Author SHA1 Message Date
feco 0bb37c07d9 Merge branch 'main' into prod
CI / test (push) Successful in 3m10s
CI / build (push) Successful in 11m40s
CI / deploy (push) Successful in 42s
2026-11-27 00:35:07 +00:00
fecoandClaude Opus 5.5 de629a068d Forum photos, a one-row bottom menu, and the site's own question windows
CI / test (push) Successful in 3m10s
CI / build (push) Skipped
CI / deploy (push) Skipped
Photos in posts and replies: a "Fotó" button in the new thread form and the
reply boxes. The browser makes the picture small before uploading it (1600
pixels at most, WebP, JPEG where WebP cannot be made); the forum checks it
is a still picture, strips its metadata and makes a square preview
(forum-photos/ in the storage). Five a member a day, five a post; one taken
off before sending is deleted and does not count. Under the post a row of
square previews; a click opens a viewer paged with arrows, swipes and keys.
Seen by whoever may read the thread (long public cache only for public
topics). Unsent photos go after a day, those of removed posts after a year;
removed with the account and listed in the data export. Terms and privacy
notice updated.

The forum's bottom menu keeps its five items in one row (the fifth wrapped
to a second row). On iPhones, when the keyboard goes away without the usual
tap (a photo picker opening over it), the page is put back in place instead
of the menu floating mid-screen over an empty strip.

The browser's own confirm() and prompt() windows (23 places: deleting,
revoking, blocking, muting, moderators' reasons, admin actions) are replaced
by a question window in the site's look, following the forum's light or
dark theme, with named buttons and a text box for reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-27 00:34:59 +00:00
fecoandClaude Opus 5.5 758c3ce7ea CI deploy: a newline before a new TAG_<SERVICE> line, and repair a glued one
CI / test (push) Successful in 3m12s
CI / build (push) Skipped
CI / deploy (push) Skipped
The server's .env ended without a newline, so TAG_FRONTEND stuck to the
last line (FORUM_URL=http://forum:8083TAG_FRONTEND=...): the forum gave 500
and the frontend kept its old image. The deploy now adds the missing
newline first and puts any TAG_<SERVICE>= that stuck to a line back on its
own line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 20:51:54 +00:00
fecoandClaude Opus 5.5 e625fe0487 Merge main: deploy only what changed, new-version notice, home page about personal analyses, forum visitor line
CI / test (push) Successful in 8s
CI / build (push) Successful in 51s
CI / deploy (push) Successful in 22s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 20:40:57 +00:00
fecoandClaude Opus 5.5 27a6226d86 Deploy only what changed; pages notice a new version; home page: personal analyses
CI / test (push) Successful in 3m10s
CI / build (push) Skipped
CI / deploy (push) Skipped
- CI: ci/changed-services.sh compares HEAD with the last deployment's v*
  tag: the Rust tests run only when a Rust service changed, only the
  changed images are built, and the server's .env gets a tag per built
  service (TAG_FRONTEND, TAG_BACKEND, ...; TAG stays the fallback), so only
  their containers restart. Everything when in doubt.
- The frontend image knows its version (APP_VERSION, the commit): Next's
  deploymentId (a page from an older version reloads on navigation) and
  /api/version. VersionWatcher checks every 5 minutes and when the tab
  comes to the front: idle with nothing typed, the page reloads; otherwise
  a "Frissült az oldal" notice offers it.
- Home page: "Nem sablonszöveg, hanem a te elemzésed" in the hero, the
  "Miért más?" section now about analyses written for each chart; the two
  hero buttons side by side on phones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 20:40:43 +00:00
fecoandClaude Opus 5.5 083de72877 Forum: a more natural line for visitors on the front page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 18:59:18 +00:00
fecoandClaude Opus 5.5 7b52a46541 Merge main: thread cards with the opening's start, latest and pinned threads on the forum home; avatars and conversation requests for every member
CI / test (push) Successful in 3m7s
CI / build (push) Successful in 11m22s
CI / deploy (push) Successful in 42s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 18:19:08 +00:00
fecoandClaude Opus 5.5 8150247503 Forum: thread cards with the start of the opening post, latest threads and pinned threads on the front page
CI / test (push) Successful in 3m19s
CI / build (push) Skipped
CI / deploy (push) Skipped
- Every thread card shows the start of the opening post (two lines on a
  computer, three on a phone), its topic with the icon (a lock for
  members-only and restricted ones), pinned and the wish; the replies, the
  last activity and what is new on the right (in the bottom line on a
  phone). The same card in topics, search and followed threads.
- The front page: "Legutóbbi szálak" below the topics, from every topic
  the viewer may read (not the archived ones), the latest activity first,
  20 a page with a pager; pinned threads in "Kitűzve" above the topics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 18:15:43 +00:00
52 changed files with 1986 additions and 173 deletions
+44 -12
View File
@@ -2,6 +2,11 @@
# prod: tests, image build (tags: commit hash, `prod`, `latest`), then
# deployment to the server.
#
# Only what changed since the last deployment (ci/changed-services.sh): the
# Rust tests run when a Rust service changed, only the changed images are
# built, and only their containers restart (each service has its own tag on
# the server: TAG_BACKEND, TAG_FRONTEND, ...; TAG is the fallback).
#
# Runs on the self-hosted runner in ci/runner (label `linux`), one job at a
# time; building on main too would build every deployed commit twice. Jobs use
# the host's Docker daemon, so image builds share its BuildKit cache.
@@ -53,14 +58,23 @@ jobs:
apk add --no-cache -q git musl-dev
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git fetch -q --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
git fetch -q --unshallow --tags origin
- name: Wait for Postgres
run: |
for i in $(seq 30); do nc -z postgres 5432 && exit 0; sleep 1; done
echo "postgres did not start" >&2; exit 1
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
# data (scripts/fetch-deps.sh); their tests run locally.
# data (scripts/fetch-deps.sh); their tests run locally. Skipped when
# only the frontend (or nothing built) changed since the last deployment.
- name: Test
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
run: |
services=$(sh ci/changed-services.sh)
echo "changed since the last deployment: ${services:-nothing}"
case " $services " in
*" backend "*|*" worker "*|*" forum "*|*" horoscope-api "*) ;;
*) echo "no Rust service changed: tests skipped"; exit 0 ;;
esac
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
@@ -72,6 +86,7 @@ jobs:
apk add --no-cache -q git
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git fetch -q --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
git fetch -q --unshallow --tags origin
- name: Log in to the registry
env:
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
@@ -92,11 +107,15 @@ jobs:
docker push -q "$image:$t"
done
}
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
services=$(sh ci/changed-services.sh)
echo "building: ${services:-nothing}"
for svc in $services; do
case "$svc" in
# The frontend knows its version (the page's new-version notice, Next's skew protection).
frontend) build frontend --build-arg APP_VERSION="$tag" services/frontend ;;
*) build "$svc" -f "services/$svc/Dockerfile" . ;;
esac
done
# Only the last 5 commit images of each service stay in the registry,
# plus `main`, `prod`, `latest` and the commit running in production
# (the server pulls it by its commit tag).
@@ -156,6 +175,7 @@ jobs:
apk add --no-cache -q git openssh-client
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git fetch -q --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
git fetch -q --unshallow --tags origin
- name: SSH key
env:
KEY: ${{ secrets.DEPLOY_SSH_KEY }}
@@ -164,8 +184,9 @@ jobs:
mkdir -p ~/.ssh && chmod 700 ~/.ssh
(umask 077 && printf '%s\n' "$KEY" > ~/.ssh/id_ed25519)
printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
# Copies the compose files, pins TAG in the server's .env and restarts
# the changed services. The database migrations run when the backend starts.
# Copies the compose files, pins the built services' tags (TAG_<SERVICE>)
# in the server's .env and restarts the changed services only. The
# database migrations run when the backend (or the forum) starts.
- name: Deploy
env:
HOST: ${{ vars.DEPLOY_HOST }}
@@ -173,9 +194,19 @@ jobs:
run: |
set -eu
tag=$(echo "${{ github.sha }}" | cut -c1-12)
services=$(sh ci/changed-services.sh)
echo "deploying: ${services:-nothing new}"
pin=""
for svc in $services; do
var="TAG_$(echo "$svc" | tr 'a-z-' 'A-Z_')"
pin="$pin (grep -q '^$var=' .env && sed -i 's/^$var=.*/$var=$tag/' .env || echo '$var=$tag' >> .env) &&"
done
scp -q deploy/docker-compose.yml deploy/Caddyfile "$HOST:$DIR/"
ssh "$HOST" "cd '$DIR' && \
(grep -q '^TAG=' .env && sed -i 's/^TAG=.*/TAG=$tag/' .env || echo 'TAG=$tag' >> .env) && \
# The .env may end without a newline (a line added by hand): one first,
# so a new TAG_<SERVICE> line does not stick to the last one; and a
# TAG_<SERVICE>= that did stick (2026-11-26) goes back to its own line.
fix="sed -i -e '\$a\\' .env && sed -i -e 's/\\([^[:space:]]\\)\\(TAG_[A-Z_]*=\\)/\\1\\n\\2/' .env &&"
ssh "$HOST" "cd '$DIR' && $fix $pin \
docker compose pull -q && docker compose up -d --remove-orphans --wait && \
docker compose exec -T caddy caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile && \
docker image prune -af >/dev/null"
@@ -188,7 +219,8 @@ jobs:
run: |
set -eu
apk add --no-cache -q curl jq
git fetch -q --unshallow --tags origin
# The checkout above already has the whole history.
git fetch -q --tags origin
short=$(echo "${{ github.sha }}" | cut -c1-7)
name="v$(date -u +%Y.%m.%d)-$short"
if curl -fsS -o /dev/null -H "Authorization: token $TOKEN" "$API/releases/tags/$name" 2>/dev/null; then
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# Prints the services whose image has to be built for HEAD: those whose files
# changed since the last deployment (the newest v* release tag among HEAD's
# ancestors; the release step tags every deployment). Prints all of them when
# there is no such tag or the comparison fails, so a doubt builds everything.
# Needs the full history and the tags (git fetch --unshallow --tags).
#
# frontend services/frontend/
# backend, worker, forum their folder, the shared crates/, Cargo.toml, Cargo.lock
# horoscope-api the same, and scripts/fetch-deps.sh
set -u
ALL="horoscope-api backend worker forum frontend"
prev=$(git describe --tags --abbrev=0 --match 'v*' HEAD 2>/dev/null) || { echo "$ALL"; exit 0; }
files=$(git diff --name-only "$prev" HEAD) || { echo "$ALL"; exit 0; }
changed() { printf '%s\n' "$files" | grep -Eq "$1"; }
rust='^(crates/|Cargo\.toml$|Cargo\.lock$)'
out=""
changed "^services/horoscope-api/|^scripts/fetch-deps\.sh$|$rust" && out="$out horoscope-api"
for svc in backend worker forum; do
changed "^services/$svc/|$rust" && out="$out $svc"
done
changed '^services/frontend/' && out="$out frontend"
echo $out
@@ -0,0 +1,18 @@
-- Photos in posts: resized in the browser, checked and stripped of their
-- metadata by the forum, kept in the object storage (forum-photos/), with a
-- square preview. Uploaded first (post_id NULL), attached when the post is
-- sent; unattached ones go after a day. At most five a member a day.
CREATE TABLE forum.photos (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
post_id bigint REFERENCES forum.posts ON DELETE CASCADE,
-- Files in the bucket's forum-photos/ folder: the picture and its preview.
file text NOT NULL,
thumb text NOT NULL,
width integer NOT NULL,
height integer NOT NULL,
bytes integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX photos_post_idx ON forum.photos (post_id, created_at) WHERE post_id IS NOT NULL;
CREATE INDEX photos_owner_idx ON forum.photos (owner_id, created_at DESC);
+8 -4
View File
@@ -9,10 +9,14 @@ A runner egyszerre egy feladatot futtat; ha a main is buildelne, minden kitett c
A lépések:
1. **test**: `cargo test` a backendre, a workerre, a db-re, a horoscope-clientre és a service-kitre, egy Postgres szolgáltatás-konténerrel.
2. **build** (csak prod): megépíti a négy image-et, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-<szolgáltatás>` címre. A frontend buildje a TypeScript-típusokat is ellenőrzi.
3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, beírja az új `TAG`-et a szerveren lévő `.env`-be, majd `docker compose pull && up -d`. Az adatbázis-migrációk a backend indulásakor futnak le.
4. **release** (csak prod, a deploy után): létrehoz egy `v<év.hónap.nap>-<hash>` taget és Gitea-release-t az előző release óta bekerült commitok listájával (repó → Releases).
Csak az épül és indul újra, ami az előző élesítés óta változott (`ci/changed-services.sh`: az előző élesítés `v*` taghez képest nézi a változott fájlokat). A frontend a `services/frontend` mappától függ; a backend, a worker és a fórum a saját mappájától és a közös Rust-csomagoktól (`crates/`, `Cargo.toml`, `Cargo.lock`); a horoscope-api ezektől és a `scripts/fetch-deps.sh`-tól. Ha nincs előző tag, vagy kétséges a helyzet, minden épül.
1. **test**: `cargo test` a Rust-szolgáltatásokra, egy Postgres szolgáltatás-konténerrel. Kimarad, ha egyik Rust-szolgáltatás sem változott.
2. **build** (csak prod): megépíti a változott image-eket, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-<szolgáltatás>` címre. A frontend buildje a TypeScript-típusokat is ellenőrzi, és megkapja a verzióját (`APP_VERSION`, a commit): ebből lesz a Next `deploymentId`-je és a `/api/version` válasza.
3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, a szerveren lévő `.env`-be csak a megépült szolgáltatások címkéjét írja be (`TAG_BACKEND`, `TAG_FRONTEND`, `TAG_FORUM`, `TAG_WORKER`, `TAG_HOROSCOPE_API`; ahol nincs ilyen, a régi `TAG` érvényes), majd `docker compose pull && up -d`: csak a változott konténerek indulnak újra. Az adatbázis-migrációk a backend (és a fórum) indulásakor futnak le.
4. **release** (csak prod, a deploy után): létrehoz egy `v<év.hónap.nap>-<hash>` taget és Gitea-release-t az előző release óta bekerült commitok listájával (repó → Releases). A következő élesítés ehhez a taghez méri a változást.
Új frontend-verziónál a nyitva hagyott oldalak maguk veszik észre (`VersionWatcher`, 5 percenként és amikor a fül előtérbe kerül): ha a látogató nem csinál semmit és nincs beírt szöveg, újratöltődik, különben egy „Frissült az oldal” sáv kínálja fel a frissítést. Linkre kattintva a Next magától teljes újratöltést csinál.
Kézzel is indítható a repó Actions oldaláról (workflow_dispatch).
+6 -6
View File
@@ -28,7 +28,7 @@ services:
restart: unless-stopped
horoscope-api:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-horoscope-api:${TAG:-latest}
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-horoscope-api:${TAG_HOROSCOPE_API:-${TAG:-latest}}
read_only: true
logging: *logging
restart: unless-stopped
@@ -75,7 +75,7 @@ services:
restart: unless-stopped
backend:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-backend:${TAG:-latest}
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-backend:${TAG_BACKEND:-${TAG:-latest}}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
HOROSCOPE_API_URL: http://horoscope-api:8080
@@ -134,7 +134,7 @@ services:
# E-mail delivery, cleanup and the other background jobs.
worker:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG_WORKER:-${TAG:-latest}}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary.
@@ -167,7 +167,7 @@ services:
# The same image writing the analyses and answers (quick and slow lane);
# OPENROUTER_API_KEY comes from .env.secrets.
worker-ai:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG_WORKER:-${TAG:-latest}}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
WORKER_TASKS: analyses
@@ -195,7 +195,7 @@ services:
# 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}
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-forum:${TAG_FORUM:-${TAG:-latest}}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
# The links in the forum's e-mails.
@@ -219,7 +219,7 @@ services:
restart: unless-stopped
frontend:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG_FRONTEND:-${TAG:-latest}}
environment:
BACKEND_URL: http://backend:8081
HOROSCOPE_API_URL: http://horoscope-api:8080
+8 -2
View File
@@ -305,8 +305,14 @@ A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderát
- **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)
- **Videó:** YouTube-linknél előnézet; asztali gépen helyben lejátszható, mobilon a YouTube-appot nyitja.
- **Fotó:** minden tag tölthet fel az új szálhoz és a válaszhoz („Fotó” gomb), tagonként naponta legfeljebb 5-öt, egy hozzászóláshoz legfeljebb 5-öt.
- A böngésző kicsinyíti feltöltés előtt (a hosszabbik oldal legfeljebb 1600 pixel, WebP; ahol a böngésző nem tud WebP-t készíteni, ott JPEG).
- A fórum ellenőrzi, hogy valódi állókép-e (mozgó WebP nem), eltávolítja a rejtett adatokat (EXIF, hely, színprofil), és 360×360-as négyzetes előnézetet készít. A tárolóban: `forum-photos/`.
- A hozzászólás alatt egy sorban négyzetes előnézetek, fix magassággal (ha több van, oldalra görgethető); rákattintva lapozható képnézegető (nyilak, húzás, billentyűk).
- Ugyanaz látja, aki a szálat: nyilvános témánál hosszú nyilvános cache-sel (Cloudflare), csak tagoknak vagy zárt körnek szóló témánál privát válasszal.
- Az el nem küldött fotó egy nap után törlődik; az eltávolított hozzászólás fotói egy év után (addig a moderátorok látják). A fiók törlésekor a tag összes fotója törlődik, az adatexportban szerepel.
- Szerkesztéskor egyelőre nem lehet fotót hozzáadni vagy levenni.
- Az aláírás csak szöveg lehet. (javaslat)
## Privát üzenetek
+13 -1
View File
@@ -181,6 +181,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
"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_photos": rows("SELECT json_build_object('photo', file, 'post_id', post_id, 'uploaded_at', created_at) FROM forum.photos WHERE owner_id = $1 ORDER BY created_at").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?,
@@ -258,11 +259,15 @@ pub async fn delete_me(
.bind(auth.id())
.execute(&mut *tx)
.await?;
// The forum's own avatar picture (in the object storage) goes too.
// The forum's own avatar picture and the photos in posts (in the object storage) go 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?;
let photos: Vec<(String, String)> = sqlx::query_as("SELECT file, thumb FROM forum.photos WHERE owner_id = $1")
.bind(auth.id())
.fetch_all(&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)
@@ -270,6 +275,13 @@ pub async fn delete_me(
{
tracing::warn!(error = %e, "removing a deleted account's forum avatar");
}
if let Some(storage) = &state.storage {
for name in photos.iter().flat_map(|(file, thumb)| [file, thumb]) {
if let Err(e) = storage.delete(&format!("forum-photos/{name}")).await {
tracing::warn!(error = %e, "removing a deleted account's forum photo");
}
}
}
tracing::info!(user = %auth.id(), "account deleted");
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
+15
View File
@@ -75,6 +75,21 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("S3_ENDPOINT is not set: no avatar uploads");
}
let state = Arc::new(AppState::new(pool, base_url, storage));
// Every hour: photos left unattached for a day, and those of long-removed posts.
{
let state = state.clone();
tokio::spawn(async move {
let mut every = tokio::time::interval(std::time::Duration::from_secs(3600));
loop {
every.tick().await;
match routes::photo_cleanup(&state).await {
Ok(0) => {}
Ok(n) => tracing::info!(photos = n, "old photos removed"),
Err(e) => tracing::warn!(error = %e, "photo cleanup"),
}
}
});
}
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}"))?;
+37
View File
@@ -152,6 +152,16 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
.fetch_all(&state.db)
.await?;
// Pinned threads (the daily sky too) stand above the topics.
let pinned: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND th.pinned AND tp.archived_at IS NULL ORDER BY th.last_post_at DESC LIMIT 5",
card_sql(&viewer)
))
.bind(me)
.bind(since)
.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 \
@@ -195,6 +205,7 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
"online": online,
"topics": topics,
"unanswered": cards_json(&state.db, unanswered).await?,
"pinned": cards_json(&state.db, pinned).await?,
"hot": cards_json(&state.db, hot).await?,
})))
}
@@ -318,6 +329,32 @@ pub async fn topic(
})))
}
/// "Legutóbbi szálak" on the front page: the threads of every topic the
/// viewer may read (not the archived ones), the latest activity first.
const LATEST_PAGE: i64 = 20;
pub async fn latest(
State(state): St,
viewer: Viewer,
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
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 tp.archived_at IS NULL ORDER BY th.last_post_at DESC LIMIT $3 OFFSET $4",
card_sql(&viewer)
))
.bind(me)
.bind(since)
.bind(LATEST_PAGE + 1)
.bind((page - 1) * LATEST_PAGE)
.fetch_all(&state.db)
.await?;
let has_more = rows.len() as i64 > LATEST_PAGE;
let rows = rows.into_iter().take(LATEST_PAGE as usize).collect();
Ok(Json(json!({ "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()?;
+18 -2
View File
@@ -13,6 +13,7 @@ mod mentions;
mod messages;
mod moderation;
mod mutes;
mod photos;
mod posts;
mod replies;
mod reports;
@@ -42,6 +43,8 @@ pub type Body<T> = WithRejection<Json<T>, ApiError>;
pub type IdPath = WithRejection<Path<i64>, ApiError>;
pub type St = State<Arc<AppState>>;
pub use photos::cleanup as photo_cleanup;
pub fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/healthz", get(health))
@@ -52,6 +55,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.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/latest", get(home::latest))
.route("/v1/forum/replies", get(replies::list))
.route("/v1/forum/search", get(search::search))
.route("/v1/forum/share-card/{slug}", get(attachments::preview))
@@ -84,6 +88,11 @@ pub fn router(state: Arc<AppState>) -> Router {
put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)),
)
.route("/v1/forum/avatars/{file}", get(avatars::serve))
.route(
"/v1/forum/photos",
post(photos::upload).layer(axum::extract::DefaultBodyLimit::max(photos::MAX_UPLOAD + 1024)),
)
.route("/v1/forum/photos/{file}", get(photos::serve).delete(photos::discard))
.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))
@@ -155,6 +164,9 @@ pub struct CardRow {
pub unread: Option<i64>,
/// The site's own thread (the daily sky).
pub system: bool,
pub topic_visibility: String,
/// The opening post's text (for the excerpt on the card).
pub opening: Option<String>,
}
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
@@ -177,7 +189,9 @@ pub fn card_sql(viewer: &Viewer) -> String {
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 \
th.system, tp.visibility AS topic_visibility, \
(SELECT p.body FROM forum.posts p WHERE p.thread_id = th.id AND p.is_opening \
AND p.deleted_at IS NULL LIMIT 1) AS opening \
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"),
@@ -204,8 +218,10 @@ pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, s
"slug": crate::text::slug(&r.title),
"title": r.title,
"intent": r.intent,
"topic": { "slug": r.topic_slug, "name": r.topic_name },
"topic": { "slug": r.topic_slug, "name": r.topic_name, "visibility": r.topic_visibility },
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
// The start of the opening post, as much as a card shows.
"excerpt": r.opening.as_deref().map(|b| crate::text::excerpt(b, 280)),
"created_at": rfc3339(r.created_at),
"last_post_at": rfc3339(r.last_post_at),
"reply_count": r.reply_count,
+340
View File
@@ -0,0 +1,340 @@
//! Photos in posts. The browser makes the picture small (1600 pixels at
//! most, WebP, or JPEG where it cannot make WebP) before it uploads it; the
//! forum checks that it is a real still picture, strips its metadata (camera,
//! place) and makes a square JPEG preview. A member uploads at most
//! [`DAILY`] in a day; a photo uploaded first is attached when the post is
//! sent ([`attach`]), and one left unattached goes after a day ([`cleanup`]).
//! A photo is shown to whoever may read its post: from a public topic with a
//! long public cache, otherwise privately.
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::{DynamicImage, ImageFormat, ImageReader, Limits};
use serde_json::{Value, json};
use sqlx::PgPool;
use uuid::Uuid;
use super::St;
use crate::AppState;
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
/// Photos a member may upload in a day (rolling 24 hours).
pub const DAILY: i64 = 5;
/// Photos under one post.
pub const PER_POST: usize = 5;
/// The largest upload accepted (already made small by the browser).
pub const MAX_UPLOAD: usize = 4 * 1024 * 1024;
/// The longest side accepted, in pixels.
const MAX_SIDE: u32 = 2560;
const MIN_SIDE: u32 = 32;
/// The square preview's side.
const THUMB: u32 = 360;
const FOLDER: &str = "forum-photos";
/// A checked picture: the bytes to keep, their kind, and the decoded image.
struct Checked {
bytes: Vec<u8>,
extension: &'static str,
content_type: &'static str,
image: DynamicImage,
}
/// A WebP without its metadata chunks (EXIF, XMP, ICC profile); `None` for an
/// animation or a broken container.
fn strip_webp(bytes: &[u8]) -> Option<Vec<u8>> {
if bytes.len() < 12 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WEBP" {
return None;
}
let mut out = Vec::with_capacity(bytes.len());
out.extend_from_slice(b"RIFF\0\0\0\0WEBP");
let mut at = 12;
while at + 8 <= bytes.len() {
let fourcc = &bytes[at..at + 4];
let size = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().ok()?) as usize;
let end = at.checked_add(8)?.checked_add(size)?;
if end > bytes.len() {
return None;
}
let padded = end + (size & 1);
match fourcc {
b"ANIM" | b"ANMF" => return None,
b"EXIF" | b"XMP " | b"ICCP" => {}
b"VP8X" => {
let mut chunk = bytes[at..end].to_vec();
// Flags: ICC (0x20), EXIF (0x08), XMP (0x04) off; animation (0x02) means no.
if chunk.len() > 8 {
if chunk[8] & 0x02 != 0 {
return None;
}
chunk[8] &= !(0x20 | 0x08 | 0x04);
}
out.extend_from_slice(&chunk);
}
_ => out.extend_from_slice(&bytes[at..end]),
}
if padded > end && padded <= bytes.len() {
out.push(0);
}
at = padded;
}
let riff = u32::try_from(out.len() - 8).ok()?;
out[4..8].copy_from_slice(&riff.to_le_bytes());
Some(out)
}
/// A WebP or JPEG still picture of a sensible size, without its metadata.
/// The error is a message for the member.
fn check(bytes: &[u8]) -> Result<Checked, String> {
let unreadable = || "A képet nem sikerült feldolgozni. JPEG, PNG vagy WebP képet válassz.".to_string();
let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| unreadable())?;
let format = reader.format();
let mut reader = reader;
let mut limits = Limits::default();
limits.max_image_width = Some(MAX_SIDE);
limits.max_image_height = Some(MAX_SIDE);
reader.limits(limits);
let image = reader.decode().map_err(|_| "A kép túl nagy vagy sérült.".to_string())?;
if image.width() < MIN_SIDE || image.height() < MIN_SIDE {
return Err("A kép túl kicsi.".into());
}
match format {
Some(ImageFormat::WebP) => {
let bytes = strip_webp(bytes).ok_or_else(|| "Mozgó képet nem lehet feltölteni.".to_string())?;
Ok(Checked { bytes, extension: "webp", content_type: "image/webp", image })
}
// A JPEG (or a PNG from an older browser) is written again: no metadata survives.
Some(ImageFormat::Jpeg | ImageFormat::Png) => {
let rgb = image.to_rgb8();
let mut out = Vec::new();
JpegEncoder::new_with_quality(&mut out, 84).encode_image(&rgb).map_err(|_| unreadable())?;
Ok(Checked {
bytes: out,
extension: "jpg",
content_type: "image/jpeg",
image: DynamicImage::ImageRgb8(rgb),
})
}
_ => Err(unreadable()),
}
}
/// The middle square, small, as JPEG.
fn preview(image: &DynamicImage) -> Result<Vec<u8>, String> {
let side = image.width().min(image.height());
let square = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side);
let small = square.resize_exact(THUMB, THUMB, FilterType::Triangle).to_rgb8();
let mut out = Vec::new();
JpegEncoder::new_with_quality(&mut out, 80).encode_image(&small).map_err(|e| e.to_string())?;
Ok(out)
}
fn photo_json(id: Uuid, file: &str, thumb: &str, width: i32, height: i32) -> Value {
json!({
"id": id,
"url": format!("/api/v1/forum/photos/{file}"),
"thumb": format!("/api/v1/forum/photos/{thumb}"),
"width": width,
"height": height,
})
}
/// `POST /v1/forum/photos`: a picture (the body), resized by the browser.
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?.clone();
let Some(storage) = &state.storage else {
return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into()));
};
let today: i64 = sqlx::query_scalar(
"SELECT count(*) FROM forum.photos WHERE owner_id = $1 AND created_at > now() - interval '1 day'",
)
.bind(member.user_id)
.fetch_one(&state.db)
.await?;
if today >= DAILY {
return Err(ApiError::Limited(format!("Naponta legfeljebb {DAILY} fotót tölthetsz fel. Holnap újra lehet.")));
}
if body.len() > MAX_UPLOAD {
return Err(ApiError::bad("A kép túl nagy."));
}
let bytes = body.to_vec();
let (checked, thumb) = tokio::task::spawn_blocking(move || {
let checked = check(&bytes)?;
let thumb = preview(&checked.image)?;
Ok::<_, String>((checked, thumb))
})
.await
.map_err(|e| ApiError::Internal(e.to_string()))?
.map_err(ApiError::BadRequest)?;
let id = Uuid::now_v7();
let file = format!("{}.{}", id.simple(), checked.extension);
let thumb_file = format!("{}-t.jpg", id.simple());
storage
.put(&format!("{FOLDER}/{file}"), checked.bytes.clone(), checked.content_type)
.await
.map_err(|e| ApiError::Internal(format!("storing a photo: {e}")))?;
storage
.put(&format!("{FOLDER}/{thumb_file}"), thumb, "image/jpeg")
.await
.map_err(|e| ApiError::Internal(format!("storing a photo preview: {e}")))?;
let (width, height) = (checked.image.width() as i32, checked.image.height() as i32);
sqlx::query(
"INSERT INTO forum.photos (id, owner_id, file, thumb, width, height, bytes) VALUES ($1, $2, $3, $4, $5, $6, $7)",
)
.bind(id)
.bind(member.user_id)
.bind(&file)
.bind(&thumb_file)
.bind(width)
.bind(height)
.bind(checked.bytes.len() as i32)
.execute(&state.db)
.await?;
let mut out = photo_json(id, &file, &thumb_file, width, height);
out["remaining"] = json!(DAILY - today - 1);
Ok((StatusCode::CREATED, Json(out)))
}
/// `DELETE /v1/forum/photos/{id}`: a photo taken off before the post was sent;
/// it does not count in the day's five.
pub async fn discard(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): WithRejection<Path<Uuid>, ApiError>,
) -> ApiResult<StatusCode> {
let member = viewer.require_writer()?.clone();
let files: Option<(String, String)> = sqlx::query_as(
"DELETE FROM forum.photos WHERE id = $1 AND owner_id = $2 AND post_id IS NULL RETURNING file, thumb",
)
.bind(id)
.bind(member.user_id)
.fetch_optional(&state.db)
.await?;
let (file, thumb) = files.ok_or(ApiError::NotFound("photo"))?;
if let Some(storage) = &state.storage {
for name in [file, thumb] {
if let Err(e) = storage.delete(&format!("{FOLDER}/{name}")).await {
tracing::warn!(error = %e, "removing a discarded photo");
}
}
}
Ok(StatusCode::NO_CONTENT)
}
/// Attaches the member's uploaded photos to their new post (in its transaction).
pub async fn attach(tx: &mut sqlx::PgConnection, owner: Uuid, post: i64, photos: &[Uuid]) -> Result<(), ApiError> {
if photos.len() > PER_POST {
return Err(ApiError::bad(format!("Egy hozzászóláshoz legfeljebb {PER_POST} fotó tartozhat.")));
}
if photos.is_empty() {
return Ok(());
}
sqlx::query("UPDATE forum.photos SET post_id = $3 WHERE id = ANY($1) AND owner_id = $2 AND post_id IS NULL")
.bind(photos)
.bind(owner)
.bind(post)
.execute(&mut *tx)
.await?;
Ok(())
}
/// The photos of these posts, in upload order.
pub async fn of_posts(db: &PgPool, posts: &[i64]) -> Result<std::collections::HashMap<i64, Vec<Value>>, sqlx::Error> {
let mut out: std::collections::HashMap<i64, Vec<Value>> = Default::default();
if posts.is_empty() {
return Ok(out);
}
let rows: Vec<(i64, Uuid, String, String, i32, i32)> = sqlx::query_as(
"SELECT post_id, id, file, thumb, width, height FROM forum.photos \
WHERE post_id = ANY($1) ORDER BY created_at",
)
.bind(posts)
.fetch_all(db)
.await?;
for (post, id, file, thumb, width, height) in rows {
out.entry(post).or_default().push(photo_json(id, &file, &thumb, width, height));
}
Ok(out)
}
#[derive(sqlx::FromRow)]
struct Served {
owner_id: Uuid,
post_id: Option<i64>,
}
/// `GET /v1/forum/photos/{file}`: a photo or its preview, to whoever may read its post.
pub async fn serve(
State(state): St,
viewer: Viewer,
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
) -> ApiResult<Response> {
let valid = file.len() <= 48 && file.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.'));
if !valid {
return Err(ApiError::NotFound("photo"));
}
let row: Served = sqlx::query_as("SELECT owner_id, post_id FROM forum.photos WHERE file = $1 OR thumb = $1")
.bind(&file)
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("photo"))?;
// Who may see it: the uploader before it is sent; afterwards whoever may read the post.
let public = match row.post_id {
None if viewer.user_id() == Some(row.owner_id) => false,
None => return Err(ApiError::NotFound("photo")),
Some(post) => {
let (thread, deleted): (i64, bool) =
sqlx::query_as("SELECT thread_id, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1")
.bind(post)
.fetch_one(&state.db)
.await?;
if deleted && !viewer.is_moderator() {
return Err(ApiError::NotFound("photo"));
}
let thread = super::threads::readable_thread(&state.db, &viewer, thread)
.await
.map_err(|_| ApiError::NotFound("photo"))?;
thread.deleted_at.is_none() && thread.visibility == "public" && !deleted
}
};
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("photo"))?;
let object = storage
.get(&format!("{FOLDER}/{file}"))
.await
.map_err(|e| ApiError::Internal(format!("reading a photo: {e}")))?
.ok_or(ApiError::NotFound("photo"))?;
let content_type = if file.ends_with(".webp") { "image/webp" } else { "image/jpeg" };
let cache = if public { "public, max-age=31536000, immutable" } else { "private, max-age=3600" };
Ok(([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, cache)], object.bytes).into_response())
}
/// Every hour: unattached photos older than a day, and the photos of posts
/// removed more than a year ago, leave the storage and the table.
pub async fn cleanup(state: &AppState) -> anyhow::Result<u64> {
let Some(storage) = &state.storage else { return Ok(0) };
let gone: Vec<(Uuid, String, String)> = sqlx::query_as(
"SELECT ph.id, ph.file, ph.thumb FROM forum.photos ph LEFT JOIN forum.posts p ON p.id = ph.post_id \
WHERE (ph.post_id IS NULL AND ph.created_at < now() - interval '1 day') \
OR (p.deleted_at IS NOT NULL AND p.deleted_at < now() - interval '1 year') \
LIMIT 500",
)
.fetch_all(&state.db)
.await?;
for (id, file, thumb) in &gone {
for name in [file, thumb] {
if let Err(e) = storage.delete(&format!("{FOLDER}/{name}")).await {
tracing::warn!(error = %e, "removing a photo");
}
}
sqlx::query("DELETE FROM forum.photos WHERE id = $1").bind(id).execute(&state.db).await?;
}
Ok(gone.len() as u64)
}
+1 -10
View File
@@ -98,7 +98,7 @@ pub async fn list(
"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),
"excerpt": crate::text::excerpt(&r.body, 160),
"created_at": rfc3339(r.created_at),
"kind": r.kind,
"unread": r.unread,
@@ -124,12 +124,3 @@ pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult<StatusCode>
.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,
}
}
+12
View File
@@ -117,6 +117,9 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
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 shown: Vec<i64> =
posts.iter().filter(|p| p.deleted_at.is_none() || viewer.is_moderator()).map(|p| p.id).collect();
let photos = super::photos::of_posts(db, &shown).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)
@@ -197,6 +200,7 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
"share": p.share_id.and_then(|id| cards.get(&id).cloned()),
// Previews of the links a provider knows (YouTube).
"links": previews.get(&p.id),
"photos": photos.get(&p.id),
});
if moderator {
post["down"] = json!(down);
@@ -328,6 +332,9 @@ pub struct CreateThread {
/// A share made for the forum on the main site (`/s/<slug>`).
#[serde(default)]
share: Option<String>,
/// Photos uploaded for the opening post.
#[serde(default)]
photos: Vec<Uuid>,
}
/// Starts a thread with its opening post; the author follows it.
@@ -382,6 +389,7 @@ pub async fn create(
.bind(share)
.fetch_one(&mut *tx)
.await?;
super::photos::attach(&mut tx, member.user_id, post_id, &req.photos).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");
@@ -436,6 +444,9 @@ pub struct Reply {
/// post (two levels at most), a reply to the opening post is first-level.
#[serde(default)]
parent_id: Option<i64>,
/// Photos uploaded for the reply.
#[serde(default)]
photos: Vec<Uuid>,
}
pub async fn reply(
@@ -486,6 +497,7 @@ pub async fn reply(
.bind(id)
.execute(&mut *tx)
.await?;
super::photos::attach(&mut tx, member.user_id, post.id, &req.photos).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).
+257 -1
View File
@@ -35,17 +35,40 @@ impl TestApp {
/// With the link providers at these (fake) addresses.
fn with_links(pool: PgPool, links: crate::links::LinkConfig) -> Self {
Self::with_parts(pool, links, None)
}
fn with_parts(pool: PgPool, links: crate::links::LinkConfig, storage: Option<object_storage::Storage>) -> Self {
let state = AppState {
db: pool.clone(),
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: None,
storage,
links,
};
Self { router: routes::router(Arc::new(state)), pool }
}
/// A raw request (an uploaded picture); status, headers and the body as bytes.
async fn raw(
&self,
method: &str,
uri: &str,
user: Option<&User>,
content_type: &str,
body: Vec<u8>,
) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
let mut req = Request::builder().method(method).uri(uri).header("content-type", content_type);
if let Some(u) = user {
req = req.header("authorization", format!("Bearer {}", u.token));
}
let res = self.router.clone().oneshot(req.body(Body::from(body)).unwrap()).await.unwrap();
let (status, headers) = (res.status(), res.headers().clone());
let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
(status, headers, bytes)
}
/// A user with a session, as after a login in the backend.
async fn user(&self, email: &str, roles: &[&str]) -> User {
let id = Uuid::now_v7();
@@ -1408,3 +1431,236 @@ async fn any_member_may_upload_an_avatar(pool: PgPool) {
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.to_string().contains("nem érhető el"), "{body}");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn latest_threads_with_their_beginning(pool: PgPool) {
let app = TestApp::new(pool);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let public = app.thread(&anna, "torzsasztal", "Téli levesek").await;
let members = app.thread(&anna, "ami-a-szivemen-van", "Nehéz napok").await;
app.reply(&anna, public, "Még egy gondolat.", None).await;
let ids =
|v: Value| -> Vec<i64> { v["threads"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect() };
// Members see every topic they may read, the latest activity first; visitors the public ones.
assert_eq!(ids(app.get("/v1/forum/latest", Some(&anna)).await), vec![public, members]);
let visitor = app.get("/v1/forum/latest", None).await;
assert_eq!(ids(visitor.clone()), vec![public]);
assert_eq!(visitor["has_more"], false);
// The card carries the start of the opening post and the topic's visibility.
let card = &visitor["threads"][0];
assert!(card["excerpt"].as_str().unwrap().len() > 3, "{card}");
assert_eq!(card["topic"]["visibility"], "public");
// A pinned thread stands above the topics on the front page.
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
let (status, _) =
app.call("PATCH", &format!("/v1/forum/threads/{public}"), Some(&admin), json!({ "pinned": true })).await;
assert_eq!(status, StatusCode::NO_CONTENT);
let home = app.get("/v1/forum/home", None).await;
assert_eq!(home["pinned"][0]["id"], public);
}
/// An in-memory S3 bucket for the photo tests.
async fn fake_s3() -> object_storage::StorageConfig {
type Store = Arc<std::sync::Mutex<std::collections::HashMap<String, (String, Vec<u8>)>>>;
let store: Store = Default::default();
async fn handle(
axum::extract::State(store): axum::extract::State<Store>,
method: axum::http::Method,
headers: axum::http::HeaderMap,
axum::extract::Path(key): axum::extract::Path<String>,
body: axum::body::Bytes,
) -> axum::response::Response {
use axum::response::IntoResponse;
let mut store = store.lock().unwrap();
match method.as_str() {
"PUT" => {
let ct = headers.get("content-type").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
store.insert(key, (ct, body.to_vec()));
StatusCode::OK.into_response()
}
"GET" => match store.get(&key) {
Some((ct, bytes)) => ([("content-type", ct.clone())], bytes.clone()).into_response(),
None => StatusCode::NOT_FOUND.into_response(),
},
"DELETE" => {
store.remove(&key);
StatusCode::NO_CONTENT.into_response()
}
_ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
}
}
let app = Router::new().route("/photos/{*key}", axum::routing::any(handle)).with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
object_storage::StorageConfig {
endpoint: format!("http://{addr}"),
bucket: "photos".into(),
region: "us-east-1".into(),
access_key: "test-key".into(),
secret_key: "test-secret".into(),
}
}
/// A made-up 800×600 picture as JPEG with an EXIF block hiding a "place".
fn jpeg_with_exif() -> Vec<u8> {
let img = image::RgbImage::from_fn(800, 600, |x, y| image::Rgb([(x % 256) as u8, (y % 256) as u8, 120]));
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80).encode_image(&img).unwrap();
let mut exif = b"Exif\0\0GPSSECRET-47.49N-19.04E".to_vec();
let len = (exif.len() + 2) as u16;
let mut out = vec![0xFF, 0xD8, 0xFF, 0xE1];
out.extend_from_slice(&len.to_be_bytes());
out.append(&mut exif);
out.extend_from_slice(&jpeg[2..]);
out
}
/// A made-up picture as an extended WebP with an EXIF chunk.
fn webp_with_exif() -> Vec<u8> {
let img = image::RgbImage::from_fn(640, 480, |x, y| image::Rgb([(y % 256) as u8, 90, (x % 256) as u8]));
let mut simple = Vec::new();
image::codecs::webp::WebPEncoder::new_lossless(&mut simple)
.encode(img.as_raw(), 640, 480, image::ExtendedColorType::Rgb8)
.unwrap();
let chunk = |fourcc: &[u8], data: &[u8]| {
let mut c = fourcc.to_vec();
c.extend_from_slice(&(data.len() as u32).to_le_bytes());
c.extend_from_slice(data);
if data.len() % 2 == 1 {
c.push(0);
}
c
};
let mut vp8x = vec![0x08, 0, 0, 0];
vp8x.extend_from_slice(&(639u32).to_le_bytes()[..3]);
vp8x.extend_from_slice(&(479u32).to_le_bytes()[..3]);
let mut body = b"WEBP".to_vec();
body.extend(chunk(b"VP8X", &vp8x));
body.extend_from_slice(&simple[12..]);
body.extend(chunk(b"EXIF", b"GPSSECRET-47.49N-19.04E"));
let mut out = b"RIFF".to_vec();
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend(body);
out
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn photos_in_posts(pool: PgPool) {
let storage = fake_s3().await;
let app = TestApp::with_parts(
pool.clone(),
crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
Some(object_storage::Storage::new(storage.clone())),
);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
let upload = |user: &User, ct: &str, body: Vec<u8>| {
let user = User { id: user.id, token: user.token.clone() };
let ct = ct.to_string();
let app = &app;
async move {
let (status, _, body) = app.raw("POST", "/v1/forum/photos", Some(&user), &ct, body).await;
(status, serde_json::from_slice::<Value>(&body).unwrap_or(Value::Null))
}
};
// A JPEG and a WebP: kept without their metadata, with a square preview.
let (status, jpeg) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
assert_eq!(status, StatusCode::CREATED, "{jpeg}");
assert_eq!(
(jpeg["width"].as_i64(), jpeg["height"].as_i64(), jpeg["remaining"].as_i64()),
(Some(800), Some(600), Some(4))
);
let (status, webp) = upload(&anna, "image/webp", webp_with_exif()).await;
assert_eq!(status, StatusCode::CREATED, "{webp}");
let path = |url: &Value| url.as_str().unwrap().trim_start_matches("/api").to_string();
for photo in [&jpeg, &webp] {
let (status, headers, bytes) = app.raw("GET", &path(&photo["url"]), Some(&anna), "", Vec::new()).await;
assert_eq!(status, StatusCode::OK);
assert!(!bytes.windows(9).any(|w| w == b"GPSSECRET"), "metadata must go");
image::load_from_memory(&bytes).expect("still a picture");
assert!(headers["cache-control"].to_str().unwrap().starts_with("private"), "not sent yet: the uploader only");
let (_, _, thumb) = app.raw("GET", &path(&photo["thumb"]), Some(&anna), "", Vec::new()).await;
let preview = image::load_from_memory(&thumb).unwrap();
assert_eq!((preview.width(), preview.height()), (360, 360));
}
assert_eq!(app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
let (status, _) = upload(&anna, "image/jpeg", b"nem kep".to_vec()).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
// Sent with a thread in a public topic: everyone sees them, cached for long.
let (status, created) = app
.call(
"POST",
"/v1/forum/threads",
Some(&anna),
json!({ "topic": "torzsasztal", "title": "Őszi kert", "body": "Nézzétek!", "photos": [jpeg["id"], webp["id"]] }),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{created}");
let thread = app.get(&format!("/v1/forum/threads/{}", created["id"]), None).await;
assert_eq!(thread["posts"][0]["photos"].as_array().unwrap().len(), 2);
let (status, headers, _) = app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await;
assert_eq!(status, StatusCode::OK);
assert!(headers["cache-control"].to_str().unwrap().contains("immutable"));
// In a members-only topic: members only, not cached publicly; Bea cannot use Anna's photo.
let (_, third) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
let heart = app.thread(&bea, "ami-a-szivemen-van", "Nehéz napok").await;
let reply = |user: &User, photos: Value| {
let user = User { id: user.id, token: user.token.clone() };
let app = &app;
async move {
app.call(
"POST",
&format!("/v1/forum/threads/{heart}/posts"),
Some(&user),
json!({ "body": "Itt vagyok.", "photos": photos }),
)
.await
}
};
let (_, stolen) = reply(&bea, json!([third["id"]])).await;
assert!(stolen["photos"].is_null(), "not hers");
let (_, mine) = reply(&anna, json!([third["id"]])).await;
assert_eq!(mine["photos"][0]["id"], third["id"]);
assert_eq!(app.raw("GET", &path(&third["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
let (status, headers, _) = app.raw("GET", &path(&third["url"]), Some(&bea), "", Vec::new()).await;
assert_eq!(status, StatusCode::OK);
assert!(headers["cache-control"].to_str().unwrap().starts_with("private"));
// Taken off before sending: gone, and it does not count.
let (_, extra) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
let gone = format!("/v1/forum/photos/{}", extra["id"].as_str().unwrap());
assert_eq!(app.raw("DELETE", &gone, Some(&bea), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
assert_eq!(app.raw("DELETE", &gone, Some(&anna), "", Vec::new()).await.0, StatusCode::NO_CONTENT);
assert_eq!(app.raw("GET", &path(&extra["url"]), Some(&anna), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
let sent = format!("/v1/forum/photos/{}", third["id"].as_str().unwrap());
assert_eq!(app.raw("DELETE", &sent, Some(&anna), "", Vec::new()).await.0, StatusCode::NOT_FOUND, "already sent");
// Five a day.
for _ in 0..2 {
assert_eq!(upload(&anna, "image/jpeg", jpeg_with_exif()).await.0, StatusCode::CREATED);
}
let (status, body) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
// Unattached for over a day: gone from the table and the storage.
sqlx::query("UPDATE forum.photos SET created_at = now() - interval '2 days' WHERE post_id IS NULL")
.execute(&pool)
.await
.unwrap();
let state = AppState {
db: pool.clone(),
flood_secs: 0,
base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(),
storage: Some(object_storage::Storage::new(storage)),
links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
};
assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 2);
let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap();
assert_eq!(left, 3);
}
+14
View File
@@ -142,6 +142,20 @@ pub fn default_avatar(key: &str) -> String {
format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()])
}
/// The start of a text on one line, at most `max` characters (cut at a word, with "…").
pub fn excerpt(body: &str, max: usize) -> String {
let line = body.split_whitespace().collect::<Vec<_>>().join(" ");
if line.chars().count() <= max {
return line;
}
let cut: String = line.chars().take(max).collect();
let cut = match cut.rfind(' ') {
Some(at) if at > max / 2 => &cut[..at],
_ => &cut[..],
};
format!("{}…", cut.trim_end_matches([',', ';', ':', '–', '-', ' ']))
}
/// 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();
+5 -2
View File
@@ -6,14 +6,17 @@ RUN --mount=type=cache,target=/root/.npm,sharing=locked npm ci --no-audit --no-f
FROM node:22.23-alpine AS build
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
# The commit being built (the CI passes it): Next's deployment id and /api/version.
ARG APP_VERSION=""
ENV NEXT_TELEMETRY_DISABLED=1 APP_VERSION=$APP_VERSION
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:22.23-alpine
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0
ARG APP_VERSION=""
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0 APP_VERSION=$APP_VERSION
RUN addgroup -S app && adduser -S -G app app
COPY --from=build --chown=app:app /app/.next/standalone ./
COPY --from=build --chown=app:app /app/.next/static ./.next/static
+4
View File
@@ -4,6 +4,10 @@ const config: NextConfig = {
// Small self-contained server for the container image.
output: "standalone",
poweredByHeader: false,
// The image's version (the commit, APP_VERSION from the CI build): a page
// loaded from an older version reloads itself on its next navigation, and
// VersionWatcher offers a reload when a new one is out. None in development.
deploymentId: process.env.APP_VERSION || undefined,
// The fonts of the share preview images are read from disk at run time.
outputFileTracingIncludes: {
"/s/[slug]/kep/[file]": ["./src/assets/og/*.ttf"],
+22 -8
View File
@@ -71,10 +71,23 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
Add meg, mikor és hol születtél: percre pontosan kiszámoljuk a képletedet, és személyre szóló elemzést írunk
belőle. Megmutatjuk, mit hoz az éved, és mennyire illetek össze azzal, akit szeretsz.
</p>
<p className="ai-line lp-ai-line lp-rise lp-r3">
Részletes, személyre szóló elemzések a legfejlettebb AI-modellekkel: percek alatt, egy személyes konzultáció
árának töredékéért.
</p>
<div className="lp-personal lp-rise lp-r3">
<svg aria-hidden="true" viewBox="0 0 24 24" className="lp-personal-icon">
<path d="M12 3.5a7.5 7.5 0 0 1 7.5 7.5c0 3-.6 5.7-1.6 7.8" />
<path d="M4.5 11a7.5 7.5 0 0 1 3-6" />
<path d="M8 11a4 4 0 0 1 8 0c0 3.4-.9 6.4-2.3 8.6" />
<path d="M12 11c0 3.8-1.2 6.9-3.2 9" />
<path d="M4.6 14.5c.4 1.8.2 3.4-.4 4.6" />
</svg>
<div>
<strong className="lp-personal-title">Nem sablonszöveg, hanem a te elemzésed</strong>
<p className="lp-personal-text">
Sok horoszkópoldalon előre megírt bekezdések állnak össze: minden Halak ugyanazt kapja. Itt minden
elemzés a te képletedből készül. Nem azt olvasod, hogy „a Halak érzékeny”, hanem hogy a te Halak Napod a
te házaidban, a te fényszögeiddel mit jelent, percek alatt, a legfejlettebb AI-modellekkel.
</p>
</div>
</div>
<div className="lp-actions lp-rise lp-r4">
<Link href={start} className="btn btn-primary lp-btn">
{signIn}
@@ -195,7 +208,7 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
<div className="lp-intro">
<span className="eyebrow">Miért más?</span>
<h2 id="why-title" className="lp-h2">
Alapos elemzés, töredék áron
Személyre szabott, nem előre megírt
</h2>
</div>
<ul className="lp-why-grid">
@@ -204,10 +217,11 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
<path d="M12 3l1.8 4.6L18.5 9l-4.7 1.6L12 15l-1.8-4.4L5.5 9l4.7-1.4z" />
<path d="M18 15l.9 2.1L21 18l-2.1.9L18 21l-.9-2.1L15 18l2.1-.9z" />
</svg>
<h3 className="lp-step-title">A legfejlettebb AI-modellek</h3>
<h3 className="lp-step-title">Minden mondat rólad szól</h3>
<p className="lp-small">
Az elemzéseket a legújabb, legnagyobb nyelvi modellek írják, a te képleted pontosan kiszámolt adataiból. Nem
sablonszövegekből rakjuk össze: minden mondat a te képletedről szól.
Nem csillagjegyenként előre megírt szövegekből rakjuk össze. A legújabb, legnagyobb nyelvi modellek a te
képleted pontosan kiszámolt adataiból írják meg, ezért két ember elemzése akkor is más, ha ugyanaz a
csillagjegyük.
</p>
</li>
<li className="card lp-why-card">
@@ -161,8 +161,8 @@ export default async function PrivacyPage() {
<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
rangod; a hozzászólásaidhoz feltöltött fotók; 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>
@@ -237,7 +237,9 @@ export default async function PrivacyPage() {
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
bármikor leveheted, és a kérdés törlésével a link is megszűnik. A hozzászólásokhoz feltöltött fotóidat a
böngésződ kicsinyíti, a szerverünk eltávolítja belőlük a rejtett adatokat (például a helyet), és ugyanazok
látják, akik a szálat. 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
@@ -381,7 +383,8 @@ export default async function PrivacyPage() {
</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 fórumprofilodat (a saját képeddel együtt), a hozzászólásaidhoz feltöltött fotókat (eltávolított
hozzászólásnál legfeljebb egy évig), 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
+11 -4
View File
@@ -7,6 +7,7 @@ import { huf, usePackages } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { ROLE_LABELS, formatDate } from "@/lib/astro";
import type { AdminUser, Package, Role } from "@/lib/types";
import { confirmDialog } from "@/components/Dialogs";
const PAGE_SIZE = 25;
const EDITABLE_ROLES: Role[] = ["user", "creator", "moderator", "admin"];
@@ -248,10 +249,16 @@ function UserDialog({
}) {
// What was chosen or typed but not sent yet (a package, a number of units).
const unsent = useRef<{ pkg: string | null; credit: string | null }>({ pkg: null, credit: null });
const canClose = () => {
const canClose = async () => {
const { pkg, credit } = unsent.current;
const what = [pkg && `a(z) ${pkg} csomag`, credit && `${credit} jóváírás`].filter(Boolean).join(" és ");
return !what || window.confirm(`Még nem küldted el: ${what}. Bezárod nélküle?`);
if (!what) return true;
return confirmDialog({
title: "Bezárod küldés nélkül?",
text: `Még nem küldted el: ${what}.`,
confirm: "Bezárás",
cancel: "Vissza",
});
};
return (
<Modal
@@ -285,8 +292,8 @@ function UserDialog({
<button
type="button"
className="btn"
onClick={() => {
if (canClose()) onClose();
onClick={async () => {
if (await canClose()) onClose();
}}
>
Bezárás
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { AdminGift } from "@/lib/types";
import { confirmDialog } from "@/components/Dialogs";
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
@@ -51,18 +52,23 @@ export function AdminGifts() {
}, [q, load]);
async function refund(g: AdminGift) {
const late = g.within_withdrawal
? ""
: "\n\nFigyelem: a 14 napos elállási idő már letelt.";
const money = g.checkout?.amount_huf
? ` (${huf(g.checkout.amount_huf)})`
: "";
if (
!window.confirm(
`Visszatéríted a(z) „${g.package.name}” ajándékot${money}? A ${g.code} kód érvénytelen lesz, a Stripe visszautalja az árát, a számla sztornózódik.${late}`,
)
)
return;
const money = g.checkout?.amount_huf ? ` (${huf(g.checkout.amount_huf)})` : "";
const ok = await confirmDialog({
title: `Visszatéríted a(z) „${g.package.name}” ajándékot${money}?`,
text: (
<>
<p>A {g.code} kód érvénytelen lesz, a Stripe visszautalja az árát, a számla sztornózódik.</p>
{!g.within_withdrawal && (
<p>
<strong>Figyelem:</strong> a 14 napos elállási idő már letelt.
</p>
)}
</>
),
confirm: "Visszatérítés",
danger: true,
});
if (!ok) return;
setBusy(g.id);
setError(null);
setDone(null);
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { GenerationError } from "@/lib/types";
import { confirmDialog } from "@/components/Dialogs";
const PAGE = 50;
@@ -83,7 +84,13 @@ export function ErrorLog() {
async function removeMatching() {
const what = source || outcome ? `a szűrésnek megfelelő ${total} bejegyzést` : `mind a ${total} bejegyzést`;
if (!window.confirm(`Biztosan törlöd ${what}? Nem vonható vissza.`)) return;
const ok = await confirmDialog({
title: `Törlöd ${what}?`,
text: "Nem vonható vissza.",
confirm: "Törlés",
danger: true,
});
if (!ok) return;
setBusy(true);
setError(null);
try {
@@ -13,6 +13,7 @@ import { objectPosition, photoSrc } from "@/lib/celebrityPhoto";
import type { AdminCelebrity, Analysis } from "@/lib/types";
import { ANALYSIS_STATUS, SubtitleField } from "../AdminCelebrities";
import { confirmDialog } from "@/components/Dialogs";
const POLL_MS = 10_000;
@@ -65,7 +66,14 @@ export function CelebrityEditor({ id, selfId, isAdmin }: { id: string; selfId: s
}
async function remove() {
if (!c || !window.confirm(`Biztosan törlöd: ${c.name}? A képlet, a portré és a fotó is törlődik.`)) return;
if (!c) return;
const ok = await confirmDialog({
title: `Törlöd: ${c.name}?`,
text: "A képlet, a portré és a fotó is törlődik.",
confirm: "Törlés",
danger: true,
});
if (!ok) return;
try {
await api(url, { method: "DELETE" });
router.push("/admin/hires-emberek");
@@ -190,7 +198,7 @@ function PhotoSection({
}
async function removePhoto() {
if (!window.confirm("Törlöd a fotót?")) return;
if (!(await confirmDialog({ title: "Törlöd a fotót?", confirm: "Törlés", danger: true }))) return;
try {
onChange(await api<AdminCelebrity>(`${url}/photo`, { method: "DELETE" }));
} catch (e) {
@@ -6,6 +6,7 @@ import { usePackages } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { AdminInvitation, InvitationResult } from "@/lib/types";
import { confirmDialog, copyDialog } from "@/components/Dialogs";
const MAX_MESSAGE = 300;
@@ -47,7 +48,11 @@ function CopyLink({ url }: { url: string }) {
await navigator.clipboard.writeText(url);
setCopied(true);
} catch {
window.prompt("A meghívólink:", url);
await copyDialog({
title: "A meghívólink",
text: "A böngésző nem engedte a vágólapra másolni: jelöld ki, és másold ki innen.",
value: url,
});
}
}}
>
@@ -325,7 +330,16 @@ function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitatio
const [url, setUrl] = useState<string | null>(null);
async function act(kind: "resend" | "revoke") {
if (kind === "revoke" && !window.confirm(`Visszavonod a meghívót (${i.email})?`)) return;
if (
kind === "revoke" &&
!(await confirmDialog({
title: "Visszavonod a meghívót?",
text: `${i.email}: a link ezután nem fog működni.`,
confirm: "Visszavonás",
danger: true,
}))
)
return;
setBusy(true);
setNote(null);
try {
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { Package, PromoCode } from "@/lib/types";
import { confirmDialog } from "@/components/Dialogs";
const PAGE = 100;
@@ -168,7 +169,13 @@ function CodeList({ packages }: { packages: Package[] }) {
}, [q]);
async function revoke(c: PromoCode) {
if (!window.confirm(`Visszavonod a(z) ${c.code} kódot? Utána nem váltható be.`)) return;
const ok = await confirmDialog({
title: `Visszavonod a(z) ${c.code} kódot?`,
text: "Utána nem váltható be.",
confirm: "Visszavonás",
danger: true,
});
if (!ok) return;
try {
await api(`/admin/promo-codes/${c.id}/revoke`, { body: {} });
load(0);
@@ -0,0 +1,7 @@
// The version this frontend runs (the commit it was built from), for the
// pages' new-version notice (VersionWatcher). null in development.
export const dynamic = "force-dynamic";
export function GET() {
return Response.json({ version: process.env.APP_VERSION || null }, { headers: { "cache-control": "no-store" } });
}
+3
View File
@@ -192,6 +192,9 @@ export default async function TermsPage() {
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.
A hozzászólásokhoz naponta legfeljebb öt fotót tölthetsz fel. Csak olyan képet, amelyhez jogod van, amelyen
más nem ismerhető fel a hozzájárulása nélkül, és amely nem sértő vagy szexuális tartalmú; a moderátorok a nem
odaillőt eltávolítják.
</p>
<h3>8.4. Privát üzenetek</h3>
+73 -1
View File
@@ -92,7 +92,8 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
/* 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));
/* One row, as many equal columns as items. */
display: grid; grid-auto-flow: column; grid-auto-columns: 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);
@@ -786,3 +787,74 @@ a.fh-online-item:hover { color: var(--gold); }
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);
}
/* --- thread cards with the start of the opening post --- */
.ft-row { align-items: flex-start; }
.ft-tags { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; font-size: 13px; color: var(--ink-2); }
.ft-topic { display: inline-flex; align-items: center; gap: 5px; }
.ft-topic .topic-icon { width: 14px; height: 14px; }
.ft-lock { width: 11px; height: 11px; fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; }
.ft-row .ft-excerpt { font-size: 14.5px; line-height: 1.5; -webkit-line-clamp: 3; }
.ft-meta { flex-wrap: wrap; font-size: 13px; }
.ft-who { color: var(--ink); font-weight: 500; }
.ft-m-new { margin-left: auto; }
.ft-side { display: none; }
@media (min-width: 760px) {
.ft-row { display: grid; grid-template-columns: minmax(0, 1fr) 140px; gap: 0 24px; padding: 16px 20px; align-items: center; }
.ft-row .ft-excerpt { font-size: 15px; -webkit-line-clamp: 2; }
.ft-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; font-size: 15px; color: var(--ink); }
.ft-side .hint { font-size: 13px; }
.ft-side strong { font-weight: 600; }
}
/* --- photos in posts --- */
.fphoto-btn { display: inline-flex; align-items: center; gap: 6px; }
.fphoto-btn svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.fphoto-picked { list-style: none; margin: 4px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px; }
.fnew-paper .fphoto-picked { padding: 0 18px 10px; }
.fphoto-chip { position: relative; width: 64px; height: 64px; border-radius: 10px; overflow: hidden; background: var(--f-tint); }
.fphoto-chip img { width: 100%; height: 100%; object-fit: cover; display: block; }
.fphoto-busy img { opacity: 0.45; }
.fphoto-remove {
position: absolute; top: 3px; right: 3px; width: 22px; height: 22px; display: grid; place-items: center; padding: 0;
border: 0; border-radius: 999px; background: rgba(10, 14, 24, 0.7); color: #fff; font-size: 15px; line-height: 1; cursor: pointer;
}
.fphoto-spinner {
position: absolute; inset: 0; margin: auto; width: 22px; height: 22px; border-radius: 999px;
border: 2px solid rgba(255, 255, 255, 0.5); border-top-color: var(--gold); animation: fphoto-spin 0.8s linear infinite;
}
@keyframes fphoto-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .fphoto-spinner { animation: none; } }
.fnew-foot-left { display: inline-flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.fnew-photo-error { margin: 0 18px 10px; }
/* One row of square previews, a fixed height; more scroll sideways. */
.fpics { display: flex; gap: 8px; margin-top: 10px; overflow-x: auto; scroll-snap-type: x proximity; padding-bottom: 2px; }
.fpic {
flex: none; width: 112px; height: 112px; padding: 0; border: 0; border-radius: 12px; overflow: hidden;
background: var(--f-tint); cursor: zoom-in; scroll-snap-align: start;
}
.fpic img { display: block; width: 100%; height: 100%; object-fit: cover; transition: transform 0.2s; }
.fpic:hover img { transform: scale(1.04); }
@media (min-width: 760px) { .fpic { width: 136px; height: 136px; } }
/* The viewer. */
dialog.flight {
width: 100vw; height: 100dvh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0;
background: rgba(5, 8, 16, 0.95); color: #fff; overflow: hidden;
}
dialog.flight::backdrop { background: transparent; }
.flight-figure { margin: 0; width: 100%; height: 100%; display: grid; place-items: center; }
.flight-img { max-width: 94vw; max-height: 86dvh; width: auto; height: auto; object-fit: contain; border-radius: 6px; user-select: none; }
.flight-btn {
position: absolute; display: grid; place-items: center; width: 48px; height: 48px; padding: 0; border: 0;
border-radius: 999px; background: rgba(255, 255, 255, 0.12); color: #fff; font-size: 30px; line-height: 1; cursor: pointer;
}
.flight-btn:hover, .flight-btn:focus-visible { background: rgba(255, 255, 255, 0.24); }
.flight-close { top: calc(14px + env(safe-area-inset-top)); right: 14px; font-size: 26px; }
.flight-prev { left: 12px; top: 50%; transform: translateY(-50%); }
.flight-next { right: 12px; top: 50%; transform: translateY(-50%); }
.flight-count { position: absolute; bottom: calc(18px + env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); font-size: 14px; opacity: 0.8; }
/* The red button of a question window keeps its colour on hover in the light theme. */
.forum[data-theme="light"] .btn-danger-solid:hover { background: #a93226; border-color: #a93226; color: #fff; }
@@ -7,6 +7,7 @@ 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";
import { askDialog } from "@/components/Dialogs";
const STATUS: Record<string, string> = { resolved: "Lezárva", dismissed: "Alaptalan" };
@@ -31,11 +32,18 @@ export function ReportsList({ initial }: { initial: ReportEntry[] }) {
}
}
function removePost(r: ReportEntry) {
async 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;
const reason = await askDialog({
title: "Eltávolítod a hozzászólást?",
text: "Az indoklás a hozzászólás helyén látszik.",
label: "Miért távolítod el?",
required: true,
confirm: "Eltávolítás",
danger: true,
});
if (!reason) return;
void act(r, () => api(`/forum/posts/${id}`, { method: "DELETE", body: { reason } }));
}
@@ -7,6 +7,7 @@ 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";
import { confirmDialog } from "@/components/Dialogs";
const VISIBILITY: Record<string, string> = {
public: "Nyilvános (a keresők is látják)",
@@ -122,10 +123,14 @@ export function TopicsAdmin({
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")
}
onClick={async () => {
const ok = await confirmDialog({
title: `Eltávolítod ${r.member?.nickname ?? "a tagot"} a(z) „${r.topic.name}” témából?`,
confirm: "Eltávolítás",
danger: true,
});
if (ok) decide(r, "remove");
}}
>
Eltávolítom
</button>
@@ -151,13 +156,17 @@ export function TopicsAdmin({
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 } }))
}
onClick={async () => {
const ok =
t.archived ||
(await confirmDialog({
title: `Archiválod a(z) „${t.name}” témát?`,
text: "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.",
confirm: "Archiválás",
}));
if (ok)
act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { archived: !t.archived } }));
}}
>
{t.archived ? "Visszaállítás" : "Archiválás"}
</button>
+41 -4
View File
@@ -8,7 +8,7 @@ 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 { type ForumHome, type ThreadCard, 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";
@@ -61,10 +61,16 @@ function SkyCard({ sky }: { sky: SkyNow }) {
);
}
export default async function ForumHomePage() {
const [home, sky] = await Promise.all([forumGet<ForumHome>("/v1/forum/home"), loadSky()]);
export default async function ForumHomePage({ searchParams }: { searchParams: Promise<{ oldal?: string }> }) {
const page = Math.max(1, Number((await searchParams).oldal) || 1);
const [home, sky, latest] = await Promise.all([
forumGet<ForumHome>("/v1/forum/home"),
loadSky(),
forumGet<{ threads: ThreadCard[]; has_more: boolean }>(`/v1/forum/latest?page=${page}`),
]);
if (!home.ok) notFound();
const { viewer, replies, waiting, topics, unanswered, hot } = home.data;
const pinned = home.data.pinned ?? [];
return (
<div className="fh fh-home">
@@ -77,7 +83,8 @@ export default async function ForumHomePage() {
á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.
A beszélgetések többségét belépés nélkül is elolvashatod. Ha hozzászólnál, vagy az „Ami a szívemen van”
témába is benéznél, lépj be.
</p>
<Link href="/belepes?vissza=/forum" className="btn btn-primary">
Belépés
@@ -135,6 +142,17 @@ export default async function ForumHomePage() {
</section>
)}
{pinned.length > 0 && (
<section className="fh-section o-6" aria-labelledby="fh-pinned">
<div className="fh-section-head">
<h2 id="fh-pinned">Kitűzve</h2>
</div>
<div className="fh-card fh-flush">
<ThreadList threads={pinned} />
</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>
@@ -234,6 +252,25 @@ export default async function ForumHomePage() {
</details>
)}
</section>
{latest.ok && (latest.data.threads.length > 0 || page > 1) && (
<section className="fh-section o-6" id="legutobbi" aria-labelledby="fh-latest">
<div className="fh-section-head">
<h2 id="fh-latest">Legutóbbi szálak</h2>
<span className="hint">a legfrissebb beszélgetések elöl</span>
</div>
<div className="fh-card fh-flush">
<ThreadList threads={latest.data.threads} />
</div>
{(page > 1 || latest.data.has_more) && (
<nav className="forum-pager" aria-label="Lapozás">
{page > 1 ? <Link href={`/forum?oldal=${page - 1}#legutobbi`}>‹ Újabbak</Link> : <span />}
<span className="hint">{page}. oldal</span>
{latest.data.has_more ? <Link href={`/forum?oldal=${page + 1}#legutobbi`}>Régebbiek ›</Link> : <span />}
</nav>
)}
</section>
)}
</div>
<aside className="fh-col fh-col-side" aria-label="Oldalsáv">
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { confirmDialog } from "@/components/Dialogs";
const DURATIONS: { hours: number | null; label: string }[] = [
{ hours: 3, label: "3 óra" },
@@ -45,10 +46,15 @@ export function BanPanel({ nickname, banned, ownPicture }: { nickname: string; b
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" }))
}
onClick={async () => {
const ok = await confirmDialog({
title: "Visszaállítod a kezdő avatart?",
text: "A feltöltött kép törlődik.",
confirm: "Visszaállítás",
danger: true,
});
if (ok) act(() => api(`/forum/members/${encodeURIComponent(nickname)}/avatar-reset`, { method: "POST" }));
}}
>
Saját kép eltávolítása
</button>
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { confirmDialog } from "@/components/Dialogs";
/** The admin's switch for the "Alapító tag" badge (e.g. off for a test account; the place goes to the next newcomer). */
export function FounderToggle({ nickname, founder }: { nickname: string; founder: boolean }) {
@@ -19,7 +20,12 @@ export function FounderToggle({ nickname, founder }: { nickname: string; founder
onClick={async () => {
if (
founder &&
!window.confirm(`Elveszed ${nickname} Alapító tag jelvényét? A helyét a következő új tag kapja.`)
!(await confirmDialog({
title: `Elveszed ${nickname} Alapító tag jelvényét?`,
text: "A helyét a következő új tag kapja.",
confirm: "Jelvény elvétele",
danger: true,
}))
)
return;
setBusy(true);
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { confirmDialog } from "@/components/Dialogs";
/** "Némítás" on a member's profile: their threads, posts and notices step out of the viewer's way. */
export function MuteButton({ nickname, muted }: { nickname: string; muted: boolean }) {
@@ -19,9 +20,11 @@ export function MuteButton({ nickname, muted }: { nickname: string; muted: boole
onClick={async () => {
if (
!muted &&
!window.confirm(
`Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud.`,
)
!(await confirmDialog({
title: `Elnémítod ${nickname} tagot?`,
text: "A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud.",
confirm: "Elnémítás",
}))
)
return;
setBusy(true);
@@ -4,11 +4,13 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { PhotoButton, PickedPhotos } from "@/components/forum/Photos";
import { ShareCard } from "@/components/forum/ShareCard";
import { TopicIcon } from "@/components/forum/TopicIcon";
import { api, errorText } from "@/lib/api";
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
import { type ForumTopic, type ShareCardData, threadHref } from "@/lib/forum";
import { usePhotoUploads } from "@/lib/photos";
type Intent = "listen" | "advice" | "";
@@ -75,6 +77,7 @@ export function NewThreadForm({
const [body, setBody] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const picked = usePhotoUploads();
// A listening topic: hearing or opinions, no small talk.
const choices = INTENT_CHOICES.filter((c) => !listening || c.value !== "");
const intentHint = choices.find((c) => c.value === intent)?.hint;
@@ -87,7 +90,7 @@ export function NewThreadForm({
}
async function submit() {
if (busy || !title.trim() || !body.trim() || !topic) return;
if (busy || picked.busy || !title.trim() || !body.trim() || !topic) return;
setBusy(true);
setError(null);
try {
@@ -98,6 +101,7 @@ export function NewThreadForm({
body: convertEmoticons(body, body.length, true).text,
intent: intent || null,
share: share?.slug ?? null,
photos: picked.ids,
},
});
router.push(threadHref(created));
@@ -212,14 +216,23 @@ export function NewThreadForm({
}
}}
/>
<PickedPhotos items={picked.items} onRemove={picked.remove} />
{picked.error && (
<p className="msg msg-error fnew-photo-error" role="alert">
{picked.error}
</p>
)}
<div className="fnew-foot">
<span className="hint">
Kérjük, tartsd be a <Link href="/aszf#forum">házirendet</Link>.
<span className="fnew-foot-left">
<PhotoButton onFiles={(files) => void picked.add(files)} disabled={picked.full} />
<span className="hint">
Kérjük, tartsd be a <Link href="/aszf#forum">házirendet</Link>.
</span>
</span>
<button
type="button"
className="btn btn-primary"
disabled={busy || !title.trim() || !body.trim() || !topic}
disabled={busy || picked.busy || !title.trim() || !body.trim() || !topic}
onClick={() => void submit()}
>
{busy ? "Küldés…" : "Szál indítása"}
@@ -8,6 +8,7 @@ import { AuthorLine } from "@/components/forum/AuthorLine";
import { Avatar } from "@/components/forum/Avatar";
import { api, errorText } from "@/lib/api";
import { type ConversationItem, ago } from "@/lib/forum";
import { confirmDialog } from "@/components/Dialogs";
export function Conversations({ initial }: { initial: ConversationItem[] }) {
const router = useRouter();
@@ -86,7 +87,15 @@ export function Conversations({ initial }: { initial: ConversationItem[] }) {
type="button"
className="btn btn-ghost btn-sm"
disabled={busy === c.id}
onClick={() => window.confirm("Letiltod? Nem küldhet neked több kérést.") && answer(c, "block")}
onClick={async () => {
const ok = await confirmDialog({
title: `Letiltod ${c.other?.nickname ?? "ezt a tagot"}?`,
text: "Nem küldhet neked több kérést.",
confirm: "Letiltás",
danger: true,
});
if (ok) answer(c, "block");
}}
>
Letiltom
</button>
@@ -13,6 +13,7 @@ import { ReportButton } from "@/components/forum/ReportButton";
import { TypingLine, useTypingSender, useTypingWatch } from "@/components/forum/typing";
import { api, errorText } from "@/lib/api";
import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum";
import { confirmDialog } from "@/components/Dialogs";
/** A safety net: how often an open conversation looks for new messages anyway. */
const POLL_MS = 30_000;
@@ -140,7 +141,15 @@ export function Chat({ initial }: { initial: ConversationPage }) {
<button
type="button"
className="danger"
onClick={() => window.confirm(`Letiltod ${other} tagot? Nem írhat neked többet.`) && answer("block")}
onClick={async () => {
const ok = await confirmDialog({
title: `Letiltod ${other} tagot?`,
text: "Nem írhat neked többet.",
confirm: "Letiltás",
danger: true,
});
if (ok) answer("block");
}}
>
Letiltás
</button>
+39
View File
@@ -538,6 +538,20 @@ dialog.modal::backdrop { background: rgba(5, 8, 16, 0.72); backdrop-filter: blur
.balance-grid dt { font-size: 12px; color: var(--muted); }
.balance-grid dd { margin: 0; font-size: 18px; color: var(--ink); }
@media (max-width: 480px) { .modal-inner { padding: 18px 16px 20px; } }
/* A question in a small window (Dialogs.tsx), instead of the browser's own confirm() and prompt(). */
dialog.modal-ask { width: min(440px, calc(100vw - 32px)); }
.modal-ask .modal-inner { gap: 14px; }
.modal-ask-title { font-size: 22px; line-height: 1.2; overflow-wrap: anywhere; }
.modal-ask-text { display: flex; flex-direction: column; gap: 8px; color: var(--ink-2); font-size: 15px; line-height: 1.5; overflow-wrap: anywhere; }
.modal-ask-text p { margin: 0; }
.modal-ask-field { display: flex; flex-direction: column; gap: 6px; font-size: 14px; font-weight: 500; color: var(--ink-2); }
.modal-ask-field textarea { min-height: 88px; resize: vertical; font-weight: 400; }
.modal-ask-actions { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; margin-top: 4px; }
@media (max-width: 480px) { .modal-ask-actions .btn { flex: 1; } }
.btn-danger-solid { background: #c0392b; border-color: #c0392b; color: #fff; font-weight: 600; }
.btn-danger-solid:hover { background: #a93226; border-color: #a93226; color: #fff; }
/* While typing on a phone: in the part of the screen above the keyboard (KeyboardSafe). */
.kb-open dialog.modal-ask { margin: calc(var(--vv-top, 0px) + 12px) auto auto; max-height: calc(var(--vv-height, 100dvh) - 24px); }
.prompt-kind { display: flex; flex-direction: column; gap: 20px; }
.prompt-kind-head { display: flex; gap: 16px 24px; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; }
.prompt-kind-head > p { flex: 1 1 360px; margin: 0; }
@@ -1814,3 +1828,28 @@ span.tarot-fan-card { cursor: default; }
}
.pw-eye:hover, .pw-eye:focus-visible { color: var(--gold); }
.pw-eye svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
/* The home page: analyses written for each chart, not template texts. */
.lp-personal {
display: flex; gap: 14px; align-items: flex-start; max-width: 560px; padding: 16px 18px;
border: 1px solid rgba(217, 180, 106, 0.35); border-radius: 14px; background: rgba(217, 180, 106, 0.07);
}
.lp-personal-icon { width: 30px; height: 30px; flex: none; margin-top: 2px; fill: none; stroke: var(--gold); stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
.lp-personal-title { display: block; color: var(--ink); font-size: 17px; font-weight: 600; margin-bottom: 4px; }
.lp-personal-text { margin: 0; color: var(--ink-2); font-size: 15.5px; line-height: 1.6; }
/* Phones: the hero's two buttons side by side (each takes half the row). */
@media (max-width: 479px) {
.lp-hero .lp-actions { flex-wrap: nowrap; gap: 10px; }
.lp-hero .lp-actions .lp-btn { flex: 1 1 auto; min-width: 0; padding: 0 14px; font-size: 15px; text-align: center; }
}
/* "Frissült az oldal": a new version is out (VersionWatcher). */
.update-note {
position: fixed; top: calc(12px + env(safe-area-inset-top)); left: 50%; transform: translateX(-50%); z-index: 80;
display: flex; align-items: center; gap: 12px; width: max-content; max-width: calc(100vw - 24px); padding: 10px 12px 10px 16px;
background: var(--panel, #121a2e); color: var(--ink, #ece6d8); border: 1px solid var(--gold); border-radius: 14px;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35); font-size: 15px;
}
.update-note-later { border: 0; background: none; color: var(--ink-2, #c9cfdc); font: inherit; font-size: 14px; cursor: pointer; padding: 6px; }
.update-note-later:hover { color: var(--gold); }
@media (max-width: 479px) { .update-note { flex-wrap: wrap; justify-content: center; text-align: center; } }
+4
View File
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";
import { Cormorant_Garamond, Inter } from "next/font/google";
import { Suspense } from "react";
import { DialogHost } from "@/components/Dialogs";
import { KeyboardSafe } from "@/components/KeyboardSafe";
import { NightSky } from "@/components/NightSky";
import { NpsBanner } from "@/components/NpsBanner";
@@ -9,6 +10,7 @@ import { PaymentReturn } from "@/components/PaymentReturn";
import { SiteFooter } from "@/components/PublicFooter";
import { SiteHeader } from "@/components/SiteHeader";
import { ValidationMessages } from "@/components/ValidationMessages";
import { VersionWatcher } from "@/components/VersionWatcher";
import { getMe } from "@/lib/server";
import { loadSky } from "@/lib/sky";
import { siteUrl } from "@/lib/share";
@@ -44,6 +46,8 @@ export default async function RootLayout({ children }: { children: React.ReactNo
<body>
<NightSky />
<KeyboardSafe />
<VersionWatcher />
<DialogHost />
<ValidationMessages />
{me && <SiteHeader me={me} sky={sky} />}
{children}
+6 -3
View File
@@ -90,7 +90,7 @@ const DATA: [string, string, string][] = [
"Performance of the contract",
],
[
"Your forum threads and posts, your reactions and “Ez segített” (it helped) marks, your points and rank; whom you mentioned (@nickname); what you have read, the threads you follow, and the members you muted",
"Your forum threads and posts, your reactions and “Ez segített” (it helped) marks, your points and rank; the photos you uploaded with your posts; whom you mentioned (@nickname); what you have read, the threads you follow, and the members you muted",
"Running the forum, the ranks, showing what is new",
"Performance of the contract",
],
@@ -203,7 +203,9 @@ export default async function PrivacyPolicyPage() {
yearly forecast or a comparison to a question, only logged-in members see it: the drawing with degrees and
houses, the short summary or the forecast text, without names, birth date, time or place. A practised
astrologer can roughly work out the birth date and time from the degrees, and a forecast's first day is the
birthday. You can take it off at any time, and deleting the question ends the link. If a post has a YouTube
birthday. You can take it off at any time, and deleting the question ends the link. The photos you upload
with posts are made smaller by your browser, our server removes their hidden data (such as the place), and
whoever can read the thread can see them. If a post has a YouTube
link, our server fetches the video's title and picture and we show them from our own server: reading the
forum sends YouTube nothing about you. If you play the video on the forum, the player loads from YouTube's
(Google's) servers (youtube-nocookie.com), which see your IP address and what you play; on a phone, opening
@@ -347,7 +349,8 @@ export default async function PrivacyPolicyPage() {
</li>
<li>Data needed for invoicing: for the period required by accounting law (8 years).</li>
<li>
Your forum profile (with your own picture), private conversations, reactions, followed threads and
Your forum profile (with your own picture), the photos of your posts (at most a year after a post is
removed), private conversations, reactions, followed threads and
restricted topic memberships: until you delete your account; a declined request is deleted at once.
When you delete it, your private conversations are deleted for the other person too. Your threads and
posts stay, shown as “Törölt tag” (deleted member), so that the conversations remain readable; to have them
@@ -0,0 +1,220 @@
"use client";
import { useEffect, useId, useRef, useState } from "react";
import { createPortal } from "react-dom";
/**
* Small question windows in the site's own look, instead of the browser's
* grey confirm() and prompt(): `confirmDialog` (yes or no), `askDialog` (a
* short text, e.g. a moderator's reason) and `copyDialog` (a link to copy by
* hand). Each returns a promise; the one `DialogHost` (root layout) shows
* them one after the other. In the forum the window is placed inside the
* forum's part of the page, so it takes the forum's light or dark colours.
*/
interface Question {
title: string;
/** A line or two under the title: what will happen. */
text?: React.ReactNode;
/** The button that goes ahead, named for what it does ("Törlés", "Letiltás"). */
confirm?: string;
cancel?: string;
/** Something that removes or ends something: the button is red. */
danger?: boolean;
}
export interface AskQuestion extends Question {
/** The label of the text box. */
label: string;
placeholder?: string;
maxLength?: number;
/** The button waits until something is typed. */
required?: boolean;
}
export interface CopyQuestion {
title: string;
text?: React.ReactNode;
value: string;
}
type Request = { id: number } & (
| { kind: "confirm"; question: Question; resolve: (ok: boolean) => void }
| { kind: "ask"; question: AskQuestion; resolve: (text: string | null) => void }
| { kind: "copy"; question: CopyQuestion; resolve: () => void }
);
type NewRequest = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
let enqueue: ((request: NewRequest) => void) | null = null;
/** Yes or no: true when the person goes ahead. */
export function confirmDialog(question: Question): Promise<boolean> {
return new Promise((resolve) => {
// The host is always on the page; the browser's own window only as a last resort.
if (!enqueue) return resolve(window.confirm(question.title));
enqueue({ kind: "confirm", question, resolve });
});
}
/** A short text (trimmed), or null when the person steps back. */
export function askDialog(question: AskQuestion): Promise<string | null> {
return new Promise((resolve) => {
if (!enqueue) return resolve(window.prompt(question.label)?.trim() || null);
enqueue({ kind: "ask", question, resolve });
});
}
/** Shows a value to copy by hand (when the clipboard is not allowed). */
export function copyDialog(question: CopyQuestion): Promise<void> {
return new Promise((resolve) => {
if (!enqueue) {
window.prompt(question.title, question.value);
return resolve();
}
enqueue({ kind: "copy", question, resolve });
});
}
export function DialogHost() {
const [queue, setQueue] = useState<Request[]>([]);
const counter = useRef(0);
useEffect(() => {
enqueue = (request) => setQueue((q) => [...q, { ...request, id: ++counter.current } as Request]);
return () => {
enqueue = null;
};
}, []);
const current = queue[0];
if (!current) return null;
const place = document.querySelector<HTMLElement>(".forum") ?? document.body;
return createPortal(
<QuestionWindow key={current.id} request={current} onDone={() => setQueue((q) => q.slice(1))} />,
place,
);
}
function QuestionWindow({ request, onDone }: { request: Request; onDone: () => void }) {
const ref = useRef<HTMLDialogElement>(null);
const first = useRef<HTMLButtonElement | HTMLTextAreaElement | HTMLInputElement | null>(null);
const titleId = useId();
const textId = useId();
const [value, setValue] = useState("");
const answered = useRef(false);
const pressedBackdrop = useRef(false);
const { question } = request;
const ask = request.kind === "ask" ? request.question : null;
const waiting = ask?.required === true && value.trim() === "";
const finish = (ok: boolean) => {
if (answered.current) return;
answered.current = true;
if (request.kind === "confirm") request.resolve(ok);
else if (request.kind === "ask") request.resolve(ok && value.trim() ? value.trim() : null);
else request.resolve();
onDone();
};
const goAhead = () => {
if (!waiting) finish(true);
};
useEffect(() => {
const dialog = ref.current;
if (dialog && !dialog.open) dialog.showModal();
// A text box, or for something that removes a thing the safe button, has the focus.
first.current?.focus();
if (first.current instanceof HTMLInputElement) first.current.select();
}, []);
const danger = request.kind !== "copy" && request.question.danger;
const confirmLabel = request.kind === "copy" ? "Bezárás" : (request.question.confirm ?? "Rendben");
return (
<dialog
ref={ref}
className="modal modal-ask"
aria-labelledby={titleId}
aria-describedby={question.text ? textId : undefined}
// Escape, or the window closing in any other way: stepping back.
onClose={() => finish(false)}
onPointerDown={(e) => {
pressedBackdrop.current = e.target === ref.current;
}}
onClick={(e) => {
const onBackdrop = pressedBackdrop.current && e.target === ref.current;
pressedBackdrop.current = false;
if (onBackdrop) finish(false);
}}
>
<div className="modal-inner">
<h2 id={titleId} className="modal-ask-title">
{question.title}
</h2>
{question.text && (
<div id={textId} className="modal-ask-text">
{question.text}
</div>
)}
{ask && (
<label className="modal-ask-field">
<span>{ask.label}</span>
<textarea
ref={(el) => {
first.current = el;
}}
className="inp"
rows={3}
value={value}
maxLength={ask.maxLength ?? 500}
placeholder={ask.placeholder}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
goAhead();
}
}}
/>
</label>
)}
{request.kind === "copy" && (
<input
ref={(el) => {
first.current = el;
}}
className="inp"
readOnly
value={request.question.value}
onFocus={(e) => e.target.select()}
aria-label={request.question.title}
/>
)}
<div className="modal-ask-actions">
{request.kind !== "copy" && (
<button
ref={(el) => {
if (danger && !ask) first.current = el;
}}
type="button"
className="btn"
onClick={() => finish(false)}
>
{request.question.cancel ?? "Mégse"}
</button>
)}
<button
ref={(el) => {
if (!danger && !ask && request.kind !== "copy") first.current = el;
}}
type="button"
className={danger ? "btn btn-danger-solid" : "btn btn-primary"}
disabled={waiting}
onClick={goAhead}
>
{confirmLabel}
</button>
</div>
</div>
</dialog>
);
}
@@ -30,6 +30,11 @@ function typedInto(el: Element | null): el is HTMLElement {
* into that part. A text box gets `autocomplete="off"` unless it says
* otherwise, so iOS Safari does not lay its AutoFill bar (passwords, cards,
* addresses) over it.
*
* iOS sometimes leaves the page scrolled past its end when the keyboard goes
* away without the usual tap (a photo picker opening over it, for one): the
* fixed bottom menu then floats mid-screen above an empty strip. When the
* keyboard is gone, a one-pixel scroll puts the page back in place.
*/
export function KeyboardSafe() {
useEffect(() => {
@@ -39,6 +44,7 @@ export function KeyboardSafe() {
let timer: number | undefined;
let again: number | undefined;
let closing: number | undefined;
const settling: number[] = [];
const measure = () => {
root.style.setProperty("--vv-top", `${vv ? vv.offsetTop : 0}px`);
@@ -63,6 +69,21 @@ export function KeyboardSafe() {
if (Math.abs(delta) > 2) window.scrollBy({ top: delta, behavior: "instant" });
};
// The visible part has drifted below the page (iOS, keyboard gone): back.
const settle = () => {
if (!vv || root.classList.contains("kb-open")) return;
if (Math.abs(vv.scale - 1) > 0.01 || vv.offsetTop < 2) return;
const end = Math.max(0, document.documentElement.scrollHeight - vv.height);
const top = Math.min(vv.pageTop, end);
window.scrollTo({ top: Math.max(0, top - 1), behavior: "instant" });
requestAnimationFrame(() => window.scrollTo({ top, behavior: "instant" }));
};
// Checked a few times while the keyboard slides down.
const settleSoon = () => {
settling.splice(0).forEach((t) => window.clearTimeout(t));
for (const ms of [120, 450, 900]) settling.push(window.setTimeout(settle, ms));
};
// After the keyboard has slid up (and once more when the browser's own
// scrolling has settled), and whenever the free part changes.
const later = (ms: number) => {
@@ -87,20 +108,34 @@ export function KeyboardSafe() {
// Moving to another field keeps it open.
window.clearTimeout(closing);
closing = window.setTimeout(() => {
if (!typedInto(document.activeElement)) root.classList.remove("kb-open");
if (typedInto(document.activeElement)) return;
root.classList.remove("kb-open");
settleSoon();
}, 150);
};
const onViewport = () => {
if (!root.classList.contains("kb-open")) return;
if (!root.classList.contains("kb-open")) {
settleSoon();
return;
}
measure();
later(150);
};
// Back from a picker (photos) or another app.
const onReturn = () => {
if (document.visibilityState === "visible") settleSoon();
};
document.addEventListener("focusin", onFocusIn);
document.addEventListener("focusout", onFocusOut);
vv?.addEventListener("resize", onViewport);
vv?.addEventListener("scroll", measure);
window.addEventListener("focus", onReturn);
document.addEventListener("visibilitychange", onReturn);
return () => {
settling.forEach((t) => window.clearTimeout(t));
window.removeEventListener("focus", onReturn);
document.removeEventListener("visibilitychange", onReturn);
window.clearTimeout(timer);
window.clearTimeout(again);
window.clearTimeout(closing);
+11 -8
View File
@@ -5,7 +5,8 @@ import { useEffect, useId, useRef } from "react";
/**
* A modal window (the browser's own <dialog>: focus stays inside, Escape
* closes it). Shown while mounted; a click on the dimmed backdrop closes it.
* `canClose`: asked first (e.g. about unsaved input); false keeps it open.
* `canClose`: asked first (e.g. about unsaved input, maybe in a question
* window); false keeps it open.
*/
export function Modal({
title,
@@ -17,7 +18,7 @@ export function Modal({
title: string;
subtitle?: React.ReactNode;
onClose: () => void;
canClose?: () => boolean;
canClose?: () => boolean | Promise<boolean>;
children: React.ReactNode;
}) {
const ref = useRef<HTMLDialogElement>(null);
@@ -26,8 +27,8 @@ export function Modal({
// it (not a text selection dragged out, nor a pick from a select's list that
// hangs over the backdrop).
const pressedBackdrop = useRef(false);
const close = () => {
if (!canClose || canClose()) onClose();
const close = async () => {
if (!canClose || (await canClose())) onClose();
};
// No close() on unmount: that would fire onClose; a removed dialog is gone anyway.
@@ -43,8 +44,10 @@ export function Modal({
aria-labelledby={titleId}
onClose={onClose}
onCancel={(e) => {
// Escape: the dialog would close by itself.
if (canClose && !canClose()) e.preventDefault();
// Escape: the dialog would close by itself; with a question first it waits for the answer.
if (!canClose) return;
e.preventDefault();
void close();
}}
onPointerDown={(e) => {
pressedBackdrop.current = e.target === ref.current;
@@ -52,7 +55,7 @@ export function Modal({
onClick={(e) => {
const onBackdrop = pressedBackdrop.current && e.target === ref.current;
pressedBackdrop.current = false;
if (onBackdrop) close();
if (onBackdrop) void close();
}}
>
<div className="modal-inner">
@@ -61,7 +64,7 @@ export function Modal({
<h2 id={titleId}>{title}</h2>
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
</div>
<button type="button" className="modal-close" onClick={close} aria-label="Bezárás">
<button type="button" className="modal-close" onClick={() => void close()} aria-label="Bezárás">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M6 6l12 12M18 6L6 18" />
</svg>
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { PersonInvite } from "@/lib/types";
import { confirmDialog } from "@/components/Dialogs";
/** The user's "how compatible are we?" invitations: waiting ones (revocable) and accepted ones. */
export function PendingInvites() {
@@ -25,7 +26,13 @@ export function PendingInvites() {
}, [load]);
async function revoke(i: PersonInvite) {
if (!window.confirm(`Visszavonod a meghívót${i.label ? ` (${i.label})` : ""}? A link nem fog működni.`)) return;
const ok = await confirmDialog({
title: "Visszavonod a meghívót?",
text: `${i.label ? `${i.label}: ` : ""}a link ezután nem fog működni.`,
confirm: "Visszavonás",
danger: true,
});
if (!ok) return;
try {
await api(`/invites/${i.id}`, { method: "DELETE" });
await load();
@@ -3,6 +3,7 @@
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { confirmDialog } from "@/components/Dialogs";
interface Share {
id: string;
@@ -83,7 +84,14 @@ export function ShareChart({
}
async function revoke() {
if (!share || !window.confirm("Visszavonod a linket? Aki megkapta, többé nem tudja megnyitni.")) return;
if (!share) return;
const ok = await confirmDialog({
title: "Visszavonod a linket?",
text: "Aki megkapta, többé nem tudja megnyitni.",
confirm: "Visszavonás",
danger: true,
});
if (!ok) return;
setBusy(true);
try {
await api(`/shares/${share.id}`, { method: "DELETE" });
@@ -0,0 +1,89 @@
"use client";
import { useEffect, useState } from "react";
/** How often an open page asks (only while it is in front). */
const EVERY_MS = 5 * 60 * 1000;
/** No key, click or touch for this long counts as idle. */
const IDLE_MS = 2 * 60 * 1000;
/** Typed text that a reload would lose (a reply being written, a form filled in). */
function unsaved(): boolean {
const fields = document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>(
"textarea, input:not([type]), input[type=text], input[type=email], input[type=search], input[type=password]",
);
return Array.from(fields).some(
(f) => !f.readOnly && !f.disabled && f.value.trim() !== "" && f.value !== f.defaultValue,
);
}
/**
* When a new version of the site is out (its /api/version differs from the
* one this page was built from, Next's `data-dpl-id`): an idle page with
* nothing typed in reloads itself; otherwise a small notice offers the reload.
* (A click on a link reloads anyway: Next's skew protection.)
*/
export function VersionWatcher() {
const [fresh, setFresh] = useState(false);
useEffect(() => {
const mine = document.documentElement.dataset.dplId;
if (!mine) return;
let lastInput = Date.now();
let dismissed = false;
const touched = () => {
lastInput = Date.now();
};
const check = async () => {
if (document.visibilityState !== "visible" || dismissed) return;
try {
const res = await fetch("/api/version", { cache: "no-store" });
const { version } = (await res.json()) as { version: string | null };
if (!version || version === mine) return;
const idle = Date.now() - lastInput > IDLE_MS;
if (idle && !unsaved() && !document.querySelector("dialog[open]")) window.location.reload();
else setFresh(true);
} catch {
// Offline or mid-deployment: the next check tries again.
}
};
const timer = window.setInterval(check, EVERY_MS);
const onVisible = () => document.visibilityState === "visible" && void check();
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
window.addEventListener("online", onVisible);
for (const e of ["keydown", "pointerdown", "touchstart"]) window.addEventListener(e, touched, { passive: true });
const later = () => {
dismissed = true;
setFresh(false);
window.setTimeout(() => (dismissed = false), 30 * 60 * 1000);
};
window.addEventListener("version-watcher:later", later);
return () => {
window.clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("focus", onVisible);
window.removeEventListener("online", onVisible);
for (const e of ["keydown", "pointerdown", "touchstart"]) window.removeEventListener(e, touched);
window.removeEventListener("version-watcher:later", later);
};
}, []);
if (!fresh) return null;
return (
<div className="update-note" role="status">
<span>Frissült az oldal: elérhető az új változata.</span>
<button type="button" className="btn btn-primary btn-sm" onClick={() => window.location.reload()}>
Frissítés
</button>
<button
type="button"
className="update-note-later"
aria-label="Később"
onClick={() => window.dispatchEvent(new Event("version-watcher:later"))}
>
Később
</button>
</div>
);
}
@@ -3,10 +3,12 @@
import { useEffect, useRef, useState } from "react";
import { api } from "@/lib/api";
import { usePhotoUploads } from "@/lib/photos";
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
import type { ForumAuthor } from "@/lib/forum";
import { Avatar } from "./Avatar";
import { PhotoButton, PickedPhotos } from "./Photos";
/** "@Ho" right before the caret: what was typed after the "@", and where it starts. */
function mentionAt(text: string, caret: number): { query: string; start: number } | null {
@@ -22,6 +24,7 @@ function mentionAt(text: string, caret: number): { query: string; start: number
* `onTyping`: called on every keystroke (the "… gépel" notice).
* `mentions`: typing "@Ho" offers the members whose nickname starts so.
* `onChange`: the text as it is typed (to keep a draft when the box moves).
* `photos`: a "Fotó" button; the uploaded photos' ids go with the text.
*/
export function Composer({
id,
@@ -35,6 +38,7 @@ export function Composer({
onTyping,
onChange,
mentions = false,
photos = false,
rows = 3,
autoFocus = false,
}: {
@@ -44,17 +48,19 @@ export function Composer({
initial?: string;
submitLabel?: string;
busy: boolean;
onSubmit: (text: string) => Promise<boolean>;
onSubmit: (text: string, photos: string[]) => Promise<boolean>;
onCancel?: () => void;
onTyping?: () => void;
onChange?: (text: string) => void;
mentions?: boolean;
photos?: boolean;
rows?: number;
autoFocus?: boolean;
}) {
const [text, setText] = useState(initial);
const [suggest, setSuggest] = useState<{ query: string; start: number; members: ForumAuthor[] } | null>(null);
const area = useRef<HTMLTextAreaElement>(null);
const picked = usePhotoUploads();
const timer = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
@@ -92,11 +98,12 @@ export function Composer({
}
async function submit() {
if (!text.trim() || busy) return;
if (!text.trim() || busy || picked.busy) return;
const final = convertEmoticons(text, text.length, true).text;
if (await onSubmit(final)) {
if (await onSubmit(final, picked.ids)) {
setText("");
setSuggest(null);
picked.reset();
}
}
@@ -148,7 +155,14 @@ export function Composer({
))}
</div>
)}
{photos && <PickedPhotos items={picked.items} onRemove={picked.remove} />}
{photos && picked.error && (
<p className="msg msg-error" role="alert">
{picked.error}
</p>
)}
<div className="fc-actions">
{photos && <PhotoButton onFiles={(files) => void picked.add(files)} disabled={picked.full} />}
<span className="fc-spacer" />
{onCancel && (
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
@@ -158,7 +172,7 @@ export function Composer({
<button
type="button"
className="btn btn-primary btn-sm"
disabled={busy || !text.trim()}
disabled={busy || picked.busy || !text.trim()}
onClick={() => void submit()}
>
{busy ? "Küldés…" : submitLabel}
@@ -0,0 +1,155 @@
"use client";
import { useEffect, useRef, useState } from "react";
import type { ForumPhoto, PickedPhoto } from "@/lib/photos";
/** "Fotó": picks pictures from the phone or the computer. */
export function PhotoButton({ onFiles, disabled }: { onFiles: (files: FileList) => void; disabled?: boolean }) {
const input = useRef<HTMLInputElement>(null);
return (
<>
<button
type="button"
className="btn btn-ghost btn-sm fphoto-btn"
disabled={disabled}
onClick={() => input.current?.click()}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="3" y="5" width="18" height="15" rx="2.5" />
<circle cx="9" cy="10.5" r="2" />
<path d="M21 16l-5-5-8 8" />
</svg>
Fotó
</button>
<input
ref={input}
type="file"
accept="image/*"
multiple
className="sr-only"
tabIndex={-1}
onChange={(e) => {
if (e.target.files?.length) onFiles(e.target.files);
e.target.value = "";
}}
/>
</>
);
}
/** The picked photos before sending: small squares, each removable. */
export function PickedPhotos({ items, onRemove }: { items: PickedPhoto[]; onRemove: (key: string) => void }) {
if (items.length === 0) return null;
return (
<ul className="fphoto-picked">
{items.map((p) => (
<li key={p.key} className={p.id ? "fphoto-chip" : "fphoto-chip fphoto-busy"}>
{/* A local preview or the forum's square preview. */}
<img src={p.preview} alt="" />
{p.id ? (
<button
type="button"
className="fphoto-remove"
aria-label="Fotó eltávolítása"
onClick={() => onRemove(p.key)}
>
×
</button>
) : (
<span className="fphoto-spinner" aria-label="Feltöltés…" />
)}
</li>
))}
</ul>
);
}
/** A post's photos: one row of square previews; a click opens the viewer. */
export function PostPhotos({ photos }: { photos: ForumPhoto[] }) {
const [open, setOpen] = useState<number | null>(null);
return (
<>
<div className="fpics">
{photos.map((p, i) => (
<button
key={p.id}
type="button"
className="fpic"
onClick={() => setOpen(i)}
aria-label={photos.length > 1 ? `${i + 1}. fotó megnyitása` : "Fotó megnyitása"}
>
<img src={p.thumb} alt="" width={360} height={360} loading="lazy" />
</button>
))}
</div>
{open !== null && <Lightbox photos={photos} start={open} onClose={() => setOpen(null)} />}
</>
);
}
/** The photo viewer: one picture at a time; arrows, swiping and the keyboard turn the pages. */
function Lightbox({ photos, start, onClose }: { photos: ForumPhoto[]; start: number; onClose: () => void }) {
const [at, setAt] = useState(start);
const dialog = useRef<HTMLDialogElement>(null);
const touch = useRef<number | null>(null);
const many = photos.length > 1;
const go = (step: number) => setAt((i) => (i + step + photos.length) % photos.length);
useEffect(() => {
const d = dialog.current;
if (d && !d.open) d.showModal();
}, []);
// The neighbours load ahead.
useEffect(() => {
for (const step of [1, -1]) {
const next = photos[(at + step + photos.length) % photos.length];
if (next) new Image().src = next.url;
}
}, [at, photos]);
const photo = photos[at];
return (
<dialog
ref={dialog}
className="flight"
aria-label="Fotók"
onClose={onClose}
onKeyDown={(e) => {
if (e.key === "ArrowRight" && many) go(1);
if (e.key === "ArrowLeft" && many) go(-1);
}}
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
onPointerDown={(e) => (touch.current = e.clientX)}
onPointerUp={(e) => {
if (touch.current === null || !many) return;
const dx = e.clientX - touch.current;
touch.current = null;
if (Math.abs(dx) > 50) go(dx < 0 ? 1 : -1);
}}
>
<figure className="flight-figure" onClick={(e) => e.target === e.currentTarget && onClose()}>
{/* The photo itself (already made small by the browser that uploaded it). */}
<img src={photo.url} alt="" className="flight-img" width={photo.width} height={photo.height} />
</figure>
<button type="button" className="flight-btn flight-close" aria-label="Bezárás" onClick={onClose}>
×
</button>
{many && (
<>
<button type="button" className="flight-btn flight-prev" aria-label="Előző fotó" onClick={() => go(-1)}>
‹
</button>
<button type="button" className="flight-btn flight-next" aria-label="Következő fotó" onClick={() => go(1)}>
›
</button>
<span className="flight-count">
{at + 1} / {photos.length}
</span>
</>
)}
</dialog>
);
}
@@ -3,6 +3,7 @@ import Link from "next/link";
import { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum";
import { Avatar } from "./Avatar";
import { TopicIcon } from "./TopicIcon";
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
if (!intent) return null;
@@ -10,53 +11,80 @@ export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent
return <span className={`ft-intent ft-intent-${intent}`}>{text}</span>;
}
function UnreadPill({ n }: { n: number | null }) {
function UnreadPill({ n, onlyNew = false }: { n: number | null; onlyNew?: boolean }) {
if (n === null) return null;
if (n === 0) return <span className="ft-read">olvasva</span>;
if (n === 0) return onlyNew ? null : <span className="ft-read">olvasva</span>;
return <span className="ft-new">{n > 99 ? "99+" : n} új</span>;
}
/** Threads in a list: title, topic, replies, the starter, what is new. */
/**
* Threads in a list. Each card: the topic (with a lock for members-only and
* restricted ones), pinned and the wish, the title, the start of the opening
* post (two lines on a computer, three on a phone), the starter; replies,
* the last activity and what is new on the right on a computer, in the
* bottom line on a phone.
*/
export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) {
return (
<ul className="ft-list">
{threads.map((t) => (
<li key={t.id}>
<Link href={threadHref(t)} className="ft-row">
<span className="ft-main">
<span className="ft-title">
{t.pinned && <span className="ft-pin">Kitűzve</span>}
{t.locked && <span className="ft-pin">Lezárva</span>}
{t.title}
</span>
<span className="ft-meta">
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
<span>
{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}
{showTopic && ` · ${t.topic.name}`}
{threads.map((t) => {
const closed = t.topic.visibility !== undefined && t.topic.visibility !== "public";
const tags = showTopic || t.pinned || t.locked || t.intent;
return (
<li key={t.id}>
<Link href={threadHref(t)} className="ft-row">
<span className="ft-main">
{tags && (
<span className="ft-tags">
{showTopic && (
<span className="ft-topic">
<TopicIcon slug={t.topic.slug} />
{t.topic.name}
{closed && (
<svg viewBox="0 0 24 24" className="ft-lock" role="img" aria-label="Nem nyilvános 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>
)}
{t.pinned && <span className="ft-pin">Kitűzve</span>}
{t.locked && <span className="ft-pin">Lezárva</span>}
<IntentTag intent={t.intent} />
</span>
)}
<span className="ft-title">{t.title}</span>
{t.excerpt && <span className="ft-excerpt">{t.excerpt}</span>}
<span className="ft-meta">
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
<span className="ft-who">{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}</span>
<span className="ft-m-narrow">
{" "}
· {t.reply_count} válasz ·{" "}
<time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)}
</time>
</span>
<span className="ft-m-narrow ft-m-new">
<UnreadPill n={t.unread} onlyNew />
</span>
</span>
</span>
</span>
<span className="ft-col ft-col-replies">
<strong>{t.reply_count}</strong> válasz
{t.participants > 1 && <span className="hint">{t.participants} résztvevő</span>}
</span>
<span className="ft-col ft-col-last">
<time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)}
</time>
</span>
<UnreadPill n={t.unread} />
</Link>
</li>
))}
<span className="ft-side">
<span>
<strong>{t.reply_count}</strong> válasz
</span>
<span className="hint">
utoljára{" "}
<time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)}
</time>
</span>
<UnreadPill n={t.unread} />
</span>
</Link>
</li>
);
})}
</ul>
);
}
@@ -14,9 +14,11 @@ import type { LiveNotice } from "./ForumNav";
import { ReactionIcon } from "./ReactionIcon";
import { ReportForm } from "./ReportButton";
import { LinkPreviews } from "./LinkPreviews";
import { PostPhotos } from "./Photos";
import { ShareCard } from "./ShareCard";
import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
import { Badge, RankBadge } from "./Badges";
import { askDialog, confirmDialog } from "@/components/Dialogs";
/** How often the open thread looks for new replies (while the page is in front). */
const POLL_MS = 30_000;
@@ -338,6 +340,7 @@ function PostCard({
post.body !== null && (
<>
<PostBody text={post.body} mentions={post.mentions} hide={post.links?.map((l) => l.url) ?? []} />
{post.photos && post.photos.length > 0 && <PostPhotos photos={post.photos} />}
{post.links && post.links.length > 0 && <LinkPreviews links={post.links} />}
{post.share && <ShareCard share={post.share} />}
</>
@@ -529,12 +532,20 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
if (updated) replacePost(updated);
return updated !== null;
},
remove: (post) => {
remove: async (post) => {
let reason: string | null = null;
if (post.own) {
if (!window.confirm("Biztosan törlöd a hozzászólásodat?")) return;
const ok = await confirmDialog({ title: "Törlöd a hozzászólásodat?", confirm: "Törlés", danger: true });
if (!ok) return;
} else {
reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik.");
reason = await askDialog({
title: "Eltávolítod a hozzászólást?",
text: "Az indoklás a hozzászólás helyén látszik.",
label: "Miért távolítod el?",
required: true,
confirm: "Eltávolítás",
danger: true,
});
if (!reason) return;
}
void run(async () => {
@@ -547,21 +558,29 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
await reload();
}),
detachShare: (post) => {
if (!window.confirm("Leveszed a csatolt képletet? A kártya eltűnik, és a link sem működik többé.")) return;
detachShare: async (post) => {
const ok = await confirmDialog({
title: "Leveszed a csatolt képletet?",
text: "A kártya eltűnik, és a link sem működik többé.",
confirm: "Levétel",
danger: true,
});
if (!ok) return;
void run(async () => {
await api(`/forum/posts/${post.id}/share`, { method: "DELETE" });
await reload();
});
},
mute: (post) => {
mute: async (post) => {
const nickname = post.author?.nickname;
if (!nickname) return;
if (
!post.muted &&
!window.confirm(
`Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud. A beállításoknál bármikor feloldhatod.`,
)
!(await confirmDialog({
title: `Elnémítod ${nickname} tagot?`,
text: "A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud. A beállításoknál bármikor feloldhatod.",
confirm: "Elnémítás",
}))
)
return;
void run(async () => {
@@ -579,8 +598,10 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
};
/** A first-level reply (the box at the bottom), or one to `replyTo` (the box in its branch). */
async function sendReply(text: string, to: ForumPost | null): Promise<boolean> {
const post = await run(() => api<ForumPost>(`${base}/posts`, { body: { body: text, parent_id: to?.id ?? null } }));
async function sendReply(text: string, to: ForumPost | null, photos: string[] = []): Promise<boolean> {
const post = await run(() =>
api<ForumPost>(`${base}/posts`, { body: { body: text, parent_id: to?.id ?? null, photos } }),
);
if (!post) return false;
if (to) {
draft.current = "";
@@ -603,7 +624,14 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
}
async function removeThread() {
const reason = window.prompt("Miért távolítod el az egész szálat? Az indoklás látszik a helyén.");
const reason = await askDialog({
title: "Eltávolítod az egész szálat?",
text: "Az indoklás látszik a szál helyén.",
label: "Miért távolítod el?",
required: true,
confirm: "Eltávolítás",
danger: true,
});
if (!reason) return;
await run(() => api(base, { method: "DELETE", body: { reason } }));
await reload();
@@ -741,6 +769,7 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
<Composer
key={top.id}
mentions
photos
onTyping={imTyping}
id={`valasz-${top.id}`}
label={`Válasz neki: ${replyTo.author?.nickname ?? "Törölt tag"}`}
@@ -750,7 +779,7 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
draft.current = text;
}}
busy={busy}
onSubmit={(text) => sendReply(text, replyTo)}
onSubmit={(text, photos) => sendReply(text, replyTo, photos)}
onCancel={() => {
draft.current = "";
setReplyTo(null);
@@ -801,12 +830,13 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
<>
<Composer
mentions
photos
onTyping={imTyping}
id="valasz-szoveg"
label="Válaszod"
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
busy={busy}
onSubmit={(text) => sendReply(text, null)}
onSubmit={(text, photos) => sendReply(text, null, photos)}
/>
</>
)}
+8 -1
View File
@@ -2,6 +2,7 @@
// by its server and client components.
/** The forum's colours: light by default, dark on request (a cookie). */
import type { ForumPhoto } from "./photos";
import type { ChartResult, InterAspect } from "./types";
export const FORUM_THEME_COOKIE = "sf_forum_theme";
@@ -61,8 +62,10 @@ export interface ThreadCard {
slug: string;
title: string;
intent: "listen" | "advice" | null;
topic: TopicRef;
topic: TopicRef & { visibility?: string };
author: ForumAuthor | null;
/** The start of the opening post (as much as a card shows). */
excerpt?: string | null;
created_at: string;
last_post_at: string;
reply_count: number;
@@ -86,6 +89,8 @@ export interface ForumHome {
topics: ForumTopic[];
unanswered: ThreadCard[];
hot: ThreadCard[];
/** Pinned threads, above the topics. */
pinned?: ThreadCard[];
}
export interface TopicPage {
@@ -125,6 +130,8 @@ export interface ForumPost {
share?: ShareCardData | null;
/** Previews of the links a provider knows (YouTube for now). */
links?: LinkPreview[] | null;
/** Photos uploaded with the post. */
photos?: ForumPhoto[] | null;
}
/** A link the forum's link module knows, under a post. */
+140
View File
@@ -0,0 +1,140 @@
"use client";
// Photos in forum posts, in the browser: made small before the upload (the
// longest side 1600 pixels, WebP; JPEG where the browser cannot make WebP),
// so phones send a fraction of the original. The forum checks it again and
// strips what metadata could be left.
import { useCallback, useRef, useState } from "react";
export const MAX_SIDE = 1600;
/** Photos under one post (the forum allows five a member a day too). */
export const PER_POST = 5;
export interface ForumPhoto {
id: string;
url: string;
thumb: string;
width: number;
height: number;
}
type Drawable = ImageBitmap | HTMLImageElement;
async function decode(file: File): Promise<Drawable> {
if (typeof createImageBitmap === "function") {
try {
return await createImageBitmap(file, { imageOrientation: "from-image" });
} catch {
// Some formats only an <img> can read.
}
}
const url = URL.createObjectURL(file);
try {
const img = new Image();
img.src = url;
await img.decode();
return img;
} finally {
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
}
function toBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise<Blob | null> {
return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
}
/** The picture at most MAX_SIDE pixels long, as WebP (or JPEG). */
export async function resizeForUpload(file: File): Promise<Blob> {
const picture = await decode(file);
const width = "naturalWidth" in picture ? picture.naturalWidth : picture.width;
const height = "naturalHeight" in picture ? picture.naturalHeight : picture.height;
if (!width || !height) throw new Error("A képet nem sikerült beolvasni.");
const scale = Math.min(1, MAX_SIDE / Math.max(width, height));
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(width * scale));
canvas.height = Math.max(1, Math.round(height * scale));
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("A képet nem sikerült feldolgozni.");
ctx.imageSmoothingQuality = "high";
ctx.drawImage(picture, 0, 0, canvas.width, canvas.height);
if ("close" in picture) picture.close();
const webp = await toBlob(canvas, "image/webp", 0.82);
if (webp && webp.type === "image/webp") return webp;
const jpeg = await toBlob(canvas, "image/jpeg", 0.85);
if (!jpeg) throw new Error("A képet nem sikerült feldolgozni.");
return jpeg;
}
export interface PickedPhoto {
key: string;
/** A local preview while it uploads, then the forum's square preview. */
preview: string;
id: string | null;
}
/** The photos picked for one post: resized, uploaded one by one, removable before sending. */
export function usePhotoUploads() {
const [items, setItems] = useState<PickedPhoto[]>([]);
const [error, setError] = useState<string | null>(null);
const counter = useRef(0);
const add = useCallback(
async (files: FileList | File[]) => {
setError(null);
const room = PER_POST - items.length;
const chosen = Array.from(files).slice(0, Math.max(0, room));
if (files.length > room) setError(`Egy hozzászóláshoz legfeljebb ${PER_POST} fotó tartozhat.`);
for (const file of chosen) {
const key = `p${++counter.current}`;
const local = URL.createObjectURL(file);
setItems((list) => [...list, { key, preview: local, id: null }]);
try {
const blob = await resizeForUpload(file);
const res = await fetch("/api/v1/forum/photos", {
method: "POST",
body: blob,
headers: { "content-type": blob.type },
credentials: "same-origin",
});
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error(data?.error?.message ?? "A fotót nem sikerült feltölteni.");
setItems((list) => list.map((p) => (p.key === key ? { ...p, id: data.id, preview: data.thumb } : p)));
URL.revokeObjectURL(local);
} catch (e) {
setItems((list) => list.filter((p) => p.key !== key));
URL.revokeObjectURL(local);
setError(e instanceof Error ? e.message : "A fotót nem sikerült feltölteni.");
break;
}
}
},
[items.length],
);
// Taken off before sending: the forum forgets it, and it does not count in the day's five.
const remove = useCallback(
(key: string) => {
const gone = items.find((p) => p.key === key);
if (gone?.id) {
void fetch(`/api/v1/forum/photos/${gone.id}`, { method: "DELETE", credentials: "same-origin" }).catch(() => {});
}
setItems((list) => list.filter((p) => p.key !== key));
},
[items],
);
const reset = useCallback(() => {
setItems([]);
setError(null);
}, []);
return {
items,
error,
add,
remove,
reset,
ids: items.filter((p) => p.id).map((p) => p.id as string),
busy: items.some((p) => !p.id),
full: items.length >= PER_POST,
};
}