Files
sorsfonalak/services/backend/src/routes/celebrities.rs
T

547 lines
20 KiB
Rust
Raw Normal View History

//! Famous people: admins add them (birth data, one photo) and get a detailed
//! analysis written about them in the third person (`celebrity` kind, its own
//! prompt). Published ones have a public page (`/hires-emberek/<slug>`) with
//! the birth data, the chart, the analysis and the photo; drafts only admins see.
//!
//! The photo is stored once (see [`crate::photo`]) under a new key at every
//! upload and served by [`photo`], so the frontend's image optimizer and the
//! CDN may keep it forever.
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;
use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue};
use super::charts::{CHART_COLUMNS, ChartRow, calculate, find_chart};
use super::{Body, IdPath, St, double_option};
use crate::AppState;
use crate::auth::{AdminUser, AuthUser};
use crate::error::{ApiError, ApiResult};
use crate::views::{chart_highlights, public_chart, rfc3339, rfc3339_opt};
/// The analyses of famous people are written in Hungarian (the public pages are).
const LANGUAGE: &str = "hu";
#[derive(Debug, sqlx::FromRow)]
struct CelebrityRow {
id: Uuid,
chart_id: Uuid,
name: String,
subtitle: Option<String>,
slug: String,
photo_key: Option<String>,
photo_width: Option<i32>,
photo_height: Option<i32>,
focus_x: f32,
focus_y: f32,
published_at: Option<OffsetDateTime>,
created_at: OffsetDateTime,
updated_at: OffsetDateTime,
}
const COLUMNS: &str = "id, chart_id, name, subtitle, slug, photo_key, photo_width, photo_height, focus_x, focus_y, \
published_at, created_at, updated_at";
impl CelebrityRow {
fn photo(&self) -> Value {
match (&self.photo_key, self.photo_width, self.photo_height) {
(Some(key), Some(width), Some(height)) => json!({
"key": key, "width": width, "height": height, "focus_x": self.focus_x, "focus_y": self.focus_y,
}),
_ => Value::Null,
}
}
fn base(&self) -> Value {
json!({
"id": self.id,
"name": self.name,
"subtitle": self.subtitle,
"slug": self.slug,
"published": self.published_at.is_some(),
"published_at": rfc3339_opt(self.published_at),
"photo": self.photo(),
"created_at": rfc3339(self.created_at),
"updated_at": rfc3339(self.updated_at),
})
}
}
async fn find(db: &PgPool, id: Uuid) -> Result<CelebrityRow, ApiError> {
sqlx::query_as(&format!("SELECT {COLUMNS} FROM celebrities WHERE id = $1"))
.bind(id)
.fetch_optional(db)
.await?
.ok_or(ApiError::NotFound("celebrity"))
}
/// The newest analysis of the famous person's chart (any state).
async fn latest_analysis(db: &PgPool, chart_id: Uuid) -> Result<Option<AnalysisRow>, sqlx::Error> {
sqlx::query_as(&format!(
"SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE chart_id = $1 AND kind = 'celebrity' \
ORDER BY created_at DESC LIMIT 1"
))
.bind(chart_id)
.fetch_optional(db)
.await
}
/// "Marilyn Monroe" → "marilyn-monroe"; "Kovács Ödön" → "kovacs-odon".
fn slugify(name: &str) -> String {
let ascii = deunicode::deunicode(name).to_lowercase();
let mut slug = String::new();
for c in ascii.chars() {
if c.is_ascii_alphanumeric() {
slug.push(c);
} else if !slug.is_empty() && !slug.ends_with('-') {
slug.push('-');
}
}
let slug = slug.trim_end_matches('-').chars().take(80).collect::<String>();
let slug = slug.trim_end_matches('-').to_string();
if slug.is_empty() { "hires-ember".into() } else { slug }
}
fn valid_slug(slug: &str) -> bool {
!slug.is_empty()
&& slug.len() <= 80
&& slug
.split('-')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
}
/// `base`, or `base-2`, `base-3`, ... whichever is free (`except`: the row being renamed).
async fn free_slug(db: &PgPool, base: &str, except: Option<Uuid>) -> Result<String, sqlx::Error> {
for n in 1..1000 {
let slug = if n == 1 { base.to_string() } else { format!("{base}-{n}") };
let taken: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM celebrities WHERE slug = $1 AND id IS DISTINCT FROM $2)")
.bind(&slug)
.bind(except)
.fetch_one(db)
.await?;
if !taken {
return Ok(slug);
}
}
Ok(format!("{base}-{}", Uuid::now_v7().simple()))
}
fn clean_name(name: &str) -> Result<String, ApiError> {
let name: String = name.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(100).collect();
if name.is_empty() { Err(ApiError::BadRequest("A név nem lehet üres.".into())) } else { Ok(name) }
}
fn clean_subtitle(subtitle: Option<&str>) -> Option<String> {
subtitle.map(|s| s.trim().chars().take(160).collect::<String>()).filter(|s| !s.is_empty())
}
/// Calculates the chart from birth data (the horoscope service never sees the name).
async fn chart_for(state: &AppState, birth: Value) -> Result<(Value, Value, String), ApiError> {
calculate(state, birth).await
}
/// Queues the analysis of the chart (no unit is spent); an existing one with
/// the same cache key is returned instead.
async fn queue_analysis(state: &AppState, admin: &AuthUser, chart: &ChartRow) -> Result<AnalysisRow, ApiError> {
let target = Target::Celebrity { chart_id: chart.id, hash: chart.chart_hash.clone() };
Ok(queue(state, admin.id(), &target, LANGUAGE, None).await?.1)
}
/// The admin view: everything, with the birth data for the edit form.
async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result<Value, ApiError> {
let chart = find_chart(db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
let analysis = latest_analysis(db, row.chart_id).await?;
let mut view = row.base();
view["birth_data"] = chart.birth_data.clone();
view["birth"] = public_chart(&chart.result, true)["birth"].clone();
view["highlights"] = chart_highlights(&chart.result);
view["chart"] = chart.result.clone();
view["analysis"] = analysis.map_or(Value::Null, |a| a.view());
Ok(view)
}
// --- admin -------------------------------------------------------------------------------------
type ListRow =
(Uuid, Uuid, String, Option<String>, String, Option<OffsetDateTime>, Option<String>, Value, Option<String>);
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
let rows: Vec<ListRow> = sqlx::query_as(
"SELECT c.id, c.chart_id, c.name, c.subtitle, c.slug, c.published_at, c.photo_key, ch.result, \
(SELECT a.status FROM analyses a WHERE a.chart_id = c.chart_id AND a.kind = 'celebrity' \
ORDER BY a.created_at DESC LIMIT 1) \
FROM celebrities c JOIN charts ch ON ch.id = c.chart_id ORDER BY c.created_at DESC",
)
.fetch_all(&state.db)
.await?;
let items: Vec<Value> = rows
.into_iter()
.map(|(id, chart_id, name, subtitle, slug, published_at, photo_key, result, status)| {
json!({
"id": id, "chart_id": chart_id, "name": name, "subtitle": subtitle, "slug": slug,
"published": published_at.is_some(), "has_photo": photo_key.is_some(),
"birth": public_chart(&result, true)["birth"].clone(),
"highlights": chart_highlights(&result),
"analysis_status": status,
})
})
.collect();
Ok(Json(json!({ "celebrities": items })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CreateCelebrity {
name: String,
subtitle: Option<String>,
/// Birth data as for a chart (`POST /v1/charts`).
birth: Value,
}
/// Adds a famous person: calculates the chart and queues the analysis.
pub async fn create(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Json(req), _): Body<CreateCelebrity>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let name = clean_name(&req.name)?;
let (birth, result, hash) = chart_for(&state, req.birth).await?;
let slug = free_slug(&state.db, &slugify(&name), None).await?;
let mut tx = state.db.begin().await?;
let chart: ChartRow = sqlx::query_as(&format!(
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
VALUES ($1, $2, $3, false, 'celebrity', $4, $5, $6) RETURNING {CHART_COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(admin.id())
.bind(&name)
.bind(birth)
.bind(result)
.bind(hash)
.fetch_one(&mut *tx)
.await?;
let row: CelebrityRow = sqlx::query_as(&format!(
"INSERT INTO celebrities (id, chart_id, name, subtitle, slug, created_by) \
VALUES ($1, $2, $3, $4, $5, $6) RETURNING {COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(chart.id)
.bind(&name)
.bind(clean_subtitle(req.subtitle.as_deref()))
.bind(&slug)
.bind(admin.id())
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
queue_analysis(&state, &admin, &chart).await?;
tracing::info!(admin = %admin.id(), celebrity = %row.id, "famous person added");
Ok((StatusCode::CREATED, Json(admin_view(&state.db, &row).await?)))
}
pub async fn get_one(
State(state): St,
_admin: AdminUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let row = find(&state.db, id).await?;
Ok(Json(admin_view(&state.db, &row).await?))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateCelebrity {
name: Option<String>,
#[serde(default, deserialize_with = "double_option")]
subtitle: Option<Option<String>>,
slug: Option<String>,
published: Option<bool>,
focus_x: Option<f32>,
focus_y: Option<f32>,
/// Corrected birth data: the chart is calculated again and, if it changed,
/// the analysis is written again.
birth: Option<Value>,
}
pub async fn update(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<UpdateCelebrity>,
) -> ApiResult<Json<Value>> {
let row = find(&state.db, id).await?;
let name = req.name.as_deref().map(clean_name).transpose()?.unwrap_or_else(|| row.name.clone());
let subtitle = match &req.subtitle {
Some(s) => clean_subtitle(s.as_deref()),
None => row.subtitle.clone(),
};
let slug = match req.slug.as_deref().map(str::trim) {
Some(s) if s != row.slug => {
if !valid_slug(s) {
return Err(ApiError::BadRequest(
"A cím csak kisbetűt, számot és kötőjelet tartalmazhat (pl. marilyn-monroe).".into(),
));
}
if free_slug(&state.db, s, Some(id)).await? != s {
return Err(ApiError::conflict("slug_taken", "Ez a cím már foglalt."));
}
s.to_string()
}
_ => row.slug.clone(),
};
let unit =
|v: Option<f32>, current: f32| v.map_or(current, |v| if v.is_finite() { v.clamp(0.0, 1.0) } else { current });
let (focus_x, focus_y) = (unit(req.focus_x, row.focus_x), unit(req.focus_y, row.focus_y));
let published_at = match req.published {
Some(true) => row.published_at.or(Some(OffsetDateTime::now_utc())),
Some(false) => None,
None => row.published_at,
};
let chart = find_chart(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
let birth = req.birth.filter(|b| *b != chart.birth_data);
let recalculated = match birth {
Some(birth) => Some(chart_for(&state, birth).await?),
None => None,
};
let chart_changed = recalculated.as_ref().is_some_and(|(_, _, hash)| *hash != chart.chart_hash);
let mut tx = state.db.begin().await?;
if let Some((birth, result, hash)) = &recalculated {
if chart_changed {
// The analysis was written from the old chart.
sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(chart.id).execute(&mut *tx).await?;
}
sqlx::query(
"UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3, updated_at = now() WHERE id = $4",
)
.bind(birth)
.bind(result)
.bind(hash)
.bind(chart.id)
.execute(&mut *tx)
.await?;
}
sqlx::query("UPDATE charts SET label = $1 WHERE id = $2").bind(&name).bind(chart.id).execute(&mut *tx).await?;
let row: CelebrityRow = sqlx::query_as(&format!(
"UPDATE celebrities SET name = $2, subtitle = $3, slug = $4, focus_x = $5, focus_y = $6, published_at = $7, \
updated_at = now() WHERE id = $1 RETURNING {COLUMNS}"
))
.bind(id)
.bind(&name)
.bind(&subtitle)
.bind(&slug)
.bind(focus_x)
.bind(focus_y)
.bind(published_at)
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
if chart_changed {
let chart = find_chart(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
queue_analysis(&state, &admin, &chart).await?;
}
Ok(Json(admin_view(&state.db, &row).await?))
}
/// Queues the analysis again when there is none or the last one failed
/// (rewriting a finished one: `POST /v1/admin/analyses/{id}/regenerate`).
pub async fn request_analysis(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let row = find(&state.db, id).await?;
let chart = find_chart(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
queue_analysis(&state, &admin, &chart).await?;
Ok(Json(admin_view(&state.db, &row).await?))
}
fn storage(state: &AppState) -> Result<&crate::storage::Storage, ApiError> {
state
.storage
.as_ref()
.ok_or_else(|| ApiError::conflict("storage_not_configured", "A fotótárolás nincs beállítva (S3_ENDPOINT)."))
}
/// Deletes a stored photo; a failure is only logged (the row no longer points to it).
async fn delete_photo(state: &AppState, key: &str) {
if let Some(storage) = &state.storage
&& let Err(e) = storage.delete(key).await
{
tracing::warn!(key, error = %e, "deleting a photo from the object storage failed");
}
}
/// Uploads the photo (the request body is the image itself: JPEG, PNG or
/// WebP); it replaces the previous one. The face point is reset.
pub async fn upload_photo(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
body: Bytes,
) -> ApiResult<Json<Value>> {
let row = find(&state.db, id).await?;
let storage = storage(&state)?;
if body.len() > crate::photo::MAX_UPLOAD {
return Err(ApiError::BadRequest("A kép legfeljebb 15 MB lehet.".into()));
}
let photo = tokio::task::spawn_blocking(move || crate::photo::normalize(&body))
.await
.map_err(|e| ApiError::Internal(format!("photo processing: {e}")))?
.map_err(ApiError::BadRequest)?;
let key = format!("celebrities/{}/{}.jpg", row.id, db::random_token(9));
storage
.put(&key, photo.jpeg, "image/jpeg")
.await
.map_err(|e| ApiError::Internal(format!("storing the photo: {e}")))?;
let updated: CelebrityRow = sqlx::query_as(&format!(
"UPDATE celebrities SET photo_key = $2, photo_width = $3, photo_height = $4, focus_x = 0.5, focus_y = 0.3, \
updated_at = now() WHERE id = $1 RETURNING {COLUMNS}"
))
.bind(id)
.bind(&key)
.bind(i32::try_from(photo.width).unwrap_or(i32::MAX))
.bind(i32::try_from(photo.height).unwrap_or(i32::MAX))
.fetch_one(&state.db)
.await?;
if let Some(old) = &row.photo_key {
delete_photo(&state, old).await;
}
tracing::info!(admin = %admin.id(), celebrity = %id, width = photo.width, height = photo.height, "photo uploaded");
Ok(Json(admin_view(&state.db, &updated).await?))
}
pub async fn remove_photo(
State(state): St,
_admin: AdminUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let row = find(&state.db, id).await?;
let updated: CelebrityRow = sqlx::query_as(&format!(
"UPDATE celebrities SET photo_key = NULL, photo_width = NULL, photo_height = NULL, updated_at = now() \
WHERE id = $1 RETURNING {COLUMNS}"
))
.bind(id)
.fetch_one(&state.db)
.await?;
if let Some(old) = &row.photo_key {
delete_photo(&state, old).await;
}
Ok(Json(admin_view(&state.db, &updated).await?))
}
/// Deletes the famous person with their chart, analysis and photo.
pub async fn remove(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<StatusCode> {
let row = find(&state.db, id).await?;
sqlx::query("DELETE FROM charts WHERE id = $1").bind(row.chart_id).execute(&state.db).await?;
if let Some(key) = &row.photo_key {
delete_photo(&state, key).await;
}
tracing::info!(admin = %admin.id(), celebrity = %id, "famous person deleted");
Ok(StatusCode::NO_CONTENT)
}
// --- public ------------------------------------------------------------------------------------
/// Public: the published famous people, newest first.
pub async fn public_list(State(state): St) -> ApiResult<Json<Value>> {
let rows: Vec<CelebrityRow> = sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM celebrities WHERE published_at IS NOT NULL ORDER BY published_at DESC"
))
.fetch_all(&state.db)
.await?;
let mut items = Vec::with_capacity(rows.len());
for row in &rows {
let chart = find_chart(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
let mut item = row.base();
item["birth"] = public_chart(&chart.result, true)["birth"].clone();
item["highlights"] = chart_highlights(&chart.result);
items.push(item);
}
Ok(Json(json!({ "celebrities": items })))
}
/// Public: one famous person's page (a draft only for admins).
pub async fn public_view(
State(state): St,
auth: Result<AuthUser, ApiError>,
Path(slug): Path<String>,
) -> ApiResult<Json<Value>> {
let row: CelebrityRow = sqlx::query_as(&format!("SELECT {COLUMNS} FROM celebrities WHERE slug = $1"))
.bind(slug.trim())
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("celebrity"))?;
let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin));
if row.published_at.is_none() && !admin {
return Err(ApiError::NotFound("celebrity"));
}
let chart = find_chart(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
let analysis = latest_analysis(&state.db, row.chart_id).await?.filter(|a| a.status == "done");
let mut view = row.base();
view["chart"] = public_chart(&chart.result, true);
view["analysis"] = match analysis {
Some(a) => json!({
"id": a.id,
"language": a.language,
"content": a.content,
"completed_at": rfc3339_opt(a.completed_at),
}),
None => Value::Null,
};
Ok(Json(view))
}
/// Public: a stored photo, only while a famous person uses it. The key changes
/// with every upload, so it may be cached for good.
pub async fn photo(State(state): St, Path(key): Path<String>) -> ApiResult<Response> {
let used: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM celebrities WHERE photo_key = $1)")
.bind(&key)
.fetch_one(&state.db)
.await?;
if !used {
return Err(ApiError::NotFound("photo"));
}
let object = storage(&state)?
.get(&key)
.await
.map_err(|e| ApiError::Internal(format!("reading the photo: {e}")))?
.ok_or(ApiError::NotFound("photo"))?;
Ok((
[
(header::CONTENT_TYPE, object.content_type.unwrap_or_else(|| "image/jpeg".into())),
(header::CACHE_CONTROL, "public, max-age=31536000, immutable".into()),
],
object.bytes,
)
.into_response())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs() {
assert_eq!(slugify("Marilyn Monroe"), "marilyn-monroe");
assert_eq!(slugify(" Kovács Ödön (1911–1996) "), "kovacs-odon-1911-1996");
assert_eq!(slugify("Szőke Szabolcs, Jr."), "szoke-szabolcs-jr");
assert_eq!(slugify("!!!"), "hires-ember");
assert!(valid_slug("marilyn-monroe") && valid_slug("a1"));
assert!(!valid_slug("Marilyn") && !valid_slug("a--b") && !valid_slug("-a") && !valid_slug(""));
}
}