Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7665e9acc | ||
|
|
b37094e481 | ||
|
|
7cc642f8b8 | ||
|
|
0358e137f1 | ||
|
|
14ed31fddc | ||
|
|
50c29e4595 | ||
|
|
0bb37c07d9 | ||
|
|
de629a068d | ||
|
|
758c3ce7ea | ||
|
|
e625fe0487 | ||
|
|
27a6226d86 | ||
|
|
083de72877 | ||
|
|
7b52a46541 | ||
|
|
8150247503 | ||
|
|
09c15f067a | ||
|
|
46a2b6781e |
+44
-12
@@ -2,6 +2,11 @@
|
|||||||
# prod: tests, image build (tags: commit hash, `prod`, `latest`), then
|
# prod: tests, image build (tags: commit hash, `prod`, `latest`), then
|
||||||
# deployment to the server.
|
# 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
|
# 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
|
# 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.
|
# 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
|
apk add --no-cache -q git musl-dev
|
||||||
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.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 --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
|
||||||
|
git fetch -q --unshallow --tags origin
|
||||||
- name: Wait for Postgres
|
- name: Wait for Postgres
|
||||||
run: |
|
run: |
|
||||||
for i in $(seq 30); do nc -z postgres 5432 && exit 0; sleep 1; done
|
for i in $(seq 30); do nc -z postgres 5432 && exit 0; sleep 1; done
|
||||||
echo "postgres did not start" >&2; exit 1
|
echo "postgres did not start" >&2; exit 1
|
||||||
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
|
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
|
||||||
# data (scripts/fetch-deps.sh); their tests run locally.
|
# data (scripts/fetch-deps.sh); their tests run locally. Skipped when
|
||||||
|
# only the frontend (or nothing built) changed since the last deployment.
|
||||||
- name: Test
|
- 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:
|
build:
|
||||||
needs: test
|
needs: test
|
||||||
@@ -72,6 +86,7 @@ jobs:
|
|||||||
apk add --no-cache -q git
|
apk add --no-cache -q git
|
||||||
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.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 --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
|
||||||
|
git fetch -q --unshallow --tags origin
|
||||||
- name: Log in to the registry
|
- name: Log in to the registry
|
||||||
env:
|
env:
|
||||||
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
@@ -92,11 +107,15 @@ jobs:
|
|||||||
docker push -q "$image:$t"
|
docker push -q "$image:$t"
|
||||||
done
|
done
|
||||||
}
|
}
|
||||||
build horoscope-api -f services/horoscope-api/Dockerfile .
|
services=$(sh ci/changed-services.sh)
|
||||||
build backend -f services/backend/Dockerfile .
|
echo "building: ${services:-nothing}"
|
||||||
build worker -f services/worker/Dockerfile .
|
for svc in $services; do
|
||||||
build forum -f services/forum/Dockerfile .
|
case "$svc" in
|
||||||
build frontend services/frontend
|
# 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,
|
# Only the last 5 commit images of each service stay in the registry,
|
||||||
# plus `main`, `prod`, `latest` and the commit running in production
|
# plus `main`, `prod`, `latest` and the commit running in production
|
||||||
# (the server pulls it by its commit tag).
|
# (the server pulls it by its commit tag).
|
||||||
@@ -156,6 +175,7 @@ jobs:
|
|||||||
apk add --no-cache -q git openssh-client
|
apk add --no-cache -q git openssh-client
|
||||||
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.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 --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
|
||||||
|
git fetch -q --unshallow --tags origin
|
||||||
- name: SSH key
|
- name: SSH key
|
||||||
env:
|
env:
|
||||||
KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||||
@@ -164,8 +184,9 @@ jobs:
|
|||||||
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
(umask 077 && printf '%s\n' "$KEY" > ~/.ssh/id_ed25519)
|
(umask 077 && printf '%s\n' "$KEY" > ~/.ssh/id_ed25519)
|
||||||
printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
|
printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
# Copies the compose files, pins TAG in the server's .env and restarts
|
# Copies the compose files, pins the built services' tags (TAG_<SERVICE>)
|
||||||
# the changed services. The database migrations run when the backend starts.
|
# in the server's .env and restarts the changed services only. The
|
||||||
|
# database migrations run when the backend (or the forum) starts.
|
||||||
- name: Deploy
|
- name: Deploy
|
||||||
env:
|
env:
|
||||||
HOST: ${{ vars.DEPLOY_HOST }}
|
HOST: ${{ vars.DEPLOY_HOST }}
|
||||||
@@ -173,9 +194,19 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
tag=$(echo "${{ github.sha }}" | cut -c1-12)
|
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/"
|
scp -q deploy/docker-compose.yml deploy/Caddyfile "$HOST:$DIR/"
|
||||||
ssh "$HOST" "cd '$DIR' && \
|
# The .env may end without a newline (a line added by hand): one first,
|
||||||
(grep -q '^TAG=' .env && sed -i 's/^TAG=.*/TAG=$tag/' .env || echo 'TAG=$tag' >> .env) && \
|
# 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 pull -q && docker compose up -d --remove-orphans --wait && \
|
||||||
docker compose exec -T caddy caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile && \
|
docker compose exec -T caddy caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile && \
|
||||||
docker image prune -af >/dev/null"
|
docker image prune -af >/dev/null"
|
||||||
@@ -188,7 +219,8 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
apk add --no-cache -q curl jq
|
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)
|
short=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||||
name="v$(date -u +%Y.%m.%d)-$short"
|
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
|
if curl -fsS -o /dev/null -H "Authorization: token $TOKEN" "$API/releases/tags/$name" 2>/dev/null; then
|
||||||
|
|||||||
Executable
+23
@@ -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
|
||||||
@@ -28,6 +28,10 @@ pub enum Kind {
|
|||||||
/// A detailed analysis of a famous person's chart, about them in the third
|
/// A detailed analysis of a famous person's chart, about them in the third
|
||||||
/// person, for the public pages (the name comes with the data, see [`with_name`]).
|
/// person, for the public pages (the name comes with the data, see [`with_name`]).
|
||||||
Celebrity,
|
Celebrity,
|
||||||
|
/// The free weekly horoscope: the week's sky on the member's own chart, a
|
||||||
|
/// title and a few paragraphs. Written by the summary's model; its prompt
|
||||||
|
/// is not edited on the admin page (so it is not in [`Kind::ALL`]).
|
||||||
|
Weekly,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Kind {
|
impl Kind {
|
||||||
@@ -44,6 +48,7 @@ impl Kind {
|
|||||||
Kind::Forecast => "forecast",
|
Kind::Forecast => "forecast",
|
||||||
Kind::Question => "question",
|
Kind::Question => "question",
|
||||||
Kind::Celebrity => "celebrity",
|
Kind::Celebrity => "celebrity",
|
||||||
|
Kind::Weekly => "weekly",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,6 +60,7 @@ impl Kind {
|
|||||||
"forecast" => Some(Kind::Forecast),
|
"forecast" => Some(Kind::Forecast),
|
||||||
"question" => Some(Kind::Question),
|
"question" => Some(Kind::Question),
|
||||||
"celebrity" => Some(Kind::Celebrity),
|
"celebrity" => Some(Kind::Celebrity),
|
||||||
|
"weekly" => Some(Kind::Weekly),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -153,7 +159,7 @@ fn sections_in(kind: Kind, language: &str) -> Vec<(&'static str, &'static str)>
|
|||||||
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS_HU,
|
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS_HU,
|
||||||
Kind::Synastry => &SYNASTRY_SECTIONS_HU,
|
Kind::Synastry => &SYNASTRY_SECTIONS_HU,
|
||||||
Kind::Forecast => &FORECAST_SECTIONS_HU,
|
Kind::Forecast => &FORECAST_SECTIONS_HU,
|
||||||
Kind::Summary | Kind::Question => &[],
|
Kind::Summary | Kind::Question | Kind::Weekly => &[],
|
||||||
};
|
};
|
||||||
sections(kind).iter().zip(hu).map(|(&(key, en), &hu)| (key, if language == "hu" { hu } else { en })).collect()
|
sections(kind).iter().zip(hu).map(|(&(key, en), &hu)| (key, if language == "hu" { hu } else { en })).collect()
|
||||||
}
|
}
|
||||||
@@ -163,7 +169,7 @@ fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
|
|||||||
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS,
|
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS,
|
||||||
Kind::Synastry => &SYNASTRY_SECTIONS,
|
Kind::Synastry => &SYNASTRY_SECTIONS,
|
||||||
Kind::Forecast => &FORECAST_SECTIONS,
|
Kind::Forecast => &FORECAST_SECTIONS,
|
||||||
Kind::Summary | Kind::Question => &[],
|
Kind::Summary | Kind::Question | Kind::Weekly => &[],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,6 +190,17 @@ pub fn schema(kind: Kind) -> Value {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if kind == Kind::Weekly {
|
||||||
|
return json!({
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"required": ["title", "text"],
|
||||||
|
"properties": {
|
||||||
|
"title": {"type": "string", "description": "Short, evocative title for this week (at most 6 words)"},
|
||||||
|
"text": {"type": "string", "description": "3 short paragraphs separated by a blank line, 150-220 words in all"}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
if kind == Kind::Summary {
|
if kind == Kind::Summary {
|
||||||
return json!({
|
return json!({
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -269,6 +286,13 @@ fn hungarian_system(kind: Kind) -> String {
|
|||||||
előrejelzés kb. 1500–2000 szó.",
|
előrejelzés kb. 1500–2000 szó.",
|
||||||
),
|
),
|
||||||
Kind::Question => unreachable!("questions have their own prompt"),
|
Kind::Question => unreachable!("questions have their own prompt"),
|
||||||
|
Kind::Weekly => (
|
||||||
|
"személyes heti horoszkópot (a hét égboltja az olvasó saját születési képletén; ingyenes, hétfőnként új)",
|
||||||
|
SECOND_PERSON_HU,
|
||||||
|
"Terjedelem: 3 rövid bekezdés, összesen 150–220 szó. Az első a hét fő témája a két-három legerősebb \
|
||||||
|
tranzitból; a második a hét kulcsnapjai (a hét napjainak nevével: „szerdán”, „a hét végén”); a harmadik \
|
||||||
|
egy konkrét, a hétre szóló javaslat. Ne sorold fel az összes tranzitot.",
|
||||||
|
),
|
||||||
Kind::Celebrity => (
|
Kind::Celebrity => (
|
||||||
"portrét egy híres ember születési képletéről (az olvasó nem ő maga, hanem egy érdeklődő látogató)",
|
"portrét egy híres ember születési képletéről (az olvasó nem ő maga, hanem egy érdeklődő látogató)",
|
||||||
THIRD_PERSON_HU,
|
THIRD_PERSON_HU,
|
||||||
@@ -315,6 +339,9 @@ használhatsz.
|
|||||||
if kind == Kind::Celebrity {
|
if kind == Kind::Celebrity {
|
||||||
text.push_str(CELEBRITY_RULES_HU);
|
text.push_str(CELEBRITY_RULES_HU);
|
||||||
}
|
}
|
||||||
|
if kind == Kind::Weekly {
|
||||||
|
text.push_str(WEEKLY_RULES_HU);
|
||||||
|
}
|
||||||
text.push_str(HUNGARIAN_TERMS);
|
text.push_str(HUNGARIAN_TERMS);
|
||||||
if kind == Kind::Forecast {
|
if kind == Kind::Forecast {
|
||||||
text.push_str(HUNGARIAN_FORECAST_TERMS);
|
text.push_str(HUNGARIAN_FORECAST_TERMS);
|
||||||
@@ -341,6 +368,23 @@ rajzolódik ki, aki…”), mert lehet, hogy már nem él. Ne állíts semmit az
|
|||||||
kijelentést.
|
kijelentést.
|
||||||
- Az „advice” mező nem neki szóló tanács, hanem zárógondolat: egy bekezdés, amely összefogja a portrét.";
|
- Az „advice” mező nem neki szóló tanács, hanem zárógondolat: egy bekezdés, amely összefogja a portrét.";
|
||||||
|
|
||||||
|
const WEEKLY_RULES_HU: &str = "
|
||||||
|
|
||||||
|
A heti horoszkóp szabályai:
|
||||||
|
- Ez nem jellemrajz, hanem a hétről szól: a születési képletet csak ott említsd, ahol egy tranzit érinti.
|
||||||
|
- Úgy súlyozz, ahogy egy asztrológus: a lassú bolygók (Jupitertől a Plútóig) tranzitjai a hét háttere; a gyors \
|
||||||
|
bolygók pontos fényszögei a Napra, a Holdra, az Aszcendensre, az MC-re és a horoszkóp uralkodójára a hét eseményes \
|
||||||
|
napjai; a Hold jegyváltásai a hét hangulatának hullámzása; az újhold, a telihold és a retrográd fordulók csak akkor \
|
||||||
|
hangsúlyosak, ha a képletet érintik.
|
||||||
|
- Témákról, hangulatokról és lehetőségekről írj, ne biztos eseményekről: „jó nap arra, hogy”, „hozhat”, „azt kéri \
|
||||||
|
tőled”. Semmit betegségről, halálról, balesetről, terhességről, pénz nyereségéről vagy elvesztéséről. A feszült \
|
||||||
|
fényszögeket is kihívásként és lehetőségként írd le, ne riogass.
|
||||||
|
- Csak az adatokban szereplő napokat használd. A napokat a hét napjainak nevével említsd (hétfő, kedd, …), \
|
||||||
|
dátumszám nélkül.
|
||||||
|
- Ne reklámozz, és ne említs más elemzést vagy szolgáltatást.
|
||||||
|
- Kifejezések: tranzit („a Mars tranzitja a Napod felett”), retrográd, újhold, telihold, a Hold jegyváltása. A \
|
||||||
|
születési képlet pontjait „a születési Vénuszod”, „a Holdad” formában említsd, ne „natális”-ként.";
|
||||||
|
|
||||||
const FORECAST_RULES_HU: &str = "
|
const FORECAST_RULES_HU: &str = "
|
||||||
|
|
||||||
Az előrejelzés szabályai:
|
Az előrejelzés szabályai:
|
||||||
@@ -408,6 +452,10 @@ pub fn default_system(kind: Kind, language: &str) -> String {
|
|||||||
}
|
}
|
||||||
let (role, reader) = match kind {
|
let (role, reader) = match kind {
|
||||||
Kind::Question => unreachable!("questions have their own prompt"),
|
Kind::Question => unreachable!("questions have their own prompt"),
|
||||||
|
Kind::Weekly => (
|
||||||
|
"a personal weekly horoscope (the week's sky on the reader's own natal chart; free, new every Monday)",
|
||||||
|
"Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
|
||||||
|
),
|
||||||
Kind::Celebrity => (
|
Kind::Celebrity => (
|
||||||
"a portrait of a famous person's natal chart (the reader is not that person but an interested visitor)",
|
"a portrait of a famous person's natal chart (the reader is not that person but an interested visitor)",
|
||||||
"Write about them in the third person singular, by name: the full name in the summary, later also the \
|
"Write about them in the third person singular, by name: the full name in the summary, later also the \
|
||||||
@@ -455,6 +503,9 @@ and no medical, legal or financial advice.
|
|||||||
length = match kind {
|
length = match kind {
|
||||||
Kind::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
|
Kind::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
|
||||||
paragraphs; the whole forecast about 1500-2000 words.",
|
paragraphs; the whole forecast about 1500-2000 words.",
|
||||||
|
Kind::Weekly => "Length: 3 short paragraphs, 150-220 words in all. The first is the main theme of the \
|
||||||
|
week from the two or three strongest transits; the second the key days (by weekday name: \"on \
|
||||||
|
Wednesday\", \"at the weekend\"); the third one concrete suggestion for the week. Do not list every transit.",
|
||||||
Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
|
Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
|
||||||
(if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
|
(if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
|
||||||
a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
|
a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
|
||||||
@@ -468,9 +519,25 @@ and no medical, legal or financial advice.
|
|||||||
if kind == Kind::Celebrity {
|
if kind == Kind::Celebrity {
|
||||||
text.push_str(CELEBRITY_RULES);
|
text.push_str(CELEBRITY_RULES);
|
||||||
}
|
}
|
||||||
|
if kind == Kind::Weekly {
|
||||||
|
text.push_str(WEEKLY_RULES);
|
||||||
|
}
|
||||||
text
|
text
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const WEEKLY_RULES: &str = "
|
||||||
|
|
||||||
|
Weekly horoscope rules:
|
||||||
|
- This is not a portrait but the week: mention the natal chart only where a transit touches it.
|
||||||
|
- Weigh as an astrologer would: the slow planets' transits (Jupiter to Pluto) are the background of the week; the \
|
||||||
|
fast planets' exact aspects to the Sun, Moon, Ascendant, Midheaven and chart ruler mark its eventful days; the Moon's \
|
||||||
|
sign changes are the ebb and flow of the mood; new and full moons and stations matter where they touch the chart.
|
||||||
|
- Write about themes, moods and opportunities, never certain events: \"a good day to\", \"may bring\", \"asks you \
|
||||||
|
to\". Nothing about illness, death, accidents, pregnancy, or winning or losing money. Describe tense aspects as \
|
||||||
|
challenges and chances, without alarm.
|
||||||
|
- Use only the days in the data, and name them by weekday (Monday, Tuesday, ...), without dates.
|
||||||
|
- No sales talk, and do not mention any other analysis or service.";
|
||||||
|
|
||||||
const CELEBRITY_RULES: &str = "
|
const CELEBRITY_RULES: &str = "
|
||||||
|
|
||||||
Rules for a famous person's portrait:
|
Rules for a famous person's portrait:
|
||||||
@@ -651,6 +718,8 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
|
|||||||
user.push_str(chart_text);
|
user.push_str(chart_text);
|
||||||
if kind == Kind::Summary {
|
if kind == Kind::Summary {
|
||||||
user.push_str(if hu { "\nMost írd meg a rövid összefoglalót." } else { "\nWrite the short summary now." });
|
user.push_str(if hu { "\nMost írd meg a rövid összefoglalót." } else { "\nWrite the short summary now." });
|
||||||
|
} else if kind == Kind::Weekly {
|
||||||
|
user.push_str(if hu { "\nMost írd meg a heti horoszkópot." } else { "\nWrite the weekly horoscope now." });
|
||||||
} else {
|
} else {
|
||||||
user.push_str(if hu {
|
user.push_str(if hu {
|
||||||
"\nA megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom):\n"
|
"\nA megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom):\n"
|
||||||
@@ -672,6 +741,7 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
|
|||||||
Kind::Summary => "chart_summary",
|
Kind::Summary => "chart_summary",
|
||||||
Kind::Question => "question_answer",
|
Kind::Question => "question_answer",
|
||||||
Kind::Forecast => "forecast_analysis",
|
Kind::Forecast => "forecast_analysis",
|
||||||
|
Kind::Weekly => "weekly_horoscope",
|
||||||
},
|
},
|
||||||
schema: schema(kind),
|
schema: schema(kind),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ pub fn date_of(jd_ut: f64, offset_hours: f64) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The zodiac of the natal chart, geocentric (transits are not topocentric).
|
/// The zodiac of the natal chart, geocentric (transits are not topocentric).
|
||||||
fn frame_of(natal: &NatalChart) -> Frame {
|
pub(crate) fn frame_of(natal: &NatalChart) -> Frame {
|
||||||
let o = natal.settings.options;
|
let o = natal.settings.options;
|
||||||
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
|
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ fn natal_lon(natal: &NatalChart, id: PointId) -> Option<f64> {
|
|||||||
natal.points.iter().find(|p| p.id == id).map(|p| p.position.longitude)
|
natal.points.iter().find(|p| p.id == id).map(|p| p.position.longitude)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
pub(crate) fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||||
let houses = natal.houses.as_ref()?;
|
let houses = natal.houses.as_ref()?;
|
||||||
let mut cusps = [0.0; 12];
|
let mut cusps = [0.0; 12];
|
||||||
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
||||||
@@ -82,7 +82,7 @@ fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
|||||||
/// The natal points transits and progressions are measured to: the ten
|
/// The natal points transits and progressions are measured to: the ten
|
||||||
/// planets and, with a known birth time, the Ascendant and the Midheaven.
|
/// planets and, with a known birth time, the Ascendant and the Midheaven.
|
||||||
/// Without a birth time the Moon is left out (it may be 7° off).
|
/// Without a birth time the Moon is left out (it may be 7° off).
|
||||||
fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
|
pub(crate) fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
|
||||||
let known = natal.angles.is_some();
|
let known = natal.angles.is_some();
|
||||||
let mut out: Vec<(PointId, f64)> = Body::PLANETS
|
let mut out: Vec<(PointId, f64)> = Body::PLANETS
|
||||||
.iter()
|
.iter()
|
||||||
@@ -129,15 +129,15 @@ type Window = (f64, f64);
|
|||||||
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
|
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
|
||||||
|
|
||||||
/// Longitude and daily motion sampled at equal steps.
|
/// Longitude and daily motion sampled at equal steps.
|
||||||
struct Samples {
|
pub(crate) struct Samples {
|
||||||
start: f64,
|
start: f64,
|
||||||
step: f64,
|
step: f64,
|
||||||
lon: Vec<f64>,
|
pub(crate) lon: Vec<f64>,
|
||||||
speed: Vec<f64>,
|
pub(crate) speed: Vec<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Samples {
|
impl Samples {
|
||||||
fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
pub(crate) fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
||||||
let n = ((to - from) / step).ceil() as usize + 1;
|
let n = ((to - from) / step).ceil() as usize + 1;
|
||||||
let mut lon = Vec::with_capacity(n);
|
let mut lon = Vec::with_capacity(n);
|
||||||
let mut speed = Vec::with_capacity(n);
|
let mut speed = Vec::with_capacity(n);
|
||||||
@@ -149,7 +149,7 @@ impl Samples {
|
|||||||
Ok(Self { start: from, step, lon, speed })
|
Ok(Self { start: from, step, lon, speed })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn jd(&self, i: usize) -> f64 {
|
pub(crate) fn jd(&self, i: usize) -> f64 {
|
||||||
self.start + i as f64 * self.step
|
self.start + i as f64 * self.step
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -230,22 +230,30 @@ pub struct Contact {
|
|||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub house: Option<u8>,
|
pub house: Option<u8>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
peak_jd: f64,
|
pub(crate) peak_jd: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One year of a natal chart.
|
/// What counts as a contact: the orb, the aspects, and whether the periods
|
||||||
struct Year<'a> {
|
/// within orb are listed.
|
||||||
engine: &'a dyn Ephemeris,
|
pub(crate) struct ContactRule<'a> {
|
||||||
natal: &'a NatalChart,
|
pub(crate) orb: f64,
|
||||||
frame: Frame,
|
pub(crate) aspects: &'a [AspectKind],
|
||||||
start: f64,
|
pub(crate) with_periods: bool,
|
||||||
end: f64,
|
}
|
||||||
offset: f64,
|
|
||||||
cusps: Option<[f64; 12]>,
|
/// One year of a natal chart (or any shorter span: see [`crate::week`]).
|
||||||
|
pub(crate) struct Year<'a> {
|
||||||
|
pub(crate) engine: &'a dyn Ephemeris,
|
||||||
|
pub(crate) natal: &'a NatalChart,
|
||||||
|
pub(crate) frame: Frame,
|
||||||
|
pub(crate) start: f64,
|
||||||
|
pub(crate) end: f64,
|
||||||
|
pub(crate) offset: f64,
|
||||||
|
pub(crate) cusps: Option<[f64; 12]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Year<'_> {
|
impl Year<'_> {
|
||||||
fn date(&self, jd: f64) -> String {
|
pub(crate) fn date(&self, jd: f64) -> String {
|
||||||
date_of(jd, self.offset)
|
date_of(jd, self.offset)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,17 +262,17 @@ impl Year<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Contacts of one moving planet (sampled in `s`) with the natal points.
|
/// Contacts of one moving planet (sampled in `s`) with the natal points.
|
||||||
fn contacts(
|
pub(crate) fn contacts(
|
||||||
&self,
|
&self,
|
||||||
planet: PointId,
|
planet: PointId,
|
||||||
s: &Samples,
|
s: &Samples,
|
||||||
lon_at: &dyn Fn(f64) -> Result<f64>,
|
lon_at: &dyn Fn(f64) -> Result<f64>,
|
||||||
targets: &[(PointId, f64)],
|
targets: &[(PointId, f64)],
|
||||||
with_periods: bool,
|
rule: &ContactRule,
|
||||||
) -> Result<Vec<Contact>> {
|
) -> Result<Vec<Contact>> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
for &(natal_point, natal) in targets {
|
for &(natal_point, natal) in targets {
|
||||||
for aspect in ASPECTS {
|
for &aspect in rule.aspects {
|
||||||
let a = aspect.angle();
|
let a = aspect.angle();
|
||||||
let mut points = vec![natal + a];
|
let mut points = vec![natal + a];
|
||||||
if a != 0.0 && a != 180.0 {
|
if a != 0.0 && a != 180.0 {
|
||||||
@@ -272,7 +280,7 @@ impl Year<'_> {
|
|||||||
}
|
}
|
||||||
let (mut windows, mut exact) = (Vec::new(), Vec::new());
|
let (mut windows, mut exact) = (Vec::new(), Vec::new());
|
||||||
for target in points {
|
for target in points {
|
||||||
let (w, e) = crossings(s, target, ORB, lon_at)?;
|
let (w, e) = crossings(s, target, rule.orb, lon_at)?;
|
||||||
windows.extend(w);
|
windows.extend(w);
|
||||||
exact.extend(e);
|
exact.extend(e);
|
||||||
}
|
}
|
||||||
@@ -289,7 +297,7 @@ impl Year<'_> {
|
|||||||
.map(|i| (i, separation(s.lon[i], natal)))
|
.map(|i| (i, separation(s.lon[i], natal)))
|
||||||
.map(|(i, sep)| (i, (sep - a).abs()))
|
.map(|(i, sep)| (i, (sep - a).abs()))
|
||||||
.min_by(|x, y| x.1.total_cmp(&y.1))
|
.min_by(|x, y| x.1.total_cmp(&y.1))
|
||||||
.unwrap_or((0, ORB));
|
.unwrap_or((0, rule.orb));
|
||||||
let (peak_jd, min_orb) = match exact.first() {
|
let (peak_jd, min_orb) = match exact.first() {
|
||||||
Some(&(jd, _)) => (jd, 0.0),
|
Some(&(jd, _)) => (jd, 0.0),
|
||||||
None => (s.jd(closest_i), closest),
|
None => (s.jd(closest_i), closest),
|
||||||
@@ -301,7 +309,7 @@ impl Year<'_> {
|
|||||||
aspect,
|
aspect,
|
||||||
nature: aspect.nature(),
|
nature: aspect.nature(),
|
||||||
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
|
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
|
||||||
periods: if with_periods {
|
periods: if rule.with_periods {
|
||||||
windows
|
windows
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
|
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
|
||||||
@@ -319,7 +327,7 @@ impl Year<'_> {
|
|||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
|
pub(crate) fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
|
||||||
let s = self.engine.position(body, jd, &self.frame)?;
|
let s = self.engine.position(body, jd, &self.frame)?;
|
||||||
Ok((s.longitude, s.speed_longitude))
|
Ok((s.longitude, s.speed_longitude))
|
||||||
}
|
}
|
||||||
@@ -333,7 +341,8 @@ impl Year<'_> {
|
|||||||
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||||
let s = Samples::take(self.start - MARGIN_DAYS, self.end + MARGIN_DAYS, 1.0, &at)?;
|
let s = Samples::take(self.start - MARGIN_DAYS, self.end + MARGIN_DAYS, 1.0, &at)?;
|
||||||
let planet = PointId::from_planet(body);
|
let planet = PointId::from_planet(body);
|
||||||
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, true)?);
|
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: true };
|
||||||
|
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||||
if let Some(cusps) = self.cusps {
|
if let Some(cusps) = self.cusps {
|
||||||
houses.push(self.house_changes(planet, &s, &cusps));
|
houses.push(self.house_changes(planet, &s, &cusps));
|
||||||
}
|
}
|
||||||
@@ -378,7 +387,8 @@ impl Year<'_> {
|
|||||||
// A progressed planet meeting its own natal place only matters for the Moon (the progressed lunar return).
|
// A progressed planet meeting its own natal place only matters for the Moon (the progressed lunar return).
|
||||||
let own: Vec<(PointId, f64)> =
|
let own: Vec<(PointId, f64)> =
|
||||||
targets.iter().copied().filter(|&(id, _)| id != planet || body == Body::Moon).collect();
|
targets.iter().copied().filter(|&(id, _)| id != planet || body == Body::Moon).collect();
|
||||||
contacts.extend(self.contacts(planet, &s, &lon_at, &own, false)?);
|
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: false };
|
||||||
|
contacts.extend(self.contacts(planet, &s, &lon_at, &own, &rule)?);
|
||||||
}
|
}
|
||||||
let start = ZodiacPosition::new(s.lon[0]);
|
let start = ZodiacPosition::new(s.lon[0]);
|
||||||
let mut sign_changes = Vec::new();
|
let mut sign_changes = Vec::new();
|
||||||
|
|||||||
@@ -6,8 +6,9 @@
|
|||||||
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
||||||
//! without touching the chart logic. [`synastry`] compares two charts;
|
//! without touching the chart logic. [`synastry`] compares two charts;
|
||||||
//! [`forecast`] looks at one year of a chart (solar return, transits,
|
//! [`forecast`] looks at one year of a chart (solar return, transits,
|
||||||
//! progressions, profection, eclipses); [`sky`] is the sky by date, the same
|
//! progressions, profection, eclipses); [`week`] is one week of a chart (the
|
||||||
//! for everyone (lunar phases, retrograde periods).
|
//! weekly horoscope); [`sky`] is the sky by date, the same for everyone (lunar
|
||||||
|
//! phases, retrograde periods).
|
||||||
|
|
||||||
pub mod angle;
|
pub mod angle;
|
||||||
pub mod chart;
|
pub mod chart;
|
||||||
@@ -17,6 +18,7 @@ pub mod sky;
|
|||||||
pub mod synastry;
|
pub mod synastry;
|
||||||
pub mod time;
|
pub mod time;
|
||||||
pub mod types;
|
pub mod types;
|
||||||
|
pub mod week;
|
||||||
|
|
||||||
#[cfg(feature = "swisseph")]
|
#[cfg(feature = "swisseph")]
|
||||||
pub mod swiss;
|
pub mod swiss;
|
||||||
@@ -29,3 +31,4 @@ pub use engine::{
|
|||||||
pub use forecast::{Forecast, calculate_forecast, solar_return};
|
pub use forecast::{Forecast, calculate_forecast, solar_return};
|
||||||
pub use synastry::{Synastry, calculate_synastry};
|
pub use synastry::{Synastry, calculate_synastry};
|
||||||
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
||||||
|
pub use week::{Week, calculate_week};
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
//! One week of a natal chart, for the weekly horoscope: the planets' aspects
|
||||||
|
//! to the natal points during the week (with the day each is exact), where
|
||||||
|
//! the planets stand at the start, the Moon's sign changes, the main lunar
|
||||||
|
//! phases, and the planets' stations and sign changes.
|
||||||
|
//!
|
||||||
|
//! The aspects use the yearly forecast's machinery ([`crate::forecast`]) on a
|
||||||
|
//! seven-day span, with the Sun to Pluto as the moving planets (the Moon
|
||||||
|
//! would touch every natal point in a week, so only its signs are given).
|
||||||
|
//! Dates are calendar days at a fixed UTC offset given by the caller.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::chart::{AspectKind, NatalChart, PointId, ZodiacPosition, house_of};
|
||||||
|
use crate::engine::{EngineError, Ephemeris};
|
||||||
|
use crate::forecast::{Contact, ContactRule, Samples, Year, cusps_of, frame_of, natal_targets};
|
||||||
|
use crate::sky::{LunationKind, RETROGRADING, lunations, moon_ingresses, stations};
|
||||||
|
use crate::types::{Body, ZodiacSign};
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, EngineError>;
|
||||||
|
|
||||||
|
/// The moving planets: everything but the Moon.
|
||||||
|
const MOVING: [Body; 9] = [
|
||||||
|
Body::Sun,
|
||||||
|
Body::Mercury,
|
||||||
|
Body::Venus,
|
||||||
|
Body::Mars,
|
||||||
|
Body::Jupiter,
|
||||||
|
Body::Saturn,
|
||||||
|
Body::Uranus,
|
||||||
|
Body::Neptune,
|
||||||
|
Body::Pluto,
|
||||||
|
];
|
||||||
|
/// The major aspects only: a week has room for the strong themes.
|
||||||
|
const ASPECTS: [AspectKind; 5] =
|
||||||
|
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
||||||
|
/// Orb of a contact, degrees: within it at some time during the week.
|
||||||
|
pub const WEEK_ORB: f64 = 1.0;
|
||||||
|
/// Sampling step, days (Mercury moves at most about 2° a day).
|
||||||
|
const STEP: f64 = 0.25;
|
||||||
|
/// Days sampled around the week, so a pass beginning before it is found whole.
|
||||||
|
const MARGIN_DAYS: f64 = 20.0;
|
||||||
|
|
||||||
|
/// A planet at the start of the week.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekPosition {
|
||||||
|
pub planet: PointId,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub position: ZodiacPosition,
|
||||||
|
pub retrograde: bool,
|
||||||
|
/// Natal house (birth time known).
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub house: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A planet (or the Moon) entering a sign.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekIngress {
|
||||||
|
pub date: String,
|
||||||
|
pub planet: PointId,
|
||||||
|
pub sign: ZodiacSign,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub house: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new moon, quarter or full moon.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekLunation {
|
||||||
|
pub date: String,
|
||||||
|
pub kind: LunationKind,
|
||||||
|
/// Where the Moon is.
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub position: ZodiacPosition,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub house: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A planet standing still before turning retrograde or direct.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct WeekStation {
|
||||||
|
pub date: String,
|
||||||
|
pub planet: PointId,
|
||||||
|
pub retrograde: bool,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub position: ZodiacPosition,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One week of a natal chart.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Week {
|
||||||
|
/// First and last day (Monday and Sunday).
|
||||||
|
pub start: String,
|
||||||
|
pub end: String,
|
||||||
|
/// The planets' aspects to the natal points, by their peak inside the week.
|
||||||
|
pub contacts: Vec<Contact>,
|
||||||
|
pub positions: Vec<WeekPosition>,
|
||||||
|
/// The Moon's sign at the start, and its sign changes.
|
||||||
|
pub moon_sign: ZodiacSign,
|
||||||
|
pub moon_ingresses: Vec<WeekIngress>,
|
||||||
|
/// The other planets' sign changes.
|
||||||
|
pub ingresses: Vec<WeekIngress>,
|
||||||
|
pub lunations: Vec<WeekLunation>,
|
||||||
|
pub stations: Vec<WeekStation>,
|
||||||
|
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The week from `start_jd` (the first moment of Monday) to `end_jd` (the
|
||||||
|
/// first moment of the next Monday); dates are given at `offset_hours` from UTC.
|
||||||
|
pub fn calculate_week(
|
||||||
|
engine: &dyn Ephemeris,
|
||||||
|
natal: &NatalChart,
|
||||||
|
start_jd: f64,
|
||||||
|
end_jd: f64,
|
||||||
|
offset_hours: f64,
|
||||||
|
) -> Result<Week> {
|
||||||
|
if end_jd <= start_jd || end_jd - start_jd > 8.0 {
|
||||||
|
return Err(EngineError::Calculation("a week is at most eight days".into()));
|
||||||
|
}
|
||||||
|
let span = Year {
|
||||||
|
engine,
|
||||||
|
natal,
|
||||||
|
frame: frame_of(natal),
|
||||||
|
start: start_jd,
|
||||||
|
// The next Monday's first moment belongs to the next week.
|
||||||
|
end: end_jd - 1.0 / 86_400.0,
|
||||||
|
offset: offset_hours,
|
||||||
|
cusps: cusps_of(natal),
|
||||||
|
};
|
||||||
|
let house = |lon: f64| span.cusps.as_ref().map(|c| house_of(lon, c));
|
||||||
|
// The last day is the day before the next Monday.
|
||||||
|
let last_day = span.date(end_jd - 0.5 / 24.0);
|
||||||
|
let targets = natal_targets(natal);
|
||||||
|
let rule = ContactRule { orb: WEEK_ORB, aspects: &ASPECTS, with_periods: false };
|
||||||
|
|
||||||
|
let mut contacts = Vec::new();
|
||||||
|
let mut positions = Vec::new();
|
||||||
|
let mut ingresses = Vec::new();
|
||||||
|
for body in MOVING {
|
||||||
|
let at = |jd: f64| span.position(body, jd);
|
||||||
|
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||||
|
let s = Samples::take(start_jd - MARGIN_DAYS, end_jd + MARGIN_DAYS, STEP, &at)?;
|
||||||
|
let planet = PointId::from_planet(body);
|
||||||
|
contacts.extend(span.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||||
|
|
||||||
|
let (lon, speed) = at(start_jd)?;
|
||||||
|
positions.push(WeekPosition {
|
||||||
|
planet,
|
||||||
|
position: ZodiacPosition::new(lon),
|
||||||
|
retrograde: speed < 0.0,
|
||||||
|
house: house(lon),
|
||||||
|
});
|
||||||
|
// Sign changes inside the week, to the sample (a few hours).
|
||||||
|
for i in 1..s.lon.len() {
|
||||||
|
let jd = s.jd(i);
|
||||||
|
if jd <= start_jd || jd > end_jd {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let sign = ZodiacSign::from_longitude(s.lon[i]);
|
||||||
|
if sign != ZodiacSign::from_longitude(s.lon[i - 1]) {
|
||||||
|
ingresses.push(WeekIngress { date: span.date(jd), planet, sign, house: house(s.lon[i]) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
contacts.sort_by(|a, b| a.peak_jd.total_cmp(&b.peak_jd));
|
||||||
|
|
||||||
|
let moon_start = span.position(Body::Moon, start_jd)?.0;
|
||||||
|
let moon_ingresses = moon_ingresses(engine, start_jd, end_jd)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(jd, sign)| {
|
||||||
|
let lon = span.position(Body::Moon, jd + 1.0 / 24.0).map(|(l, _)| l).unwrap_or(sign.index() as f64 * 30.0);
|
||||||
|
WeekIngress { date: span.date(jd), planet: PointId::Moon, sign, house: house(lon) }
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let lunations = lunations(engine, start_jd, end_jd)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|l| WeekLunation {
|
||||||
|
date: span.date(l.jd_ut),
|
||||||
|
kind: l.kind,
|
||||||
|
position: ZodiacPosition::new(l.moon_longitude),
|
||||||
|
house: house(l.moon_longitude),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut week_stations = Vec::new();
|
||||||
|
for body in RETROGRADING {
|
||||||
|
for st in stations(engine, body, start_jd, end_jd)? {
|
||||||
|
week_stations.push(WeekStation {
|
||||||
|
date: span.date(st.jd_ut),
|
||||||
|
planet: PointId::from_planet(body),
|
||||||
|
retrograde: st.retrograde,
|
||||||
|
position: ZodiacPosition::new(st.longitude),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
week_stations.sort_by(|a, b| a.date.cmp(&b.date));
|
||||||
|
ingresses.sort_by(|a, b| a.date.cmp(&b.date));
|
||||||
|
|
||||||
|
let mut warnings = Vec::new();
|
||||||
|
if natal.angles.is_none() {
|
||||||
|
warnings
|
||||||
|
.push("Birth time unknown: no houses or angles, and the natal Moon is left out of the contacts.".into());
|
||||||
|
}
|
||||||
|
Ok(Week {
|
||||||
|
start: span.date(start_jd),
|
||||||
|
end: last_day,
|
||||||
|
contacts,
|
||||||
|
positions,
|
||||||
|
moon_sign: ZodiacSign::from_longitude(moon_start),
|
||||||
|
moon_ingresses,
|
||||||
|
ingresses,
|
||||||
|
lunations,
|
||||||
|
stations: week_stations,
|
||||||
|
warnings,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -217,3 +217,37 @@ fn solar_return_and_forecast() {
|
|||||||
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
|
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
|
||||||
serde_json::to_string(&f).unwrap();
|
serde_json::to_string(&f).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_week() {
|
||||||
|
use astro_engine::calculate_week;
|
||||||
|
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
|
||||||
|
let natal = calculate_chart(engine(), &input).unwrap();
|
||||||
|
// Monday 30 November 2026, 0:00 in Budapest (UTC+1), to the next Monday.
|
||||||
|
let start = 2_461_374.5 - 1.0 / 24.0;
|
||||||
|
assert_eq!(astro_engine::forecast::date_of(start, 1.0), "2026-11-30");
|
||||||
|
let w = calculate_week(engine(), &natal, start, start + 7.0, 1.0).unwrap();
|
||||||
|
assert_eq!((w.start.as_str(), w.end.as_str()), ("2026-11-30", "2026-12-06"));
|
||||||
|
assert_eq!(w.positions.len(), 9);
|
||||||
|
assert!(w.positions.iter().all(|p| p.house.is_some()));
|
||||||
|
// Every contact is within orb during the week, with its peak and exact hits inside it.
|
||||||
|
assert!(!w.contacts.is_empty());
|
||||||
|
for c in &w.contacts {
|
||||||
|
assert!(c.min_orb <= 1.0, "{c:?}");
|
||||||
|
assert!(c.peak.as_str() >= w.start.as_str() && c.peak.as_str() <= w.end.as_str(), "{c:?}");
|
||||||
|
assert!(c.exact.iter().all(|e| e.date >= w.start && e.date <= w.end), "{c:?}");
|
||||||
|
assert_ne!(c.planet, astro_engine::chart::PointId::Moon);
|
||||||
|
}
|
||||||
|
// The Moon changes sign every two or three days, each time into the next sign.
|
||||||
|
assert!((2..=4).contains(&w.moon_ingresses.len()), "{:?}", w.moon_ingresses);
|
||||||
|
let mut sign = w.moon_sign;
|
||||||
|
for i in &w.moon_ingresses {
|
||||||
|
assert_eq!(i.sign.index(), (sign.index() + 1) % 12);
|
||||||
|
sign = i.sign;
|
||||||
|
}
|
||||||
|
// About one main lunar phase a week.
|
||||||
|
assert!((1..=2).contains(&w.lunations.len()), "{:?}", w.lunations);
|
||||||
|
let json = serde_json::to_value(&w).unwrap();
|
||||||
|
assert!(json["contacts"][0]["planet"].is_string());
|
||||||
|
assert!(json["positions"][0]["sign"].is_string());
|
||||||
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- The free weekly horoscope: the week's sky on a member's own chart (from
|
||||||
|
-- the horoscope service), its text (an analysis of kind 'weekly', written by
|
||||||
|
-- the summary's model), and the Monday e-mail that says it is there (on for
|
||||||
|
-- everyone, the members of today too; it can be turned off).
|
||||||
|
|
||||||
|
CREATE TABLE weekly_skies (
|
||||||
|
chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||||
|
-- The chart's data when it was calculated: new birth data, new week sky.
|
||||||
|
chart_hash text NOT NULL,
|
||||||
|
-- The Monday the week starts on (Hungarian time).
|
||||||
|
week_start date NOT NULL,
|
||||||
|
result jsonb NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (chart_id, chart_hash, week_start)
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE analyses ADD COLUMN week_start date;
|
||||||
|
|
||||||
|
ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check;
|
||||||
|
ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check
|
||||||
|
CHECK (kind IN ('natal', 'synastry', 'summary', 'forecast', 'tarot', 'celebrity', 'weekly'));
|
||||||
|
|
||||||
|
ALTER TABLE analyses DROP CONSTRAINT analyses_target;
|
||||||
|
ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK (
|
||||||
|
(kind IN ('natal', 'summary', 'celebrity') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||||
|
OR (kind = 'tarot' AND tarot IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'weekly' AND chart_id IS NOT NULL AND week_start IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The Monday e-mail: on unless the member turns it off. The token opens the
|
||||||
|
-- page of every e-mail setting from an e-mail's footer (no login needed).
|
||||||
|
ALTER TABLE users ADD COLUMN weekly_email boolean NOT NULL DEFAULT true;
|
||||||
|
ALTER TABLE users ADD COLUMN weekly_email_sent_on date;
|
||||||
|
ALTER TABLE users ADD COLUMN email_token uuid NOT NULL DEFAULT gen_random_uuid();
|
||||||
|
CREATE UNIQUE INDEX users_email_token ON users (email_token);
|
||||||
@@ -182,6 +182,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
|||||||
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
||||||
("gift", _) => gift(lang, payload, url)?,
|
("gift", _) => gift(lang, payload, url)?,
|
||||||
("gift_package", _) => gift_package(lang, payload, url)?,
|
("gift_package", _) => gift_package(lang, payload, url)?,
|
||||||
|
("weekly_horoscope", _) => weekly_horoscope(lang, payload, url)?,
|
||||||
// The forum is Hungarian only.
|
// The forum is Hungarian only.
|
||||||
("forum_reply", _) => forum_reply(payload, url)?,
|
("forum_reply", _) => forum_reply(payload, url)?,
|
||||||
("forum_digest", _) => forum_digest(payload, url)?,
|
("forum_digest", _) => forum_digest(payload, url)?,
|
||||||
@@ -602,6 +603,117 @@ fn name(payload: &Value, field: &str) -> Option<String> {
|
|||||||
(!name.is_empty()).then(|| name.to_owned())
|
(!name.is_empty()).then(|| name.to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Monday's notice that the weekly horoscope is there: only that, the text
|
||||||
|
/// itself is read on the site after logging in.
|
||||||
|
fn weekly_horoscope(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||||
|
let start = field(payload, "week_start")?;
|
||||||
|
let end = field(payload, "week_end")?;
|
||||||
|
let range = week_range(lang, &start, &end).ok_or(TemplateError::MissingField("week_start"))?;
|
||||||
|
let greeting = match (lang, name(payload, "display_name")) {
|
||||||
|
(Lang::Hu, Some(n)) => format!("Szia {n}!"),
|
||||||
|
(Lang::Hu, None) => "Szia!".to_owned(),
|
||||||
|
(Lang::En, Some(n)) => format!("Hi {n},"),
|
||||||
|
(Lang::En, None) => "Hi,".to_owned(),
|
||||||
|
};
|
||||||
|
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
||||||
|
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
|
||||||
|
Ok(match lang {
|
||||||
|
Lang::Hu => Content {
|
||||||
|
subject: "Itt a heti horoszkópod".into(),
|
||||||
|
preheader: Some(format!("{range}: belépés után a Heti horoszkóp oldalon olvashatod.")),
|
||||||
|
greeting,
|
||||||
|
intro: format!(
|
||||||
|
"Itt a heti horoszkópod {} {range} közötti hétre. Belépés után a Heti horoszkóp oldalon olvashatod.",
|
||||||
|
// "az április 6–12.", "a november 30."
|
||||||
|
if range.starts_with(['a', 'á', 'e', 'é', 'i', 'í', 'o', 'ó', 'ö', 'ő', 'u', 'ú', 'ü', 'ű']) {
|
||||||
|
"az"
|
||||||
|
} else {
|
||||||
|
"a"
|
||||||
|
}
|
||||||
|
),
|
||||||
|
quote: None,
|
||||||
|
points: None,
|
||||||
|
code: None,
|
||||||
|
button: "Megnézem",
|
||||||
|
url,
|
||||||
|
note: "A saját képletedből és a hét égboltjából készül.".into(),
|
||||||
|
reason: Some(
|
||||||
|
"Azért kapod ezt a levelet, mert van képleted a Sorsfonalakon. Ha nem kéred, az alábbi linken vagy a \
|
||||||
|
Profil oldalon kikapcsolhatod."
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
unsubscribe: Some(("Leiratkozás, értesítések beállítása", unsubscribe_url)),
|
||||||
|
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||||
|
},
|
||||||
|
Lang::En => Content {
|
||||||
|
subject: "Your weekly horoscope is here".into(),
|
||||||
|
preheader: Some(format!("{range}: log in to read it on the Weekly horoscope page.")),
|
||||||
|
greeting,
|
||||||
|
intro: format!(
|
||||||
|
"Your weekly horoscope for {range} is here. Log in to read it on the Weekly horoscope page."
|
||||||
|
),
|
||||||
|
quote: None,
|
||||||
|
points: None,
|
||||||
|
code: None,
|
||||||
|
button: "Read it",
|
||||||
|
url,
|
||||||
|
note: "It is written from your own chart and the week's sky.".into(),
|
||||||
|
reason: Some(
|
||||||
|
"You get this e-mail because you have a chart on Sorsfonalak. If you do not want it, turn it off with \
|
||||||
|
the link below or on your Profile page."
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
unsubscribe: Some(("Unsubscribe, e-mail settings", unsubscribe_url)),
|
||||||
|
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "november 30. – december 6." or "december 7–13." (no year).
|
||||||
|
fn week_range(lang: Lang, start: &str, end: &str) -> Option<String> {
|
||||||
|
let parse = |iso: &str| -> Option<(usize, u32)> {
|
||||||
|
let mut parts = iso.splitn(3, '-').skip(1);
|
||||||
|
let m: usize = parts.next()?.parse().ok()?;
|
||||||
|
let d: u32 = parts.next()?.get(..2)?.parse().ok()?;
|
||||||
|
Some((m.checked_sub(1).filter(|&i| i < 12)?, d))
|
||||||
|
};
|
||||||
|
let ((m1, d1), (m2, d2)) = (parse(start)?, parse(end)?);
|
||||||
|
const HU: [&str; 12] = [
|
||||||
|
"január",
|
||||||
|
"február",
|
||||||
|
"március",
|
||||||
|
"április",
|
||||||
|
"május",
|
||||||
|
"június",
|
||||||
|
"július",
|
||||||
|
"augusztus",
|
||||||
|
"szeptember",
|
||||||
|
"október",
|
||||||
|
"november",
|
||||||
|
"december",
|
||||||
|
];
|
||||||
|
const EN: [&str; 12] = [
|
||||||
|
"January",
|
||||||
|
"February",
|
||||||
|
"March",
|
||||||
|
"April",
|
||||||
|
"May",
|
||||||
|
"June",
|
||||||
|
"July",
|
||||||
|
"August",
|
||||||
|
"September",
|
||||||
|
"October",
|
||||||
|
"November",
|
||||||
|
"December",
|
||||||
|
];
|
||||||
|
Some(match (lang, m1 == m2) {
|
||||||
|
(Lang::Hu, true) => format!("{} {d1}–{d2}.", HU[m1]),
|
||||||
|
(Lang::Hu, false) => format!("{} {d1}. – {} {d2}.", HU[m1], HU[m2]),
|
||||||
|
(Lang::En, true) => format!("{d1}–{d2} {}", EN[m1]),
|
||||||
|
(Lang::En, false) => format!("{d1} {} – {d2} {}", EN[m1], EN[m2]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The confirmation of a purchase: what was bought, and that the buyer asked
|
/// The confirmation of a purchase: what was bought, and that the buyer asked
|
||||||
/// for immediate delivery and so gave up the 14-day withdrawal right (the
|
/// for immediate delivery and so gave up the 14-day withdrawal right (the
|
||||||
/// confirmation 45/2014. Korm. rendelet 29. § asks for).
|
/// confirmation 45/2014. Korm. rendelet 29. § asks for).
|
||||||
@@ -1227,6 +1339,31 @@ mod tests {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn weekly_horoscope_only_says_it_is_there() {
|
||||||
|
let payload = json!({
|
||||||
|
"url": "https://sorsfonalak.test/heti-horoszkop",
|
||||||
|
"display_name": "Kata",
|
||||||
|
"week_start": "2026-11-30",
|
||||||
|
"week_end": "2026-12-06",
|
||||||
|
"unsubscribe_url": "https://sorsfonalak.test/ertesitesek?token=abc",
|
||||||
|
"unsubscribe_post_url": "https://sorsfonalak.test/api/v1/public/weekly/unsubscribe?token=abc",
|
||||||
|
});
|
||||||
|
let hu = render("weekly_horoscope", "hu", &payload).unwrap();
|
||||||
|
assert_eq!(hu.subject, "Itt a heti horoszkópod");
|
||||||
|
assert!(hu.text.contains("a november 30. – december 6. közötti hétre"), "{}", hu.text);
|
||||||
|
assert!(
|
||||||
|
hu.text.contains("Leiratkozás, értesítések beállítása: https://sorsfonalak.test/ertesitesek?token=abc")
|
||||||
|
);
|
||||||
|
assert!(hu.html.contains(r#"href="https://sorsfonalak.test/heti-horoszkop""#));
|
||||||
|
assert!(hu.unsubscribe_post_url.is_some());
|
||||||
|
let mut same_month = payload.clone();
|
||||||
|
same_month["week_start"] = json!("2026-12-07");
|
||||||
|
same_month["week_end"] = json!("2026-12-13");
|
||||||
|
let en = render("weekly_horoscope", "en", &same_month).unwrap();
|
||||||
|
assert!(en.text.contains("for 7–13 December is here"), "{}", en.text);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn waitlist_confirmation_has_the_leave_link() {
|
fn waitlist_confirmation_has_the_leave_link() {
|
||||||
let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
|
let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
|
||||||
|
|||||||
@@ -48,6 +48,11 @@ impl HoroscopeClient {
|
|||||||
self.post("/v1/forecast", request).await
|
self.post("/v1/forecast", request).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `POST /v1/week`: one week of a natal chart (the weekly horoscope's sky).
|
||||||
|
pub async fn week(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||||
|
self.post("/v1/week", request).await
|
||||||
|
}
|
||||||
|
|
||||||
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
|
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
|
||||||
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
|
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
|
||||||
self.get("/v1/sky", &[]).await
|
self.get("/v1/sky", &[]).await
|
||||||
|
|||||||
+8
-4
@@ -9,10 +9,14 @@ A runner egyszerre egy feladatot futtat; ha a main is buildelne, minden kitett c
|
|||||||
|
|
||||||
A lépések:
|
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.
|
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.
|
||||||
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.
|
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.
|
||||||
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).
|
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).
|
Kézzel is indítható a repó Actions oldaláról (workflow_dispatch).
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
horoscope-api:
|
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
|
read_only: true
|
||||||
logging: *logging
|
logging: *logging
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
@@ -75,7 +75,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
backend:
|
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:
|
environment:
|
||||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||||
@@ -134,11 +134,12 @@ services:
|
|||||||
|
|
||||||
# E-mail delivery, cleanup and the other background jobs.
|
# E-mail delivery, cleanup and the other background jobs.
|
||||||
worker:
|
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:
|
environment:
|
||||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||||
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary.
|
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary;
|
||||||
WORKER_TASKS: email,cleanup,invoices,notify,forum
|
# weekly: Monday's e-mail about the weekly horoscope.
|
||||||
|
WORKER_TASKS: email,cleanup,invoices,notify,forum,weekly
|
||||||
# The sky of the forum's daily thread.
|
# The sky of the forum's daily thread.
|
||||||
BACKEND_URL: http://backend:8081
|
BACKEND_URL: http://backend:8081
|
||||||
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
|
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
|
||||||
@@ -167,7 +168,7 @@ services:
|
|||||||
# The same image writing the analyses and answers (quick and slow lane);
|
# The same image writing the analyses and answers (quick and slow lane);
|
||||||
# OPENROUTER_API_KEY comes from .env.secrets.
|
# OPENROUTER_API_KEY comes from .env.secrets.
|
||||||
worker-ai:
|
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:
|
environment:
|
||||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||||
WORKER_TASKS: analyses
|
WORKER_TASKS: analyses
|
||||||
@@ -195,7 +196,7 @@ services:
|
|||||||
# The forum (docs/kozosseg.md): its own service on the same database and
|
# 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.
|
# login; switched on for the visitors by FORUM_URL in the frontend below.
|
||||||
forum:
|
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:
|
environment:
|
||||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||||
# The links in the forum's e-mails.
|
# The links in the forum's e-mails.
|
||||||
@@ -219,7 +220,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
|
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG_FRONTEND:-${TAG:-latest}}
|
||||||
environment:
|
environment:
|
||||||
BACKEND_URL: http://backend:8081
|
BACKEND_URL: http://backend:8081
|
||||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Heti horoszkóp
|
||||||
|
|
||||||
|
Ingyenes, személyes heti szöveg a tag saját képletéből és a hét égboltjából. Hétfőtől vasárnapig tart, magyar idő szerint.
|
||||||
|
|
||||||
|
## Az oldal
|
||||||
|
|
||||||
|
- **Saját oldala van:** `/heti-horoszkop`, a menüben a „Képletem” után. A saját képlet oldalán, az összefoglaló alatt egy kis kártya visz ide.
|
||||||
|
- **Egy hónap egyszerre:** a hetek a hétfőjük hónapjához tartoznak, legelöl a legújabb. A „Korábbi hónap” és „Újabb hónap” gomb lapoz (`?honap=2026-10`); csak olyan hónapra visz, amelyben van szöveg, és előre csak az aktuális hónapig.
|
||||||
|
- **Készül:** az aktuális hónapban az oldal egyszer kéri a heti szöveget (`POST /v1/weekly`), utána csak olvassa (`GET /v1/analyses/{id}`), amíg a worker megírja (kb. 20 másodperc); közben a hét kártyáján a várakozó animáció látszik, a hónap többi hete alatta. Ha nem sikerült, az oldal nem próbálja újra magától (minden próba fizetős AI-hívás); újratöltéskor egyszer újra megírja.
|
||||||
|
- **Kijelentkezve:** nyitóoldal belépés és regisztráció gombbal, és egy valódi példa heti horoszkóppal a példaelemzés kitalált képletéhez (`src/content/pelda-heti.json`, a helyi rendszerrel és ugyanazzal a modellel generálva). Előnézeti kép: `/kep/heti-horoszkop.png`.
|
||||||
|
- **Csak a megnézett hetek:** régebbi hétnek csak akkor van szövege, ha a tag azon a héten megnyitotta az oldalt. Visszamenőleg nem készül.
|
||||||
|
- API: `GET /v1/weekly/history?month=2026-11` → `{month, current_month, this_week, weeks: [{week_start, week_end, analysis}], older, newer, email}`. Minden saját képlet hetei számítanak, mert a születési adat közben változhatott.
|
||||||
|
|
||||||
|
## Hogyan készül
|
||||||
|
|
||||||
|
- **A hét égboltja:** a horoscope-api `POST /v1/week` végpontja (`astro_engine::week`). Tartalma:
|
||||||
|
- a bolygók (a Naptól a Plútóig) fényszögei a születési pontokhoz, 1°-os hatásfokkal, a pontos nappal;
|
||||||
|
- hol állnak a bolygók a hét elején (jegy, születési ház, retrográd);
|
||||||
|
- a Hold jegyváltásai, a fő holdfázisok, a bolygók irányváltásai és jegyváltásai.
|
||||||
|
|
||||||
|
A Hold fényszögei nincsenek benne, mert egy hét alatt minden pontot érint. A backend képletenként, születési adatonként és hetenként egyszer kéri le, és a `weekly_skies` táblába menti.
|
||||||
|
- **A szöveg:** egy `weekly` típusú elemzés (`analyses.week_start` a hétfő). Az összefoglaló olcsó modellje írja (az admin modellbeállításainál a „Tömör összefoglaló és heti horoszkóp”). Formája: cím, és 3 rövid bekezdés (150–220 szó): a hét fő témája, a kulcsnapok a hét napjainak nevével, és egy javaslat. Az admin promptszerkesztőben nem szerkeszthető.
|
||||||
|
- **Csak aki megnézi:** a szöveg akkor készül el, amikor a tag a héten először megnyitja a Heti horoszkóp oldalt (`POST /v1/weekly`). Így az AI-költség csak azokra jut, akik olvassák (egy szöveg kb. 1–1,5 Ft).
|
||||||
|
- **Értékelés:** a szöveg alatt ugyanaz a csillagos értékelés van, mint az elemzéseknél. Admin újraírathatja.
|
||||||
|
|
||||||
|
## Hétfői levél
|
||||||
|
|
||||||
|
- **Kinek:** minden tagnak, akinek van saját képlete, és nem kapcsolta ki (`users.weekly_email`, alapból bekapcsolva, a meglévő tagoknál is).
|
||||||
|
- **Mikor:** hétfőn 7 órától, hetente egyszer (`users.weekly_email_sent_on`). A worker `weekly` feladata 10 percenként nézi. Ha a worker egész hétfőn állt, az a hét kimarad.
|
||||||
|
- **Mi van benne:** csak annyi, hogy itt a heti horoszkóp, és egy gomb a Heti horoszkóp oldalra. A szöveget csak belépés után lehet elolvasni.
|
||||||
|
- **Kikapcsolás:**
|
||||||
|
- a Heti horoszkóp oldal alján lévő kapcsolóval;
|
||||||
|
- a Profil oldal „Levelek” részében;
|
||||||
|
- a levél alján lévő linkkel (`/ertesitesek?token=<users.email_token>`, belépés nélkül);
|
||||||
|
- a levelező saját „Leiratkozás” gombjával (RFC 8058, `POST /v1/public/weekly/unsubscribe`), ez csak ezt a levelet kapcsolja ki.
|
||||||
|
|
||||||
|
Az oldalon bekapcsolva az első levél a következő hétfőn jön, mert a heti szöveget a tag már látja.
|
||||||
|
|
||||||
|
## Értesítések oldal
|
||||||
|
|
||||||
|
Az `/ertesitesek?token=…` oldalon belépés nélkül beállítható minden olyan levél, amely nem egy lépéshez tartozik:
|
||||||
|
|
||||||
|
- a heti horoszkóp hétfői levele;
|
||||||
|
- fórumtagoknál a fórum levelei, ugyanazok a beállítások, mint a fórumprofilnál (válaszok, követett szálak, privát üzenetek, említések, kísérő értesítések, heti összefoglaló).
|
||||||
|
|
||||||
|
API: `GET` és `PUT /v1/public/notifications?token=`. A jelszóval, a vásárlással és a számlával kapcsolatos levelek mindig mennek. A „Mindenről leiratkozom” gomb mindent kikapcsol.
|
||||||
|
|
||||||
|
## Később
|
||||||
|
|
||||||
|
Ha a tagok rászoknak, előfizetéses lesz (havi és éves). Ehhez a `POST /v1/weekly` kap egy jogosultság-ellenőrzést; az oldal, a régi hetek és a hétfői levél maradhat.
|
||||||
+12
-6
@@ -157,7 +157,7 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több
|
|||||||
- **Napi „Mai égbolt” szál:** a worker reggel 5 órától nyitja meg az „Égbolt és képletek” témában, a backend nyilvános égboltjából (a Hold jegye és fázisa, jegyváltás, retrográd bolygók, a következő holdfázis), kötött magyar mondatokkal, AI nélkül. Egy napig ki van tűzve; a szerzője „Sorsfonalak”.
|
- **Napi „Mai égbolt” szál:** a worker reggel 5 órától nyitja meg az „Égbolt és képletek” témában, a backend nyilvános égboltjából (a Hold jegye és fázisa, jegyváltás, retrográd bolygók, a következő holdfázis), kötött magyar mondatokkal, AI nélkül. Egy napig ki van tűzve; a szerzője „Sorsfonalak”.
|
||||||
- **Önkéntes kísérők** (a Kereső rangtól; eredetileg „meghallgató”, a felhasználó átnevezte): „Kísérő” jelvény; a fórum főoldalán, a saját kártyájukon látják, hány meghallgatást kérő szál vár válaszra; e-mail, ha egy szál két órája vár (ha kérik, legfeljebb hatóránként egy).
|
- **Önkéntes kísérők** (a Kereső rangtól; eredetileg „meghallgató”, a felhasználó átnevezte): „Kísérő” jelvény; a fórum főoldalán, a saját kártyájukon látják, hány meghallgatást kérő szál vár válaszra; e-mail, ha egy szál két órája vár (ha kérik, legfeljebb hatóránként egy).
|
||||||
- **Említés:** „@Holdfény” (szóközös álnévvel is). Az említett tag követni kezdi a szálat, élőben és (ha kéri) e-mailben is értesül. Gépelés közben ajánló segít, az említés link a profilra.
|
- **Említés:** „@Holdfény” (szóközös álnévvel is). Az említett tag követni kezdi a szálat, élőben és (ha kéri) e-mailben is értesül. Gépelés közben ajánló segít, az említés link a profilra.
|
||||||
- **Saját avatar** a Kereső rangtól: 256×256-os JPEG lesz belőle, a kép rejtett adatai (EXIF) nélkül, a backenddel közös tárolóban (`crates/object-storage`, `forum-avatars/`). A moderátor visszaállíthatja a kezdő avatart. A fiók törlésekor a kép is törlődik.
|
- **Saját avatar** bárkinek (eredetileg a Kereső rangtól; 2026-11-26 óta minden tag): 256×256-os JPEG lesz belőle, a kép rejtett adatai (EXIF) nélkül, a backenddel közös tárolóban (`crates/object-storage`, `forum-avatars/`). A moderátor visszaállíthatja a kezdő avatart. A fiók törlésekor a kép is törlődik.
|
||||||
- **„Támogató” jelvény:** csak vásárlóknak, és csak ha bekapcsolják. Rangot nem ad.
|
- **„Támogató” jelvény:** csak vásárlóknak, és csak ha bekapcsolják. Rangot nem ad.
|
||||||
- **Zárt témák:** az admin a Moderálás → Témák fülön hoz létre és szerkeszt témát. A zárt témába a tag pár szóval jelentkezik, egy moderátor jóváhagyja vagy elutasítja, és később el is távolíthatja. Az elutasított jelentkezés azonnal törlődik (a moderálási naplóban marad nyoma).
|
- **Zárt témák:** az admin a Moderálás → Témák fülön hoz létre és szerkeszt témát. A zárt témába a tag pár szóval jelentkezik, egy moderátor jóváhagyja vagy elutasítja, és később el is távolíthatja. Az elutasított jelentkezés azonnal törlődik (a moderálási naplóban marad nyoma).
|
||||||
- **Csak tagoknak szóló témák:** a téma oldalán és a szál morzsamenüjében belépve is látszik, hogy kívülről és a keresőkből nem olvasható.
|
- **Csak tagoknak szóló témák:** a téma oldalán és a szál morzsamenüjében belépve is látszik, hogy kívülről és a keresőkből nem olvasható.
|
||||||
@@ -272,14 +272,14 @@ Rangnevek (javaslat): *Vándor → Kereső → Fonó → Csillagfonó → Sorsfo
|
|||||||
|
|
||||||
A rang egyben **jogosultsági szint** is: ettől függ, ki küldhet privát üzenetkérést, ki tölthet fel saját avatart, ki tehet be linket, és ki használhatja a ⌄ jelet.
|
A rang egyben **jogosultsági szint** is: ettől függ, ki küldhet privát üzenetkérést, ki tölthet fel saját avatart, ki tehet be linket, és ki használhatja a ⌄ jelet.
|
||||||
|
|
||||||
**A kezdő (Vándor) is nyithat szálat és hozzászólhat**, mert lehet, hogy épp segítségre van szüksége. A hozzászólásai nem várnak moderátori jóváhagyásra. **Privát üzenetet viszont nem kezdeményezhet.** Ha valaki más kérést küld neki, azt elfogadhatja. (az elfogadás javaslat)
|
**A kezdő (Vándor) is nyithat szálat és hozzászólhat**, mert lehet, hogy épp segítségre van szüksége. A hozzászólásai nem várnak moderátori jóváhagyásra. ~~Privát üzenetet viszont nem kezdeményezhet.~~ **2026-11-26 óta privát beszélgetést is kérhet az első naptól** (a felhasználó döntése; később korlátozható, a `messages.rs` `may_request` függvényében).
|
||||||
|
|
||||||
A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderátor, kísérő, támogató.
|
A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderátor, kísérő, támogató.
|
||||||
|
|
||||||
### Vásárlás és rang
|
### Vásárlás és rang
|
||||||
|
|
||||||
**A csomagvásárlás nem ad rangot.** A rang bizalmat jelent, ezért pénzért nem járhat, és a csalóknak is megérné egy olcsó csomagért hamarabb privát üzenetet írni. Helyette:
|
**A csomagvásárlás nem ad rangot.** A rang bizalmat jelent, ezért pénzért nem járhat, és a csalóknak is megérné egy olcsó csomagért hamarabb privát üzenetet írni. Helyette:
|
||||||
- **Feloldja a kezdő korlátokat** (napi hozzászólásszám, a szavazat beszámítása), mert aki fizetett, az szinte biztosan valódi ember. Privát üzenetkéréshez továbbra is rang kell.
|
- **Feloldja a kezdő korlátokat** (napi hozzászólásszám, a szavazat beszámítása), mert aki fizetett, az szinte biztosan valódi ember. (Privát üzenetkéréshez 2026-11-26 óta nem kell rang.)
|
||||||
- **„Támogató” jelvény,** amit a tag maga dönt el, hogy kiteszi-e. Alapból rejtve.
|
- **„Támogató” jelvény,** amit a tag maga dönt el, hogy kiteszi-e. Alapból rejtve.
|
||||||
|
|
||||||
## Profil és álnév
|
## Profil és álnév
|
||||||
@@ -299,14 +299,20 @@ A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderát
|
|||||||
|
|
||||||
- Egyelőre **egy** avatarja van mindenkinek.
|
- Egyelőre **egy** avatarja van mindenkinek.
|
||||||
- **Kezdő készlet:** néhány tucat generált kép. SVG-ben, a márka színeivel (holdfázisok, csillagképek, növények, szimbólumok), így tárolni sem kell őket. (az SVG javaslat)
|
- **Kezdő készlet:** néhány tucat generált kép. SVG-ben, a márka színeivel (holdfázisok, csillagképek, növények, szimbólumok), így tárolni sem kell őket. (az SVG javaslat)
|
||||||
- **Saját kép:** a DO Spacesbe kerül, a meglévő `services/backend/src/storage.rs` mintájára (privát tároló, a szolgáltatás adja ki, a Cloudflare tartja gyorsítótárban). Csak egy rang fölött tölthető fel, a moderátor egy kattintással visszaállíthatja. Feltöltéskor csak az első képkocka marad meg, animált avatar nincs. (javaslat)
|
- **Saját kép:** a DO Spacesbe kerül, a meglévő `services/backend/src/storage.rs` mintájára (privát tároló, a szolgáltatás adja ki, a Cloudflare tartja gyorsítótárban). 2026-11-26 óta bárki feltölthet (az álnév első mentése után); a moderátor egy kattintással visszaállíthatja. Feltöltéskor csak az első képkocka marad meg, animált avatar nincs. (javaslat)
|
||||||
|
|
||||||
## Média
|
## Média
|
||||||
|
|
||||||
- **GIF nincs.**
|
- **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.
|
- **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)
|
- **Videó:** YouTube-linknél előnézet; asztali gépen helyben lejátszható, mobilon a YouTube-appot nyitja.
|
||||||
- **Kép:** az elején nincs, később hozzászólásonként legfeljebb egy, rang fölött, kis méretben. (javaslat)
|
- **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)
|
- Az aláírás csak szöveg lehet. (javaslat)
|
||||||
|
|
||||||
## Privát üzenetek
|
## Privát üzenetek
|
||||||
|
|||||||
@@ -45,7 +45,8 @@ impl Function {
|
|||||||
|
|
||||||
pub fn of(kind: Kind) -> Function {
|
pub fn of(kind: Kind) -> Function {
|
||||||
match kind {
|
match kind {
|
||||||
Kind::Summary => Function::Summary,
|
// The weekly horoscope is written by the summary's (cheaper) model.
|
||||||
|
Kind::Summary | Kind::Weekly => Function::Summary,
|
||||||
Kind::Question => Function::Question,
|
Kind::Question => Function::Question,
|
||||||
Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis,
|
Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
|||||||
.await?;
|
.await?;
|
||||||
let replies = super::feedback::unseen_replies(&mut conn, auth.id()).await?;
|
let replies = super::feedback::unseen_replies(&mut conn, auth.id()).await?;
|
||||||
let nps_due = super::feedback::nps_due(&mut conn, auth.id()).await?;
|
let nps_due = super::feedback::nps_due(&mut conn, auth.id()).await?;
|
||||||
|
let weekly_email: bool = sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1")
|
||||||
|
.bind(auth.id())
|
||||||
|
.fetch_one(&mut *conn)
|
||||||
|
.await?;
|
||||||
Ok(Json(json!({
|
Ok(Json(json!({
|
||||||
"user": UserView::from(&auth.user),
|
"user": UserView::from(&auth.user),
|
||||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||||
@@ -59,6 +63,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
|||||||
"feedback_replies_unseen": replies,
|
"feedback_replies_unseen": replies,
|
||||||
// Ask the "would you recommend us?" question now.
|
// Ask the "would you recommend us?" question now.
|
||||||
"nps_due": nps_due,
|
"nps_due": nps_due,
|
||||||
|
// Monday's e-mail about the weekly horoscope is on.
|
||||||
|
"weekly_email": weekly_email,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,6 +175,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
|
|||||||
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
||||||
"user": UserView::from(&auth.user),
|
"user": UserView::from(&auth.user),
|
||||||
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
||||||
|
"weekly_horoscope_email": rows("SELECT json_build_object('on', weekly_email, 'last_sent_for_week', weekly_email_sent_on) FROM users WHERE id = $1").await?.into_iter().next(),
|
||||||
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
||||||
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
||||||
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1 AND kind <> 'celebrity'").await?,
|
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1 AND kind <> 'celebrity'").await?,
|
||||||
@@ -181,6 +188,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?,
|
"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.
|
// 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_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_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_posts": rows("SELECT json_build_object('id', p.id, 'thread_id', p.thread_id, 'thread_title', th.title, 'opening', p.is_opening, 'body', p.body, 'created_at', p.created_at, 'edited_at', p.edited_at, 'removed_at', p.deleted_at, 'removal_reason', p.delete_reason) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.author_id = $1 ORDER BY p.id").await?,
|
||||||
"forum_reactions": rows("SELECT json_build_object('post_id', post_id, 'kind', kind, 'created_at', created_at) FROM forum.reactions WHERE user_id = $1 ORDER BY created_at").await?,
|
"forum_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 +266,15 @@ pub async fn delete_me(
|
|||||||
.bind(auth.id())
|
.bind(auth.id())
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.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")
|
let avatar: Option<String> = sqlx::query_scalar("SELECT avatar FROM forum.members WHERE user_id = $1")
|
||||||
.bind(auth.id())
|
.bind(auth.id())
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_optional(&mut *tx)
|
||||||
.await?;
|
.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?;
|
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
if let (Some(file), Some(storage)) = (avatar.as_deref().and_then(|a| a.strip_prefix("upload:")), &state.storage)
|
if let (Some(file), Some(storage)) = (avatar.as_deref().and_then(|a| a.strip_prefix("upload:")), &state.storage)
|
||||||
@@ -270,6 +282,13 @@ pub async fn delete_me(
|
|||||||
{
|
{
|
||||||
tracing::warn!(error = %e, "removing a deleted account's forum avatar");
|
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");
|
tracing::info!(user = %auth.id(), "account deleted");
|
||||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
//! instead, free of charge, so the same chart is never paid for twice.
|
//! instead, free of charge, so the same chart is never paid for twice.
|
||||||
//!
|
//!
|
||||||
//! Every saved chart also gets a free short summary (`summary` kind, written
|
//! Every saved chart also gets a free short summary (`summary` kind, written
|
||||||
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
|
//! by `SUMMARY_MODEL`); the detailed analyses are paid. The own chart's free
|
||||||
|
//! weekly horoscope (`weekly` kind, see [`super::weekly`]) uses the summary's model.
|
||||||
|
|
||||||
use analysis_prompt::Kind;
|
use analysis_prompt::Kind;
|
||||||
use axum::Json;
|
use axum::Json;
|
||||||
@@ -18,7 +19,7 @@ use axum_extra::extract::WithRejection;
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use time::OffsetDateTime;
|
use time::{Date, OffsetDateTime};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::auth::validate_locale;
|
use super::auth::validate_locale;
|
||||||
@@ -53,11 +54,14 @@ pub struct AnalysisRow {
|
|||||||
pub next_attempt_at: OffsetDateTime,
|
pub next_attempt_at: OffsetDateTime,
|
||||||
/// When the current text was asked for (set again by a regeneration).
|
/// When the current text was asked for (set again by a regeneration).
|
||||||
pub requested_at: OffsetDateTime,
|
pub requested_at: OffsetDateTime,
|
||||||
|
/// The Monday of a weekly horoscope.
|
||||||
|
pub week_start: Option<Date>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
|
pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
|
||||||
content, error, \
|
content, error, \
|
||||||
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at";
|
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at, \
|
||||||
|
week_start";
|
||||||
|
|
||||||
impl AnalysisRow {
|
impl AnalysisRow {
|
||||||
pub fn view(&self) -> Value {
|
pub fn view(&self) -> Value {
|
||||||
@@ -78,6 +82,7 @@ impl AnalysisRow {
|
|||||||
"attempts": self.attempts,
|
"attempts": self.attempts,
|
||||||
"next_attempt_at": rfc3339(self.next_attempt_at),
|
"next_attempt_at": rfc3339(self.next_attempt_at),
|
||||||
"requested_at": rfc3339(self.requested_at),
|
"requested_at": rfc3339(self.requested_at),
|
||||||
|
"week_start": self.week_start.map(|d| d.to_string()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -143,6 +148,12 @@ pub(super) enum Target {
|
|||||||
chart_id: Uuid,
|
chart_id: Uuid,
|
||||||
hash: String,
|
hash: String,
|
||||||
},
|
},
|
||||||
|
/// The own chart's weekly horoscope (free); `hash` covers the chart and the week.
|
||||||
|
Weekly {
|
||||||
|
chart_id: Uuid,
|
||||||
|
hash: String,
|
||||||
|
week_start: Date,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn request(
|
async fn request(
|
||||||
@@ -197,6 +208,11 @@ pub(super) async fn queue(
|
|||||||
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
|
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
|
||||||
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
|
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
|
||||||
Target::Celebrity { chart_id, hash } => ("celebrity", hash, Some(*chart_id), None, None),
|
Target::Celebrity { chart_id, hash } => ("celebrity", hash, Some(*chart_id), None, None),
|
||||||
|
Target::Weekly { chart_id, hash, .. } => ("weekly", hash, Some(*chart_id), None, None),
|
||||||
|
};
|
||||||
|
let week_start = match target {
|
||||||
|
Target::Weekly { week_start, .. } => Some(*week_start),
|
||||||
|
_ => None,
|
||||||
};
|
};
|
||||||
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?;
|
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?;
|
||||||
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
|
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
|
||||||
@@ -225,8 +241,9 @@ pub(super) async fn queue(
|
|||||||
let insert = format!(
|
let insert = format!(
|
||||||
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
|
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
|
||||||
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \
|
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \
|
||||||
forecast_id, fallback_model) \
|
forecast_id, fallback_model, week_start) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING {ANALYSIS_COLUMNS}"
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
|
||||||
|
RETURNING {ANALYSIS_COLUMNS}"
|
||||||
);
|
);
|
||||||
let id = Uuid::now_v7();
|
let id = Uuid::now_v7();
|
||||||
|
|
||||||
@@ -263,6 +280,7 @@ pub(super) async fn queue(
|
|||||||
.bind(OffsetDateTime::now_utc())
|
.bind(OffsetDateTime::now_utc())
|
||||||
.bind(forecast_id)
|
.bind(forecast_id)
|
||||||
.bind(fallback)
|
.bind(fallback)
|
||||||
|
.bind(week_start)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
@@ -288,6 +306,7 @@ pub(super) async fn queue(
|
|||||||
.bind(None::<OffsetDateTime>)
|
.bind(None::<OffsetDateTime>)
|
||||||
.bind(forecast_id)
|
.bind(forecast_id)
|
||||||
.bind(fallback)
|
.bind(fallback)
|
||||||
|
.bind(week_start)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
if let Some(unit) = unit {
|
if let Some(unit) = unit {
|
||||||
@@ -395,6 +414,14 @@ pub async fn request_for_forecast(
|
|||||||
/// The hash of what the analysis is about (chart, comparison or forecast),
|
/// The hash of what the analysis is about (chart, comparison or forecast),
|
||||||
/// part of its cache key; `None` when that was deleted.
|
/// part of its cache key; `None` when that was deleted.
|
||||||
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
|
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
|
||||||
|
if row.kind == "weekly" {
|
||||||
|
let hash: Option<String> = sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
|
||||||
|
.bind(row.chart_id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
let week = row.week_start.map(|d| d.to_string()).unwrap_or_default();
|
||||||
|
return Ok(hash.map(|h| super::weekly::target_hash(&h, &week)));
|
||||||
|
}
|
||||||
let (query, id) = match row.kind.as_str() {
|
let (query, id) = match row.kind.as_str() {
|
||||||
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
|
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
|
||||||
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
|
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
|
||||||
|
|||||||
@@ -349,7 +349,8 @@ async fn corrected_birth(
|
|||||||
// The user's own comparisons with the person are deleted on correction (they
|
// The user's own comparisons with the person are deleted on correction (they
|
||||||
// no longer match), unless a paid analysis was written for one of them.
|
// no longer match), unless a paid analysis was written for one of them.
|
||||||
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
|
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
|
||||||
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \
|
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind NOT IN ('summary', 'weekly') \
|
||||||
|
AND status <> 'failed') \
|
||||||
OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \
|
OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \
|
||||||
WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed') \
|
WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed') \
|
||||||
OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \
|
OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ pub const TAGS: [&str; 10] = [
|
|||||||
"useful",
|
"useful",
|
||||||
];
|
];
|
||||||
/// What can be rated (analysis kinds, and answers to questions).
|
/// What can be rated (analysis kinds, and answers to questions).
|
||||||
const RATED_KINDS: [&str; 5] = ["summary", "natal", "synastry", "forecast", "tarot"];
|
const RATED_KINDS: [&str; 6] = ["summary", "natal", "synastry", "forecast", "tarot", "weekly"];
|
||||||
const MAX_COMMENT: usize = 1000;
|
const MAX_COMMENT: usize = 1000;
|
||||||
const MAX_MESSAGE: usize = 2000;
|
const MAX_MESSAGE: usize = 2000;
|
||||||
const MAX_REPLY: usize = 4000;
|
const MAX_REPLY: usize = 4000;
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ mod invitations;
|
|||||||
mod invoices_user;
|
mod invoices_user;
|
||||||
mod jobs;
|
mod jobs;
|
||||||
mod models;
|
mod models;
|
||||||
|
mod notifications;
|
||||||
pub(crate) mod payments;
|
pub(crate) mod payments;
|
||||||
mod promo;
|
mod promo;
|
||||||
mod prompts;
|
mod prompts;
|
||||||
@@ -29,6 +30,7 @@ mod shares;
|
|||||||
pub mod sky;
|
pub mod sky;
|
||||||
mod synastries;
|
mod synastries;
|
||||||
mod tarot;
|
mod tarot;
|
||||||
|
mod weekly;
|
||||||
|
|
||||||
pub use recalculate::run as recalculate;
|
pub use recalculate::run as recalculate;
|
||||||
|
|
||||||
@@ -36,7 +38,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||||
use axum::http::{HeaderValue, Method, header};
|
use axum::http::{HeaderValue, Method, header};
|
||||||
use axum::routing::{delete, get, patch, post};
|
use axum::routing::{delete, get, patch, post, put};
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
use axum_extra::extract::WithRejection;
|
use axum_extra::extract::WithRejection;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -101,6 +103,9 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
||||||
.route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
|
.route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
|
||||||
.route("/v1/charts/{id}/summary", post(analyses::summary_for_chart))
|
.route("/v1/charts/{id}/summary", post(analyses::summary_for_chart))
|
||||||
|
.route("/v1/weekly", post(weekly::current))
|
||||||
|
.route("/v1/weekly/email", put(weekly::set_email))
|
||||||
|
.route("/v1/weekly/history", get(weekly::history))
|
||||||
.route("/v1/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create))
|
.route("/v1/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create))
|
||||||
.route("/v1/forecasts/{id}", get(forecasts::get_one))
|
.route("/v1/forecasts/{id}", get(forecasts::get_one))
|
||||||
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
|
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
|
||||||
@@ -145,6 +150,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
|
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
|
||||||
.route("/v1/public/invites/{token}", get(synastries::public_invite))
|
.route("/v1/public/invites/{token}", get(synastries::public_invite))
|
||||||
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
||||||
|
.route("/v1/public/weekly/unsubscribe", post(weekly::unsubscribe))
|
||||||
|
.route("/v1/public/notifications", get(notifications::get_settings).put(notifications::put_settings))
|
||||||
.route("/v1/public/invitations/{token}", get(invitations::public_view))
|
.route("/v1/public/invitations/{token}", get(invitations::public_view))
|
||||||
.route("/v1/public/waitlist", post(invitations::join_waitlist))
|
.route("/v1/public/waitlist", post(invitations::join_waitlist))
|
||||||
.route("/v1/public/chart", post(calculator::chart))
|
.route("/v1/public/chart", post(calculator::chart))
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
//! The page of every e-mail setting, opened from an e-mail's footer with the
|
||||||
|
//! user's `email_token` (no login needed): Monday's weekly horoscope e-mail
|
||||||
|
//! and, for forum members, the forum's e-mails (the same settings as on the
|
||||||
|
//! forum profile). The e-mails that belong to something the user does
|
||||||
|
//! (password, purchase, invoice) always go, so they are not listed.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Query, State};
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::{Body, St};
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct TokenQuery {
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn user_of(state: &AppState, token: &str) -> Result<Uuid, ApiError> {
|
||||||
|
let token = Uuid::parse_str(token.trim()).map_err(|_| ApiError::NotFound("token"))?;
|
||||||
|
let user: Option<Uuid> =
|
||||||
|
sqlx::query_scalar("SELECT id FROM users WHERE email_token = $1").bind(token).fetch_optional(&state.db).await?;
|
||||||
|
user.ok_or(ApiError::NotFound("token"))
|
||||||
|
}
|
||||||
|
|
||||||
|
type ForumRow = (String, String, String, String, String, bool, bool);
|
||||||
|
|
||||||
|
async fn settings(state: &AppState, user: Uuid) -> Result<Value, ApiError> {
|
||||||
|
let weekly: bool =
|
||||||
|
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await?;
|
||||||
|
let forum: Option<ForumRow> = sqlx::query_as(
|
||||||
|
"SELECT email_replies, email_followed, email_messages, email_mentions, email_listener, email_weekly, listener \
|
||||||
|
FROM forum.members WHERE user_id = $1",
|
||||||
|
)
|
||||||
|
.bind(user)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(json!({
|
||||||
|
"weekly_horoscope": weekly,
|
||||||
|
"forum": forum.map(|(replies, followed, messages, mentions, listener_mail, weekly, listener)| json!({
|
||||||
|
"replies": replies,
|
||||||
|
"followed": followed,
|
||||||
|
"messages": messages,
|
||||||
|
"mentions": mentions,
|
||||||
|
// Only volunteer listeners get these.
|
||||||
|
"listener": listener.then_some(listener_mail),
|
||||||
|
"weekly": weekly,
|
||||||
|
})),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_settings(
|
||||||
|
State(state): St,
|
||||||
|
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let user = user_of(&state, &q.token).await?;
|
||||||
|
Ok(Json(settings(&state, user).await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Settings {
|
||||||
|
weekly_horoscope: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
forum: Option<ForumSettings>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct ForumSettings {
|
||||||
|
replies: String,
|
||||||
|
followed: String,
|
||||||
|
messages: String,
|
||||||
|
mentions: String,
|
||||||
|
#[serde(default)]
|
||||||
|
listener: Option<String>,
|
||||||
|
weekly: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn one_of(value: &str, allowed: &[&str], what: &str) -> Result<(), ApiError> {
|
||||||
|
if allowed.contains(&value) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ApiError::BadRequest(format!("{what} must be one of {}", allowed.join(", "))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn put_settings(
|
||||||
|
State(state): St,
|
||||||
|
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||||
|
WithRejection(Json(req), _): Body<Settings>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let user = user_of(&state, &q.token).await?;
|
||||||
|
if let Some(f) = &req.forum {
|
||||||
|
one_of(&f.replies, &["off", "daily", "instant"], "replies")?;
|
||||||
|
one_of(&f.followed, &["off", "daily"], "followed")?;
|
||||||
|
one_of(&f.messages, &["off", "instant"], "messages")?;
|
||||||
|
one_of(&f.mentions, &["off", "instant"], "mentions")?;
|
||||||
|
if let Some(l) = &f.listener {
|
||||||
|
one_of(l, &["off", "instant"], "listener")?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
// As the switch on the site: turned on again, the first one comes next Monday.
|
||||||
|
sqlx::query(&super::weekly::switch_sql()).bind(user).bind(req.weekly_horoscope).execute(&mut *tx).await?;
|
||||||
|
if let Some(f) = &req.forum {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE forum.members SET email_replies = $2, email_followed = $3, email_messages = $4, \
|
||||||
|
email_mentions = $5, email_listener = coalesce($6, email_listener), email_weekly = $7 \
|
||||||
|
WHERE user_id = $1",
|
||||||
|
)
|
||||||
|
.bind(user)
|
||||||
|
.bind(&f.replies)
|
||||||
|
.bind(&f.followed)
|
||||||
|
.bind(&f.messages)
|
||||||
|
.bind(&f.mentions)
|
||||||
|
.bind(&f.listener)
|
||||||
|
.bind(f.weekly)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Json(settings(&state, user).await?))
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
//! The free weekly horoscope of the member's own chart: the week's sky (from
|
||||||
|
//! the horoscope service, stored per chart and week in `weekly_skies`) and its
|
||||||
|
//! text (an analysis of kind `weekly`, written by the summary's model). It is
|
||||||
|
//! asked for when the weekly horoscope page opens, so it is only written for
|
||||||
|
//! those who look; Monday's e-mail (worker; on unless turned off) says no
|
||||||
|
//! more than that it is there. The page shows one month at a time, the
|
||||||
|
//! newest week first ([`history`]).
|
||||||
|
//!
|
||||||
|
//! Weeks run from Monday to Sunday, Hungarian time.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Query, State};
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::Date;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue};
|
||||||
|
use super::charts::{ChartRow, owned_chart};
|
||||||
|
use super::{Body, St};
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::auth::AuthUser;
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
|
||||||
|
/// The Monday of the current week in Hungary.
|
||||||
|
pub(super) const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date";
|
||||||
|
|
||||||
|
/// What a weekly text is about, for its cache key: the chart and the week.
|
||||||
|
pub fn target_hash(chart_hash: &str, week_start: &str) -> String {
|
||||||
|
format!("{chart_hash}|week|{week_start}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The week's sky on the chart, calculated once per chart, birth data and week.
|
||||||
|
async fn ensure_sky(state: &AppState, chart: &ChartRow, week: Date) -> Result<(), ApiError> {
|
||||||
|
let (exists,): (bool,) = sqlx::query_as(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM weekly_skies WHERE chart_id = $1 AND chart_hash = $2 AND week_start = $3)",
|
||||||
|
)
|
||||||
|
.bind(chart.id)
|
||||||
|
.bind(&chart.chart_hash)
|
||||||
|
.bind(week)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
if exists {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut result = state.horoscope.week(&json!({ "birth": chart.birth_data, "start": week.to_string() })).await?;
|
||||||
|
if let Some(obj) = result.as_object_mut() {
|
||||||
|
obj.remove("meta");
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO weekly_skies (chart_id, chart_hash, week_start, result) VALUES ($1, $2, $3, $4) \
|
||||||
|
ON CONFLICT DO NOTHING",
|
||||||
|
)
|
||||||
|
.bind(chart.id)
|
||||||
|
.bind(&chart.chart_hash)
|
||||||
|
.bind(week)
|
||||||
|
.bind(&result)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn weekly_email(state: &AppState, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||||
|
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This week's horoscope of the own chart: queued if it does not exist yet
|
||||||
|
/// (or the last attempt failed); the page polls this until it is written.
|
||||||
|
pub async fn current(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||||
|
let chart_id: Option<Uuid> = sqlx::query_scalar("SELECT id FROM charts WHERE owner_id = $1 AND is_primary")
|
||||||
|
.bind(auth.id())
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
let chart = owned_chart(&state.db, chart_id.ok_or(ApiError::NotFound("chart"))?, auth.id()).await?;
|
||||||
|
let week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?;
|
||||||
|
ensure_sky(&state, &chart, week).await?;
|
||||||
|
let target = Target::Weekly {
|
||||||
|
chart_id: chart.id,
|
||||||
|
hash: target_hash(&chart.chart_hash, &week.to_string()),
|
||||||
|
week_start: week,
|
||||||
|
};
|
||||||
|
let (_, row) = queue(&state, auth.id(), &target, &auth.user.locale, None).await?;
|
||||||
|
let end = week.saturating_add(time::Duration::days(6));
|
||||||
|
Ok(Json(json!({
|
||||||
|
"week_start": week.to_string(),
|
||||||
|
"week_end": end.to_string(),
|
||||||
|
"analysis": row.view(),
|
||||||
|
"email": weekly_email(&state, auth.id()).await?,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "2026-11".
|
||||||
|
fn month_key(date: Date) -> String {
|
||||||
|
format!("{:04}-{:02}", date.year(), u8::from(date.month()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first day of a "2026-11" month.
|
||||||
|
fn month_start(key: &str) -> Option<Date> {
|
||||||
|
let (y, m) = key.split_once('-')?;
|
||||||
|
let month = time::Month::try_from(m.parse::<u8>().ok()?).ok()?;
|
||||||
|
Date::from_calendar_date(y.parse().ok()?, month, 1).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_month(first: Date) -> Date {
|
||||||
|
let (y, m) = (first.year(), first.month());
|
||||||
|
let y = if m == time::Month::December { y + 1 } else { y };
|
||||||
|
Date::from_calendar_date(y, m.next(), 1).expect("the first of a month")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct MonthQuery {
|
||||||
|
/// "2026-11"; this month by default.
|
||||||
|
month: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One month of the member's weekly horoscopes (weeks counted by their
|
||||||
|
/// Monday), the newest first, and the months before and after that have any.
|
||||||
|
/// Only weeks the member opened have a text.
|
||||||
|
pub async fn history(
|
||||||
|
State(state): St,
|
||||||
|
auth: AuthUser,
|
||||||
|
WithRejection(Query(q), _): WithRejection<Query<MonthQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let this_week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?;
|
||||||
|
let current = month_start(&month_key(this_week)).expect("a valid month");
|
||||||
|
let first = match q.month.as_deref() {
|
||||||
|
Some(m) => month_start(m).ok_or_else(|| ApiError::BadRequest("month must look like 2026-11".into()))?,
|
||||||
|
None => current,
|
||||||
|
}
|
||||||
|
.min(current);
|
||||||
|
let next = next_month(first);
|
||||||
|
// Every own chart counts: the birth data may have changed meanwhile.
|
||||||
|
const MINE: &str = "kind = 'weekly' AND chart_id IN (SELECT id FROM charts WHERE owner_id = $1 AND kind = 'own')";
|
||||||
|
let rows: Vec<AnalysisRow> = sqlx::query_as(&format!(
|
||||||
|
"SELECT DISTINCT ON (week_start) {ANALYSIS_COLUMNS} FROM analyses \
|
||||||
|
WHERE {MINE} AND week_start >= $2 AND week_start < $3 \
|
||||||
|
ORDER BY week_start DESC, (status = 'done') DESC, created_at DESC"
|
||||||
|
))
|
||||||
|
.bind(auth.id())
|
||||||
|
.bind(first)
|
||||||
|
.bind(next)
|
||||||
|
.fetch_all(&state.db)
|
||||||
|
.await?;
|
||||||
|
let (older, newer): (Option<Date>, Option<Date>) = sqlx::query_as(&format!(
|
||||||
|
"SELECT (SELECT max(week_start) FROM analyses WHERE {MINE} AND week_start < $2), \
|
||||||
|
(SELECT min(week_start) FROM analyses WHERE {MINE} AND week_start >= $3)"
|
||||||
|
))
|
||||||
|
.bind(auth.id())
|
||||||
|
.bind(first)
|
||||||
|
.bind(next)
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
// This month always has a page (its week is written when it opens).
|
||||||
|
let newer = newer.map(month_key).or_else(|| (first < current).then(|| month_key(current)));
|
||||||
|
let weeks: Vec<Value> = rows
|
||||||
|
.iter()
|
||||||
|
.filter_map(|r| {
|
||||||
|
let start = r.week_start?;
|
||||||
|
Some(json!({
|
||||||
|
"week_start": start.to_string(),
|
||||||
|
"week_end": start.saturating_add(time::Duration::days(6)).to_string(),
|
||||||
|
"analysis": r.view(),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(Json(json!({
|
||||||
|
"month": month_key(first),
|
||||||
|
"current_month": month_key(current),
|
||||||
|
"this_week": this_week.to_string(),
|
||||||
|
"weeks": weeks,
|
||||||
|
"older": older.map(month_key),
|
||||||
|
"newer": newer,
|
||||||
|
"email": weekly_email(&state, auth.id()).await?,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EmailSwitch {
|
||||||
|
on: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turns Monday's e-mail on or off. Turned on, the first one comes next
|
||||||
|
/// Monday (this week's horoscope is already in front of the member).
|
||||||
|
pub(super) fn switch_sql() -> String {
|
||||||
|
// Only a change from off to on moves the date: saving "on" again must not
|
||||||
|
// hold back this Monday's e-mail.
|
||||||
|
format!(
|
||||||
|
"UPDATE users SET \
|
||||||
|
weekly_email_sent_on = CASE WHEN $2 AND NOT weekly_email \
|
||||||
|
THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \
|
||||||
|
ELSE weekly_email_sent_on END, \
|
||||||
|
weekly_email = $2, updated_at = now() \
|
||||||
|
WHERE id = $1"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_email(
|
||||||
|
State(state): St,
|
||||||
|
auth: AuthUser,
|
||||||
|
WithRejection(Json(req), _): Body<EmailSwitch>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
sqlx::query(&switch_sql()).bind(auth.id()).bind(req.on).execute(&state.db).await?;
|
||||||
|
Ok(Json(json!({ "email": req.on })))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct TokenQuery {
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "No more weekly horoscope e-mails", straight from the mail client's
|
||||||
|
/// unsubscribe button (RFC 8058 one-click POST); the footer link opens the
|
||||||
|
/// page of every e-mail setting ([`super::notifications`]). No login needed.
|
||||||
|
pub async fn unsubscribe(
|
||||||
|
State(state): St,
|
||||||
|
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let token = Uuid::parse_str(q.token.trim()).map_err(|_| ApiError::NotFound("token"))?;
|
||||||
|
let done = sqlx::query("UPDATE users SET weekly_email = false, updated_at = now() WHERE email_token = $1")
|
||||||
|
.bind(token)
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
if done.rows_affected() == 0 {
|
||||||
|
return Err(ApiError::NotFound("token"));
|
||||||
|
}
|
||||||
|
Ok(Json(json!({ "unsubscribed": true })))
|
||||||
|
}
|
||||||
@@ -90,6 +90,23 @@ async fn fake_forecast(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Calls of the fake week endpoint (only `weekly_horoscope_of_the_own_chart` uses it).
|
||||||
|
static WEEK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
|
||||||
|
async fn fake_week(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
||||||
|
WEEK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let start = body["start"].as_str().unwrap_or("2026-11-30").to_string();
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
Json(json!({
|
||||||
|
"timezone": "Europe/Budapest",
|
||||||
|
"week": {"start": start, "end": "?", "contacts": [], "positions": [], "moon_sign": "leo",
|
||||||
|
"moon_ingresses": [], "ingresses": [], "lunations": [], "stations": []},
|
||||||
|
"meta": {}
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Calls of the fake sky endpoints (only `the_sky_is_shared_and_kept` uses them).
|
/// Calls of the fake sky endpoints (only `the_sky_is_shared_and_kept` uses them).
|
||||||
static SKY_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
static SKY_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
|
||||||
@@ -254,6 +271,7 @@ async fn fake_services_with(s3: FakeS3) -> String {
|
|||||||
)
|
)
|
||||||
.route("/v1/synastry", post(fake_synastry))
|
.route("/v1/synastry", post(fake_synastry))
|
||||||
.route("/v1/forecast", post(fake_forecast))
|
.route("/v1/forecast", post(fake_forecast))
|
||||||
|
.route("/v1/week", post(fake_week))
|
||||||
.route(
|
.route(
|
||||||
"/v1/sky",
|
"/v1/sky",
|
||||||
get(|| async {
|
get(|| async {
|
||||||
@@ -1107,7 +1125,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
|||||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||||
/// logged-in user, so other apps cannot use them.
|
/// logged-in user, so other apps cannot use them.
|
||||||
const PUBLIC_ROUTES: [&str; 24] = [
|
const PUBLIC_ROUTES: [&str; 26] = [
|
||||||
"/healthz",
|
"/healthz",
|
||||||
// Stripe calls it; the signature proves it.
|
// Stripe calls it; the signature proves it.
|
||||||
"/v1/payments/stripe/webhook",
|
"/v1/payments/stripe/webhook",
|
||||||
@@ -1123,6 +1141,9 @@ const PUBLIC_ROUTES: [&str; 24] = [
|
|||||||
"/v1/public/shares/{slug}/visit",
|
"/v1/public/shares/{slug}/visit",
|
||||||
"/v1/public/invites/{token}",
|
"/v1/public/invites/{token}",
|
||||||
"/v1/public/invitations/unsubscribe",
|
"/v1/public/invitations/unsubscribe",
|
||||||
|
// The e-mail settings behind an e-mail's footer link: the token stands for the login.
|
||||||
|
"/v1/public/weekly/unsubscribe",
|
||||||
|
"/v1/public/notifications",
|
||||||
"/v1/public/invitations/{token}",
|
"/v1/public/invitations/{token}",
|
||||||
"/v1/public/waitlist",
|
"/v1/public/waitlist",
|
||||||
// The public birth chart (limited per visitor address).
|
// The public birth chart (limited per visitor address).
|
||||||
@@ -1957,6 +1978,155 @@ async fn invitation_only_signup(pool: PgPool) {
|
|||||||
assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta");
|
assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn weekly_horoscope_of_the_own_chart(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool.clone()).await;
|
||||||
|
let anna = app.register("anna@example.com", "Anna").await;
|
||||||
|
let bob = app.register("bob@example.com", "Bob").await;
|
||||||
|
// No own chart yet: nothing to write it from.
|
||||||
|
assert_eq!(app.call("POST", "/v1/weekly", Some(&bob), None).await.status, StatusCode::NOT_FOUND);
|
||||||
|
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||||
|
|
||||||
|
let calls = WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let r = app.call("POST", "/v1/weekly", Some(&anna), None).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
let parts: Vec<i32> = r.body["week_start"].as_str().unwrap().split('-').map(|p| p.parse().unwrap()).collect();
|
||||||
|
let month = time::Month::try_from(parts[1] as u8).unwrap();
|
||||||
|
let start = time::Date::from_calendar_date(parts[0], month, parts[2] as u8).unwrap();
|
||||||
|
assert_eq!(start.weekday(), time::Weekday::Monday);
|
||||||
|
assert_eq!(r.body["week_end"], start.saturating_add(time::Duration::days(6)).to_string());
|
||||||
|
let a = &r.body["analysis"];
|
||||||
|
assert_eq!((a["kind"].as_str(), a["status"].as_str()), (Some("weekly"), Some("pending")));
|
||||||
|
assert_eq!((a["chart_id"].as_str(), a["credits_charged"].as_i64()), (chart["id"].as_str(), Some(0)));
|
||||||
|
assert_eq!(a["week_start"], r.body["week_start"]);
|
||||||
|
// On by default.
|
||||||
|
assert_eq!(r.body["email"], true);
|
||||||
|
// Asked again: the same text, the sky calculated once.
|
||||||
|
let again = app.call("POST", "/v1/weekly", Some(&anna), None).await.body;
|
||||||
|
assert_eq!(again["analysis"]["id"], a["id"]);
|
||||||
|
assert_eq!(WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed), calls + 1);
|
||||||
|
// Written by the summary's model; not among the chart's analyses on its page, but listed.
|
||||||
|
let (weekly_model, summary_model): (String, String) = sqlx::query_as(
|
||||||
|
"SELECT w.model, s.model FROM analyses w JOIN analyses s ON s.chart_id = w.chart_id AND s.kind = 'summary' \
|
||||||
|
WHERE w.kind = 'weekly'",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(weekly_model, summary_model);
|
||||||
|
|
||||||
|
// The page: one month at a time, the newest week first; older months page back.
|
||||||
|
let month = app.get("/v1/weekly/history", Some(&anna)).await.body;
|
||||||
|
assert_eq!(month["month"], month["current_month"]);
|
||||||
|
assert_eq!(month["this_week"], r.body["week_start"]);
|
||||||
|
assert_eq!(month["weeks"].as_array().unwrap().len(), 1);
|
||||||
|
assert_eq!(month["weeks"][0]["analysis"]["id"], a["id"]);
|
||||||
|
assert_eq!((month["older"].is_null(), month["newer"].is_null()), (true, true));
|
||||||
|
let old_week = start.saturating_sub(time::Duration::days(35));
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, status, \
|
||||||
|
content, credits_charged, week_start) \
|
||||||
|
SELECT $1, 'weekly', c.id, c.owner_id, 'hu', 'm', 'v3', 'old', 'done', '{\"title\": \"Régi hét\"}', 0, $2 \
|
||||||
|
FROM charts c WHERE c.id = $3",
|
||||||
|
)
|
||||||
|
.bind(uuid::Uuid::now_v7())
|
||||||
|
.bind(old_week)
|
||||||
|
.bind(uuid::Uuid::parse_str(chart["id"].as_str().unwrap()).unwrap())
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let older_key = format!("{:04}-{:02}", old_week.year(), u8::from(old_week.month()));
|
||||||
|
let month = app.get("/v1/weekly/history", Some(&anna)).await.body;
|
||||||
|
assert_eq!(month["older"], older_key);
|
||||||
|
let back = app.get(&format!("/v1/weekly/history?month={older_key}"), Some(&anna)).await.body;
|
||||||
|
assert_eq!(back["weeks"][0]["analysis"]["content"]["title"], "Régi hét");
|
||||||
|
assert_eq!(back["weeks"][0]["week_start"], old_week.to_string());
|
||||||
|
assert_eq!(back["newer"], month["current_month"]);
|
||||||
|
// Not into the future; a bad month is refused; others see nothing of it.
|
||||||
|
assert_eq!(app.get("/v1/weekly/history?month=2999-01", Some(&anna)).await.body["month"], month["current_month"]);
|
||||||
|
assert_eq!(app.get("/v1/weekly/history?month=nope", Some(&anna)).await.status, StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(app.get("/v1/weekly/history", Some(&bob)).await.body["weeks"], json!([]));
|
||||||
|
|
||||||
|
// Monday's e-mail: off and on again from the site.
|
||||||
|
let r = app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": false}))).await;
|
||||||
|
assert_eq!((r.status, &r.body["email"]), (StatusCode::OK, &json!(false)));
|
||||||
|
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["weekly_email"], false);
|
||||||
|
app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": true}))).await;
|
||||||
|
let (on, sent_on): (bool, Option<time::Date>) =
|
||||||
|
sqlx::query_as("SELECT weekly_email, weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
// Turned on again, the first one comes next Monday.
|
||||||
|
assert_eq!((on, sent_on), (true, Some(start)));
|
||||||
|
|
||||||
|
// The page of every e-mail setting, from the footer link (no login).
|
||||||
|
let (token,): (uuid::Uuid,) = sqlx::query_as("SELECT email_token FROM users WHERE email = 'anna@example.com'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let page = format!("/v1/public/notifications?token={token}");
|
||||||
|
let r = app.get(&page, None).await;
|
||||||
|
assert_eq!((r.status, &r.body), (StatusCode::OK, &json!({"weekly_horoscope": true, "forum": null})));
|
||||||
|
assert_eq!(app.get("/v1/public/notifications?token=nope", None).await.status, StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(
|
||||||
|
app.get(&format!("/v1/public/notifications?token={}", uuid::Uuid::now_v7()), None).await.status,
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
);
|
||||||
|
// A forum member sees the forum's e-mails too.
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \
|
||||||
|
SELECT id, 'Csillag', 'csillag', 'moon-gold' FROM users WHERE email = 'anna@example.com'",
|
||||||
|
)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let r = app.get(&page, None).await.body;
|
||||||
|
assert_eq!(
|
||||||
|
r["forum"],
|
||||||
|
json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant", "listener": null, "weekly": false})
|
||||||
|
);
|
||||||
|
let mut forum = r["forum"].clone();
|
||||||
|
forum["replies"] = json!("loud");
|
||||||
|
let bad = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true, "forum": forum}))).await;
|
||||||
|
assert_eq!(bad.status, StatusCode::BAD_REQUEST);
|
||||||
|
let off = json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off", "listener": null, "weekly": false});
|
||||||
|
let r = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": false, "forum": off}))).await;
|
||||||
|
assert_eq!((r.status, &r.body["weekly_horoscope"], &r.body["forum"]), (StatusCode::OK, &json!(false), &off));
|
||||||
|
// Turned on again from this page: as on the site, the first one comes next Monday.
|
||||||
|
sqlx::query("UPDATE users SET weekly_email_sent_on = NULL WHERE email = 'anna@example.com'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
|
||||||
|
let sent_on: Option<time::Date> =
|
||||||
|
sqlx::query_scalar("SELECT weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(sent_on, Some(start));
|
||||||
|
// Saved again while on: this Monday's e-mail is not held back.
|
||||||
|
sqlx::query("UPDATE users SET weekly_email_sent_on = NULL WHERE email = 'anna@example.com'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
|
||||||
|
let sent_on: Option<time::Date> =
|
||||||
|
sqlx::query_scalar("SELECT weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(sent_on, None);
|
||||||
|
// The mail client's one-click unsubscribe turns off the weekly e-mail only.
|
||||||
|
let r = app.call("POST", &format!("/v1/public/weekly/unsubscribe?token={token}"), None, None).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
assert_eq!(app.get(&page, None).await.body["weekly_horoscope"], false);
|
||||||
|
assert_eq!(
|
||||||
|
app.call("POST", "/v1/public/weekly/unsubscribe?token=nope", None, None).await.status,
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
||||||
let app = TestApp::new(pool.clone()).await;
|
let app = TestApp::new(pool.clone()).await;
|
||||||
|
|||||||
@@ -204,6 +204,10 @@ struct Incoming {
|
|||||||
|
|
||||||
/// At most one typing notice per target in this time.
|
/// At most one typing notice per target in this time.
|
||||||
const TYPING_EVERY: Duration = Duration::from_secs(2);
|
const TYPING_EVERY: Duration = Duration::from_secs(2);
|
||||||
|
/// At most one typing notice this often per connection, whatever the place.
|
||||||
|
const TYPING_ANY_EVERY: Duration = Duration::from_secs(1);
|
||||||
|
/// A typing notice is a few dozen bytes; anything longer is not one.
|
||||||
|
const TYPING_MAX_BYTES: usize = 200;
|
||||||
|
|
||||||
/// "I am typing", from the page: passed on to those who may see that place.
|
/// "I am typing", from the page: passed on to those who may see that place.
|
||||||
async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
||||||
@@ -248,6 +252,9 @@ async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
|||||||
async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, db: PgPool, me: Me) {
|
async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, db: PgPool, me: Me) {
|
||||||
let (user, moderator) = (me.user, me.moderator);
|
let (user, moderator) = (me.user, me.moderator);
|
||||||
let mut last_typing: Option<(String, std::time::Instant)> = None;
|
let mut last_typing: Option<(String, std::time::Instant)> = None;
|
||||||
|
// Whatever the place: at most one notice a second per connection, so
|
||||||
|
// alternating places cannot flood the database and the other members.
|
||||||
|
let mut last_any: Option<std::time::Instant> = None;
|
||||||
let mut ping = tokio::time::interval(PING);
|
let mut ping = tokio::time::interval(PING);
|
||||||
ping.tick().await;
|
ping.tick().await;
|
||||||
loop {
|
loop {
|
||||||
@@ -280,12 +287,16 @@ async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, d
|
|||||||
}
|
}
|
||||||
incoming = socket.recv() => match incoming {
|
incoming = socket.recv() => match incoming {
|
||||||
Some(Ok(Message::Text(text))) => {
|
Some(Ok(Message::Text(text))) => {
|
||||||
// Typing notices, a few seconds apart per place.
|
// Typing notices, a few seconds apart per place, one a second in all.
|
||||||
let fresh = last_typing
|
let fresh = text.len() <= TYPING_MAX_BYTES
|
||||||
.as_ref()
|
&& last_any.is_none_or(|at| at.elapsed() >= TYPING_ANY_EVERY)
|
||||||
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
|
&& last_typing
|
||||||
|
.as_ref()
|
||||||
|
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
|
||||||
if fresh {
|
if fresh {
|
||||||
last_typing = Some((text.to_string(), std::time::Instant::now()));
|
let now = std::time::Instant::now();
|
||||||
|
last_any = Some(now);
|
||||||
|
last_typing = Some((text.to_string(), now));
|
||||||
if let Some(event) = typing(&db, &me, &text).await {
|
if let Some(event) = typing(&db, &me, &text).await {
|
||||||
emit(&db, event).await;
|
emit(&db, event).await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,6 +75,21 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
tracing::info!("S3_ENDPOINT is not set: no avatar uploads");
|
tracing::info!("S3_ENDPOINT is not set: no avatar uploads");
|
||||||
}
|
}
|
||||||
let state = Arc::new(AppState::new(pool, base_url, storage));
|
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()));
|
tokio::spawn(live::listen(state.db.clone(), state.hub.clone()));
|
||||||
let app = routes::router(state);
|
let app = routes::router(state);
|
||||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
//! Own avatars: a member from the Kereső rank may upload a picture instead of
|
//! Own avatars: any member may upload a picture instead of a starter avatar. It is cut to a square, made small (256 pixels), stripped
|
||||||
//! a starter avatar. It is cut to a square, made small (256 pixels), stripped
|
|
||||||
//! of its metadata (EXIF: camera, place) and kept in the object storage; the
|
//! of its metadata (EXIF: camera, place) and kept in the object storage; the
|
||||||
//! forum serves it. A moderator can put the starter avatar back.
|
//! forum serves it. A moderator can put the starter avatar back.
|
||||||
|
|
||||||
@@ -17,7 +16,6 @@ use image::metadata::Orientation;
|
|||||||
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
|
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use time::OffsetDateTime;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::St;
|
use super::St;
|
||||||
@@ -97,9 +95,6 @@ pub async fn forget(state: &crate::AppState, avatar: &str) {
|
|||||||
/// `PUT /v1/forum/me/avatar`: the picture's bytes as the body.
|
/// `PUT /v1/forum/me/avatar`: the picture's bytes as the body.
|
||||||
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<Json<Value>> {
|
pub async fn upload(State(state): St, viewer: Viewer, body: Bytes) -> ApiResult<Json<Value>> {
|
||||||
let member = viewer.require_writer()?.clone();
|
let member = viewer.require_writer()?.clone();
|
||||||
if member.rank(OffsetDateTime::now_utc()).is_newcomer() && !viewer.is_moderator() {
|
|
||||||
return Err(ApiError::Forbidden("Saját képet a Kereső rangtól tölthetsz fel.".into()));
|
|
||||||
}
|
|
||||||
let Some(storage) = &state.storage else {
|
let Some(storage) = &state.storage else {
|
||||||
return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into()));
|
return Err(ApiError::Forbidden("A képfeltöltés most nem érhető el.".into()));
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -152,6 +152,16 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
|||||||
.fetch_all(&state.db)
|
.fetch_all(&state.db)
|
||||||
.await?;
|
.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!(
|
let hot: Vec<CardRow> = sqlx::query_as(&format!(
|
||||||
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
|
"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 \
|
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,
|
"online": online,
|
||||||
"topics": topics,
|
"topics": topics,
|
||||||
"unanswered": cards_json(&state.db, unanswered).await?,
|
"unanswered": cards_json(&state.db, unanswered).await?,
|
||||||
|
"pinned": cards_json(&state.db, pinned).await?,
|
||||||
"hot": cards_json(&state.db, hot).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.
|
/// 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>> {
|
pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||||
viewer.require_member()?;
|
viewer.require_member()?;
|
||||||
|
|||||||
@@ -61,9 +61,9 @@ pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
|||||||
},
|
},
|
||||||
"listener": m.listener,
|
"listener": m.listener,
|
||||||
"supporter_badge": m.supporter_badge,
|
"supporter_badge": m.supporter_badge,
|
||||||
// From the Kereső rank: volunteering as a listener, an own picture.
|
// From the Kereső rank: volunteering as a companion. An own picture: anyone.
|
||||||
"can_listen": viewer.is_moderator() || !rank.is_newcomer(),
|
"can_listen": viewer.is_moderator() || !rank.is_newcomer(),
|
||||||
"can_upload_avatar": viewer.is_moderator() || !rank.is_newcomer(),
|
"can_upload_avatar": true,
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
let buyer = super::has_purchase(&state.db, user.id).await?;
|
let buyer = super::has_purchase(&state.db, user.id).await?;
|
||||||
|
|||||||
@@ -82,10 +82,11 @@ fn pair(a: Uuid, b: Uuid) -> (Uuid, Uuid) {
|
|||||||
if a < b { (a, b) } else { (b, a) }
|
if a < b { (a, b) } else { (b, a) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a member may start conversations: from the Kereső rank and after
|
/// Whether a member may start conversations: any member for now, from the
|
||||||
/// writing in public (moderators always).
|
/// first day (the user decided on 2026-11-26; a newcomers' limit, such as the
|
||||||
fn may_request(viewer: &Viewer, member: &Member) -> bool {
|
/// Kereső rank, may come back later here).
|
||||||
viewer.is_moderator() || (!member.rank(OffsetDateTime::now_utc()).is_newcomer() && member.post_count > 0)
|
fn may_request(_viewer: &Viewer, _member: &Member) -> bool {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The viewer's relation to another member, for the profile page.
|
/// The viewer's relation to another member, for the profile page.
|
||||||
@@ -143,8 +144,7 @@ pub async fn request(
|
|||||||
let me = viewer.require_writer()?;
|
let me = viewer.require_writer()?;
|
||||||
if !may_request(&viewer, me) {
|
if !may_request(&viewer, me) {
|
||||||
return Err(ApiError::Forbidden(
|
return Err(ApiError::Forbidden(
|
||||||
"Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba. A neked küldött kéréseket addig is elfogadhatod."
|
"Most nem kezdeményezhetsz beszélgetést. A neked küldött kéréseket elfogadhatod.".into(),
|
||||||
.into(),
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let other: Uuid = sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
|
let other: Uuid = sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ mod mentions;
|
|||||||
mod messages;
|
mod messages;
|
||||||
mod moderation;
|
mod moderation;
|
||||||
mod mutes;
|
mod mutes;
|
||||||
|
mod photos;
|
||||||
mod posts;
|
mod posts;
|
||||||
mod replies;
|
mod replies;
|
||||||
mod reports;
|
mod reports;
|
||||||
@@ -42,6 +43,8 @@ pub type Body<T> = WithRejection<Json<T>, ApiError>;
|
|||||||
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
||||||
pub type St = State<Arc<AppState>>;
|
pub type St = State<Arc<AppState>>;
|
||||||
|
|
||||||
|
pub use photos::cleanup as photo_cleanup;
|
||||||
|
|
||||||
pub fn router(state: Arc<AppState>) -> Router {
|
pub fn router(state: Arc<AppState>) -> Router {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/healthz", get(health))
|
.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/topics/{slug}/join", post(topics::join).delete(topics::leave))
|
||||||
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
|
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
|
||||||
.route("/v1/forum/followed", get(home::followed))
|
.route("/v1/forum/followed", get(home::followed))
|
||||||
|
.route("/v1/forum/latest", get(home::latest))
|
||||||
.route("/v1/forum/replies", get(replies::list))
|
.route("/v1/forum/replies", get(replies::list))
|
||||||
.route("/v1/forum/search", get(search::search))
|
.route("/v1/forum/search", get(search::search))
|
||||||
.route("/v1/forum/share-card/{slug}", get(attachments::preview))
|
.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)),
|
put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)),
|
||||||
)
|
)
|
||||||
.route("/v1/forum/avatars/{file}", get(avatars::serve))
|
.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/members/{nickname}/avatar-reset", post(avatars::reset))
|
||||||
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
||||||
.route("/v1/forum/presence", post(members::presence))
|
.route("/v1/forum/presence", post(members::presence))
|
||||||
@@ -155,6 +164,9 @@ pub struct CardRow {
|
|||||||
pub unread: Option<i64>,
|
pub unread: Option<i64>,
|
||||||
/// The site's own thread (the daily sky).
|
/// The site's own thread (the daily sky).
|
||||||
pub system: bool,
|
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
|
/// `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.created_at > $2::timestamptz AND {} \
|
||||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
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, \
|
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 \
|
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||||
WHERE th.deleted_at IS NULL AND ({}) AND {}",
|
WHERE th.deleted_at IS NULL AND ({}) AND {}",
|
||||||
not_muted("p.author_id"),
|
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),
|
"slug": crate::text::slug(&r.title),
|
||||||
"title": r.title,
|
"title": r.title,
|
||||||
"intent": r.intent,
|
"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()),
|
"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),
|
"created_at": rfc3339(r.created_at),
|
||||||
"last_post_at": rfc3339(r.last_post_at),
|
"last_post_at": rfc3339(r.last_post_at),
|
||||||
"reply_count": r.reply_count,
|
"reply_count": r.reply_count,
|
||||||
|
|||||||
@@ -0,0 +1,348 @@
|
|||||||
|
//! 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"))?;
|
||||||
|
// A removed thread takes its photos down too (moderators still see them).
|
||||||
|
if thread.deleted_at.is_some() && !viewer.is_moderator() {
|
||||||
|
return 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" };
|
||||||
|
// Not for long even when public: a moderator may remove the post, and the
|
||||||
|
// CDN and the browsers must let go of the photo within the hour.
|
||||||
|
let cache = if public { "public, max-age=3600" } 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
|
||||||
|
/// (or whole threads) 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 \
|
||||||
|
LEFT JOIN forum.threads t ON t.id = p.thread_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') \
|
||||||
|
OR (t.deleted_at IS NOT NULL AND t.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)
|
||||||
|
}
|
||||||
@@ -316,13 +316,19 @@ async fn set_helped(
|
|||||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The sharer's link goes (as when revoked on the main site).
|
/// The sharer's link goes (as when revoked on the main site), unless another
|
||||||
|
/// live question of theirs still shows it: asking twice about the same chart
|
||||||
|
/// reuses one link (call it after this post let go of it).
|
||||||
async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> {
|
async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> {
|
||||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
sqlx::query(
|
||||||
.bind(share)
|
"UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL \
|
||||||
.bind(owner)
|
AND NOT EXISTS (SELECT 1 FROM forum.posts p JOIN forum.threads t ON t.id = p.thread_id \
|
||||||
.execute(db)
|
WHERE p.share_id = $1 AND p.deleted_at IS NULL AND t.deleted_at IS NULL)",
|
||||||
.await?;
|
)
|
||||||
|
.bind(share)
|
||||||
|
.bind(owner)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ pub async fn list(
|
|||||||
"id": r.id,
|
"id": r.id,
|
||||||
"thread": { "id": r.thread_id, "title": r.title, "slug": crate::text::slug(&r.title) },
|
"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()),
|
"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),
|
"created_at": rfc3339(r.created_at),
|
||||||
"kind": r.kind,
|
"kind": r.kind,
|
||||||
"unread": r.unread,
|
"unread": r.unread,
|
||||||
@@ -124,12 +124,3 @@ pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult<StatusCode>
|
|||||||
.await?;
|
.await?;
|
||||||
Ok(StatusCode::NO_CONTENT)
|
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -117,6 +117,9 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
|
|||||||
let texts: Vec<(i64, &str)> =
|
let texts: Vec<(i64, &str)> =
|
||||||
posts.iter().filter(|p| p.deleted_at.is_none()).map(|p| (p.id, p.body.as_str())).collect();
|
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 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)> =
|
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")
|
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||||
.bind(&ids)
|
.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()),
|
"share": p.share_id.and_then(|id| cards.get(&id).cloned()),
|
||||||
// Previews of the links a provider knows (YouTube).
|
// Previews of the links a provider knows (YouTube).
|
||||||
"links": previews.get(&p.id),
|
"links": previews.get(&p.id),
|
||||||
|
"photos": photos.get(&p.id),
|
||||||
});
|
});
|
||||||
if moderator {
|
if moderator {
|
||||||
post["down"] = json!(down);
|
post["down"] = json!(down);
|
||||||
@@ -328,6 +332,9 @@ pub struct CreateThread {
|
|||||||
/// A share made for the forum on the main site (`/s/<slug>`).
|
/// A share made for the forum on the main site (`/s/<slug>`).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
share: Option<String>,
|
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.
|
/// Starts a thread with its opening post; the author follows it.
|
||||||
@@ -382,6 +389,7 @@ pub async fn create(
|
|||||||
.bind(share)
|
.bind(share)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?;
|
.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?;
|
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
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.
|
/// post (two levels at most), a reply to the opening post is first-level.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
parent_id: Option<i64>,
|
parent_id: Option<i64>,
|
||||||
|
/// Photos uploaded for the reply.
|
||||||
|
#[serde(default)]
|
||||||
|
photos: Vec<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn reply(
|
pub async fn reply(
|
||||||
@@ -486,6 +497,7 @@ pub async fn reply(
|
|||||||
.bind(id)
|
.bind(id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.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?;
|
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
// The one answered hears of it (on the second level, not the branch's first post).
|
// The one answered hears of it (on the second level, not the branch's first post).
|
||||||
|
|||||||
+314
-14
@@ -35,17 +35,40 @@ impl TestApp {
|
|||||||
|
|
||||||
/// With the link providers at these (fake) addresses.
|
/// With the link providers at these (fake) addresses.
|
||||||
fn with_links(pool: PgPool, links: crate::links::LinkConfig) -> Self {
|
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 {
|
let state = AppState {
|
||||||
db: pool.clone(),
|
db: pool.clone(),
|
||||||
flood_secs: 0,
|
flood_secs: 0,
|
||||||
base_url: "https://sorsfonalak.test".into(),
|
base_url: "https://sorsfonalak.test".into(),
|
||||||
hub: crate::live::Hub::default(),
|
hub: crate::live::Hub::default(),
|
||||||
storage: None,
|
storage,
|
||||||
links,
|
links,
|
||||||
};
|
};
|
||||||
Self { router: routes::router(Arc::new(state)), pool }
|
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.
|
/// A user with a session, as after a login in the backend.
|
||||||
async fn user(&self, email: &str, roles: &[&str]) -> User {
|
async fn user(&self, email: &str, roles: &[&str]) -> User {
|
||||||
let id = Uuid::now_v7();
|
let id = Uuid::now_v7();
|
||||||
@@ -642,13 +665,7 @@ async fn private_messages_start_with_a_request(pool: PgPool) {
|
|||||||
async move { app.call("POST", "/v1/forum/conversations", Some(&user), body).await }
|
async move { app.call("POST", "/v1/forum/conversations", Some(&user), body).await }
|
||||||
};
|
};
|
||||||
|
|
||||||
// A newcomer may not start one; a seasoned member who wrote in public may.
|
// Any member may start one from the first day (a newcomers' limit may come later).
|
||||||
let (status, _) = request(&anna, "Holdfény", "Szia, olvastam a hozzászólásodat.").await;
|
|
||||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
||||||
let profile = app.get("/v1/forum/members/Holdfény", Some(&anna)).await;
|
|
||||||
assert_eq!(profile["relation"]["can_request"], false);
|
|
||||||
app.thread(&anna, "torzsasztal", "Sziasztok").await;
|
|
||||||
app.season(&anna, 5, 10).await;
|
|
||||||
assert_eq!(app.get("/v1/forum/members/Holdfény", Some(&anna)).await["relation"]["can_request"], true);
|
assert_eq!(app.get("/v1/forum/members/Holdfény", Some(&anna)).await["relation"]["can_request"], true);
|
||||||
assert_eq!(request(&anna, "Holdfény", "Nézd: www.pelda.hu").await.0, StatusCode::BAD_REQUEST);
|
assert_eq!(request(&anna, "Holdfény", "Nézd: www.pelda.hu").await.0, StatusCode::BAD_REQUEST);
|
||||||
assert_eq!(request(&anna, "Csendesvíz", "Szia, én vagyok.").await.0, StatusCode::BAD_REQUEST);
|
assert_eq!(request(&anna, "Csendesvíz", "Szia, én vagyok.").await.0, StatusCode::BAD_REQUEST);
|
||||||
@@ -1310,18 +1327,41 @@ async fn a_question_about_ones_chart(pool: PgPool) {
|
|||||||
assert_eq!(shown["posts"][0]["share"]["revoked"], true);
|
assert_eq!(shown["posts"][0]["share"]["revoked"], true);
|
||||||
assert!(shown["posts"][0]["share"].get("points").is_none());
|
assert!(shown["posts"][0]["share"].get("points").is_none());
|
||||||
|
|
||||||
// The author takes it off (only she may): the card goes, the link stops working.
|
// A second question about the same chart uses the same link.
|
||||||
sqlx::query("UPDATE shares SET revoked_at = NULL WHERE slug = 'annaforum000001'").execute(&app.pool).await.unwrap();
|
sqlx::query("UPDATE shares SET revoked_at = NULL WHERE slug = 'annaforum000001'").execute(&app.pool).await.unwrap();
|
||||||
|
let (status, second) = app
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/v1/forum/threads",
|
||||||
|
Some(&anna),
|
||||||
|
json!({ "topic": "egbolt-es-kepletek", "title": "És a Vénusz?", "body": "Még egy kérdés.", "share": "annaforum000001" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED, "{second}");
|
||||||
|
let second = second["id"].as_i64().unwrap();
|
||||||
|
let revoked = || async {
|
||||||
|
sqlx::query_scalar::<_, bool>("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
||||||
|
.fetch_one(&app.pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// The author takes it off the first (only she may): that card goes, the
|
||||||
|
// other question keeps it, so the link stays.
|
||||||
let opening = shown["posts"][0]["id"].as_i64().unwrap();
|
let opening = shown["posts"][0]["id"].as_i64().unwrap();
|
||||||
let uri = format!("/v1/forum/posts/{opening}/share");
|
let uri = format!("/v1/forum/posts/{opening}/share");
|
||||||
assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN);
|
assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN);
|
||||||
assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT);
|
assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT);
|
||||||
assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null());
|
assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null());
|
||||||
let revoked: bool = sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
assert!(!revoked().await);
|
||||||
.fetch_one(&app.pool)
|
let other = app.get(&format!("/v1/forum/threads/{second}"), Some(&bea)).await;
|
||||||
.await
|
assert_eq!(other["posts"][0]["share"]["points"][1]["sign"], "pisces");
|
||||||
.unwrap();
|
|
||||||
assert!(revoked);
|
// Deleting the last question that shows it: now the link stops working.
|
||||||
|
let last = other["posts"][0]["id"].as_i64().unwrap();
|
||||||
|
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{last}"), Some(&anna), json!({})).await;
|
||||||
|
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||||
|
assert!(revoked().await);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
@@ -1403,3 +1443,263 @@ async fn youtube_links_get_a_preview(pool: PgPool) {
|
|||||||
assert_eq!(shown["posts"][1]["links"][0]["title"], "Telihold meditáció");
|
assert_eq!(shown["posts"][1]["links"][0]["title"], "Telihold meditáció");
|
||||||
assert!(shown["posts"][0]["links"].is_null());
|
assert!(shown["posts"][0]["links"].is_null());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn any_member_may_upload_an_avatar(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool);
|
||||||
|
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||||
|
// A newcomer (Vándor) is offered it too; without storage the upload says it is not available.
|
||||||
|
assert_eq!(app.get("/v1/forum/me", Some(&anna)).await["member"]["can_upload_avatar"], true);
|
||||||
|
let (status, body) = app.call("PUT", "/v1/forum/me/avatar", Some(&anna), Value::Null).await;
|
||||||
|
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);
|
||||||
|
// Public, but only for an hour: a removed post's photo must not linger in caches.
|
||||||
|
assert_eq!(headers["cache-control"].to_str().unwrap(), "public, max-age=3600");
|
||||||
|
|
||||||
|
// 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}");
|
||||||
|
|
||||||
|
// A removed thread takes its photos down (the posts themselves stay unmarked).
|
||||||
|
sqlx::query("UPDATE forum.threads SET deleted_at = now() WHERE id = $1")
|
||||||
|
.bind(created["id"].as_i64().unwrap())
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(app.raw("GET", &path(&jpeg["url"]), Some(&bea), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
// Unattached for over a day, and in a thread removed over a year ago: 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();
|
||||||
|
sqlx::query("UPDATE forum.threads SET deleted_at = now() - interval '2 years' WHERE id = $1")
|
||||||
|
.bind(created["id"].as_i64().unwrap())
|
||||||
|
.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(), 4);
|
||||||
|
let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap();
|
||||||
|
assert_eq!(left, 1);
|
||||||
|
}
|
||||||
|
|||||||
@@ -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()])
|
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`.
|
/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`.
|
||||||
pub fn slug(title: &str) -> String {
|
pub fn slug(title: &str) -> String {
|
||||||
let ascii = deunicode::deunicode(title).to_lowercase();
|
let ascii = deunicode::deunicode(title).to_lowercase();
|
||||||
|
|||||||
@@ -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
|
FROM node:22.23-alpine AS build
|
||||||
WORKDIR /app
|
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 --from=deps /app/node_modules ./node_modules
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:22.23-alpine
|
FROM node:22.23-alpine
|
||||||
WORKDIR /app
|
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
|
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/standalone ./
|
||||||
COPY --from=build --chown=app:app /app/.next/static ./.next/static
|
COPY --from=build --chown=app:app /app/.next/static ./.next/static
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ const config: NextConfig = {
|
|||||||
// Small self-contained server for the container image.
|
// Small self-contained server for the container image.
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
poweredByHeader: false,
|
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.
|
// The fonts of the share preview images are read from disk at run time.
|
||||||
outputFileTracingIncludes: {
|
outputFileTracingIncludes: {
|
||||||
"/s/[slug]/kep/[file]": ["./src/assets/og/*.ttf"],
|
"/s/[slug]/kep/[file]": ["./src/assets/og/*.ttf"],
|
||||||
|
|||||||
@@ -61,21 +61,34 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
|||||||
<section className="lp-hero">
|
<section className="lp-hero">
|
||||||
<div className="lp-wrap lp-hero-grid">
|
<div className="lp-wrap lp-hero-grid">
|
||||||
<div className="lp-hero-text">
|
<div className="lp-hero-text">
|
||||||
<span className="eyebrow lp-rise lp-r1">Születési képlet · Éves előrejelzés · Kapcsolat</span>
|
<span className="eyebrow">Születési képlet · Éves előrejelzés · Kapcsolat</span>
|
||||||
<h1 className="lp-title lp-rise lp-r2">
|
<h1 className="lp-title">
|
||||||
Ahol a csillagok
|
Ahol a csillagok
|
||||||
<br />
|
<br />
|
||||||
összekötnek.
|
összekötnek.
|
||||||
</h1>
|
</h1>
|
||||||
<p className="lp-lead lp-rise lp-r3">
|
<p className="lp-lead">
|
||||||
Add meg, mikor és hol születtél: percre pontosan kiszámoljuk a képletedet, és személyre szóló elemzést írunk
|
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.
|
belőle. Megmutatjuk, mit hoz az éved, és mennyire illetek össze azzal, akit szeretsz.
|
||||||
</p>
|
</p>
|
||||||
<p className="ai-line lp-ai-line lp-rise lp-r3">
|
<div className="lp-personal">
|
||||||
Részletes, személyre szóló elemzések a legfejlettebb AI-modellekkel: percek alatt, egy személyes konzultáció
|
<svg aria-hidden="true" viewBox="0 0 24 24" className="lp-personal-icon">
|
||||||
árának töredékéért.
|
<path d="M12 3.5a7.5 7.5 0 0 1 7.5 7.5c0 3-.6 5.7-1.6 7.8" />
|
||||||
</p>
|
<path d="M4.5 11a7.5 7.5 0 0 1 3-6" />
|
||||||
<div className="lp-actions lp-rise lp-r4">
|
<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">
|
||||||
<Link href={start} className="btn btn-primary lp-btn">
|
<Link href={start} className="btn btn-primary lp-btn">
|
||||||
{signIn}
|
{signIn}
|
||||||
</Link>
|
</Link>
|
||||||
@@ -84,13 +97,13 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
{!loggedIn && (
|
{!loggedIn && (
|
||||||
<p className="lp-free-line lp-rise lp-r4">
|
<p className="lp-free-line">
|
||||||
<span className="lp-free-label">Ingyenes</span>
|
<span className="lp-free-label">Ingyenes</span>
|
||||||
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{!loggedIn && (
|
{!loggedIn && (
|
||||||
<p className="hint lp-rise lp-r4">
|
<p className="hint">
|
||||||
{inviteOnly
|
{inviteOnly
|
||||||
? "Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be."
|
? "Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be."
|
||||||
: "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."}
|
: "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."}
|
||||||
@@ -195,7 +208,7 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
|||||||
<div className="lp-intro">
|
<div className="lp-intro">
|
||||||
<span className="eyebrow">Miért más?</span>
|
<span className="eyebrow">Miért más?</span>
|
||||||
<h2 id="why-title" className="lp-h2">
|
<h2 id="why-title" className="lp-h2">
|
||||||
Alapos elemzés, töredék áron
|
Személyre szabott, nem előre megírt
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<ul className="lp-why-grid">
|
<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="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" />
|
<path d="M18 15l.9 2.1L21 18l-2.1.9L18 21l-.9-2.1L15 18l2.1-.9z" />
|
||||||
</svg>
|
</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">
|
<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
|
Nem csillagjegyenként előre megírt szövegekből rakjuk össze. A legújabb, legnagyobb nyelvi modellek a te
|
||||||
sablonszövegekből rakjuk össze: minden mondat a te képletedről szól.
|
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>
|
</p>
|
||||||
</li>
|
</li>
|
||||||
<li className="card lp-why-card">
|
<li className="card lp-why-card">
|
||||||
|
|||||||
@@ -161,8 +161,8 @@ export default async function PrivacyPage() {
|
|||||||
<tr>
|
<tr>
|
||||||
<td>
|
<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
|
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
|
rangod; a hozzászólásaidhoz feltöltött fotók; kiket említettél (@álnév); hogy mit olvastál el,
|
||||||
némítottál el
|
mely szálakat követed, és kiket némítottál el
|
||||||
</td>
|
</td>
|
||||||
<td>A fórum működése, a rangok, az újdonságok jelzése</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>
|
<td>Szerződés teljesítése</td>
|
||||||
@@ -207,6 +207,25 @@ export default async function PrivacyPage() {
|
|||||||
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
||||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
Heti horoszkóp: a hét égboltja a saját képleteden, a belőle írt szöveg, és hogy kéred-e a hétfői
|
||||||
|
értesítő levelet
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
Az ingyenes heti horoszkóp; hétfőnként egy rövid levél, hogy itt az új (alapból küldjük, a levél
|
||||||
|
alján, a Heti horoszkóp oldalon vagy a Profil oldalon bármikor kikapcsolhatod)
|
||||||
|
</td>
|
||||||
|
<td>Szerződés teljesítése; a levélnél jogos érdek (6. cikk (1) f)</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
Melyik oldalt nyitottad meg, honnan érkeztél, a böngésződ és az eszközöd típusa, az országod és az oldal
|
||||||
|
betöltési ideje (látogatottságmérés)
|
||||||
|
</td>
|
||||||
|
<td>Hogy lássuk, mennyien nézik az egyes oldalakat, és elég gyors-e az oldal</td>
|
||||||
|
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||||
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
@@ -237,7 +256,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,
|
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
|
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
|
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
|
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
|
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
|
(youtube-nocookie.com), amely látja az IP-címedet és a lejátszás adatait; telefonon a megnyitás a YouTube
|
||||||
@@ -261,7 +282,8 @@ export default async function PrivacyPage() {
|
|||||||
<p>
|
<p>
|
||||||
<strong>Mire használjuk:</strong> a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az
|
<strong>Mire használjuk:</strong> a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az
|
||||||
e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy
|
e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy
|
||||||
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted); a
|
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted) és a
|
||||||
|
heti horoszkóp hétfői értesítőjéhez (ha nem kapcsoltad ki); a
|
||||||
nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.
|
nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
@@ -302,10 +324,11 @@ export default async function PrivacyPage() {
|
|||||||
<section>
|
<section>
|
||||||
<h2>4. Az elemzések és a mesterséges intelligencia</h2>
|
<h2>4. Az elemzések és a mesterséges intelligencia</h2>
|
||||||
<p>
|
<p>
|
||||||
A rövid összefoglalót, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott válaszokat nagy nyelvi
|
A rövid összefoglalót, a heti horoszkópot, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott
|
||||||
modell (mesterséges intelligencia) írja. A modellhez a <strong>képlet csillagászati adatai</strong> jutnak
|
válaszokat nagy nyelvi modell (mesterséges intelligencia) írja. A modellhez a{" "}
|
||||||
el (a bolygók jegye, foka, háza és fényszögei), kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel,
|
<strong>képlet csillagászati adatai</strong> jutnak el (a bolygók jegye, foka, háza és fényszögei), a heti
|
||||||
a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a
|
horoszkópnál a hét égboltja is (hol járnak a bolygók, és milyen fényszöget alkotnak a képleteddel),
|
||||||
|
kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel, a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a
|
||||||
kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és
|
kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és
|
||||||
önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.
|
önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.
|
||||||
</p>
|
</p>
|
||||||
@@ -335,7 +358,8 @@ export default async function PrivacyPage() {
|
|||||||
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
||||||
letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a
|
letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a
|
||||||
Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is
|
Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is
|
||||||
vizsgálja).
|
vizsgálja). A Web Analytics szolgáltatásával méri a látogatottságot és az oldal sebességét, süti és a
|
||||||
|
böngészőben tárolt azonosító nélkül; az egyes látogatókat nem követi.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
||||||
@@ -381,7 +405,8 @@ export default async function PrivacyPage() {
|
|||||||
</li>
|
</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 számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.</li>
|
||||||
<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
|
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
|
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
|
tag” néven megmaradnak, hogy a beszélgetések érthetők maradjanak; ha a törlésüket is kéred, írj a fenti
|
||||||
@@ -403,7 +428,13 @@ export default async function PrivacyPage() {
|
|||||||
<p>
|
<p>
|
||||||
A működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve tart. Ha a
|
A működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve tart. Ha a
|
||||||
fórumon világos vagy sötét témát választasz, a választásodat egy második süti (<code>sf_forum_theme</code>)
|
fórumon világos vagy sötét témát választasz, a választásodat egy második süti (<code>sf_forum_theme</code>)
|
||||||
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.
|
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket nem használunk.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
A látogatottságot a Cloudflare Web Analytics méri, süti és a böngészőben tárolt azonosító nélkül. Az oldal
|
||||||
|
betöltésekor egy kis szkript elküldi, melyik oldalt nyitottad meg, honnan érkeztél, milyen böngészőt és
|
||||||
|
eszközt használsz, és mennyi idő alatt töltődött be az oldal. Mi ebből csak összesített számokat látunk, az
|
||||||
|
egyes látogatókat nem tudjuk követni.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { huf, usePackages } from "@/components/PackageCards";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
||||||
import type { AdminUser, Package, Role } from "@/lib/types";
|
import type { AdminUser, Package, Role } from "@/lib/types";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const PAGE_SIZE = 25;
|
const PAGE_SIZE = 25;
|
||||||
const EDITABLE_ROLES: Role[] = ["user", "creator", "moderator", "admin"];
|
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).
|
// 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 unsent = useRef<{ pkg: string | null; credit: string | null }>({ pkg: null, credit: null });
|
||||||
const canClose = () => {
|
const canClose = async () => {
|
||||||
const { pkg, credit } = unsent.current;
|
const { pkg, credit } = unsent.current;
|
||||||
const what = [pkg && `a(z) ${pkg} csomag`, credit && `${credit} jóváírás`].filter(Boolean).join(" és ");
|
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 (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
@@ -285,8 +292,8 @@ function UserDialog({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn"
|
className="btn"
|
||||||
onClick={() => {
|
onClick={async () => {
|
||||||
if (canClose()) onClose();
|
if (await canClose()) onClose();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Bezárás
|
Bezárás
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import type { AdminGift } from "@/lib/types";
|
import type { AdminGift } from "@/lib/types";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
||||||
|
|
||||||
@@ -51,18 +52,23 @@ export function AdminGifts() {
|
|||||||
}, [q, load]);
|
}, [q, load]);
|
||||||
|
|
||||||
async function refund(g: AdminGift) {
|
async function refund(g: AdminGift) {
|
||||||
const late = g.within_withdrawal
|
const money = g.checkout?.amount_huf ? ` (${huf(g.checkout.amount_huf)})` : "";
|
||||||
? ""
|
const ok = await confirmDialog({
|
||||||
: "\n\nFigyelem: a 14 napos elállási idő már letelt.";
|
title: `Visszatéríted a(z) „${g.package.name}” ajándékot${money}?`,
|
||||||
const money = g.checkout?.amount_huf
|
text: (
|
||||||
? ` (${huf(g.checkout.amount_huf)})`
|
<>
|
||||||
: "";
|
<p>A {g.code} kód érvénytelen lesz, a Stripe visszautalja az árát, a számla sztornózódik.</p>
|
||||||
if (
|
{!g.within_withdrawal && (
|
||||||
!window.confirm(
|
<p>
|
||||||
`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}`,
|
<strong>Figyelem:</strong> a 14 napos elállási idő már letelt.
|
||||||
)
|
</p>
|
||||||
)
|
)}
|
||||||
return;
|
</>
|
||||||
|
),
|
||||||
|
confirm: "Visszatérítés",
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
setBusy(g.id);
|
setBusy(g.id);
|
||||||
setError(null);
|
setError(null);
|
||||||
setDone(null);
|
setDone(null);
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import type { GenerationError } from "@/lib/types";
|
import type { GenerationError } from "@/lib/types";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const PAGE = 50;
|
const PAGE = 50;
|
||||||
|
|
||||||
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
|
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
|
||||||
const KINDS: Record<string, string> = {
|
const KINDS: Record<string, string> = {
|
||||||
summary: "összefoglaló",
|
summary: "összefoglaló",
|
||||||
|
weekly: "heti horoszkóp",
|
||||||
natal: "képletelemzés",
|
natal: "képletelemzés",
|
||||||
synastry: "kapcsolati",
|
synastry: "kapcsolati",
|
||||||
forecast: "előrejelzés",
|
forecast: "előrejelzés",
|
||||||
@@ -83,7 +85,13 @@ export function ErrorLog() {
|
|||||||
|
|
||||||
async function removeMatching() {
|
async function removeMatching() {
|
||||||
const what = source || outcome ? `a szűrésnek megfelelő ${total} bejegyzést` : `mind a ${total} bejegyzést`;
|
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);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { objectPosition, photoSrc } from "@/lib/celebrityPhoto";
|
|||||||
import type { AdminCelebrity, Analysis } from "@/lib/types";
|
import type { AdminCelebrity, Analysis } from "@/lib/types";
|
||||||
|
|
||||||
import { ANALYSIS_STATUS, SubtitleField } from "../AdminCelebrities";
|
import { ANALYSIS_STATUS, SubtitleField } from "../AdminCelebrities";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const POLL_MS = 10_000;
|
const POLL_MS = 10_000;
|
||||||
|
|
||||||
@@ -65,7 +66,14 @@ export function CelebrityEditor({ id, selfId, isAdmin }: { id: string; selfId: s
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function remove() {
|
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 {
|
try {
|
||||||
await api(url, { method: "DELETE" });
|
await api(url, { method: "DELETE" });
|
||||||
router.push("/admin/hires-emberek");
|
router.push("/admin/hires-emberek");
|
||||||
@@ -190,7 +198,7 @@ function PhotoSection({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function removePhoto() {
|
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 {
|
try {
|
||||||
onChange(await api<AdminCelebrity>(`${url}/photo`, { method: "DELETE" }));
|
onChange(await api<AdminCelebrity>(`${url}/photo`, { method: "DELETE" }));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { usePackages } from "@/components/PackageCards";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import type { AdminInvitation, InvitationResult } from "@/lib/types";
|
import type { AdminInvitation, InvitationResult } from "@/lib/types";
|
||||||
|
import { confirmDialog, copyDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const MAX_MESSAGE = 300;
|
const MAX_MESSAGE = 300;
|
||||||
|
|
||||||
@@ -47,7 +48,11 @@ function CopyLink({ url }: { url: string }) {
|
|||||||
await navigator.clipboard.writeText(url);
|
await navigator.clipboard.writeText(url);
|
||||||
setCopied(true);
|
setCopied(true);
|
||||||
} catch {
|
} 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);
|
const [url, setUrl] = useState<string | null>(null);
|
||||||
|
|
||||||
async function act(kind: "resend" | "revoke") {
|
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);
|
setBusy(true);
|
||||||
setNote(null);
|
setNote(null);
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -9,7 +9,11 @@ import type { CatalogModel, ModelFunction } from "@/lib/types";
|
|||||||
import { RunningJobs } from "./RunningJobs";
|
import { RunningJobs } from "./RunningJobs";
|
||||||
|
|
||||||
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
|
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
|
||||||
summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." },
|
summary: {
|
||||||
|
title: "Tömör összefoglaló és heti horoszkóp",
|
||||||
|
about:
|
||||||
|
"Ingyenes: az összefoglaló minden új képlethez magától elkészül, a heti horoszkóp akkor, amikor a tag a héten megnyitja a képletét. Olcsó, gyors modell elég.",
|
||||||
|
},
|
||||||
analysis: {
|
analysis: {
|
||||||
title: "Elemzések és éves előrejelzés",
|
title: "Elemzések és éves előrejelzés",
|
||||||
about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.",
|
about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type { AdminJob } from "@/lib/types";
|
|||||||
|
|
||||||
const KINDS: Record<AdminJob["kind"], string> = {
|
const KINDS: Record<AdminJob["kind"], string> = {
|
||||||
summary: "Összefoglaló",
|
summary: "Összefoglaló",
|
||||||
|
weekly: "Heti horoszkóp",
|
||||||
natal: "Képletelemzés",
|
natal: "Képletelemzés",
|
||||||
synastry: "Kapcsolati elemzés",
|
synastry: "Kapcsolati elemzés",
|
||||||
forecast: "Éves előrejelzés",
|
forecast: "Éves előrejelzés",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import type { Package, PromoCode } from "@/lib/types";
|
import type { Package, PromoCode } from "@/lib/types";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const PAGE = 100;
|
const PAGE = 100;
|
||||||
|
|
||||||
@@ -168,7 +169,13 @@ function CodeList({ packages }: { packages: Package[] }) {
|
|||||||
}, [q]);
|
}, [q]);
|
||||||
|
|
||||||
async function revoke(c: PromoCode) {
|
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 {
|
try {
|
||||||
await api(`/admin/promo-codes/${c.id}/revoke`, { body: {} });
|
await api(`/admin/promo-codes/${c.id}/revoke`, { body: {} });
|
||||||
load(0);
|
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" } });
|
||||||
|
}
|
||||||
@@ -154,7 +154,7 @@ export default async function TermsPage() {
|
|||||||
felismerjenek; nem lehet sértő vagy megtévesztő, és nem utánozhat más tagot, moderátort vagy a
|
felismerjenek; nem lehet sértő vagy megtévesztő, és nem utánozhat más tagot, moderátort vagy a
|
||||||
Sorsfonalakat. A valódi neved, az e-mail-címed és a születési adataid a fórumon nem jelennek meg; a
|
Sorsfonalakat. A valódi neved, az e-mail-címed és a születési adataid a fórumon nem jelennek meg; a
|
||||||
képletedből csak annyi látszik, amennyit a fórumprofilodban megosztasz, fokok nélkül.
|
képletedből csak annyi látszik, amennyit a fórumprofilodban megosztasz, fokok nélkül.
|
||||||
A Kereső rangtól saját képet is feltölthetsz avatarnak: csak olyat, amelyhez jogod van, és amelyen más nem
|
Saját képet is feltölthetsz avatarnak: csak olyat, amelyhez jogod van, és amelyen más nem
|
||||||
ismerhető fel a hozzájárulása nélkül; a moderátorok a nem odaillő képet eltávolíthatják.
|
ismerhető fel a hozzájárulása nélkül; a moderátorok a nem odaillő képet eltávolíthatják.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -192,11 +192,14 @@ 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
|
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
|
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.
|
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>
|
</p>
|
||||||
|
|
||||||
<h3>8.4. Privát üzenetek</h3>
|
<h3>8.4. Privát üzenetek</h3>
|
||||||
<p>
|
<p>
|
||||||
Privát beszélgetést a Kereső rangtól, egy rövid bemutatkozást tartalmazó kéréssel lehet kezdeményezni. A
|
Privát beszélgetést egy rövid bemutatkozást tartalmazó kéréssel lehet kezdeményezni. A
|
||||||
címzett elfogadhatja, elutasíthatja (erről a küldő nem kap értesítést), vagy letilthatja a küldőt. A privát
|
címzett elfogadhatja, elutasíthatja (erről a küldő nem kap értesítést), vagy letilthatja a küldőt. A privát
|
||||||
üzeneteket a moderátorok nem olvassák. Ha valaki egy üzenetet jelent, a moderátorok a jelentett üzenetet és
|
üzeneteket a moderátorok nem olvassák. Ha valaki egy üzenetet jelent, a moderátorok a jelentett üzenetet és
|
||||||
az előtte lévő néhány üzenetet látják, hogy dönteni tudjanak.
|
az előtte lévő néhány üzenetet látják, hogy dönteni tudjanak.
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { copyDialog } from "@/components/Dialogs";
|
||||||
|
import { chromeIntent, type InAppBrowser } from "@/lib/inAppBrowser";
|
||||||
|
|
||||||
|
/** "a Facebook", "az Instagram": the Hungarian article, capitalised at the start of a sentence. */
|
||||||
|
function named(app: string | null): string {
|
||||||
|
if (!app) return "Egy alkalmazás";
|
||||||
|
return `${/^[aáeéiíoóöőuúüű]/i.test(app) ? "Az" : "A"} ${app}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On the login page inside an app's built-in browser (Facebook and co.):
|
||||||
|
* why the Google button is missing, and the way out to the phone's own
|
||||||
|
* browser. On Android a link opens the page in Chrome; on an iPhone only the
|
||||||
|
* app's own menu can, so the text says where, and the link can be copied.
|
||||||
|
*/
|
||||||
|
export function InAppNotice({ browser, url, password }: { browser: InAppBrowser; url: string; password: boolean }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const where = browser.android ? "a Chrome-ban" : "a böngésződben (Safari)";
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url);
|
||||||
|
setCopied(true);
|
||||||
|
} catch {
|
||||||
|
await copyDialog({
|
||||||
|
title: "A belépési oldal linkje",
|
||||||
|
text: "Másold ki, és nyisd meg a böngésződben.",
|
||||||
|
value: url,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="inapp-note" role="note">
|
||||||
|
<strong>{named(browser.app)} beépített böngészőjében vagy</strong>
|
||||||
|
<p>
|
||||||
|
Itt a Google nem engedi a Google-fiókos belépést. {password ? "Lépj be e-mail-címmel, vagy nyisd" : "Nyisd"} meg
|
||||||
|
az oldalt {where}, ott a Google-fiókoddal is beléphetsz.
|
||||||
|
{!browser.android && " Ehhez koppints a jobb felső sarokban a ⋯ gombra, és válaszd a megnyitást böngészőben."}
|
||||||
|
</p>
|
||||||
|
<div className="inapp-actions">
|
||||||
|
{browser.android && (
|
||||||
|
<a className="btn btn-primary" href={chromeIntent(url)}>
|
||||||
|
Megnyitás Chrome-ban
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<button type="button" className="btn" onClick={() => void copy()}>
|
||||||
|
{copied ? "Kimásolva" : "Link másolása"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
|
import { headers } from "next/headers";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
@@ -6,11 +7,14 @@ import { Logo } from "@/components/SiteHeader";
|
|||||||
import { ZodiacWheel } from "@/components/ZodiacWheel";
|
import { ZodiacWheel } from "@/components/ZodiacWheel";
|
||||||
import { BACKEND_URL, getMe } from "@/lib/server";
|
import { BACKEND_URL, getMe } from "@/lib/server";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
|
import { inAppBrowser } from "@/lib/inAppBrowser";
|
||||||
import { contents } from "@/lib/packageContents";
|
import { contents } from "@/lib/packageContents";
|
||||||
|
import { siteUrl } from "@/lib/share";
|
||||||
import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
||||||
|
|
||||||
import { AppleLogin } from "./AppleLogin";
|
import { AppleLogin } from "./AppleLogin";
|
||||||
import { GoogleLogin } from "./GoogleLogin";
|
import { GoogleLogin } from "./GoogleLogin";
|
||||||
|
import { InAppNotice } from "./InAppNotice";
|
||||||
import { PasswordLogin } from "./PasswordLogin";
|
import { PasswordLogin } from "./PasswordLogin";
|
||||||
|
|
||||||
export const metadata: Metadata = { title: "Belépés" };
|
export const metadata: Metadata = { title: "Belépés" };
|
||||||
@@ -123,6 +127,46 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
|||||||
const password = config?.password_login === true;
|
const password = config?.password_login === true;
|
||||||
const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod;
|
const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod;
|
||||||
const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login";
|
const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login";
|
||||||
|
// Facebook's and other apps' built-in browsers: Google refuses to sign in
|
||||||
|
// there, so the e-mail form comes first and the way out to the phone's own
|
||||||
|
// browser (this same page, with its invitation or referral) is offered.
|
||||||
|
const inApp = inAppBrowser((await headers()).get("user-agent") ?? "");
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
for (const [key, value] of Object.entries(params)) {
|
||||||
|
for (const v of Array.isArray(value) ? value : [value]) query.append(key, v);
|
||||||
|
}
|
||||||
|
const here = `${await siteUrl()}/belepes${query.size ? `?${query}` : ""}`;
|
||||||
|
|
||||||
|
const google =
|
||||||
|
clientId && !inApp ? (
|
||||||
|
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||||
|
) : null;
|
||||||
|
const apple =
|
||||||
|
clientId && appleId ? (
|
||||||
|
<AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||||
|
) : null;
|
||||||
|
const social =
|
||||||
|
google || apple ? (
|
||||||
|
<div className="field" style={{ gap: 12 }}>
|
||||||
|
{google}
|
||||||
|
{apple}
|
||||||
|
</div>
|
||||||
|
) : null;
|
||||||
|
const passwordForm = password ? (
|
||||||
|
<PasswordLogin
|
||||||
|
target={target}
|
||||||
|
inviteToken={pendingInvite}
|
||||||
|
referral={referral}
|
||||||
|
initialMode={initialMode}
|
||||||
|
turnstileKey={config?.turnstile_site_key ?? null}
|
||||||
|
/>
|
||||||
|
) : null;
|
||||||
|
const or =
|
||||||
|
social && passwordForm ? (
|
||||||
|
<div className="auth-or" role="separator">
|
||||||
|
<span>vagy</span>
|
||||||
|
</div>
|
||||||
|
) : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="auth">
|
<div className="auth">
|
||||||
@@ -149,35 +193,25 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
|||||||
{rawToken && (
|
{rawToken && (
|
||||||
<InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} password={password} />
|
<InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} password={password} />
|
||||||
)}
|
)}
|
||||||
|
{inApp && config !== null && <InAppNotice browser={inApp} url={here} password={password} />}
|
||||||
{config === null ? (
|
{config === null ? (
|
||||||
<p className="msg msg-error" role="alert">
|
<p className="msg msg-error" role="alert">
|
||||||
A szerver most nem érhető el. Próbáld újra egy kicsit később.
|
A szerver most nem érhető el. Próbáld újra egy kicsit később.
|
||||||
</p>
|
</p>
|
||||||
) : clientId || password ? (
|
) : clientId || password ? (
|
||||||
<>
|
inApp ? (
|
||||||
{clientId && (
|
<>
|
||||||
<div className="field" style={{ gap: 12 }}>
|
{passwordForm}
|
||||||
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} referral={referral} />
|
{or}
|
||||||
{appleId && (
|
{social}
|
||||||
<AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} referral={referral} />
|
</>
|
||||||
)}
|
) : (
|
||||||
</div>
|
<>
|
||||||
)}
|
{social}
|
||||||
{clientId && password && (
|
{or}
|
||||||
<div className="auth-or" role="separator">
|
{passwordForm}
|
||||||
<span>vagy</span>
|
</>
|
||||||
</div>
|
)
|
||||||
)}
|
|
||||||
{password && (
|
|
||||||
<PasswordLogin
|
|
||||||
target={target}
|
|
||||||
inviteToken={pendingInvite}
|
|
||||||
referral={referral}
|
|
||||||
initialMode={initialMode}
|
|
||||||
turnstileKey={config?.turnstile_site_key ?? null}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<p className="msg msg-error" role="alert">
|
<p className="msg msg-error" role="alert">
|
||||||
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
|
||||||
|
interface ForumMail {
|
||||||
|
replies: "off" | "daily" | "instant";
|
||||||
|
followed: "off" | "daily";
|
||||||
|
messages: "off" | "instant";
|
||||||
|
mentions: "off" | "instant";
|
||||||
|
/** Only for volunteer listeners. */
|
||||||
|
listener: "off" | "instant" | null;
|
||||||
|
weekly: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Settings {
|
||||||
|
weekly_horoscope: boolean;
|
||||||
|
forum: ForumMail | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Everything off: the weekly horoscope and every forum e-mail. */
|
||||||
|
function allOff(s: Settings): Settings {
|
||||||
|
return {
|
||||||
|
weekly_horoscope: false,
|
||||||
|
forum: s.forum
|
||||||
|
? {
|
||||||
|
replies: "off",
|
||||||
|
followed: "off",
|
||||||
|
messages: "off",
|
||||||
|
mentions: "off",
|
||||||
|
listener: s.forum.listener === null ? null : "off",
|
||||||
|
weekly: false,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The e-mail settings behind an e-mail's footer link: the token in the link
|
||||||
|
* stands for the login. Nothing changes until a button is pressed (mail
|
||||||
|
* providers' link scanners open every link).
|
||||||
|
*/
|
||||||
|
export function MailSettings({ token }: { token: string | null }) {
|
||||||
|
const [settings, setSettings] = useState<Settings | null>(null);
|
||||||
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [saved, setSaved] = useState<string | null>(null);
|
||||||
|
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!token) return;
|
||||||
|
api<Settings>(`/public/notifications${query}`)
|
||||||
|
.then(setSettings)
|
||||||
|
.catch((e) => setLoadError(errorText(e)));
|
||||||
|
}, [token, query]);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
Hiányzik a link vége. Nyisd meg a teljes linket a levélből.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (loadError) {
|
||||||
|
return (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
Ez a link nem érvényes. Nyisd meg a teljes linket a levélből, vagy lépj be, és a Profil oldalon állítsd be.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!settings) {
|
||||||
|
return <p className="muted">Betöltés…</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(next: Settings, done: string) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setSaved(null);
|
||||||
|
try {
|
||||||
|
setSettings(await api<Settings>(`/public/notifications${query}`, { method: "PUT", body: next }));
|
||||||
|
setSaved(done);
|
||||||
|
} catch (e) {
|
||||||
|
setError(errorText(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const forum = settings.forum;
|
||||||
|
const setForum = (patch: Partial<ForumMail>) => {
|
||||||
|
setSaved(null);
|
||||||
|
setSettings({ ...settings, forum: forum ? { ...forum, ...patch } : null });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card field mail-settings" style={{ gap: 18 }}>
|
||||||
|
<fieldset className="mail-set">
|
||||||
|
<legend>Heti horoszkóp</legend>
|
||||||
|
<label className="check">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.weekly_horoscope}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSaved(null);
|
||||||
|
setSettings({ ...settings, weekly_horoscope: e.target.checked });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span>Hétfőnként szóljatok, ha itt az új heti horoszkópom</span>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
{forum && (
|
||||||
|
<fieldset className="mail-set">
|
||||||
|
<legend>Fórum</legend>
|
||||||
|
<label htmlFor="mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
|
||||||
|
<select
|
||||||
|
id="mail-replies"
|
||||||
|
className="inp"
|
||||||
|
value={forum.replies}
|
||||||
|
onChange={(e) => setForum({ replies: e.target.value as ForumMail["replies"] })}
|
||||||
|
>
|
||||||
|
<option value="daily">Napi összesítőben, este</option>
|
||||||
|
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
</select>
|
||||||
|
<label htmlFor="mail-followed">Új hozzászólás a követett szálaimban</label>
|
||||||
|
<select
|
||||||
|
id="mail-followed"
|
||||||
|
className="inp"
|
||||||
|
value={forum.followed}
|
||||||
|
onChange={(e) => setForum({ followed: e.target.value as ForumMail["followed"] })}
|
||||||
|
>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
<option value="daily">Napi összesítőben, este</option>
|
||||||
|
</select>
|
||||||
|
<label htmlFor="mail-messages">Privát üzenet vagy beszélgetési kérés</label>
|
||||||
|
<select
|
||||||
|
id="mail-messages"
|
||||||
|
className="inp"
|
||||||
|
value={forum.messages}
|
||||||
|
onChange={(e) => setForum({ messages: e.target.value as ForumMail["messages"] })}
|
||||||
|
>
|
||||||
|
<option value="instant">Azonnal</option>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
</select>
|
||||||
|
<label htmlFor="mail-mentions">Ha valaki megemlít</label>
|
||||||
|
<select
|
||||||
|
id="mail-mentions"
|
||||||
|
className="inp"
|
||||||
|
value={forum.mentions}
|
||||||
|
onChange={(e) => setForum({ mentions: e.target.value as ForumMail["mentions"] })}
|
||||||
|
>
|
||||||
|
<option value="instant">Azonnal</option>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
</select>
|
||||||
|
{forum.listener !== null && (
|
||||||
|
<>
|
||||||
|
<label htmlFor="mail-listener">
|
||||||
|
Kísérőként: ha egy meghallgatást kérő szál két órája válasz nélkül vár
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="mail-listener"
|
||||||
|
className="inp"
|
||||||
|
value={forum.listener}
|
||||||
|
onChange={(e) => setForum({ listener: e.target.value as "off" | "instant" })}
|
||||||
|
>
|
||||||
|
<option value="off">Ne küldjetek</option>
|
||||||
|
<option value="instant">Azonnal (hat óránként legfeljebb egy levél)</option>
|
||||||
|
</select>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={forum.weekly} onChange={(e) => setForum({ weekly: e.target.checked })} />
|
||||||
|
<span>Heti összefoglaló vasárnap este: a hét legélénkebb szálai</span>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void save(settings, "Elmentettük a beállításaidat.")}
|
||||||
|
>
|
||||||
|
{busy ? "Mentés…" : "Mentés"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void save(allOff(settings), "Leiratkoztál: ezekről nem küldünk több levelet.")}
|
||||||
|
>
|
||||||
|
Mindenről leiratkozom
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{saved && (
|
||||||
|
<p className="msg msg-ok" role="status">
|
||||||
|
{saved}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="hint" style={{ margin: 0 }}>
|
||||||
|
A jelszóval, a vásárlással és a számlával kapcsolatos leveleket ettől függetlenül megkapod.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
|
||||||
|
import { MailSettings } from "./MailSettings";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: "Értesítések", robots: { index: false } };
|
||||||
|
|
||||||
|
/** Every e-mail setting, from the link in an e-mail's footer (no login needed). */
|
||||||
|
export default async function MailSettingsPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<Record<string, string | string[]>>;
|
||||||
|
}) {
|
||||||
|
const raw = (await searchParams).token;
|
||||||
|
const token = Array.isArray(raw) ? raw[0] : raw;
|
||||||
|
return (
|
||||||
|
<main className="page" style={{ maxWidth: 640 }}>
|
||||||
|
<div className="page-head">
|
||||||
|
<h1>Értesítések</h1>
|
||||||
|
<p className="muted">Itt állíthatod be, miről kérsz levelet a Sorsfonalaktól.</p>
|
||||||
|
</div>
|
||||||
|
<MailSettings token={token ?? null} />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -157,6 +157,9 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{!avatar && <span className="hint">Ha nem választasz, az álneved alapján kapsz egyet.</span>}
|
{!avatar && <span className="hint">Ha nem választasz, az álneved alapján kapsz egyet.</span>}
|
||||||
|
{!member && (
|
||||||
|
<span className="hint">Saját képet az álneved első mentése után tölthetsz fel, itt, ezen az oldalon.</span>
|
||||||
|
)}
|
||||||
{member?.can_upload_avatar && (
|
{member?.can_upload_avatar && (
|
||||||
<div className="fprof-upload">
|
<div className="fprof-upload">
|
||||||
{uploaded && <Avatar avatar={avatar} size={56} />}
|
{uploaded && <Avatar avatar={avatar} size={56} />}
|
||||||
|
|||||||
@@ -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. */
|
/* The forum's menu: a bar at the bottom on phones, tabs in the forum bar on wider screens. */
|
||||||
.forum-nav {
|
.forum-nav {
|
||||||
position: fixed; left: 0; right: 0; bottom: 0; z-index: 25;
|
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);
|
background: var(--f-nav-bg); border-top: 1px solid var(--line);
|
||||||
padding-bottom: env(safe-area-inset-bottom);
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
|
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;
|
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);
|
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; }
|
||||||
|
|||||||
@@ -6,14 +6,30 @@ import { notFound } from "next/navigation";
|
|||||||
import { ForumNav } from "@/components/forum/ForumNav";
|
import { ForumNav } from "@/components/forum/ForumNav";
|
||||||
import { ThemeToggle } from "@/components/forum/ThemeToggle";
|
import { ThemeToggle } from "@/components/forum/ThemeToggle";
|
||||||
import { PublicHeader } from "@/components/SiteHeader";
|
import { PublicHeader } from "@/components/SiteHeader";
|
||||||
import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
import { FORUM_PREVIEW, FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
||||||
import { forumEnabled, forumGet } from "@/lib/forumServer";
|
import { forumEnabled, forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
import "./forum.css";
|
import "./forum.css";
|
||||||
|
|
||||||
|
const DESCRIPTION = "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
|
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
|
||||||
description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.",
|
description: DESCRIPTION,
|
||||||
|
openGraph: {
|
||||||
|
type: "website",
|
||||||
|
siteName: "Sorsfonalak",
|
||||||
|
locale: "hu_HU",
|
||||||
|
title: "Sorsfonalak fórum",
|
||||||
|
description: DESCRIPTION,
|
||||||
|
images: [FORUM_PREVIEW],
|
||||||
|
},
|
||||||
|
twitter: {
|
||||||
|
card: "summary_large_image",
|
||||||
|
title: "Sorsfonalak fórum",
|
||||||
|
description: DESCRIPTION,
|
||||||
|
images: [FORUM_PREVIEW.url],
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { useState } from "react";
|
|||||||
import { PostBody } from "@/components/forum/PostBody";
|
import { PostBody } from "@/components/forum/PostBody";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { REPORT_KINDS, type ReportEntry, ago, memberHref, threadHref } from "@/lib/forum";
|
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" };
|
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;
|
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 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 } }));
|
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 { RankBadge } from "@/components/forum/Badges";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { type ForumTopic, type TopicRequest, ago } from "@/lib/forum";
|
import { type ForumTopic, type TopicRequest, ago } from "@/lib/forum";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const VISIBILITY: Record<string, string> = {
|
const VISIBILITY: Record<string, string> = {
|
||||||
public: "Nyilvános (a keresők is látják)",
|
public: "Nyilvános (a keresők is látják)",
|
||||||
@@ -122,10 +123,14 @@ export function TopicsAdmin({
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-sm btn-ghost"
|
className="btn btn-sm btn-ghost"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={() =>
|
onClick={async () => {
|
||||||
window.confirm(`Eltávolítod ${r.member?.nickname} tagot a(z) „${r.topic.name}” témából?`) &&
|
const ok = await confirmDialog({
|
||||||
decide(r, "remove")
|
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
|
Eltávolítom
|
||||||
</button>
|
</button>
|
||||||
@@ -151,13 +156,17 @@ export function TopicsAdmin({
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-sm btn-ghost"
|
className="btn btn-sm btn-ghost"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={() =>
|
onClick={async () => {
|
||||||
(t.archived ||
|
const ok =
|
||||||
window.confirm(
|
t.archived ||
|
||||||
`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.`,
|
(await confirmDialog({
|
||||||
)) &&
|
title: `Archiválod a(z) „${t.name}” témát?`,
|
||||||
act(() => api(`/forum/topics/${t.slug}`, { method: "PATCH", body: { archived: !t.archived } }))
|
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"}
|
{t.archived ? "Visszaállítás" : "Archiválás"}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { TopicIcon } from "@/components/forum/TopicIcon";
|
|||||||
import { ThreadList, WaitingCard } from "@/components/forum/ThreadList";
|
import { ThreadList, WaitingCard } from "@/components/forum/ThreadList";
|
||||||
import { MoonPhaseIcon } from "@/components/MoonChip";
|
import { MoonPhaseIcon } from "@/components/MoonChip";
|
||||||
import { MOON_PHASES, SIGNS } from "@/lib/astro";
|
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 { forumGet } from "@/lib/forumServer";
|
||||||
import { loadSky } from "@/lib/sky";
|
import { loadSky } from "@/lib/sky";
|
||||||
import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText";
|
import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText";
|
||||||
@@ -61,10 +61,16 @@ function SkyCard({ sky }: { sky: SkyNow }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function ForumHomePage() {
|
export default async function ForumHomePage({ searchParams }: { searchParams: Promise<{ oldal?: string }> }) {
|
||||||
const [home, sky] = await Promise.all([forumGet<ForumHome>("/v1/forum/home"), loadSky()]);
|
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();
|
if (!home.ok) notFound();
|
||||||
const { viewer, replies, waiting, topics, unanswered, hot } = home.data;
|
const { viewer, replies, waiting, topics, unanswered, hot } = home.data;
|
||||||
|
const pinned = home.data.pinned ?? [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fh fh-home">
|
<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.
|
álnéven ír, a tempó nyugodt, és a meghallgatás fontosabb a vitánál.
|
||||||
</p>
|
</p>
|
||||||
<p className="hint">
|
<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>
|
</p>
|
||||||
<Link href="/belepes?vissza=/forum" className="btn btn-primary">
|
<Link href="/belepes?vissza=/forum" className="btn btn-primary">
|
||||||
Belépés
|
Belépés
|
||||||
@@ -135,6 +142,17 @@ export default async function ForumHomePage() {
|
|||||||
</section>
|
</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">
|
<section className="fh-section o-6" aria-labelledby="fh-topics">
|
||||||
<div className="fh-section-head">
|
<div className="fh-section-head">
|
||||||
<h2 id="fh-topics">Témák</h2>
|
<h2 id="fh-topics">Témák</h2>
|
||||||
@@ -234,6 +252,25 @@ export default async function ForumHomePage() {
|
|||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
</section>
|
</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>
|
</div>
|
||||||
|
|
||||||
<aside className="fh-col fh-col-side" aria-label="Oldalsáv">
|
<aside className="fh-col fh-col-side" aria-label="Oldalsáv">
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
|||||||
import { notFound, permanentRedirect, redirect } from "next/navigation";
|
import { notFound, permanentRedirect, redirect } from "next/navigation";
|
||||||
|
|
||||||
import { ThreadView } from "@/components/forum/ThreadView";
|
import { ThreadView } from "@/components/forum/ThreadView";
|
||||||
import type { ThreadPage } from "@/lib/forum";
|
import { FORUM_PREVIEW, type ThreadPage } from "@/lib/forum";
|
||||||
import { forumGet } from "@/lib/forumServer";
|
import { forumGet } from "@/lib/forumServer";
|
||||||
|
|
||||||
type Props = { params: Promise<{ id: string }> };
|
type Props = { params: Promise<{ id: string }> };
|
||||||
@@ -19,18 +19,42 @@ async function load(param: string) {
|
|||||||
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
|
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The start of a post for a description: one line, cut at a word, at most `max` characters. */
|
||||||
|
function excerpt(text: string, max: number): string {
|
||||||
|
const line = text.replace(/\s+/g, " ").trim();
|
||||||
|
if (line.length <= max) return line;
|
||||||
|
const cut = line.slice(0, max - 1);
|
||||||
|
const words = cut.slice(0, Math.max(cut.lastIndexOf(" "), max / 2)).trimEnd();
|
||||||
|
return `${words.replace(/[.,;:!?–-]+$/, "")}…`;
|
||||||
|
}
|
||||||
|
|
||||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
const res = await load((await params).id);
|
const res = await load((await params).id);
|
||||||
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
|
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
|
||||||
const { thread, posts } = res.data;
|
const { thread, posts } = res.data;
|
||||||
const open = thread.topic.visibility === "public" && !thread.deleted;
|
const open = thread.topic.visibility === "public" && !thread.deleted;
|
||||||
const opening = posts.find((p) => p.is_opening)?.body ?? "";
|
const opening = posts.find((p) => p.is_opening)?.body ?? "";
|
||||||
|
const url = `/forum/szal/${thread.id}-${thread.slug}`;
|
||||||
|
// The link preview: a public thread's title and opening words; of a
|
||||||
|
// members-only or removed one nothing (link previews are public).
|
||||||
|
const preview = open
|
||||||
|
? { title: thread.title, description: excerpt(opening, 200) }
|
||||||
|
: { title: "Sorsfonalak fórum", description: "Beszélgetés a Sorsfonalak fórumán." };
|
||||||
return {
|
return {
|
||||||
title: thread.title,
|
title: thread.title,
|
||||||
description: open ? opening.slice(0, 160) : undefined,
|
description: open ? excerpt(opening, 160) : undefined,
|
||||||
alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` },
|
alternates: { canonical: url },
|
||||||
// Members-only topics and removed threads stay out of search engines.
|
// Members-only topics and removed threads stay out of search engines.
|
||||||
robots: open ? undefined : { index: false, follow: false },
|
robots: open ? undefined : { index: false, follow: false },
|
||||||
|
openGraph: {
|
||||||
|
type: "article",
|
||||||
|
siteName: "Sorsfonalak",
|
||||||
|
locale: "hu_HU",
|
||||||
|
url,
|
||||||
|
...preview,
|
||||||
|
images: [FORUM_PREVIEW],
|
||||||
|
},
|
||||||
|
twitter: { card: "summary_large_image", ...preview, images: [FORUM_PREVIEW.url] },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
const DURATIONS: { hours: number | null; label: string }[] = [
|
const DURATIONS: { hours: number | null; label: string }[] = [
|
||||||
{ hours: 3, label: "3 óra" },
|
{ hours: 3, label: "3 óra" },
|
||||||
@@ -45,10 +46,15 @@ export function BanPanel({ nickname, banned, ownPicture }: { nickname: string; b
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-sm"
|
className="btn btn-sm"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={() =>
|
onClick={async () => {
|
||||||
window.confirm("Visszaállítod a kezdő avatart? A feltöltött kép törlődik.") &&
|
const ok = await confirmDialog({
|
||||||
act(() => api(`/forum/members/${encodeURIComponent(nickname)}/avatar-reset`, { method: "POST" }))
|
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
|
Saját kép eltávolítása
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { api, errorText } from "@/lib/api";
|
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). */
|
/** 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 }) {
|
export function FounderToggle({ nickname, founder }: { nickname: string; founder: boolean }) {
|
||||||
@@ -19,7 +20,12 @@ export function FounderToggle({ nickname, founder }: { nickname: string; founder
|
|||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (
|
if (
|
||||||
founder &&
|
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;
|
return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { api, errorText } from "@/lib/api";
|
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. */
|
/** "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 }) {
|
export function MuteButton({ nickname, muted }: { nickname: string; muted: boolean }) {
|
||||||
@@ -19,9 +20,11 @@ export function MuteButton({ nickname, muted }: { nickname: string; muted: boole
|
|||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (
|
if (
|
||||||
!muted &&
|
!muted &&
|
||||||
!window.confirm(
|
!(await confirmDialog({
|
||||||
`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.`,
|
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;
|
return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ export function RequestPanel({ nickname, relation }: { nickname: string; relatio
|
|||||||
if (relation.state === "blocked_by_me")
|
if (relation.state === "blocked_by_me")
|
||||||
return <p className="hint">Letiltottad. A tiltást az üzeneteidnél oldhatod fel.</p>;
|
return <p className="hint">Letiltottad. A tiltást az üzeneteidnél oldhatod fel.</p>;
|
||||||
if (!relation.eligible) {
|
if (!relation.eligible) {
|
||||||
return <p className="hint">Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba.</p>;
|
return <p className="hint">Most nem kezdeményezhetsz beszélgetést.</p>;
|
||||||
}
|
}
|
||||||
if (!relation.can_request) return null;
|
if (!relation.can_request) return null;
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ import Link from "next/link";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { PhotoButton, PickedPhotos } from "@/components/forum/Photos";
|
||||||
import { ShareCard } from "@/components/forum/ShareCard";
|
import { ShareCard } from "@/components/forum/ShareCard";
|
||||||
import { TopicIcon } from "@/components/forum/TopicIcon";
|
import { TopicIcon } from "@/components/forum/TopicIcon";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
||||||
import { type ForumTopic, type ShareCardData, threadHref } from "@/lib/forum";
|
import { type ForumTopic, type ShareCardData, threadHref } from "@/lib/forum";
|
||||||
|
import { usePhotoUploads } from "@/lib/photos";
|
||||||
|
|
||||||
type Intent = "listen" | "advice" | "";
|
type Intent = "listen" | "advice" | "";
|
||||||
|
|
||||||
@@ -75,6 +77,7 @@ export function NewThreadForm({
|
|||||||
const [body, setBody] = useState("");
|
const [body, setBody] = useState("");
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const picked = usePhotoUploads();
|
||||||
// A listening topic: hearing or opinions, no small talk.
|
// A listening topic: hearing or opinions, no small talk.
|
||||||
const choices = INTENT_CHOICES.filter((c) => !listening || c.value !== "");
|
const choices = INTENT_CHOICES.filter((c) => !listening || c.value !== "");
|
||||||
const intentHint = choices.find((c) => c.value === intent)?.hint;
|
const intentHint = choices.find((c) => c.value === intent)?.hint;
|
||||||
@@ -87,7 +90,7 @@ export function NewThreadForm({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
if (busy || !title.trim() || !body.trim() || !topic) return;
|
if (busy || picked.busy || !title.trim() || !body.trim() || !topic) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
@@ -98,6 +101,7 @@ export function NewThreadForm({
|
|||||||
body: convertEmoticons(body, body.length, true).text,
|
body: convertEmoticons(body, body.length, true).text,
|
||||||
intent: intent || null,
|
intent: intent || null,
|
||||||
share: share?.slug ?? null,
|
share: share?.slug ?? null,
|
||||||
|
photos: picked.ids,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
router.push(threadHref(created));
|
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">
|
<div className="fnew-foot">
|
||||||
<span className="hint">
|
<span className="fnew-foot-left">
|
||||||
Kérjük, tartsd be a <Link href="/aszf#forum">házirendet</Link>.
|
<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>
|
</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
disabled={busy || !title.trim() || !body.trim() || !topic}
|
disabled={busy || picked.busy || !title.trim() || !body.trim() || !topic}
|
||||||
onClick={() => void submit()}
|
onClick={() => void submit()}
|
||||||
>
|
>
|
||||||
{busy ? "Küldés…" : "Szál indítása"}
|
{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 { Avatar } from "@/components/forum/Avatar";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { type ConversationItem, ago } from "@/lib/forum";
|
import { type ConversationItem, ago } from "@/lib/forum";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
export function Conversations({ initial }: { initial: ConversationItem[] }) {
|
export function Conversations({ initial }: { initial: ConversationItem[] }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -86,7 +87,15 @@ export function Conversations({ initial }: { initial: ConversationItem[] }) {
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-ghost btn-sm"
|
className="btn btn-ghost btn-sm"
|
||||||
disabled={busy === c.id}
|
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
|
Letiltom
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { ReportButton } from "@/components/forum/ReportButton";
|
|||||||
import { TypingLine, useTypingSender, useTypingWatch } from "@/components/forum/typing";
|
import { TypingLine, useTypingSender, useTypingWatch } from "@/components/forum/typing";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum";
|
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. */
|
/** A safety net: how often an open conversation looks for new messages anyway. */
|
||||||
const POLL_MS = 30_000;
|
const POLL_MS = 30_000;
|
||||||
@@ -140,7 +141,15 @@ export function Chat({ initial }: { initial: ConversationPage }) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="danger"
|
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
|
Letiltás
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -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 dt { font-size: 12px; color: var(--muted); }
|
||||||
.balance-grid dd { margin: 0; font-size: 18px; color: var(--ink); }
|
.balance-grid dd { margin: 0; font-size: 18px; color: var(--ink); }
|
||||||
@media (max-width: 480px) { .modal-inner { padding: 18px 16px 20px; } }
|
@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 { 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 { 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; }
|
.prompt-kind-head > p { flex: 1 1 360px; margin: 0; }
|
||||||
@@ -1020,8 +1034,6 @@ a.pair-row:hover strong { color: var(--gold); }
|
|||||||
.lp-caption { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
|
.lp-caption { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
|
||||||
.lp-caption .share-trio { justify-content: center; font-size: 15px; }
|
.lp-caption .share-trio { justify-content: center; font-size: 15px; }
|
||||||
.lp-asc { color: var(--gold); font-weight: 600; font-size: 12px; letter-spacing: 0.5px; }
|
.lp-asc { color: var(--gold); font-weight: 600; font-size: 12px; letter-spacing: 0.5px; }
|
||||||
.lp-rise { opacity: 0; transform: translateY(14px); animation: lp-rise 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) forwards; }
|
|
||||||
.lp-r1 { animation-delay: 0.1s; } .lp-r2 { animation-delay: 0.25s; } .lp-r3 { animation-delay: 0.4s; } .lp-r4 { animation-delay: 0.55s; }
|
|
||||||
|
|
||||||
.lp-band { border-top: 1px solid var(--line); padding: 96px 0; }
|
.lp-band { border-top: 1px solid var(--line); padding: 96px 0; }
|
||||||
.lp-alt { background: var(--panel-2); }
|
.lp-alt { background: var(--panel-2); }
|
||||||
@@ -1098,7 +1110,6 @@ body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
|||||||
@keyframes lp-fade { to { opacity: 1; } }
|
@keyframes lp-fade { to { opacity: 1; } }
|
||||||
@keyframes lp-draw { to { stroke-dashoffset: 0; } }
|
@keyframes lp-draw { to { stroke-dashoffset: 0; } }
|
||||||
@keyframes lp-spin { to { transform: rotate(360deg); } }
|
@keyframes lp-spin { to { transform: rotate(360deg); } }
|
||||||
@keyframes lp-rise { to { opacity: 1; transform: none; } }
|
|
||||||
@keyframes lp-float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }
|
@keyframes lp-float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }
|
||||||
@keyframes lp-pulse { 0%, 100% { transform: scale(1); opacity: 0.9; } 50% { transform: scale(1.6); opacity: 0.2; } }
|
@keyframes lp-pulse { 0%, 100% { transform: scale(1); opacity: 0.9; } 50% { transform: scale(1.6); opacity: 0.2; } }
|
||||||
@media (max-width: 900px) { .lp-analysis-grid { grid-template-columns: minmax(0, 1fr); } }
|
@media (max-width: 900px) { .lp-analysis-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||||
@@ -1127,7 +1138,7 @@ body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
|||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.lp *, .lp-orbit { animation: none !important; }
|
.lp *, .lp-orbit { animation: none !important; }
|
||||||
.lp-rise, .lp-wheel .w-point { opacity: 1; transform: none; }
|
.lp-wheel .w-point { opacity: 1; transform: none; }
|
||||||
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
|
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
|
||||||
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
|
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
|
||||||
}
|
}
|
||||||
@@ -1396,7 +1407,7 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* The ☰ menu: instead of the header's link rows where they no longer fit
|
/* The ☰ menu: instead of the header's link rows where they no longer fit
|
||||||
on one line (logged out below 1240px; logged in below 1380px, with more
|
on one line (logged out below 1240px; logged in below 1520px, with more
|
||||||
links and the package). */
|
links and the package). */
|
||||||
.mobile-menu { display: none; margin-left: auto; }
|
.mobile-menu { display: none; margin-left: auto; }
|
||||||
.mobile-menu-button {
|
.mobile-menu-button {
|
||||||
@@ -1425,7 +1436,7 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
@media (max-width: 1500px) {
|
@media (max-width: 1500px) {
|
||||||
.site-header .pkg-pill-detail { display: none; }
|
.site-header .pkg-pill-detail { display: none; }
|
||||||
}
|
}
|
||||||
@media (max-width: 1380px) {
|
@media (max-width: 1520px) {
|
||||||
.mobile-menu-app { display: block; }
|
.mobile-menu-app { display: block; }
|
||||||
.site-header .app-nav { display: none; }
|
.site-header .app-nav { display: none; }
|
||||||
.site-header .who { margin-left: auto; }
|
.site-header .who { margin-left: auto; }
|
||||||
@@ -1814,3 +1825,61 @@ span.tarot-fan-card { cursor: default; }
|
|||||||
}
|
}
|
||||||
.pw-eye:hover, .pw-eye:focus-visible { color: var(--gold); }
|
.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; }
|
.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; } }
|
||||||
|
|
||||||
|
/* Login inside Facebook's or another app's built-in browser: why, and the way out. */
|
||||||
|
.inapp-note {
|
||||||
|
display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; font-size: 14px;
|
||||||
|
border: 1px solid rgba(217, 180, 106, 0.45); background: rgba(217, 180, 106, 0.07); border-radius: 10px;
|
||||||
|
}
|
||||||
|
.inapp-note p { margin: 0; color: var(--ink-2); }
|
||||||
|
.inapp-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||||
|
|
||||||
|
/* The weekly horoscope page (one month at a time) and its link on the chart page. */
|
||||||
|
.weekly-card { gap: 10px; }
|
||||||
|
.weekly-text p { margin: 0 0 10px; }
|
||||||
|
.weekly-text p:last-child { margin-bottom: 0; }
|
||||||
|
.weekly-pager { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 10px; }
|
||||||
|
.weekly-pager > :first-child { justify-self: start; }
|
||||||
|
.weekly-pager > :last-child { justify-self: end; }
|
||||||
|
.weekly-pager strong { font-family: var(--font-display); font-size: 22px; font-weight: 600; text-align: center; }
|
||||||
|
.weekly-teaser { display: flex; flex-direction: column; gap: 6px; text-decoration: none; color: var(--ink-2); border-color: rgba(217, 180, 106, 0.35); }
|
||||||
|
.weekly-teaser:hover { border-color: var(--gold); }
|
||||||
|
.weekly-teaser-more { color: var(--gold); font-weight: 500; }
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.weekly-pager { grid-template-columns: 1fr 1fr; }
|
||||||
|
.weekly-pager strong { grid-column: 1 / -1; grid-row: 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The e-mail settings behind an e-mail's footer link. */
|
||||||
|
.mail-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
|
||||||
|
.mail-set legend { font-family: var(--font-display); font-size: 20px; font-weight: 600; margin-bottom: 4px; }
|
||||||
|
.mail-set label:not(.check) { font-size: 14px; color: var(--ink-2); margin-top: 6px; }
|
||||||
|
.weekly-landing-lead { font-size: 17px; line-height: 1.6; max-width: 640px; }
|
||||||
|
.weekly-landing-actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 6px; }
|
||||||
|
.weekly-steps { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 10px; color: var(--ink-2); line-height: 1.55; }
|
||||||
|
.weekly-steps strong { color: var(--ink); font-weight: 600; }
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { Paragraphs } from "@/components/Rich";
|
||||||
|
import example from "@/content/pelda-heti.json";
|
||||||
|
import { weekRange } from "@/lib/weekly";
|
||||||
|
|
||||||
|
const LOGIN = "/belepes?vissza=/heti-horoszkop";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The weekly horoscope for visitors: what it is, a real example written for
|
||||||
|
* the example chart (the one of the Példaelemzés page), and the way in.
|
||||||
|
*/
|
||||||
|
export function WeeklyLanding() {
|
||||||
|
return (
|
||||||
|
<main className="page weekly-landing" style={{ maxWidth: 820 }}>
|
||||||
|
<div className="page-head">
|
||||||
|
<span className="eyebrow">Ingyenes · hétfőnként új</span>
|
||||||
|
<h1>Heti horoszkóp, ami rólad szól</h1>
|
||||||
|
<p className="muted weekly-landing-lead">
|
||||||
|
Nem a csillagjegyedre írt általános szöveg: a hét égboltját a saját születési képletedre vetítjük. Melyik
|
||||||
|
bolygó milyen fényszöget alkot a te pontjaiddal, melyik napon, és mit kérhet tőled a héten.
|
||||||
|
</p>
|
||||||
|
<div className="weekly-landing-actions">
|
||||||
|
<Link href={LOGIN} className="btn btn-primary lp-btn">
|
||||||
|
Belépés
|
||||||
|
</Link>
|
||||||
|
<Link href={`/belepes?mod=regisztracio&vissza=/heti-horoszkop`} className="btn lp-btn">
|
||||||
|
Regisztráció
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<article className="card summary-card weekly-card" aria-labelledby="weekly-example-title">
|
||||||
|
<span className="eyebrow">Példa · {weekRange(example.week_start, example.week_end)}</span>
|
||||||
|
<h2 id="weekly-example-title" className="summary-title">
|
||||||
|
{example.title}
|
||||||
|
</h2>
|
||||||
|
<div className="summary-text weekly-text" lang="hu">
|
||||||
|
<Paragraphs text={example.text} />
|
||||||
|
</div>
|
||||||
|
<p className="hint" style={{ margin: 0 }}>
|
||||||
|
Ezt a heti horoszkópot a <Link href="/pelda">példaelemzés</Link> kitalált képletéhez írtuk (1990. március 15.,
|
||||||
|
14:30, Szeged), ugyanúgy, ahogy a tiédet is megírjuk.
|
||||||
|
</p>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<section className="card field weekly-how" aria-labelledby="weekly-how-title" style={{ gap: 12 }}>
|
||||||
|
<h2 id="weekly-how-title">Hogyan működik?</h2>
|
||||||
|
<ol className="weekly-steps">
|
||||||
|
<li>
|
||||||
|
<strong>Megadod, mikor és hol születtél.</strong> Ebből percre pontosan kiszámoljuk a születési képletedet.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Hétfőnként új heti horoszkópot kapsz,</strong> a te képletedből és a hét égboltjából: a hét fő
|
||||||
|
témája, a kulcsnapok és egy javaslat.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Hétfő reggel e-mailben szólunk,</strong> hogy itt az új. Ha nem kéred, egy kattintással
|
||||||
|
kikapcsolhatod.
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
<div>
|
||||||
|
<Link href={LOGIN} className="btn btn-primary">
|
||||||
|
Belépés, és kérem a heti horoszkópomat
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import { WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import type { Analysis } from "@/lib/types";
|
||||||
|
import { MONTHS } from "@/lib/weekly";
|
||||||
|
|
||||||
|
const POLL_MS = 3000;
|
||||||
|
const MAX_POLLS = 60;
|
||||||
|
|
||||||
|
interface Week {
|
||||||
|
week_start: string;
|
||||||
|
week_end: string;
|
||||||
|
analysis: Analysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Month {
|
||||||
|
month: string;
|
||||||
|
current_month: string;
|
||||||
|
this_week: string;
|
||||||
|
weeks: Week[];
|
||||||
|
older: string | null;
|
||||||
|
newer: string | null;
|
||||||
|
email: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026. november". */
|
||||||
|
function monthName(key: string): string {
|
||||||
|
const [y, m] = key.split("-").map(Number);
|
||||||
|
return `${y}. ${MONTHS[m - 1]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One month of weekly horoscopes, the newest week first. In this month the
|
||||||
|
* week's horoscope is asked for first (queued if new), then read until the
|
||||||
|
* worker has written it (or given up); meanwhile its card shows the waiting
|
||||||
|
* animation.
|
||||||
|
*/
|
||||||
|
export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin: boolean }) {
|
||||||
|
const [data, setData] = useState<Month | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [gaveUp, setGaveUp] = useState(false);
|
||||||
|
// Bumped when an admin has this week's text written again: polls anew.
|
||||||
|
const [round, setRound] = useState(0);
|
||||||
|
const query = month ? `?month=${month}` : "";
|
||||||
|
|
||||||
|
/** This week's horoscope into the list (it may not be there yet). */
|
||||||
|
const putWeek = (week: Week) =>
|
||||||
|
setData((d) => (d ? { ...d, weeks: [week, ...d.weeks.filter((w) => w.week_start !== week.week_start)] } : d));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let stopped = false;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
const wait = () => new Promise((resolve) => (timer = setTimeout(resolve, POLL_MS)));
|
||||||
|
/**
|
||||||
|
* This week's text: asked for once (queued if new, or written again if
|
||||||
|
* the last attempt failed), then only read until the worker is done.
|
||||||
|
*/
|
||||||
|
const follow = async () => {
|
||||||
|
let week: Week | null = null;
|
||||||
|
for (let tries = 0; !week && tries < 5 && !stopped; tries++) {
|
||||||
|
try {
|
||||||
|
const got = await api<Week & { email: boolean }>("/weekly", { method: "POST" });
|
||||||
|
week = { week_start: got.week_start, week_end: got.week_end, analysis: got.analysis };
|
||||||
|
} catch {
|
||||||
|
await wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!week || stopped) return setGaveUp(!stopped);
|
||||||
|
putWeek(week);
|
||||||
|
for (let polls = 0; !stopped; polls++) {
|
||||||
|
const { status } = week.analysis;
|
||||||
|
if (status === "done" || status === "failed") return;
|
||||||
|
if (polls >= MAX_POLLS) return setGaveUp(true);
|
||||||
|
await wait();
|
||||||
|
try {
|
||||||
|
const id: string = week.analysis.id;
|
||||||
|
const analysis: Analysis = await api<Analysis>(`/analyses/${id}`);
|
||||||
|
if (stopped) return;
|
||||||
|
week = { ...week, analysis };
|
||||||
|
putWeek(week);
|
||||||
|
} catch {
|
||||||
|
// try again on the next tick
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const page = await api<Month>(`/weekly/history${query}`);
|
||||||
|
if (stopped) return;
|
||||||
|
setData(page);
|
||||||
|
if (page.month === page.current_month) await follow();
|
||||||
|
} catch (e) {
|
||||||
|
if (!stopped) setError(errorText(e));
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, [query, round]);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return <p className="muted">Betöltés…</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const restarted = (week: Week) => (a: Analysis) => {
|
||||||
|
setGaveUp(false);
|
||||||
|
setData((d) =>
|
||||||
|
d ? { ...d, weeks: d.weeks.map((w) => (w.week_start === week.week_start ? { ...w, analysis: a } : w)) } : d,
|
||||||
|
);
|
||||||
|
if (week.week_start === data.this_week) setRound((r) => r + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const pager = (
|
||||||
|
<nav className="weekly-pager" aria-label="Hónapok">
|
||||||
|
{data.older ? (
|
||||||
|
<Link href={`/heti-horoszkop?honap=${data.older}`} className="btn btn-sm">
|
||||||
|
← Korábbi hónap
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
<strong>{monthName(data.month)}</strong>
|
||||||
|
{data.newer ? (
|
||||||
|
<Link
|
||||||
|
href={data.newer === data.current_month ? "/heti-horoszkop" : `/heti-horoszkop?honap=${data.newer}`}
|
||||||
|
className="btn btn-sm"
|
||||||
|
>
|
||||||
|
Újabb hónap →
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="field" style={{ gap: 18 }}>
|
||||||
|
{pager}
|
||||||
|
{data.weeks.length === 0 ? (
|
||||||
|
<p className="muted">Ebben a hónapban nem nézted meg a heti horoszkópodat.</p>
|
||||||
|
) : (
|
||||||
|
data.weeks.map((w) => (
|
||||||
|
<WeekCard
|
||||||
|
key={w.week_start}
|
||||||
|
start={w.week_start}
|
||||||
|
end={w.week_end}
|
||||||
|
analysis={w.analysis}
|
||||||
|
current={w.week_start === data.this_week}
|
||||||
|
gaveUp={w.week_start === data.this_week && gaveUp}
|
||||||
|
isAdmin={isAdmin}
|
||||||
|
onRestarted={restarted(w)}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
{(data.older || data.newer) && data.weeks.length > 1 && pager}
|
||||||
|
<div className="card">
|
||||||
|
<WeeklyEmailSwitch initial={data.email} label="Hétfőnként szóljatok e-mailben, ha itt az új heti horoszkópom" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { PublicHeader } from "@/components/SiteHeader";
|
||||||
|
import { getMe } from "@/lib/server";
|
||||||
|
import { siteUrl } from "@/lib/share";
|
||||||
|
|
||||||
|
import { WeeklyLanding } from "./Landing";
|
||||||
|
import { WeeklyPage } from "./WeeklyPage";
|
||||||
|
|
||||||
|
/** Bumped when the preview image changes, so Facebook and co. fetch it again. */
|
||||||
|
const PREVIEW_VERSION = 1;
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
const base = await siteUrl();
|
||||||
|
const title = "Heti horoszkóp, ami rólad szól";
|
||||||
|
const description =
|
||||||
|
"Ingyenes, hétfőnként új személyes heti horoszkóp a saját születési képletedből és a hét égboltjából: a hét fő témája, a kulcsnapok és egy javaslat.";
|
||||||
|
const image = { url: `${base}/kep/heti-horoszkop.png?v=${PREVIEW_VERSION}`, width: 1200, height: 630, alt: title };
|
||||||
|
return {
|
||||||
|
title: "Heti horoszkóp",
|
||||||
|
description,
|
||||||
|
alternates: { canonical: `${base}/heti-horoszkop` },
|
||||||
|
openGraph: {
|
||||||
|
type: "website",
|
||||||
|
siteName: "Sorsfonalak",
|
||||||
|
locale: "hu_HU",
|
||||||
|
url: `${base}/heti-horoszkop`,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
images: [image],
|
||||||
|
},
|
||||||
|
twitter: { card: "summary_large_image", title, description, images: [image.url] },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The weekly horoscope. Members: their own, one month at a time, the newest
|
||||||
|
* first (`?honap=2026-11` pages back); this week's is written when the page
|
||||||
|
* opens. Visitors: what it is, with an example, and the way in.
|
||||||
|
*/
|
||||||
|
export default async function WeeklyHoroscopePage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<Record<string, string | string[]>>;
|
||||||
|
}) {
|
||||||
|
const me = await getMe();
|
||||||
|
if (!me) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PublicHeader />
|
||||||
|
<WeeklyLanding />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const raw = (await searchParams).honap;
|
||||||
|
const month = (Array.isArray(raw) ? raw[0] : raw) ?? null;
|
||||||
|
return (
|
||||||
|
<main className="page" style={{ maxWidth: 760 }}>
|
||||||
|
<div className="page-head">
|
||||||
|
<h1>Heti horoszkóp</h1>
|
||||||
|
<p className="muted">Hétfőnként új, a saját képletedből és a hét égboltjából.</p>
|
||||||
|
</div>
|
||||||
|
{me.primary_chart_id ? (
|
||||||
|
<WeeklyPage
|
||||||
|
key={month ?? "now"}
|
||||||
|
month={month && /^\d{4}-\d{2}$/.test(month) ? month : null}
|
||||||
|
isAdmin={me.user.roles.includes("admin")}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="card field" style={{ gap: 12 }}>
|
||||||
|
<p style={{ margin: 0 }}>A heti horoszkóphoz előbb add meg a születési adataidat.</p>
|
||||||
|
<div>
|
||||||
|
<Link href="/profil#birth" className="btn btn-primary">
|
||||||
|
Születési adatok megadása
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// The link preview image of the forum's pages (og:image), drawn from the
|
||||||
|
// example chart. The pages link it with a version (?v=…).
|
||||||
|
import example from "@/content/pelda.json";
|
||||||
|
import { chartCard } from "@/lib/ogCard";
|
||||||
|
import type { ChartResult } from "@/lib/types";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
return chartCard({
|
||||||
|
chart: example.chart as unknown as ChartResult,
|
||||||
|
timeKnown: true,
|
||||||
|
eyebrow: "SORSFONALAK FÓRUM",
|
||||||
|
title: "Ahol meghallgatnak.",
|
||||||
|
text: "Beszélgetés, meghallgatás, asztrológia és álmok: egy nyugodt, figyelmes közösség.",
|
||||||
|
lines: [
|
||||||
|
{ glyph: "☽", label: "Meghallgatás" },
|
||||||
|
{ glyph: "☿", label: "Beszélgetés" },
|
||||||
|
{ glyph: "♀", label: "Asztrológia" },
|
||||||
|
],
|
||||||
|
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// The link preview image of the weekly horoscope page (og:image), drawn from
|
||||||
|
// the example chart. The page links it with a version (?v=…).
|
||||||
|
import example from "@/content/pelda.json";
|
||||||
|
import { chartCard } from "@/lib/ogCard";
|
||||||
|
import type { ChartResult } from "@/lib/types";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
return chartCard({
|
||||||
|
chart: example.chart as unknown as ChartResult,
|
||||||
|
timeKnown: true,
|
||||||
|
eyebrow: "HETI HOROSZKÓP",
|
||||||
|
title: "A te heted, nem a csillagjegyedé.",
|
||||||
|
text: "Hétfőnként új, személyes horoszkóp a saját születési képletedből és a hét égboltjából. Ingyenes.",
|
||||||
|
lines: [
|
||||||
|
{ glyph: "☉", label: "A saját képletedből" },
|
||||||
|
{ glyph: "☽", label: "A hét égboltjából" },
|
||||||
|
{ glyph: "☿", label: "Hétfőnként új" },
|
||||||
|
],
|
||||||
|
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -87,6 +87,15 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
|||||||
referralOpen={config?.referral_rewards ?? false}
|
referralOpen={config?.referral_rewards ?? false}
|
||||||
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
|
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
|
||||||
/>
|
/>
|
||||||
|
{chart.id === me.primary_chart_id && (
|
||||||
|
<Link href="/heti-horoszkop" className="card weekly-teaser">
|
||||||
|
<span className="eyebrow">Heti horoszkóp</span>
|
||||||
|
<span>Hétfőnként új, a saját képletedből és a hét égboltjából.</span>
|
||||||
|
<span className="weekly-teaser-more">
|
||||||
|
Elolvasom a heti horoszkópomat<span aria-hidden="true"> →</span>
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
<BigThree chart={chart} />
|
<BigThree chart={chart} />
|
||||||
{forumEnabled() && (
|
{forumEnabled() && (
|
||||||
<div className="card ask-forum-card">
|
<div className="card ask-forum-card">
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";
|
|||||||
import { Cormorant_Garamond, Inter } from "next/font/google";
|
import { Cormorant_Garamond, Inter } from "next/font/google";
|
||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
|
|
||||||
|
import { DialogHost } from "@/components/Dialogs";
|
||||||
import { KeyboardSafe } from "@/components/KeyboardSafe";
|
import { KeyboardSafe } from "@/components/KeyboardSafe";
|
||||||
import { NightSky } from "@/components/NightSky";
|
import { NightSky } from "@/components/NightSky";
|
||||||
import { NpsBanner } from "@/components/NpsBanner";
|
import { NpsBanner } from "@/components/NpsBanner";
|
||||||
@@ -9,6 +10,7 @@ import { PaymentReturn } from "@/components/PaymentReturn";
|
|||||||
import { SiteFooter } from "@/components/PublicFooter";
|
import { SiteFooter } from "@/components/PublicFooter";
|
||||||
import { SiteHeader } from "@/components/SiteHeader";
|
import { SiteHeader } from "@/components/SiteHeader";
|
||||||
import { ValidationMessages } from "@/components/ValidationMessages";
|
import { ValidationMessages } from "@/components/ValidationMessages";
|
||||||
|
import { VersionWatcher } from "@/components/VersionWatcher";
|
||||||
import { getMe } from "@/lib/server";
|
import { getMe } from "@/lib/server";
|
||||||
import { loadSky } from "@/lib/sky";
|
import { loadSky } from "@/lib/sky";
|
||||||
import { siteUrl } from "@/lib/share";
|
import { siteUrl } from "@/lib/share";
|
||||||
@@ -44,6 +46,8 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
|||||||
<body>
|
<body>
|
||||||
<NightSky />
|
<NightSky />
|
||||||
<KeyboardSafe />
|
<KeyboardSafe />
|
||||||
|
<VersionWatcher />
|
||||||
|
<DialogHost />
|
||||||
<ValidationMessages />
|
<ValidationMessages />
|
||||||
{me && <SiteHeader me={me} sky={sky} />}
|
{me && <SiteHeader me={me} sky={sky} />}
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ const DATA: [string, string, string][] = [
|
|||||||
"Performance of the contract",
|
"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",
|
"Running the forum, the ranks, showing what is new",
|
||||||
"Performance of the contract",
|
"Performance of the contract",
|
||||||
],
|
],
|
||||||
@@ -124,6 +124,16 @@ const DATA: [string, string, string][] = [
|
|||||||
"Security, troubleshooting, preventing abuse",
|
"Security, troubleshooting, preventing abuse",
|
||||||
"Legitimate interest (Art. 6(1)(f))",
|
"Legitimate interest (Art. 6(1)(f))",
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
"Weekly horoscope: the week's sky on your own chart, the text written from it, and whether you want the Monday notice e-mail",
|
||||||
|
"The free weekly horoscope; a short e-mail on Mondays that the new one is there (sent by default; turn it off at any time in the e-mail's footer, on the Weekly horoscope page or on your Profile page)",
|
||||||
|
"Performance of the contract; for the e-mail, legitimate interest (Art. 6(1)(f))",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Which page you opened, where you came from, your browser and device type, your country and how long the page took to load (visitor statistics)",
|
||||||
|
"Seeing how many people view each page and whether the site is fast enough",
|
||||||
|
"Legitimate interest (Art. 6(1)(f))",
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
/** The privacy policy in English (the Hungarian one at /adatvedelem is the same in content). */
|
/** The privacy policy in English (the Hungarian one at /adatvedelem is the same in content). */
|
||||||
@@ -203,7 +213,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
|
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
|
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
|
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
|
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
|
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
|
(Google's) servers (youtube-nocookie.com), which see your IP address and what you play; on a phone, opening
|
||||||
@@ -227,7 +239,8 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<p>
|
<p>
|
||||||
<strong>How we use it:</strong> to create your account and recognise you when you sign in; your e-mail address
|
<strong>How we use it:</strong> to create your account and recognise you when you sign in; your e-mail address
|
||||||
for service e-mails (for example when a reading is ready, an invitation was accepted, or someone replied on the
|
for service e-mails (for example when a reading is ready, an invitation was accepted, or someone replied on the
|
||||||
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these); your name for
|
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these) and for the
|
||||||
|
weekly horoscope's Monday notice (unless you turned it off); your name for
|
||||||
display;
|
display;
|
||||||
your language for the language of the site and your readings.
|
your language for the language of the site and your readings.
|
||||||
</p>
|
</p>
|
||||||
@@ -269,10 +282,11 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<section>
|
<section>
|
||||||
<h2>4. Readings and artificial intelligence</h2>
|
<h2>4. Readings and artificial intelligence</h2>
|
||||||
<p>
|
<p>
|
||||||
The short summary, the detailed readings, tarot readings and the answers to your questions are written by a
|
The short summary, the weekly horoscope, the detailed readings, tarot readings and the answers to your
|
||||||
large language model (artificial intelligence). The model receives the{" "}
|
questions are written by a large language model (artificial intelligence). The model receives the{" "}
|
||||||
<strong>astronomical data of the chart</strong> (the signs, degrees, houses and aspects of the planets), for
|
<strong>astronomical data of the chart</strong> (the signs, degrees, houses and aspects of the planets), for
|
||||||
a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail
|
the weekly horoscope also the week's sky (where the planets are and the aspects they make to your chart),
|
||||||
|
for a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail
|
||||||
address, birth date, time or place. Please do not write names or sensitive data (such as health data) into
|
address, birth date, time or place. Please do not write names or sensitive data (such as health data) into
|
||||||
your questions either. The readings are for entertainment and self-reflection and are not medical,
|
your questions either. The readings are for entertainment and self-reflection and are not medical,
|
||||||
financial, legal or other professional advice.
|
financial, legal or other professional advice.
|
||||||
@@ -303,6 +317,8 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
||||||
address and request data when the site loads. On the e-mail sign-up and password request forms its
|
address and request data when the site loads. On the e-mail sign-up and password request forms its
|
||||||
Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
|
Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
|
||||||
|
Its Web Analytics service measures visits and page speed without cookies or any identifier stored in the
|
||||||
|
browser, and does not follow individual visitors.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Google LLC</strong>: signing in with a Google account.
|
<strong>Google LLC</strong>: signing in with a Google account.
|
||||||
@@ -347,7 +363,8 @@ export default async function PrivacyPolicyPage() {
|
|||||||
</li>
|
</li>
|
||||||
<li>Data needed for invoicing: for the period required by accounting law (8 years).</li>
|
<li>Data needed for invoicing: for the period required by accounting law (8 years).</li>
|
||||||
<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.
|
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
|
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
|
posts stay, shown as “Törölt tag” (deleted member), so that the conversations remain readable; to have them
|
||||||
@@ -366,7 +383,12 @@ export default async function PrivacyPolicyPage() {
|
|||||||
<p>
|
<p>
|
||||||
We use a cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you signed
|
We use a cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you signed
|
||||||
in. If you choose the light or dark theme on the forum, a second cookie (<code>sf_forum_theme</code>) keeps
|
in. If you choose the light or dark theme on the forum, a second cookie (<code>sf_forum_theme</code>) keeps
|
||||||
your choice for a year; it stores nothing else. We use no advertising or tracking cookies and no analytics.
|
your choice for a year; it stores nothing else. We use no advertising or tracking cookies.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Visits are counted by Cloudflare Web Analytics, without cookies or any identifier stored in the browser.
|
||||||
|
When a page loads, a small script sends which page you opened, where you came from, your browser and device
|
||||||
|
type, and how long the page took to load. We only see totals and cannot follow individual visitors.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
|
||||||
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
||||||
|
import { WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||||
import { backendGet, requireMe } from "@/lib/server";
|
import { backendGet, requireMe } from "@/lib/server";
|
||||||
import type { Chart } from "@/lib/types";
|
import type { Chart } from "@/lib/types";
|
||||||
|
|
||||||
@@ -84,6 +85,18 @@ export default async function ProfilePage() {
|
|||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section className="card" aria-labelledby="levelek-title" id="levelek">
|
||||||
|
<h2 id="levelek-title">Levelek</h2>
|
||||||
|
<WeeklyEmailSwitch
|
||||||
|
initial={me.weekly_email}
|
||||||
|
label="Heti horoszkóp: hétfőnként szólunk e-mailben, ha itt az új"
|
||||||
|
/>
|
||||||
|
<p className="hint" style={{ margin: 0 }}>
|
||||||
|
A levélben csak annyi áll, hogy elkészült; a horoszkópot belépés után a Heti horoszkóp oldalon olvashatod.
|
||||||
|
{!chart && " Ehhez előbb add meg a születési adataidat."}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="card" aria-labelledby="adataim">
|
<section className="card" aria-labelledby="adataim">
|
||||||
<h2 id="adataim">Adataim</h2>
|
<h2 id="adataim">Adataim</h2>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
|||||||
return [
|
return [
|
||||||
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
|
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
|
||||||
{ url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 },
|
{ url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 },
|
||||||
|
{ url: `${base}/heti-horoszkop`, changeFrequency: "weekly", priority: 0.8 },
|
||||||
{ url: `${base}/kartyajoslas/pelda`, changeFrequency: "monthly", priority: 0.7 },
|
{ url: `${base}/kartyajoslas/pelda`, changeFrequency: "monthly", priority: 0.7 },
|
||||||
{ url: `${base}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 },
|
{ url: `${base}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 },
|
||||||
{ url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 },
|
{ url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 },
|
||||||
|
|||||||
@@ -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
|
* into that part. A text box gets `autocomplete="off"` unless it says
|
||||||
* otherwise, so iOS Safari does not lay its AutoFill bar (passwords, cards,
|
* otherwise, so iOS Safari does not lay its AutoFill bar (passwords, cards,
|
||||||
* addresses) over it.
|
* 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() {
|
export function KeyboardSafe() {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -39,6 +44,7 @@ export function KeyboardSafe() {
|
|||||||
let timer: number | undefined;
|
let timer: number | undefined;
|
||||||
let again: number | undefined;
|
let again: number | undefined;
|
||||||
let closing: number | undefined;
|
let closing: number | undefined;
|
||||||
|
const settling: number[] = [];
|
||||||
|
|
||||||
const measure = () => {
|
const measure = () => {
|
||||||
root.style.setProperty("--vv-top", `${vv ? vv.offsetTop : 0}px`);
|
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" });
|
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
|
// After the keyboard has slid up (and once more when the browser's own
|
||||||
// scrolling has settled), and whenever the free part changes.
|
// scrolling has settled), and whenever the free part changes.
|
||||||
const later = (ms: number) => {
|
const later = (ms: number) => {
|
||||||
@@ -87,20 +108,34 @@ export function KeyboardSafe() {
|
|||||||
// Moving to another field keeps it open.
|
// Moving to another field keeps it open.
|
||||||
window.clearTimeout(closing);
|
window.clearTimeout(closing);
|
||||||
closing = window.setTimeout(() => {
|
closing = window.setTimeout(() => {
|
||||||
if (!typedInto(document.activeElement)) root.classList.remove("kb-open");
|
if (typedInto(document.activeElement)) return;
|
||||||
|
root.classList.remove("kb-open");
|
||||||
|
settleSoon();
|
||||||
}, 150);
|
}, 150);
|
||||||
};
|
};
|
||||||
const onViewport = () => {
|
const onViewport = () => {
|
||||||
if (!root.classList.contains("kb-open")) return;
|
if (!root.classList.contains("kb-open")) {
|
||||||
|
settleSoon();
|
||||||
|
return;
|
||||||
|
}
|
||||||
measure();
|
measure();
|
||||||
later(150);
|
later(150);
|
||||||
};
|
};
|
||||||
|
// Back from a picker (photos) or another app.
|
||||||
|
const onReturn = () => {
|
||||||
|
if (document.visibilityState === "visible") settleSoon();
|
||||||
|
};
|
||||||
|
|
||||||
document.addEventListener("focusin", onFocusIn);
|
document.addEventListener("focusin", onFocusIn);
|
||||||
document.addEventListener("focusout", onFocusOut);
|
document.addEventListener("focusout", onFocusOut);
|
||||||
vv?.addEventListener("resize", onViewport);
|
vv?.addEventListener("resize", onViewport);
|
||||||
vv?.addEventListener("scroll", measure);
|
vv?.addEventListener("scroll", measure);
|
||||||
|
window.addEventListener("focus", onReturn);
|
||||||
|
document.addEventListener("visibilitychange", onReturn);
|
||||||
return () => {
|
return () => {
|
||||||
|
settling.forEach((t) => window.clearTimeout(t));
|
||||||
|
window.removeEventListener("focus", onReturn);
|
||||||
|
document.removeEventListener("visibilitychange", onReturn);
|
||||||
window.clearTimeout(timer);
|
window.clearTimeout(timer);
|
||||||
window.clearTimeout(again);
|
window.clearTimeout(again);
|
||||||
window.clearTimeout(closing);
|
window.clearTimeout(closing);
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import { useEffect, useId, useRef } from "react";
|
|||||||
/**
|
/**
|
||||||
* A modal window (the browser's own <dialog>: focus stays inside, Escape
|
* 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.
|
* 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({
|
export function Modal({
|
||||||
title,
|
title,
|
||||||
@@ -17,7 +18,7 @@ export function Modal({
|
|||||||
title: string;
|
title: string;
|
||||||
subtitle?: React.ReactNode;
|
subtitle?: React.ReactNode;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
canClose?: () => boolean;
|
canClose?: () => boolean | Promise<boolean>;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const ref = useRef<HTMLDialogElement>(null);
|
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
|
// it (not a text selection dragged out, nor a pick from a select's list that
|
||||||
// hangs over the backdrop).
|
// hangs over the backdrop).
|
||||||
const pressedBackdrop = useRef(false);
|
const pressedBackdrop = useRef(false);
|
||||||
const close = () => {
|
const close = async () => {
|
||||||
if (!canClose || canClose()) onClose();
|
if (!canClose || (await canClose())) onClose();
|
||||||
};
|
};
|
||||||
|
|
||||||
// No close() on unmount: that would fire onClose; a removed dialog is gone anyway.
|
// No close() on unmount: that would fire onClose; a removed dialog is gone anyway.
|
||||||
@@ -43,8 +44,10 @@ export function Modal({
|
|||||||
aria-labelledby={titleId}
|
aria-labelledby={titleId}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onCancel={(e) => {
|
onCancel={(e) => {
|
||||||
// Escape: the dialog would close by itself.
|
// Escape: the dialog would close by itself; with a question first it waits for the answer.
|
||||||
if (canClose && !canClose()) e.preventDefault();
|
if (!canClose) return;
|
||||||
|
e.preventDefault();
|
||||||
|
void close();
|
||||||
}}
|
}}
|
||||||
onPointerDown={(e) => {
|
onPointerDown={(e) => {
|
||||||
pressedBackdrop.current = e.target === ref.current;
|
pressedBackdrop.current = e.target === ref.current;
|
||||||
@@ -52,7 +55,7 @@ export function Modal({
|
|||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
const onBackdrop = pressedBackdrop.current && e.target === ref.current;
|
const onBackdrop = pressedBackdrop.current && e.target === ref.current;
|
||||||
pressedBackdrop.current = false;
|
pressedBackdrop.current = false;
|
||||||
if (onBackdrop) close();
|
if (onBackdrop) void close();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="modal-inner">
|
<div className="modal-inner">
|
||||||
@@ -61,7 +64,7 @@ export function Modal({
|
|||||||
<h2 id={titleId}>{title}</h2>
|
<h2 id={titleId}>{title}</h2>
|
||||||
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
|
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
|
||||||
</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">
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
<path d="M6 6l12 12M18 6L6 18" />
|
<path d="M6 6l12 12M18 6L6 18" />
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
export type NavIconName =
|
export type NavIconName =
|
||||||
| "chart"
|
| "chart"
|
||||||
|
| "weekly"
|
||||||
| "persons"
|
| "persons"
|
||||||
| "compare"
|
| "compare"
|
||||||
| "tarot"
|
| "tarot"
|
||||||
@@ -45,6 +46,13 @@ export function NavIcon({ name }: { name: NavIconName }) {
|
|||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{name === "weekly" && (
|
||||||
|
<>
|
||||||
|
<rect x="4" y="5" width="16" height="15" rx="2.2" />
|
||||||
|
<path d="M4 9.5h16M8.5 3v4M15.5 3v4" />
|
||||||
|
<path d="M12 12l.9 2 2.1.9-2.1.9-.9 2-.9-2-2.1-.9 2.1-.9z" className="nav-icon-fill" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{name === "famous" && (
|
{name === "famous" && (
|
||||||
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
|
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import type { PersonInvite } from "@/lib/types";
|
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. */
|
/** The user's "how compatible are we?" invitations: waiting ones (revocable) and accepted ones. */
|
||||||
export function PendingInvites() {
|
export function PendingInvites() {
|
||||||
@@ -25,7 +26,13 @@ export function PendingInvites() {
|
|||||||
}, [load]);
|
}, [load]);
|
||||||
|
|
||||||
async function revoke(i: PersonInvite) {
|
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 {
|
try {
|
||||||
await api(`/invites/${i.id}`, { method: "DELETE" });
|
await api(`/invites/${i.id}`, { method: "DELETE" });
|
||||||
await load();
|
await load();
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { confirmDialog } from "@/components/Dialogs";
|
||||||
|
|
||||||
interface Share {
|
interface Share {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -83,7 +84,14 @@ export function ShareChart({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function revoke() {
|
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);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
await api(`/shares/${share.id}`, { method: "DELETE" });
|
await api(`/shares/${share.id}`, { method: "DELETE" });
|
||||||
|
|||||||
@@ -148,11 +148,12 @@ const EXPLORE: NavItem[] = [
|
|||||||
/**
|
/**
|
||||||
* The header of the logged-in app: the menu with gold marks (the free pages
|
* The header of the logged-in app: the menu with gold marks (the free pages
|
||||||
* in one "Felfedezés" dropdown), the Moon today, the package and the account.
|
* in one "Felfedezés" dropdown), the Moon today, the package and the account.
|
||||||
* Below 1380px the menu moves behind ☰, grouped.
|
* Below 1520px the menu moves behind ☰, grouped.
|
||||||
*/
|
*/
|
||||||
export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
||||||
const own: NavItem[] = [
|
const own: NavItem[] = [
|
||||||
{ href: "/keplet", label: "Képletem", icon: "chart" },
|
{ href: "/keplet", label: "Képletem", icon: "chart" },
|
||||||
|
{ href: "/heti-horoszkop", label: "Heti horoszkóp", icon: "weekly" },
|
||||||
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
||||||
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
||||||
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import type { Analysis } from "@/lib/types";
|
||||||
|
import { weekRange } from "@/lib/weekly";
|
||||||
|
|
||||||
|
import { AnalysisLoading } from "./AnalysisLoading";
|
||||||
|
import { RateContent } from "./RateContent";
|
||||||
|
import { RegenerateButton } from "./RegenerateButton";
|
||||||
|
import { RetryNotice } from "./RetryNotice";
|
||||||
|
import { Paragraphs } from "./Rich";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Monday's e-mail about the weekly horoscope, on or off. Turned on, the first
|
||||||
|
* one comes next Monday.
|
||||||
|
*/
|
||||||
|
export function WeeklyEmailSwitch({ initial, label }: { initial: boolean; label: string }) {
|
||||||
|
const [on, setOn] = useState(initial);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
useEffect(() => setOn(initial), [initial]);
|
||||||
|
|
||||||
|
async function toggle(next: boolean) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setOn(next);
|
||||||
|
try {
|
||||||
|
await api("/weekly/email", { method: "PUT", body: { on: next } });
|
||||||
|
} catch (e) {
|
||||||
|
setOn(!next);
|
||||||
|
setError(errorText(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="weekly-email">
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={on} disabled={busy} onChange={(e) => void toggle(e.target.checked)} />
|
||||||
|
<span>{label}</span>
|
||||||
|
</label>
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One week's horoscope: the text, or while the worker writes it the waiting
|
||||||
|
* animation (this week's, the page polls it), or a note when it failed.
|
||||||
|
*/
|
||||||
|
export function WeekCard({
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
analysis,
|
||||||
|
current = false,
|
||||||
|
gaveUp = false,
|
||||||
|
isAdmin = false,
|
||||||
|
onRestarted,
|
||||||
|
}: {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
analysis: Analysis | null;
|
||||||
|
/** This week: marked, and it may still be written. */
|
||||||
|
current?: boolean;
|
||||||
|
/** The page stopped waiting for it. */
|
||||||
|
gaveUp?: boolean;
|
||||||
|
isAdmin?: boolean;
|
||||||
|
onRestarted?: (a: Analysis) => void;
|
||||||
|
}) {
|
||||||
|
const content = analysis?.status === "done" ? analysis.content : null;
|
||||||
|
const titleId = `week-${start}`;
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
className={current ? "card summary-card weekly-card weekly-current" : "card weekly-card"}
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
aria-busy={!content && !gaveUp && analysis?.status !== "failed"}
|
||||||
|
>
|
||||||
|
<span className="eyebrow">
|
||||||
|
{weekRange(start, end)}
|
||||||
|
{current && " · ez a hét"}
|
||||||
|
</span>
|
||||||
|
{content ? (
|
||||||
|
<>
|
||||||
|
{isAdmin && analysis && onRestarted && (
|
||||||
|
<RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={onRestarted} />
|
||||||
|
)}
|
||||||
|
<h2 id={titleId} className="summary-title">
|
||||||
|
{content.title}
|
||||||
|
</h2>
|
||||||
|
<div className="summary-text weekly-text" lang={analysis?.language}>
|
||||||
|
<Paragraphs text={content.text ?? ""} />
|
||||||
|
</div>
|
||||||
|
{analysis && <RateContent analysisId={analysis.id} />}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<h2 id={titleId} className="sr-only">
|
||||||
|
Heti horoszkóp, {weekRange(start, end)}
|
||||||
|
</h2>
|
||||||
|
{gaveUp || analysis?.status === "failed" ? (
|
||||||
|
<p className="muted" role="status">
|
||||||
|
{current
|
||||||
|
? "A heti horoszkóp most nem készült el. Töltsd újra az oldalt egy kicsit később."
|
||||||
|
: "Ez a heti horoszkóp nem készült el."}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<AnalysisLoading
|
||||||
|
compact
|
||||||
|
text="A heti horoszkópod készül, ez fél percig is eltarthat…"
|
||||||
|
since={analysis?.requested_at ?? analysis?.created_at}
|
||||||
|
/>
|
||||||
|
{analysis && (
|
||||||
|
<RetryNotice
|
||||||
|
status={analysis.status}
|
||||||
|
error={analysis.error}
|
||||||
|
nextAttemptAt={analysis.next_attempt_at}
|
||||||
|
isAdmin={isAdmin}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,10 +3,12 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
|
import { usePhotoUploads } from "@/lib/photos";
|
||||||
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
||||||
import type { ForumAuthor } from "@/lib/forum";
|
import type { ForumAuthor } from "@/lib/forum";
|
||||||
|
|
||||||
import { Avatar } from "./Avatar";
|
import { Avatar } from "./Avatar";
|
||||||
|
import { PhotoButton, PickedPhotos } from "./Photos";
|
||||||
|
|
||||||
/** "@Ho" right before the caret: what was typed after the "@", and where it starts. */
|
/** "@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 {
|
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).
|
* `onTyping`: called on every keystroke (the "… gépel" notice).
|
||||||
* `mentions`: typing "@Ho" offers the members whose nickname starts so.
|
* `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).
|
* `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({
|
export function Composer({
|
||||||
id,
|
id,
|
||||||
@@ -35,6 +38,7 @@ export function Composer({
|
|||||||
onTyping,
|
onTyping,
|
||||||
onChange,
|
onChange,
|
||||||
mentions = false,
|
mentions = false,
|
||||||
|
photos = false,
|
||||||
rows = 3,
|
rows = 3,
|
||||||
autoFocus = false,
|
autoFocus = false,
|
||||||
}: {
|
}: {
|
||||||
@@ -44,17 +48,19 @@ export function Composer({
|
|||||||
initial?: string;
|
initial?: string;
|
||||||
submitLabel?: string;
|
submitLabel?: string;
|
||||||
busy: boolean;
|
busy: boolean;
|
||||||
onSubmit: (text: string) => Promise<boolean>;
|
onSubmit: (text: string, photos: string[]) => Promise<boolean>;
|
||||||
onCancel?: () => void;
|
onCancel?: () => void;
|
||||||
onTyping?: () => void;
|
onTyping?: () => void;
|
||||||
onChange?: (text: string) => void;
|
onChange?: (text: string) => void;
|
||||||
mentions?: boolean;
|
mentions?: boolean;
|
||||||
|
photos?: boolean;
|
||||||
rows?: number;
|
rows?: number;
|
||||||
autoFocus?: boolean;
|
autoFocus?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [text, setText] = useState(initial);
|
const [text, setText] = useState(initial);
|
||||||
const [suggest, setSuggest] = useState<{ query: string; start: number; members: ForumAuthor[] } | null>(null);
|
const [suggest, setSuggest] = useState<{ query: string; start: number; members: ForumAuthor[] } | null>(null);
|
||||||
const area = useRef<HTMLTextAreaElement>(null);
|
const area = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const picked = usePhotoUploads();
|
||||||
const timer = useRef<number | undefined>(undefined);
|
const timer = useRef<number | undefined>(undefined);
|
||||||
|
|
||||||
useEffect(() => () => window.clearTimeout(timer.current), []);
|
useEffect(() => () => window.clearTimeout(timer.current), []);
|
||||||
@@ -92,11 +98,12 @@ export function Composer({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
if (!text.trim() || busy) return;
|
if (!text.trim() || busy || picked.busy) return;
|
||||||
const final = convertEmoticons(text, text.length, true).text;
|
const final = convertEmoticons(text, text.length, true).text;
|
||||||
if (await onSubmit(final)) {
|
if (await onSubmit(final, picked.ids)) {
|
||||||
setText("");
|
setText("");
|
||||||
setSuggest(null);
|
setSuggest(null);
|
||||||
|
picked.reset();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +155,14 @@ export function Composer({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</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">
|
<div className="fc-actions">
|
||||||
|
{photos && <PhotoButton onFiles={(files) => void picked.add(files)} disabled={picked.full} />}
|
||||||
<span className="fc-spacer" />
|
<span className="fc-spacer" />
|
||||||
{onCancel && (
|
{onCancel && (
|
||||||
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
|
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
|
||||||
@@ -158,7 +172,7 @@ export function Composer({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary btn-sm"
|
className="btn btn-primary btn-sm"
|
||||||
disabled={busy || !text.trim()}
|
disabled={busy || picked.busy || !text.trim()}
|
||||||
onClick={() => void submit()}
|
onClick={() => void submit()}
|
||||||
>
|
>
|
||||||
{busy ? "Küldés…" : submitLabel}
|
{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 { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum";
|
||||||
|
|
||||||
import { Avatar } from "./Avatar";
|
import { Avatar } from "./Avatar";
|
||||||
|
import { TopicIcon } from "./TopicIcon";
|
||||||
|
|
||||||
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
|
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
|
||||||
if (!intent) return null;
|
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>;
|
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 === 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>;
|
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 }) {
|
export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<ul className="ft-list">
|
<ul className="ft-list">
|
||||||
{threads.map((t) => (
|
{threads.map((t) => {
|
||||||
<li key={t.id}>
|
const closed = t.topic.visibility !== undefined && t.topic.visibility !== "public";
|
||||||
<Link href={threadHref(t)} className="ft-row">
|
const tags = showTopic || t.pinned || t.locked || t.intent;
|
||||||
<span className="ft-main">
|
return (
|
||||||
<span className="ft-title">
|
<li key={t.id}>
|
||||||
{t.pinned && <span className="ft-pin">Kitűzve</span>}
|
<Link href={threadHref(t)} className="ft-row">
|
||||||
{t.locked && <span className="ft-pin">Lezárva</span>}
|
<span className="ft-main">
|
||||||
{t.title}
|
{tags && (
|
||||||
</span>
|
<span className="ft-tags">
|
||||||
<span className="ft-meta">
|
{showTopic && (
|
||||||
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
|
<span className="ft-topic">
|
||||||
<span>
|
<TopicIcon slug={t.topic.slug} />
|
||||||
{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}
|
{t.topic.name}
|
||||||
{showTopic && ` · ${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">
|
<span className="ft-m-narrow">
|
||||||
{" "}
|
|
||||||
· {t.reply_count} válasz ·{" "}
|
· {t.reply_count} válasz ·{" "}
|
||||||
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
||||||
{ago(t.last_post_at)}
|
{ago(t.last_post_at)}
|
||||||
</time>
|
</time>
|
||||||
</span>
|
</span>
|
||||||
|
<span className="ft-m-narrow ft-m-new">
|
||||||
|
<UnreadPill n={t.unread} onlyNew />
|
||||||
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
<span className="ft-side">
|
||||||
<span className="ft-col ft-col-replies">
|
<span>
|
||||||
<strong>{t.reply_count}</strong> válasz
|
<strong>{t.reply_count}</strong> válasz
|
||||||
{t.participants > 1 && <span className="hint">{t.participants} résztvevő</span>}
|
</span>
|
||||||
</span>
|
<span className="hint">
|
||||||
<span className="ft-col ft-col-last">
|
utoljára{" "}
|
||||||
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
<time suppressHydrationWarning dateTime={t.last_post_at}>
|
||||||
{ago(t.last_post_at)}
|
{ago(t.last_post_at)}
|
||||||
</time>
|
</time>
|
||||||
</span>
|
</span>
|
||||||
<UnreadPill n={t.unread} />
|
<UnreadPill n={t.unread} />
|
||||||
</Link>
|
</span>
|
||||||
</li>
|
</Link>
|
||||||
))}
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,9 +14,11 @@ import type { LiveNotice } from "./ForumNav";
|
|||||||
import { ReactionIcon } from "./ReactionIcon";
|
import { ReactionIcon } from "./ReactionIcon";
|
||||||
import { ReportForm } from "./ReportButton";
|
import { ReportForm } from "./ReportButton";
|
||||||
import { LinkPreviews } from "./LinkPreviews";
|
import { LinkPreviews } from "./LinkPreviews";
|
||||||
|
import { PostPhotos } from "./Photos";
|
||||||
import { ShareCard } from "./ShareCard";
|
import { ShareCard } from "./ShareCard";
|
||||||
import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
|
import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
|
||||||
import { Badge, RankBadge } from "./Badges";
|
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). */
|
/** How often the open thread looks for new replies (while the page is in front). */
|
||||||
const POLL_MS = 30_000;
|
const POLL_MS = 30_000;
|
||||||
@@ -338,6 +340,7 @@ function PostCard({
|
|||||||
post.body !== null && (
|
post.body !== null && (
|
||||||
<>
|
<>
|
||||||
<PostBody text={post.body} mentions={post.mentions} hide={post.links?.map((l) => l.url) ?? []} />
|
<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.links && post.links.length > 0 && <LinkPreviews links={post.links} />}
|
||||||
{post.share && <ShareCard share={post.share} />}
|
{post.share && <ShareCard share={post.share} />}
|
||||||
</>
|
</>
|
||||||
@@ -529,12 +532,20 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
if (updated) replacePost(updated);
|
if (updated) replacePost(updated);
|
||||||
return updated !== null;
|
return updated !== null;
|
||||||
},
|
},
|
||||||
remove: (post) => {
|
remove: async (post) => {
|
||||||
let reason: string | null = null;
|
let reason: string | null = null;
|
||||||
if (post.own) {
|
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 {
|
} 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;
|
if (!reason) return;
|
||||||
}
|
}
|
||||||
void run(async () => {
|
void run(async () => {
|
||||||
@@ -547,21 +558,29 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
|
await api(`/forum/posts/${post.id}/restore`, { method: "POST" });
|
||||||
await reload();
|
await reload();
|
||||||
}),
|
}),
|
||||||
detachShare: (post) => {
|
detachShare: async (post) => {
|
||||||
if (!window.confirm("Leveszed a csatolt képletet? A kártya eltűnik, és a link sem működik többé.")) return;
|
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 () => {
|
void run(async () => {
|
||||||
await api(`/forum/posts/${post.id}/share`, { method: "DELETE" });
|
await api(`/forum/posts/${post.id}/share`, { method: "DELETE" });
|
||||||
await reload();
|
await reload();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
mute: (post) => {
|
mute: async (post) => {
|
||||||
const nickname = post.author?.nickname;
|
const nickname = post.author?.nickname;
|
||||||
if (!nickname) return;
|
if (!nickname) return;
|
||||||
if (
|
if (
|
||||||
!post.muted &&
|
!post.muted &&
|
||||||
!window.confirm(
|
!(await confirmDialog({
|
||||||
`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.`,
|
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;
|
return;
|
||||||
void run(async () => {
|
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). */
|
/** 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> {
|
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 } }));
|
const post = await run(() =>
|
||||||
|
api<ForumPost>(`${base}/posts`, { body: { body: text, parent_id: to?.id ?? null, photos } }),
|
||||||
|
);
|
||||||
if (!post) return false;
|
if (!post) return false;
|
||||||
if (to) {
|
if (to) {
|
||||||
draft.current = "";
|
draft.current = "";
|
||||||
@@ -603,7 +624,14 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function removeThread() {
|
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;
|
if (!reason) return;
|
||||||
await run(() => api(base, { method: "DELETE", body: { reason } }));
|
await run(() => api(base, { method: "DELETE", body: { reason } }));
|
||||||
await reload();
|
await reload();
|
||||||
@@ -741,6 +769,7 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
<Composer
|
<Composer
|
||||||
key={top.id}
|
key={top.id}
|
||||||
mentions
|
mentions
|
||||||
|
photos
|
||||||
onTyping={imTyping}
|
onTyping={imTyping}
|
||||||
id={`valasz-${top.id}`}
|
id={`valasz-${top.id}`}
|
||||||
label={`Válasz neki: ${replyTo.author?.nickname ?? "Törölt tag"}`}
|
label={`Válasz neki: ${replyTo.author?.nickname ?? "Törölt tag"}`}
|
||||||
@@ -750,7 +779,7 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
draft.current = text;
|
draft.current = text;
|
||||||
}}
|
}}
|
||||||
busy={busy}
|
busy={busy}
|
||||||
onSubmit={(text) => sendReply(text, replyTo)}
|
onSubmit={(text, photos) => sendReply(text, replyTo, photos)}
|
||||||
onCancel={() => {
|
onCancel={() => {
|
||||||
draft.current = "";
|
draft.current = "";
|
||||||
setReplyTo(null);
|
setReplyTo(null);
|
||||||
@@ -801,12 +830,13 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
<>
|
<>
|
||||||
<Composer
|
<Composer
|
||||||
mentions
|
mentions
|
||||||
|
photos
|
||||||
onTyping={imTyping}
|
onTyping={imTyping}
|
||||||
id="valasz-szoveg"
|
id="valasz-szoveg"
|
||||||
label="Válaszod"
|
label="Válaszod"
|
||||||
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
|
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
|
||||||
busy={busy}
|
busy={busy}
|
||||||
onSubmit={(text) => sendReply(text, null)}
|
onSubmit={(text, photos) => sendReply(text, null, photos)}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"week_start": "2026-11-30",
|
||||||
|
"week_end": "2026-12-06",
|
||||||
|
"title": "Gondolatok, amelyek összeérnek",
|
||||||
|
"text": "A héten a gondolkodásod és a szíved egymásra hangolódnak. A legtisztább üzenetet a Merkúr hozza: a trigonja a születési Merkúrod felett hétfőn pontos, ez a világos fejtartás napja. A Nap a Nyilas jegyében a születési Vénuszodra szextilt vet, a Merkúr pedig a Szaturnuszoddal is harmonizál. A háttérben a Plútó lassan dolgozik a születési Marsod közelében: mély, kitartó átalakulás, nem hirtelen fordulat.\n\nHétfőn a Mars szextilje a születési Jupiteroddal is kedvező, a Mars az 1. házban jár, így a kezdeményezőkedved most erős. Kedden csúcsnap jön: a Nap szextilje a Vénuszoddal és a Merkúr szextilje a Szaturnusszal a hét legtisztább harmóniája, miközben az utolsó negyedben álló Hold a Szűz jegyében, az 1. házban a dolgok lecsupaszítására hív. Szerdán a Merkúr trigonja a Napoddal megerősíti, hogy a szavaid mögött valódi meggyőződés áll. Pénteken a Vénusz Skorpióba lép a 3. házban, szombaton a Hold is követi, így a hét vége befelé forduló, mélyebb hangulatú. Vasárnap a Vénusz trigonja a Jupiterrel bőséges, nagylelkű zárást ad.\n\nJavaslat: kedden írd le azt a kérést vagy elhatározást, amit eddig halogattál, mert a Merkúr és a Szaturnusz összhangja most kitartást ad a szavaidnak. A hét végén engedj teret a csendnek a Hold skorpiós hullámzásában, és vasárnap, a Vénusz–Jupiter trigon jegyében, merj örülni annak, ami már a tiéd."
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ export const TAG_LABELS: Record<string, string> = {
|
|||||||
|
|
||||||
export const KIND_LABELS: Record<string, string> = {
|
export const KIND_LABELS: Record<string, string> = {
|
||||||
summary: "Rövid összefoglaló",
|
summary: "Rövid összefoglaló",
|
||||||
|
weekly: "Heti horoszkóp",
|
||||||
natal: "Képletelemzés",
|
natal: "Képletelemzés",
|
||||||
synastry: "Kapcsolati elemzés",
|
synastry: "Kapcsolati elemzés",
|
||||||
forecast: "Éves előrejelzés",
|
forecast: "Éves előrejelzés",
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
// by its server and client components.
|
// by its server and client components.
|
||||||
|
|
||||||
/** The forum's colours: light by default, dark on request (a cookie). */
|
/** The forum's colours: light by default, dark on request (a cookie). */
|
||||||
|
import type { ForumPhoto } from "./photos";
|
||||||
import type { ChartResult, InterAspect } from "./types";
|
import type { ChartResult, InterAspect } from "./types";
|
||||||
|
|
||||||
export const FORUM_THEME_COOKIE = "sf_forum_theme";
|
export const FORUM_THEME_COOKIE = "sf_forum_theme";
|
||||||
@@ -61,8 +62,10 @@ export interface ThreadCard {
|
|||||||
slug: string;
|
slug: string;
|
||||||
title: string;
|
title: string;
|
||||||
intent: "listen" | "advice" | null;
|
intent: "listen" | "advice" | null;
|
||||||
topic: TopicRef;
|
topic: TopicRef & { visibility?: string };
|
||||||
author: ForumAuthor | null;
|
author: ForumAuthor | null;
|
||||||
|
/** The start of the opening post (as much as a card shows). */
|
||||||
|
excerpt?: string | null;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
last_post_at: string;
|
last_post_at: string;
|
||||||
reply_count: number;
|
reply_count: number;
|
||||||
@@ -86,6 +89,8 @@ export interface ForumHome {
|
|||||||
topics: ForumTopic[];
|
topics: ForumTopic[];
|
||||||
unanswered: ThreadCard[];
|
unanswered: ThreadCard[];
|
||||||
hot: ThreadCard[];
|
hot: ThreadCard[];
|
||||||
|
/** Pinned threads, above the topics. */
|
||||||
|
pinned?: ThreadCard[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TopicPage {
|
export interface TopicPage {
|
||||||
@@ -125,6 +130,8 @@ export interface ForumPost {
|
|||||||
share?: ShareCardData | null;
|
share?: ShareCardData | null;
|
||||||
/** Previews of the links a provider knows (YouTube for now). */
|
/** Previews of the links a provider knows (YouTube for now). */
|
||||||
links?: LinkPreview[] | null;
|
links?: LinkPreview[] | null;
|
||||||
|
/** Photos uploaded with the post. */
|
||||||
|
photos?: ForumPhoto[] | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A link the forum's link module knows, under a post. */
|
/** A link the forum's link module knows, under a post. */
|
||||||
@@ -273,6 +280,9 @@ export const INTENTS = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
||||||
|
/** The forum's link preview image (Facebook and co.); a thread adds its own title and text. */
|
||||||
|
export const FORUM_PREVIEW = { url: "/kep/forum.png?v=1", width: 1200, height: 630, alt: "A Sorsfonalak fóruma" };
|
||||||
|
|
||||||
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
||||||
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
||||||
return postId ? `${path}#h${postId}` : path;
|
return postId ? `${path}#h${postId}` : path;
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* The browsers built into apps: Facebook, Messenger, Instagram, TikTok, and
|
||||||
|
* other Android apps that show pages in their own window (WebView). Google
|
||||||
|
* does not allow signing in with a Google account in them (its error page
|
||||||
|
* says "disallowed_useragent"), so the login page offers the e-mail login
|
||||||
|
* and a way out to the phone's own browser instead.
|
||||||
|
*/
|
||||||
|
export interface InAppBrowser {
|
||||||
|
/** The app's name for the text ("Facebook"); null for an unknown app. */
|
||||||
|
app: string | null;
|
||||||
|
android: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function inAppBrowser(userAgent: string): InAppBrowser | null {
|
||||||
|
const android = /Android/i.test(userAgent);
|
||||||
|
let app: string | null = null;
|
||||||
|
if (/Instagram/i.test(userAgent)) app = "Instagram";
|
||||||
|
else if (/MessengerForiOS|Orca-Android|FB_IAB\/MESSENGER/i.test(userAgent)) app = "Messenger";
|
||||||
|
else if (/FBAN|FBAV|FB_IAB|FBIOS|FB4A/.test(userAgent)) app = "Facebook";
|
||||||
|
else if (/TikTok|musical_ly|Bytedance/i.test(userAgent)) app = "TikTok";
|
||||||
|
if (app) return { app, android };
|
||||||
|
// Any other Android app's window: "; wv)" in the browser's name.
|
||||||
|
if (android && /; wv\)/.test(userAgent)) return { app: null, android };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A link that opens the page in Chrome on Android, out of the app's window.
|
||||||
|
* Without Chrome the phone falls back to the same page.
|
||||||
|
*/
|
||||||
|
export function chromeIntent(url: string): string {
|
||||||
|
const u = new URL(url);
|
||||||
|
const fallback = encodeURIComponent(url);
|
||||||
|
return `intent://${u.host}${u.pathname}${u.search}#Intent;scheme=${u.protocol.replace(":", "")};package=com.android.chrome;S.browser_fallback_url=${fallback};end`;
|
||||||
|
}
|
||||||
@@ -18,8 +18,8 @@ export const ARBITRATION_BOARD = {
|
|||||||
web: "https://panaszrendezes.hu",
|
web: "https://panaszrendezes.hu",
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PRIVACY_UPDATED = "2026. november 26.";
|
export const PRIVACY_UPDATED = "2026. november 27.";
|
||||||
export const PRIVACY_UPDATED_EN = "26 November 2026";
|
export const PRIVACY_UPDATED_EN = "27 November 2026";
|
||||||
|
|
||||||
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
||||||
export const TERMS_UPDATED = "2026. november 26.";
|
export const TERMS_UPDATED = "2026. november 26.";
|
||||||
|
|||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -31,6 +31,8 @@ export interface Me {
|
|||||||
nps_due: boolean;
|
nps_due: boolean;
|
||||||
/** Natal analyses earned by bringing new users through shared links. */
|
/** Natal analyses earned by bringing new users through shared links. */
|
||||||
referral_rewards: { earned: number; limit: number };
|
referral_rewards: { earned: number; limit: number };
|
||||||
|
/** Monday's e-mail about the weekly horoscope is on. */
|
||||||
|
weekly_email: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A package from the catalog (`GET /v1/packages`). */
|
/** A package from the catalog (`GET /v1/packages`). */
|
||||||
@@ -258,7 +260,7 @@ export interface SynastryListItem {
|
|||||||
|
|
||||||
export interface Analysis {
|
export interface Analysis {
|
||||||
id: string;
|
id: string;
|
||||||
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity";
|
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity" | "weekly";
|
||||||
status: "pending" | "running" | "done" | "failed";
|
status: "pending" | "running" | "done" | "failed";
|
||||||
model: string;
|
model: string;
|
||||||
language: string;
|
language: string;
|
||||||
@@ -272,6 +274,8 @@ export interface Analysis {
|
|||||||
next_attempt_at?: string;
|
next_attempt_at?: string;
|
||||||
/** When the current text was asked for: the waiting page counts from here. */
|
/** When the current text was asked for: the waiting page counts from here. */
|
||||||
requested_at?: string;
|
requested_at?: string;
|
||||||
|
/** The Monday of a weekly horoscope. */
|
||||||
|
week_start?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Admin: one failed attempt in the error log. */
|
/** Admin: one failed attempt in the error log. */
|
||||||
@@ -325,7 +329,7 @@ export interface ModelFunction {
|
|||||||
export interface AdminJob {
|
export interface AdminJob {
|
||||||
id: string;
|
id: string;
|
||||||
type: "analysis" | "question";
|
type: "analysis" | "question";
|
||||||
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity";
|
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity" | "weekly";
|
||||||
status: "pending" | "running";
|
status: "pending" | "running";
|
||||||
/** The model of the current attempt. */
|
/** The model of the current attempt. */
|
||||||
model: string;
|
model: string;
|
||||||
@@ -467,6 +471,8 @@ export interface AdminCelebrityRow {
|
|||||||
export interface AnalysisContent {
|
export interface AnalysisContent {
|
||||||
title?: string;
|
title?: string;
|
||||||
summary?: string;
|
summary?: string;
|
||||||
|
/** The weekly horoscope's paragraphs. */
|
||||||
|
text?: string;
|
||||||
sections?: Record<string, { title: string; body: string }>;
|
sections?: Record<string, { title: string; body: string }>;
|
||||||
strengths?: string[];
|
strengths?: string[];
|
||||||
challenges?: string[];
|
challenges?: string[];
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user