hafas 1.0.0

Client for the HAFAS ReST public transport API
Documentation
//! The requests of the API, one type per service.
//!
//! Fields left at `None` are not sent, so the server uses its default. The
//! client adds `accessId`, `format` and `lang` itself. Dates are
//! `YYYY-MM-DD` and times `HH:MM`, in the time zone of the server.

use std::fmt::Display;

use serde::de::DeserializeOwned;

use crate::enums::RtMode;
use crate::types::{ArrivalList, DepartureList, Journey, LocationList, TripList};

/// A request to one service, sent with [`Client::send`](crate::Client::send).
pub trait Request {
    /// The path below the base URL, without a leading slash.
    const PATH: &'static str;

    /// What the service answers.
    type Response: DeserializeOwned;

    /// The query parameters, in a fixed order.
    fn query(&self) -> Vec<(&'static str, String)>;
}

/// Collects query parameters, skipping the unset ones.
#[derive(Default)]
struct Query(Vec<(&'static str, String)>);

impl Query {
    fn set(mut self, name: &'static str, value: impl Display) -> Self {
        self.0.push((name, value.to_string()));
        self
    }

    fn opt(self, name: &'static str, value: Option<impl Display>) -> Self {
        match value {
            Some(value) => self.set(name, value),
            None => self,
        }
    }

    /// A flag, sent as `1` or `0` like the API takes it.
    fn flag(self, name: &'static str, value: Option<bool>) -> Self {
        self.opt(name, value.map(u8::from))
    }
}

/// Finds locations by name (`location.name`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LocationName {
    pub input: String,
    /// The most matches to return.
    pub max_no: Option<u32>,
    /// Which kinds of locations, like `S` for stops only or `ALL`.
    pub kind: Option<String>,
    /// Only stops served by these product classes, as a bit mask.
    pub products: Option<u32>,
    /// Prefers matches near this position, as latitude and longitude
    /// (`coordLat`, `coordLong`).
    pub near: Option<(f64, f64)>,
}

impl LocationName {
    pub fn new(input: impl Into<String>) -> Self {
        Self {
            input: input.into(),
            ..Self::default()
        }
    }
}

impl Request for LocationName {
    const PATH: &'static str = "location.name";
    type Response = LocationList;

    fn query(&self) -> Vec<(&'static str, String)> {
        Query::default()
            .set("input", &self.input)
            .opt("maxNo", self.max_no)
            .opt("type", self.kind.as_ref())
            .opt("products", self.products)
            .opt("coordLat", self.near.map(|(lat, _)| lat))
            .opt("coordLong", self.near.map(|(_, lon)| lon))
            .0
    }
}

/// Finds stops near a position (`location.nearbystops`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NearbyStops {
    pub lat: f64,
    pub lon: f64,
    /// The search radius in meters.
    pub r: Option<u32>,
    pub max_no: Option<u32>,
    pub kind: Option<String>,
    pub products: Option<u32>,
}

impl NearbyStops {
    pub fn new(lat: f64, lon: f64) -> Self {
        Self {
            lat,
            lon,
            ..Self::default()
        }
    }
}

impl Request for NearbyStops {
    const PATH: &'static str = "location.nearbystops";
    type Response = LocationList;

    fn query(&self) -> Vec<(&'static str, String)> {
        Query::default()
            .set("originCoordLat", self.lat)
            .set("originCoordLong", self.lon)
            .opt("r", self.r)
            .opt("maxNo", self.max_no)
            .opt("type", self.kind.as_ref())
            .opt("products", self.products)
            .0
    }
}

/// Defines the request of a board: the departures or the arrivals of a stop.
macro_rules! board {
    ($(#[$meta:meta])* $name:ident, $path:literal, $response:ty) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Default, PartialEq)]
        pub struct $name {
            /// The stop, as a full or a short ID.
            pub id: String,
            /// The server takes the current date and time if unset.
            pub date: Option<String>,
            pub time: Option<String>,
            /// How far ahead to look, in minutes.
            pub duration: Option<u32>,
            /// The most journeys to return.
            pub max_journeys: Option<u32>,
            pub products: Option<u32>,
            /// Only journeys that go on to this stop.
            pub direction: Option<String>,
            pub rt_mode: Option<RtMode>,
        }

        impl $name {
            pub fn new(id: impl Into<String>) -> Self {
                Self {
                    id: id.into(),
                    ..Self::default()
                }
            }
        }

        impl Request for $name {
            const PATH: &'static str = $path;
            type Response = $response;

            fn query(&self) -> Vec<(&'static str, String)> {
                Query::default()
                    .set("id", &self.id)
                    .opt("date", self.date.as_ref())
                    .opt("time", self.time.as_ref())
                    .opt("duration", self.duration)
                    .opt("maxJourneys", self.max_journeys)
                    .opt("products", self.products)
                    .opt("direction", self.direction.as_ref())
                    .opt("rtMode", self.rt_mode.as_ref())
                    .0
            }
        }
    };
}

board!(
    /// The departures at a stop (`departureBoard`).
    DepartureBoard,
    "departureBoard",
    DepartureList
);
board!(
    /// The arrivals at a stop (`arrivalBoard`).
    ArrivalBoard,
    "arrivalBoard",
    ArrivalList
);

/// Where a trip starts or ends.
#[derive(Debug, Clone, PartialEq)]
pub enum Place {
    /// A location by its full or short ID.
    Id(String),
    /// A position.
    Coord { lat: f64, lon: f64 },
}

impl Default for Place {
    fn default() -> Self {
        Self::Id(String::new())
    }
}

/// Searches connections between two places (`trip`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TripSearch {
    pub origin: Place,
    pub destination: Place,
    /// The server takes the current date and time if unset.
    pub date: Option<String>,
    pub time: Option<String>,
    /// Whether [`TripSearch::time`] is the arrival.
    pub search_for_arrival: Option<bool>,
    /// How many trips after and before the time, together at most 6.
    pub num_f: Option<u32>,
    pub num_b: Option<u32>,
    /// A scroll context of an earlier answer (`scrB` or `scrF`).
    pub context: Option<String>,
    /// The most changes, 0 to 11.
    pub max_change: Option<u32>,
    pub products: Option<u32>,
    pub rt_mode: Option<RtMode>,
    /// Whether to list the intermediate stops of every leg.
    pub passlist: Option<bool>,
}

impl TripSearch {
    pub fn new(origin: Place, destination: Place) -> Self {
        Self {
            origin,
            destination,
            ..Self::default()
        }
    }
}

fn place(query: Query, prefix: Prefix, place: &Place) -> Query {
    match place {
        Place::Id(id) => query.set(prefix.id, id),
        Place::Coord { lat, lon } => query.set(prefix.lat, lat).set(prefix.lon, lon),
    }
}

#[derive(Clone, Copy)]
struct Prefix {
    id: &'static str,
    lat: &'static str,
    lon: &'static str,
}

const ORIGIN: Prefix = Prefix {
    id: "originId",
    lat: "originCoordLat",
    lon: "originCoordLong",
};

const DESTINATION: Prefix = Prefix {
    id: "destId",
    lat: "destCoordLat",
    lon: "destCoordLong",
};

impl Request for TripSearch {
    const PATH: &'static str = "trip";
    type Response = TripList;

    fn query(&self) -> Vec<(&'static str, String)> {
        let query = place(Query::default(), ORIGIN, &self.origin);
        place(query, DESTINATION, &self.destination)
            .opt("date", self.date.as_ref())
            .opt("time", self.time.as_ref())
            .flag("searchForArrival", self.search_for_arrival)
            .opt("numF", self.num_f)
            .opt("numB", self.num_b)
            .opt("context", self.context.as_ref())
            .opt("maxChange", self.max_change)
            .opt("products", self.products)
            .opt("rtMode", self.rt_mode.as_ref())
            .flag("passlist", self.passlist)
            .0
    }
}

/// One journey with all its stops (`journeyDetail`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct JourneyDetail {
    /// The reference of a [`JourneyDetailRef`](crate::JourneyDetailRef).
    pub id: String,
    /// The day of the journey, if the reference does not say.
    pub date: Option<String>,
    pub rt_mode: Option<RtMode>,
}

impl JourneyDetail {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            ..Self::default()
        }
    }
}

impl Request for JourneyDetail {
    const PATH: &'static str = "journeyDetail";
    type Response = Journey;

    fn query(&self) -> Vec<(&'static str, String)> {
        Query::default()
            .set("id", &self.id)
            .opt("date", self.date.as_ref())
            .opt("rtMode", self.rt_mode.as_ref())
            .0
    }
}

/// Checks a trip again with current data (`recon`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Recon {
    /// The [`Trip::ctx_recon`](crate::Trip::ctx_recon) of the trip.
    pub ctx: String,
    pub rt_mode: Option<RtMode>,
    pub passlist: Option<bool>,
}

impl Recon {
    pub fn new(ctx: impl Into<String>) -> Self {
        Self {
            ctx: ctx.into(),
            ..Self::default()
        }
    }
}

impl Request for Recon {
    const PATH: &'static str = "recon";
    type Response = TripList;

    fn query(&self) -> Vec<(&'static str, String)> {
        Query::default()
            .set("ctx", &self.ctx)
            .opt("rtMode", self.rt_mode.as_ref())
            .flag("passlist", self.passlist)
            .0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sends_places_as_ids_or_positions() {
        let trip = TripSearch {
            search_for_arrival: Some(true),
            passlist: Some(false),
            ..TripSearch::new(
                Place::Id("3000010".to_owned()),
                Place::Coord {
                    lat: 50.1,
                    lon: 8.6,
                },
            )
        };
        assert_eq!(
            trip.query(),
            [
                ("originId", "3000010".to_owned()),
                ("destCoordLat", "50.1".to_owned()),
                ("destCoordLong", "8.6".to_owned()),
                ("searchForArrival", "1".to_owned()),
                ("passlist", "0".to_owned()),
            ]
        );
    }
}