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
+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);
}