Weekly horoscope landing page, link previews for the forum, and fixes from the review
CI / test (push) Successful in 3m19s
CI / build (push) Skipped
CI / deploy (push) Skipped

- /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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-27 10:12:27 +00:00
co-authored by Claude Opus 5.5
parent 0358e137f1
commit b37094e481
24 changed files with 461 additions and 90 deletions
+2 -5
View File
@@ -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, \
+15 -12
View File
@@ -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<EmailSwitch>,
) -> ApiResult<Json<Value>> {
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 })))
}
+24 -1
View File
@@ -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<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);
+16 -5
View File
@@ -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<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) {
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<std::time::Instant> = 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<Arc<Event>>, 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;
}
+10 -2
View File
@@ -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<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)
+12 -6
View File
@@ -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(())
}
+49 -10
View File
@@ -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);
}
+18 -2
View File
@@ -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],
},
};
/**
@@ -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<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> {
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] },
};
}
+4
View File
@@ -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; }
@@ -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>
);
}
@@ -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<Month | null>(null);
@@ -52,25 +54,45 @@ export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin:
useEffect(() => {
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let polls = 0;
const poll = async () => {
try {
const week = await api<Week & { email: boolean }>("/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<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
}
}
if (++polls >= MAX_POLLS) return setGaveUp(true);
timer = setTimeout(poll, POLL_MS);
};
(async () => {
try {
const page = await api<Month>(`/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));
}
@@ -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<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 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<Record<string, string | string[]>>;
}) {
const me = await requireMe("/heti-horoszkop");
const me = await getMe();
if (!me) {
return (
<>
<PublicHeader />
<WeeklyLanding />
</>
);
}
const raw = (await searchParams).honap;
const month = (Array.isArray(raw) ? raw[0] : raw) ?? null;
return (
@@ -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",
});
}
+1
View File
@@ -16,6 +16,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
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 },
@@ -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.
@@ -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."
}
+3
View File
@@ -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;
+23
View File
@@ -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}.`;
}
+5
View File
@@ -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);
+4 -1
View File
@@ -57,7 +57,10 @@ pub fn calculate(state: &AppState, req: WeekRequest) -> Result<WeekResponse, Api
let (start_jd, offset) = jd_at(start)?;
let next = start.checked_add(jiff::Span::new().days(7)).map_err(|e| ApiError::Internal(e.to_string()))?;
let (end_jd, _) = jd_at(next)?;
let week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset)
let mut week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset)
.map_err(|e| ApiError::Calculation(e.to_string()))?;
// The last day from the calendar: the offset at the start would be an hour
// off in the week the clocks go back.
week.end = start.checked_add(jiff::Span::new().days(6)).map_err(|e| ApiError::Internal(e.to_string()))?.to_string();
Ok(WeekResponse { timezone: zone_name, week })
}
+49
View File
@@ -65,7 +65,12 @@ pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usi
for m in due {
let threads: Vec<(String, i64)> = 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<String> = 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)]