Merge the forum (community module) into main

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-26 16:43:19 +00:00
co-authored by Claude Opus 5.5
131 changed files with 17773 additions and 357 deletions
+19
View File
@@ -179,6 +179,15 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
"questions": rows("SELECT json_build_object('id', q.id, 'analysis_id', q.analysis_id, 'question', q.question, 'status', q.status, 'answer', q.answer, 'created_at', q.created_at) FROM questions q WHERE q.asked_by = $1").await?,
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").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.
"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_topic_memberships": rows("SELECT json_build_object('topic', tp.name, 'status', tm.status, 'note', tm.note, 'requested_at', tm.requested_at) FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id WHERE tm.user_id = $1").await?,
"forum_posts": rows("SELECT json_build_object('id', p.id, 'thread_id', p.thread_id, 'thread_title', th.title, 'opening', p.is_opening, 'body', p.body, 'created_at', p.created_at, 'edited_at', p.edited_at, 'removed_at', p.deleted_at, 'removal_reason', p.delete_reason) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.author_id = $1 ORDER BY p.id").await?,
"forum_reactions": rows("SELECT json_build_object('post_id', post_id, 'kind', kind, 'created_at', created_at) FROM forum.reactions WHERE user_id = $1 ORDER BY created_at").await?,
"forum_followed_threads": rows("SELECT json_build_object('thread_id', thread_id, 'since', created_at) FROM forum.follows WHERE user_id = $1").await?,
"forum_conversations": rows("SELECT json_build_object('id', c.id, 'with', m.nickname, 'requested_by_me', c.requested_by = $1, 'intro', c.intro, 'status', c.status, 'created_at', c.created_at) FROM forum.conversations c LEFT JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $1 THEN c.user_b ELSE c.user_a END WHERE $1 IN (c.user_a, c.user_b)").await?,
"forum_messages_sent": rows("SELECT json_build_object('conversation_id', conversation_id, 'body', body, 'created_at', created_at) FROM forum.messages WHERE sender_id = $1 ORDER BY id").await?,
"forum_reports_sent": rows("SELECT json_build_object('post_id', post_id, 'message_id', message_id, 'kind', kind, 'note', note, 'status', status, 'created_at', created_at) FROM forum.reports WHERE reporter_id = $1").await?,
});
Ok(([("content-disposition", "attachment; filename=\"sorsfonalak-export.json\"")], Json(document)))
}
@@ -249,8 +258,18 @@ pub async fn delete_me(
.bind(auth.id())
.execute(&mut *tx)
.await?;
// The forum's own avatar picture (in the object storage) goes too.
let avatar: Option<String> = sqlx::query_scalar("SELECT avatar FROM forum.members WHERE user_id = $1")
.bind(auth.id())
.fetch_optional(&mut *tx)
.await?;
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
tx.commit().await?;
if let (Some(file), Some(storage)) = (avatar.as_deref().and_then(|a| a.strip_prefix("upload:")), &state.storage)
&& let Err(e) = storage.delete(&format!("forum-avatars/{file}")).await
{
tracing::warn!(error = %e, "removing a deleted account's forum avatar");
}
tracing::info!(user = %auth.id(), "account deleted");
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
+1 -1
View File
@@ -85,7 +85,7 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> {
}
/// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`.
pub const TERMS_VERSION: &str = "2026-11-23";
pub const TERMS_VERSION: &str = "2026-11-26";
/// Only admins can buy through Stripe: until purchases open, and always with a
/// test key (nobody gets packages with Stripe's test cards, nobody types a
+82 -11
View File
@@ -13,6 +13,12 @@
//! per user: a click proves little. A natal analysis is earned by bringing a
//! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and
//! makes their own chart, at most [`REFERRAL_LIMIT`] times.
//!
//! A share made for the forum (`for_forum`, a question about one's chart,
//! forecast or synastry) never shows birth data, and its public view leaves
//! out the chart names: they may be real names next to a nickname. A yearly
//! forecast can be shared too: its calculation and its detailed text, without
//! the place of the birthday.
use axum::Json;
use axum::extract::{Path, State};
@@ -27,6 +33,7 @@ use uuid::Uuid;
use super::analyses::{can_see, find_analysis};
use super::charts::{ChartRow, find_chart, owned_chart};
use super::forecasts::{ForecastRow, find_forecast, owned_forecast};
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
use super::{Body, IdPath, St};
use crate::auth::{AuthUser, user_agent};
@@ -39,6 +46,7 @@ pub enum ShareKind {
Chart,
Synastry,
Analysis,
Forecast,
}
#[derive(Debug, sqlx::FromRow)]
@@ -50,16 +58,18 @@ struct ShareRow {
chart_id: Option<Uuid>,
synastry_id: Option<Uuid>,
analysis_id: Option<Uuid>,
forecast_id: Option<Uuid>,
title: Option<String>,
show_birth_data: bool,
for_forum: bool,
view_count: i64,
created_at: OffsetDateTime,
revoked_at: Option<OffsetDateTime>,
owner_ip_hash: Option<Vec<u8>>,
}
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
view_count, created_at, revoked_at, owner_ip_hash";
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, forecast_id, title, \
show_birth_data, for_forum, view_count, created_at, revoked_at, owner_ip_hash";
use super::client_ip;
@@ -113,8 +123,10 @@ impl ShareRow {
"chart_id": self.chart_id,
"synastry_id": self.synastry_id,
"analysis_id": self.analysis_id,
"forecast_id": self.forecast_id,
"title": self.title,
"show_birth_data": self.show_birth_data,
"for_forum": self.for_forum,
"view_count": self.view_count,
"created_at": rfc3339(self.created_at),
"revoked_at": rfc3339_opt(self.revoked_at),
@@ -132,6 +144,9 @@ pub struct CreateShare {
/// Show birth date, time and place (only ever of the sharer's own charts).
#[serde(default)]
show_birth_data: bool,
/// For a forum post: no birth data, no names, no title.
#[serde(default)]
for_forum: bool,
}
pub async fn create(
@@ -140,14 +155,22 @@ pub async fn create(
headers: HeaderMap,
WithRejection(Json(req), _): Body<CreateShare>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
let (mut chart_id, mut synastry_id, mut analysis_id, mut forecast_id) = (None, None, None, None);
let kind = match req.kind {
ShareKind::Chart => {
owned_chart(&state.db, req.target_id, auth.id()).await?;
(Some(req.target_id), None, None, "chart")
chart_id = Some(req.target_id);
"chart"
}
ShareKind::Synastry => {
visible_synastry(&state.db, req.target_id, auth.id()).await?;
(None, Some(req.target_id), None, "synastry")
synastry_id = Some(req.target_id);
"synastry"
}
ShareKind::Forecast => {
owned_forecast(&state.db, req.target_id, auth.id()).await?;
forecast_id = Some(req.target_id);
"forecast"
}
ShareKind::Analysis => {
let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?;
@@ -157,14 +180,18 @@ pub async fn create(
if analysis.status != "done" {
return Err(ApiError::conflict("analysis_not_ready", "Csak elkészült elemzést lehet megosztani."));
}
(None, None, Some(req.target_id), "analysis")
analysis_id = Some(req.target_id);
"analysis"
}
};
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
// A forum share: never birth data, and no title of the sharer's own.
let (title, show_birth_data) = if req.for_forum { (None, false) } else { (title, req.show_birth_data) };
let open: Option<ShareRow> = sqlx::query_as(&format!(
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
AND forecast_id IS NOT DISTINCT FROM $8 AND for_forum = $9 \
ORDER BY created_at DESC LIMIT 1"
))
.bind(auth.id())
@@ -173,7 +200,9 @@ pub async fn create(
.bind(synastry_id)
.bind(analysis_id)
.bind(&title)
.bind(req.show_birth_data)
.bind(show_birth_data)
.bind(forecast_id)
.bind(req.for_forum)
.fetch_optional(&state.db)
.await?;
if let Some(row) = open {
@@ -182,8 +211,8 @@ pub async fn create(
let slug = new_slug();
let row: ShareRow = sqlx::query_as(&format!(
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
owner_ip_hash) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}"
owner_ip_hash, forecast_id, for_forum) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING {SHARE_COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(auth.id())
@@ -193,8 +222,10 @@ pub async fn create(
.bind(synastry_id)
.bind(analysis_id)
.bind(title)
.bind(req.show_birth_data)
.bind(show_birth_data)
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
.bind(forecast_id)
.bind(req.for_forum)
.fetch_one(&state.db)
.await?;
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
@@ -229,7 +260,27 @@ fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
// Birth data only of the sharer's own chart, never of a partner's or of a
// person they added (that is someone else's data).
let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own";
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
// A forum share leaves out the names (they may be real names next to a nickname).
let label = if share.for_forum { Value::Null } else { Value::from(chart.label.clone()) };
json!({ "label": label, "chart": public_chart(&chart.result, show) })
}
/// A yearly forecast without where it was reckoned: the solar return chart
/// without its place and time zone, and the year's calculation.
fn public_forecast_block(forecast: &ForecastRow) -> Value {
let sr = &forecast.result["solar_return"];
let solar_return = if sr.is_object() {
let mut chart = public_chart(sr, false);
if let Some(obj) = chart.as_object_mut() {
for key in ["local_time", "timezone", "utc_offset", "moment_utc", "location"] {
obj.remove(key);
}
}
chart
} else {
Value::Null
};
json!({ "year": forecast.year, "forecast": forecast.result["forecast"], "solar_return": solar_return })
}
fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value {
@@ -269,6 +320,26 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
body["synastry"] = public_synastry_block(&s, share);
}
} else if let Some(forecast_id) = share.forecast_id {
let forecast = find_forecast(db, forecast_id).await?.ok_or(ApiError::NotFound("share"))?;
body["forecast"] = public_forecast_block(&forecast);
// The detailed text of the year, if it was written.
let analysis: Option<(String, Option<Value>, Option<OffsetDateTime>)> = sqlx::query_as(
"SELECT language, content, completed_at FROM analyses \
WHERE forecast_id = $1 AND kind = 'forecast' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
)
.bind(forecast_id)
.fetch_optional(db)
.await?;
body["analysis"] = match analysis {
Some((language, content, completed_at)) => json!({
"kind": "forecast",
"language": language,
"content": content,
"completed_at": rfc3339_opt(completed_at),
}),
None => Value::Null,
};
}
Ok(body)
}