use hafas::{Place, Recon, RtMode, TripList, TripSearch};
use crate::model::{Attribution, Connection, Location, PageCursor, TripResult};
use crate::service::Rmv;
use crate::{Error, convert, modes, resolve, time};
pub const MAX_CONNECTIONS: u32 = 6;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TripQuery {
pub from: String,
pub to: String,
pub time: Option<jiff::Timestamp>,
pub arrive_by: bool,
pub count: u32,
pub modes: Vec<String>,
pub max_transfers: Option<u32>,
pub page_cursor: Option<String>,
pub realtime_routing: bool,
}
struct Endpoint {
place: Place,
location: Location,
}
impl Rmv {
async fn endpoint(&self, input: &str) -> Result<Endpoint, Error> {
if let Some((lat, lon)) = resolve::coordinates(input) {
return Ok(Endpoint {
place: Place::Coord { lat, lon },
location: Location {
id: None,
name: input.trim().to_owned(),
dhid: None,
},
});
}
let (id, name) = self.resolve_stop(input).await?;
Ok(Endpoint {
location: Location {
name: name.unwrap_or_else(|| id.clone()),
id: Some(id.clone()),
dhid: None,
},
place: Place::Id(id),
})
}
pub async fn trip(&self, query: &TripQuery) -> Result<TripResult, Error> {
let products = modes::products(&query.modes)?;
if query.max_transfers.is_some_and(|max| max > 11) {
return Err(Error::BadRequest {
message: "max_transfers is at most 11".to_owned(),
});
}
let from = self.endpoint(&query.from).await?;
let to = self.endpoint(&query.to).await?;
let cursor = query
.page_cursor
.as_deref()
.map(str::trim)
.filter(|c| !c.is_empty());
let (date, time) = match cursor {
Some(_) => (None, None),
None => query.time.map(time::request).unzip(),
};
let count = query.count.clamp(1, MAX_CONNECTIONS);
let request = TripSearch {
date,
time,
search_for_arrival: query.arrive_by.then_some(true),
num_f: Some(count),
context: cursor.map(str::to_owned),
max_change: query.max_transfers,
products,
rt_mode: Some(if query.realtime_routing {
RtMode::Realtime
} else {
RtMode::Infos
}),
passlist: Some(false),
..TripSearch::new(from.place, to.place)
};
let mut list = self.call_or_none(&request).await?.unwrap_or_default();
let mut warnings = Vec::new();
if query.arrive_by
&& cursor.is_none()
&& list.trips.len() < count as usize
&& let Some(earlier) = list.scr_b.clone()
{
let missing = count as usize - list.trips.len();
let request = TripSearch {
context: Some(earlier),
num_f: u32::try_from(missing).ok(),
..request
};
let more = self.call_or_none(&request).await;
fill_up(&mut list, more, missing, &mut warnings);
}
Ok(self.trip_result(list, from.location, to.location, warnings))
}
pub async fn recheck(&self, token: &str) -> Result<TripResult, Error> {
let token = token.trim();
if token.is_empty() {
return Err(Error::BadRequest {
message: "the recheck token is empty".to_owned(),
});
}
let request = Recon {
rt_mode: Some(RtMode::Infos),
passlist: Some(false),
..Recon::new(token)
};
let list = self.call(&request).await?;
let unknown = || Location {
id: None,
name: String::new(),
dhid: None,
};
Ok(self.trip_result(list, unknown(), unknown(), Vec::new()))
}
fn trip_result(
&self,
mut list: TripList,
from: Location,
to: Location,
warnings: Vec<String>,
) -> TripResult {
dedupe(&mut list.trips);
list.trips.sort_by_key(convert::departure);
let now = (self.clock)();
let first = list.trips.first();
let from = first
.and_then(|trip| {
trip.legs
.first()
.map(|leg| &leg.origin)
.or(trip.origin.as_ref())
})
.map_or(from, Location::from);
let to = first
.and_then(|trip| {
trip.legs
.last()
.map(|leg| &leg.destination)
.or(trip.destination.as_ref())
})
.map_or(to, Location::from);
TripResult {
from,
to,
connections: list
.trips
.iter()
.map(|trip| Connection::new(trip, now, self.delay_threshold_minutes))
.collect(),
page_cursor: PageCursor {
earlier: list.scr_b,
later: list.scr_f,
},
realtime_as_of: time::plan_rt(list.info.plan_rt_ts.as_deref()),
attribution: Attribution::default(),
warnings,
}
}
}
fn dedupe(trips: &mut Vec<hafas::Trip>) {
let mut seen: Vec<String> = Vec::new();
trips.retain(|trip| {
let Some(ctx) = trip.ctx_recon.as_deref() else {
return true;
};
let new = !seen.iter().any(|known| known == ctx);
if new {
seen.push(ctx.to_owned());
}
new
});
}
fn fill_up(
list: &mut TripList,
earlier: Result<Option<TripList>, Error>,
missing: usize,
warnings: &mut Vec<String>,
) {
match earlier {
Ok(more) => {
let mut more = more.unwrap_or_default();
dedupe(&mut more.trips);
more.trips.retain(|trip| {
trip.ctx_recon.is_none()
|| !list
.trips
.iter()
.any(|known| known.ctx_recon == trip.ctx_recon)
});
let skip = more.trips.len().saturating_sub(missing);
list.trips.extend(more.trips.into_iter().skip(skip));
list.scr_b = more.scr_b;
}
Err(error) => warnings.push(format!("no earlier connections: {error}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_each_trip_once() {
let trip = |ctx: Option<&str>| hafas::Trip {
ctx_recon: ctx.map(str::to_owned),
..hafas::Trip::default()
};
let mut trips = vec![trip(Some("a")), trip(None), trip(Some("a")), trip(None)];
dedupe(&mut trips);
let left: Vec<Option<&str>> = trips.iter().map(|t| t.ctx_recon.as_deref()).collect();
assert_eq!(left, [Some("a"), None, None]);
}
#[test]
fn a_failed_earlier_page_is_a_warning() {
let mut list = TripList {
scr_b: Some("before".to_owned()),
..TripList::default()
};
let mut warnings = Vec::new();
fill_up(
&mut list,
Err(Error::Unavailable {
message: "down".to_owned(),
}),
1,
&mut warnings,
);
assert_eq!(list.scr_b.as_deref(), Some("before"));
assert_eq!(warnings.len(), 1);
assert!(
warnings[0].starts_with("no earlier connections: "),
"{warnings:?}"
);
fill_up(&mut list, Ok(None), 1, &mut warnings);
assert_eq!(list.scr_b, None);
}
#[test]
fn the_earlier_page_only_fills_up() {
let trip = |ctx: &str| hafas::Trip {
ctx_recon: Some(ctx.to_owned()),
..hafas::Trip::default()
};
let mut list = TripList {
trips: vec![trip("c")],
..TripList::default()
};
let earlier = TripList {
trips: vec![trip("x"), trip("a"), trip("b"), trip("c")],
..TripList::default()
};
let mut warnings = Vec::new();
fill_up(&mut list, Ok(Some(earlier)), 2, &mut warnings);
let left: Vec<Option<&str>> = list.trips.iter().map(|t| t.ctx_recon.as_deref()).collect();
assert_eq!(left, [Some("c"), Some("a"), Some("b")]);
assert_eq!(warnings, Vec::<String>::new());
}
}