1use hafas::{Place, Recon, RtMode, TripList, TripSearch};
4
5use crate::model::{Attribution, Connection, Location, PageCursor, TripResult};
6use crate::service::Rmv;
7use crate::{Error, convert, modes, resolve, time};
8
9pub const MAX_CONNECTIONS: u32 = 6;
11
12#[derive(Debug, Clone, Default, PartialEq)]
14pub struct TripQuery {
15 pub from: String,
17 pub to: String,
18 pub time: Option<jiff::Timestamp>,
20 pub arrive_by: bool,
22 pub count: u32,
24 pub modes: Vec<String>,
26 pub max_transfers: Option<u32>,
27 pub page_cursor: Option<String>,
29 pub realtime_routing: bool,
32}
33
34struct Endpoint {
36 place: Place,
37 location: Location,
38}
39
40impl Rmv {
41 async fn endpoint(&self, input: &str) -> Result<Endpoint, Error> {
42 if let Some((lat, lon)) = resolve::coordinates(input) {
43 return Ok(Endpoint {
44 place: Place::Coord { lat, lon },
45 location: Location {
46 id: None,
47 name: input.trim().to_owned(),
48 dhid: None,
49 },
50 });
51 }
52 let (id, name) = self.resolve_stop(input).await?;
53 Ok(Endpoint {
54 location: Location {
55 name: name.unwrap_or_else(|| id.clone()),
56 id: Some(id.clone()),
57 dhid: None,
58 },
59 place: Place::Id(id),
60 })
61 }
62
63 pub async fn trip(&self, query: &TripQuery) -> Result<TripResult, Error> {
65 let products = modes::products(&query.modes)?;
66 if query.max_transfers.is_some_and(|max| max > 11) {
67 return Err(Error::BadRequest {
68 message: "max_transfers is at most 11".to_owned(),
69 });
70 }
71 let from = self.endpoint(&query.from).await?;
72 let to = self.endpoint(&query.to).await?;
73 let cursor = query
74 .page_cursor
75 .as_deref()
76 .map(str::trim)
77 .filter(|c| !c.is_empty());
78 let (date, time) = match cursor {
79 Some(_) => (None, None),
80 None => query.time.map(time::request).unzip(),
81 };
82 let count = query.count.clamp(1, MAX_CONNECTIONS);
83 let request = TripSearch {
84 date,
85 time,
86 search_for_arrival: query.arrive_by.then_some(true),
87 num_f: Some(count),
88 context: cursor.map(str::to_owned),
89 max_change: query.max_transfers,
90 products,
91 rt_mode: Some(if query.realtime_routing {
92 RtMode::Realtime
93 } else {
94 RtMode::Infos
95 }),
96 passlist: Some(false),
97 ..TripSearch::new(from.place, to.place)
98 };
99 let mut list = self.call_or_none(&request).await?.unwrap_or_default();
100 let mut warnings = Vec::new();
101 if query.arrive_by
104 && cursor.is_none()
105 && list.trips.len() < count as usize
106 && let Some(earlier) = list.scr_b.clone()
107 {
108 let missing = count as usize - list.trips.len();
110 let request = TripSearch {
111 context: Some(earlier),
112 num_f: u32::try_from(missing).ok(),
113 ..request
114 };
115 let more = self.call_or_none(&request).await;
116 fill_up(&mut list, more, missing, &mut warnings);
117 }
118 Ok(self.trip_result(list, from.location, to.location, warnings))
119 }
120
121 pub async fn recheck(&self, token: &str) -> Result<TripResult, Error> {
123 let token = token.trim();
124 if token.is_empty() {
125 return Err(Error::BadRequest {
126 message: "the recheck token is empty".to_owned(),
127 });
128 }
129 let request = Recon {
130 rt_mode: Some(RtMode::Infos),
131 passlist: Some(false),
132 ..Recon::new(token)
133 };
134 let list = self.call(&request).await?;
135 let unknown = || Location {
136 id: None,
137 name: String::new(),
138 dhid: None,
139 };
140 Ok(self.trip_result(list, unknown(), unknown(), Vec::new()))
141 }
142
143 fn trip_result(
145 &self,
146 mut list: TripList,
147 from: Location,
148 to: Location,
149 warnings: Vec<String>,
150 ) -> TripResult {
151 dedupe(&mut list.trips);
152 list.trips.sort_by_key(convert::departure);
153 let now = (self.clock)();
154 let first = list.trips.first();
155 let from = first
156 .and_then(|trip| {
157 trip.legs
158 .first()
159 .map(|leg| &leg.origin)
160 .or(trip.origin.as_ref())
161 })
162 .map_or(from, Location::from);
163 let to = first
164 .and_then(|trip| {
165 trip.legs
166 .last()
167 .map(|leg| &leg.destination)
168 .or(trip.destination.as_ref())
169 })
170 .map_or(to, Location::from);
171 TripResult {
172 from,
173 to,
174 connections: list
175 .trips
176 .iter()
177 .map(|trip| Connection::new(trip, now, self.delay_threshold_minutes))
178 .collect(),
179 page_cursor: PageCursor {
180 earlier: list.scr_b,
181 later: list.scr_f,
182 },
183 realtime_as_of: time::plan_rt(list.info.plan_rt_ts.as_deref()),
184 attribution: Attribution::default(),
185 warnings,
186 }
187 }
188}
189
190fn dedupe(trips: &mut Vec<hafas::Trip>) {
193 let mut seen: Vec<String> = Vec::new();
194 trips.retain(|trip| {
195 let Some(ctx) = trip.ctx_recon.as_deref() else {
196 return true;
197 };
198 let new = !seen.iter().any(|known| known == ctx);
199 if new {
200 seen.push(ctx.to_owned());
201 }
202 new
203 });
204}
205
206fn fill_up(
210 list: &mut TripList,
211 earlier: Result<Option<TripList>, Error>,
212 missing: usize,
213 warnings: &mut Vec<String>,
214) {
215 match earlier {
216 Ok(more) => {
217 let mut more = more.unwrap_or_default();
218 dedupe(&mut more.trips);
219 more.trips.retain(|trip| {
220 trip.ctx_recon.is_none()
221 || !list
222 .trips
223 .iter()
224 .any(|known| known.ctx_recon == trip.ctx_recon)
225 });
226 let skip = more.trips.len().saturating_sub(missing);
227 list.trips.extend(more.trips.into_iter().skip(skip));
228 list.scr_b = more.scr_b;
229 }
230 Err(error) => warnings.push(format!("no earlier connections: {error}")),
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 #[test]
239 fn keeps_each_trip_once() {
240 let trip = |ctx: Option<&str>| hafas::Trip {
241 ctx_recon: ctx.map(str::to_owned),
242 ..hafas::Trip::default()
243 };
244 let mut trips = vec![trip(Some("a")), trip(None), trip(Some("a")), trip(None)];
245 dedupe(&mut trips);
246 let left: Vec<Option<&str>> = trips.iter().map(|t| t.ctx_recon.as_deref()).collect();
247 assert_eq!(left, [Some("a"), None, None]);
248 }
249
250 #[test]
251 fn a_failed_earlier_page_is_a_warning() {
252 let mut list = TripList {
253 scr_b: Some("before".to_owned()),
254 ..TripList::default()
255 };
256 let mut warnings = Vec::new();
257 fill_up(
258 &mut list,
259 Err(Error::Unavailable {
260 message: "down".to_owned(),
261 }),
262 1,
263 &mut warnings,
264 );
265 assert_eq!(list.scr_b.as_deref(), Some("before"));
266 assert_eq!(warnings.len(), 1);
267 assert!(
268 warnings[0].starts_with("no earlier connections: "),
269 "{warnings:?}"
270 );
271 fill_up(&mut list, Ok(None), 1, &mut warnings);
272 assert_eq!(list.scr_b, None);
273 }
274
275 #[test]
276 fn the_earlier_page_only_fills_up() {
277 let trip = |ctx: &str| hafas::Trip {
278 ctx_recon: Some(ctx.to_owned()),
279 ..hafas::Trip::default()
280 };
281 let mut list = TripList {
282 trips: vec![trip("c")],
283 ..TripList::default()
284 };
285 let earlier = TripList {
286 trips: vec![trip("x"), trip("a"), trip("b"), trip("c")],
287 ..TripList::default()
288 };
289 let mut warnings = Vec::new();
290 fill_up(&mut list, Ok(Some(earlier)), 2, &mut warnings);
291 let left: Vec<Option<&str>> = list.trips.iter().map(|t| t.ctx_recon.as_deref()).collect();
292 assert_eq!(left, [Some("c"), Some("a"), Some("b")]);
293 assert_eq!(warnings, Vec::<String>::new());
294 }
295}