297 lines
9.9 KiB
Rust
297 lines
9.9 KiB
Rust
//! The sky by date, the same for everyone (tropical, geocentric):
|
|||
|
|
//!
|
||
|
|
//! * `GET /v1/sky?at=&tz=`: the sky at a moment (default now): where the
|
||
|
|
//! planets are, which are retrograde and their next station, the Moon's
|
||
|
|
//! phase, when it changes sign, and the next main phases;
|
||
|
|
//! * `GET /v1/sky/events?year=&tz=`: a calendar year's lunar phases (with the
|
||
|
|
//! eclipses on them), the Moon's sign changes and the retrograde periods
|
||
|
|
//! with their shadows.
|
||
|
|
//!
|
||
|
|
//! Local times are on the clock of `tz` (default Europe/Budapest).
|
||
|
|
|
||
|
|
use astro_engine::chart::{MoonPhaseName, ZodiacPosition};
|
||
|
|
use astro_engine::sky::{
|
||
|
|
LunationKind, RETROGRADING, Station, lunations, moon_ingresses, moon_now, next_station, retrograde_periods,
|
||
|
|
};
|
||
|
|
use astro_engine::{Body, EclipseKind, EclipseType, Frame, ZodiacSign};
|
||
|
|
use geo_tz::tz::format_offset;
|
||
|
|
use jiff::Timestamp;
|
||
|
|
use jiff::tz::TimeZone;
|
||
|
|
use serde::{Deserialize, Serialize};
|
||
|
|
|
||
|
|
use crate::AppState;
|
||
|
|
use crate::error::ApiError;
|
||
|
|
|
||
|
|
pub const DEFAULT_TZ: &str = "Europe/Budapest";
|
||
|
|
/// The calendar years served.
|
||
|
|
pub const YEARS: std::ops::RangeInclusive<i32> = 1900..=2100;
|
||
|
|
/// Far enough ahead for every planet's next station (Mars may run direct for two years).
|
||
|
|
const STATION_HORIZON_DAYS: f64 = 800.0;
|
||
|
|
|
||
|
|
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
|
||
|
|
|
||
|
|
fn jd_of(ts: Timestamp) -> f64 {
|
||
|
|
ts.as_second() as f64 / 86_400.0 + UNIX_EPOCH_JD
|
||
|
|
}
|
||
|
|
|
||
|
|
fn timestamp_of(jd: f64) -> Result<Timestamp, ApiError> {
|
||
|
|
Timestamp::from_second(((jd - UNIX_EPOCH_JD) * 86_400.0).round() as i64)
|
||
|
|
.map_err(|e| ApiError::Internal(e.to_string()))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn calc(e: astro_engine::EngineError) -> ApiError {
|
||
|
|
ApiError::Calculation(e.to_string())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A moment in UTC and on the local clock (to the minute).
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct Moment {
|
||
|
|
pub moment_utc: String,
|
||
|
|
/// `YYYY-MM-DDTHH:MM`, rounded to the minute.
|
||
|
|
pub local_time: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
fn moment(jd: f64, tz: &TimeZone) -> Result<Moment, ApiError> {
|
||
|
|
let ts = timestamp_of(jd)?;
|
||
|
|
let minute = Timestamp::from_second((ts.as_second() + 30).div_euclid(60) * 60)
|
||
|
|
.map_err(|e| ApiError::Internal(e.to_string()))?;
|
||
|
|
Ok(Moment { moment_utc: ts.to_string(), local_time: tz.to_datetime(minute).strftime("%Y-%m-%dT%H:%M").to_string() })
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct StationOut {
|
||
|
|
#[serde(flatten)]
|
||
|
|
pub moment: Moment,
|
||
|
|
/// Turns retrograde (`true`) or direct here.
|
||
|
|
pub retrograde: bool,
|
||
|
|
pub position: ZodiacPosition,
|
||
|
|
}
|
||
|
|
|
||
|
|
fn station(s: &Station, tz: &TimeZone) -> Result<StationOut, ApiError> {
|
||
|
|
Ok(StationOut {
|
||
|
|
moment: moment(s.jd_ut, tz)?,
|
||
|
|
retrograde: s.retrograde,
|
||
|
|
position: ZodiacPosition::new(s.longitude),
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct EclipseOut {
|
||
|
|
pub kind: EclipseKind,
|
||
|
|
pub eclipse_type: EclipseType,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct LunationOut {
|
||
|
|
pub kind: LunationKind,
|
||
|
|
#[serde(flatten)]
|
||
|
|
pub moment: Moment,
|
||
|
|
/// Where the Moon is.
|
||
|
|
pub position: ZodiacPosition,
|
||
|
|
/// The eclipse at this new or full moon, if any.
|
||
|
|
pub eclipse: Option<EclipseOut>,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The lunations between two moments, with the eclipses on them.
|
||
|
|
fn lunations_out(state: &AppState, from: f64, to: f64, tz: &TimeZone) -> Result<Vec<LunationOut>, ApiError> {
|
||
|
|
let engine = state.engine.as_ref();
|
||
|
|
let eclipses = engine.eclipses(from - 1.0, to + 1.0).map_err(calc)?;
|
||
|
|
lunations(engine, from, to)
|
||
|
|
.map_err(calc)?
|
||
|
|
.into_iter()
|
||
|
|
.map(|l| {
|
||
|
|
let eclipse = eclipses
|
||
|
|
.iter()
|
||
|
|
.find(|e| {
|
||
|
|
let on = match e.kind {
|
||
|
|
EclipseKind::Solar => LunationKind::NewMoon,
|
||
|
|
EclipseKind::Lunar => LunationKind::FullMoon,
|
||
|
|
};
|
||
|
|
on == l.kind && (e.jd_ut - l.jd_ut).abs() < 0.6
|
||
|
|
})
|
||
|
|
.map(|e| EclipseOut { kind: e.kind, eclipse_type: e.eclipse_type });
|
||
|
|
Ok(LunationOut {
|
||
|
|
kind: l.kind,
|
||
|
|
moment: moment(l.jd_ut, tz)?,
|
||
|
|
position: ZodiacPosition::new(l.moon_longitude),
|
||
|
|
eclipse,
|
||
|
|
})
|
||
|
|
})
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct IngressOut {
|
||
|
|
#[serde(flatten)]
|
||
|
|
pub moment: Moment,
|
||
|
|
pub sign: ZodiacSign,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct PlanetNow {
|
||
|
|
pub id: Body,
|
||
|
|
pub position: ZodiacPosition,
|
||
|
|
/// Degrees a day (negative: retrograde).
|
||
|
|
pub speed: f64,
|
||
|
|
pub retrograde: bool,
|
||
|
|
/// The next station (the end of a retrograde period, or the start of the next one).
|
||
|
|
pub next_station: Option<StationOut>,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct MoonOut {
|
||
|
|
pub position: ZodiacPosition,
|
||
|
|
pub phase: MoonPhaseName,
|
||
|
|
/// Illuminated fraction of the disc (0..1).
|
||
|
|
pub illumination: f64,
|
||
|
|
/// Moon minus Sun, degrees.
|
||
|
|
pub elongation: f64,
|
||
|
|
pub waxing: bool,
|
||
|
|
/// When the Moon enters the next sign.
|
||
|
|
pub sign_change: Option<IngressOut>,
|
||
|
|
/// The next four main phases.
|
||
|
|
pub next_phases: Vec<LunationOut>,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct SkyResponse {
|
||
|
|
#[serde(flatten)]
|
||
|
|
pub moment: Moment,
|
||
|
|
pub timezone: String,
|
||
|
|
pub utc_offset: String,
|
||
|
|
pub planets: Vec<PlanetNow>,
|
||
|
|
pub moon: MoonOut,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Deserialize)]
|
||
|
|
#[serde(deny_unknown_fields)]
|
||
|
|
pub struct SkyQuery {
|
||
|
|
/// RFC 3339; now when not given.
|
||
|
|
pub at: Option<String>,
|
||
|
|
pub tz: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
fn zone(state: &AppState, name: Option<&str>) -> Result<(String, TimeZone), ApiError> {
|
||
|
|
let name = name.unwrap_or(DEFAULT_TZ);
|
||
|
|
Ok((name.to_string(), state.atlas.zones.get(name)?))
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn now(state: &AppState, query: SkyQuery) -> Result<SkyResponse, ApiError> {
|
||
|
|
let (zone_name, tz) = zone(state, query.tz.as_deref())?;
|
||
|
|
let ts = match query.at.as_deref() {
|
||
|
|
Some(at) => at.parse::<Timestamp>().map_err(|_| ApiError::BadRequest("at must be an RFC 3339 time".into()))?,
|
||
|
|
None => Timestamp::now(),
|
||
|
|
};
|
||
|
|
let jd = jd_of(ts);
|
||
|
|
let year = tz.to_datetime(ts).year();
|
||
|
|
if !YEARS.contains(&i32::from(year)) {
|
||
|
|
return Err(ApiError::BadRequest(format!("at must be between {} and {}", YEARS.start(), YEARS.end())));
|
||
|
|
}
|
||
|
|
let engine = state.engine.as_ref();
|
||
|
|
let planets = Body::PLANETS
|
||
|
|
.iter()
|
||
|
|
.map(|&body| {
|
||
|
|
let s = engine.position(body, jd, &Frame::TROPICAL_GEOCENTRIC).map_err(calc)?;
|
||
|
|
let next = if RETROGRADING.contains(&body) {
|
||
|
|
next_station(engine, body, jd, STATION_HORIZON_DAYS).map_err(calc)?
|
||
|
|
} else {
|
||
|
|
None
|
||
|
|
};
|
||
|
|
Ok(PlanetNow {
|
||
|
|
id: body,
|
||
|
|
position: ZodiacPosition::new(s.longitude),
|
||
|
|
speed: s.speed_longitude,
|
||
|
|
retrograde: s.speed_longitude < 0.0,
|
||
|
|
next_station: next.as_ref().map(|n| station(n, &tz)).transpose()?,
|
||
|
|
})
|
||
|
|
})
|
||
|
|
.collect::<Result<Vec<_>, ApiError>>()?;
|
||
|
|
|
||
|
|
let m = moon_now(engine, jd).map_err(calc)?;
|
||
|
|
let sign_change = moon_ingresses(engine, jd, jd + 3.0)
|
||
|
|
.map_err(calc)?
|
||
|
|
.first()
|
||
|
|
.map(|&(t, sign)| Ok::<_, ApiError>(IngressOut { moment: moment(t, &tz)?, sign }))
|
||
|
|
.transpose()?;
|
||
|
|
let mut next_phases = lunations_out(state, jd, jd + 31.0, &tz)?;
|
||
|
|
next_phases.truncate(4);
|
||
|
|
let moon = MoonOut {
|
||
|
|
position: ZodiacPosition::new(m.longitude),
|
||
|
|
phase: m.phase,
|
||
|
|
illumination: m.illumination,
|
||
|
|
elongation: m.elongation,
|
||
|
|
waxing: m.elongation < 180.0,
|
||
|
|
sign_change,
|
||
|
|
next_phases,
|
||
|
|
};
|
||
|
|
Ok(SkyResponse {
|
||
|
|
moment: moment(jd, &tz)?,
|
||
|
|
timezone: zone_name,
|
||
|
|
utc_offset: format_offset(tz.to_offset(ts)),
|
||
|
|
planets,
|
||
|
|
moon,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct RetrogradeOut {
|
||
|
|
pub planet: Body,
|
||
|
|
pub station_retrograde: StationOut,
|
||
|
|
pub station_direct: StationOut,
|
||
|
|
/// The planet first reaches the degree where it turns direct.
|
||
|
|
pub shadow_start: Moment,
|
||
|
|
/// The planet is back at the degree where it turned retrograde.
|
||
|
|
pub shadow_end: Moment,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Serialize)]
|
||
|
|
pub struct EventsResponse {
|
||
|
|
pub year: i32,
|
||
|
|
pub timezone: String,
|
||
|
|
pub lunations: Vec<LunationOut>,
|
||
|
|
pub moon_ingresses: Vec<IngressOut>,
|
||
|
|
/// The retrograde periods overlapping the year, by planet, then by time.
|
||
|
|
pub retrogrades: Vec<RetrogradeOut>,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Deserialize)]
|
||
|
|
#[serde(deny_unknown_fields)]
|
||
|
|
pub struct EventsQuery {
|
||
|
|
pub year: i32,
|
||
|
|
pub tz: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn events(state: &AppState, query: EventsQuery) -> Result<EventsResponse, ApiError> {
|
||
|
|
if !YEARS.contains(&query.year) {
|
||
|
|
return Err(ApiError::BadRequest(format!("year must be between {} and {}", YEARS.start(), YEARS.end())));
|
||
|
|
}
|
||
|
|
let (zone_name, tz) = zone(state, query.tz.as_deref())?;
|
||
|
|
let start_of = |year: i32| -> Result<f64, ApiError> {
|
||
|
|
let zoned =
|
||
|
|
jiff::civil::date(year as i16, 1, 1).to_zoned(tz.clone()).map_err(|e| ApiError::Internal(e.to_string()))?;
|
||
|
|
Ok(jd_of(zoned.timestamp()))
|
||
|
|
};
|
||
|
|
let (from, to) = (start_of(query.year)?, start_of(query.year + 1)?);
|
||
|
|
let engine = state.engine.as_ref();
|
||
|
|
|
||
|
|
let lunations = lunations_out(state, from, to, &tz)?;
|
||
|
|
let moon_ingresses = moon_ingresses(engine, from, to)
|
||
|
|
.map_err(calc)?
|
||
|
|
.into_iter()
|
||
|
|
.map(|(t, sign)| Ok(IngressOut { moment: moment(t, &tz)?, sign }))
|
||
|
|
.collect::<Result<Vec<_>, ApiError>>()?;
|
||
|
|
let mut retrogrades = Vec::new();
|
||
|
|
for body in RETROGRADING {
|
||
|
|
for p in retrograde_periods(engine, body, from, to).map_err(calc)? {
|
||
|
|
retrogrades.push(RetrogradeOut {
|
||
|
|
planet: body,
|
||
|
|
station_retrograde: station(&p.station_retrograde, &tz)?,
|
||
|
|
station_direct: station(&p.station_direct, &tz)?,
|
||
|
|
shadow_start: moment(p.shadow_start, &tz)?,
|
||
|
|
shadow_end: moment(p.shadow_end, &tz)?,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(EventsResponse { year: query.year, timezone: zone_name, lunations, moon_ingresses, retrogrades })
|
||
|
|
}
|