125 lines
4.7 KiB
Rust
125 lines
4.7 KiB
Rust
//! The public sign calculator (`/aszcendens-kalkulator`): the Sun, Moon and
|
|||
|
|
//! Ascendant signs from birth data, without an account, plus the country list
|
||
|
|
//! and place search it needs. Nothing is stored. Each visitor address may
|
||
|
|
//! make a limited number of calculations and place searches an hour, so the
|
||
|
|
//! endpoints cannot serve as a free calculation service for other apps.
|
||
|
|
|
||
|
|
use axum::Json;
|
||
|
|
use axum::extract::{Query, State};
|
||
|
|
use axum::http::HeaderMap;
|
||
|
|
use axum_extra::extract::WithRejection;
|
||
|
|
use serde::Deserialize;
|
||
|
|
use serde_json::{Value, json};
|
||
|
|
|
||
|
|
use super::{Body, St, client_ip};
|
||
|
|
use crate::error::{ApiError, ApiResult};
|
||
|
|
|
||
|
|
/// The limiter key of the visitor (all unknown addresses share one).
|
||
|
|
fn visitor(headers: &HeaderMap) -> String {
|
||
|
|
client_ip(headers).map_or_else(|| "unknown".to_string(), |ip| format!("ip:{ip}"))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn valid_country(country: &str) -> bool {
|
||
|
|
country.len() == 2 && country.chars().all(|c| c.is_ascii_uppercase())
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn countries(State(state): St) -> ApiResult<Json<Value>> {
|
||
|
|
Ok(Json(state.horoscope.countries().await?))
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
pub struct PlacesQuery {
|
||
|
|
country: String,
|
||
|
|
q: String,
|
||
|
|
limit: Option<u32>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn places(
|
||
|
|
State(state): St,
|
||
|
|
headers: HeaderMap,
|
||
|
|
WithRejection(Query(query), _): WithRejection<Query<PlacesQuery>, ApiError>,
|
||
|
|
) -> ApiResult<Json<Value>> {
|
||
|
|
let q = query.q.trim();
|
||
|
|
if !valid_country(&query.country) || q.chars().count() < 2 || q.chars().count() > 80 {
|
||
|
|
return Err(ApiError::BadRequest("a country code and 2 to 80 characters of a place name are needed".into()));
|
||
|
|
}
|
||
|
|
state.places_limiter.hit(&visitor(&headers))?;
|
||
|
|
Ok(Json(state.horoscope.places(&query.country, q, query.limit.unwrap_or(8).min(10)).await?))
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
#[serde(deny_unknown_fields)]
|
||
|
|
pub struct SignsRequest {
|
||
|
|
date: String,
|
||
|
|
/// "HH:MM"; without it there is no Ascendant.
|
||
|
|
time: Option<String>,
|
||
|
|
country: String,
|
||
|
|
geonames_id: i64,
|
||
|
|
/// "earlier" or "later", for a time that occurred twice (clocks set back).
|
||
|
|
ambiguous_time: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One sign of the answer. `uncertain`: without a birth time the point may
|
||
|
|
/// have been in the neighbouring sign at the start or the end of the day.
|
||
|
|
fn sign(point: &Value, time_known: bool, default_speed: f64) -> Value {
|
||
|
|
let degree = point["degree_in_sign"].as_f64();
|
||
|
|
let speed = point["speed"].as_f64().unwrap_or(default_speed).abs();
|
||
|
|
let uncertain = !time_known && degree.is_some_and(|d| d < speed / 2.0 || 30.0 - d < speed / 2.0);
|
||
|
|
json!({ "sign": point["sign"], "degree": degree.map(|d| d.floor()), "uncertain": uncertain })
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The Sun, Moon and Ascendant signs of the birth data.
|
||
|
|
pub async fn signs(
|
||
|
|
State(state): St,
|
||
|
|
headers: HeaderMap,
|
||
|
|
WithRejection(Json(req), _): Body<SignsRequest>,
|
||
|
|
) -> ApiResult<Json<Value>> {
|
||
|
|
if !valid_country(&req.country) {
|
||
|
|
return Err(ApiError::BadRequest("invalid country code".into()));
|
||
|
|
}
|
||
|
|
if req.ambiguous_time.as_deref().is_some_and(|a| a != "earlier" && a != "later") {
|
||
|
|
return Err(ApiError::BadRequest("ambiguous_time is 'earlier' or 'later'".into()));
|
||
|
|
}
|
||
|
|
state.calculator_limiter.hit(&visitor(&headers))?;
|
||
|
|
let mut birth = json!({ "date": req.date, "country": req.country, "geonames_id": req.geonames_id });
|
||
|
|
if let Some(time) = &req.time {
|
||
|
|
birth["time"] = json!(time);
|
||
|
|
}
|
||
|
|
if let Some(ambiguous) = &req.ambiguous_time {
|
||
|
|
birth["ambiguous_time"] = json!(ambiguous);
|
||
|
|
}
|
||
|
|
let chart = state.horoscope.natal(&birth).await?;
|
||
|
|
let time_known = req.time.is_some();
|
||
|
|
let point = |id: &str| {
|
||
|
|
chart["points"]
|
||
|
|
.as_array()
|
||
|
|
.and_then(|points| points.iter().find(|p| p["id"] == id))
|
||
|
|
.cloned()
|
||
|
|
.unwrap_or(Value::Null)
|
||
|
|
};
|
||
|
|
let ascendant = &chart["angles"]["ascendant"];
|
||
|
|
Ok(Json(json!({
|
||
|
|
"sun": sign(&point("sun"), time_known, 1.0),
|
||
|
|
"moon": sign(&point("moon"), time_known, 13.2),
|
||
|
|
"ascendant": (time_known && ascendant["sign"].is_string()).then(|| sign(ascendant, true, 0.0)),
|
||
|
|
"time_known": time_known,
|
||
|
|
"place": chart["location"]["place"]["name"],
|
||
|
|
})))
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::*;
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn signs_near_a_border_are_uncertain_without_a_time() {
|
||
|
|
let moon = json!({"sign": "pisces", "degree_in_sign": 3.2, "speed": 12.6});
|
||
|
|
assert_eq!(sign(&moon, false, 13.2)["uncertain"], true);
|
||
|
|
assert_eq!(sign(&moon, true, 13.2)["uncertain"], false);
|
||
|
|
let middle = json!({"sign": "pisces", "degree_in_sign": 15.0, "speed": 12.6});
|
||
|
|
assert_eq!(sign(&middle, false, 13.2), json!({"sign": "pisces", "degree": 15.0, "uncertain": false}));
|
||
|
|
let sun = json!({"sign": "cancer", "degree_in_sign": 29.8});
|
||
|
|
assert_eq!(sign(&sun, false, 1.0)["uncertain"], true);
|
||
|
|
}
|
||
|
|
}
|