Files
sorsfonalak/services/backend/src/views.rs
T

130 lines
4.8 KiB
Rust
Raw Normal View History

//! JSON shapes returned by the API and helpers to build them.
use db::User;
use serde::Serialize;
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use uuid::Uuid;
pub fn sha256_hex(text: &str) -> String {
Sha256::digest(text.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
}
/// Identifies a calculated chart independently of how the place was entered:
/// the resolved UTC moment, coordinates, options and ephemeris version.
pub fn chart_hash(result: &Value) -> String {
let settings = serde_json::to_string(&result["settings"]).unwrap_or_default();
sha256_hex(&format!(
"natal|{}|{}|{:.5}|{:.5}|{settings}|{}",
result["time"]["utc"].as_str().unwrap_or_default(),
result["time"]["time_known"].as_bool().unwrap_or(true),
result["location"]["latitude"].as_f64().unwrap_or_default(),
result["location"]["longitude"].as_f64().unwrap_or_default(),
result["meta"]["data_sources"]["ephemeris"]["version"].as_str().unwrap_or_default(),
))
}
pub fn synastry_hash(hash1: &str, hash2: &str, settings: &Value) -> String {
sha256_hex(&format!("synastry|{hash1}|{hash2}|{}", serde_json::to_string(settings).unwrap_or_default()))
}
/// The chart without anything that identifies the birth (date, time, place,
/// Julian day, request echo); positions, houses, aspects and summary stay.
/// With `show_birth_data` a short `birth` block is added instead.
pub fn public_chart(result: &Value, show_birth_data: bool) -> Value {
let mut out = Map::new();
if let Some(obj) = result.as_object() {
for (k, v) in obj {
if !matches!(k.as_str(), "input" | "location" | "time" | "astronomy" | "meta" | "warnings") {
out.insert(k.clone(), v.clone());
}
}
}
out.insert("time_known".into(), result["time"]["time_known"].clone());
if show_birth_data {
let known = result["time"]["time_known"].as_bool().unwrap_or(false);
let local = result["time"]["local"].as_str().unwrap_or_default();
let (date, time) = local.split_once('T').unwrap_or((local, ""));
out.insert(
"birth".into(),
json!({
"date": date,
"time": if known { Value::from(time.get(..5).unwrap_or(time)) } else { Value::Null },
"place": result["location"]["place"]["name"],
"region": result["location"]["place"]["region"],
"country": result["location"]["country"]["name"],
}),
);
}
Value::Object(out)
}
/// Sign of a point or angle, for compact listings.
pub fn chart_highlights(result: &Value) -> Value {
let sign_of = |id: &str| {
result["points"].as_array().and_then(|ps| ps.iter().find(|p| p["id"] == id)).map(|p| p["sign"].clone())
};
json!({
"sun": sign_of("sun"),
"moon": sign_of("moon"),
"ascendant": result["angles"]["ascendant"]["sign"],
"time_known": result["time"]["time_known"],
})
}
#[derive(Debug, Serialize)]
pub struct UserView {
pub id: Uuid,
pub email: String,
pub email_verified: bool,
pub display_name: Option<String>,
pub locale: String,
pub roles: Vec<String>,
#[serde(with = "time::serde::rfc3339")]
pub created_at: OffsetDateTime,
}
impl From<&User> for UserView {
fn from(u: &User) -> Self {
Self {
id: u.id,
email: u.email.clone(),
email_verified: u.email_verified_at.is_some(),
display_name: u.display_name.clone(),
locale: u.locale.clone(),
roles: u.roles.clone(),
created_at: u.created_at,
}
}
}
pub fn rfc3339(t: OffsetDateTime) -> String {
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
}
pub fn rfc3339_opt(t: Option<OffsetDateTime>) -> Value {
t.map(|t| Value::from(rfc3339(t))).unwrap_or(Value::Null)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn public_chart_hides_birth_data() {
let result = json!({
"input": {"date": "1990-03-15"}, "location": {"place": {"name": "Szeged"}, "country": {"name": "Hungary"}},
"time": {"local": "1990-03-15T14:30:00", "time_known": true}, "astronomy": {"julian_day_ut": 1.0},
"meta": {}, "warnings": [], "points": [{"id": "sun", "sign": "cancer"}]
});
let hidden = public_chart(&result, false);
assert!(hidden.get("input").is_none() && hidden.get("location").is_none() && hidden.get("birth").is_none());
assert_eq!(hidden["points"][0]["sign"], "cancer");
let shown = public_chart(&result, true);
assert_eq!(shown["birth"]["date"], "1990-03-15");
assert_eq!(shown["birth"]["time"], "14:30");
assert_eq!(shown["birth"]["place"], "Szeged");
}
}