From b37094e481a581c212d8543c0352f3a25e1f9122 Mon Sep 17 00:00:00 2001 From: feco Date: Fri, 27 Nov 2026 10:12:27 +0000 Subject: [PATCH] Weekly horoscope landing page, link previews for the forum, and fixes from the review - /heti-horoszkop for visitors: what it is, a real example written for the example chart, login and sign-up buttons; its own link preview image. - Forum: link previews (image, title; a public thread's opening words) for every forum page; none of a members-only thread's content. - Review fixes: a removed thread's photos are no longer served; public photos are cached for an hour, not a year (removals take effect); photos of threads removed a year ago are cleaned up; deleting one forum question no longer revokes the chart link another question still shows; the daily digest leaves out closed topics the member is no longer in; typing notices at most one a second per connection; the weekly page asks for the text once and then only reads it (no repeated paid runs after a failure); turning the Monday e-mail back on from the e-mail page waits for next Monday, like the site's switch; the week's last day is right in the week the clocks go back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- docs/heti-horoszkop.md | 3 +- services/backend/src/routes/notifications.rs | 7 +- services/backend/src/routes/weekly.rs | 27 +++---- services/backend/src/tests.rs | 25 ++++++- services/forum/src/live.rs | 21 ++++-- services/forum/src/routes/photos.rs | 12 +++- services/forum/src/routes/posts.rs | 18 +++-- services/forum/src/tests.rs | 59 +++++++++++++--- services/frontend/src/app/forum/layout.tsx | 20 +++++- .../frontend/src/app/forum/szal/[id]/page.tsx | 30 +++++++- services/frontend/src/app/globals.css | 4 ++ .../src/app/heti-horoszkop/Landing.tsx | 70 +++++++++++++++++++ .../src/app/heti-horoszkop/WeeklyPage.tsx | 52 ++++++++++---- .../frontend/src/app/heti-horoszkop/page.tsx | 46 ++++++++++-- .../frontend/src/app/kep/forum.png/route.tsx | 21 ++++++ .../src/app/kep/heti-horoszkop.png/route.tsx | 21 ++++++ services/frontend/src/app/sitemap.ts | 1 + .../src/components/WeeklyHoroscope.tsx | 23 +----- services/frontend/src/content/pelda-heti.json | 6 ++ services/frontend/src/lib/forum.ts | 3 + services/frontend/src/lib/weekly.ts | 23 ++++++ services/horoscope-api/src/tests.rs | 5 ++ services/horoscope-api/src/week.rs | 5 +- services/worker/src/forum_digest.rs | 49 +++++++++++++ 24 files changed, 461 insertions(+), 90 deletions(-) create mode 100644 services/frontend/src/app/heti-horoszkop/Landing.tsx create mode 100644 services/frontend/src/app/kep/forum.png/route.tsx create mode 100644 services/frontend/src/app/kep/heti-horoszkop.png/route.tsx create mode 100644 services/frontend/src/content/pelda-heti.json create mode 100644 services/frontend/src/lib/weekly.ts diff --git a/docs/heti-horoszkop.md b/docs/heti-horoszkop.md index 1b57920..22b9ebe 100644 --- a/docs/heti-horoszkop.md +++ b/docs/heti-horoszkop.md @@ -6,7 +6,8 @@ Ingyenes, személyes heti szöveg a tag saját képletéből és a hét égboltj - **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 először a heti szöveget kéri (`POST /v1/weekly`). Amíg a worker írja (kb. 20 másodperc), a hét kártyáján a várakozó animáció látszik, a hónap többi hete alatta. +- **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. diff --git a/services/backend/src/routes/notifications.rs b/services/backend/src/routes/notifications.rs index e82f8d8..981a9cf 100644 --- a/services/backend/src/routes/notifications.rs +++ b/services/backend/src/routes/notifications.rs @@ -105,11 +105,8 @@ pub async fn put_settings( } } let mut tx = state.db.begin().await?; - sqlx::query("UPDATE users SET weekly_email = $2, updated_at = now() WHERE id = $1") - .bind(user) - .bind(req.weekly_horoscope) - .execute(&mut *tx) - .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, \ diff --git a/services/backend/src/routes/weekly.rs b/services/backend/src/routes/weekly.rs index 77607b8..e62ad44 100644 --- a/services/backend/src/routes/weekly.rs +++ b/services/backend/src/routes/weekly.rs @@ -24,7 +24,7 @@ use crate::auth::AuthUser; use crate::error::{ApiError, ApiResult}; /// The Monday of the current week in Hungary. -const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date"; +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 { @@ -184,22 +184,25 @@ pub struct EmailSwitch { /// 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, ) -> ApiResult> { - sqlx::query(&format!( - "UPDATE users SET weekly_email = $2, \ - weekly_email_sent_on = CASE WHEN $2 THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \ - ELSE weekly_email_sent_on END, \ - updated_at = now() \ - WHERE id = $1" - )) - .bind(auth.id()) - .bind(req.on) - .execute(&state.db) - .await?; + sqlx::query(&switch_sql()).bind(auth.id()).bind(req.on).execute(&state.db).await?; Ok(Json(json!({ "email": req.on }))) } diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 2e72442..7b3d58f 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -2093,8 +2093,31 @@ async fn weekly_horoscope_of_the_own_chart(pool: PgPool) { 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)); - // The mail client's one-click unsubscribe turns off the weekly e-mail only. + // 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 = + 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 = + 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); diff --git a/services/forum/src/live.rs b/services/forum/src/live.rs index 6aab4e4..04addfc 100644 --- a/services/forum/src/live.rs +++ b/services/forum/src/live.rs @@ -204,6 +204,10 @@ struct Incoming { /// At most one typing notice per target in this time. 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. async fn typing(db: &PgPool, me: &Me, text: &str) -> Option { @@ -248,6 +252,9 @@ async fn typing(db: &PgPool, me: &Me, text: &str) -> Option { async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver>, db: PgPool, me: Me) { let (user, moderator) = (me.user, me.moderator); let mut last_typing: Option<(String, std::time::Instant)> = None; + // 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 = None; let mut ping = tokio::time::interval(PING); ping.tick().await; loop { @@ -280,12 +287,16 @@ async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver>, d } incoming = socket.recv() => match incoming { Some(Ok(Message::Text(text))) => { - // Typing notices, a few seconds apart per place. - let fresh = last_typing - .as_ref() - .is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY); + // Typing notices, a few seconds apart per place, one a second in all. + let fresh = text.len() <= TYPING_MAX_BYTES + && last_any.is_none_or(|at| at.elapsed() >= TYPING_ANY_EVERY) + && last_typing + .as_ref() + .is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY); if fresh { - last_typing = Some((text.to_string(), std::time::Instant::now())); + 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 { emit(&db, event).await; } diff --git a/services/forum/src/routes/photos.rs b/services/forum/src/routes/photos.rs index ffe27dd..ce04441 100644 --- a/services/forum/src/routes/photos.rs +++ b/services/forum/src/routes/photos.rs @@ -302,6 +302,10 @@ pub async fn serve( 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 } }; @@ -312,18 +316,22 @@ pub async fn serve( .map_err(|e| ApiError::Internal(format!("reading a photo: {e}")))? .ok_or(ApiError::NotFound("photo"))?; let content_type = if file.ends_with(".webp") { "image/webp" } else { "image/jpeg" }; - let cache = if public { "public, max-age=31536000, immutable" } else { "private, max-age=3600" }; + // 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 -/// removed more than a year ago, leave the storage and the table. +/// (or whole threads) removed more than a year ago, leave the storage and the table. pub async fn cleanup(state: &AppState) -> anyhow::Result { 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) diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs index 4ef0750..a44b386 100644 --- a/services/forum/src/routes/posts.rs +++ b/services/forum/src/routes/posts.rs @@ -316,13 +316,19 @@ async fn set_helped( 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> { - sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL") - .bind(share) - .bind(owner) - .execute(db) - .await?; + sqlx::query( + "UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL \ + AND NOT EXISTS (SELECT 1 FROM forum.posts p JOIN forum.threads t ON t.id = p.thread_id \ + WHERE p.share_id = $1 AND p.deleted_at IS NULL AND t.deleted_at IS NULL)", + ) + .bind(share) + .bind(owner) + .execute(db) + .await?; Ok(()) } diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index 6c8740c..15df4a5 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -1327,18 +1327,41 @@ async fn a_question_about_ones_chart(pool: PgPool) { assert_eq!(shown["posts"][0]["share"]["revoked"], true); assert!(shown["posts"][0]["share"].get("points").is_none()); - // The author takes it off (only she may): the card goes, the link stops working. + // 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(); + 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 uri = format!("/v1/forum/posts/{opening}/share"); assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN); assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT); assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null()); - let revoked: bool = sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'") - .fetch_one(&app.pool) - .await - .unwrap(); - assert!(revoked); + assert!(!revoked().await); + let other = app.get(&format!("/v1/forum/threads/{second}"), Some(&bea)).await; + assert_eq!(other["posts"][0]["share"]["points"][1]["sign"], "pisces"); + + // 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")] @@ -1604,7 +1627,8 @@ async fn photos_in_posts(pool: PgPool) { assert_eq!(thread["posts"][0]["photos"].as_array().unwrap().len(), 2); let (status, headers, _) = app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await; assert_eq!(status, StatusCode::OK); - assert!(headers["cache-control"].to_str().unwrap().contains("immutable")); + // 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; @@ -1647,11 +1671,26 @@ async fn photos_in_posts(pool: PgPool) { let (status, body) = upload(&anna, "image/jpeg", jpeg_with_exif()).await; assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}"); - // Unattached for over a day: gone from the table and the storage. + // 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, @@ -1660,7 +1699,7 @@ async fn photos_in_posts(pool: PgPool) { storage: Some(object_storage::Storage::new(storage)), links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"), }; - assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 2); + 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, 3); + assert_eq!(left, 1); } diff --git a/services/frontend/src/app/forum/layout.tsx b/services/frontend/src/app/forum/layout.tsx index 3acd01d..294a130 100644 --- a/services/frontend/src/app/forum/layout.tsx +++ b/services/frontend/src/app/forum/layout.tsx @@ -6,14 +6,30 @@ import { notFound } from "next/navigation"; import { ForumNav } from "@/components/forum/ForumNav"; import { ThemeToggle } from "@/components/forum/ThemeToggle"; import { PublicHeader } from "@/components/SiteHeader"; -import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum"; +import { FORUM_PREVIEW, FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum"; import { forumEnabled, forumGet } from "@/lib/forumServer"; import "./forum.css"; +const DESCRIPTION = "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok."; + export const metadata: Metadata = { title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" }, - description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.", + 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], + }, }; /** diff --git a/services/frontend/src/app/forum/szal/[id]/page.tsx b/services/frontend/src/app/forum/szal/[id]/page.tsx index cb0cd59..429b269 100644 --- a/services/frontend/src/app/forum/szal/[id]/page.tsx +++ b/services/frontend/src/app/forum/szal/[id]/page.tsx @@ -2,7 +2,7 @@ import type { Metadata } from "next"; import { notFound, permanentRedirect, redirect } from "next/navigation"; import { ThreadView } from "@/components/forum/ThreadView"; -import type { ThreadPage } from "@/lib/forum"; +import { FORUM_PREVIEW, type ThreadPage } from "@/lib/forum"; import { forumGet } from "@/lib/forumServer"; type Props = { params: Promise<{ id: string }> }; @@ -19,18 +19,42 @@ async function load(param: string) { return forumGet(`/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 { const res = await load((await params).id); if (!res?.ok) return { title: "Fórum", robots: { index: false } }; const { thread, posts } = res.data; const open = thread.topic.visibility === "public" && !thread.deleted; const opening = posts.find((p) => p.is_opening)?.body ?? ""; + 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 { title: thread.title, - description: open ? opening.slice(0, 160) : undefined, - alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` }, + description: open ? excerpt(opening, 160) : undefined, + alternates: { canonical: url }, // Members-only topics and removed threads stay out of search engines. 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] }, }; } diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 00ae6fb..6867c16 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -1879,3 +1879,7 @@ span.tarot-fan-card { cursor: default; } .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; } diff --git a/services/frontend/src/app/heti-horoszkop/Landing.tsx b/services/frontend/src/app/heti-horoszkop/Landing.tsx new file mode 100644 index 0000000..cab3be3 --- /dev/null +++ b/services/frontend/src/app/heti-horoszkop/Landing.tsx @@ -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 ( +
+
+ Ingyenes · hétfőnként új +

Heti horoszkóp, ami rólad szól

+

+ 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. +

+
+ + Belépés + + + Regisztráció + +
+
+ +
+ Példa · {weekRange(example.week_start, example.week_end)} +

+ {example.title} +

+
+ +
+

+ Ezt a heti horoszkópot a példaelemzés kitalált képletéhez írtuk (1990. március 15., + 14:30, Szeged), ugyanúgy, ahogy a tiédet is megírjuk. +

+
+ +
+

Hogyan működik?

+
    +
  1. + Megadod, mikor és hol születtél. Ebből percre pontosan kiszámoljuk a születési képletedet. +
  2. +
  3. + Hétfőnként új heti horoszkópot kapsz, a te képletedből és a hét égboltjából: a hét fő + témája, a kulcsnapok és egy javaslat. +
  4. +
  5. + Hétfő reggel e-mailben szólunk, hogy itt az új. Ha nem kéred, egy kattintással + kikapcsolhatod. +
  6. +
+
+ + Belépés, és kérem a heti horoszkópomat + +
+
+
+ ); +} diff --git a/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx b/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx index 1c8e182..7b2eef3 100644 --- a/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx +++ b/services/frontend/src/app/heti-horoszkop/WeeklyPage.tsx @@ -3,9 +3,10 @@ import Link from "next/link"; import { useEffect, useState } from "react"; -import { MONTHS, WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope"; +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; @@ -34,8 +35,9 @@ function monthName(key: string): string { /** * One month of weekly horoscopes, the newest week first. In this month the - * week's horoscope is asked for first (queued if new), and polled until the - * worker has written it; meanwhile its card shows the waiting animation. + * 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(null); @@ -52,25 +54,45 @@ export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin: useEffect(() => { let stopped = false; let timer: ReturnType | undefined; - let polls = 0; - const poll = async () => { - try { - const week = await api("/weekly", { method: "POST" }); - if (stopped) return; - putWeek({ week_start: week.week_start, week_end: week.week_end, analysis: week.analysis }); - if (week.analysis.status === "done") return; - } catch { - // try again on the next tick + 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("/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(`/analyses/${id}`); + if (stopped) return; + week = { ...week, analysis }; + putWeek(week); + } catch { + // try again on the next tick + } } - if (++polls >= MAX_POLLS) return setGaveUp(true); - timer = setTimeout(poll, POLL_MS); }; (async () => { try { const page = await api(`/weekly/history${query}`); if (stopped) return; setData(page); - if (page.month === page.current_month) await poll(); + if (page.month === page.current_month) await follow(); } catch (e) { if (!stopped) setError(errorText(e)); } diff --git a/services/frontend/src/app/heti-horoszkop/page.tsx b/services/frontend/src/app/heti-horoszkop/page.tsx index bcfaf0d..182134e 100644 --- a/services/frontend/src/app/heti-horoszkop/page.tsx +++ b/services/frontend/src/app/heti-horoszkop/page.tsx @@ -1,22 +1,58 @@ import type { Metadata } from "next"; import Link from "next/link"; -import { requireMe } from "@/lib/server"; +import { PublicHeader } from "@/components/SiteHeader"; +import { getMe } from "@/lib/server"; +import { siteUrl } from "@/lib/share"; +import { WeeklyLanding } from "./Landing"; import { WeeklyPage } from "./WeeklyPage"; -export const metadata: Metadata = { title: "Heti horoszkóp" }; +/** Bumped when the preview image changes, so Facebook and co. fetch it again. */ +const PREVIEW_VERSION = 1; + +export async function generateMetadata(): Promise { + 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 member's weekly horoscopes, one month at a time, the newest first - * (`?honap=2026-11` pages back). This week's is written when the page opens. + * 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>; }) { - const me = await requireMe("/heti-horoszkop"); + const me = await getMe(); + if (!me) { + return ( + <> + + + + ); + } const raw = (await searchParams).honap; const month = (Array.isArray(raw) ? raw[0] : raw) ?? null; return ( diff --git a/services/frontend/src/app/kep/forum.png/route.tsx b/services/frontend/src/app/kep/forum.png/route.tsx new file mode 100644 index 0000000..efed7c5 --- /dev/null +++ b/services/frontend/src/app/kep/forum.png/route.tsx @@ -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", + }); +} diff --git a/services/frontend/src/app/kep/heti-horoszkop.png/route.tsx b/services/frontend/src/app/kep/heti-horoszkop.png/route.tsx new file mode 100644 index 0000000..7654d2f --- /dev/null +++ b/services/frontend/src/app/kep/heti-horoszkop.png/route.tsx @@ -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", + }); +} diff --git a/services/frontend/src/app/sitemap.ts b/services/frontend/src/app/sitemap.ts index 598d18b..1e88dfc 100644 --- a/services/frontend/src/app/sitemap.ts +++ b/services/frontend/src/app/sitemap.ts @@ -16,6 +16,7 @@ export default async function sitemap(): Promise { return [ { url: `${base}/`, changeFrequency: "weekly", priority: 1 }, { 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}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 }, { url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 }, diff --git a/services/frontend/src/components/WeeklyHoroscope.tsx b/services/frontend/src/components/WeeklyHoroscope.tsx index ff2f703..81f4c96 100644 --- a/services/frontend/src/components/WeeklyHoroscope.tsx +++ b/services/frontend/src/components/WeeklyHoroscope.tsx @@ -4,6 +4,7 @@ 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"; @@ -11,28 +12,6 @@ import { RegenerateButton } from "./RegenerateButton"; import { RetryNotice } from "./RetryNotice"; import { Paragraphs } from "./Rich"; -export const MONTHS = [ - "január", - "február", - "március", - "április", - "május", - "június", - "július", - "augusztus", - "szeptember", - "október", - "november", - "december", -]; - -/** "november 30. – december 6." or "december 7–13.". */ -export function weekRange(start: string, end: string): string { - const [, m1, d1] = start.split("-").map(Number); - const [, m2, d2] = end.split("-").map(Number); - return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`; -} - /** * Monday's e-mail about the weekly horoscope, on or off. Turned on, the first * one comes next Monday. diff --git a/services/frontend/src/content/pelda-heti.json b/services/frontend/src/content/pelda-heti.json new file mode 100644 index 0000000..1dd6944 --- /dev/null +++ b/services/frontend/src/content/pelda-heti.json @@ -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." +} diff --git a/services/frontend/src/lib/forum.ts b/services/frontend/src/lib/forum.ts index 3e9f0b0..bd389a2 100644 --- a/services/frontend/src/lib/forum.ts +++ b/services/frontend/src/lib/forum.ts @@ -280,6 +280,9 @@ export const INTENTS = { } as const; /** `/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 { const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`; return postId ? `${path}#h${postId}` : path; diff --git a/services/frontend/src/lib/weekly.ts b/services/frontend/src/lib/weekly.ts new file mode 100644 index 0000000..498555f --- /dev/null +++ b/services/frontend/src/lib/weekly.ts @@ -0,0 +1,23 @@ +/** Dates of the weekly horoscope (shared by the server and the browser). */ + +export const MONTHS = [ + "január", + "február", + "március", + "április", + "május", + "június", + "július", + "augusztus", + "szeptember", + "október", + "november", + "december", +]; + +/** "november 30. – december 6." or "december 7–13.". */ +export function weekRange(start: string, end: string): string { + const [, m1, d1] = start.split("-").map(Number); + const [, m2, d2] = end.split("-").map(Number); + return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`; +} diff --git a/services/horoscope-api/src/tests.rs b/services/horoscope-api/src/tests.rs index 4f0f6ea..ba32f94 100644 --- a/services/horoscope-api/src/tests.rs +++ b/services/horoscope-api/src/tests.rs @@ -341,6 +341,11 @@ async fn one_week_of_a_chart() { assert_eq!(status, StatusCode::OK, "{u}"); assert!(u["week"]["positions"][0]["house"].is_null()); + // The week the clocks go back (Sunday 25 October): still Monday to Sunday. + let (status, d) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-10-19"}))).await; + assert_eq!(status, StatusCode::OK, "{d}"); + assert_eq!((d["week"]["start"].as_str(), d["week"]["end"].as_str()), (Some("2026-10-19"), Some("2026-10-25"))); + // Not a Monday. let (status, _) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-12-01"}))).await; assert_eq!(status, StatusCode::BAD_REQUEST); diff --git a/services/horoscope-api/src/week.rs b/services/horoscope-api/src/week.rs index b48c4ce..ea12061 100644 --- a/services/horoscope-api/src/week.rs +++ b/services/horoscope-api/src/week.rs @@ -57,7 +57,10 @@ pub fn calculate(state: &AppState, req: WeekRequest) -> Result Result = sqlx::query_as( "SELECT th.title, count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \ + JOIN forum.topics tp ON tp.id = th.topic_id \ WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \ + AND (tp.visibility <> 'restricted' \ + OR EXISTS (SELECT 1 FROM forum.topic_members tm \ + WHERE tm.topic_id = tp.id AND tm.user_id = $1 AND tm.status = 'approved') \ + OR EXISTS (SELECT 1 FROM users mu WHERE mu.id = $1 AND mu.roles && ARRAY['moderator', 'admin'])) \ AND p.created_at > $2 \ AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ WHERE r.user_id = $1 AND r.thread_id = th.id), 0) \ @@ -382,6 +387,50 @@ mod tests { .unwrap(); assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0); } + + #[sqlx::test(migrator = "db::MIGRATOR")] + async fn a_closed_topic_only_for_its_members(pool: PgPool) { + let anna = member(&pool, "anna@example.com", "Anna", "off", "daily").await; + let bea = member(&pool, "bea@example.com", "Bea", "off", "daily").await; + let cili = member(&pool, "cili@example.com", "Cili", "off", "off").await; + let topic: i16 = sqlx::query_scalar( + "INSERT INTO forum.topics (id, slug, name, description, visibility, position) \ + VALUES (90, 'zart-kor', 'Zárt kör', 'Próba', 'restricted', 90) RETURNING id", + ) + .fetch_one(&pool) + .await + .unwrap(); + // Anna is still in; Bea followed the thread while she was, and has left since. + sqlx::query("INSERT INTO forum.topic_members (topic_id, user_id, status) VALUES ($1, $2, 'approved')") + .bind(topic) + .bind(anna) + .execute(&pool) + .await + .unwrap(); + let thread: i64 = sqlx::query_scalar( + "INSERT INTO forum.threads (topic_id, author_id, title) VALUES ($1, $2, 'Titkos cím') RETURNING id", + ) + .bind(topic) + .bind(cili) + .fetch_one(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2), ($3, $2)") + .bind(anna) + .bind(thread) + .bind(bea) + .execute(&pool) + .await + .unwrap(); + post(&pool, thread, cili, None).await; + + assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 1); + let to: Vec = sqlx::query_scalar("SELECT to_email FROM email_outbox WHERE template = 'forum_digest'") + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(to, ["anna@example.com"], "the title stays inside the closed topic"); + } } #[cfg(test)]